2 # -*- coding: koi8-r -*-
4 __author__ = "Oleg Broytman <phd@phdru.name>"
5 __copyright__ = "Copyright (C) 2006-2012 PhiloSoft Design"
9 blog_data_root = sys.argv[1]
10 blog_root = sys.argv[2]
11 blog_filename = os.path.join(blog_data_root, "blog_dict.pickle")
14 import cPickle as pickle
18 from Cheetah.Template import Template
24 blog_file = open(blog_filename, "rb")
28 old_blog = pickle.load(blog_file)
32 # blog is a dictionary mapping
33 # (year, month, day) => [list of (file, title, lead, tags)]
38 # bodies is a dictionary mapping file => body
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():
48 if not file.endswith(".tmpl"):
50 fullpath = os.path.join(dirpath, file)
51 template = Template(file=fullpath)
52 title_parts = template.Title.split()
53 title = ' '.join(title_parts[6:])
57 if isinstance(tags, basestring):
61 key = year, month, day = tuple(dirpath[len(blog_root):].split(os.sep)[1:])
66 days.append((file, title, lead, tags))
71 months = years[year] = {}
76 days = months[month] = []
78 if day not in days: days.append(day)
80 file = file[:-len("tmpl")] + "html"
81 key = (year, month, day, file)
82 bodies[key] = template.body()
84 # Need to save the blog?
86 blog_file = open(blog_filename, "wb")
87 pickle.dump(blog, blog_file, pickle.HIGHEST_PROTOCOL)
90 # Localized month names
93 locale.setlocale(locale.LC_ALL, "ru_RU.KOI8-R")
94 from calendar import _localized_day, _localized_month
96 locale.setlocale(locale.LC_TIME, 'C')
97 months_names_en = list(_localized_month('%B'))
98 months_abbrs_en = list(_localized_month('%b'))
100 locale.setlocale(locale.LC_TIME, "ru_RU.KOI8-R")
101 #months_names_ru = list(_localized_month('%B'))
103 months_names_ru = ['', "января", "февраля", "марта", "апреля", "мая", "июня",
104 "июля", "августа", "сентября", "октября", "ноября", "декабря"
107 months_names_ru0 = ['', "январь", "февраль", "март", "апрель", "май", "июнь",
108 "июль", "август", "сентябрь", "октябрь", "ноябрь", "декабрь"
111 from news import write_if_changed
114 def write_template(level, year, month, day, titles, tags=None):
122 path.append("index.tmpl")
123 index_name = os.path.join(*path)
126 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
134 #attr $Title = "Oleg Broytman's blog"
135 #attr $Description = "Broytman Russian Blog Index Document"
136 #attr $Copyright = %(cyear)s
137 #attr $alternates = (("Новости [Atom 1.0] только заголовки", "application/atom+xml", "atom_10_titles.xml"),
138 ("Новости [Atom 1.0]", "application/atom+xml", "atom_10.xml"),
139 ("Новости [Atom 1.0] полные тексты", "application/atom+xml", "atom_10_full.xml"),
140 ("Новости [RSS 2.0] только заголовки", "application/rss+xml", "rss_20_titles.xml"),
141 ("Новости [RSS 2.0]", "application/rss+xml", "rss_20.xml"),
142 ("Новости [RSS 2.0] полные тексты", "application/rss+xml", "rss_20_full.xml"),
147 """ % {"cyear": year or 2005})
151 #attr $Title = "Oleg Broytman's blog: %(year)s"
152 #attr $Description = "Broytman Russian Blog %(year)s Index Document"
153 #attr $Copyright = %(cyear)s
156 <h1>Журнал: %(year)s</h1>
157 """ % {"year": year, "cyear": year or 2005})
162 #attr $Title = "Oleg Broytman's blog: %(month_abbr_en)s %(year)s"
163 #attr $Description = "Broytman Russian Blog %(month_name_en)s %(year)s Index Document"
164 #attr $Copyright = %(cyear)s
167 <h1>Журнал: %(month_name_ru0)s %(year)s</h1>
169 "year": year, "cyear": year or 2005,
170 "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
171 "month_name_ru0": months_names_ru0[imonth],
180 #attr $Refresh = "0; URL=%s"
184 #attr $Title = "Oleg Broytman's blog: %(day)d %(month_abbr_en)s %(year)s"
185 #attr $Description = "Broytman Russian Blog %(day)d %(month_name_en)s %(year)s Index Document"
186 #attr $Copyright = %(cyear)s
189 <h1>Журнал: %(day)d %(month_name_ru)s %(year)s</h1>
191 "year": year, "cyear": year or 2005,
192 "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
193 "month_name_ru": months_names_ru[imonth],
197 save_titles = titles[:]
201 for year, month, day, file, title, lead in titles:
210 href = '/'.join(href)
211 if day[0] == '0': day = day[1:]
212 if save_date <> (year, month, day):
214 new_text.append('\n<h2>%s %s %s</h2>' % (day, months_names_ru[int(month)], year))
216 new_text.append('\n<h2>%s %s</h2>' % (day, months_names_ru[int(month)]))
217 save_date = year, month, day
220 %s<a href="%s">%s</a>.
222 ''' % (lead+' ' if lead else '', href, title))
228 <p class="head">Новостевая лента в форматах
229 <img src="../../Graphics/atom_10.jpg" border=0>
230 <A HREF="atom_10_titles.xml">Atom 1.0 только заголовки</A> /
231 <A HREF="atom_10.xml">Atom 1.0</A> /
232 <A HREF="atom_10_full.xml">Atom 1.0 полные тексты</A>
233 и <img src="../../Graphics/rss_20.jpg" border=0>
234 <A HREF="rss_20_titles.xml">RSS 2.0 только заголовки</A> /
235 <A HREF="rss_20.xml">RSS 2.0</A> /
236 <A HREF="rss_20_full.xml">RSS 2.0 полные тексты</A>.
241 for year, month, day, file, title, lead in save_titles:
244 <p class="head"><a href="tags/">Теги</a>:
247 for count, tag, links in all_tags:
251 new_text.append(' - ')
252 new_text.append("""<a href="tags/%s.html">%s (%d)</a>""" % (tag, tag, count))
257 max_year = int(sorted(years.keys())[-1])
258 years = range(max_year, 2005, -1)
261 <p class="head">По годам:
268 new_text.append(' - ')
269 new_text.append('<a href="%s/">%s</a>' % (year, year))
276 <p class="head"><a href="http://phd.livejournal.com/">ЖЖ</a>
281 $phd_site.respond(self)
284 write_if_changed(index_name, ''.join(new_text))
291 for year in sorted(years.keys()):
294 for month in sorted(months.keys()):
296 for day in sorted(months[month]):
298 key = year, month, day
300 for file, title, lead, tags in blog[key]:
301 if file.endswith(".tmpl"): file = file[:-len("tmpl")] + "html"
302 value = (year, month, day, file, title, lead)
303 all_titles_tags.append((year, month, day, file, title, lead, tags))
304 all_titles.append(value)
305 year_titles.append(value)
306 month_titles.append(value)
307 day_titles.append(value)
310 tag_links = all_tags[tag]
312 tag_links = all_tags[tag] = []
313 tag_links.append(value)
314 write_template(3, year, month, day, day_titles)
315 write_template(2, year, month, day, month_titles)
316 write_template(1, year, month, day, year_titles)
318 def by_count_rev_tag_link(t1, t2):
319 """Sort all_tags by count in descending order,
320 and by tags and links in ascending order
322 r = cmp(t1[0], t2[0])
325 return cmp((t1[1], t1[2]), (t2[1], t2[2]))
327 all_tags = [(len(links), tag, links) for (tag, links) in all_tags.items()]
328 all_tags.sort(by_count_rev_tag_link)
330 write_template(0, year, month, day, all_titles[-20:], all_tags)
333 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
337 #attr $Title = "Oleg Broytman's blog: tags"
338 #attr $Description = "Broytman Russian Blog Tags Index Document"
339 #attr $Copyright = 2006
348 for i, (count, tag, links) in enumerate(all_tags):
350 <dt><a href="%s.html">%s (%d)</a></dt>
351 """ % (tag, tag, count))
353 first = all_tags[0][1]
357 prev = all_tags[i-1][1]
358 if i >= len(all_tags)-1:
361 next = all_tags[i+1][1]
362 last = all_tags[-1][1]
365 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
369 #attr $Title = "Oleg Broytman's blog: tag %s"
370 #attr $Description = "Broytman Russian Blog Tag %s Index Document"
392 #attr $Copyright = 2006
402 for year, month, day, filename, title, lead in reversed(links):
403 link = "../%s/%s/%s/%s" % (year, month, day, filename)
404 item_text = """<li><a href="%s">%s/%s/%s: %s%s</a></li>""" % (link, year, month, day, lead+' ' if lead else '', title)
408 new_text.append(" <dd>%s</dd>\n" % item_text)
410 tag_text.append(" %s\n" % item_text)
416 $phd_site.respond(self)
418 write_if_changed(os.path.join(blog_root, "tags", tag+".tmpl"), ''.join(tag_text))
424 $phd_site.respond(self)
426 write_if_changed(os.path.join(blog_root, "tags", "index.tmpl"), ''.join(new_text))
429 from HTMLParser import HTMLParseError
431 from urlparse import urljoin
432 from m_lib.net.www.html import HTMLParser as _HTMLParser
434 class HTMLDone(Exception): pass
437 class FirstPHTMLParser(_HTMLParser):
439 _HTMLParser.__init__(self)
442 def start_p(self, attrs):
443 self.accumulator = '<p>'
446 self.first_p = self.accumulator + '</p>'
449 def get_first_p(body):
450 parser = FirstPHTMLParser()
454 except (HTMLParseError, HTMLDone):
459 except (HTMLParseError, HTMLDone):
462 return parser.first_p
465 class AbsURLHTMLParser(_HTMLParser):
466 def __init__(self, base):
467 _HTMLParser.__init__(self)
470 def start_a(self, attrs):
471 self.accumulator += '<a'
472 for attrname, value in attrs:
473 value = cgi.escape(value, True)
474 if attrname == 'href':
475 self.accumulator += ' href="%s"' % urljoin(self.base, value)
477 self.accumulator += ' %s="%s"' % (attrname, value)
478 self.accumulator += '>'
481 self.accumulator += '</a>'
483 def absolute_urls(body, base):
484 parser = AbsURLHTMLParser(base)
488 except HTMLParseError:
493 except HTMLParseError:
496 return parser.accumulator
499 from atom_10 import atom_10
500 from rss_20 import rss_20
501 from news import NewsItem
504 baseURL = "http://phdru.name/%s/" % blog_root
506 baseURL = "http://phdru.name/"
509 for item in tuple(reversed(all_titles_tags))[:10]:
510 year, month, day, file, title, lead, tags = item
511 url_path = "%s/%s/%s/%s" % (year, month, day, file)
513 "%s-%s-%s" % (year, month, day),
514 "%s%s" % (lead+' ' if lead else '', title),
517 item.baseURL = baseURL
518 item.categoryList = tags
519 body = bodies[(year, month, day, file)]
520 body = absolute_urls(body, baseURL + url_path)
522 item.excerpt = get_first_p(body)
525 "title": "Oleg Broytman's blog",
530 "author": "Oleg Broytman",
531 "email": "phd@phdru.name",
532 "generator": os.path.basename(sys.argv[0]),
537 locale.setlocale(locale.LC_TIME, 'C')
539 atom_tmpl = str(atom_10(searchList=[namespace]))
540 write_if_changed(os.path.join(blog_root, "atom_10.xml"), atom_tmpl)
541 rss_tmpl = str(rss_20(searchList=[namespace]))
542 write_if_changed(os.path.join(blog_root, "rss_20.xml"), rss_tmpl)
547 atom_tmpl = str(atom_10(searchList=[namespace]))
548 write_if_changed(os.path.join(blog_root, "atom_10_titles.xml"), atom_tmpl)
549 rss_tmpl = str(rss_20(searchList=[namespace]))
550 write_if_changed(os.path.join(blog_root, "rss_20_titles.xml"), rss_tmpl)
553 item.content = item.body
555 atom_tmpl = str(atom_10(searchList=[namespace]))
556 write_if_changed(os.path.join(blog_root, "atom_10_full.xml"), atom_tmpl)
557 rss_tmpl = str(rss_20(searchList=[namespace]))
558 write_if_changed(os.path.join(blog_root, "rss_20_full.xml"), rss_tmpl)