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

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