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