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 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. # menu helper macro
  12. # -----------------------------------------------------------------------------
  13. def printMenuItem(p, yearsAsHeading = False, showDateSpan = False, showOnlyStartDate = False, nicelyFormatFullDate = False, lastyear = "0", lang = ""):
  14. title = p.title
  15. if lang != "":
  16. if p.get("title_" + lang, "") != "":
  17. title = p.get("title_" + lang, "")
  18. if p.title == "Blog":
  19. title = p.post
  20. year = p.get("date", "")[0:4]
  21. if year != lastyear:
  22. lastyear = year
  23. if yearsAsHeading:
  24. print "\n\n#### %s\n" % (year)
  25. dateto = ""
  26. if p.get("date", "" != ""):
  27. year = p.get("date", "")[0:4]
  28. if showOnlyStartDate:
  29. dateto = " (%s)" % (year)
  30. if p.get("update", "") != "" and p.get("update", "")[0:4] != year:
  31. if showDateSpan:
  32. dateto = " (%s - %s)" % (year, p.get("update", "")[0:4])
  33. if nicelyFormatFullDate:
  34. dateto = " - " + datetime.strptime(p.date, "%Y-%m-%d").strftime("%B %d, %Y")
  35. print " * **[%s](%s)**%s" % (title, p.url, dateto)
  36. if p.get("description", "") != "":
  37. description = p.get("description", "")
  38. if lang != "":
  39. if p.get("description_" + lang, "") != "":
  40. description = p.get("description_" + lang, "")
  41. print "<br><span class=\"listdesc\">" + description + "</span>"
  42. return lastyear
  43. def printRecentMenu(count = 5):
  44. posts = [p for p in pages if "date" in p]
  45. posts.sort(key=lambda p: p.get("date"), reverse=True)
  46. for p in posts[0:count]:
  47. printMenuItem(p, False, False, False, True)
  48. def printBlogMenu():
  49. posts = [p for p in pages if "post" in p]
  50. posts.sort(key=lambda p: p.get("date", "9999-01-01"), reverse=True)
  51. lastyear = "0"
  52. for p in posts:
  53. lastyear = printMenuItem(p, True, False, False, True, lastyear)
  54. def printProjectsMenu():
  55. # prints all pages with parent 'projects' or 'stuff'.
  56. # first the ones without date, sorted by position.
  57. # then afterwards those with date, split by year.
  58. # also supports blog posts with parent.
  59. enpages = [p for p in pages if p.lang == "en"]
  60. dpages = [p for p in enpages if p.get("date", "") == ""]
  61. mpages = [p for p in dpages if any(x in p.get("parent", "") for x in [ 'projects', 'stuff' ])]
  62. mpages.sort(key=lambda p: [int(p.get("position", "999"))])
  63. for p in mpages:
  64. printMenuItem(p)
  65. dpages = [p for p in enpages if p.get("date", "") != ""]
  66. mpages = [p for p in dpages if any(x in p.get("parent", "") for x in [ 'projects', 'stuff' ])]
  67. mpages.sort(key=lambda p: [p.get("date", "9999-01-01")], reverse = True)
  68. lastyear = "0"
  69. for p in mpages:
  70. lastyear = printMenuItem(p, True, True, False, False, lastyear)
  71. def print3DPrintingMenu():
  72. mpages = [p for p in pages if p.get("parent", "") == "3d-printing" and p.lang == "en"]
  73. mpages.sort(key=lambda p: int(p["position"]))
  74. for p in mpages:
  75. printMenuItem(p, False, True, True)
  76. def printQuadcopterMenu():
  77. mpages = [p for p in pages if p.get("parent", "") == "quadcopters" and p.lang == "en"]
  78. mpages.sort(key=lambda p: int(p["position"]))
  79. for p in mpages:
  80. printMenuItem(p, False, True, True)
  81. # -----------------------------------------------------------------------------
  82. # lightgallery helper macro
  83. # -----------------------------------------------------------------------------
  84. # call this macro like this
  85. # lightgallery([
  86. # [ "image-link", "description" ],
  87. # [ "image-link", "thumbnail-link", "description" ],
  88. # [ "youtube-link", "thumbnail-link", "description" ],
  89. # [ "video-link", "mime", "thumbnail-link", "image-link", "description" ]
  90. # ])
  91. def lightgallery(links):
  92. videos = [l for l in links if len(l) == 5]
  93. v_i = 0
  94. for v in videos:
  95. link, mime, thumb, poster, alt = v
  96. v_i += 1
  97. print '<div style="display:none;" id="video' + str(v_i) + '">'
  98. print '<video class="lg-video-object lg-html5" controls preload="none">'
  99. print '<source src="' + link + '" type="' + mime + '">'
  100. print 'Your browser does not support HTML5 video.'
  101. print '</video>'
  102. print '</div>'
  103. print '<div class="lightgallery">'
  104. v_i = 0
  105. for l in links:
  106. if (len(l) == 3) or (len(l) == 2):
  107. link = img = alt = ""
  108. if len(l) == 3:
  109. link, img, alt = l
  110. else:
  111. link, alt = l
  112. x = link.rfind('.')
  113. img = link[:x] + '_small' + link[x:]
  114. print '<div class="border" data-src="' + link + '"><a href="' + link + '"><img class="pic" src="' + img + '" alt="' + alt + '"></a></div>'
  115. elif len(l) == 5:
  116. v_i += 1
  117. link, mime, thumb, poster, alt = v
  118. 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>'
  119. else:
  120. raise NameError('Invalid number of arguments for lightgallery')
  121. print '</div>'
  122. # -----------------------------------------------------------------------------
  123. # github helper macros
  124. # -----------------------------------------------------------------------------
  125. import urllib, json
  126. def restRequest(url):
  127. response = urllib.urlopen(url)
  128. data = json.loads(response.read())
  129. return data
  130. def restReleases(user, repo):
  131. s = "https://api.github.com/repos/"
  132. s += user
  133. s += "/"
  134. s += repo
  135. s += "/releases"
  136. return restRequest(s)
  137. def printLatestRelease(user, repo):
  138. repo_url = "https://github.com/" + user + "/" + repo
  139. print("<div class=\"releasecard\">")
  140. print("Release builds for " + repo + " are <a href=\"" + repo_url + "/releases\">available on GitHub</a>.<br>\n")
  141. releases = restReleases(user, repo)
  142. if len(releases) <= 0:
  143. print("No release has been published on GitHub yet.")
  144. print("</div>")
  145. return
  146. releases.sort(key=lambda x: x["published_at"], reverse=True)
  147. r = releases[0]
  148. release_url = r["html_url"]
  149. print("Latest release of <a href=\"" + repo_url + "\">" + repo + "</a>, at the time of this writing: <a href=\"" + release_url + "\">" + r["name"] + "</a> (" + datetime.strptime(r["published_at"], "%Y-%m-%dT%H:%M:%SZ").strftime("%Y-%m-%d %H:%M:%S") + ")\n")
  150. if len(r["assets"]) <= 0:
  151. print("<br>No release assets have been published on GitHub for that.")
  152. print("</div>")
  153. return
  154. print("<ul>")
  155. print("Release Assets:")
  156. for a in r["assets"]:
  157. size = int(a["size"])
  158. ss = " "
  159. if size >= (1024 * 1024):
  160. ss += "(%.1f MiB)" % (size / (1024.0 * 1024.0))
  161. elif size >= 1024:
  162. ss += "(%d KiB)" % (size // 1024)
  163. else:
  164. ss += "(%d Byte)" % (size)
  165. print("<li><a href=\"" + a["browser_download_url"] + "\">" + a["name"] + "</a>" + ss)
  166. print("</ul></div>")
  167. # -----------------------------------------------------------------------------
  168. # preconvert hooks
  169. # -----------------------------------------------------------------------------
  170. def hook_preconvert_anotherlang():
  171. MKD_PATT = r'\.(?:md|mkd|mdown|markdown)$'
  172. _re_lang = re.compile(r'^[\s+]?lang[\s+]?[:=]((?:.|\n )*)', re.MULTILINE)
  173. vpages = [] # Set of all virtual pages
  174. for p in pages:
  175. current_lang = DEFAULT_LANG # Default language
  176. langs = [] # List of languages for the current page
  177. page_vpages = {} # Set of virtual pages for the current page
  178. text_lang = re.split(_re_lang, p.source)
  179. text_grouped = dict(zip([current_lang,] + \
  180. [lang.strip() for lang in text_lang[1::2]], \
  181. text_lang[::2]))
  182. for lang, text in text_grouped.iteritems():
  183. spath = p.fname.split(os.path.sep)
  184. langs.append(lang)
  185. if lang == "en":
  186. filename = re.sub(MKD_PATT, "%s\g<0>" % "", p.fname).split(os.path.sep)[-1]
  187. else:
  188. filename = re.sub(MKD_PATT, ".%s\g<0>" % lang, p.fname).split(os.path.sep)[-1]
  189. vp = Page(filename, virtual=text)
  190. # Copy real page attributes to the virtual page
  191. for attr in p:
  192. if not vp.has_key(attr):
  193. vp[attr] = p[attr]
  194. # Define a title in the proper language
  195. vp["title"] = p["title_%s" % lang] \
  196. if p.has_key("title_%s" % lang) \
  197. else p["title"]
  198. # Keep track of the current lang of the virtual page
  199. vp["lang"] = lang
  200. # Fix post name if exists
  201. if vp.has_key("post"):
  202. if lang == "en":
  203. vp["post"] = vp["post"][:]
  204. else:
  205. vp["post"] = vp["post"][:-len(lang) - 1]
  206. page_vpages[lang] = vp
  207. # Each virtual page has to know about its sister vpages
  208. for lang, vpage in page_vpages.iteritems():
  209. vpage["lang_links"] = dict([(l, v["url"]) for l, v in page_vpages.iteritems()])
  210. vpage["other_lang"] = langs # set other langs and link
  211. vpages += page_vpages.values()
  212. pages[:] = vpages
  213. _COMPAT = """ case "%s":
  214. $loc = "%s/%s";
  215. break;
  216. """
  217. _COMPAT_404 = """ default:
  218. $loc = "%s";
  219. break;
  220. """
  221. def hook_preconvert_compat():
  222. fp = open(os.path.join(options.project, "output", "index.php"), 'w')
  223. fp.write("<?\n")
  224. fp.write("// Auto generated xyCMS compatibility index.php\n")
  225. fp.write("$loc = 'https://www.xythobuz.de/index.de.html';\n")
  226. fp.write("if (isset($_GET['p'])) {\n")
  227. fp.write(" if (isset($_GET['lang'])) {\n")
  228. fp.write(" $_GET['p'] .= 'EN';\n")
  229. fp.write(" }\n")
  230. fp.write(" switch($_GET['p']) {\n")
  231. for p in pages:
  232. if p.get("compat", "") != "":
  233. tmp = p["compat"]
  234. if p.get("lang", DEFAULT_LANG) == DEFAULT_LANG:
  235. tmp = tmp + "EN"
  236. fp.write(_COMPAT % (tmp, "https://www.xythobuz.de", p.url))
  237. fp.write("\n")
  238. fp.write(_COMPAT_404 % "/404.html")
  239. fp.write(" }\n")
  240. fp.write("}\n")
  241. fp.write("if ($_SERVER['SERVER_PROTOCOL'] == 'HTTP/1.1') {\n")
  242. fp.write(" if (php_sapi_name() == 'cgi') {\n")
  243. fp.write(" header('Status: 301 Moved Permanently');\n")
  244. fp.write(" } else {\n")
  245. fp.write(" header('HTTP/1.1 301 Moved Permanently');\n")
  246. fp.write(" }\n")
  247. fp.write("}\n");
  248. fp.write("header('Location: '.$loc);\n")
  249. fp.write("?>")
  250. fp.close()
  251. _SITEMAP = """<?xml version="1.0" encoding="UTF-8"?>
  252. <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  253. %s
  254. </urlset>
  255. """
  256. _SITEMAP_URL = """
  257. <url>
  258. <loc>%s/%s</loc>
  259. <lastmod>%s</lastmod>
  260. <changefreq>%s</changefreq>
  261. <priority>%s</priority>
  262. </url>
  263. """
  264. def hook_preconvert_sitemap():
  265. date = datetime.strftime(datetime.now(), "%Y-%m-%d")
  266. urls = []
  267. for p in pages:
  268. urls.append(_SITEMAP_URL % (BASE_URL, p.url, date, p.get("changefreq", "monthly"), p.get("priority", "0.5")))
  269. fname = os.path.join(options.project, "output", "sitemap.xml")
  270. fp = open(fname, 'w')
  271. fp.write(_SITEMAP % "".join(urls))
  272. fp.close()
  273. # -----------------------------------------------------------------------------
  274. # postconvert hooks
  275. # -----------------------------------------------------------------------------
  276. _RSS = """<?xml version="1.0"?>
  277. <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  278. <channel>
  279. <title>%s</title>
  280. <link>%s</link>
  281. <atom:link href="%s" rel="self" type="application/rss+xml" />
  282. <description>%s</description>
  283. <language>en-us</language>
  284. <pubDate>%s</pubDate>
  285. <lastBuildDate>%s</lastBuildDate>
  286. <docs>http://blogs.law.harvard.edu/tech/rss</docs>
  287. <generator>Poole</generator>
  288. %s
  289. </channel>
  290. </rss>
  291. """
  292. _RSS_ITEM = """
  293. <item>
  294. <title>%s</title>
  295. <link>%s</link>
  296. <description>%s</description>
  297. <pubDate>%s</pubDate>
  298. <guid>%s</guid>
  299. </item>
  300. """
  301. def hook_postconvert_rss():
  302. items = []
  303. posts = [p for p in pages if "date" in p]
  304. posts.sort(key=lambda p: p.date, reverse=True)
  305. posts = posts[:10]
  306. for p in posts:
  307. title = p.title
  308. if "post" in p:
  309. title = p.post
  310. link = "%s/%s" % (BASE_URL, p.url)
  311. desc = p.html.replace("href=\"img", "%s%s%s" % ("href=\"", BASE_URL, "/img"))
  312. desc = desc.replace("src=\"img", "%s%s%s" % ("src=\"", BASE_URL, "/img"))
  313. desc = desc.replace("href=\"/img", "%s%s%s" % ("href=\"", BASE_URL, "/img"))
  314. desc = desc.replace("src=\"/img", "%s%s%s" % ("src=\"", BASE_URL, "/img"))
  315. desc = htmlspecialchars(desc)
  316. date = time.mktime(time.strptime("%s 12" % p.date, "%Y-%m-%d %H"))
  317. date = email.utils.formatdate(date)
  318. items.append(_RSS_ITEM % (title, link, desc, date, link))
  319. items = "".join(items)
  320. title = "xythobuz.de Blog"
  321. link = "%s" % BASE_URL
  322. feed = "%s/rss.xml" % BASE_URL
  323. desc = htmlspecialchars("xythobuz Electronics & Software Projects")
  324. date = email.utils.formatdate()
  325. rss = _RSS % (title, link, feed, desc, date, date, items)
  326. fp = codecs.open(os.path.join(output, "rss.xml"), "w", "utf-8")
  327. fp.write(rss)
  328. fp.close()
  329. _COMPAT_MOB = """ case "%s":
  330. $loc = "%s/%s";
  331. break;
  332. """
  333. _COMPAT_404_MOB = """ default:
  334. $loc = "%s";
  335. break;
  336. """
  337. def hook_postconvert_mobilecompat():
  338. directory = os.path.join(output, "mobile")
  339. if not os.path.exists(directory):
  340. os.makedirs(directory)
  341. fp = codecs.open(os.path.join(directory, "index.php"), "w", "utf-8")
  342. fp.write("<?\n")
  343. fp.write("// Auto generated xyCMS compatibility mobile/index.php\n")
  344. fp.write("$loc = 'https://www.xythobuz.de/index.de.html';\n")
  345. fp.write("if (isset($_GET['p'])) {\n")
  346. fp.write(" if (isset($_GET['lang'])) {\n")
  347. fp.write(" $_GET['p'] .= 'EN';\n")
  348. fp.write(" }\n")
  349. fp.write(" switch($_GET['p']) {\n")
  350. for p in pages:
  351. if p.get("compat", "") != "":
  352. tmp = p["compat"]
  353. if p.get("lang", DEFAULT_LANG) == DEFAULT_LANG:
  354. tmp = tmp + "EN"
  355. fp.write(_COMPAT_MOB % (tmp, "https://www.xythobuz.de", re.sub(".html", ".html", p.url)))
  356. fp.write("\n")
  357. fp.write(_COMPAT_404_MOB % "/404.mob.html")
  358. fp.write(" }\n")
  359. fp.write("}\n")
  360. fp.write("if ($_SERVER['SERVER_PROTOCOL'] == 'HTTP/1.1') {\n")
  361. fp.write(" if (php_sapi_name() == 'cgi') {\n")
  362. fp.write(" header('Status: 301 Moved Permanently');\n")
  363. fp.write(" } else {\n")
  364. fp.write(" header('HTTP/1.1 301 Moved Permanently');\n")
  365. fp.write(" }\n")
  366. fp.write("}\n");
  367. fp.write("header('Location: '.$loc);\n")
  368. fp.write("?>")
  369. fp.close()
  370. def hook_postconvert_size():
  371. file_ext = '|'.join(['pdf', 'zip', 'rar', 'ods', 'odt', 'odp', 'doc', 'xls', 'ppt', 'docx', 'xlsx', 'pptx', 'exe', 'brd', 'mp3', 'mp4', 'plist'])
  372. def matched_link(matchobj):
  373. try:
  374. path = matchobj.group(1)
  375. if path.startswith("http") or path.startswith("//") or path.startswith("ftp"):
  376. return '<a href=\"%s\">%s</a>' % (matchobj.group(1), matchobj.group(3))
  377. elif path.startswith("/"):
  378. path = path.strip("/")
  379. path = os.path.join("static/", path)
  380. size = os.path.getsize(path)
  381. if size >= (1024 * 1024):
  382. return "<a href=\"%s\">%s</a>&nbsp;(%.1f MiB)" % (matchobj.group(1), matchobj.group(3), size / (1024.0 * 1024.0))
  383. elif size >= 1024:
  384. return "<a href=\"%s\">%s</a>&nbsp;(%d KiB)" % (matchobj.group(1), matchobj.group(3), size // 1024)
  385. else:
  386. return "<a href=\"%s\">%s</a>&nbsp;(%d Byte)" % (matchobj.group(1), matchobj.group(3), size)
  387. except:
  388. print "Unable to estimate file size for %s" % matchobj.group(1)
  389. return '<a href=\"%s\">%s</a>' % (matchobj.group(1), matchobj.group(3))
  390. _re_url = '<a href=\"([^\"]*?\.(%s))\">(.*?)<\/a>' % file_ext
  391. for p in pages:
  392. p.html = re.sub(_re_url, matched_link, p.html)