]> git.llucax.com Git - software/blitiri.git/blob - blitiri.cgi
Add a "list" view to list all articles.
[software/blitiri.git] / blitiri.cgi
1 #!/usr/bin/env python
2 #coding: utf8
3
4 # blitiri - A single-file blog engine.
5 # Alberto Bertogli (albertito@gmail.com)
6
7 #
8 # Configuration section
9 #
10 # You can edit these values, or create a file named "config.py" and put them
11 # there to make updating easier. The ones in config.py take precedence.
12 #
13
14 # Directory where entries are stored
15 data_path = "/tmp/blog/data"
16
17 # Path where templates are stored. Use an empty string for the built-in
18 # default templates. If they're not found, the built-in ones will be used.
19 templates_path = "/tmp/blog/templates"
20
21 # URL to the blog, including the name. Can be a full URL or just the path.
22 blog_url = "/blog/blitiri.cgi"
23
24 # Style sheet (CSS) URL. Can be relative or absolute. To use the built-in
25 # default, set it to blog_url + "/style".
26 css_url = blog_url + "/style"
27
28 # Blog title
29 title = "I don't like blogs"
30
31 # Default author
32 author = "Hartmut Kegan"
33
34 # Article encoding
35 encoding = "utf8"
36
37 #
38 # End of configuration
39 # DO *NOT* EDIT ANYTHING PAST HERE
40 #
41
42
43 import sys
44 import os
45 import time
46 import datetime
47 import calendar
48 import zlib
49 import urllib
50 import cgi
51 from docutils.core import publish_parts
52
53 # Load the config file, if there is one
54 try:
55         from config import *
56 except:
57         pass
58
59
60 # Default template
61
62 default_main_header = """
63 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
64
65 <html>
66 <head>
67 <link rel="alternate" title="%(title)s" href="%(fullurl)s/atom"
68         type="application/atom+xml" />
69 <link href="%(css_url)s" rel="stylesheet"
70         type="text/css" />
71 <title>%(title)s</title>
72 </head>
73
74 <body>
75
76 <h1><a href="%(url)s">%(title)s</a></h1>
77
78 <div class="content">
79 """
80
81 default_main_footer = """
82 </div><p/>
83 <hr/><br/>
84 <div class="footer">
85   %(showyear)s: %(monthlinks)s<br/>
86   years: %(yearlinks)s<br/>
87   subscribe: <a href="%(url)s/atom">atom</a><br/>
88   views: <a href="%(url)s/">blog</a> <a href="%(url)s/list">list</a><br/>
89 </div>
90
91 </body>
92 </html>
93 """
94
95 default_article_header = """
96 <div class="article">
97 <h2><a href="%(url)s/post/%(uuid)s">%(arttitle)s</a></h2>
98 <span class="artinfo">
99   by %(author)s on <span class="date">
100
101 <a class="date" href="%(url)s/%(cyear)d/">%(cyear)04d</a>-\
102 <a class="date" href="%(url)s/%(cyear)d/%(cmonth)d/">%(cmonth)02d</a>-\
103 <a class="date" href="%(url)s/%(cyear)d/%(cmonth)d/%(cday)d/">%(cday)02d</a>\
104     %(chour)02d:%(cminute)02d</span>
105   (updated on <span class="date">
106 <a class="date" href="%(url)s/%(uyear)d/">%(uyear)04d</a>-\
107 <a class="date" href="%(url)s/%(uyear)d/%(umonth)d/">%(umonth)02d</a>-\
108 <a class="date" href="%(url)s/%(uyear)d/%(umonth)d/%(uday)d/">%(uday)02d</a>\
109     %(uhour)02d:%(uminute)02d)</span><br/>
110   <span class="tags">tagged %(tags)s</span>
111 </span><br/>
112 <p/>
113 <div class="artbody">
114 """
115
116 default_article_footer = """
117 <p/>
118 </div>
119 </div>
120 """
121
122 # Default CSS
123 default_css = """
124 body {
125         font-family: sans-serif;
126         font-size: small;
127 }
128
129 div.content {
130         width: 50%;
131 }
132
133 h1 {
134         font-size: large;
135         border-bottom: 2px solid #99F;
136         width: 60%;
137         margin-bottom: 1em;
138 }
139
140 h2 {
141         font-size: medium;
142         font-weigth: none;
143         margin-bottom: 1pt;
144         border-bottom: 1px solid #99C;
145 }
146
147 h1 a, h2 a {
148         text-decoration: none;
149         color: black;
150 }
151
152 span.artinfo {
153         font-size: xx-small;
154 }
155
156 span.artinfo a {
157         text-decoration: none;
158         color: #339;
159 }
160
161 span.artinfo a:hover {
162         text-decoration: none;
163         color: blue;
164 }
165
166 div.artbody {
167         margin-left: 1em;
168 }
169
170 div.article {
171         margin-bottom: 2em;
172 }
173
174 hr {
175         float: left;
176         height: 2px;
177         border: 0;
178         background-color: #99F;
179         width: 60%;
180 }
181
182 div.footer {
183         font-size: x-small;
184 }
185
186 div.footer a {
187         text-decoration: none;
188 }
189
190 /* Articles are enclosed in <div class="section"> */
191 div.section h1 {
192         font-size: small;
193         font-weigth: none;
194         width: 100%;
195         margin-bottom: 1pt;
196         border-bottom: 1px dotted #99C;
197 }
198
199 """
200
201 # find out our URL, needed for syndication
202 try:
203         n = os.environ['SERVER_NAME']
204         p = os.environ['SERVER_PORT']
205         s = os.environ['SCRIPT_NAME']
206         if p == '80': p = ''
207         else: p = ':' + p
208         full_url = 'http://%s%s%s' % (n, p, s)
209 except KeyError:
210         full_url = 'Not needed'
211
212
213 class Templates (object):
214         def __init__(self, tpath, db, showyear = None):
215                 self.tpath = tpath
216                 self.db = db
217                 now = datetime.datetime.now()
218                 if not showyear:
219                         showyear = now.year
220
221                 self.vars = {
222                         'css_url': css_url,
223                         'title': title,
224                         'url': blog_url,
225                         'fullurl': full_url,
226                         'year': now.year,
227                         'month': now.month,
228                         'day': now.day,
229                         'showyear': showyear,
230                         'monthlinks': ' '.join(db.get_month_links(showyear)),
231                         'yearlinks': ' '.join(db.get_year_links()),
232                 }
233
234         def get_main_header(self):
235                 p = self.tpath + '/header.html'
236                 if os.path.isfile(p):
237                         return open(p).read() % self.vars
238                 return default_main_header % self.vars
239
240         def get_main_footer(self):
241                 p = self.tpath + '/footer.html'
242                 if os.path.isfile(p):
243                         return open(p).read() % self.vars
244                 return default_main_footer % self.vars
245
246         def get_article_header(self, article):
247                 avars = self.vars.copy()
248                 avars.update( {
249                         'arttitle': article.title,
250                         'author': article.author,
251                         'date': article.created.isoformat(' '),
252                         'uuid': article.uuid,
253                         'created': article.created.isoformat(' '),
254                         'updated': article.updated.isoformat(' '),
255                         'tags': article.get_tags_links(),
256
257                         'cyear': article.created.year,
258                         'cmonth': article.created.month,
259                         'cday': article.created.day,
260                         'chour': article.created.hour,
261                         'cminute': article.created.minute,
262                         'csecond': article.created.second,
263
264                         'uyear': article.updated.year,
265                         'umonth': article.updated.month,
266                         'uday': article.updated.day,
267                         'uhour': article.updated.hour,
268                         'uminute': article.updated.minute,
269                         'usecond': article.updated.second,
270                 } )
271
272                 p = self.tpath + '/art_header.html'
273                 if os.path.isfile(p):
274                         return open(p).read() % avars
275                 return default_article_header % avars
276
277         def get_article_footer(self, article):
278                 avars = self.vars.copy()
279                 avars.update( {
280                         'arttitle': article.title,
281                         'author': article.author,
282                         'date': article.created.isoformat(' '),
283                         'uuid': article.uuid,
284                         'created': article.created.isoformat(' '),
285                         'updated': article.updated.isoformat(' '),
286                         'tags': article.get_tags_links(),
287
288                         'cyear': article.created.year,
289                         'cmonth': article.created.month,
290                         'cday': article.created.day,
291                         'chour': article.created.hour,
292                         'cminute': article.created.minute,
293                         'csecond': article.created.second,
294
295                         'uyear': article.updated.year,
296                         'umonth': article.updated.month,
297                         'uday': article.updated.day,
298                         'uhour': article.updated.hour,
299                         'uminute': article.updated.minute,
300                         'usecond': article.updated.second,
301                 } )
302
303                 p = self.tpath + '/art_footer.html'
304                 if os.path.isfile(p):
305                         return open(p).read() % avars
306                 return default_article_footer % avars
307
308
309 class Article (object):
310         def __init__(self, path):
311                 self.path = path
312                 self.created = None
313                 self.updated = None
314                 self.uuid = "%08x" % zlib.crc32(self.path)
315
316                 self.loaded = False
317
318                 # loaded on demand
319                 self._title = 'Removed post'
320                 self._author = author
321                 self._tags = []
322                 self._raw_content = ''
323
324
325         def get_title(self):
326                 if not self.loaded:
327                         self.load()
328                 return self._title
329         title = property(fget = get_title)
330
331         def get_author(self):
332                 if not self.loaded:
333                         self.load()
334                 return self._author
335         author = property(fget = get_author)
336
337         def get_tags(self):
338                 if not self.loaded:
339                         self.load()
340                 return self._tags
341         tags = property(fget = get_tags)
342
343         def get_raw_content(self):
344                 if not self.loaded:
345                         self.load()
346                 return self._raw_content
347         raw_content = property(fget = get_raw_content)
348
349
350         def __cmp__(self, other):
351                 if self.path == other.path:
352                         return 0
353                 if not self.created:
354                         return 1
355                 if not other.created:
356                         return -1
357                 if self.created < other.created:
358                         return -1
359                 return 1
360
361         def title_cmp(self, other):
362                 return cmp(self.title, other.title)
363
364
365         def load(self):
366                 try:
367                         raw = open(data_path + '/' + self.path).readlines()
368                 except:
369                         return
370
371                 count = 0
372                 for l in raw:
373                         if ':' in l:
374                                 name, value = l.split(':', 1)
375                                 if name.lower() == 'title':
376                                         self._title = value
377                                 elif name.lower() == 'author':
378                                         self._author = value
379                                 elif name.lower() == 'tags':
380                                         ts = value.split(',')
381                                         ts = [t.strip() for t in ts]
382                                         self._tags = set(ts)
383                         elif l == '\n':
384                                 # end of header
385                                 break
386                         count += 1
387                 self._raw_content = ''.join(raw[count + 1:])
388                 self.loaded = True
389
390         def to_html(self):
391                 try:
392                         raw = open(data_path + '/' + self.path).readlines()
393                 except:
394                         return "Can't open post file<p>"
395                 raw = raw[raw.index('\n'):]
396
397                 settings = {
398                         'input_encoding': encoding,
399                         'output_encoding': 'utf8',
400                 }
401                 parts = publish_parts(self.raw_content,
402                                 settings_overrides = settings,
403                                 writer_name = "html")
404                 return parts['body'].encode('utf8')
405
406         def get_tags_links(self):
407                 l = []
408                 tags = list(self.tags)
409                 tags.sort()
410                 for t in tags:
411                         l.append('<a class="tag" href="%s/tag/%s">%s</a>' % \
412                                 (blog_url, urllib.quote(t), t) )
413                 return ', '.join(l)
414
415
416 class DB (object):
417         def __init__(self, dbpath):
418                 self.dbpath = dbpath
419                 self.articles = []
420                 self.uuids = {}
421                 self.actyears = set()
422                 self.actmonths = set()
423                 self.load()
424
425         def get_articles(self, year = 0, month = 0, day = 0, tags = None):
426                 l = []
427                 for a in self.articles:
428                         if year and a.created.year != year: continue
429                         if month and a.created.month != month: continue
430                         if day and a.created.day != day: continue
431                         if tags and not tags.issubset(a.tags): continue
432
433                         l.append(a)
434
435                 return l
436
437         def get_article(self, uuid):
438                 return self.uuids[uuid]
439
440         def load(self):
441                 try:
442                         f = open(self.dbpath)
443                 except:
444                         return
445
446                 for l in f:
447                         # Each line has the following comma separated format:
448                         # path (relative to data_path), \
449                         #       created (epoch), \
450                         #       updated (epoch)
451                         try:
452                                 l = l.split(',')
453                         except:
454                                 continue
455
456                         a = Article(l[0])
457                         a.created = datetime.datetime.fromtimestamp(
458                                                 float(l[1]) )
459                         a.updated = datetime.datetime.fromtimestamp(
460                                                 float(l[2]))
461                         self.uuids[a.uuid] = a
462                         self.actyears.add(a.created.year)
463                         self.actmonths.add((a.created.year, a.created.month))
464                         self.articles.append(a)
465
466         def save(self):
467                 f = open(self.dbpath + '.tmp', 'w')
468                 for a in self.articles:
469                         s = ''
470                         s += a.path + ', '
471                         s += str(time.mktime(a.created.timetuple())) + ', '
472                         s += str(time.mktime(a.updated.timetuple())) + '\n'
473                         f.write(s)
474                 f.close()
475                 os.rename(self.dbpath + '.tmp', self.dbpath)
476
477         def get_year_links(self):
478                 yl = list(self.actyears)
479                 yl.sort(reverse = True)
480                 return [ '<a href="%s/%d/">%d</a>' % (blog_url, y, y)
481                                 for y in yl ]
482
483         def get_month_links(self, year):
484                 am = [ i[1] for i in self.actmonths if i[0] == year ]
485                 ml = []
486                 for i in range(1, 13):
487                         name = calendar.month_name[i][:3]
488                         if i in am:
489                                 s = '<a href="%s/%d/%d/">%s</a>' % \
490                                         ( blog_url, year, i, name )
491                         else:
492                                 s = name
493                         ml.append(s)
494                 return ml
495
496 #
497 # Main
498 #
499
500
501 def render_html(articles, db, actyear = None):
502         template = Templates(templates_path, db, actyear)
503         print 'Content-type: text/html; charset=utf-8\n'
504         print template.get_main_header()
505         for a in articles:
506                 print template.get_article_header(a)
507                 print a.to_html()
508                 print template.get_article_footer(a)
509         print template.get_main_footer()
510
511 def render_artlist(articles, db, actyear = None):
512         template = Templates(templates_path, db, actyear)
513         print 'Content-type: text/html; charset=utf-8\n'
514         print template.get_main_header()
515         print '<h2>Articles</h2>'
516         for a in articles:
517                 print '<li><a href="%(url)s/uuid/%(uuid)s">%(title)s</a></li>' \
518                         % {     'url': blog_url,
519                                 'uuid': a.uuid,
520                                 'title': a.title,
521                                 'author': a.author,
522                         }
523         print template.get_main_footer()
524
525 def render_atom(articles):
526         if len(articles) > 0:
527                 updated = articles[0].updated.isoformat()
528         else:
529                 updated = datetime.datetime.now().isoformat()
530
531         print 'Content-type: application/atom+xml; charset=utf-8\n'
532         print """<?xml version="1.0" encoding="utf-8"?>
533
534 <feed xmlns="http://www.w3.org/2005/Atom">
535  <title>%(title)s</title>
536  <link rel="alternate" type="text/html" href="%(url)s"/>
537  <link rel="self" type="application/atom+xml" href="%(url)s/atom"/>
538  <id>%(url)s</id> <!-- TODO: find a better <id>, see RFC 4151 -->
539  <updated>%(updated)sZ</updated>
540
541         """ % {
542                 'title': title,
543                 'url': full_url,
544                 'updated': updated,
545         }
546
547         for a in articles:
548                 print """
549   <entry>
550     <title>%(arttitle)s</title>
551     <author><name>%(author)s</name></author>
552     <link href="%(url)s/post/%(uuid)s" />
553     <id>%(url)s/post/%(uuid)s</id>
554     <summary>%(arttitle)s</summary>
555     <published>%(created)sZ</published>
556     <updated>%(updated)sZ</updated>
557     <content type="xhtml">
558       <div xmlns="http://www.w3.org/1999/xhtml"><p>
559 %(contents)s
560       </p></div>
561     </content>
562   </entry>
563                 """ % {
564                         'arttitle': a.title,
565                         'author': a.author,
566                         'uuid': a.uuid,
567                         'url': full_url,
568                         'created': a.created.isoformat(),
569                         'updated': a.updated.isoformat(),
570                         'contents': a.to_html(),
571                 }
572
573         print "</feed>"
574
575
576 def render_style():
577         print 'Content-type: text/plain\n'
578         print default_css
579
580 def handle_cgi():
581         import cgitb; cgitb.enable()
582
583         form = cgi.FieldStorage()
584         year = int(form.getfirst("year", 0))
585         month = int(form.getfirst("month", 0))
586         day = int(form.getfirst("day", 0))
587         tags = set(form.getlist("tag"))
588         uuid = None
589         atom = False
590         style = False
591         post = False
592         artlist = False
593
594         if os.environ.has_key('PATH_INFO'):
595                 path_info = os.environ['PATH_INFO']
596                 style = path_info == '/style'
597                 atom = path_info == '/atom'
598                 tag = path_info.startswith('/tag/')
599                 post = path_info.startswith('/post/')
600                 artlist = path_info.startswith('/list')
601                 if not style and not atom and not post and not tag \
602                                 and not artlist:
603                         date = path_info.split('/')[1:]
604                         try:
605                                 if len(date) > 1 and date[0]:
606                                         year = int(date[0])
607                                 if len(date) > 2 and date[1]:
608                                         month = int(date[1])
609                                 if len(date) > 3 and date[2]:
610                                         day = int(date[2])
611                         except ValueError:
612                                 pass
613                 elif post:
614                         uuid = path_info.replace('/post/', '')
615                         uuid = uuid.replace('/', '')
616                 elif tag:
617                         t = path_info.replace('/tag/', '')
618                         t = t.replace('/', '')
619                         t = urllib.unquote_plus(t)
620                         tags = set((t,))
621
622         db = DB(data_path + '/db')
623         if atom:
624                 articles = db.get_articles(tags = tags)
625                 articles.sort(reverse = True)
626                 render_atom(articles[:10])
627         elif style:
628                 render_style()
629         elif post:
630                 render_html( [db.get_article(uuid)], db, year )
631         elif artlist:
632                 articles = db.get_articles()
633                 articles.sort(cmp = Article.title_cmp)
634                 render_artlist(articles, db)
635         else:
636                 articles = db.get_articles(year, month, day, tags)
637                 articles.sort(reverse = True)
638                 if not year and not month and not day and not tags:
639                         articles = articles[:10]
640                 render_html(articles, db, year)
641
642
643 def usage():
644         print 'Usage: %s {add|rm|update} article_path' % sys.argv[0]
645
646 def handle_cmd():
647         if len(sys.argv) != 3:
648                 usage()
649                 return 1
650
651         cmd = sys.argv[1]
652         art_path = os.path.realpath(sys.argv[2])
653
654         if os.path.commonprefix([data_path, art_path]) != data_path:
655                 print "Error: article (%s) must be inside data_path (%s)" % \
656                                 (art_path, data_path)
657                 return 1
658         art_path = art_path[len(data_path):]
659
660         if not os.path.isfile(data_path + '/db'):
661                 open(data_path + '/db', 'w').write('')
662         db = DB(data_path + '/db')
663
664         if cmd == 'add':
665                 article = Article(art_path)
666                 for a in db.articles:
667                         if a == article:
668                                 print 'Error: article already exists'
669                                 return 1
670                 db.articles.append(article)
671                 article.created = datetime.datetime.now()
672                 article.updated = datetime.datetime.now()
673                 db.save()
674         elif cmd == 'rm':
675                 article = Article(art_path)
676                 for a in db.articles:
677                         if a == article:
678                                 break
679                 else:
680                         print "Error: no such article"
681                         return 1
682                 db.articles.remove(a)
683                 db.save()
684         elif cmd == 'update':
685                 article = Article(art_path)
686                 for a in db.articles:
687                         if a == article:
688                                 break
689                 else:
690                         print "Error: no such article"
691                         return 1
692                 a.updated = datetime.datetime.now()
693                 db.save()
694         else:
695                 usage()
696                 return 1
697
698         return 0
699
700
701 if os.environ.has_key('GATEWAY_INTERFACE'):
702         handle_cgi()
703 else:
704         sys.exit(handle_cmd())
705
706