My static website generator using poole https://www.xythobuz.de
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

macros.py 19KB

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