2 # -*- coding: koi8-r -*-
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"
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")
18 import cPickle as pickle
22 from Cheetah.Template import Template
28 blog_file = open(blog_filename, "rb")
32 old_blog = pickle.load(blog_file)
36 # blog is a dictionary mapping
37 # (year, month, day) => [list of (file, title, lead, tags)]
42 # bodies is a dictionary mapping file => body
46 # Walk the directory recursively
47 for dirpath, dirs, files in os.walk(blog_root):
48 d = os.path.basename(dirpath)
49 if not d.startswith("20") and not d.isdigit():
52 if not file.endswith(".tmpl"):
54 fullpath = os.path.join(dirpath, file)
55 template = Template(file=fullpath)
56 title_parts = template.Title.split()
57 title = ' '.join(title_parts[6:])
61 if isinstance(tags, basestring):
65 key = year, month, day = tuple(dirpath[len(blog_root):].split(os.sep)[1:])
70 days.append((file, title, lead, tags))
75 months = years[year] = {}
80 days = months[month] = []
82 if day not in days: days.append(day)
84 file = file[:-len("tmpl")] + "html"
85 key = (year, month, day, file)
86 bodies[key] = template.body()
88 # Need to save the blog?
90 blog_file = open(blog_filename, "wb")
91 pickle.dump(blog, blog_file, pickle.HIGHEST_PROTOCOL)
94 # Localized month names
97 locale.setlocale(locale.LC_ALL, "ru_RU.KOI8-R")
98 from calendar import _localized_day, _localized_month
100 locale.setlocale(locale.LC_TIME, 'C')
101 months_names_en = list(_localized_month('%B'))
102 months_abbrs_en = list(_localized_month('%b'))
104 locale.setlocale(locale.LC_TIME, "ru_RU.KOI8-R")
105 #months_names_ru = list(_localized_month('%B'))
107 months_names_ru = ['', "января", "февраля", "марта", "апреля", "мая", "июня",
108 "июля", "августа", "сентября", "октября", "ноября", "декабря"
111 months_names_ru0 = ['', "январь", "февраль", "март", "апрель", "май", "июнь",
112 "июль", "август", "сентябрь", "октябрь", "ноябрь", "декабрь"
115 from news import write_if_changed
118 def write_template(level, year, month, day, titles, tags=None):
126 path.append("index.tmpl")
127 index_name = os.path.join(*path)
130 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
137 #attr $Title = "Oleg Broytman's blog"
138 #attr $Description = "Broytman Russian Blog Index Document"
139 #attr $Copyright = %(cyear)s
140 #attr $alternates = (("Новости [Atom 1.0] только заголовки", "application/atom+xml", "atom_10_titles.xml"),
141 ("Новости [Atom 1.0]", "application/atom+xml", "atom_10.xml"),
142 ("Новости [Atom 1.0] полные тексты", "application/atom+xml", "atom_10_full.xml"),
143 ("Новости [RSS 2.0] только заголовки", "application/rss+xml", "rss_20_titles.xml"),
144 ("Новости [RSS 2.0]", "application/rss+xml", "rss_20.xml"),
145 ("Новости [RSS 2.0] полные тексты", "application/rss+xml", "rss_20_full.xml"),
150 """ % {"cyear": year or 2005})
154 #attr $Title = "Oleg Broytman's blog: %(year)s"
155 #attr $Description = "Broytman Russian Blog %(year)s Index Document"
156 #attr $Copyright = %(cyear)s
159 <h1>Журнал: %(year)s</h1>
160 """ % {"year": year, "cyear": year or 2005})
165 #attr $Title = "Oleg Broytman's blog: %(month_abbr_en)s %(year)s"
166 #attr $Description = "Broytman Russian Blog %(month_name_en)s %(year)s Index Document"
167 #attr $Copyright = %(cyear)s
170 <h1>Журнал: %(month_name_ru0)s %(year)s</h1>
172 "year": year, "cyear": year or 2005,
173 "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
174 "month_name_ru0": months_names_ru0[imonth],
183 #attr $refresh = "0; URL=%s"
187 #attr $Title = "Oleg Broytman's blog: %(day)d %(month_abbr_en)s %(year)s"
188 #attr $Description = "Broytman Russian Blog %(day)d %(month_name_en)s %(year)s Index Document"
189 #attr $Copyright = %(cyear)s
192 <h1>Журнал: %(day)d %(month_name_ru)s %(year)s</h1>
194 "year": year, "cyear": year or 2005,
195 "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
196 "month_name_ru": months_names_ru[imonth],
200 save_titles = titles[:]
204 for year, month, day, file, title, lead in titles:
213 href = '/'.join(href)
214 if day[0] == '0': day = day[1:]
215 if save_date <> (year, month, day):
217 new_text.append('\n<h2>%s %s %s</h2>' % (day, months_names_ru[int(month)], year))
219 new_text.append('\n<h2>%s %s</h2>' % (day, months_names_ru[int(month)]))
220 save_date = year, month, day
223 %s<a href="%s">%s</a>.
225 ''' % (lead+' ' if lead else '', href, title))
231 <p class="head">Новостевая лента в форматах
232 <img src="../../Graphics/atom_10.jpg" border=0>
233 <A HREF="atom_10_titles.xml">Atom 1.0 только заголовки</A> /
234 <A HREF="atom_10.xml">Atom 1.0</A> /
235 <A HREF="atom_10_full.xml">Atom 1.0 полные тексты</A>
236 и <img src="../../Graphics/rss_20.jpg" border=0>
237 <A HREF="rss_20_titles.xml">RSS 2.0 только заголовки</A> /
238 <A HREF="rss_20.xml">RSS 2.0</A> /
239 <A HREF="rss_20_full.xml">RSS 2.0 полные тексты</A>.
244 for year, month, day, file, title, lead in save_titles:
247 <p class="head"><a href="tags/">Теги</a>:
250 for count, tag, links in all_tags:
254 new_text.append(' - ')
255 new_text.append("""<a href="tags/%s.html">%s (%d)</a>""" % (tag, tag, count))
260 max_year = int(sorted(years.keys())[-1])
261 years = range(2005, max_year+1)
264 <p class="head">По годам:
271 new_text.append(' - ')
272 new_text.append('<a href="%s/">%s</a>' % (year, year))
279 <p class="head"><a href="http://phd.livejournal.com/">ЖЖ</a>
284 $phd_pp_ru.respond(self)
287 write_if_changed(index_name, ''.join(new_text))
294 for year in sorted(years.keys()):
297 for month in sorted(months.keys()):
299 for day in sorted(months[month]):
301 key = year, month, day
303 for file, title, lead, tags in blog[key]:
304 if file.endswith(".tmpl"): file = file[:-len("tmpl")] + "html"
305 value = (year, month, day, file, title, lead)
306 all_titles_tags.append((year, month, day, file, title, lead, tags))
307 all_titles.append(value)
308 year_titles.append(value)
309 month_titles.append(value)
310 day_titles.append(value)
313 tag_links = all_tags[tag]
315 tag_links = all_tags[tag] = []
316 tag_links.append(value)
317 write_template(3, year, month, day, day_titles)
318 write_template(2, year, month, day, month_titles)
319 write_template(1, year, month, day, year_titles)
321 def by_count_rev_tag_link(t1, t2):
322 """Sort all_tags by count in descending order,
323 and by tags and links in ascending order
325 r = cmp(t1[0], t2[0])
328 return cmp((t1[1], t1[2]), (t2[1], t2[2]))
330 all_tags = [(len(links), tag, links) for (tag, links) in all_tags.items()]
331 all_tags.sort(by_count_rev_tag_link)
333 write_template(0, year, month, day, all_titles[-20:], all_tags)
336 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
339 #attr $Title = "Oleg Broytman's blog: tags"
340 #attr $Description = "Broytman Russian Blog Tags Index Document"
341 #attr $Copyright = 2006
350 for i, (count, tag, links) in enumerate(all_tags):
352 <dt><a href="%s.html">%s (%d)</a></dt>
353 """ % (tag, tag, count))
355 first = all_tags[0][1]
359 prev = all_tags[i-1][1]
360 if i >= len(all_tags)-1:
363 next = all_tags[i+1][1]
364 last = all_tags[-1][1]
367 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
370 #attr $Title = "Oleg Broytman's blog: tag %s"
371 #attr $Description = "Broytman Russian Blog Tag %s Index Document"
393 #attr $Copyright = 2006
403 for year, month, day, filename, title, lead in reversed(links):
404 link = "../%s/%s/%s/%s" % (year, month, day, filename)
405 item_text = """<li><a href="%s">%s/%s/%s: %s%s</a></li>""" % (link, year, month, day, lead+' ' if lead else '', title)
409 new_text.append(" <dd>%s</dd>\n" % item_text)
411 tag_text.append(" %s\n" % item_text)
417 $phd_pp_ru.respond(self)
419 write_if_changed(os.path.join(blog_root, "tags", tag+".tmpl"), ''.join(tag_text))
425 $phd_pp_ru.respond(self)
427 write_if_changed(os.path.join(blog_root, "tags", "index.tmpl"), ''.join(new_text))
430 from HTMLParser import HTMLParseError
432 from urlparse import urljoin
433 from m_lib.net.www.html import HTMLParser as _HTMLParser
435 class HTMLDone(Exception): pass
438 class FirstPHTMLParser(_HTMLParser):
440 _HTMLParser.__init__(self)
443 def start_p(self, attrs):
444 self.accumulator = '<p>'
447 self.first_p = self.accumulator + '</p>'
450 def get_first_p(body):
451 parser = FirstPHTMLParser()
455 except (HTMLParseError, HTMLDone):
460 except (HTMLParseError, HTMLDone):
463 return parser.first_p
466 class AbsURLHTMLParser(_HTMLParser):
467 def __init__(self, base):
468 _HTMLParser.__init__(self)
471 def start_a(self, attrs):
472 self.accumulator += '<a'
473 for attrname, value in attrs:
474 value = cgi.escape(value, True)
475 if attrname == 'href':
476 self.accumulator += ' href="%s"' % urljoin(self.base, value)
478 self.accumulator += ' %s="%s"' % (attrname, value)
479 self.accumulator += '>'
482 self.accumulator += '</a>'
484 def absolute_urls(body, base):
485 parser = AbsURLHTMLParser(base)
489 except HTMLParseError:
494 except HTMLParseError:
497 return parser.accumulator
500 from atom_10 import atom_10
501 from rss_20 import rss_20
502 from news import NewsItem
505 baseURL = "http://phd.pp.ru/%s/" % blog_root
507 baseURL = "http://phd.pp.ru/"
510 for item in tuple(reversed(all_titles_tags))[:10]:
511 year, month, day, file, title, lead, tags = item
512 url_path = "%s/%s/%s/%s" % (year, month, day, file)
514 "%s-%s-%s" % (year, month, day),
515 "%s%s" % (lead+' ' if lead else '', title),
518 item.baseURL = baseURL
519 item.categoryList = tags
520 body = bodies[(year, month, day, file)]
521 body = absolute_urls(body, baseURL + url_path)
523 item.excerpt = get_first_p(body)
526 "title": "Oleg Broytman's blog",
531 "author": "Oleg Broytman",
532 "email": "phd@phd.pp.ru",
533 "generator": os.path.basename(sys.argv[0]),
538 locale.setlocale(locale.LC_TIME, 'C')
540 atom_tmpl = str(atom_10(searchList=[namespace]))
541 write_if_changed(os.path.join(blog_root, "atom_10.xml"), atom_tmpl)
542 rss_tmpl = str(rss_20(searchList=[namespace]))
543 write_if_changed(os.path.join(blog_root, "rss_20.xml"), rss_tmpl)
548 atom_tmpl = str(atom_10(searchList=[namespace]))
549 write_if_changed(os.path.join(blog_root, "atom_10_titles.xml"), atom_tmpl)
550 rss_tmpl = str(rss_20(searchList=[namespace]))
551 write_if_changed(os.path.join(blog_root, "rss_20_titles.xml"), rss_tmpl)
554 item.content = item.body
556 atom_tmpl = str(atom_10(searchList=[namespace]))
557 write_if_changed(os.path.join(blog_root, "atom_10_full.xml"), atom_tmpl)
558 rss_tmpl = str(rss_20(searchList=[namespace]))
559 write_if_changed(os.path.join(blog_root, "rss_20_full.xml"), rss_tmpl)