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