]> git.phdru.name Git - phdru.name/phdru.name.git/blob - reindex_blog.py
3370d6f892b7896aab65257b6b22cd4efc6658ae
[phdru.name/phdru.name.git] / reindex_blog.py
1 #! /usr/bin/env python3
2 # -*- coding: koi8-r -*-
3
4 __author__ = "Oleg Broytman <phd@phdru.name>"
5 __copyright__ = "Copyright (C) 2006-2024 PhiloSoft Design"
6
7 from calendar import _localized_month
8 from html import escape
9 import locale
10 import sys, os
11 from urllib.parse import quote, urljoin
12
13 from Cheetah.Template import Template
14 from Cheetah.compat import string_type
15 from m_lib.net.www.html import HTMLParser as _HTMLParser
16
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
21
22
23 old_blog = load_blog()
24
25 # blog is a dictionary mapping
26 # (year, month, day) => [list of (file, title, lead, tags)]
27
28 blog = {}
29 years = {}
30
31 # bodies is a dictionary mapping file => body
32
33 bodies = {}
34
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():
39         continue
40     for file in files:
41         if not file.endswith(".tmpl"):
42             continue
43         fullpath = os.path.join(dirpath, file)
44         template = Template(file=fullpath)
45         title_parts = template.Title.split()
46         title = ' '.join(title_parts[6:])
47         lead = template.Lead
48
49         tags = template.Tag
50         if isinstance(tags, string_type):
51             tags = (tags,)
52
53         if title:
54             key = year, month, day = \
55                 tuple(dirpath[len(blog_root):].split(os.sep)[1:])
56             if key in blog:
57                 days = blog[key]
58             else:
59                 days = blog[key] = []
60             days.append((file, title, lead, tags))
61
62             if year in years:
63                 months = years[year]
64             else:
65                 months = years[year] = {}
66
67             if month in months:
68                 days = months[month]
69             else:
70                 days = months[month] = []
71
72             if day not in days: days.append(day)
73
74             file = file[:-len("tmpl")] + "html"
75             key = (year, month, day, file)
76             body = template.body()
77             bodies[key] = body
78
79 # Need to save the blog?
80 if blog != old_blog:
81     save_blog(blog)
82
83 # Localized month names
84 locale.setlocale(locale.LC_ALL, "ru_RU.KOI8-R")
85
86 locale.setlocale(locale.LC_TIME, 'C')
87 months_names_en = list(_localized_month('%B'))
88 months_abbrs_en = list(_localized_month('%b'))
89
90 locale.setlocale(locale.LC_TIME, "ru_RU.KOI8-R")
91 # months_names_ru = list(_localized_month('%B'))
92
93 months_names_ru = [
94     '', "января", "февраля", "марта", "апреля", "мая", "июня",
95     "июля", "августа", "сентября", "октября", "ноября", "декабря"
96 ]
97
98 months_names_ru0 = [
99     '', "январь", "февраль", "март", "апрель", "май", "июнь",
100     "июль", "август", "сентябрь", "октябрь", "ноябрь", "декабрь"
101 ]
102
103
104 def encode_tag(tag):
105     return quote(tag.replace(' ', '_'), encoding='koi8-r')
106
107
108 def write_template(level, year, month, day, titles, tags=None):
109     path = [blog_root]
110     if level >= 1:
111         path.append(year)
112     if level >= 2:
113         path.append(month)
114     if level == 3:
115         path.append(day)
116     path.append("index.tmpl")
117     index_name = os.path.join(*path)
118
119     new_text = ["""\
120 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
121 #encoding koi8-r
122 #extends phd_site
123 #implements respond
124 """]
125
126     if level == 0:
127         new_text.append("""\
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"),
137 )
138 ##
139 #def body_html
140 <h1>Журнал</h1>
141 """ % {"cyear": year or 2005})
142
143     elif level == 1:
144         new_text.append("""\
145 #attr $Title = "Oleg Broytman's blog: %(year)s"
146 #attr $Description = "Broytman Russian Blog %(year)s Index Document"
147 #attr $Copyright = %(cyear)s
148 ##
149 #def body_html
150 <h1>Журнал: %(year)s</h1>
151 """ % {"year": year, "cyear": year or 2005})
152
153     elif level == 2:
154         imonth = int(month)
155         new_text.append("""\
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
159 ##
160 #def body_html
161 <h1>Журнал: %(month_name_ru0)s %(year)s</h1>
162 """ % {
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],
166         })
167
168     elif level == 3:
169         iday = int(day)
170         imonth = int(month)
171
172         if len(titles) == 1:
173             new_text.append("""\
174 #attr $Refresh = "0; URL=%s"
175 """ % titles[0][3])
176
177         new_text.append("""\
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
181 ##
182 #def body_html
183 <h1>Журнал: %(day)d %(month_name_ru)s %(year)s</h1>
184 """ % {
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],
188             "day": iday
189         })
190
191     save_titles = titles[:]
192     titles.reverse()
193
194     save_date = None
195     for year, month, day, file, title, lead in titles:
196         href = []
197         if level == 0:
198             href.append(year)
199         if level <= 1:
200             href.append(month)
201         if level <= 2:
202             href.append(day)
203         href.append(file)
204         href = '/'.join(href)
205         if day[0] == '0': day = day[1:]
206         if save_date != (year, month, day):
207             if level == 0:
208                 new_text.append('\n<h2>%s %s %s</h2>' % (day, months_names_ru[int(month)], year))
209             else:
210                 new_text.append('\n<h2>%s %s</h2>' % (day, months_names_ru[int(month)]))
211             save_date = year, month, day
212         new_text.append('''
213 <p class="head">
214     %s<a href="%s">%s</a>.
215 </p>
216 ''' % (lead+' ' if lead else '', href, title))
217
218     if level == 0:
219         new_text.append("""
220 <hr>
221
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>.
231 </p>
232 """)
233
234         years = {}
235         for year, month, day, file, title, lead in save_titles:
236             years[year] = True
237         new_text.append('''
238 <p class="head"><a href="tags/">Теги</a>:
239 ''')
240         first_tag = True
241         for count, tag, links in all_tags:
242             if first_tag:
243                 first_tag = False
244             else:
245                 new_text.append(' - ')
246             new_text.append("""<a href="tags/%s.html">%s (%d)</a>""" % (
247                  encode_tag(tag), tag, count))
248         new_text.append('''
249 </p>
250 ''')
251
252         max_year = int(sorted(years.keys())[-1])
253         years = range(max_year, 2005, -1)
254
255         new_text.append('''
256 <p class="head">По годам:
257 ''')
258
259         year_counts = {}
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
264
265         first_year = True
266         for year in years:
267             if first_year:
268                 first_year = False
269             else:
270                 new_text.append(' - ')
271             new_text.append('<a href="%s/">%s (%d)</a>' % (year, year, year_counts[str(year)]))
272         new_text.append('''
273 </p>
274 ''')
275
276         new_text.append("""
277 <hr>
278 <p class="head"><a href="http://phd.livejournal.com/">ЖЖ</a>
279 """)
280
281     new_text.append("""\
282 #end def
283 $phd_site.respond(self)
284 """)
285
286     write_if_changed(index_name, ''.join(new_text))
287
288
289 all_tags = {}
290 all_titles = []
291 all_titles_tags = []
292
293 for year in sorted(years.keys()):
294     year_titles = []
295     months = years[year]
296     for month in sorted(months.keys()):
297         month_titles = []
298         for day in sorted(months[month]):
299             day_titles = []
300             key = year, month, day
301             if key in blog:
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)
310                     for tag in tags:
311                         if tag in all_tags:
312                             tag_links = all_tags[tag]
313                         else:
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)
319
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
323     """
324     return tag[:3]
325
326 all_tags = [(len(links), tag, links) for (tag, links) in all_tags.items()]
327 all_tags.sort(key=by_count_rev_tag_link)
328
329 write_template(0, year, month, day, all_titles[-20:], all_tags)
330
331 new_text = ["""\
332 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
333 #encoding koi8-r
334 #extends phd_site
335 #implements respond
336 #attr $Title = "Oleg Broytman's blog: tags"
337 #attr $Description = "Broytman Russian Blog Tags Index Document"
338 #attr $Copyright = 2006
339 ##
340 #def body_html
341 <h1>Теги</h1>
342
343 <p class="head small">
344 Форма поиска позволяет искать сообщения в блоге, соответствующие выражению.
345 Синтаксис выражения:</p>
346 <ul class="small">
347      <li>Тег - если такой тег существует, произойдёт перенаправление на страницу тега.</li>
348      <li>Оператор '!' (NOT, not, НЕ, не) - ищет записи, в которых нет этого тега.</li>
349      <li>Оператор '&amp;' (AND, and, И, и) - ищет записи, в которых есть оба тега.</li>
350      <li>Оператор '|' (OR, or, ИЛИ, или) - ищет записи, в которых есть любые из тегов.</li>
351      <li>Приоритет операций стандартный: NOT &gt; AND &gt; OR. Скобки '()' позволяют объединять выражения.</li>
352      <li>Поиск игнорирует регистр: теги Linux и linux эквивалентны.</li>
353 </ul>
354 <p class="small">
355 Примеры выражений: linux - произойдёт перенаправление
356 на страницу Linux.html; linux&amp;!debian - искать записи в которых есть тег
357 Linux и нет тега Debian; Linux and not Debian - то же самое. Если в теге есть
358 пробел ("Мёртвое море", "Чёрное море") - его надо заменить на подчёркивание;
359 например: "Израиль И НЕ мёртвое_море", "Кавказ и не чёрное_море".
360 </p>
361
362 <center>
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="Искать">
366 </form>
367 </center>
368
369 <dl>
370 """]
371
372 for i, (count, tag, links) in enumerate(all_tags):
373     new_text.append("""\
374     <dt><a href="%s.html">%s (%d)</a></dt>
375 """ % (encode_tag(tag), tag, count))
376
377     first = all_tags[0][1]
378     if i == 0:
379         prev = None
380     else:
381         prev = all_tags[i-1][1]
382     if i >= len(all_tags)-1:
383         next = None
384     else:
385         next = all_tags[i+1][1]
386     last = all_tags[-1][1]
387
388     tag_text = ["""\
389 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
390 #encoding koi8-r
391 #extends phd_site
392 #implements respond
393 #attr $Title = "Oleg Broytman's blog: tag %s"
394 #attr $Description = "Broytman Russian Blog Tag %s Index Document"
395 """ % (tag, tag)]
396
397     tag_text.append("""\
398 #attr $First = "%s"
399 """ % first)
400
401     if prev:
402         tag_text.append("""\
403 #attr $Prev = "%s"
404 """ % prev)
405
406     if next:
407         tag_text.append("""\
408 #attr $Next = "%s"
409 """ % next)
410
411     tag_text.append("""\
412 #attr $Last = "%s"
413 """ % last)
414
415     tag_text.append("""\
416 #attr $Copyright = 2006
417 ##
418 #def body_html
419 <h1>%s</h1>
420
421 <ul>
422 """ % tag)
423
424     count = 0
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)
428
429         count += 1
430         if count <= 5:
431             new_text.append("         <dd>%s</dd>\n" % item_text)
432
433         tag_text.append("   %s\n" % item_text)
434
435     tag_text.append("""\
436 </ul>
437 #end def
438 $phd_site.respond(self)
439 """)
440     write_if_changed(os.path.join(blog_root, "tags",
441                                   tag.replace(' ', '_') + ".tmpl"),
442                      ''.join(tag_text))
443
444 new_text.append("""\
445 </dl>
446 #end def
447 $phd_site.respond(self)
448 """)
449 write_if_changed(os.path.join(blog_root, "tags", "index.tmpl"), ''.join(new_text))
450
451
452 class HTMLDone(Exception): pass
453
454
455 class FirstPHTMLParser(_HTMLParser):
456     def __init__(self):
457         _HTMLParser.__init__(self)
458         self.first_p = None
459
460     def start_p(self, attrs):
461         self.accumulator = '<p>'
462
463     def end_p(self):
464         self.first_p = self.accumulator + '</p>'
465         raise HTMLDone()
466
467 def get_first_p(body):
468     parser = FirstPHTMLParser()
469
470     try:
471         parser.feed(body)
472     except HTMLDone:
473         pass
474
475     try:
476         parser.close()
477     except HTMLDone:
478         pass
479
480     return parser.first_p
481
482
483 class AbsURLHTMLParser(_HTMLParser):
484     def __init__(self, base):
485         _HTMLParser.__init__(self)
486         self.base = base
487
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)
494             else:
495                 self.accumulator += ' %s="%s"' % (attrname, value)
496         self.accumulator += '>'
497
498     def end_a(self):
499         self.accumulator += '</a>'
500
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)
507             else:
508                 self.accumulator += ' %s="%s"' % (attrname, value)
509         self.accumulator += '>'
510
511     def end_img(self):
512         pass
513
514 def absolute_urls(body, base):
515     parser = AbsURLHTMLParser(base)
516
517     try:
518         parser.feed(body)
519     except Exception:
520         pass
521
522     try:
523         parser.close()
524     except Exception:
525         pass
526
527     return parser.accumulator
528
529
530 if blog_root:
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
534 else:
535     baseURL = "https://phdru.name/"
536
537 items = []
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)
541     item = NewsItem(
542         "%s-%s-%s" % (year, month, day),
543         "%s%s" % (lead+' ' if lead else '', title),
544         url_path)
545     items.append(item)
546     item.baseURL = baseURL
547     item.categoryList = tags
548     body = bodies[(year, month, day, file)]
549     body = absolute_urls(body, baseURL + url_path)
550     item.body = body
551     excerpt = get_first_p(body)
552     item.excerpt = excerpt
553
554 namespace = {
555     "title": "Oleg Broytman's blog",
556     "baseURL": baseURL,
557     "indexFile": "",
558     "description": "",
559     "lang": "ru",
560     "author": "Oleg Broytman",
561     "email": "phd@phdru.name",
562     "generator": os.path.basename(sys.argv[0]),
563     "posts": items,
564 }
565
566 # For english dates
567 locale.setlocale(locale.LC_TIME, 'C')
568
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))
573
574 for item in items:
575     item.excerpt = None
576
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))
581
582 for item in items:
583     item.content = item.body
584
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))
589
590 # vim: set ts=8 sts=4 sw=4 et :