]> git.phdru.name Git - phdru.name/phdru.name.git/blobdiff - reindex_blog.py
Feat(blog): Encode tags
[phdru.name/phdru.name.git] / reindex_blog.py
index cd6906c0424691cc51512378e14a4b4691bfd5ea..0b7c2a6dd9fbf39af81f038f172c0b998470b84b 100755 (executable)
@@ -1,34 +1,21 @@
-#! /usr/local/bin/python -O
+#! /usr/bin/env python
 # -*- coding: koi8-r -*-
 
-__version__ = "$Revision$"[11:-2]
-__revision__ = "$Id$"[5:-2]
-__date__ = "$Date$"[7:-2]
-__author__ = "Oleg BroytMann <phd@phd.pp.ru>"
-__copyright__ = "Copyright (C) 2006 PhiloSoft Design"
-
+__author__ = "Oleg Broytman <phd@phdru.name>"
+__copyright__ = "Copyright (C) 2006-2024 PhiloSoft Design"
 
 import sys, os
-
 try:
-   import cPickle as pickle
+    from urllib.parse import quote
 except ImportError:
-   import pickle
+    from urllib import quote
 
 from Cheetah.Template import Template
+from Cheetah.compat import string_type
+from blog_db import blog_root, load_blog, save_blog
 
 
-# Load old blog
-
-blog_filename = sys.argv[1]
-try:
-   blog_file = open(blog_filename, "rb")
-except IOError:
-   old_blog = {}
-else:
-   old_blog = pickle.load(blog_file)
-   blog_file.close()
-
+old_blog = load_blog()
 
 # blog is a dictionary mapping
 # (year, month, day) => [list of (file, title, lead, tags)]
@@ -36,27 +23,31 @@ else:
 blog = {}
 years = {}
 
+# bodies is a dictionary mapping file => body
+
+bodies = {}
+
 # Walk the directory recursively
-for dirpath, dirs, files in os.walk(os.curdir):
+for dirpath, dirs, files in os.walk(blog_root):
    d = os.path.basename(dirpath)
    if not d.startswith("20") and not d.isdigit():
       continue
    for file in files:
-      # Ignore index.tmpl and *.html files; supose all other files are *.tmpl
-      if file == "index.tmpl" or file.endswith(".html"):
+      if not file.endswith(".tmpl"):
          continue
       fullpath = os.path.join(dirpath, file)
       template = Template(file=fullpath)
-      title_parts = template.Title.split()
+      title_parts = template.Title.decode('utf-8').encode('koi8-r').split()
       title = ' '.join(title_parts[6:])
-      lead = getattr(template, "Lead", None)
+      lead = template.Lead.decode('utf-8').encode('koi8-r')
 
-      tags = getattr(template, "Tag", None)
-      if isinstance(tags, basestring):
+      tags = template.Tag
+      if isinstance(tags, string_type):
          tags = (tags,)
+      tags = [tag.decode('utf-8').encode('koi8-r') for tag in tags]
 
       if title:
-         key = year, month, day = tuple(dirpath.split(os.sep)[1:])
+         key = year, month, day = tuple(dirpath[len(blog_root):].split(os.sep)[1:])
          if key in blog:
             days = blog[key]
          else:
@@ -75,26 +66,33 @@ for dirpath, dirs, files in os.walk(os.curdir):
 
          if day not in days: days.append(day)
 
+         file = file[:-len("tmpl")] + "html"
+         key = (year, month, day, file)
+         body = template.body()
+         if isinstance(body, unicode):
+            body = body.encode('koi8-r')
+         bodies[key] = body
 
 # Need to save the blog?
-if blog <> old_blog:
-   blog_file = open(blog_filename, "wb")
-   pickle.dump(blog, blog_file, pickle.HIGHEST_PROTOCOL)
-   blog_file.close()
-
+if blog != old_blog:
+    save_blog(blog)
 
 # Localized month names
 
 import locale
-locale.setlocale(locale.LC_ALL, '')
-from calendar import _localized_day, _localized_month
+locale.setlocale(locale.LC_ALL, "ru_RU.KOI8-R")
+from calendar import _localized_month
 
 locale.setlocale(locale.LC_TIME, 'C')
 months_names_en = list(_localized_month('%B'))
 months_abbrs_en = list(_localized_month('%b'))
 
-locale.setlocale(locale.LC_TIME, '')
-months_names_ru = [month.lower() for month in _localized_month('%B')]
+locale.setlocale(locale.LC_TIME, "ru_RU.KOI8-R")
+# months_names_ru = list(_localized_month('%B'))
+
+months_names_ru = ['', "января", "февраля", "марта", "апреля", "мая", "июня",
+   "июля", "августа", "сентября", "октября", "ноября", "декабря"
+]
 
 months_names_ru0 = ['', "январь", "февраль", "март", "апрель", "май", "июнь",
    "июль", "август", "сентябрь", "октябрь", "ноябрь", "декабрь"
@@ -102,9 +100,11 @@ months_names_ru0 = ['', "
 
 from news import write_if_changed
 
+def encode_tag(tag):
+    return quote(tag.replace(' ', '_'))
 
 def write_template(level, year, month, day, titles, tags=None):
-   path = []
+   path = [blog_root]
    if level >= 1:
       path.append(year)
    if level >= 2:
@@ -116,39 +116,47 @@ def write_template(level, year, month, day, titles, tags=None):
 
    new_text = ["""\
 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
-#extends phd_pp_ru
+#encoding koi8-r
+#extends phd_site
 #implements respond
 """]
 
    if level == 0:
       new_text.append("""\
-#attr $Title = "Oleg BroytMann's blog"
-#attr $Description = "BroytMann Russian Blog Index Document"
+#attr $Title = "Oleg Broytman's blog"
+#attr $Description = "Broytman Russian Blog Index Document"
 #attr $Copyright = %(cyear)s
+#attr $alternates = (("Новости [Atom 1.0] только заголовки", "application/atom+xml", "atom_10_titles.xml"),
+                     ("Новости [Atom 1.0]", "application/atom+xml", "atom_10.xml"),
+                     ("Новости [Atom 1.0] полные тексты", "application/atom+xml", "atom_10_full.xml"),
+                     ("Новости [RSS 2.0] только заголовки",  "application/rss+xml",  "rss_20_titles.xml"),
+                     ("Новости [RSS 2.0]",  "application/rss+xml",  "rss_20.xml"),
+                     ("Новости [RSS 2.0] полные тексты",  "application/rss+xml",  "rss_20_full.xml"),
+)
 ##
 #def body_html
-<H1>Журнал</H1>
+<h1>Журнал</h1>
 """ % {"cyear": year or 2005})
 
    elif level == 1:
       new_text.append("""\
-#attr $Title = "Oleg BroytMann's blog: %(year)s"
-#attr $Description = "BroytMann Russian Blog %(year)s Index Document"
+#attr $Title = "Oleg Broytman's blog: %(year)s"
+#attr $Description = "Broytman Russian Blog %(year)s Index Document"
 #attr $Copyright = %(cyear)s
 ##
 #def body_html
-<H1>Журнал: %(year)s</H1>
+<h1>Журнал: %(year)s</h1>
 """ % {"year": year, "cyear": year or 2005})
 
    elif level == 2:
       imonth = int(month)
       new_text.append("""\
-#attr $Title = "Oleg BroytMann's blog: %(month_abbr_en)s %(year)s"
-#attr $Description = "BroytMann Russian Blog %(month_name_en)s %(year)s Index Document"
+#attr $Title = "Oleg Broytman's blog: %(month_abbr_en)s %(year)s"
+#attr $Description = "Broytman Russian Blog %(month_name_en)s %(year)s Index Document"
 #attr $Copyright = %(cyear)s
 ##
 #def body_html
-<H1>Журнал: %(month_name_ru0)s %(year)s</H1>
+<h1>Журнал: %(month_name_ru0)s %(year)s</h1>
 """ % {
       "year": year, "cyear": year or 2005,
       "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
@@ -159,34 +167,29 @@ def write_template(level, year, month, day, titles, tags=None):
       iday = int(day)
       imonth = int(month)
 
-      new_text.append("""\
-#attr $Next = "%s"
-""" % titles[0][3])
-
-
       if len(titles) == 1:
          new_text.append("""\
-#attr $refresh = "0; URL=%s"
+#attr $Refresh = "0; URL=%s"
 """ % titles[0][3])
 
       new_text.append("""\
-#attr $Title = "Oleg BroytMann's blog: %(day)d %(month_abbr_en)s %(year)s"
-#attr $Description = "BroytMann Russian Blog %(day)d %(month_name_en)s %(year)s Index Document"
+#attr $Title = "Oleg Broytman's blog: %(day)d %(month_abbr_en)s %(year)s"
+#attr $Description = "Broytman Russian Blog %(day)d %(month_name_en)s %(year)s Index Document"
 #attr $Copyright = %(cyear)s
 ##
 #def body_html
-<H1>Журнал: %(day)d %(month_name_ru0)s %(year)s</H1>
+<h1>Журнал: %(day)d %(month_name_ru)s %(year)s</h1>
 """ % {
       "year": year, "cyear": year or 2005,
       "month_abbr_en": months_abbrs_en[imonth], "month_name_en": months_names_en[imonth],
-      "month_name_ru0": months_names_ru0[imonth],
+      "month_name_ru": months_names_ru[imonth],
       "day": iday
    })
 
    save_titles = titles[:]
    titles.reverse()
 
-   save_day = None
+   save_date = None
    for year, month, day, file, title, lead in titles:
       href = []
       if level == 0:
@@ -198,30 +201,39 @@ def write_template(level, year, month, day, titles, tags=None):
       href.append(file)
       href = '/'.join(href)
       if day[0] == '0': day = day[1:]
-      if save_day <> day:
+      if save_date != (year, month, day):
          if level == 0:
             new_text.append('\n<h2>%s %s %s</h2>' % (day, months_names_ru[int(month)], year))
          else:
             new_text.append('\n<h2>%s %s</h2>' % (day, months_names_ru[int(month)]))
-         save_day = day
-      if lead:
-         lead = lead + ' '
-      else:
-         lead = ''
+         save_date = year, month, day
       new_text.append('''
 <p class="head">
    %s<a href="%s">%s</a>.
 </p>
-''' % (lead, href, title))
+''' % (lead+' ' if lead else '', href, title))
 
    if level == 0:
+      new_text.append("""
+<hr>
+
+<p class="head">Новостевая лента в форматах
+<img src="../../Graphics/atom_10.jpg" border=0>
+<A HREF="atom_10_titles.xml">Atom 1.0 только заголовки</A> /
+<A HREF="atom_10.xml">Atom 1.0</A> /
+<A HREF="atom_10_full.xml">Atom 1.0 полные тексты</A>
+и <img src="../../Graphics/rss_20.jpg" border=0>
+<A HREF="rss_20_titles.xml">RSS 2.0 только заголовки</A> /
+<A HREF="rss_20.xml">RSS 2.0</A> /
+<A HREF="rss_20_full.xml">RSS 2.0 полные тексты</A>.
+</p>
+""")
+
       years = {}
       for year, month, day, file, title, lead in save_titles:
          years[year] = True
       new_text.append('''
-<hr>
-
-<p class="noindent"><a href="tags/">Теги</a>:
+<p class="head"><a href="tags/">Теги</a>:
 ''')
       first_tag = True
       for count, tag, links in all_tags:
@@ -229,35 +241,52 @@ def write_template(level, year, month, day, titles, tags=None):
             first_tag = False
          else:
             new_text.append(' - ')
-         new_text.append("""<a href="tags/%s.html">%s (%d)</a>""" % (tag, tag, count))
+         new_text.append("""<a href="tags/%s.html">%s (%d)</a>""" % (
+             encode_tag(tag), tag, count))
       new_text.append('''
 </p>
 ''')
 
+      max_year = int(sorted(years.keys())[-1])
+      years = range(max_year, 2005, -1)
+
       new_text.append('''
-<p class="noindent">По годам:
+<p class="head">По годам:
 ''')
+
+      year_counts = {}
+      for year, month, day, file, title, lead in all_titles:
+         year_counts[year] = 0
+      for year, month, day, file, title, lead in all_titles:
+         year_counts[year] += 1
+
       first_year = True
-      for year in sorted(years.keys()):
+      for year in years:
          if first_year:
             first_year = False
          else:
             new_text.append(' - ')
-         new_text.append('<a href="%s/">%s</a>' % (year, year))
+         new_text.append('<a href="%s/">%s (%d)</a>' % (year, year, year_counts[str(year)]))
       new_text.append('''
 </p>
 ''')
 
+      new_text.append("""
+<hr>
+<p class="head"><a href="http://phd.livejournal.com/">ЖЖ</a>
+""")
+
    new_text.append("""\
 #end def
-$phd_pp_ru.respond(self)
+$phd_site.respond(self)
 """)
 
    write_if_changed(index_name, ''.join(new_text))
 
 
-all_titles = []
 all_tags = {}
+all_titles = []
+all_titles_tags = []
 
 for year in sorted(years.keys()):
    year_titles = []
@@ -271,6 +300,7 @@ for year in sorted(years.keys()):
             for file, title, lead, tags in blog[key]:
                if file.endswith(".tmpl"): file = file[:-len("tmpl")] + "html"
                value = (year, month, day, file, title, lead)
+               all_titles_tags.append((year, month, day, file, title, lead, tags))
                all_titles.append(value)
                year_titles.append(value)
                month_titles.append(value)
@@ -285,54 +315,114 @@ for year in sorted(years.keys()):
       write_template(2, year, month, day, month_titles)
    write_template(1, year, month, day, year_titles)
 
+def by_count_rev_tag_link(t1, t2):
+   """Sort all_tags by count in descending order,
+   and by tags and links in ascending order
+   """
+   r = cmp(t1[0], t2[0])
+   if r:
+      return -r
+   return cmp((t1[1], t1[2]), (t2[1], t2[2]))
+
 all_tags = [(len(links), tag, links) for (tag, links) in all_tags.items()]
-all_tags.sort()
+all_tags.sort(by_count_rev_tag_link)
 
 write_template(0, year, month, day, all_titles[-20:], all_tags)
 
 new_text = ["""\
 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
-#extends phd_pp_ru
+#encoding koi8-r
+#extends phd_site
 #implements respond
-#attr $Title = "Oleg BroytMann's blog: tags"
-#attr $Description = "BroytMann Russian Blog Tags Index Document"
+#attr $Title = "Oleg Broytman's blog: tags"
+#attr $Description = "Broytman Russian Blog Tags Index Document"
 #attr $Copyright = 2006
 ##
 #def body_html
-<H1>Теги</H1>
+<h1>Теги</h1>
+
+<p class="head small">
+Форма поиска позволяет искать сообщения в блоге, соответствующие выражению.
+Синтаксис выражения:</p>
+<ul class="small">
+    <li>Тег - если такой тег существует, произойдёт перенаправление на страницу тега.</li>
+    <li>Оператор '!' (NOT, not) - ищет записи, в которых нет этого тега.</li>
+    <li>Оператор '&amp;' (AND, and) - ищет записи, в которых есть оба тега.</li>
+    <li>Оператор '|' (OR, or) - ищет записи, в которых есть любые из тегов.</li>
+    <li>Приоритет операций стандартный: NOT &gt; AND &gt; OR. Скобки '()' позволяют объединять выражения.</li>
+</ul>
+<p class="small">
+Примеры выражений: linux - произойдёт перенаправление
+на страницу linux.html; linux&amp;!audio - искать записи в которых есть тег
+linux и нет тега audio; linux and not audio - то же самое.
+</p>
+
+<center>
+<form method=GET action="../../../cgi-bin/blog-ru/search-tags/search-tags.py">
+    <input type=text name=q>
+    <input type=submit name=submit value="Искать">
+</form>
+</center>
 
-<p class="head">
 <dl>
 """]
 
-for count, tag, links in all_tags:
+for i, (count, tag, links) in enumerate(all_tags):
    new_text.append("""\
    <dt><a href="%s.html">%s (%d)</a></dt>
-""" % (tag, tag, count))
+""" % (encode_tag(tag), tag, count))
+
+   first = all_tags[0][1]
+   if i == 0:
+      prev = None
+   else:
+      prev = all_tags[i-1][1]
+   if i >= len(all_tags)-1:
+      next = None
+   else:
+      next = all_tags[i+1][1]
+   last = all_tags[-1][1]
 
    tag_text = ["""\
 ## THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
-#extends phd_pp_ru
+#encoding koi8-r
+#extends phd_site
 #implements respond
-#attr $Title = "Oleg BroytMann's blog: tag %s"
-#attr $Description = "BroytMann Russian Blog Tag %s Index Document"
+#attr $Title = "Oleg Broytman's blog: tag %s"
+#attr $Description = "Broytman Russian Blog Tag %s Index Document"
+""" % (tag, tag)]
+
+   tag_text.append("""\
+#attr $First = "%s"
+""" % first)
+
+   if prev:
+      tag_text.append("""\
+#attr $Prev = "%s"
+""" % prev)
+
+   if next:
+      tag_text.append("""\
+#attr $Next = "%s"
+""" % next)
+
+   tag_text.append("""\
+#attr $Last = "%s"
+""" % last)
+
+   tag_text.append("""\
 #attr $Copyright = 2006
 ##
 #def body_html
-<H1>%s</H1>
+<h1>%s</h1>
 
-<p class="head">
 <ul>
-""" % (tag, tag, tag)]
+""" % tag)
 
    count = 0
    for year, month, day, filename, title, lead in reversed(links):
-      if lead:
-         lead = lead + ' '
-      else:
-         lead = ''
       link = "../%s/%s/%s/%s" % (year, month, day, filename)
-      item_text = """<li><a href="%s">%s/%s/%s: %s%s</a></li>""" % (link, year, month, day, lead, title)
+      item_text = """<li><a href="%s">%s/%s/%s: %s%s</a></li>""" % (link, year, month, day, lead+' ' if lead else '', title)
 
       count += 1
       if count <= 5:
@@ -342,16 +432,176 @@ for count, tag, links in all_tags:
 
    tag_text.append("""\
 </ul>
-</p>
 #end def
-$phd_pp_ru.respond(self)
+$phd_site.respond(self)
 """)
-   write_if_changed(os.path.join("tags", tag+".tmpl"), ''.join(tag_text))
+   write_if_changed(os.path.join(blog_root, "tags",
+                                 tag.replace(' ', '_') + ".tmpl"),
+                    ''.join(tag_text))
 
 new_text.append("""\
 </dl>
-</p>
 #end def
-$phd_pp_ru.respond(self)
+$phd_site.respond(self)
 """)
-write_if_changed(os.path.join("tags", "index.tmpl"), ''.join(new_text))
+write_if_changed(os.path.join(blog_root, "tags", "index.tmpl"), ''.join(new_text))
+
+
+from HTMLParser import HTMLParseError
+import cgi
+from urlparse import urljoin
+from m_lib.net.www.html import HTMLParser as _HTMLParser
+
+class HTMLDone(Exception): pass
+
+
+class FirstPHTMLParser(_HTMLParser):
+   def __init__(self):
+      _HTMLParser.__init__(self)
+      self.first_p = None
+
+   def start_p(self, attrs):
+      self.accumulator = '<p>'
+
+   def end_p(self):
+      self.first_p = self.accumulator + '</p>'
+      raise HTMLDone()
+
+def get_first_p(body):
+   parser = FirstPHTMLParser()
+
+   try:
+      parser.feed(body)
+   except (HTMLParseError, HTMLDone):
+      pass
+
+   try:
+      parser.close()
+   except (HTMLParseError, HTMLDone):
+      pass
+
+   return parser.first_p
+
+
+class AbsURLHTMLParser(_HTMLParser):
+   def __init__(self, base):
+      _HTMLParser.__init__(self)
+      self.base = base
+
+   def start_a(self, attrs):
+      self.accumulator += '<a'
+      for attrname, value in attrs:
+         value = cgi.escape(value, True)
+         if isinstance(value, unicode):
+            value = value.encode('koi8-r')
+         if attrname == 'href':
+            self.accumulator += ' href="%s"' % urljoin(self.base, value)
+         else:
+            self.accumulator += ' %s="%s"' % (attrname, value)
+      self.accumulator += '>'
+
+   def end_a(self):
+      self.accumulator += '</a>'
+
+   def start_img(self, attrs):
+      self.accumulator += '<img'
+      for attrname, value in attrs:
+         value = cgi.escape(value, True)
+         if attrname == 'src':
+            self.accumulator += ' src="%s"' % urljoin(self.base, value)
+         else:
+            self.accumulator += ' %s="%s"' % (attrname, value)
+      self.accumulator += '>'
+
+   def end_img(self):
+       pass
+
+def absolute_urls(body, base):
+   parser = AbsURLHTMLParser(base)
+
+   try:
+      parser.feed(body)
+   except HTMLParseError:
+      pass
+
+   try:
+      parser.close()
+   except HTMLParseError:
+      pass
+
+   return parser.accumulator
+
+
+from atom_10 import atom_10
+from rss_20 import rss_20
+from news import NewsItem
+
+if blog_root:
+   blog_root_url = blog_root[
+        blog_root.find('/htdocs/phdru.name/') + len('/htdocs/phdru.name/'):]
+   baseURL = "https://phdru.name/%s/" % blog_root_url
+else:
+   baseURL = "https://phdru.name/"
+
+items = []
+for item in tuple(reversed(all_titles_tags))[:10]:
+   year, month, day, file, title, lead, tags = item
+   lead = lead.decode('koi8-r').encode('utf-8')
+   title = title.decode('koi8-r').encode('utf-8')
+   url_path = "%s/%s/%s/%s" % (year, month, day, file)
+   item = NewsItem(
+      "%s-%s-%s" % (year, month, day),
+      "%s%s" % (lead+' ' if lead else '', title),
+      url_path)
+   items.append(item)
+   item.baseURL = baseURL
+   item.categoryList = [t.decode('koi8-r').encode('utf-8') for t in tags]
+   body = bodies[(year, month, day, file)]
+   body = absolute_urls(body, baseURL + url_path)
+   try:
+       body.decode('utf-8')
+   except UnicodeDecodeError:
+       body = body.decode('koi8-r').encode('utf-8')
+   item.body = body
+   excerpt = get_first_p(body)
+   try:
+       excerpt.decode('utf-8')
+   except UnicodeDecodeError:
+       excerpt = excerpt.decode('koi8-r').encode('utf-8')
+   item.excerpt = excerpt
+
+namespace = {
+   "title": "Oleg Broytman's blog",
+   "baseURL": baseURL,
+   "indexFile": "",
+   "description": "",
+   "lang": "ru",
+   "author": "Oleg Broytman",
+   "email": "phd@phdru.name",
+   "generator": os.path.basename(sys.argv[0]),
+   "posts": items,
+}
+
+# For english dates
+locale.setlocale(locale.LC_TIME, 'C')
+
+atom_tmpl = unicode(atom_10(searchList=[namespace])).encode('koi8-r')
+write_if_changed(os.path.join(blog_root, "atom_10.xml"), atom_tmpl)
+rss_tmpl = unicode(rss_20(searchList=[namespace])).encode('koi8-r')
+write_if_changed(os.path.join(blog_root, "rss_20.xml"), rss_tmpl)
+
+for item in items:
+    item.excerpt = None
+
+atom_tmpl = unicode(atom_10(searchList=[namespace])).encode('koi8-r')
+write_if_changed(os.path.join(blog_root, "atom_10_titles.xml"), atom_tmpl)
+rss_tmpl = unicode(rss_20(searchList=[namespace])).encode('koi8-r')
+write_if_changed(os.path.join(blog_root, "rss_20_titles.xml"), rss_tmpl)
+
+for item in items:
+    item.content = item.body
+
+atom_tmpl = unicode(atom_10(searchList=[namespace])).encode('koi8-r')
+write_if_changed(os.path.join(blog_root, "atom_10_full.xml"), atom_tmpl)
+rss_tmpl = unicode(rss_20(searchList=[namespace])).encode('koi8-r')
+write_if_changed(os.path.join(blog_root, "rss_20_full.xml"), rss_tmpl)