]> git.phdru.name Git - phdru.name/phdru.name.git/blob - reindex_blog.py
Generate sitemaps using google's sitemap_gen.py
[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 small">
356 Форма поиска позволяет искать сообщения в блоге, соответствующие выражению.
357 Синтаксис выражения:</p>
358 <ul class="small">
359     <li>Тег - если такой тег существует, произойдёт перенаправление на страницу тега.</li>
360     <li>Оператор '!' (NOT) - ищет записи, в которых нет этого тега.</li>
361     <li>Оператор '&amp;' (AND) - ищет записи, в которых есть оба тега.</li>
362     <li>Оператор '|' (OR) - ищет записи, в которых есть один из тегов.</li>
363     <li>Скобки '()' позволяют объединять выражения.</li>
364 </ul>
365 <p class="small">
366 Пробелы не допускаются. Примеры выражений: linux - произойдёт перенаправление
367 на страницу linux.html; linux&amp;!audio - искать записи в которых есть тег
368 linux и нет тега audio.
369 </p>
370
371 <center>
372 <form method=GET action="../../../cgi-bin/blog-ru/search-tags/search-tags.py">
373     <input type=text name=q>
374     <input type=submit name=submit value="Искать">
375 </form>
376 </center>
377
378 <p class="head">
379 <dl>
380 """]
381
382 for i, (count, tag, links) in enumerate(all_tags):
383    new_text.append("""\
384    <dt><a href="%s.html">%s (%d)</a></dt>
385 """ % (tag, tag, count))
386
387    first = all_tags[0][1]
388    if i == 0:
389       prev = None
390    else:
391       prev = all_tags[i-1][1]
392    if i >= len(all_tags)-1:
393       next = None
394    else:
395       next = all_tags[i+1][1]
396    last = all_tags[-1][1]
397
398    tag_text = ["""\
399 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
400 #encoding koi8-r
401 #extends phd_site
402 #implements respond
403 #attr $Title = "Oleg Broytman's blog: tag %s"
404 #attr $Description = "Broytman Russian Blog Tag %s Index Document"
405 """ % (tag, tag)]
406
407    tag_text.append("""\
408 #attr $First = "%s"
409 """ % first)
410
411    if prev:
412       tag_text.append("""\
413 #attr $Prev = "%s"
414 """ % prev)
415
416    if next:
417       tag_text.append("""\
418 #attr $Next = "%s"
419 """ % next)
420
421    tag_text.append("""\
422 #attr $Last = "%s"
423 """ % last)
424
425    tag_text.append("""\
426 #attr $Copyright = 2006
427 ##
428 #def body_html
429 <h1>%s</h1>
430
431 <p class="head">
432 <ul>
433 """ % tag)
434
435    count = 0
436    for year, month, day, filename, title, lead in reversed(links):
437       link = "../%s/%s/%s/%s" % (year, month, day, filename)
438       item_text = """<li><a href="%s">%s/%s/%s: %s%s</a></li>""" % (link, year, month, day, lead+' ' if lead else '', title)
439
440       count += 1
441       if count <= 5:
442          new_text.append("      <dd>%s</dd>\n" % item_text)
443
444       tag_text.append("   %s\n" % item_text)
445
446    tag_text.append("""\
447 </ul>
448 </p>
449 #end def
450 $phd_site.respond(self)
451 """)
452    write_if_changed(os.path.join(blog_root, "tags", tag+".tmpl"), ''.join(tag_text))
453
454 new_text.append("""\
455 </dl>
456 </p>
457 #end def
458 $phd_site.respond(self)
459 """)
460 write_if_changed(os.path.join(blog_root, "tags", "index.tmpl"), ''.join(new_text))
461
462
463 from HTMLParser import HTMLParseError
464 import cgi
465 from urlparse import urljoin
466 from m_lib.net.www.html import HTMLParser as _HTMLParser
467
468 class HTMLDone(Exception): pass
469
470
471 class FirstPHTMLParser(_HTMLParser):
472    def __init__(self):
473       _HTMLParser.__init__(self)
474       self.first_p = None
475
476    def start_p(self, attrs):
477       self.accumulator = '<p>'
478
479    def end_p(self):
480       self.first_p = self.accumulator + '</p>'
481       raise HTMLDone()
482
483 def get_first_p(body):
484    parser = FirstPHTMLParser()
485
486    try:
487       parser.feed(body)
488    except (HTMLParseError, HTMLDone):
489       pass
490
491    try:
492       parser.close()
493    except (HTMLParseError, HTMLDone):
494       pass
495
496    return parser.first_p
497
498
499 class AbsURLHTMLParser(_HTMLParser):
500    def __init__(self, base):
501       _HTMLParser.__init__(self)
502       self.base = base
503
504    def start_a(self, attrs):
505       self.accumulator += '<a'
506       for attrname, value in attrs:
507          value = cgi.escape(value, True)
508          if attrname == 'href':
509             self.accumulator += ' href="%s"' % urljoin(self.base, value)
510          else:
511             self.accumulator += ' %s="%s"' % (attrname, value)
512       self.accumulator += '>'
513
514    def end_a(self):
515       self.accumulator += '</a>'
516
517    def start_img(self, attrs):
518       self.accumulator += '<img'
519       for attrname, value in attrs:
520          value = cgi.escape(value, True)
521          if attrname == 'src':
522             self.accumulator += ' src="%s"' % urljoin(self.base, value)
523          else:
524             self.accumulator += ' %s="%s"' % (attrname, value)
525       self.accumulator += '>'
526
527    def end_img(self):
528        pass
529
530 def absolute_urls(body, base):
531    parser = AbsURLHTMLParser(base)
532
533    try:
534       parser.feed(body)
535    except HTMLParseError:
536       pass
537
538    try:
539       parser.close()
540    except HTMLParseError:
541       pass
542
543    return parser.accumulator
544
545
546 from atom_10 import atom_10
547 from rss_20 import rss_20
548 from news import NewsItem
549
550 if blog_root:
551    baseURL = "http://phdru.name/%s/" % blog_root
552 else:
553    baseURL = "http://phdru.name/"
554
555 items = []
556 for item in tuple(reversed(all_titles_tags))[:10]:
557    year, month, day, file, title, lead, tags = item
558    lead = lead.decode('koi8-r').encode('utf-8')
559    title = title.decode('koi8-r').encode('utf-8')
560    url_path = "%s/%s/%s/%s" % (year, month, day, file)
561    item = NewsItem(
562       "%s-%s-%s" % (year, month, day),
563       "%s%s" % (lead+' ' if lead else '', title),
564       url_path)
565    items.append(item)
566    item.baseURL = baseURL
567    item.categoryList = tags
568    body = bodies[(year, month, day, file)]
569    body = absolute_urls(body, baseURL + url_path)
570    body = body.decode('koi8-r').encode('utf-8')
571    item.body = body
572    item.excerpt = get_first_p(body)
573
574 namespace = {
575    "title": "Oleg Broytman's blog",
576    "baseURL": baseURL,
577    "indexFile": "",
578    "description": "",
579    "lang": "ru",
580    "author": "Oleg Broytman",
581    "email": "phd@phdru.name",
582    "generator": os.path.basename(sys.argv[0]),
583    "posts": items,
584 }
585
586 # For english dates
587 locale.setlocale(locale.LC_TIME, 'C')
588
589 atom_tmpl = unicode(atom_10(searchList=[namespace])).encode('koi8-r')
590 write_if_changed(os.path.join(blog_root, "atom_10.xml"), atom_tmpl)
591 rss_tmpl = unicode(rss_20(searchList=[namespace])).encode('koi8-r')
592 write_if_changed(os.path.join(blog_root, "rss_20.xml"), rss_tmpl)
593
594 for item in items:
595     item.excerpt = None
596
597 atom_tmpl = unicode(atom_10(searchList=[namespace])).encode('koi8-r')
598 write_if_changed(os.path.join(blog_root, "atom_10_titles.xml"), atom_tmpl)
599 rss_tmpl = unicode(rss_20(searchList=[namespace])).encode('koi8-r')
600 write_if_changed(os.path.join(blog_root, "rss_20_titles.xml"), rss_tmpl)
601
602 for item in items:
603     item.content = item.body
604
605 atom_tmpl = unicode(atom_10(searchList=[namespace])).encode('koi8-r')
606 write_if_changed(os.path.join(blog_root, "atom_10_full.xml"), atom_tmpl)
607 rss_tmpl = unicode(rss_20(searchList=[namespace])).encode('koi8-r')
608 write_if_changed(os.path.join(blog_root, "rss_20_full.xml"), rss_tmpl)