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