]> git.phdru.name Git - phdru.name/phdru.name.git/blob - reindex_blog.py
Feat(reindex_blog): Add href to DW
[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="https://phd-ru.dreamwidth.org/">DW</a> /
279 <a href="http://phd.livejournal.com/">��</a></p>
280 """)
281
282     new_text.append("""\
283 #end def
284 $phd_site.respond(self)
285 """)
286
287     write_if_changed(index_name, ''.join(new_text))
288
289
290 all_tags = {}
291 all_titles = []
292 all_titles_tags = []
293
294 for year in sorted(years.keys()):
295     year_titles = []
296     months = years[year]
297     for month in sorted(months.keys()):
298         month_titles = []
299         for day in sorted(months[month]):
300             day_titles = []
301             key = year, month, day
302             if key in blog:
303                 for file, title, lead, tags in blog[key]:
304                     if file.endswith(".tmpl"): file = file[:-len("tmpl")] + "html"
305                     value = (year, month, day, file, title, lead)
306                     all_titles_tags.append((year, month, day, file, title, lead, tags))
307                     all_titles.append(value)
308                     year_titles.append(value)
309                     month_titles.append(value)
310                     day_titles.append(value)
311                     for tag in tags:
312                         if tag in all_tags:
313                             tag_links = all_tags[tag]
314                         else:
315                             tag_links = all_tags[tag] = []
316                         tag_links.append(value)
317             write_template(3, year, month, day, day_titles)
318         write_template(2, year, month, day, month_titles)
319     write_template(1, year, month, day, year_titles)
320
321 def by_count_rev_tag_link(tag):
322     """Sort all_tags by count in descending order,
323     and by tags and links in ascending order
324     """
325     return -tag[0], tag[1], tag[2]
326
327 all_tags = [(len(links), tag, links) for (tag, links) in all_tags.items()]
328 all_tags.sort(key=by_count_rev_tag_link)
329
330 write_template(0, year, month, day, all_titles[-20:], all_tags)
331
332 new_text = ["""\
333 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
334 #encoding koi8-r
335 #extends phd_site
336 #implements respond
337 #attr $Title = "Oleg Broytman's blog: tags"
338 #attr $Description = "Broytman Russian Blog Tags Index Document"
339 #attr $Copyright = 2006
340 ##
341 #def body_html
342 <h1>����</h1>
343
344 <p class="head small">
345 ����� ������ ��������� ������ ��������� � �����, ��������������� ���������.
346 ��������� ���������:</p>
347 <ul class="small">
348      <li>��� - ���� ����� ��� ����������, �������ģ� ��������������� �� �������� ����.</li>
349      <li>�������� '!' (NOT, not, ��, ��) - ���� ������, � ������� ��� ����� ����.</li>
350      <li>�������� '&amp;' (AND, and, �, �) - ���� ������, � ������� ���� ��� ����.</li>
351      <li>�������� '|' (OR, or, ���, ���) - ���� ������, � ������� ���� ����� �� �����.</li>
352      <li>��������� �������� �����������: NOT &gt; AND &gt; OR. ������ '()' ��������� ���������� ���������.</li>
353      <li>����� ���������� �������: ���� Linux � linux ������������.</li>
354 </ul>
355 <p class="small">
356 ������� ���������: linux - �������ģ� ���������������
357 �� �������� Linux.html; linux&amp;!debian - ������ ������ � ������� ���� ���
358 Linux � ��� ���� Debian; Linux and not Debian - �� �� �����. ���� � ���� ����
359 ������ ("������ ����", "����� ����") - ��� ���� �������� �� ���ޣ��������;
360 ��������: "������� � �� ͣ�����_����", "������ � �� ޣ����_����".
361 </p>
362
363 <center>
364 <form method=GET action="../../../cgi-bin/blog-ru/search-tags.cgi">
365      <input type=text name=q>
366      <input type=submit name=submit value="������">
367 </form>
368 </center>
369
370 <dl>
371 """]
372
373 for i, (count, tag, links) in enumerate(all_tags):
374     new_text.append("""\
375     <dt><a href="%s.html">%s (%d)</a></dt>
376 """ % (encode_tag(tag), tag, count))
377
378     first = all_tags[0][1]
379     if i == 0:
380         prev = None
381     else:
382         prev = all_tags[i-1][1]
383     if i >= len(all_tags)-1:
384         next = None
385     else:
386         next = all_tags[i+1][1]
387     last = all_tags[-1][1]
388
389     tag_text = ["""\
390 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
391 #encoding koi8-r
392 #extends phd_site
393 #implements respond
394 #attr $Title = "Oleg Broytman's blog: tag %s"
395 #attr $Description = "Broytman Russian Blog Tag %s Index Document"
396 """ % (tag, tag)]
397
398     tag_text.append("""\
399 #attr $First = "%s"
400 """ % first)
401
402     if prev:
403         tag_text.append("""\
404 #attr $Prev = "%s"
405 """ % prev)
406
407     if next:
408         tag_text.append("""\
409 #attr $Next = "%s"
410 """ % next)
411
412     tag_text.append("""\
413 #attr $Last = "%s"
414 """ % last)
415
416     tag_text.append("""\
417 #attr $Copyright = 2006
418 ##
419 #def body_html
420 <h1>%s</h1>
421
422 <ul>
423 """ % tag)
424
425     count = 0
426     for year, month, day, filename, title, lead in reversed(links):
427         link = "../%s/%s/%s/%s" % (year, month, day, filename)
428         item_text = """<li><a href="%s">%s/%s/%s: %s%s</a></li>""" % (link, year, month, day, lead+' ' if lead else '', title)
429
430         count += 1
431         if count <= 5:
432             new_text.append("         <dd>%s</dd>\n" % item_text)
433
434         tag_text.append("   %s\n" % item_text)
435
436     tag_text.append("""\
437 </ul>
438 #end def
439 $phd_site.respond(self)
440 """)
441     write_if_changed(os.path.join(blog_root, "tags",
442                                   tag.replace(' ', '_') + ".tmpl"),
443                      ''.join(tag_text))
444
445 new_text.append("""\
446 </dl>
447 #end def
448 $phd_site.respond(self)
449 """)
450 write_if_changed(os.path.join(blog_root, "tags", "index.tmpl"), ''.join(new_text))
451
452
453 class HTMLDone(Exception): pass
454
455
456 class FirstPHTMLParser(_HTMLParser):
457     def __init__(self):
458         _HTMLParser.__init__(self)
459         self.first_p = None
460
461     def start_p(self, attrs):
462         self.accumulator = '<p>'
463
464     def end_p(self):
465         self.first_p = self.accumulator + '</p>'
466         raise HTMLDone()
467
468 def get_first_p(body):
469     parser = FirstPHTMLParser()
470
471     try:
472         parser.feed(body)
473     except HTMLDone:
474         pass
475
476     try:
477         parser.close()
478     except HTMLDone:
479         pass
480
481     return parser.first_p
482
483
484 class AbsURLHTMLParser(_HTMLParser):
485     def __init__(self, base):
486         _HTMLParser.__init__(self)
487         self.base = base
488
489     def start_a(self, attrs):
490         self.accumulator += '<a'
491         for attrname, value in attrs:
492             value = escape(value, True)
493             if attrname == 'href':
494                 self.accumulator += ' href="%s"' % urljoin(self.base, value)
495             else:
496                 self.accumulator += ' %s="%s"' % (attrname, value)
497         self.accumulator += '>'
498
499     def end_a(self):
500         self.accumulator += '</a>'
501
502     def start_img(self, attrs):
503         self.accumulator += '<img'
504         for attrname, value in attrs:
505             value = escape(value, True)
506             if attrname == 'src':
507                 self.accumulator += ' src="%s"' % urljoin(self.base, value)
508             else:
509                 self.accumulator += ' %s="%s"' % (attrname, value)
510         self.accumulator += '>'
511
512     def end_img(self):
513         pass
514
515 def absolute_urls(body, base):
516     parser = AbsURLHTMLParser(base)
517
518     try:
519         parser.feed(body)
520     except Exception:
521         pass
522
523     try:
524         parser.close()
525     except Exception:
526         pass
527
528     return parser.accumulator
529
530
531 if blog_root:
532     blog_root_url = blog_root[
533           blog_root.find('/htdocs/phdru.name/') + len('/htdocs/phdru.name/'):]
534     baseURL = "https://phdru.name/%s/" % blog_root_url
535 else:
536     baseURL = "https://phdru.name/"
537
538 items = []
539 for item in tuple(reversed(all_titles_tags))[:10]:
540     year, month, day, file, title, lead, tags = item
541     url_path = "%s/%s/%s/%s" % (year, month, day, file)
542     item = NewsItem(
543         "%s-%s-%s" % (year, month, day),
544         "%s%s" % (lead+' ' if lead else '', title),
545         url_path)
546     items.append(item)
547     item.baseURL = baseURL
548     item.categoryList = tags
549     body = bodies[(year, month, day, file)]
550     body = absolute_urls(body, baseURL + url_path)
551     item.body = body
552     excerpt = get_first_p(body)
553     item.excerpt = excerpt
554
555 namespace = {
556     "title": "Oleg Broytman's blog",
557     "baseURL": baseURL,
558     "indexFile": "",
559     "description": "",
560     "lang": "ru",
561     "author": "Oleg Broytman",
562     "email": "phd@phdru.name",
563     "generator": os.path.basename(sys.argv[0]),
564     "posts": items,
565 }
566
567 # For english dates
568 locale.setlocale(locale.LC_TIME, 'C')
569
570 atom_tmpl = atom_10(searchList=[namespace])
571 write_if_changed(os.path.join(blog_root, "atom_10.xml"), str(atom_tmpl))
572 rss_tmpl = rss_20(searchList=[namespace])
573 write_if_changed(os.path.join(blog_root, "rss_20.xml"), str(rss_tmpl))
574
575 for item in items:
576     item.excerpt = None
577
578 atom_tmpl = atom_10(searchList=[namespace])
579 write_if_changed(os.path.join(blog_root, "atom_10_titles.xml"), str(atom_tmpl))
580 rss_tmpl = rss_20(searchList=[namespace])
581 write_if_changed(os.path.join(blog_root, "rss_20_titles.xml"), str(rss_tmpl))
582
583 for item in items:
584     item.content = item.body
585
586 atom_tmpl = atom_10(searchList=[namespace])
587 write_if_changed(os.path.join(blog_root, "atom_10_full.xml"), str(atom_tmpl))
588 rss_tmpl = rss_20(searchList=[namespace])
589 write_if_changed(os.path.join(blog_root, "rss_20_full.xml"), str(rss_tmpl))
590
591 # vim: set ts=8 sts=4 sw=4 et :