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