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