2 # -*- coding: koi8-r -*-
4 __author__ = "Oleg Broytman <phd@phdru.name>"
5 __copyright__ = "Copyright (C) 2006-2021 PhiloSoft Design"
8 from Cheetah.Template import Template
9 from Cheetah.compat import string_type
10 from blog_db import blog_root, load_blog, save_blog
13 old_blog = load_blog()
15 # blog is a dictionary mapping
16 # (year, month, day) => [list of (file, title, lead, tags)]
21 # bodies is a dictionary mapping file => body
25 # Walk the directory recursively
26 for dirpath, dirs, files in os.walk(blog_root):
27 d = os.path.basename(dirpath)
28 if not d.startswith("20") and not d.isdigit():
31 if not file.endswith(".tmpl"):
33 fullpath = os.path.join(dirpath, file)
34 template = Template(file=fullpath)
35 title_parts = template.Title.decode('utf-8').encode('koi8-r').split()
36 title = ' '.join(title_parts[6:])
37 lead = template.Lead.decode('utf-8').encode('koi8-r')
40 if isinstance(tags, string_type):
42 tags = [tag.decode('utf-8').encode('koi8-r') for tag in tags]
45 key = year, month, day = tuple(dirpath[len(blog_root):].split(os.sep)[1:])
50 days.append((file, title, lead, tags))
55 months = years[year] = {}
60 days = months[month] = []
62 if day not in days: days.append(day)
64 file = file[:-len("tmpl")] + "html"
65 key = (year, month, day, file)
66 body = template.body()
67 if isinstance(body, unicode):
68 body = body.encode('koi8-r')
71 # Need to save the blog?
75 # Localized month names
78 locale.setlocale(locale.LC_ALL, "ru_RU.KOI8-R")
79 from calendar import _localized_month
81 locale.setlocale(locale.LC_TIME, 'C')
82 months_names_en = list(_localized_month('%B'))
83 months_abbrs_en = list(_localized_month('%b'))
85 locale.setlocale(locale.LC_TIME, "ru_RU.KOI8-R")
86 # months_names_ru = list(_localized_month('%B'))
88 months_names_ru = ['', "января", "февраля", "марта", "апреля", "мая", "июня",
89 "июля", "августа", "сентября", "октября", "ноября", "декабря"
92 months_names_ru0 = ['', "январь", "февраль", "март", "апрель", "май", "июнь",
93 "июль", "август", "сентябрь", "октябрь", "ноябрь", "декабрь"
96 from news import write_if_changed
99 def write_template(level, year, month, day, titles, tags=None):
107 path.append("index.tmpl")
108 index_name = os.path.join(*path)
111 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
119 #attr $Title = "Oleg Broytman's blog"
120 #attr $Description = "Broytman Russian Blog Index Document"
121 #attr $Copyright = %(cyear)s
122 #attr $alternates = (("Новости [Atom 1.0] только заголовки", "application/atom+xml", "atom_10_titles.xml"),
123 ("Новости [Atom 1.0]", "application/atom+xml", "atom_10.xml"),
124 ("Новости [Atom 1.0] полные тексты", "application/atom+xml", "atom_10_full.xml"),
125 ("Новости [RSS 2.0] только заголовки", "application/rss+xml", "rss_20_titles.xml"),
126 ("Новости [RSS 2.0]", "application/rss+xml", "rss_20.xml"),
127 ("Новости [RSS 2.0] полные тексты", "application/rss+xml", "rss_20_full.xml"),
132 """ % {"cyear": year or 2005})
136 #attr $Title = "Oleg Broytman's blog: %(year)s"
137 #attr $Description = "Broytman Russian Blog %(year)s Index Document"
138 #attr $Copyright = %(cyear)s
141 <h1>Журнал: %(year)s</h1>
142 """ % {"year": year, "cyear": year or 2005})
147 #attr $Title = "Oleg Broytman's blog: %(month_abbr_en)s %(year)s"
148 #attr $Description = "Broytman Russian Blog %(month_name_en)s %(year)s Index Document"
149 #attr $Copyright = %(cyear)s
152 <h1>Журнал: %(month_name_ru0)s %(year)s</h1>
154 "year": year, "cyear": year or 2005,
155 "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
156 "month_name_ru0": months_names_ru0[imonth],
165 #attr $Refresh = "0; URL=%s"
169 #attr $Title = "Oleg Broytman's blog: %(day)d %(month_abbr_en)s %(year)s"
170 #attr $Description = "Broytman Russian Blog %(day)d %(month_name_en)s %(year)s Index Document"
171 #attr $Copyright = %(cyear)s
174 <h1>Журнал: %(day)d %(month_name_ru)s %(year)s</h1>
176 "year": year, "cyear": year or 2005,
177 "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
178 "month_name_ru": months_names_ru[imonth],
182 save_titles = titles[:]
186 for year, month, day, file, title, lead in titles:
195 href = '/'.join(href)
196 if day[0] == '0': day = day[1:]
197 if save_date != (year, month, day):
199 new_text.append('\n<h2>%s %s %s</h2>' % (day, months_names_ru[int(month)], year))
201 new_text.append('\n<h2>%s %s</h2>' % (day, months_names_ru[int(month)]))
202 save_date = year, month, day
205 %s<a href="%s">%s</a>.
207 ''' % (lead+' ' if lead else '', href, title))
213 <p class="head">Новостевая лента в форматах
214 <img src="../../Graphics/atom_10.jpg" border=0>
215 <A HREF="atom_10_titles.xml">Atom 1.0 только заголовки</A> /
216 <A HREF="atom_10.xml">Atom 1.0</A> /
217 <A HREF="atom_10_full.xml">Atom 1.0 полные тексты</A>
218 и <img src="../../Graphics/rss_20.jpg" border=0>
219 <A HREF="rss_20_titles.xml">RSS 2.0 только заголовки</A> /
220 <A HREF="rss_20.xml">RSS 2.0</A> /
221 <A HREF="rss_20_full.xml">RSS 2.0 полные тексты</A>.
226 for year, month, day, file, title, lead in save_titles:
229 <p class="head"><a href="tags/">Теги</a>:
232 for count, tag, links in all_tags:
236 new_text.append(' - ')
237 new_text.append("""<a href="tags/%s.html">%s (%d)</a>""" % (tag, tag, count))
242 max_year = int(sorted(years.keys())[-1])
243 years = range(max_year, 2005, -1)
246 <p class="head">По годам:
250 for year, month, day, file, title, lead in all_titles:
251 year_counts[year] = 0
252 for year, month, day, file, title, lead in all_titles:
253 year_counts[year] += 1
260 new_text.append(' - ')
261 new_text.append('<a href="%s/">%s (%d)</a>' % (year, year, year_counts[str(year)]))
268 <p class="head"><a href="http://phd.livejournal.com/">ЖЖ</a>
273 $phd_site.respond(self)
276 write_if_changed(index_name, ''.join(new_text))
283 for year in sorted(years.keys()):
286 for month in sorted(months.keys()):
288 for day in sorted(months[month]):
290 key = year, month, day
292 for file, title, lead, tags in blog[key]:
293 if file.endswith(".tmpl"): file = file[:-len("tmpl")] + "html"
294 value = (year, month, day, file, title, lead)
295 all_titles_tags.append((year, month, day, file, title, lead, tags))
296 all_titles.append(value)
297 year_titles.append(value)
298 month_titles.append(value)
299 day_titles.append(value)
302 tag_links = all_tags[tag]
304 tag_links = all_tags[tag] = []
305 tag_links.append(value)
306 write_template(3, year, month, day, day_titles)
307 write_template(2, year, month, day, month_titles)
308 write_template(1, year, month, day, year_titles)
310 def by_count_rev_tag_link(t1, t2):
311 """Sort all_tags by count in descending order,
312 and by tags and links in ascending order
314 r = cmp(t1[0], t2[0])
317 return cmp((t1[1], t1[2]), (t2[1], t2[2]))
319 all_tags = [(len(links), tag, links) for (tag, links) in all_tags.items()]
320 all_tags.sort(by_count_rev_tag_link)
322 write_template(0, year, month, day, all_titles[-20:], all_tags)
325 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
329 #attr $Title = "Oleg Broytman's blog: tags"
330 #attr $Description = "Broytman Russian Blog Tags Index Document"
331 #attr $Copyright = 2006
336 <p class="head small">
337 Форма поиска позволяет искать сообщения в блоге, соответствующие выражению.
338 Синтаксис выражения:</p>
340 <li>Тег - если такой тег существует, произойдёт перенаправление на страницу тега.</li>
341 <li>Оператор '!' (NOT, not) - ищет записи, в которых нет этого тега.</li>
342 <li>Оператор '&' (AND, and) - ищет записи, в которых есть оба тега.</li>
343 <li>Оператор '|' (OR, or) - ищет записи, в которых есть любые из тегов.</li>
344 <li>Приоритет операций стандартный: NOT > AND > OR. Скобки '()' позволяют объединять выражения.</li>
347 Примеры выражений: linux - произойдёт перенаправление
348 на страницу linux.html; linux&!audio - искать записи в которых есть тег
349 linux и нет тега audio; linux and not audio - то же самое.
353 <form method=GET action="../../../cgi-bin/blog-ru/search-tags/search-tags.py">
354 <input type=text name=q>
355 <input type=submit name=submit value="Искать">
362 for i, (count, tag, links) in enumerate(all_tags):
364 <dt><a href="%s.html">%s (%d)</a></dt>
365 """ % (tag, tag, count))
367 first = all_tags[0][1]
371 prev = all_tags[i-1][1]
372 if i >= len(all_tags)-1:
375 next = all_tags[i+1][1]
376 last = all_tags[-1][1]
379 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
383 #attr $Title = "Oleg Broytman's blog: tag %s"
384 #attr $Description = "Broytman Russian Blog Tag %s Index Document"
406 #attr $Copyright = 2006
415 for year, month, day, filename, title, lead in reversed(links):
416 link = "../%s/%s/%s/%s" % (year, month, day, filename)
417 item_text = """<li><a href="%s">%s/%s/%s: %s%s</a></li>""" % (link, year, month, day, lead+' ' if lead else '', title)
421 new_text.append(" <dd>%s</dd>\n" % item_text)
423 tag_text.append(" %s\n" % item_text)
428 $phd_site.respond(self)
430 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 isinstance(value, unicode):
486 value = value.encode('koi8-r')
487 if attrname == 'href':
488 self.accumulator += ' href="%s"' % urljoin(self.base, value)
490 self.accumulator += ' %s="%s"' % (attrname, value)
491 self.accumulator += '>'
494 self.accumulator += '</a>'
496 def start_img(self, attrs):
497 self.accumulator += '<img'
498 for attrname, value in attrs:
499 value = cgi.escape(value, True)
500 if attrname == 'src':
501 self.accumulator += ' src="%s"' % urljoin(self.base, value)
503 self.accumulator += ' %s="%s"' % (attrname, value)
504 self.accumulator += '>'
509 def absolute_urls(body, base):
510 parser = AbsURLHTMLParser(base)
514 except HTMLParseError:
519 except HTMLParseError:
522 return parser.accumulator
525 from atom_10 import atom_10
526 from rss_20 import rss_20
527 from news import NewsItem
530 blog_root_url = blog_root[
531 blog_root.find('/htdocs/phdru.name/') + len('/htdocs/phdru.name/'):]
532 baseURL = "https://phdru.name/%s/" % blog_root_url
534 baseURL = "https://phdru.name/"
537 for item in tuple(reversed(all_titles_tags))[:10]:
538 year, month, day, file, title, lead, tags = item
539 lead = lead.decode('koi8-r').encode('utf-8')
540 title = title.decode('koi8-r').encode('utf-8')
541 url_path = "%s/%s/%s/%s" % (year, month, day, file)
543 "%s-%s-%s" % (year, month, day),
544 "%s%s" % (lead+' ' if lead else '', title),
547 item.baseURL = baseURL
548 item.categoryList = tags
549 body = bodies[(year, month, day, file)]
550 body = absolute_urls(body, baseURL + url_path)
553 except UnicodeDecodeError:
554 body = body.decode('koi8-r').encode('utf-8')
556 excerpt = get_first_p(body)
558 excerpt.decode('utf-8')
559 except UnicodeDecodeError:
560 excerpt = excerpt.decode('koi8-r').encode('utf-8')
561 item.excerpt = excerpt
564 "title": "Oleg Broytman's blog",
569 "author": "Oleg Broytman",
570 "email": "phd@phdru.name",
571 "generator": os.path.basename(sys.argv[0]),
576 locale.setlocale(locale.LC_TIME, 'C')
578 atom_tmpl = unicode(atom_10(searchList=[namespace])).encode('koi8-r')
579 write_if_changed(os.path.join(blog_root, "atom_10.xml"), atom_tmpl)
580 rss_tmpl = unicode(rss_20(searchList=[namespace])).encode('koi8-r')
581 write_if_changed(os.path.join(blog_root, "rss_20.xml"), rss_tmpl)
586 atom_tmpl = unicode(atom_10(searchList=[namespace])).encode('koi8-r')
587 write_if_changed(os.path.join(blog_root, "atom_10_titles.xml"), atom_tmpl)
588 rss_tmpl = unicode(rss_20(searchList=[namespace])).encode('koi8-r')
589 write_if_changed(os.path.join(blog_root, "rss_20_titles.xml"), rss_tmpl)
592 item.content = item.body
594 atom_tmpl = unicode(atom_10(searchList=[namespace])).encode('koi8-r')
595 write_if_changed(os.path.join(blog_root, "atom_10_full.xml"), atom_tmpl)
596 rss_tmpl = unicode(rss_20(searchList=[namespace])).encode('koi8-r')
597 write_if_changed(os.path.join(blog_root, "rss_20_full.xml"), rss_tmpl)