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