0xGA: Check-in [66313b85fd]

Yet another PHP framework, but made for org-mode and geeks.

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Add sqlite support and features to example app
Timelines: family | ancestors | descendants | both | narv
Files: files | file ages | folders
SHA1:66313b85fd0a0a4430ba07b635af8f2849627ed4
User & Date: milouse 2014-05-07 00:49:01
Context
2014-05-10
15:42
End Sqlite ORM feature check-in: 19b06bb418 user: milouse tags: narv
2014-05-07
00:49
Add sqlite support and features to example app check-in: 66313b85fd user: milouse tags: narv
00:47
Add interruption mechanism to narv.py to allow devs to add custom actions to their apps check-in: 3f38ad2fef user: milouse tags: narv
Changes

Changes to example/milouse.py.

1
2
3
4
5


6
7
8
9
10




















































































































































































































11
12
13
14
15
16
17
18









19
20

21
22
23
24
25

26
27
28
29
30
31
32
33
34
35
36
37
38
39

40

41
42
43
44
45
46
47
48


49



50

51
52

53
54
55
56
57
58
59


60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89


90
91
92
93
94
95
96
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import re


from datetime import datetime
from configparser import ConfigParser
from narv import IcanDoThat
from narv import Narv





















































































































































































































class MilouseBlog(IcanDoThat):

    appname = 'milouse'

    monthes = ['janvier', 'février', 'mars', 'avril', 'mai', 'juin',
    'juillet', 'août', 'septembre', 'octobre', 'novembre', 'decembre']

    def archive(self, pattern=None):









        if 'blog_folder' in self.config:
            blog_folder = self.config['blog_folder']

        else:
            blog_folder = 'blog'

        blog_index = []
        blog_folder = os.path.join('srv', self.appname, blog_folder)


        if os.path.isdir(blog_folder):

            for article_permalink in os.listdir(blog_folder):
                article_local_path = os.path.join(blog_folder, article_permalink)
                meta_file = os.path.join(article_local_path, 'meta.conf')

                if os.path.isdir(article_local_path) and os.path.exists(meta_file) and os.path.isfile(meta_file):
                    meta_infos = ConfigParser()
                    meta_infos.read(meta_file)

                    if 'metadata' in meta_infos:
                        meta_infos = meta_infos['metadata']


                        if 'timestamp' in meta_infos and (pattern == None or meta_infos['timestamp'][0:len(pattern)] == pattern):


                            title = ''
                            if 'title' in meta_infos:
                                title = meta_infos['title']
                                title = re.sub('"', '', title)

                            blog_index.append((
                                meta_infos['timestamp'],


                                title,



                                article_permalink))


        return sorted(blog_index, key=lambda art: art[0], reverse=True)



    def blog(self):
        self.extension = 'html'

        date_infos = re.search(r'(\d{4})/(?:(\d{2})/)?$', self.path)
        articles = []



        if date_infos and date_infos.groups()[0]:
            date_tuple = date_infos.groups()
            date_query = date_tuple[0]

            if date_tuple[1]:
                date_query = '{0}{1}'.format(*date_tuple)

            articles = self.archive(date_query)

        else:
            articles = self.archive()

        output = "<ul>"
        for art in articles:
            art_date = datetime.strptime(art[0], "%Y%m%d%H%M%S")
            output += '<li><a href="/a-écrit/{0}/{1}/">{2}</a> {3}</li>'.format(
                art_date.strftime("%Y/%m/%d"),
                art[2],
                art[1],
                'le {0} {1} {2} à {3}'.format(
                    art_date.day,
                    '<a href="/a-écrit/{0}/">{1}</a>'.format(
                        art_date.strftime("%Y/%m"),
                        self.monthes[int(art_date.month) - 1]
                    ),
                    '<a href="/a-écrit/{0}/">{0}</a>'.format(
                        art_date.year
                    ),
                    art_date.strftime("%H:%M")))



        output += '</ul>'

        if 'blog_template' in self.config:
            blog_template = os.path.join('srv', self.appname, self.config['blog_template'])

            if os.path.isfile(blog_template):





>
>





>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







<
>
>
>
>
>
>
>
>
>


>



<

>







|






>
|
>

|
|
|
|

<
<
>
>
|
>
>
>
|
>

<
>







>
>



|


|

|


|



|
<
<
|
|

|

|
|


|

|
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231

232
233
234
235
236
237
238
239
240
241
242
243
244
245
246

247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271


272
273
274
275
276
277
278
279
280

281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306


307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import re
import sqlite3
import logging
from datetime import datetime
from configparser import ConfigParser
from narv import IcanDoThat
from narv import Narv

class Article:
    aid = 'new'
    date = None
    title = None
    abstract = None
    permalink = None
    errors = []

    def __init__(self, appname, aid=None, permalink=None, data=None):
        self.appname = appname
        self.db_path = 'var/db/{0}.blog.db'.format(self.appname)
        if not os.path.isfile(self.db_path):
            self.install()

        if aid != None:
            self.find(aid)
        elif permalink != None:
            self.find(permalink, 'permalink')
        elif data != None:
            if 'aid' in data:
                self.aid = data['aid']
            if 'date' in data:
                self.date = data['date']
            if 'title' in data:
                self.title = data['title']
            if 'abstract' in data:
                self.abstract = data['abstract']
            if 'permalink' in data:
                self.permalink = data['permalink']


    def content(self):
        if self.permalink == None:
            return None

        content = ''

        with open(os.path.join(self.permalink, 'content.html')) as f:
            content = f.read()
 
        start = content.find('<div id="content">') + 18
        end = content.find('<div id="postamble"')

        return content[start:end]


    def extract_abstract(self):
        content = self.content()

        if content == None:
            return None

        start = content.find('<p>')
        if start >= 0:
            end = content.find('</p>', start)

            if end > 0:
                end += 4
                self.abstract = content[start:end]

        return self.abstract


    def url(self):
        if self.date == None or self.permalink == None:
            return None

        dirname_parts = self.permalink.split('/')

        return "/a-écrit/{0}/{1}/".format(
            self.date.strftime("%Y/%m/%d"),
            dirname_parts[len(dirname_parts) - 1])


    def is_new(self):
        return aid == 'new'


    def find(self, value, crit='aid', n=1):
        with sqlite3.connect(self.db_path) as db:
            db.row_factory = sqlite3.Row
            cur = db.cursor()

            if crit == 'aid':
                self.aid = None
                cur.execute('select rowid, * from articles where rowid = ?', (aid,))
            elif crit == 'permalink':
                self.permalink = None
                cur.execute('select rowid, * from articles where permalink = ?', (permalink,))

            result = cur.fetchone()

            if len(result) > 0:
                if self.aid == 'new' or self.aid == None:
                    self.aid = row['rowid']
                if self.date == None:
                    self.date = datetime.strptime(row['date'], "%Y-%m-%d %H:%M:%S")
                if self.title == None:
                    self.title = row['title']
                if self.abstract == None:
                    self.abstract = row['abstract']
                if self.permalink == None:
                    self.permalink = row['permalink']

            cur.close()
            db.close()


    def find_all(self, value=None, crit='date', order=None, direction='desc'):
        articles = []

        with sqlite3.connect(self.db_path) as db:
            db.row_factory = sqlite3.Row
            cur = db.cursor()

            if value == None or crit not in ['date', 'title', 'permalink']:
                if order == 'date':
                    if direction == 'desc':
                        cur.execute('select rowid, * from articles order by date desc')
                    else:
                        cur.execute('select rowid, * from articles order by date')
                else:
                    cur.execute('select rowid, * from articles')

            else:
                if order == 'date':
                    if direction == 'desc':
                        cur.execute('select rowid, * from articles where {0} LIKE ? order by date desc'.format(crit), (value,))
                    else:
                        cur.execute('select rowid, * from articles where {0} LIKE ? order by date'.format(crit), (value,))
                else:
                    cur.execute('select rowid, * from articles where {0} LIKE ?'.format(crit), (value,))

            for row in cur:
                data = {
                    'aid': row['rowid'],
                    'title': row['title'],
                    'date': datetime.strptime(row['date'], "%Y-%m-%d %H:%M:%S"),
                    'abstract': row['abstract'],
                    'permalink': row['permalink']
                }
                articles.append(Article(self.appname, data=data))

            cur.close()


        return articles


    def validate(self):
        self.errors = []

        if self.aid == None:
            self.errors.append('aid')
        if self.date == None:
            self.errors.append('date')
        if self.title == None:
            self.errors.append('title')
        if self.permalink == None:
            self.errors.append('permalink')

        if len(self.errors) > 0:
            return False

        return True


    def merge(self):
        if self.aid == 'new':
            return True

        if self.aid != None:
            self.find(self.aid)
            return self.validate()

        return False


    def save(self):
        total = 0
        db = sqlite3.connect(self.db_path)

        if self.aid == 'new':
            if not self.validate():
                db.close()
                return False

            db.execute(
                'insert into articles values(?, ?, ?, ?)',
                (self.date.strftime("%Y-%m-%d %H:%M:%S"), self.title, self.abstract, self.permalink)
            )
        else:
            if not self.merge():
                return False

            db.exectue(
                'update articles set date = ?, title = ?, abstract = ?, permalink = ? where rowid = ?',
                (self.date.strftime("%Y-%m-%d %H:%M:%S"), self.title, self.abstract, self.permalink, self.aid)
            )

        db.commit()
        total = db.total_changes
        db.close()
        return total == 1


    def install(self):
        with sqlite3.connect(self.db_path) as db:
            db.execute('create table articles (date text, title text, abstract text, permalink text unique)')



class MilouseBlog(IcanDoThat):

    appname = 'milouse'

    monthes = ['janvier', 'février', 'mars', 'avril', 'mai', 'juin',
    'juillet', 'août', 'septembre', 'octobre', 'novembre', 'decembre']



    def do_interrupt(self):
        # Override default
        logging.info('Will index the blog')
        self.index()


    def index(self):

        if 'blog_folder' in self.config:
            blog_folder = self.config['blog_folder']

        else:
            blog_folder = 'blog'


        blog_folder = os.path.join('srv', self.appname, blog_folder)
        total = 0

        if os.path.isdir(blog_folder):

            for article_permalink in os.listdir(blog_folder):
                article_local_path = os.path.join(blog_folder, article_permalink)
                meta_file = os.path.join(article_local_path, 'meta.conf')

                if os.path.isfile(meta_file):
                    meta_infos = ConfigParser()
                    meta_infos.read(meta_file)

                    if 'metadata' in meta_infos:
                        meta_infos = meta_infos['metadata']

                        art_date = None
                        if 'timestamp' in meta_infos:
                            art_date = datetime.strptime(meta_infos['timestamp'], "%Y%m%d%H%M%S")

                        title = ''
                        if 'title' in meta_infos:
                            title = meta_infos['title']
                            title = re.sub('"', '', title)



                        article = Article(self.appname, data={
                            'date': art_date,
                            'title': title,
                            'permalink': article_local_path
                        })
                        article.extract_abstract()
                        article.save()
                        total += 1


        logging.info('{0} article(s) have been indexed'.format(total))


    def blog(self):
        self.extension = 'html'

        date_infos = re.search(r'(\d{4})/(?:(\d{2})/)?$', self.path)
        articles = []

        ref = Article(self.appname)

        if date_infos and date_infos.groups()[0]:
            date_tuple = date_infos.groups()
            date_query = date_tuple[0] + '%'

            if date_tuple[1]:
                date_query = '{0}-{1}%'.format(*date_tuple)

            articles = ref.find_all(date_query, order='date')

        else:
            articles = ref.find_all(order='date')

        output = "<ul>"
        for art in articles:
            output += '<li><h3><a href="{0}">{1}</a> {2}</h3>{3}</li>'.format(


                art.url(),
                art.title,
                'le {0} {1} {2} à {3}'.format(
                    art.date.day,
                    '<a href="/a-écrit/{0}/">{1}</a>'.format(
                        art.date.strftime("%Y/%m"),
                        self.monthes[int(art.date.month) - 1]
                    ),
                    '<a href="/a-écrit/{0}/">{0}</a>'.format(
                        art.date.year
                    ),
                    art.date.strftime("%H:%M")),
                art.abstract)


        output += '</ul>'

        if 'blog_template' in self.config:
            blog_template = os.path.join('srv', self.appname, self.config['blog_template'])

            if os.path.isfile(blog_template):