]> git.phdru.name Git - phdru.name/phdru.name.git/blob - reindex_blog.py
Fix & => &
[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
268       year_counts = {}
269       for year, month, day, file, title, lead in all_titles:
270          year_counts[year] = 0
271       for year, month, day, file, title, lead in all_titles:
272          year_counts[year] += 1
273
274       first_year = True
275       for year in years:
276          if first_year:
277             first_year = False
278          else:
279             new_text.append(' - ')
280          new_text.append('<a href="%s/">%s (%d)</a>' % (year, year, year_counts[str(year)]))
281       new_text.append('''
282 </p>
283 ''')
284
285       new_text.append("""
286 <hr>
287 <p class="head"><a href="http://phd.livejournal.com/">ЖЖ</a>
288 """)
289
290    new_text.append("""\
291 #end def
292 $phd_site.respond(self)
293 """)
294
295    write_if_changed(index_name, ''.join(new_text))
296
297
298 all_tags = {}
299 all_titles = []
300 all_titles_tags = []
301
302 for year in sorted(years.keys()):
303    year_titles = []
304    months = years[year]
305    for month in sorted(months.keys()):
306       month_titles = []
307       for day in sorted(months[month]):
308          day_titles = []
309          key = year, month, day
310          if key in blog:
311             for file, title, lead, tags in blog[key]:
312                if file.endswith(".tmpl"): file = file[:-len("tmpl")] + "html"
313                value = (year, month, day, file, title, lead)
314                all_titles_tags.append((year, month, day, file, title, lead, tags))
315                all_titles.append(value)
316                year_titles.append(value)
317                month_titles.append(value)
318                day_titles.append(value)
319                for tag in tags:
320                   if tag in all_tags:
321                      tag_links = all_tags[tag]
322                   else:
323                      tag_links = all_tags[tag] = []
324                   tag_links.append(value)
325          write_template(3, year, month, day, day_titles)
326       write_template(2, year, month, day, month_titles)
327    write_template(1, year, month, day, year_titles)
328
329 def by_count_rev_tag_link(t1, t2):
330    """Sort all_tags by count in descending order,
331    and by tags and links in ascending order
332    """
333    r = cmp(t1[0], t2[0])
334    if r:
335       return -r
336    return cmp((t1[1], t1[2]), (t2[1], t2[2]))
337
338 all_tags = [(len(links), tag, links) for (tag, links) in all_tags.items()]
339 all_tags.sort(by_count_rev_tag_link)
340
341 write_template(0, year, month, day, all_titles[-20:], all_tags)
342
343 new_text = ["""\
344 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
345 #encoding koi8-r
346 #extends phd_site
347 #implements respond
348 #attr $Title = "Oleg Broytman's blog: tags"
349 #attr $Description = "Broytman Russian Blog Tags Index Document"
350 #attr $Copyright = 2006
351 ##
352 #def body_html
353 <h1>Теги</h1>
354
355 <p class="head">
356 Форма поиска позволяет искать сообщения в блоге, соответствующие выражению.
357 Синтаксис выражения:<ul>
358     <li>Тег - если такой тег существует, произойдёт перенаправление на страницу тега.</li>
359     <li>Оператор '!' (NOT) - ищет записи, в которых нет этого тега.</li>
360     <li>Оператор '&amp;' (AND) - ищет записи, в которых есть оба тега.</li>
361     <li>Оператор '|' (OR) - ищет записи, в которых есть один из тегов.</li>
362     <li>Скобки '()' позволяют объединять выражения.</li>
363 </ul>
364 Пробелы не допускаются. Примеры выражений: linux - произойдёт перенаправление
365 на страницу linux.html; linux&amp;!audio - искать записи в которых есть тег
366 linux и нет тега audio.
367 </p>
368
369 <center>
370 <form method=GET action="../../../cgi-bin/blog-ru/search-tags/search-tags.py">
371     <input type=text name=q>
372     <input type=submit name=submit value="Искать">
373 </form>
374 </center>
375
376 <p class="head">
377 <dl>
378 """]
379
380 for i, (count, tag, links) in enumerate(all_tags):
381    new_text.append("""\
382    <dt><a href="%s.html">%s (%d)</a></dt>
383 """ % (tag, tag, count))
384
385    first = all_tags[0][1]
386    if i == 0:
387       prev = None
388    else:
389       prev = all_tags[i-1][1]
390    if i >= len(all_tags)-1:
391       next = None
392    else:
393       next = all_tags[i+1][1]
394    last = all_tags[-1][1]
395
396    tag_text = ["""\
397 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
398 #encoding koi8-r
399 #extends phd_site
400 #implements respond
401 #attr $Title = "Oleg Broytman's blog: tag %s"
402 #attr $Description = "Broytman Russian Blog Tag %s Index Document"
403 """ % (tag, tag)]
404
405    tag_text.append("""\
406 #attr $First = "%s"
407 """ % first)
408
409    if prev:
410       tag_text.append("""\
411 #attr $Prev = "%s"
412 """ % prev)
413
414    if next:
415       tag_text.append("""\
416 #attr $Next = "%s"
417 """ % next)
418
419    tag_text.append("""\
420 #attr $Last = "%s"
421 """ % last)
422
423    tag_text.append("""\
424 #attr $Copyright = 2006
425 ##
426 #def body_html
427 <h1>%s</h1>
428
429 <p class="head">
430 <ul>
431 """ % tag)
432
433    count = 0
434    for year, month, day, filename, title, lead in reversed(links):
435       link = "../%s/%s/%s/%s" % (year, month, day, filename)
436       item_text = """<li><a href="%s">%s/%s/%s: %s%s</a></li>""" % (link, year, month, day, lead+' ' if lead else '', title)
437
438       count += 1
439       if count <= 5:
440          new_text.append("      <dd>%s</dd>\n" % item_text)
441
442       tag_text.append("   %s\n" % item_text)
443
444    tag_text.append("""\
445 </ul>
446 </p>
447 #end def
448 $phd_site.respond(self)
449 """)
450    write_if_changed(os.path.join(blog_root, "tags", tag+".tmpl"), ''.join(tag_text))
451
452 new_text.append("""\
453 </dl>
454 </p>
455 #end def
456 $phd_site.respond(self)
457 """)
458 write_if_changed(os.path.join(blog_root, "tags", "index.tmpl"), ''.join(new_text))
459
460
461 from HTMLParser import HTMLParseError
462 import cgi
463 from urlparse import urljoin
464 from m_lib.net.www.html import HTMLParser as _HTMLParser
465
466 class HTMLDone(Exception): pass
467
468
469 class FirstPHTMLParser(_HTMLParser):
470    def __init__(self):
471       _HTMLParser.__init__(self)
472       self.first_p = None
473
474    def start_p(self, attrs):
475       self.accumulator = '<p>'
476
477    def end_p(self):
478       self.first_p = self.accumulator + '</p>'
479       raise HTMLDone()
480
481 def get_first_p(body):
482    parser = FirstPHTMLParser()
483
484    try:
485       parser.feed(body)
486    except (HTMLParseError, HTMLDone):
487       pass
488
489    try:
490       parser.close()
491    except (HTMLParseError, HTMLDone):
492       pass
493
494    return parser.first_p
495
496
497 class AbsURLHTMLParser(_HTMLParser):
498    def __init__(self, base):
499       _HTMLParser.__init__(self)
500       self.base = base
501
502    def start_a(self, attrs):
503       self.accumulator += '<a'
504       for attrname, value in attrs:
505          value = cgi.escape(value, True)
506          if attrname == 'href':
507             self.accumulator += ' href="%s"' % urljoin(self.base, value)
508          else:
509             self.accumulator += ' %s="%s"' % (attrname, value)
510       self.accumulator += '>'
511
512    def end_a(self):
513       self.accumulator += '</a>'
514
515    def start_img(self, attrs):
516       self.accumulator += '<img'
517       for attrname, value in attrs:
518          value = cgi.escape(value, True)
519          if attrname == 'src':
520             self.accumulator += ' src="%s"' % urljoin(self.base, value)
521          else:
522             self.accumulator += ' %s="%s"' % (attrname, value)
523       self.accumulator += '>'
524
525    def end_img(self):
526        pass
527
528 def absolute_urls(body, base):
529    parser = AbsURLHTMLParser(base)
530
531    try:
532       parser.feed(body)
533    except HTMLParseError:
534       pass
535
536    try:
537       parser.close()
538    except HTMLParseError:
539       pass
540
541    return parser.accumulator
542
543
544 from atom_10 import atom_10
545 from rss_20 import rss_20
546 from news import NewsItem
547
548 if blog_root:
549    baseURL = "http://phdru.name/%s/" % blog_root
550 else:
551    baseURL = "http://phdru.name/"
552
553 items = []
554 for item in tuple(reversed(all_titles_tags))[:10]:
555    year, month, day, file, title, lead, tags = item
556    lead = lead.decode('koi8-r').encode('utf-8')
557    title = title.decode('koi8-r').encode('utf-8')
558    url_path = "%s/%s/%s/%s" % (year, month, day, file)
559    item = NewsItem(
560       "%s-%s-%s" % (year, month, day),
561       "%s%s" % (lead+' ' if lead else '', title),
562       url_path)
563    items.append(item)
564    item.baseURL = baseURL
565    item.categoryList = tags
566    body = bodies[(year, month, day, file)]
567    body = absolute_urls(body, baseURL + url_path)
568    body = body.decode('koi8-r').encode('utf-8')
569    item.body = body
570    item.excerpt = get_first_p(body)
571
572 namespace = {
573    "title": "Oleg Broytman's blog",
574    "baseURL": baseURL,
575    "indexFile": "",
576    "description": "",
577    "lang": "ru",
578    "author": "Oleg Broytman",
579    "email": "phd@phdru.name",
580    "generator": os.path.basename(sys.argv[0]),
581    "posts": items,
582 }
583
584 # For english dates
585 locale.setlocale(locale.LC_TIME, 'C')
586
587 atom_tmpl = unicode(atom_10(searchList=[namespace])).encode('koi8-r')
588 write_if_changed(os.path.join(blog_root, "atom_10.xml"), atom_tmpl)
589 rss_tmpl = unicode(rss_20(searchList=[namespace])).encode('koi8-r')
590 write_if_changed(os.path.join(blog_root, "rss_20.xml"), rss_tmpl)
591
592 for item in items:
593     item.excerpt = None
594
595 atom_tmpl = unicode(atom_10(searchList=[namespace])).encode('koi8-r')
596 write_if_changed(os.path.join(blog_root, "atom_10_titles.xml"), atom_tmpl)
597 rss_tmpl = unicode(rss_20(searchList=[namespace])).encode('koi8-r')
598 write_if_changed(os.path.join(blog_root, "rss_20_titles.xml"), rss_tmpl)
599
600 for item in items:
601     item.content = item.body
602
603 atom_tmpl = unicode(atom_10(searchList=[namespace])).encode('koi8-r')
604 write_if_changed(os.path.join(blog_root, "atom_10_full.xml"), atom_tmpl)
605 rss_tmpl = unicode(rss_20(searchList=[namespace])).encode('koi8-r')
606 write_if_changed(os.path.join(blog_root, "rss_20_full.xml"), rss_tmpl)