]> git.llucax.com Git - software/blitiri.git/blob - blitiri.cgi
15c820ee9bd9333e7dc31bfb034ce7a77428fbbd
[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_main_header(self):
239                 p = self.tpath + '/header.html'
240                 if os.path.isfile(p):
241                         return open(p).read() % self.vars
242                 return default_main_header % self.vars
243
244         def get_main_footer(self):
245                 p = self.tpath + '/footer.html'
246                 if os.path.isfile(p):
247                         return open(p).read() % self.vars
248                 return default_main_footer % self.vars
249
250         def get_article_header(self, article):
251                 avars = self.vars.copy()
252                 avars.update(article.to_vars())
253
254                 p = self.tpath + '/art_header.html'
255                 if os.path.isfile(p):
256                         return open(p).read() % avars
257                 return default_article_header % avars
258
259         def get_article_footer(self, article):
260                 avars = self.vars.copy()
261                 avars.update(article.to_vars())
262
263                 p = self.tpath + '/art_footer.html'
264                 if os.path.isfile(p):
265                         return open(p).read() % avars
266                 return default_article_footer % avars
267
268
269 class Article (object):
270         def __init__(self, path):
271                 self.path = path
272                 self.created = None
273                 self.updated = None
274                 self.uuid = "%08x" % zlib.crc32(self.path)
275
276                 self.loaded = False
277
278                 # loaded on demand
279                 self._title = 'Removed post'
280                 self._author = author
281                 self._tags = []
282                 self._raw_content = ''
283
284
285         def get_title(self):
286                 if not self.loaded:
287                         self.load()
288                 return self._title
289         title = property(fget = get_title)
290
291         def get_author(self):
292                 if not self.loaded:
293                         self.load()
294                 return self._author
295         author = property(fget = get_author)
296
297         def get_tags(self):
298                 if not self.loaded:
299                         self.load()
300                 return self._tags
301         tags = property(fget = get_tags)
302
303         def get_raw_content(self):
304                 if not self.loaded:
305                         self.load()
306                 return self._raw_content
307         raw_content = property(fget = get_raw_content)
308
309
310         def __cmp__(self, other):
311                 if self.path == other.path:
312                         return 0
313                 if not self.created:
314                         return 1
315                 if not other.created:
316                         return -1
317                 if self.created < other.created:
318                         return -1
319                 return 1
320
321         def title_cmp(self, other):
322                 return cmp(self.title, other.title)
323
324
325         def load(self):
326                 try:
327                         raw = open(data_path + '/' + self.path).readlines()
328                 except:
329                         return
330
331                 count = 0
332                 for l in raw:
333                         if ':' in l:
334                                 name, value = l.split(':', 1)
335                                 if name.lower() == 'title':
336                                         self._title = value
337                                 elif name.lower() == 'author':
338                                         self._author = value
339                                 elif name.lower() == 'tags':
340                                         ts = value.split(',')
341                                         ts = [t.strip() for t in ts]
342                                         self._tags = set(ts)
343                         elif l == '\n':
344                                 # end of header
345                                 break
346                         count += 1
347                 self._raw_content = ''.join(raw[count + 1:])
348                 self.loaded = True
349
350         def to_html(self):
351                 try:
352                         raw = open(data_path + '/' + self.path).readlines()
353                 except:
354                         return "Can't open post file<p>"
355                 raw = raw[raw.index('\n'):]
356
357                 settings = {
358                         'input_encoding': encoding,
359                         'output_encoding': 'utf8',
360                 }
361                 parts = publish_parts(self.raw_content,
362                                 settings_overrides = settings,
363                                 writer_name = "html")
364                 return parts['body'].encode('utf8')
365
366         def to_vars(self):
367                 return {
368                         'arttitle': self.title,
369                         'author': self.author,
370                         'date': self.created.isoformat(' '),
371                         'uuid': self.uuid,
372                         'tags': self.get_tags_links(),
373
374                         'created': self.created.isoformat(' '),
375                         'ciso': self.created.isoformat(),
376                         'cyear': self.created.year,
377                         'cmonth': self.created.month,
378                         'cday': self.created.day,
379                         'chour': self.created.hour,
380                         'cminute': self.created.minute,
381                         'csecond': self.created.second,
382
383                         'updated': self.updated.isoformat(' '),
384                         'uiso': self.updated.isoformat(),
385                         'uyear': self.updated.year,
386                         'umonth': self.updated.month,
387                         'uday': self.updated.day,
388                         'uhour': self.updated.hour,
389                         'uminute': self.updated.minute,
390                         'usecond': self.updated.second,
391                 }
392
393         def get_tags_links(self):
394                 l = []
395                 tags = list(self.tags)
396                 tags.sort()
397                 for t in tags:
398                         l.append('<a class="tag" href="%s/tag/%s">%s</a>' % \
399                                 (blog_url, urllib.quote(t), t) )
400                 return ', '.join(l)
401
402
403 class DB (object):
404         def __init__(self, dbpath):
405                 self.dbpath = dbpath
406                 self.articles = []
407                 self.uuids = {}
408                 self.actyears = set()
409                 self.actmonths = set()
410                 self.load()
411
412         def get_articles(self, year = 0, month = 0, day = 0, tags = None):
413                 l = []
414                 for a in self.articles:
415                         if year and a.created.year != year: continue
416                         if month and a.created.month != month: continue
417                         if day and a.created.day != day: continue
418                         if tags and not tags.issubset(a.tags): continue
419
420                         l.append(a)
421
422                 return l
423
424         def get_article(self, uuid):
425                 return self.uuids[uuid]
426
427         def load(self):
428                 try:
429                         f = open(self.dbpath)
430                 except:
431                         return
432
433                 for l in f:
434                         # Each line has the following comma separated format:
435                         # path (relative to data_path), \
436                         #       created (epoch), \
437                         #       updated (epoch)
438                         try:
439                                 l = l.split(',')
440                         except:
441                                 continue
442
443                         a = Article(l[0])
444                         a.created = datetime.datetime.fromtimestamp(
445                                                 float(l[1]) )
446                         a.updated = datetime.datetime.fromtimestamp(
447                                                 float(l[2]))
448                         self.uuids[a.uuid] = a
449                         self.actyears.add(a.created.year)
450                         self.actmonths.add((a.created.year, a.created.month))
451                         self.articles.append(a)
452
453         def save(self):
454                 f = open(self.dbpath + '.tmp', 'w')
455                 for a in self.articles:
456                         s = ''
457                         s += a.path + ', '
458                         s += str(time.mktime(a.created.timetuple())) + ', '
459                         s += str(time.mktime(a.updated.timetuple())) + '\n'
460                         f.write(s)
461                 f.close()
462                 os.rename(self.dbpath + '.tmp', self.dbpath)
463
464         def get_year_links(self):
465                 yl = list(self.actyears)
466                 yl.sort(reverse = True)
467                 return [ '<a href="%s/%d/">%d</a>' % (blog_url, y, y)
468                                 for y in yl ]
469
470         def get_month_links(self, year):
471                 am = [ i[1] for i in self.actmonths if i[0] == year ]
472                 ml = []
473                 for i in range(1, 13):
474                         name = calendar.month_name[i][:3]
475                         if i in am:
476                                 s = '<a href="%s/%d/%d/">%s</a>' % \
477                                         ( blog_url, year, i, name )
478                         else:
479                                 s = name
480                         ml.append(s)
481                 return ml
482
483 #
484 # Main
485 #
486
487
488 def render_html(articles, db, actyear = None):
489         template = Templates(templates_path, db, actyear)
490         print 'Content-type: text/html; charset=utf-8\n'
491         print template.get_main_header()
492         for a in articles:
493                 print template.get_article_header(a)
494                 print a.to_html()
495                 print template.get_article_footer(a)
496         print template.get_main_footer()
497
498 def render_artlist(articles, db, actyear = None):
499         template = Templates(templates_path, db, actyear)
500         print 'Content-type: text/html; charset=utf-8\n'
501         print template.get_main_header()
502         print '<h2>Articles</h2>'
503         for a in articles:
504                 print '<li><a href="%(url)s/uuid/%(uuid)s">%(title)s</a></li>' \
505                         % {     'url': blog_url,
506                                 'uuid': a.uuid,
507                                 'title': a.title,
508                                 'author': a.author,
509                         }
510         print template.get_main_footer()
511
512 def render_atom(articles):
513         if len(articles) > 0:
514                 updated = articles[0].updated.isoformat()
515         else:
516                 updated = datetime.datetime.now().isoformat()
517
518         print 'Content-type: application/atom+xml; charset=utf-8\n'
519         print """<?xml version="1.0" encoding="utf-8"?>
520
521 <feed xmlns="http://www.w3.org/2005/Atom">
522  <title>%(title)s</title>
523  <link rel="alternate" type="text/html" href="%(url)s"/>
524  <link rel="self" type="application/atom+xml" href="%(url)s/atom"/>
525  <id>%(url)s</id> <!-- TODO: find a better <id>, see RFC 4151 -->
526  <updated>%(updated)sZ</updated>
527
528         """ % {
529                 'title': title,
530                 'url': full_url,
531                 'updated': updated,
532         }
533
534         for a in articles:
535                 vars = a.to_vars()
536                 vars.update( {
537                         'url': full_url,
538                         'contents': a.to_html(),
539                 } )
540                 print """
541   <entry>
542     <title>%(arttitle)s</title>
543     <author><name>%(author)s</name></author>
544     <link href="%(url)s/post/%(uuid)s" />
545     <id>%(url)s/post/%(uuid)s</id>
546     <summary>%(arttitle)s</summary>
547     <published>%(ciso)sZ</published>
548     <updated>%(uiso)sZ</updated>
549     <content type="xhtml">
550       <div xmlns="http://www.w3.org/1999/xhtml"><p>
551 %(contents)s
552       </p></div>
553     </content>
554   </entry>
555                 """ % vars
556         print "</feed>"
557
558
559 def render_style():
560         print 'Content-type: text/css\r\n\r\n',
561         print default_css
562
563 def handle_cgi():
564         import cgitb; cgitb.enable()
565
566         form = cgi.FieldStorage()
567         year = int(form.getfirst("year", 0))
568         month = int(form.getfirst("month", 0))
569         day = int(form.getfirst("day", 0))
570         tags = set(form.getlist("tag"))
571         uuid = None
572         atom = False
573         style = False
574         post = False
575         artlist = False
576
577         if os.environ.has_key('PATH_INFO'):
578                 path_info = os.environ['PATH_INFO']
579                 style = path_info == '/style'
580                 atom = path_info == '/atom'
581                 tag = path_info.startswith('/tag/')
582                 post = path_info.startswith('/post/')
583                 artlist = path_info.startswith('/list')
584                 if not style and not atom and not post and not tag \
585                                 and not artlist:
586                         date = path_info.split('/')[1:]
587                         try:
588                                 if len(date) > 1 and date[0]:
589                                         year = int(date[0])
590                                 if len(date) > 2 and date[1]:
591                                         month = int(date[1])
592                                 if len(date) > 3 and date[2]:
593                                         day = int(date[2])
594                         except ValueError:
595                                 pass
596                 elif post:
597                         uuid = path_info.replace('/post/', '')
598                         uuid = uuid.replace('/', '')
599                 elif tag:
600                         t = path_info.replace('/tag/', '')
601                         t = t.replace('/', '')
602                         t = urllib.unquote_plus(t)
603                         tags = set((t,))
604
605         db = DB(data_path + '/db')
606         if atom:
607                 articles = db.get_articles(tags = tags)
608                 articles.sort(reverse = True)
609                 render_atom(articles[:10])
610         elif style:
611                 render_style()
612         elif post:
613                 render_html( [db.get_article(uuid)], db, year )
614         elif artlist:
615                 articles = db.get_articles()
616                 articles.sort(cmp = Article.title_cmp)
617                 render_artlist(articles, db)
618         else:
619                 articles = db.get_articles(year, month, day, tags)
620                 articles.sort(reverse = True)
621                 if not year and not month and not day and not tags:
622                         articles = articles[:10]
623                 render_html(articles, db, year)
624
625
626 def usage():
627         print 'Usage: %s {add|rm|update} article_path' % sys.argv[0]
628
629 def handle_cmd():
630         if len(sys.argv) != 3:
631                 usage()
632                 return 1
633
634         cmd = sys.argv[1]
635         art_path = os.path.realpath(sys.argv[2])
636
637         if os.path.commonprefix([data_path, art_path]) != data_path:
638                 print "Error: article (%s) must be inside data_path (%s)" % \
639                                 (art_path, data_path)
640                 return 1
641         art_path = art_path[len(data_path):]
642
643         if not os.path.isfile(data_path + '/db'):
644                 open(data_path + '/db', 'w').write('')
645         db = DB(data_path + '/db')
646
647         if cmd == 'add':
648                 article = Article(art_path)
649                 for a in db.articles:
650                         if a == article:
651                                 print 'Error: article already exists'
652                                 return 1
653                 db.articles.append(article)
654                 article.created = datetime.datetime.now()
655                 article.updated = datetime.datetime.now()
656                 db.save()
657         elif cmd == 'rm':
658                 article = Article(art_path)
659                 for a in db.articles:
660                         if a == article:
661                                 break
662                 else:
663                         print "Error: no such article"
664                         return 1
665                 db.articles.remove(a)
666                 db.save()
667         elif cmd == 'update':
668                 article = Article(art_path)
669                 for a in db.articles:
670                         if a == article:
671                                 break
672                 else:
673                         print "Error: no such article"
674                         return 1
675                 a.updated = datetime.datetime.now()
676                 db.save()
677         else:
678                 usage()
679                 return 1
680
681         return 0
682
683
684 if os.environ.has_key('GATEWAY_INTERFACE'):
685         handle_cgi()
686 else:
687         sys.exit(handle_cmd())
688
689