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