]> git.phdru.name Git - phdru.name/phdru.name.git/blob - reindex_blog.py
Copyright 2013
[phdru.name/phdru.name.git] / reindex_blog.py
1 #! /usr/bin/env python
2 # -*- coding: koi8-r -*-
3
4 __author__ = "Oleg Broytman <phd@phdru.name>"
5 __copyright__ = "Copyright (C) 2006-2013 PhiloSoft Design"
6
7 import sys, os
8
9 blog_data_root = sys.argv[1]
10 blog_root = sys.argv[2]
11 blog_filename = os.path.join(blog_data_root, "blog_dict.pickle")
12
13 try:
14    import cPickle as pickle
15 except ImportError:
16    import pickle
17
18 from Cheetah.Template import Template
19
20
21 # Load old blog
22
23 try:
24    blog_file = open(blog_filename, "rb")
25 except IOError:
26    old_blog = {}
27 else:
28    old_blog = pickle.load(blog_file)
29    blog_file.close()
30
31
32 # blog is a dictionary mapping
33 # (year, month, day) => [list of (file, title, lead, tags)]
34
35 blog = {}
36 years = {}
37
38 # bodies is a dictionary mapping file => body
39
40 bodies = {}
41
42 # Walk the directory recursively
43 for dirpath, dirs, files in os.walk(blog_root):
44    d = os.path.basename(dirpath)
45    if not d.startswith("20") and not d.isdigit():
46       continue
47    for file in files:
48       if not file.endswith(".tmpl"):
49          continue
50       fullpath = os.path.join(dirpath, file)
51       template = Template(file=fullpath)
52       title_parts = template.Title.decode('utf-8').encode('koi8-r').split()
53       title = ' '.join(title_parts[6:])
54       lead = template.Lead.decode('utf-8').encode('koi8-r')
55
56       tags = template.Tag
57       if isinstance(tags, basestring):
58          tags = (tags,)
59       tags = [tag.decode('utf-8').encode('koi8-r') for tag in tags]
60
61       if title:
62          key = year, month, day = tuple(dirpath[len(blog_root):].split(os.sep)[1:])
63          if key in blog:
64             days = blog[key]
65          else:
66             days = blog[key] = []
67          days.append((file, title, lead, tags))
68
69          if year in years:
70             months = years[year]
71          else:
72             months = years[year] = {}
73
74          if month in months:
75             days = months[month]
76          else:
77             days = months[month] = []
78
79          if day not in days: days.append(day)
80
81          file = file[:-len("tmpl")] + "html"
82          key = (year, month, day, file)
83          body = template.body()
84          if isinstance(body, unicode):
85             body = body.encode('koi8-r')
86          bodies[key] = body
87
88 # Need to save the blog?
89 if blog <> old_blog:
90    blog_file = open(blog_filename, "wb")
91    pickle.dump(blog, blog_file, pickle.HIGHEST_PROTOCOL)
92    blog_file.close()
93
94 # Localized month names
95
96 import locale
97 locale.setlocale(locale.LC_ALL, "ru_RU.KOI8-R")
98 from calendar import _localized_day, _localized_month
99
100 locale.setlocale(locale.LC_TIME, 'C')
101 months_names_en = list(_localized_month('%B'))
102 months_abbrs_en = list(_localized_month('%b'))
103
104 locale.setlocale(locale.LC_TIME, "ru_RU.KOI8-R")
105 #months_names_ru = list(_localized_month('%B'))
106
107 months_names_ru = ['', "января", "февраля", "марта", "апреля", "мая", "июня",
108    "июля", "августа", "сентября", "октября", "ноября", "декабря"
109 ]
110
111 months_names_ru0 = ['', "январь", "февраль", "март", "апрель", "май", "июнь",
112    "июль", "август", "сентябрь", "октябрь", "ноябрь", "декабрь"
113 ]
114
115 from news import write_if_changed
116
117
118 def write_template(level, year, month, day, titles, tags=None):
119    path = [blog_root]
120    if level >= 1:
121       path.append(year)
122    if level >= 2:
123       path.append(month)
124    if level == 3:
125       path.append(day)
126    path.append("index.tmpl")
127    index_name = os.path.join(*path)
128
129    new_text = ["""\
130 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
131 #encoding koi8-r
132 #extends phd_site
133 #implements respond
134 """]
135
136    if level == 0:
137       new_text.append("""\
138 #attr $Title = "Oleg Broytman's blog"
139 #attr $Description = "Broytman Russian Blog Index Document"
140 #attr $Copyright = %(cyear)s
141 #attr $alternates = (("Новости [Atom 1.0] только заголовки", "application/atom+xml", "atom_10_titles.xml"),
142                      ("Новости [Atom 1.0]", "application/atom+xml", "atom_10.xml"),
143                      ("Новости [Atom 1.0] полные тексты", "application/atom+xml", "atom_10_full.xml"),
144                      ("Новости [RSS 2.0] только заголовки",  "application/rss+xml",  "rss_20_titles.xml"),
145                      ("Новости [RSS 2.0]",  "application/rss+xml",  "rss_20.xml"),
146                      ("Новости [RSS 2.0] полные тексты",  "application/rss+xml",  "rss_20_full.xml"),
147 )
148 ##
149 #def body_html
150 <h1>Журнал</h1>
151 """ % {"cyear": year or 2005})
152
153    elif level == 1:
154       new_text.append("""\
155 #attr $Title = "Oleg Broytman's blog: %(year)s"
156 #attr $Description = "Broytman Russian Blog %(year)s Index Document"
157 #attr $Copyright = %(cyear)s
158 ##
159 #def body_html
160 <h1>Журнал: %(year)s</h1>
161 """ % {"year": year, "cyear": year or 2005})
162
163    elif level == 2:
164       imonth = int(month)
165       new_text.append("""\
166 #attr $Title = "Oleg Broytman's blog: %(month_abbr_en)s %(year)s"
167 #attr $Description = "Broytman Russian Blog %(month_name_en)s %(year)s Index Document"
168 #attr $Copyright = %(cyear)s
169 ##
170 #def body_html
171 <h1>Журнал: %(month_name_ru0)s %(year)s</h1>
172 """ % {
173       "year": year, "cyear": year or 2005,
174       "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
175       "month_name_ru0": months_names_ru0[imonth],
176    })
177
178    elif level == 3:
179       iday = int(day)
180       imonth = int(month)
181
182       if len(titles) == 1:
183          new_text.append("""\
184 #attr $Refresh = "0; URL=%s"
185 """ % titles[0][3])
186
187       new_text.append("""\
188 #attr $Title = "Oleg Broytman's blog: %(day)d %(month_abbr_en)s %(year)s"
189 #attr $Description = "Broytman Russian Blog %(day)d %(month_name_en)s %(year)s Index Document"
190 #attr $Copyright = %(cyear)s
191 ##
192 #def body_html
193 <h1>Журнал: %(day)d %(month_name_ru)s %(year)s</h1>
194 """ % {
195       "year": year, "cyear": year or 2005,
196       "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
197       "month_name_ru": months_names_ru[imonth],
198       "day": iday
199    })
200
201    save_titles = titles[:]
202    titles.reverse()
203
204    save_date = None
205    for year, month, day, file, title, lead in titles:
206       href = []
207       if level == 0:
208          href.append(year)
209       if level <= 1:
210          href.append(month)
211       if level <= 2:
212          href.append(day)
213       href.append(file)
214       href = '/'.join(href)
215       if day[0] == '0': day = day[1:]
216       if save_date <> (year, month, day):
217          if level == 0:
218             new_text.append('\n<h2>%s %s %s</h2>' % (day, months_names_ru[int(month)], year))
219          else:
220             new_text.append('\n<h2>%s %s</h2>' % (day, months_names_ru[int(month)]))
221          save_date = year, month, day
222       new_text.append('''
223 <p class="head">
224    %s<a href="%s">%s</a>.
225 </p>
226 ''' % (lead+' ' if lead else '', href, title))
227
228    if level == 0:
229       new_text.append("""
230 <hr>
231
232 <p class="head">Новостевая лента в форматах
233 <img src="../../Graphics/atom_10.jpg" border=0>
234 <A HREF="atom_10_titles.xml">Atom 1.0 только заголовки</A> /
235 <A HREF="atom_10.xml">Atom 1.0</A> /
236 <A HREF="atom_10_full.xml">Atom 1.0 полные тексты</A>
237 и <img src="../../Graphics/rss_20.jpg" border=0>
238 <A HREF="rss_20_titles.xml">RSS 2.0 только заголовки</A> /
239 <A HREF="rss_20.xml">RSS 2.0</A> /
240 <A HREF="rss_20_full.xml">RSS 2.0 полные тексты</A>.
241 </p>
242 """)
243
244       years = {}
245       for year, month, day, file, title, lead in save_titles:
246          years[year] = True
247       new_text.append('''
248 <p class="head"><a href="tags/">Теги</a>:
249 ''')
250       first_tag = True
251       for count, tag, links in all_tags:
252          if first_tag:
253             first_tag = False
254          else:
255             new_text.append(' - ')
256          new_text.append("""<a href="tags/%s.html">%s (%d)</a>""" % (tag, tag, count))
257       new_text.append('''
258 </p>
259 ''')
260
261       max_year = int(sorted(years.keys())[-1])
262       years = range(max_year, 2005, -1)
263
264       new_text.append('''
265 <p class="head">По годам:
266 ''')
267       first_year = True
268       for year in years:
269          if first_year:
270             first_year = False
271          else:
272             new_text.append(' - ')
273          new_text.append('<a href="%s/">%s</a>' % (year, year))
274       new_text.append('''
275 </p>
276 ''')
277
278       new_text.append("""
279 <hr>
280 <p class="head"><a href="http://phd.livejournal.com/">ЖЖ</a>
281 """)
282
283    new_text.append("""\
284 #end def
285 $phd_site.respond(self)
286 """)
287
288    write_if_changed(index_name, ''.join(new_text))
289
290
291 all_tags = {}
292 all_titles = []
293 all_titles_tags = []
294
295 for year in sorted(years.keys()):
296    year_titles = []
297    months = years[year]
298    for month in sorted(months.keys()):
299       month_titles = []
300       for day in sorted(months[month]):
301          day_titles = []
302          key = year, month, day
303          if key in blog:
304             for file, title, lead, tags in blog[key]:
305                if file.endswith(".tmpl"): file = file[:-len("tmpl")] + "html"
306                value = (year, month, day, file, title, lead)
307                all_titles_tags.append((year, month, day, file, title, lead, tags))
308                all_titles.append(value)
309                year_titles.append(value)
310                month_titles.append(value)
311                day_titles.append(value)
312                for tag in tags:
313                   if tag in all_tags:
314                      tag_links = all_tags[tag]
315                   else:
316                      tag_links = all_tags[tag] = []
317                   tag_links.append(value)
318          write_template(3, year, month, day, day_titles)
319       write_template(2, year, month, day, month_titles)
320    write_template(1, year, month, day, year_titles)
321
322 def by_count_rev_tag_link(t1, t2):
323    """Sort all_tags by count in descending order,
324    and by tags and links in ascending order
325    """
326    r = cmp(t1[0], t2[0])
327    if r:
328       return -r
329    return cmp((t1[1], t1[2]), (t2[1], t2[2]))
330
331 all_tags = [(len(links), tag, links) for (tag, links) in all_tags.items()]
332 all_tags.sort(by_count_rev_tag_link)
333
334 write_template(0, year, month, day, all_titles[-20:], all_tags)
335
336 new_text = ["""\
337 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
338 #encoding koi8-r
339 #extends phd_site
340 #implements respond
341 #attr $Title = "Oleg Broytman's blog: tags"
342 #attr $Description = "Broytman Russian Blog Tags Index Document"
343 #attr $Copyright = 2006
344 ##
345 #def body_html
346 <h1>Теги</h1>
347
348 <p class="head">
349 <dl>
350 """]
351
352 for i, (count, tag, links) in enumerate(all_tags):
353    new_text.append("""\
354    <dt><a href="%s.html">%s (%d)</a></dt>
355 """ % (tag, tag, count))
356
357    first = all_tags[0][1]
358    if i == 0:
359       prev = None
360    else:
361       prev = all_tags[i-1][1]
362    if i >= len(all_tags)-1:
363       next = None
364    else:
365       next = all_tags[i+1][1]
366    last = all_tags[-1][1]
367
368    tag_text = ["""\
369 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
370 #encoding koi8-r
371 #extends phd_site
372 #implements respond
373 #attr $Title = "Oleg Broytman's blog: tag %s"
374 #attr $Description = "Broytman Russian Blog Tag %s Index Document"
375 """ % (tag, tag)]
376
377    tag_text.append("""\
378 #attr $First = "%s"
379 """ % first)
380
381    if prev:
382       tag_text.append("""\
383 #attr $Prev = "%s"
384 """ % prev)
385
386    if next:
387       tag_text.append("""\
388 #attr $Next = "%s"
389 """ % next)
390
391    tag_text.append("""\
392 #attr $Last = "%s"
393 """ % last)
394
395    tag_text.append("""\
396 #attr $Copyright = 2006
397 ##
398 #def body_html
399 <h1>%s</h1>
400
401 <p class="head">
402 <ul>
403 """ % tag)
404
405    count = 0
406    for year, month, day, filename, title, lead in reversed(links):
407       link = "../%s/%s/%s/%s" % (year, month, day, filename)
408       item_text = """<li><a href="%s">%s/%s/%s: %s%s</a></li>""" % (link, year, month, day, lead+' ' if lead else '', title)
409
410       count += 1
411       if count <= 5:
412          new_text.append("      <dd>%s</dd>\n" % item_text)
413
414       tag_text.append("   %s\n" % item_text)
415
416    tag_text.append("""\
417 </ul>
418 </p>
419 #end def
420 $phd_site.respond(self)
421 """)
422    write_if_changed(os.path.join(blog_root, "tags", tag+".tmpl"), ''.join(tag_text))
423
424 new_text.append("""\
425 </dl>
426 </p>
427 #end def
428 $phd_site.respond(self)
429 """)
430 write_if_changed(os.path.join(blog_root, "tags", "index.tmpl"), ''.join(new_text))
431
432
433 from HTMLParser import HTMLParseError
434 import cgi
435 from urlparse import urljoin
436 from m_lib.net.www.html import HTMLParser as _HTMLParser
437
438 class HTMLDone(Exception): pass
439
440
441 class FirstPHTMLParser(_HTMLParser):
442    def __init__(self):
443       _HTMLParser.__init__(self)
444       self.first_p = None
445
446    def start_p(self, attrs):
447       self.accumulator = '<p>'
448
449    def end_p(self):
450       self.first_p = self.accumulator + '</p>'
451       raise HTMLDone()
452
453 def get_first_p(body):
454    parser = FirstPHTMLParser()
455
456    try:
457       parser.feed(body)
458    except (HTMLParseError, HTMLDone):
459       pass
460
461    try:
462       parser.close()
463    except (HTMLParseError, HTMLDone):
464       pass
465
466    return parser.first_p
467
468
469 class AbsURLHTMLParser(_HTMLParser):
470    def __init__(self, base):
471       _HTMLParser.__init__(self)
472       self.base = base
473
474    def start_a(self, attrs):
475       self.accumulator += '<a'
476       for attrname, value in attrs:
477          value = cgi.escape(value, True)
478          if attrname == 'href':
479             self.accumulator += ' href="%s"' % urljoin(self.base, value)
480          else:
481             self.accumulator += ' %s="%s"' % (attrname, value)
482       self.accumulator += '>'
483
484    def end_a(self):
485       self.accumulator += '</a>'
486
487    def start_img(self, attrs):
488       self.accumulator += '<img'
489       for attrname, value in attrs:
490          value = cgi.escape(value, True)
491          if attrname == 'src':
492             self.accumulator += ' src="%s"' % urljoin(self.base, value)
493          else:
494             self.accumulator += ' %s="%s"' % (attrname, value)
495       self.accumulator += '>'
496
497    def end_img(self):
498        pass
499
500 def absolute_urls(body, base):
501    parser = AbsURLHTMLParser(base)
502
503    try:
504       parser.feed(body)
505    except HTMLParseError:
506       pass
507
508    try:
509       parser.close()
510    except HTMLParseError:
511       pass
512
513    return parser.accumulator
514
515
516 from atom_10 import atom_10
517 from rss_20 import rss_20
518 from news import NewsItem
519
520 if blog_root:
521    baseURL = "http://phdru.name/%s/" % blog_root
522 else:
523    baseURL = "http://phdru.name/"
524
525 items = []
526 for item in tuple(reversed(all_titles_tags))[:10]:
527    year, month, day, file, title, lead, tags = item
528    lead = lead.decode('koi8-r').encode('utf-8')
529    title = title.decode('koi8-r').encode('utf-8')
530    url_path = "%s/%s/%s/%s" % (year, month, day, file)
531    item = NewsItem(
532       "%s-%s-%s" % (year, month, day),
533       "%s%s" % (lead+' ' if lead else '', title),
534       url_path)
535    items.append(item)
536    item.baseURL = baseURL
537    item.categoryList = tags
538    body = bodies[(year, month, day, file)]
539    body = absolute_urls(body, baseURL + url_path)
540    body = body.decode('koi8-r').encode('utf-8')
541    item.body = body
542    item.excerpt = get_first_p(body)
543
544 namespace = {
545    "title": "Oleg Broytman's blog",
546    "baseURL": baseURL,
547    "indexFile": "",
548    "description": "",
549    "lang": "ru",
550    "author": "Oleg Broytman",
551    "email": "phd@phdru.name",
552    "generator": os.path.basename(sys.argv[0]),
553    "posts": items,
554 }
555
556 # For english dates
557 locale.setlocale(locale.LC_TIME, 'C')
558
559 atom_tmpl = unicode(atom_10(searchList=[namespace])).encode('koi8-r')
560 write_if_changed(os.path.join(blog_root, "atom_10.xml"), atom_tmpl)
561 rss_tmpl = unicode(rss_20(searchList=[namespace])).encode('koi8-r')
562 write_if_changed(os.path.join(blog_root, "rss_20.xml"), rss_tmpl)
563
564 for item in items:
565     item.excerpt = None
566
567 atom_tmpl = unicode(atom_10(searchList=[namespace])).encode('koi8-r')
568 write_if_changed(os.path.join(blog_root, "atom_10_titles.xml"), atom_tmpl)
569 rss_tmpl = unicode(rss_20(searchList=[namespace])).encode('koi8-r')
570 write_if_changed(os.path.join(blog_root, "rss_20_titles.xml"), rss_tmpl)
571
572 for item in items:
573     item.content = item.body
574
575 atom_tmpl = unicode(atom_10(searchList=[namespace])).encode('koi8-r')
576 write_if_changed(os.path.join(blog_root, "atom_10_full.xml"), atom_tmpl)
577 rss_tmpl = unicode(rss_20(searchList=[namespace])).encode('koi8-r')
578 write_if_changed(os.path.join(blog_root, "rss_20_full.xml"), rss_tmpl)