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