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