]> git.phdru.name Git - phdru.name/phdru.name.git/blob - reindex_blog.py
First/prev/next/last links in dotfiles and blog tags.
[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       if len(titles) == 1:
171          new_text.append("""\
172 #attr $refresh = "0; URL=%s"
173 """ % titles[0][3])
174
175       new_text.append("""\
176 #attr $Title = "Oleg Broytman's blog: %(day)d %(month_abbr_en)s %(year)s"
177 #attr $Description = "Broytman Russian Blog %(day)d %(month_name_en)s %(year)s Index Document"
178 #attr $Copyright = %(cyear)s
179 ##
180 #def body_html
181 <h1>Журнал: %(day)d %(month_name_ru)s %(year)s</h1>
182 """ % {
183       "year": year, "cyear": year or 2005,
184       "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
185       "month_name_ru": months_names_ru[imonth],
186       "day": iday
187    })
188
189    save_titles = titles[:]
190    titles.reverse()
191
192    save_date = None
193    for year, month, day, file, title, lead in titles:
194       href = []
195       if level == 0:
196          href.append(year)
197       if level <= 1:
198          href.append(month)
199       if level <= 2:
200          href.append(day)
201       href.append(file)
202       href = '/'.join(href)
203       if day[0] == '0': day = day[1:]
204       if save_date <> (year, month, day):
205          if level == 0:
206             new_text.append('\n<h2>%s %s %s</h2>' % (day, months_names_ru[int(month)], year))
207          else:
208             new_text.append('\n<h2>%s %s</h2>' % (day, months_names_ru[int(month)]))
209          save_date = year, month, day
210       if lead:
211          lead = lead + ' '
212       else:
213          lead = ''
214       new_text.append('''
215 <p class="head">
216    %s<a href="%s">%s</a>.
217 </p>
218 ''' % (lead, href, title))
219
220    if level == 0:
221       new_text.append("""
222 <hr>
223
224 <p class="head">Новостевая лента в форматах
225 <A HREF="atom_10.xml">Atom 1.0 <img src="../../Graphics/atom_10.jpg" border=0></A>
226 и <A HREF="rss_20.xml">RSS 2.0 <img src="../../Graphics/rss_20.jpg" border=0></A>.
227 </p>
228 """)
229
230       years = {}
231       for year, month, day, file, title, lead in save_titles:
232          years[year] = True
233       new_text.append('''
234 <p class="head"><a href="tags/">Теги</a>:
235 ''')
236       first_tag = True
237       for count, tag, links in all_tags:
238          if first_tag:
239             first_tag = False
240          else:
241             new_text.append(' - ')
242          new_text.append("""<a href="tags/%s.html">%s (%d)</a>""" % (tag, tag, count))
243       new_text.append('''
244 </p>
245 ''')
246
247       max_year = int(sorted(years.keys())[-1])
248       years = range(2005, max_year+1)
249
250       new_text.append('''
251 <p class="head">По годам:
252 ''')
253       first_year = True
254       for year in years:
255          if first_year:
256             first_year = False
257          else:
258             new_text.append(' - ')
259          new_text.append('<a href="%s/">%s</a>' % (year, year))
260       new_text.append('''
261 </p>
262 ''')
263
264       new_text.append("""
265 <hr>
266 <p class="head"><a href="http://phd.livejournal.com/">ЖЖ</a>
267 """)
268
269    new_text.append("""\
270 #end def
271 $phd_pp_ru.respond(self)
272 """)
273
274    write_if_changed(index_name, ''.join(new_text))
275
276
277 all_tags = {}
278 all_titles = []
279 all_titles_tags = []
280
281 for year in sorted(years.keys()):
282    year_titles = []
283    months = years[year]
284    for month in sorted(months.keys()):
285       month_titles = []
286       for day in sorted(months[month]):
287          day_titles = []
288          key = year, month, day
289          if key in blog:
290             for file, title, lead, tags in blog[key]:
291                if file.endswith(".tmpl"): file = file[:-len("tmpl")] + "html"
292                value = (year, month, day, file, title, lead)
293                all_titles_tags.append((year, month, day, file, title, lead, tags))
294                all_titles.append(value)
295                year_titles.append(value)
296                month_titles.append(value)
297                day_titles.append(value)
298                for tag in tags:
299                   if tag in all_tags:
300                      tag_links = all_tags[tag]
301                   else:
302                      tag_links = all_tags[tag] = []
303                   tag_links.append(value)
304          write_template(3, year, month, day, day_titles)
305       write_template(2, year, month, day, month_titles)
306    write_template(1, year, month, day, year_titles)
307
308 def by_count_rev_tag_link(t1, t2):
309    """Sort all_tags by count in descending order,
310    and by tags and links in ascending order
311    """
312    r = cmp(t1[0], t2[0])
313    if r:
314       return -r
315    return cmp((t1[1], t1[2]), (t2[1], t2[2]))
316
317 all_tags = [(len(links), tag, links) for (tag, links) in all_tags.items()]
318 all_tags.sort(by_count_rev_tag_link)
319
320 write_template(0, year, month, day, all_titles[-20:], all_tags)
321
322 new_text = ["""\
323 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
324 #extends phd_pp_ru
325 #implements respond
326 #attr $Title = "Oleg Broytman's blog: tags"
327 #attr $Description = "Broytman Russian Blog Tags Index Document"
328 #attr $Copyright = 2006
329 ##
330 #def body_html
331 <h1>Теги</h1>
332
333 <p class="head">
334 <dl>
335 """]
336
337 for i, (count, tag, links) in enumerate(all_tags):
338    new_text.append("""\
339    <dt><a href="%s.html">%s (%d)</a></dt>
340 """ % (tag, tag, count))
341
342    first = all_tags[0][1]
343    if i == 0:
344       prev = None
345    else:
346       prev = all_tags[i-1][1]
347    if i >= len(all_tags)-1:
348       next = None
349    else:
350       next = all_tags[i+1][1]
351    last = all_tags[-1][1]
352
353    tag_text = ["""\
354 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
355 #extends phd_pp_ru
356 #implements respond
357 #attr $Title = "Oleg Broytman's blog: tag %s"
358 #attr $Description = "Broytman Russian Blog Tag %s Index Document"
359 """ % (tag, tag)]
360
361    tag_text.append("""\
362 #attr $First = "%s"
363 """ % first)
364
365    if prev:
366       tag_text.append("""\
367 #attr $Prev = "%s"
368 """ % prev)
369
370    if next:
371       tag_text.append("""\
372 #attr $Next = "%s"
373 """ % next)
374
375    tag_text.append("""\
376 #attr $Last = "%s"
377 """ % last)
378
379    tag_text.append("""\
380 #attr $Copyright = 2006
381 ##
382 #def body_html
383 <h1>%s</h1>
384
385 <p class="head">
386 <ul>
387 """ % tag)
388
389    count = 0
390    for year, month, day, filename, title, lead in reversed(links):
391       if lead:
392          lead = lead + ' '
393       else:
394          lead = ''
395       link = "../%s/%s/%s/%s" % (year, month, day, filename)
396       item_text = """<li><a href="%s">%s/%s/%s: %s%s</a></li>""" % (link, year, month, day, lead, title)
397
398       count += 1
399       if count <= 5:
400          new_text.append("      <dd>%s</dd>\n" % item_text)
401
402       tag_text.append("   %s\n" % item_text)
403
404    tag_text.append("""\
405 </ul>
406 </p>
407 #end def
408 $phd_pp_ru.respond(self)
409 """)
410    write_if_changed(os.path.join(blog_root, "tags", tag+".tmpl"), ''.join(tag_text))
411
412 new_text.append("""\
413 </dl>
414 </p>
415 #end def
416 $phd_pp_ru.respond(self)
417 """)
418 write_if_changed(os.path.join(blog_root, "tags", "index.tmpl"), ''.join(new_text))
419
420
421 from atom_10 import atom_10
422 from rss_20 import rss_20
423 from news import NewsItem
424
425 if blog_root:
426    baseURL = "http://phd.pp.ru/%s/" % blog_root
427 else:
428    baseURL = "http://phd.pp.ru/"
429
430 items = []
431 for item in tuple(reversed(all_titles_tags))[:10]:
432    year, month, day, file, title, lead, tags = item
433    if lead:
434       lead = lead + ' '
435    else:
436       lead = ''
437    item = NewsItem(
438       "%s-%s-%s" % (year, month, day),
439       "%s%s" % (lead, title),
440       "%s/%s/%s/%s" % (year, month, day, file)
441    )
442    items.append(item)
443    item.baseURL = baseURL
444    item.categoryList = tags
445
446 namespace = {
447    "title": "Oleg Broytman's blog",
448    "baseURL": baseURL,
449    "indexFile": "",
450    "description": "",
451    "lang": "ru",
452    "author": "Oleg Broytman",
453    "email": "phd@phd.pp.ru",
454    "generator": os.path.basename(sys.argv[0]),
455    "posts": items,
456 }
457
458 # For english dates
459 locale.setlocale(locale.LC_TIME, 'C')
460
461 atom_tmpl = str(atom_10(searchList=[namespace]))
462 write_if_changed(os.path.join(blog_root, "atom_10.xml"), atom_tmpl)
463 rss_tmpl = str(rss_20(searchList=[namespace]))
464 write_if_changed(os.path.join(blog_root, "rss_20.xml"), rss_tmpl)