]> git.phdru.name Git - phdru.name/phdru.name.git/blob - reindex_blog.py
4a77fbf78e045611cf3f946bb04202cddefe9ba8
[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(' ', '_'))
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 </ul>
353 <p class="small">
354 Примеры выражений: Linux - произойдёт перенаправление
355 на страницу Linux.html; Linux&amp;!Debian - искать записи в которых есть тег
356 Linux и нет тега Debian; Linux and not Debian - то же самое.
357 </p>
358
359 <center>
360 <form method=GET action="../../../cgi-bin/blog-ru/search-tags.cgi">
361      <input type=text name=q>
362      <input type=submit name=submit value="Искать">
363 </form>
364 </center>
365
366 <dl>
367 """]
368
369 for i, (count, tag, links) in enumerate(all_tags):
370     new_text.append("""\
371     <dt><a href="%s.html">%s (%d)</a></dt>
372 """ % (encode_tag(tag), tag, count))
373
374     first = all_tags[0][1]
375     if i == 0:
376         prev = None
377     else:
378         prev = all_tags[i-1][1]
379     if i >= len(all_tags)-1:
380         next = None
381     else:
382         next = all_tags[i+1][1]
383     last = all_tags[-1][1]
384
385     tag_text = ["""\
386 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
387 #encoding koi8-r
388 #extends phd_site
389 #implements respond
390 #attr $Title = "Oleg Broytman's blog: tag %s"
391 #attr $Description = "Broytman Russian Blog Tag %s Index Document"
392 """ % (tag, tag)]
393
394     tag_text.append("""\
395 #attr $First = "%s"
396 """ % first)
397
398     if prev:
399         tag_text.append("""\
400 #attr $Prev = "%s"
401 """ % prev)
402
403     if next:
404         tag_text.append("""\
405 #attr $Next = "%s"
406 """ % next)
407
408     tag_text.append("""\
409 #attr $Last = "%s"
410 """ % last)
411
412     tag_text.append("""\
413 #attr $Copyright = 2006
414 ##
415 #def body_html
416 <h1>%s</h1>
417
418 <ul>
419 """ % tag)
420
421     count = 0
422     for year, month, day, filename, title, lead in reversed(links):
423         link = "../%s/%s/%s/%s" % (year, month, day, filename)
424         item_text = """<li><a href="%s">%s/%s/%s: %s%s</a></li>""" % (link, year, month, day, lead+' ' if lead else '', title)
425
426         count += 1
427         if count <= 5:
428             new_text.append("         <dd>%s</dd>\n" % item_text)
429
430         tag_text.append("   %s\n" % item_text)
431
432     tag_text.append("""\
433 </ul>
434 #end def
435 $phd_site.respond(self)
436 """)
437     write_if_changed(os.path.join(blog_root, "tags",
438                                   tag.replace(' ', '_') + ".tmpl"),
439                      ''.join(tag_text))
440
441 new_text.append("""\
442 </dl>
443 #end def
444 $phd_site.respond(self)
445 """)
446 write_if_changed(os.path.join(blog_root, "tags", "index.tmpl"), ''.join(new_text))
447
448
449 class HTMLDone(Exception): pass
450
451
452 class FirstPHTMLParser(_HTMLParser):
453     def __init__(self):
454         _HTMLParser.__init__(self)
455         self.first_p = None
456
457     def start_p(self, attrs):
458         self.accumulator = '<p>'
459
460     def end_p(self):
461         self.first_p = self.accumulator + '</p>'
462         raise HTMLDone()
463
464 def get_first_p(body):
465     parser = FirstPHTMLParser()
466
467     try:
468         parser.feed(body)
469     except HTMLDone:
470         pass
471
472     try:
473         parser.close()
474     except HTMLDone:
475         pass
476
477     return parser.first_p
478
479
480 class AbsURLHTMLParser(_HTMLParser):
481     def __init__(self, base):
482         _HTMLParser.__init__(self)
483         self.base = base
484
485     def start_a(self, attrs):
486         self.accumulator += '<a'
487         for attrname, value in attrs:
488             value = escape(value, True)
489             if attrname == 'href':
490                 self.accumulator += ' href="%s"' % urljoin(self.base, value)
491             else:
492                 self.accumulator += ' %s="%s"' % (attrname, value)
493         self.accumulator += '>'
494
495     def end_a(self):
496         self.accumulator += '</a>'
497
498     def start_img(self, attrs):
499         self.accumulator += '<img'
500         for attrname, value in attrs:
501             value = escape(value, True)
502             if attrname == 'src':
503                 self.accumulator += ' src="%s"' % urljoin(self.base, value)
504             else:
505                 self.accumulator += ' %s="%s"' % (attrname, value)
506         self.accumulator += '>'
507
508     def end_img(self):
509         pass
510
511 def absolute_urls(body, base):
512     parser = AbsURLHTMLParser(base)
513
514     try:
515         parser.feed(body)
516     except Exception:
517         pass
518
519     try:
520         parser.close()
521     except Exception:
522         pass
523
524     return parser.accumulator
525
526
527 if blog_root:
528     blog_root_url = blog_root[
529           blog_root.find('/htdocs/phdru.name/') + len('/htdocs/phdru.name/'):]
530     baseURL = "https://phdru.name/%s/" % blog_root_url
531 else:
532     baseURL = "https://phdru.name/"
533
534 items = []
535 for item in tuple(reversed(all_titles_tags))[:10]:
536     year, month, day, file, title, lead, tags = item
537     url_path = "%s/%s/%s/%s" % (year, month, day, file)
538     item = NewsItem(
539         "%s-%s-%s" % (year, month, day),
540         "%s%s" % (lead+' ' if lead else '', title),
541         url_path)
542     items.append(item)
543     item.baseURL = baseURL
544     item.categoryList = tags
545     body = bodies[(year, month, day, file)]
546     body = absolute_urls(body, baseURL + url_path)
547     item.body = body
548     excerpt = get_first_p(body)
549     item.excerpt = excerpt
550
551 namespace = {
552     "title": "Oleg Broytman's blog",
553     "baseURL": baseURL,
554     "indexFile": "",
555     "description": "",
556     "lang": "ru",
557     "author": "Oleg Broytman",
558     "email": "phd@phdru.name",
559     "generator": os.path.basename(sys.argv[0]),
560     "posts": items,
561 }
562
563 # For english dates
564 locale.setlocale(locale.LC_TIME, 'C')
565
566 atom_tmpl = atom_10(searchList=[namespace])
567 write_if_changed(os.path.join(blog_root, "atom_10.xml"), str(atom_tmpl))
568 rss_tmpl = rss_20(searchList=[namespace])
569 write_if_changed(os.path.join(blog_root, "rss_20.xml"), str(rss_tmpl))
570
571 for item in items:
572     item.excerpt = None
573
574 atom_tmpl = atom_10(searchList=[namespace])
575 write_if_changed(os.path.join(blog_root, "atom_10_titles.xml"), str(atom_tmpl))
576 rss_tmpl = rss_20(searchList=[namespace])
577 write_if_changed(os.path.join(blog_root, "rss_20_titles.xml"), str(rss_tmpl))
578
579 for item in items:
580     item.content = item.body
581
582 atom_tmpl = atom_10(searchList=[namespace])
583 write_if_changed(os.path.join(blog_root, "atom_10_full.xml"), str(atom_tmpl))
584 rss_tmpl = rss_20(searchList=[namespace])
585 write_if_changed(os.path.join(blog_root, "rss_20_full.xml"), str(rss_tmpl))
586
587 # vim: set ts=8 sts=4 sw=4 et :