My static website generator using poole https://www.xythobuz.de
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

macros.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import re
  2. import itertools
  3. import email.utils
  4. import os.path
  5. import time
  6. import codecs
  7. from datetime import datetime
  8. DEFAULT_LANG = "en"
  9. BASE_URL = "https://www.xythobuz.de"
  10. # -----------------------------------------------------------------------------
  11. # lightgallery helper macro
  12. # -----------------------------------------------------------------------------
  13. # call this macro like this
  14. # lightgallery([
  15. # [ "image-link", "description" ],
  16. # [ "image-link", "thumbnail-link", "description" ],
  17. # [ "youtube-link", "thumbnail-link", "description" ],
  18. # [ "video-link", "mime", "thumbnail-link", "image-link", "description" ]
  19. # ])
  20. def lightgallery(links):
  21. videos = [l for l in links if len(l) == 5]
  22. v_i = 0
  23. for v in videos:
  24. link, mime, thumb, poster, alt = v
  25. v_i += 1
  26. print '<div style="display:none;" id="video' + str(v_i) + '">'
  27. print '<video class="lg-video-object lg-html5" controls preload="none">'
  28. print '<source src="' + link + '" type="' + mime + '">'
  29. print 'Your browser does not support HTML5 video.'
  30. print '</video>'
  31. print '</div>'
  32. print '<div class="lightgallery">'
  33. v_i = 0
  34. for l in links:
  35. if (len(l) == 3) or (len(l) == 2):
  36. link = img = alt = ""
  37. if len(l) == 3:
  38. link, img, alt = l
  39. else:
  40. link, alt = l
  41. x = link.rfind('.')
  42. img = link[:x] + '_small' + link[x:]
  43. print '<div class="border" data-src="' + link + '"><a href="' + link + '"><img class="pic" src="' + img + '" alt="' + alt + '"></a></div>'
  44. elif len(l) == 5:
  45. v_i += 1
  46. link, mime, thumb, poster, alt = v
  47. print '<div class="border" data-poster="' + poster + '" data-sub-html="' + alt + '" data-html="#video' + str(v_i) + '"><a href="' + link + '"><img class="pic" src="' + thumb + '"></a></div>'
  48. else:
  49. raise NameError('Invalid number of arguments for lightgallery')
  50. print '</div>'
  51. # -----------------------------------------------------------------------------
  52. # preconvert hooks
  53. # -----------------------------------------------------------------------------
  54. def hook_preconvert_anotherlang():
  55. MKD_PATT = r'\.(?:md|mkd|mdown|markdown)$'
  56. _re_lang = re.compile(r'^[\s+]?lang[\s+]?[:=]((?:.|\n )*)', re.MULTILINE)
  57. vpages = [] # Set of all virtual pages
  58. for p in pages:
  59. current_lang = DEFAULT_LANG # Default language
  60. langs = [] # List of languages for the current page
  61. page_vpages = {} # Set of virtual pages for the current page
  62. text_lang = re.split(_re_lang, p.source)
  63. text_grouped = dict(zip([current_lang,] + \
  64. [lang.strip() for lang in text_lang[1::2]], \
  65. text_lang[::2]))
  66. for lang, text in text_grouped.iteritems():
  67. spath = p.fname.split(os.path.sep)
  68. langs.append(lang)
  69. if lang == "en":
  70. filename = re.sub(MKD_PATT, "%s\g<0>" % "", p.fname).split(os.path.sep)[-1]
  71. else:
  72. filename = re.sub(MKD_PATT, ".%s\g<0>" % lang, p.fname).split(os.path.sep)[-1]
  73. vp = Page(filename, virtual=text)
  74. # Copy real page attributes to the virtual page
  75. for attr in p:
  76. if not vp.has_key(attr):
  77. vp[attr] = p[attr]
  78. # Define a title in the proper language
  79. vp["title"] = p["title_%s" % lang] \
  80. if p.has_key("title_%s" % lang) \
  81. else p["title"]
  82. # Keep track of the current lang of the virtual page
  83. vp["lang"] = lang
  84. # Fix post name if exists
  85. if vp.has_key("post"):
  86. if lang == "en":
  87. vp["post"] = vp["post"][:]
  88. else:
  89. vp["post"] = vp["post"][:-len(lang) - 1]
  90. page_vpages[lang] = vp
  91. # Each virtual page has to know about its sister vpages
  92. for lang, vpage in page_vpages.iteritems():
  93. vpage["lang_links"] = dict([(l, v["url"]) for l, v in page_vpages.iteritems()])
  94. vpage["other_lang"] = langs # set other langs and link
  95. vpages += page_vpages.values()
  96. pages[:] = vpages
  97. _COMPAT = """ case "%s":
  98. $loc = "%s/%s";
  99. break;
  100. """
  101. _COMPAT_404 = """ default:
  102. $loc = "%s";
  103. break;
  104. """
  105. def hook_preconvert_compat():
  106. fp = open(os.path.join(options.project, "output", "index.php"), 'w')
  107. fp.write("<?\n")
  108. fp.write("// Auto generated xyCMS compatibility index.php\n")
  109. fp.write("$loc = 'https://www.xythobuz.de/index.de.html';\n")
  110. fp.write("if (isset($_GET['p'])) {\n")
  111. fp.write(" if (isset($_GET['lang'])) {\n")
  112. fp.write(" $_GET['p'] .= 'EN';\n")
  113. fp.write(" }\n")
  114. fp.write(" switch($_GET['p']) {\n")
  115. for p in pages:
  116. if p.get("compat", "") != "":
  117. tmp = p["compat"]
  118. if p.get("lang", DEFAULT_LANG) == DEFAULT_LANG:
  119. tmp = tmp + "EN"
  120. fp.write(_COMPAT % (tmp, "https://www.xythobuz.de", p.url))
  121. fp.write("\n")
  122. fp.write(_COMPAT_404 % "/404.html")
  123. fp.write(" }\n")
  124. fp.write("}\n")
  125. fp.write("if ($_SERVER['SERVER_PROTOCOL'] == 'HTTP/1.1') {\n")
  126. fp.write(" if (php_sapi_name() == 'cgi') {\n")
  127. fp.write(" header('Status: 301 Moved Permanently');\n")
  128. fp.write(" } else {\n")
  129. fp.write(" header('HTTP/1.1 301 Moved Permanently');\n")
  130. fp.write(" }\n")
  131. fp.write("}\n");
  132. fp.write("header('Location: '.$loc);\n")
  133. fp.write("?>")
  134. fp.close()
  135. _SITEMAP = """<?xml version="1.0" encoding="UTF-8"?>
  136. <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  137. %s
  138. </urlset>
  139. """
  140. _SITEMAP_URL = """
  141. <url>
  142. <loc>%s/%s</loc>
  143. <lastmod>%s</lastmod>
  144. <changefreq>%s</changefreq>
  145. <priority>%s</priority>
  146. </url>
  147. """
  148. def hook_preconvert_sitemap():
  149. date = datetime.strftime(datetime.now(), "%Y-%m-%d")
  150. urls = []
  151. for p in pages:
  152. urls.append(_SITEMAP_URL % (BASE_URL, p.url, date, p.get("changefreq", "monthly"), p.get("priority", "0.5")))
  153. fname = os.path.join(options.project, "output", "sitemap.xml")
  154. fp = open(fname, 'w')
  155. fp.write(_SITEMAP % "".join(urls))
  156. fp.close()
  157. # -----------------------------------------------------------------------------
  158. # postconvert hooks
  159. # -----------------------------------------------------------------------------
  160. _RSS = """<?xml version="1.0"?>
  161. <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  162. <channel>
  163. <title>%s</title>
  164. <link>%s</link>
  165. <atom:link href="%s" rel="self" type="application/rss+xml" />
  166. <description>%s</description>
  167. <language>en-us</language>
  168. <pubDate>%s</pubDate>
  169. <lastBuildDate>%s</lastBuildDate>
  170. <docs>http://blogs.law.harvard.edu/tech/rss</docs>
  171. <generator>Poole</generator>
  172. %s
  173. </channel>
  174. </rss>
  175. """
  176. _RSS_ITEM = """
  177. <item>
  178. <title>%s</title>
  179. <link>%s</link>
  180. <description>%s</description>
  181. <pubDate>%s</pubDate>
  182. <guid>%s</guid>
  183. </item>
  184. """
  185. def hook_postconvert_rss():
  186. items = []
  187. posts = [p for p in pages if "date" in p]
  188. posts.sort(key=lambda p: p.date, reverse=True)
  189. posts = posts[:10]
  190. for p in posts:
  191. title = p.title
  192. if "post" in p:
  193. title = p.post
  194. link = "%s/%s" % (BASE_URL, p.url)
  195. desc = p.html.replace("href=\"img", "%s%s%s" % ("href=\"", BASE_URL, "/img"))
  196. desc = desc.replace("src=\"img", "%s%s%s" % ("src=\"", BASE_URL, "/img"))
  197. desc = desc.replace("href=\"/img", "%s%s%s" % ("href=\"", BASE_URL, "/img"))
  198. desc = desc.replace("src=\"/img", "%s%s%s" % ("src=\"", BASE_URL, "/img"))
  199. desc = htmlspecialchars(desc)
  200. date = time.mktime(time.strptime("%s 12" % p.date, "%Y-%m-%d %H"))
  201. date = email.utils.formatdate(date)
  202. items.append(_RSS_ITEM % (title, link, desc, date, link))
  203. items = "".join(items)
  204. title = "xythobuz.de Blog"
  205. link = "%s" % BASE_URL
  206. feed = "%s/rss.xml" % BASE_URL
  207. desc = htmlspecialchars("xythobuz Electronics & Software Projects")
  208. date = email.utils.formatdate()
  209. rss = _RSS % (title, link, feed, desc, date, date, items)
  210. fp = codecs.open(os.path.join(output, "rss.xml"), "w", "utf-8")
  211. fp.write(rss)
  212. fp.close()
  213. _COMPAT_MOB = """ case "%s":
  214. $loc = "%s/%s";
  215. break;
  216. """
  217. _COMPAT_404_MOB = """ default:
  218. $loc = "%s";
  219. break;
  220. """
  221. def hook_postconvert_mobilecompat():
  222. directory = os.path.join(output, "mobile")
  223. if not os.path.exists(directory):
  224. os.makedirs(directory)
  225. fp = codecs.open(os.path.join(directory, "index.php"), "w", "utf-8")
  226. fp.write("<?\n")
  227. fp.write("// Auto generated xyCMS compatibility mobile/index.php\n")
  228. fp.write("$loc = 'https://www.xythobuz.de/index.de.html';\n")
  229. fp.write("if (isset($_GET['p'])) {\n")
  230. fp.write(" if (isset($_GET['lang'])) {\n")
  231. fp.write(" $_GET['p'] .= 'EN';\n")
  232. fp.write(" }\n")
  233. fp.write(" switch($_GET['p']) {\n")
  234. for p in pages:
  235. if p.get("compat", "") != "":
  236. tmp = p["compat"]
  237. if p.get("lang", DEFAULT_LANG) == DEFAULT_LANG:
  238. tmp = tmp + "EN"
  239. fp.write(_COMPAT_MOB % (tmp, "https://www.xythobuz.de", re.sub(".html", ".html", p.url)))
  240. fp.write("\n")
  241. fp.write(_COMPAT_404_MOB % "/404.mob.html")
  242. fp.write(" }\n")
  243. fp.write("}\n")
  244. fp.write("if ($_SERVER['SERVER_PROTOCOL'] == 'HTTP/1.1') {\n")
  245. fp.write(" if (php_sapi_name() == 'cgi') {\n")
  246. fp.write(" header('Status: 301 Moved Permanently');\n")
  247. fp.write(" } else {\n")
  248. fp.write(" header('HTTP/1.1 301 Moved Permanently');\n")
  249. fp.write(" }\n")
  250. fp.write("}\n");
  251. fp.write("header('Location: '.$loc);\n")
  252. fp.write("?>")
  253. fp.close()
  254. def hook_postconvert_size():
  255. file_ext = '|'.join(['pdf', 'zip', 'rar', 'ods', 'odt', 'odp', 'doc', 'xls', 'ppt', 'docx', 'xlsx', 'pptx', 'exe', 'brd', 'mp3', 'mp4', 'plist'])
  256. def matched_link(matchobj):
  257. try:
  258. path = matchobj.group(1)
  259. if path.startswith("http") or path.startswith("//") or path.startswith("ftp"):
  260. return '<a href=\"%s\">%s</a>' % (matchobj.group(1), matchobj.group(3))
  261. elif path.startswith("/"):
  262. path = path.strip("/")
  263. path = os.path.join("static/", path)
  264. size = os.path.getsize(path)
  265. if size >= (1024 * 1024):
  266. return "<a href=\"%s\">%s</a>&nbsp;(%.1f MiB)" % (matchobj.group(1), matchobj.group(3), size / (1024.0 * 1024.0))
  267. elif size >= 1024:
  268. return "<a href=\"%s\">%s</a>&nbsp;(%d KiB)" % (matchobj.group(1), matchobj.group(3), size // 1024)
  269. else:
  270. return "<a href=\"%s\">%s</a>&nbsp;(%d Byte)" % (matchobj.group(1), matchobj.group(3), size)
  271. except:
  272. print "Unable to estimate file size for %s" % matchobj.group(1)
  273. return '<a href=\"%s\">%s</a>' % (matchobj.group(1), matchobj.group(3))
  274. _re_url = '<a href=\"([^\"]*?\.(%s))\">(.*?)<\/a>' % file_ext
  275. for p in pages:
  276. p.html = re.sub(_re_url, matched_link, p.html)