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