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