0xGA: Check-in [4f674ae9ec]

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

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

Overview
Comment:More complete blog example (with atom feed support, only in french for now...)
Timelines: family | ancestors | descendants | both | narv
Files: files | file ages | folders
SHA1:4f674ae9ec6eceb0d38c39ee9c944f95c066044f
User & Date: milouse 2014-05-14 23:00:06
Context
2014-05-21
22:29
Add poke command to narv script. Take into account already existing articles in narvblog.py index method. check-in: 90c4b69fbd user: milouse tags: narv
2014-05-14
23:00
More complete blog example (with atom feed support, only in french for now...) check-in: 4f674ae9ec user: milouse tags: narv
2014-05-10
16:16
abstract sqlite management check-in: 054e202cac user: milouse tags: narv
Changes

Name change from example/milouse.py to example/narvblog.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
..
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
...
259
260
261
262
263
264
265

266
267
268
269
270
271
272
...
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
328
329
330
331
332
333
334
335
336
337
338
339
340








































































341
342
343
#!/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):
................................................................................
    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']


................................................................................

                    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={
................................................................................

        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):
                temp_content = ''
                with open(blog_template) as f:
                    temp_content = f.read()

                output = re.sub(
                    r'<p>\s+Aucun article disponible&#x2026;\s+</p>',
                    output,
                    temp_content,
                    re.M)

        return bytes(output, 'utf-8')










































































if __name__ == "__main__":
    app = Narv(('localhost', 8000), MilouseBlog)
    app.start()





>


>




>

|
<
<
<
>
>
>
>
>
>
>
|
|
<
|
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










|







 







|



|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|

<
>


<
<
<

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|







 







>







 







<
<
<

>

>







|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>










|







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

|

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
..
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
...
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
...
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

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

class Article(DataObject):




    def db_model(self):
        return {
            'table': 'articles',
            'model': {
                'date': 'text',
                'title': 'text',
                'abstract': 'text',
                'permalink': 'text unique'

            }





        }

















    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):
................................................................................
    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.datetime().strftime("%Y/%m/%d"),
            dirname_parts[len(dirname_parts) - 1])


    def datetime(self):




















        if self.date == None:


































































            return None


        return datetime.strptime(self.date, "%Y-%m-%d %H:%M:%S")















































class NarvBlog(IcanDoThat):

    appname = 'milouse'

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


................................................................................

                    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")
                            art_date = art_date.strftime("%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={
................................................................................

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


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




        ref = Article(self.appname)
        conds = {'order': 'date desc'}

        date_infos = re.search(r'(\d{4})/(?:(\d{2})/)?$', self.path)
        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)

            conds['date'] = date_query

        articles = ref.find_all(conds)
        output = ''

        if len(articles) > 0:

            if 'article_template' in self.config:
                art_format = self.config['article_template']

            else:
                art_format = """<article class="h-entry">
<h2 class="p-name">{title}</h2>
<p>Publié le <time class="dt-published" datetime="{timestamp}">
  {day} <a href="/a-écrit/{year}/{month}/">{localized_month}</a>
  <a href="/a-écrit/{year}/">{year}</a></time> —
  <a href="{url}" class="u-url">Lire plus...</a>
</p>
<div class="p-summary">{abstract}</div>
<article>"""

            for art in articles:

                art_date = art.datetime()
                if art_date != None:
                    data = {
                        'url': art.url(),
                        'title': art.title,
                        'abstract': art.abstract,
                        'year': art_date.year,
                        'month': art_date.month,
                        'localized_month': self.monthes[int(art_date.month) - 1],
                        'day': art_date.day,
                        'timestamp': art.date
                    }

                    output += art_format.format(**data)

        else:
            output = "Pas encore d'articles..."

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

            if os.path.isfile(blog_template):
                temp_content = ''
                with open(blog_template) as f:
                    temp_content = f.read()

                output = re.sub(
                    r'{{blog_content}}',
                    output,
                    temp_content,
                    re.M)

        return bytes(output, 'utf-8')


    def atom_feed(self):
        self.extension = 'atom'

        ref = Article(self.appname)
        articles = ref.find_all({'order': 'date desc'})
        art_string = ''
        last_art = None

        if len(articles) > 0:
            single_entry_format = """<entry>
    <link href="{url}" rel="alternate"/>
    <title>{title}</title>
    {atomkeywords}
    <content type="html">{content}</content>
    <updated>{date}</updated>
    <id>urn:md5:{entryid}</id>
  </entry>"""

            # Atomkeywords: <dc:subject>' . $k . '</dc:subject>

            for art in articles:
                art_date = art.datetime()
                if last_art == None or last_art < art_date:
                    last_art = art_date

                md5 = hashlib.md5()
                md5.update(bytes("{0}{1}".format(art.date, art.url()), 'utf-8'))

                if art_date != None:
                    data = {
                        'url': art.url(),
                        'entryid': md5.hexdigest(),
                        'title': art.title,
                        'content': html.escape(art.abstract),
                        'date': art_date.isoformat(),
                        'atomkeywords': ''
                    }

                    art_string += single_entry_format.format(**data)


        feed_format = """<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
      xmlns:dc="http://purl.org/dc/elements/1.1/"
      xml:lang="{lang}">
  <title>{appname}</title>
  <link href="{base_path}" rel="alternate"/>
  <link href="{base_path}/feed.atom" rel="self"/>
  <updated>{last_updated}</updated>
  <author>
    <name>{author}</name>
  </author>
  <id>urn:md5:{stream_id}</id>
  <generator uri="http://projects.depar.is/0xGA">0xGA</generator>
  {content}
</feed>"""

        md5 = hashlib.md5()
        md5.update(bytes("{0}{1}".format(self.appname, self.config['base_path']), 'utf-8'))
        data = {
            'content': art_string,
            'lang': self.config['lang'],
            'appname': self.appname,
            'base_path': self.config['base_path'],
            'author': self.config['author'],
            'stream_id': md5.hexdigest(),
            'last_updated': last_art.isoformat()
        }

        return bytes(feed_format.format(**data), 'utf-8')


if __name__ == "__main__":
    app = Narv(('localhost', 8000), NarvBlog)
    app.start()

Changes to narv.

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
...
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
...
437
438
439
440
441
442
443


444
445
446
447
448
449
450
                shift
                FOSSILFILE=`realpath $1`
                ;;
            --host|-H)
                shift
                DOMAINNAME=$1
                ;;
            create|init-chroot|restart|start|stop|-h|'help')
                COMMAND=$1
                ;;
            *)
                APPNAME=$1
                ;;
        esac
        shift
    done
fi

if [ "$WORKINGREP" = "/" ] ; then
    echo ""
    echo "DO NOT RUN THIS SCRIPT AT THE ROOT OF YOUR SYSTEM, YOU FOOL"
    echo ""
    echo "Please choose a more appropriate destination"
    echo "like /srv/http, /home/whatever/public_html or /var/www"
    exit 1
fi

case $COMMAND in
    -h|'help')
................................................................................
    (when (and (string= (file-name-nondirectory buffer-file-name) "content.org")
               (file-exists-p meta-file)
               (file-writable-p meta-file))
      (ed/orgx-parse-links)
      (with-current-buffer (find-file-noselect meta-file)
        (goto-char (point-min))
        (when (re-search-forward "title=.*" nil t)
          (replace-match (concat "title=\"" file-title "\""))
          (save-buffer 0))
        (kill-buffer))
      (message (concat "Saved " (ed/orgx-get-file-name))))))
(add-hook 'after-save-hook 'ed/orgx-propagate-save)

(defun ed/orgx-create-file-structure (title destination &optional buffer)
  (unless (file-exists-p (directory-file-name destination))
    (make-directory destination t)
    (make-directory (concat destination "media"))
    (make-directory (concat destination "templates"))
    (let ((timestamp (current-time)))
      (with-current-buffer (find-file-noselect (concat destination "meta.conf"))
        (insert "author=\"" (user-full-name) "\"\ntimestamp="
                (format-time-string "%Y%m%d%H%M%S" timestamp)
                "\"\ntitle=\"" title "\"")
        (save-buffer 0)
        (kill-buffer))
      (when buffer
        (with-current-buffer buffer
          (ed/orgx-parse-links)
          (copy-file buffer-file-name
                     (concat destination "content.org"))))
................................................................................
        narv_stop
        ;;
    restart)
        narv_restart
        ;;
    init-chroot)
        init_chroot


        ;;
    *)
        echo "There's something strange
in your neighborhood.
Who ya gonna call?"
        ;;
esac







|











|

|







 







|












|

|







 







>
>







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
...
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
...
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
                shift
                FOSSILFILE=`realpath $1`
                ;;
            --host|-H)
                shift
                DOMAINNAME=$1
                ;;
            create|deploy|init-chroot|restart|start|stop|-h|'help')
                COMMAND=$1
                ;;
            *)
                APPNAME=$1
                ;;
        esac
        shift
    done
fi

if [ "$WORKINGREP" = "/" ] ; then
    echo
    echo "DO NOT RUN THIS SCRIPT AT THE ROOT OF YOUR SYSTEM, YOU FOOL"
    echo
    echo "Please choose a more appropriate destination"
    echo "like /srv/http, /home/whatever/public_html or /var/www"
    exit 1
fi

case $COMMAND in
    -h|'help')
................................................................................
    (when (and (string= (file-name-nondirectory buffer-file-name) "content.org")
               (file-exists-p meta-file)
               (file-writable-p meta-file))
      (ed/orgx-parse-links)
      (with-current-buffer (find-file-noselect meta-file)
        (goto-char (point-min))
        (when (re-search-forward "title=.*" nil t)
          (replace-match (concat "title=" file-title))
          (save-buffer 0))
        (kill-buffer))
      (message (concat "Saved " (ed/orgx-get-file-name))))))
(add-hook 'after-save-hook 'ed/orgx-propagate-save)

(defun ed/orgx-create-file-structure (title destination &optional buffer)
  (unless (file-exists-p (directory-file-name destination))
    (make-directory destination t)
    (make-directory (concat destination "media"))
    (make-directory (concat destination "templates"))
    (let ((timestamp (current-time)))
      (with-current-buffer (find-file-noselect (concat destination "meta.conf"))
        (insert "author=" (user-full-name) "\ntimestamp="
                (format-time-string "%Y%m%d%H%M%S" timestamp)
                "\ntitle=" title)
        (save-buffer 0)
        (kill-buffer))
      (when buffer
        (with-current-buffer buffer
          (ed/orgx-parse-links)
          (copy-file buffer-file-name
                     (concat destination "content.org"))))
................................................................................
        narv_stop
        ;;
    restart)
        narv_restart
        ;;
    init-chroot)
        init_chroot
        ;;
    deploy)
        ;;
    *)
        echo "There's something strange
in your neighborhood.
Who ya gonna call?"
        ;;
esac

Changes to narv.py.

288
289
290
291
292
293
294
295

296
297
298
299
300
301
302
        'json': 'application/json; charset=utf-8',
        'js': 'text/javascript; charset=utf-8',
        'py': 'text/plain',
        'gpg': 'text/plain',
        'el': 'text/plain',
        'txt': 'text/plain',
        'org': 'text/plain; charset=utf-8',
        'pdf': 'application/pdf'

    }

    def __init__(self, request, App):

        self.routes = []
        self.App = App
        self.appname = App.appname







|
>







288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
        'json': 'application/json; charset=utf-8',
        'js': 'text/javascript; charset=utf-8',
        'py': 'text/plain',
        'gpg': 'text/plain',
        'el': 'text/plain',
        'txt': 'text/plain',
        'org': 'text/plain; charset=utf-8',
        'pdf': 'application/pdf',
        'atom': 'application/atom+xml'
    }

    def __init__(self, request, App):

        self.routes = []
        self.App = App
        self.appname = App.appname