1 #! /usr/bin/env python3
2 # -*- coding: koi8-r -*-
4 __author__ = "Oleg Broytman <phd@phdru.name>"
5 __copyright__ = "Copyright (C) 2006-2024 PhiloSoft Design"
7 from calendar import _localized_month
8 from html import escape
11 from urllib.parse import quote, urljoin
13 from Cheetah.Template import Template
14 from Cheetah.compat import string_type
15 from m_lib.net.www.html import HTMLParser as _HTMLParser
17 from atom_10 import atom_10
18 from blog_db import blog_root, load_blog, save_blog
19 from news import NewsItem, write_if_changed
20 from rss_20 import rss_20
23 old_blog = load_blog()
25 # blog is a dictionary mapping
26 # (year, month, day) => [list of (file, title, lead, tags)]
31 # bodies is a dictionary mapping file => body
35 # Walk the directory recursively
36 for dirpath, dirs, files in os.walk(blog_root):
37 d = os.path.basename(dirpath)
38 if not d.startswith("20") and not d.isdigit():
41 if not file.endswith(".tmpl"):
43 fullpath = os.path.join(dirpath, file)
44 template = Template(file=fullpath)
45 title_parts = template.Title.split()
46 title = ' '.join(title_parts[6:])
50 if isinstance(tags, string_type):
54 key = year, month, day = \
55 tuple(dirpath[len(blog_root):].split(os.sep)[1:])
60 days.append((file, title, lead, tags))
65 months = years[year] = {}
70 days = months[month] = []
72 if day not in days: days.append(day)
74 file = file[:-len("tmpl")] + "html"
75 key = (year, month, day, file)
76 body = template.body()
79 # Need to save the blog?
83 # Localized month names
84 locale.setlocale(locale.LC_ALL, "ru_RU.KOI8-R")
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'))
94 '', "января", "февраля", "марта", "апреля", "мая", "июня",
95 "июля", "августа", "сентября", "октября", "ноября", "декабря"
99 '', "январь", "февраль", "март", "апрель", "май", "июнь",
100 "июль", "август", "сентябрь", "октябрь", "ноябрь", "декабрь"
105 return quote(tag.replace(' ', '_'), encoding='koi8-r')
108 def write_template(level, year, month, day, titles, tags=None):
116 path.append("index.tmpl")
117 index_name = os.path.join(*path)
120 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
128 #attr $Title = "Oleg Broytman's blog"
129 #attr $Description = "Broytman Russian Blog Index Document"
130 #attr $Copyright = %(cyear)s
131 #attr $alternates = (("Новости [Atom 1.0] только заголовки", "application/atom+xml", "atom_10_titles.xml"),
132 ("Новости [Atom 1.0]", "application/atom+xml", "atom_10.xml"),
133 ("Новости [Atom 1.0] полные тексты", "application/atom+xml", "atom_10_full.xml"),
134 ("Новости [RSS 2.0] только заголовки", "application/rss+xml", "rss_20_titles.xml"),
135 ("Новости [RSS 2.0]", "application/rss+xml", "rss_20.xml"),
136 ("Новости [RSS 2.0] полные тексты", "application/rss+xml", "rss_20_full.xml"),
141 """ % {"cyear": year or 2005})
145 #attr $Title = "Oleg Broytman's blog: %(year)s"
146 #attr $Description = "Broytman Russian Blog %(year)s Index Document"
147 #attr $Copyright = %(cyear)s
150 <h1>Журнал: %(year)s</h1>
151 """ % {"year": year, "cyear": year or 2005})
156 #attr $Title = "Oleg Broytman's blog: %(month_abbr_en)s %(year)s"
157 #attr $Description = "Broytman Russian Blog %(month_name_en)s %(year)s Index Document"
158 #attr $Copyright = %(cyear)s
161 <h1>Журнал: %(month_name_ru0)s %(year)s</h1>
163 "year": year, "cyear": year or 2005,
164 "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
165 "month_name_ru0": months_names_ru0[imonth],
174 #attr $Refresh = "0; URL=%s"
178 #attr $Title = "Oleg Broytman's blog: %(day)d %(month_abbr_en)s %(year)s"
179 #attr $Description = "Broytman Russian Blog %(day)d %(month_name_en)s %(year)s Index Document"
180 #attr $Copyright = %(cyear)s
183 <h1>Журнал: %(day)d %(month_name_ru)s %(year)s</h1>
185 "year": year, "cyear": year or 2005,
186 "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
187 "month_name_ru": months_names_ru[imonth],
191 save_titles = titles[:]
195 for year, month, day, file, title, lead in titles:
204 href = '/'.join(href)
205 if day[0] == '0': day = day[1:]
206 if save_date != (year, month, day):
208 new_text.append('\n<h2>%s %s %s</h2>' % (day, months_names_ru[int(month)], year))
210 new_text.append('\n<h2>%s %s</h2>' % (day, months_names_ru[int(month)]))
211 save_date = year, month, day
214 %s<a href="%s">%s</a>.
216 ''' % (lead+' ' if lead else '', href, title))
222 <p class="head">Новостевая лента в форматах
223 <img src="../../Graphics/atom_10.jpg" border=0>
224 <A HREF="atom_10_titles.xml">Atom 1.0 только заголовки</A> /
225 <A HREF="atom_10.xml">Atom 1.0</A> /
226 <A HREF="atom_10_full.xml">Atom 1.0 полные тексты</A>
227 и <img src="../../Graphics/rss_20.jpg" border=0>
228 <A HREF="rss_20_titles.xml">RSS 2.0 только заголовки</A> /
229 <A HREF="rss_20.xml">RSS 2.0</A> /
230 <A HREF="rss_20_full.xml">RSS 2.0 полные тексты</A>.
235 for year, month, day, file, title, lead in save_titles:
238 <p class="head"><a href="tags/">Теги</a>:
241 for count, tag, links in all_tags:
245 new_text.append(' - ')
246 new_text.append("""<a href="tags/%s.html">%s (%d)</a>""" % (
247 encode_tag(tag), tag, count))
252 max_year = int(sorted(years.keys())[-1])
253 years = range(max_year, 2005, -1)
256 <p class="head">По годам:
260 for year, month, day, file, title, lead in all_titles:
261 year_counts[year] = 0
262 for year, month, day, file, title, lead in all_titles:
263 year_counts[year] += 1
270 new_text.append(' - ')
271 new_text.append('<a href="%s/">%s (%d)</a>' % (year, year, year_counts[str(year)]))
278 <p class="head"><a href="http://phd.livejournal.com/">ЖЖ</a>
283 $phd_site.respond(self)
286 write_if_changed(index_name, ''.join(new_text))
293 for year in sorted(years.keys()):
296 for month in sorted(months.keys()):
298 for day in sorted(months[month]):
300 key = year, month, day
302 for file, title, lead, tags in blog[key]:
303 if file.endswith(".tmpl"): file = file[:-len("tmpl")] + "html"
304 value = (year, month, day, file, title, lead)
305 all_titles_tags.append((year, month, day, file, title, lead, tags))
306 all_titles.append(value)
307 year_titles.append(value)
308 month_titles.append(value)
309 day_titles.append(value)
312 tag_links = all_tags[tag]
314 tag_links = all_tags[tag] = []
315 tag_links.append(value)
316 write_template(3, year, month, day, day_titles)
317 write_template(2, year, month, day, month_titles)
318 write_template(1, year, month, day, year_titles)
320 def by_count_rev_tag_link(tag):
321 """Sort all_tags by count in descending order,
322 and by tags and links in ascending order
326 all_tags = [(len(links), tag, links) for (tag, links) in all_tags.items()]
327 all_tags.sort(key=by_count_rev_tag_link)
329 write_template(0, year, month, day, all_titles[-20:], all_tags)
332 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
336 #attr $Title = "Oleg Broytman's blog: tags"
337 #attr $Description = "Broytman Russian Blog Tags Index Document"
338 #attr $Copyright = 2006
343 <p class="head small">
344 Форма поиска позволяет искать сообщения в блоге, соответствующие выражению.
345 Синтаксис выражения:</p>
347 <li>Тег - если такой тег существует, произойдёт перенаправление на страницу тега.</li>
348 <li>Оператор '!' (NOT, not, НЕ, не) - ищет записи, в которых нет этого тега.</li>
349 <li>Оператор '&' (AND, and, И, и) - ищет записи, в которых есть оба тега.</li>
350 <li>Оператор '|' (OR, or, ИЛИ, или) - ищет записи, в которых есть любые из тегов.</li>
351 <li>Приоритет операций стандартный: NOT > AND > OR. Скобки '()' позволяют объединять выражения.</li>
352 <li>Поиск игнорирует регистр: теги Linux и linux эквивалентны.</li>
355 Примеры выражений: linux - произойдёт перенаправление
356 на страницу Linux.html; linux&!debian - искать записи в которых есть тег
357 Linux и нет тега Debian; Linux and not Debian - то же самое. Если в теге есть
358 пробел ("Мёртвое море", "Чёрное море") - его надо заменить на подчёркивание;
359 например: "Израиль И НЕ мёртвое_море", "Кавказ и не чёрное_море".
363 <form method=GET action="../../../cgi-bin/blog-ru/search-tags.cgi">
364 <input type=text name=q>
365 <input type=submit name=submit value="Искать">
372 for i, (count, tag, links) in enumerate(all_tags):
374 <dt><a href="%s.html">%s (%d)</a></dt>
375 """ % (encode_tag(tag), tag, count))
377 first = all_tags[0][1]
381 prev = all_tags[i-1][1]
382 if i >= len(all_tags)-1:
385 next = all_tags[i+1][1]
386 last = all_tags[-1][1]
389 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
393 #attr $Title = "Oleg Broytman's blog: tag %s"
394 #attr $Description = "Broytman Russian Blog Tag %s Index Document"
416 #attr $Copyright = 2006
425 for year, month, day, filename, title, lead in reversed(links):
426 link = "../%s/%s/%s/%s" % (year, month, day, filename)
427 item_text = """<li><a href="%s">%s/%s/%s: %s%s</a></li>""" % (link, year, month, day, lead+' ' if lead else '', title)
431 new_text.append(" <dd>%s</dd>\n" % item_text)
433 tag_text.append(" %s\n" % item_text)
438 $phd_site.respond(self)
440 write_if_changed(os.path.join(blog_root, "tags",
441 tag.replace(' ', '_') + ".tmpl"),
447 $phd_site.respond(self)
449 write_if_changed(os.path.join(blog_root, "tags", "index.tmpl"), ''.join(new_text))
452 class HTMLDone(Exception): pass
455 class FirstPHTMLParser(_HTMLParser):
457 _HTMLParser.__init__(self)
460 def start_p(self, attrs):
461 self.accumulator = '<p>'
464 self.first_p = self.accumulator + '</p>'
467 def get_first_p(body):
468 parser = FirstPHTMLParser()
480 return parser.first_p
483 class AbsURLHTMLParser(_HTMLParser):
484 def __init__(self, base):
485 _HTMLParser.__init__(self)
488 def start_a(self, attrs):
489 self.accumulator += '<a'
490 for attrname, value in attrs:
491 value = escape(value, True)
492 if attrname == 'href':
493 self.accumulator += ' href="%s"' % urljoin(self.base, value)
495 self.accumulator += ' %s="%s"' % (attrname, value)
496 self.accumulator += '>'
499 self.accumulator += '</a>'
501 def start_img(self, attrs):
502 self.accumulator += '<img'
503 for attrname, value in attrs:
504 value = escape(value, True)
505 if attrname == 'src':
506 self.accumulator += ' src="%s"' % urljoin(self.base, value)
508 self.accumulator += ' %s="%s"' % (attrname, value)
509 self.accumulator += '>'
514 def absolute_urls(body, base):
515 parser = AbsURLHTMLParser(base)
527 return parser.accumulator
531 blog_root_url = blog_root[
532 blog_root.find('/htdocs/phdru.name/') + len('/htdocs/phdru.name/'):]
533 baseURL = "https://phdru.name/%s/" % blog_root_url
535 baseURL = "https://phdru.name/"
538 for item in tuple(reversed(all_titles_tags))[:10]:
539 year, month, day, file, title, lead, tags = item
540 url_path = "%s/%s/%s/%s" % (year, month, day, file)
542 "%s-%s-%s" % (year, month, day),
543 "%s%s" % (lead+' ' if lead else '', title),
546 item.baseURL = baseURL
547 item.categoryList = tags
548 body = bodies[(year, month, day, file)]
549 body = absolute_urls(body, baseURL + url_path)
551 excerpt = get_first_p(body)
552 item.excerpt = excerpt
555 "title": "Oleg Broytman's blog",
560 "author": "Oleg Broytman",
561 "email": "phd@phdru.name",
562 "generator": os.path.basename(sys.argv[0]),
567 locale.setlocale(locale.LC_TIME, 'C')
569 atom_tmpl = atom_10(searchList=[namespace])
570 write_if_changed(os.path.join(blog_root, "atom_10.xml"), str(atom_tmpl))
571 rss_tmpl = rss_20(searchList=[namespace])
572 write_if_changed(os.path.join(blog_root, "rss_20.xml"), str(rss_tmpl))
577 atom_tmpl = atom_10(searchList=[namespace])
578 write_if_changed(os.path.join(blog_root, "atom_10_titles.xml"), str(atom_tmpl))
579 rss_tmpl = rss_20(searchList=[namespace])
580 write_if_changed(os.path.join(blog_root, "rss_20_titles.xml"), str(rss_tmpl))
583 item.content = item.body
585 atom_tmpl = atom_10(searchList=[namespace])
586 write_if_changed(os.path.join(blog_root, "atom_10_full.xml"), str(atom_tmpl))
587 rss_tmpl = rss_20(searchList=[namespace])
588 write_if_changed(os.path.join(blog_root, "rss_20_full.xml"), str(rss_tmpl))
590 # vim: set ts=8 sts=4 sw=4 et :