2 # -*- coding: koi8-r -*-
4 __author__ = "Oleg Broytman <phd@phdru.name>"
5 __copyright__ = "Copyright (C) 2006-2013 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.decode('utf-8').encode('koi8-r').split()
53 title = ' '.join(title_parts[6:])
54 lead = template.Lead.decode('utf-8').encode('koi8-r')
57 if isinstance(tags, basestring):
59 tags = [tag.decode('utf-8').encode('koi8-r') for tag in tags]
62 key = year, month, day = tuple(dirpath[len(blog_root):].split(os.sep)[1:])
67 days.append((file, title, lead, tags))
72 months = years[year] = {}
77 days = months[month] = []
79 if day not in days: days.append(day)
81 file = file[:-len("tmpl")] + "html"
82 key = (year, month, day, file)
83 body = template.body()
84 if isinstance(body, unicode):
85 body = body.encode('koi8-r')
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.
138 #attr $Title = "Oleg Broytman's blog"
139 #attr $Description = "Broytman Russian Blog Index Document"
140 #attr $Copyright = %(cyear)s
141 #attr $alternates = (("Новости [Atom 1.0] только заголовки", "application/atom+xml", "atom_10_titles.xml"),
142 ("Новости [Atom 1.0]", "application/atom+xml", "atom_10.xml"),
143 ("Новости [Atom 1.0] полные тексты", "application/atom+xml", "atom_10_full.xml"),
144 ("Новости [RSS 2.0] только заголовки", "application/rss+xml", "rss_20_titles.xml"),
145 ("Новости [RSS 2.0]", "application/rss+xml", "rss_20.xml"),
146 ("Новости [RSS 2.0] полные тексты", "application/rss+xml", "rss_20_full.xml"),
151 """ % {"cyear": year or 2005})
155 #attr $Title = "Oleg Broytman's blog: %(year)s"
156 #attr $Description = "Broytman Russian Blog %(year)s Index Document"
157 #attr $Copyright = %(cyear)s
160 <h1>Журнал: %(year)s</h1>
161 """ % {"year": year, "cyear": year or 2005})
166 #attr $Title = "Oleg Broytman's blog: %(month_abbr_en)s %(year)s"
167 #attr $Description = "Broytman Russian Blog %(month_name_en)s %(year)s Index Document"
168 #attr $Copyright = %(cyear)s
171 <h1>Журнал: %(month_name_ru0)s %(year)s</h1>
173 "year": year, "cyear": year or 2005,
174 "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
175 "month_name_ru0": months_names_ru0[imonth],
184 #attr $Refresh = "0; URL=%s"
188 #attr $Title = "Oleg Broytman's blog: %(day)d %(month_abbr_en)s %(year)s"
189 #attr $Description = "Broytman Russian Blog %(day)d %(month_name_en)s %(year)s Index Document"
190 #attr $Copyright = %(cyear)s
193 <h1>Журнал: %(day)d %(month_name_ru)s %(year)s</h1>
195 "year": year, "cyear": year or 2005,
196 "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
197 "month_name_ru": months_names_ru[imonth],
201 save_titles = titles[:]
205 for year, month, day, file, title, lead in titles:
214 href = '/'.join(href)
215 if day[0] == '0': day = day[1:]
216 if save_date <> (year, month, day):
218 new_text.append('\n<h2>%s %s %s</h2>' % (day, months_names_ru[int(month)], year))
220 new_text.append('\n<h2>%s %s</h2>' % (day, months_names_ru[int(month)]))
221 save_date = year, month, day
224 %s<a href="%s">%s</a>.
226 ''' % (lead+' ' if lead else '', href, title))
232 <p class="head">Новостевая лента в форматах
233 <img src="../../Graphics/atom_10.jpg" border=0>
234 <A HREF="atom_10_titles.xml">Atom 1.0 только заголовки</A> /
235 <A HREF="atom_10.xml">Atom 1.0</A> /
236 <A HREF="atom_10_full.xml">Atom 1.0 полные тексты</A>
237 и <img src="../../Graphics/rss_20.jpg" border=0>
238 <A HREF="rss_20_titles.xml">RSS 2.0 только заголовки</A> /
239 <A HREF="rss_20.xml">RSS 2.0</A> /
240 <A HREF="rss_20_full.xml">RSS 2.0 полные тексты</A>.
245 for year, month, day, file, title, lead in save_titles:
248 <p class="head"><a href="tags/">Теги</a>:
251 for count, tag, links in all_tags:
255 new_text.append(' - ')
256 new_text.append("""<a href="tags/%s.html">%s (%d)</a>""" % (tag, tag, count))
261 max_year = int(sorted(years.keys())[-1])
262 years = range(max_year, 2005, -1)
265 <p class="head">По годам:
269 for year, month, day, file, title, lead in all_titles:
270 year_counts[year] = 0
271 for year, month, day, file, title, lead in all_titles:
272 year_counts[year] += 1
279 new_text.append(' - ')
280 new_text.append('<a href="%s/">%s (%d)</a>' % (year, year, year_counts[str(year)]))
287 <p class="head"><a href="http://phd.livejournal.com/">ЖЖ</a>
292 $phd_site.respond(self)
295 write_if_changed(index_name, ''.join(new_text))
302 for year in sorted(years.keys()):
305 for month in sorted(months.keys()):
307 for day in sorted(months[month]):
309 key = year, month, day
311 for file, title, lead, tags in blog[key]:
312 if file.endswith(".tmpl"): file = file[:-len("tmpl")] + "html"
313 value = (year, month, day, file, title, lead)
314 all_titles_tags.append((year, month, day, file, title, lead, tags))
315 all_titles.append(value)
316 year_titles.append(value)
317 month_titles.append(value)
318 day_titles.append(value)
321 tag_links = all_tags[tag]
323 tag_links = all_tags[tag] = []
324 tag_links.append(value)
325 write_template(3, year, month, day, day_titles)
326 write_template(2, year, month, day, month_titles)
327 write_template(1, year, month, day, year_titles)
329 def by_count_rev_tag_link(t1, t2):
330 """Sort all_tags by count in descending order,
331 and by tags and links in ascending order
333 r = cmp(t1[0], t2[0])
336 return cmp((t1[1], t1[2]), (t2[1], t2[2]))
338 all_tags = [(len(links), tag, links) for (tag, links) in all_tags.items()]
339 all_tags.sort(by_count_rev_tag_link)
341 write_template(0, year, month, day, all_titles[-20:], all_tags)
344 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
348 #attr $Title = "Oleg Broytman's blog: tags"
349 #attr $Description = "Broytman Russian Blog Tags Index Document"
350 #attr $Copyright = 2006
359 for i, (count, tag, links) in enumerate(all_tags):
361 <dt><a href="%s.html">%s (%d)</a></dt>
362 """ % (tag, tag, count))
364 first = all_tags[0][1]
368 prev = all_tags[i-1][1]
369 if i >= len(all_tags)-1:
372 next = all_tags[i+1][1]
373 last = all_tags[-1][1]
376 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
380 #attr $Title = "Oleg Broytman's blog: tag %s"
381 #attr $Description = "Broytman Russian Blog Tag %s Index Document"
403 #attr $Copyright = 2006
413 for year, month, day, filename, title, lead in reversed(links):
414 link = "../%s/%s/%s/%s" % (year, month, day, filename)
415 item_text = """<li><a href="%s">%s/%s/%s: %s%s</a></li>""" % (link, year, month, day, lead+' ' if lead else '', title)
419 new_text.append(" <dd>%s</dd>\n" % item_text)
421 tag_text.append(" %s\n" % item_text)
427 $phd_site.respond(self)
429 write_if_changed(os.path.join(blog_root, "tags", tag+".tmpl"), ''.join(tag_text))
435 $phd_site.respond(self)
437 write_if_changed(os.path.join(blog_root, "tags", "index.tmpl"), ''.join(new_text))
440 from HTMLParser import HTMLParseError
442 from urlparse import urljoin
443 from m_lib.net.www.html import HTMLParser as _HTMLParser
445 class HTMLDone(Exception): pass
448 class FirstPHTMLParser(_HTMLParser):
450 _HTMLParser.__init__(self)
453 def start_p(self, attrs):
454 self.accumulator = '<p>'
457 self.first_p = self.accumulator + '</p>'
460 def get_first_p(body):
461 parser = FirstPHTMLParser()
465 except (HTMLParseError, HTMLDone):
470 except (HTMLParseError, HTMLDone):
473 return parser.first_p
476 class AbsURLHTMLParser(_HTMLParser):
477 def __init__(self, base):
478 _HTMLParser.__init__(self)
481 def start_a(self, attrs):
482 self.accumulator += '<a'
483 for attrname, value in attrs:
484 value = cgi.escape(value, True)
485 if attrname == 'href':
486 self.accumulator += ' href="%s"' % urljoin(self.base, value)
488 self.accumulator += ' %s="%s"' % (attrname, value)
489 self.accumulator += '>'
492 self.accumulator += '</a>'
494 def start_img(self, attrs):
495 self.accumulator += '<img'
496 for attrname, value in attrs:
497 value = cgi.escape(value, True)
498 if attrname == 'src':
499 self.accumulator += ' src="%s"' % urljoin(self.base, value)
501 self.accumulator += ' %s="%s"' % (attrname, value)
502 self.accumulator += '>'
507 def absolute_urls(body, base):
508 parser = AbsURLHTMLParser(base)
512 except HTMLParseError:
517 except HTMLParseError:
520 return parser.accumulator
523 from atom_10 import atom_10
524 from rss_20 import rss_20
525 from news import NewsItem
528 baseURL = "http://phdru.name/%s/" % blog_root
530 baseURL = "http://phdru.name/"
533 for item in tuple(reversed(all_titles_tags))[:10]:
534 year, month, day, file, title, lead, tags = item
535 lead = lead.decode('koi8-r').encode('utf-8')
536 title = title.decode('koi8-r').encode('utf-8')
537 url_path = "%s/%s/%s/%s" % (year, month, day, file)
539 "%s-%s-%s" % (year, month, day),
540 "%s%s" % (lead+' ' if lead else '', title),
543 item.baseURL = baseURL
544 item.categoryList = tags
545 body = bodies[(year, month, day, file)]
546 body = absolute_urls(body, baseURL + url_path)
547 body = body.decode('koi8-r').encode('utf-8')
549 item.excerpt = get_first_p(body)
552 "title": "Oleg Broytman's blog",
557 "author": "Oleg Broytman",
558 "email": "phd@phdru.name",
559 "generator": os.path.basename(sys.argv[0]),
564 locale.setlocale(locale.LC_TIME, 'C')
566 atom_tmpl = unicode(atom_10(searchList=[namespace])).encode('koi8-r')
567 write_if_changed(os.path.join(blog_root, "atom_10.xml"), atom_tmpl)
568 rss_tmpl = unicode(rss_20(searchList=[namespace])).encode('koi8-r')
569 write_if_changed(os.path.join(blog_root, "rss_20.xml"), rss_tmpl)
574 atom_tmpl = unicode(atom_10(searchList=[namespace])).encode('koi8-r')
575 write_if_changed(os.path.join(blog_root, "atom_10_titles.xml"), atom_tmpl)
576 rss_tmpl = unicode(rss_20(searchList=[namespace])).encode('koi8-r')
577 write_if_changed(os.path.join(blog_root, "rss_20_titles.xml"), rss_tmpl)
580 item.content = item.body
582 atom_tmpl = unicode(atom_10(searchList=[namespace])).encode('koi8-r')
583 write_if_changed(os.path.join(blog_root, "atom_10_full.xml"), atom_tmpl)
584 rss_tmpl = unicode(rss_20(searchList=[namespace])).encode('koi8-r')
585 write_if_changed(os.path.join(blog_root, "rss_20_full.xml"), rss_tmpl)