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