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