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