2 # -*- coding: koi8-r -*-
4 __author__ = "Oleg Broytman <phd@phdru.name>"
5 __copyright__ = "Copyright (C) 2006-2024 PhiloSoft Design"
9 from urllib.parse import quote
11 from urllib import quote
13 from Cheetah.Template import Template
14 from Cheetah.compat import string_type
15 from blog_db import blog_root, load_blog, save_blog
18 old_blog = load_blog()
20 # blog is a dictionary mapping
21 # (year, month, day) => [list of (file, title, lead, tags)]
26 # bodies is a dictionary mapping file => body
30 # Walk the directory recursively
31 for dirpath, dirs, files in os.walk(blog_root):
32 d = os.path.basename(dirpath)
33 if not d.startswith("20") and not d.isdigit():
36 if not file.endswith(".tmpl"):
38 fullpath = os.path.join(dirpath, file)
39 template = Template(file=fullpath)
40 title_parts = template.Title.decode('utf-8').encode('koi8-r').split()
41 title = ' '.join(title_parts[6:])
42 lead = template.Lead.decode('utf-8').encode('koi8-r')
45 if isinstance(tags, string_type):
47 tags = [tag.decode('utf-8').encode('koi8-r') for tag in tags]
50 key = year, month, day = tuple(dirpath[len(blog_root):].split(os.sep)[1:])
55 days.append((file, title, lead, tags))
60 months = years[year] = {}
65 days = months[month] = []
67 if day not in days: days.append(day)
69 file = file[:-len("tmpl")] + "html"
70 key = (year, month, day, file)
71 body = template.body()
72 if isinstance(body, unicode):
73 body = body.encode('koi8-r')
76 # Need to save the blog?
80 # Localized month names
83 locale.setlocale(locale.LC_ALL, "ru_RU.KOI8-R")
84 from calendar import _localized_month
86 locale.setlocale(locale.LC_TIME, 'C')
87 months_names_en = list(_localized_month('%B'))
88 months_abbrs_en = list(_localized_month('%b'))
90 locale.setlocale(locale.LC_TIME, "ru_RU.KOI8-R")
91 # months_names_ru = list(_localized_month('%B'))
93 months_names_ru = ['', "января", "февраля", "марта", "апреля", "мая", "июня",
94 "июля", "августа", "сентября", "октября", "ноября", "декабря"
97 months_names_ru0 = ['', "январь", "февраль", "март", "апрель", "май", "июнь",
98 "июль", "август", "сентябрь", "октябрь", "ноябрь", "декабрь"
101 from news import write_if_changed
104 return quote(tag.replace(' ', '_'))
106 def write_template(level, year, month, day, titles, tags=None):
114 path.append("index.tmpl")
115 index_name = os.path.join(*path)
118 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
126 #attr $Title = "Oleg Broytman's blog"
127 #attr $Description = "Broytman Russian Blog Index Document"
128 #attr $Copyright = %(cyear)s
129 #attr $alternates = (("Новости [Atom 1.0] только заголовки", "application/atom+xml", "atom_10_titles.xml"),
130 ("Новости [Atom 1.0]", "application/atom+xml", "atom_10.xml"),
131 ("Новости [Atom 1.0] полные тексты", "application/atom+xml", "atom_10_full.xml"),
132 ("Новости [RSS 2.0] только заголовки", "application/rss+xml", "rss_20_titles.xml"),
133 ("Новости [RSS 2.0]", "application/rss+xml", "rss_20.xml"),
134 ("Новости [RSS 2.0] полные тексты", "application/rss+xml", "rss_20_full.xml"),
139 """ % {"cyear": year or 2005})
143 #attr $Title = "Oleg Broytman's blog: %(year)s"
144 #attr $Description = "Broytman Russian Blog %(year)s Index Document"
145 #attr $Copyright = %(cyear)s
148 <h1>Журнал: %(year)s</h1>
149 """ % {"year": year, "cyear": year or 2005})
154 #attr $Title = "Oleg Broytman's blog: %(month_abbr_en)s %(year)s"
155 #attr $Description = "Broytman Russian Blog %(month_name_en)s %(year)s Index Document"
156 #attr $Copyright = %(cyear)s
159 <h1>Журнал: %(month_name_ru0)s %(year)s</h1>
161 "year": year, "cyear": year or 2005,
162 "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
163 "month_name_ru0": months_names_ru0[imonth],
172 #attr $Refresh = "0; URL=%s"
176 #attr $Title = "Oleg Broytman's blog: %(day)d %(month_abbr_en)s %(year)s"
177 #attr $Description = "Broytman Russian Blog %(day)d %(month_name_en)s %(year)s Index Document"
178 #attr $Copyright = %(cyear)s
181 <h1>Журнал: %(day)d %(month_name_ru)s %(year)s</h1>
183 "year": year, "cyear": year or 2005,
184 "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
185 "month_name_ru": months_names_ru[imonth],
189 save_titles = titles[:]
193 for year, month, day, file, title, lead in titles:
202 href = '/'.join(href)
203 if day[0] == '0': day = day[1:]
204 if save_date != (year, month, day):
206 new_text.append('\n<h2>%s %s %s</h2>' % (day, months_names_ru[int(month)], year))
208 new_text.append('\n<h2>%s %s</h2>' % (day, months_names_ru[int(month)]))
209 save_date = year, month, day
212 %s<a href="%s">%s</a>.
214 ''' % (lead+' ' if lead else '', href, title))
220 <p class="head">Новостевая лента в форматах
221 <img src="../../Graphics/atom_10.jpg" border=0>
222 <A HREF="atom_10_titles.xml">Atom 1.0 только заголовки</A> /
223 <A HREF="atom_10.xml">Atom 1.0</A> /
224 <A HREF="atom_10_full.xml">Atom 1.0 полные тексты</A>
225 и <img src="../../Graphics/rss_20.jpg" border=0>
226 <A HREF="rss_20_titles.xml">RSS 2.0 только заголовки</A> /
227 <A HREF="rss_20.xml">RSS 2.0</A> /
228 <A HREF="rss_20_full.xml">RSS 2.0 полные тексты</A>.
233 for year, month, day, file, title, lead in save_titles:
236 <p class="head"><a href="tags/">Теги</a>:
239 for count, tag, links in all_tags:
243 new_text.append(' - ')
244 new_text.append("""<a href="tags/%s.html">%s (%d)</a>""" % (
245 encode_tag(tag), tag, count))
250 max_year = int(sorted(years.keys())[-1])
251 years = range(max_year, 2005, -1)
254 <p class="head">По годам:
258 for year, month, day, file, title, lead in all_titles:
259 year_counts[year] = 0
260 for year, month, day, file, title, lead in all_titles:
261 year_counts[year] += 1
268 new_text.append(' - ')
269 new_text.append('<a href="%s/">%s (%d)</a>' % (year, year, year_counts[str(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
344 <p class="head small">
345 Форма поиска позволяет искать сообщения в блоге, соответствующие выражению.
346 Синтаксис выражения:</p>
348 <li>Тег - если такой тег существует, произойдёт перенаправление на страницу тега.</li>
349 <li>Оператор '!' (NOT, not) - ищет записи, в которых нет этого тега.</li>
350 <li>Оператор '&' (AND, and) - ищет записи, в которых есть оба тега.</li>
351 <li>Оператор '|' (OR, or) - ищет записи, в которых есть любые из тегов.</li>
352 <li>Приоритет операций стандартный: NOT > AND > OR. Скобки '()' позволяют объединять выражения.</li>
355 Примеры выражений: linux - произойдёт перенаправление
356 на страницу linux.html; linux&!audio - искать записи в которых есть тег
357 linux и нет тега audio; linux and not audio - то же самое.
361 <form method=GET action="../../../cgi-bin/blog-ru/search-tags/search-tags.py">
362 <input type=text name=q>
363 <input type=submit name=submit value="Искать">
370 for i, (count, tag, links) in enumerate(all_tags):
372 <dt><a href="%s.html">%s (%d)</a></dt>
373 """ % (encode_tag(tag), tag, count))
375 first = all_tags[0][1]
379 prev = all_tags[i-1][1]
380 if i >= len(all_tags)-1:
383 next = all_tags[i+1][1]
384 last = all_tags[-1][1]
387 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
391 #attr $Title = "Oleg Broytman's blog: tag %s"
392 #attr $Description = "Broytman Russian Blog Tag %s Index Document"
414 #attr $Copyright = 2006
423 for year, month, day, filename, title, lead in reversed(links):
424 link = "../%s/%s/%s/%s" % (year, month, day, filename)
425 item_text = """<li><a href="%s">%s/%s/%s: %s%s</a></li>""" % (link, year, month, day, lead+' ' if lead else '', title)
429 new_text.append(" <dd>%s</dd>\n" % item_text)
431 tag_text.append(" %s\n" % item_text)
436 $phd_site.respond(self)
438 write_if_changed(os.path.join(blog_root, "tags",
439 tag.replace(' ', '_') + ".tmpl"),
445 $phd_site.respond(self)
447 write_if_changed(os.path.join(blog_root, "tags", "index.tmpl"), ''.join(new_text))
450 from HTMLParser import HTMLParseError
452 from urlparse import urljoin
453 from m_lib.net.www.html import HTMLParser as _HTMLParser
455 class HTMLDone(Exception): pass
458 class FirstPHTMLParser(_HTMLParser):
460 _HTMLParser.__init__(self)
463 def start_p(self, attrs):
464 self.accumulator = '<p>'
467 self.first_p = self.accumulator + '</p>'
470 def get_first_p(body):
471 parser = FirstPHTMLParser()
475 except (HTMLParseError, HTMLDone):
480 except (HTMLParseError, HTMLDone):
483 return parser.first_p
486 class AbsURLHTMLParser(_HTMLParser):
487 def __init__(self, base):
488 _HTMLParser.__init__(self)
491 def start_a(self, attrs):
492 self.accumulator += '<a'
493 for attrname, value in attrs:
494 value = cgi.escape(value, True)
495 if isinstance(value, unicode):
496 value = value.encode('koi8-r')
497 if attrname == 'href':
498 self.accumulator += ' href="%s"' % urljoin(self.base, value)
500 self.accumulator += ' %s="%s"' % (attrname, value)
501 self.accumulator += '>'
504 self.accumulator += '</a>'
506 def start_img(self, attrs):
507 self.accumulator += '<img'
508 for attrname, value in attrs:
509 value = cgi.escape(value, True)
510 if attrname == 'src':
511 self.accumulator += ' src="%s"' % urljoin(self.base, value)
513 self.accumulator += ' %s="%s"' % (attrname, value)
514 self.accumulator += '>'
519 def absolute_urls(body, base):
520 parser = AbsURLHTMLParser(base)
524 except HTMLParseError:
529 except HTMLParseError:
532 return parser.accumulator
535 from atom_10 import atom_10
536 from rss_20 import rss_20
537 from news import NewsItem
540 blog_root_url = blog_root[
541 blog_root.find('/htdocs/phdru.name/') + len('/htdocs/phdru.name/'):]
542 baseURL = "https://phdru.name/%s/" % blog_root_url
544 baseURL = "https://phdru.name/"
547 for item in tuple(reversed(all_titles_tags))[:10]:
548 year, month, day, file, title, lead, tags = item
549 lead = lead.decode('koi8-r').encode('utf-8')
550 title = title.decode('koi8-r').encode('utf-8')
551 url_path = "%s/%s/%s/%s" % (year, month, day, file)
553 "%s-%s-%s" % (year, month, day),
554 "%s%s" % (lead+' ' if lead else '', title),
557 item.baseURL = baseURL
558 item.categoryList = [t.decode('koi8-r').encode('utf-8') for t in tags]
559 body = bodies[(year, month, day, file)]
560 body = absolute_urls(body, baseURL + url_path)
563 except UnicodeDecodeError:
564 body = body.decode('koi8-r').encode('utf-8')
566 excerpt = get_first_p(body)
568 excerpt.decode('utf-8')
569 except UnicodeDecodeError:
570 excerpt = excerpt.decode('koi8-r').encode('utf-8')
571 item.excerpt = excerpt
574 "title": "Oleg Broytman's blog",
579 "author": "Oleg Broytman",
580 "email": "phd@phdru.name",
581 "generator": os.path.basename(sys.argv[0]),
586 locale.setlocale(locale.LC_TIME, 'C')
588 atom_tmpl = unicode(atom_10(searchList=[namespace])).encode('koi8-r')
589 write_if_changed(os.path.join(blog_root, "atom_10.xml"), atom_tmpl)
590 rss_tmpl = unicode(rss_20(searchList=[namespace])).encode('koi8-r')
591 write_if_changed(os.path.join(blog_root, "rss_20.xml"), rss_tmpl)
596 atom_tmpl = unicode(atom_10(searchList=[namespace])).encode('koi8-r')
597 write_if_changed(os.path.join(blog_root, "atom_10_titles.xml"), atom_tmpl)
598 rss_tmpl = unicode(rss_20(searchList=[namespace])).encode('koi8-r')
599 write_if_changed(os.path.join(blog_root, "rss_20_titles.xml"), rss_tmpl)
602 item.content = item.body
604 atom_tmpl = unicode(atom_10(searchList=[namespace])).encode('koi8-r')
605 write_if_changed(os.path.join(blog_root, "atom_10_full.xml"), atom_tmpl)
606 rss_tmpl = unicode(rss_20(searchList=[namespace])).encode('koi8-r')
607 write_if_changed(os.path.join(blog_root, "rss_20_full.xml"), rss_tmpl)