]> git.phdru.name Git - phdru.name/phdru.name.git/blob - phd.py
Style(phd.py): Fix `flake8` warnings
[phdru.name/phdru.name.git] / phd.py
1 import os, re, time
2 try:
3     from urllib import quote as url_quote
4 except ImportError:
5     from urllib.parse import quote as url_quote
6 from Cheetah.Template import Template
7 from Cheetah.compat import PY2
8 from blog_db import load_blog
9
10
11 url_re = r"(((https?|ftp|gopher|telnet)://|(mailto|file|news|about|ed2k|irc|sip|magnet):)[^' \t<>\"]+|(www|web|w3)[A-Za-z0-9_-]*\.[A-Za-z0-9._-]+\.[^' \t<>\"]+)[A-Za-z0-9/]"
12
13
14 def _url2href(match):
15     url = match.group(0)
16     return '<a href="%s">%s</a>' % (url, url)
17
18
19 full_dirs = len(os.getcwd().split('/')) + 1
20
21
22 class phd(Template):
23     def __init__(self, *args, **kw):
24         if not hasattr(self, "_fileBaseName"):
25             self._fileDirName, self._fileBaseName = \
26                 os.path.split(os.path.abspath(self._CHEETAH_src))
27         Template.__init__(self, *args, **kw)
28         # remove directories up to "./files"
29         directories = self._fileDirName.split('/')[full_dirs:]
30         dirs_to_root = len(directories)
31         if dirs_to_root:
32             root = "../"*dirs_to_root
33         else:
34             root = ''
35         self.root = root
36         path = '/'.join(directories) + '/' + \
37             self._fileBaseName.replace(".tmpl", ".html")
38         if path[0] != '/': path = '/' + path
39         self.path = path
40
41     def copyright(self, start_year):
42         this_year = time.localtime()[0]
43         if start_year >= this_year:
44             return this_year
45         if start_year == this_year - 1:
46             return "%s, %s" % (start_year, this_year)
47         return "%s-%s" % (start_year, this_year)
48
49     def body(self):
50         if hasattr(self, "body_html"):
51             return self.body_html()
52         if hasattr(self, "body_text"):
53             return self.text2html()
54         if hasattr(self, "body_rst"):
55             return self.rst2html()
56         if hasattr(self, "body_mkd"):
57             return self.mkd2html()
58
59     def text2html(self):
60         body = re.sub(url_re, _url2href, self.body_text())
61
62         paragraphs = body.split("\n\n")
63
64         new_paras = []
65         for p in paragraphs:
66             if PY2 and not isinstance(p, bytes):
67                 p = p.encode('utf-8')
68             parts = p.split("\n  ")
69             parts[0] = parts[0].strip()
70             new_paras.append('\n</p>\n<p>\n'.join(parts))
71
72         if self.Title:
73             title = "<h1>%s</h1>\n\n" % self.Title
74         else:
75             title = ''
76
77         body = '\n</p>\n\n<p class="head">\n'.join(new_paras)
78         return "%s<p>%s</p>" % (title, body)
79
80     def rst2html(self):
81         from docutils.core import publish_parts
82
83         parts = publish_parts(self.body_rst(), writer_name="html")
84
85         title = parts["title"] or self.Title
86         if title:
87             title = "<h1>%s</h1>" % title
88
89         subtitle = parts["subtitle"]
90         if subtitle:
91             subtitle = "<h2>%s</h2>" % subtitle
92
93         body = parts["body"]
94         parts = []
95         for part in (title, subtitle, body):
96             if not part:
97                 continue
98             if PY2 and not isinstance(part, bytes):
99                 part = part.encode('utf-8')
100             parts.append(part)
101         return "\n\n".join(parts)
102
103     def mkd2html(self):
104         from markdown import markdown
105         return markdown(self.body_mkd(), output_format="html")
106
107     def find_near_blog_posts(self):
108         if not self.path.startswith("/Russian/blog/"):
109             return None, None, None, None
110         dirs = self.path.split('/')
111         # blog post is ['', 'Russian', 'blog', year, month, day, filename]
112         if len(dirs) != 7:  # Not a blog post
113             return None, None, None, None
114         ymd = tuple(dirs[3:-1])
115         filename = self._fileBaseName
116
117         prev_key = prev_blog_post = current_key = current_blog_post = \
118             next_key = next_blog_post = None
119         blog = load_blog()
120         for key in sorted(blog):
121             for blog_post in sorted(blog[key]):
122                 if current_blog_post:
123                     prev_key = current_key
124                     prev_blog_post = current_blog_post
125                 if next_blog_post:
126                     current_key = next_key
127                     current_blog_post = next_blog_post
128                 next_key = key
129                 next_blog_post = blog_post
130                 if current_blog_post and (current_key == ymd) and \
131                         (current_blog_post[0] == filename):  # Found!
132                     return prev_key, prev_blog_post, next_key, next_blog_post
133         return current_key, current_blog_post, None, None
134
135     def img_thumbnail_800_1024(self, img_name):
136         return """\
137 <img src="%(img_name)s-thumbnail.jpg" alt="%(img_name)s-thumbnail.jpg" /><br />
138 <a href="%(img_name)s-800x600.jpg">800x600</a>, <a href="%(img_name)s-1024x800.jpg">1024x800</a>""" % {"img_name": img_name}
139
140     def wikipedia(self, query):
141         return "https://en.wikipedia.org/wiki/%s" % quote_string(
142             query.replace(' ', '_'), ext_safe=',')
143
144     def wikipedia_ru(self, query):
145         return "https://ru.wikipedia.org/wiki/%s" % quote_string(
146             query.replace(' ', '_'), ext_safe=',')
147
148     def startpage(self, query):
149         return "https://startpage.com/do/search?q=%s" % quote_string(query)
150
151     search = startpage
152
153     def nigma(self, query):
154         return "http://www.nigma.ru/index.php?s=%s" % quote_string(query)
155
156     def yandex(self, query):
157         return "http://www.yandex.ru/yandsearch?text=%s&rpt=rad" \
158             % quote_string(query, "cp1251")
159
160     def google(self, query):
161         return "http://www.google.com/search?hl=en&ie=utf-8&oe=utf-8&q=%s" \
162             % quote_string(query)
163
164     def google_ru(self, query):
165         return "http://www.google.ru/search?hl=ru&ie=utf-8&oe=utf-8&q=%s" \
166             % quote_string(query)
167
168     def lurkmoar(self, query):
169         return "https://lurkmore.to/%s" % quote_string(
170             query.replace(' ', '_'), ext_safe=',')
171
172
173 def quote_string(s, to_encoding="utf-8", ext_safe=''):
174     if isinstance(s, bytes):
175         s = s.decode("utf-8")
176         if PY2:
177             s = s.encode(to_encoding)
178     return url_quote(s, '/' + ext_safe)