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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  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. import urlparse
  10. DEFAULT_LANG = "en"
  11. BASE_URL = "https://www.xythobuz.de"
  12. # -----------------------------------------------------------------------------
  13. # sub page helper macro
  14. # -----------------------------------------------------------------------------
  15. def backToParent():
  16. # check for special parent cases
  17. posts = []
  18. if page.get("show_in_quadcopters", "false") == "true":
  19. posts = [p for p in pages if p.url == "quadcopters.html"]
  20. # if not, check for actual parent
  21. if len(posts) == 0:
  22. url = page.get("parent", "") + ".html"
  23. posts = [p for p in pages if p.url == url]
  24. # print if any parent link found
  25. if len(posts) > 0:
  26. p = posts[0]
  27. print '<span class="listdesc">[...back to ' + p.title + ' overview](' + p.url + ')</span>'
  28. # -----------------------------------------------------------------------------
  29. # table helper macro
  30. # -----------------------------------------------------------------------------
  31. def tableHelper(style, header, content):
  32. print "<table>"
  33. if (header != None) and (len(header) == len(style)):
  34. print "<tr>"
  35. for h in header:
  36. print "<th>" + h + "</th>"
  37. print "</tr>"
  38. for ci in range(0, len(content)):
  39. if len(content[ci]) != len(style):
  40. # invalid call of table helper!
  41. continue
  42. print "<tr>"
  43. for i in range(0, len(style)):
  44. s = style[i]
  45. td_style = ""
  46. if "monospaced" in s:
  47. td_style += " font-family: monospace;"
  48. if "align-last-right" in s:
  49. if ci == (len(content) - 1):
  50. td_style += " text-align: right;"
  51. else:
  52. if "align-center" in s:
  53. td_style += " text-align: center;"
  54. elif "align-right" in s:
  55. td_style += " text-align: right;"
  56. elif "align-center" in s:
  57. td_style += " text-align: center;"
  58. td_args = ""
  59. if td_style != "":
  60. td_args = " style=\"" + td_style + "\""
  61. print "<td" + td_args + ">"
  62. if isinstance(content[ci][i], tuple):
  63. text, link = content[ci][i]
  64. print "<a href=\"" + link + "\">" + text + "</a>"
  65. else:
  66. text = content[ci][i]
  67. print text
  68. print "</td>"
  69. print "</tr>"
  70. print "</table>"
  71. # -----------------------------------------------------------------------------
  72. # menu helper macro
  73. # -----------------------------------------------------------------------------
  74. def githubCommitBadge(p, showInline = False):
  75. ret = ""
  76. if p.get("github", "") != "":
  77. link = p.get("git", p.github)
  78. linkParts = p.github.split("/")
  79. if len(linkParts) >= 5:
  80. ret += "<a href=\"" + link + "\"><img "
  81. if showInline:
  82. ret += "style =\"vertical-align: top;\" "
  83. ret += "src=\"https://img.shields.io/github/last-commit/"
  84. ret += linkParts[3] + "/" + linkParts[4]
  85. ret += ".svg?logo=git&style=flat\" /></a>"
  86. return ret
  87. def printMenuItem(p, yearsAsHeading = False, showDateSpan = False, showOnlyStartDate = False, nicelyFormatFullDate = False, lastyear = "0", lang = "", showLastCommit = True):
  88. title = p.title
  89. if lang != "":
  90. if p.get("title_" + lang, "") != "":
  91. title = p.get("title_" + lang, "")
  92. if title == "Blog":
  93. title = p.post
  94. year = p.get("date", "")[0:4]
  95. if year != lastyear:
  96. lastyear = year
  97. if yearsAsHeading:
  98. print "\n\n#### %s\n" % (year)
  99. dateto = ""
  100. if p.get("date", "" != ""):
  101. year = p.get("date", "")[0:4]
  102. if showOnlyStartDate:
  103. dateto = " (%s)" % (year)
  104. if p.get("update", "") != "" and p.get("update", "")[0:4] != year:
  105. if showDateSpan:
  106. dateto = " (%s - %s)" % (year, p.get("update", "")[0:4])
  107. if nicelyFormatFullDate:
  108. dateto = " - " + datetime.strptime(p.get("update", p.date), "%Y-%m-%d").strftime("%B %d, %Y")
  109. print " * **[%s](%s)**%s" % (title, p.url, dateto)
  110. if p.get("description", "") != "":
  111. description = p.get("description", "")
  112. if lang != "":
  113. if p.get("description_" + lang, "") != "":
  114. description = p.get("description_" + lang, "")
  115. print "<br><span class=\"listdesc\">" + description + "</span>"
  116. if showLastCommit:
  117. link = githubCommitBadge(p)
  118. if len(link) > 0:
  119. print "<br>" + link
  120. return lastyear
  121. def printRecentMenu(count = 5):
  122. posts = [p for p in pages if "date" in p and p.lang == "en"]
  123. posts.sort(key=lambda p: p.get("update", p.get("date")), reverse=True)
  124. if count > 0:
  125. posts = posts[0:count]
  126. for p in posts:
  127. printMenuItem(p, False, False, False, True, "0", "", False)
  128. def printBlogMenu():
  129. posts = [p for p in pages if "post" in p and p.lang == "en"]
  130. posts.sort(key=lambda p: p.get("date", "9999-01-01"), reverse=True)
  131. lastyear = "0"
  132. for p in posts:
  133. lastyear = printMenuItem(p, True, False, False, True, lastyear)
  134. def printProjectsMenu():
  135. # prints all pages with parent 'projects' or 'stuff'.
  136. # first the ones without date, sorted by position.
  137. # then afterwards those with date, split by year.
  138. # also supports blog posts with parent.
  139. enpages = [p for p in pages if p.lang == "en"]
  140. dpages = [p for p in enpages if p.get("date", "") == ""]
  141. mpages = [p for p in dpages if any(x in p.get("parent", "") for x in [ 'projects', 'stuff' ])]
  142. mpages.sort(key=lambda p: [int(p.get("position", "999"))])
  143. for p in mpages:
  144. printMenuItem(p)
  145. dpages = [p for p in enpages if p.get("date", "") != ""]
  146. mpages = [p for p in dpages if any(x in p.get("parent", "") for x in [ 'projects', 'stuff' ])]
  147. mpages.sort(key=lambda p: [p.get("date", "9999-01-01")], reverse = True)
  148. lastyear = "0"
  149. for p in mpages:
  150. lastyear = printMenuItem(p, True, True, False, False, lastyear)
  151. def print3DPrintingMenu():
  152. mpages = [p for p in pages if p.get("parent", "") == "3d-printing" and p.lang == "en"]
  153. mpages.sort(key=lambda p: int(p["position"]))
  154. for p in mpages:
  155. printMenuItem(p, False, True, True)
  156. def printInputDevicesMenu():
  157. mpages = [p for p in pages if p.get("parent", "") == "input_devices" and p.lang == "en"]
  158. mpages.sort(key=lambda p: [p.get("date", "9999-01-01")], reverse = True)
  159. for p in mpages:
  160. printMenuItem(p, False, True, True)
  161. def printInputDevicesRelatedMenu():
  162. mpages = [p for p in pages if p.get("show_in_input_devices", "false") == "true"]
  163. mpages.sort(key=lambda p: [p.get("date", "9999-01-01")], reverse = True)
  164. for p in mpages:
  165. printMenuItem(p, False, True, True)
  166. def printSmarthomeMenu():
  167. mpages = [p for p in pages if p.get("parent", "") == "smarthome" and p.lang == "en"]
  168. mpages.sort(key=lambda p: int(p["position"]))
  169. for p in mpages:
  170. printMenuItem(p, False, True, True)
  171. def printQuadcopterMenu():
  172. mpages = [p for p in pages if p.get("parent", "") == "quadcopters" and p.lang == "en"]
  173. mpages.sort(key=lambda p: int(p["position"]))
  174. for p in mpages:
  175. printMenuItem(p, False, True, True)
  176. def printQuadcopterRelatedMenu():
  177. mpages = [p for p in pages if p.get("show_in_quadcopters", "false") == "true"]
  178. mpages.sort(key=lambda p: [p.get("date", "9999-01-01")], reverse = True)
  179. for p in mpages:
  180. printMenuItem(p, False, True, True)
  181. def printRobotMenuEnglish():
  182. mpages = [p for p in pages if p.get("parent", "") == "xyrobot" and p.lang == "en"]
  183. mpages.sort(key=lambda p: int(p["position"]))
  184. for p in mpages:
  185. printMenuItem(p)
  186. def printRobotMenuDeutsch():
  187. mpages = [p for p in pages if p.get("parent", "") == "xyrobot" and p.lang == "de"]
  188. mpages.sort(key=lambda p: int(p["position"]))
  189. for p in mpages:
  190. printMenuItem(p, False, False, False, False, "0", "de")
  191. def printSteamMenuEnglish():
  192. mpages = [p for p in pages if p.get("parent", "") == "steam" and p.lang == "en"]
  193. mpages.sort(key=lambda p: [p.get("date", "9999-01-01")], reverse = True)
  194. for p in mpages:
  195. printMenuItem(p, False, False, False, True)
  196. def printSteamMenuDeutsch():
  197. # TODO show german pages, or english pages when german not available
  198. printSteamMenuEnglish()
  199. # -----------------------------------------------------------------------------
  200. # lightgallery helper macro
  201. # -----------------------------------------------------------------------------
  202. # call this macro like this:
  203. # lightgallery([
  204. # [ "image-link", "description" ],
  205. # [ "image-link", "thumbnail-link", "description" ],
  206. # [ "youtube-link", "thumbnail-link", "description" ],
  207. # [ "video-link", "mime", "thumbnail-link", "image-link", "description" ],
  208. # [ "video-link", "mime", "", "", "description" ],
  209. # ])
  210. # it will also auto-generate thumbnails and resize and strip EXIF from images
  211. # using the included web-image-resize script.
  212. # and it can generate video thumbnails and posters with the video-thumb script.
  213. def lightgallery_check_thumbnail(link, thumb):
  214. # only check local image links
  215. if not link.startswith('img/'):
  216. return
  217. # generate thumbnail filename web-image-resize will create
  218. x = link.rfind('.')
  219. img = link[:x] + '_small' + link[x:]
  220. # only run when desired thumb path matches calculated ones
  221. if thumb != img:
  222. return
  223. # generate fs path to images
  224. path = os.path.join(os.getcwd(), 'static', link)
  225. img = os.path.join(os.getcwd(), 'static', thumb)
  226. # no need to generate thumb again
  227. if os.path.exists(img):
  228. return
  229. # run web-image-resize to generate thumbnail
  230. script = os.path.join(os.getcwd(), 'web-image-resize')
  231. os.system(script + ' ' + path)
  232. def lightgallery_check_thumbnail_video(link, thumb, poster):
  233. # only check local image links
  234. if not link.startswith('img/'):
  235. return
  236. # generate thumbnail filenames video-thumb will create
  237. x = link.rfind('.')
  238. thumb_l = link[:x] + '_thumb.png'
  239. poster_l = link[:x] + '_poster.png'
  240. # only run when desired thumb path matches calculated ones
  241. if (thumb_l != thumb) or (poster_l != poster):
  242. return
  243. # generate fs path to images
  244. path = os.path.join(os.getcwd(), 'static', link)
  245. thumb_p = os.path.join(os.getcwd(), 'static', thumb)
  246. poster_p = os.path.join(os.getcwd(), 'static', poster)
  247. # no need to generate thumb again
  248. if os.path.exists(thumb_p) or os.path.exists(poster_p):
  249. return
  250. # run video-thumb to generate thumbnail
  251. script = os.path.join(os.getcwd(), 'video-thumb')
  252. os.system(script + ' ' + path)
  253. def lightgallery(links):
  254. global v_ii
  255. try:
  256. v_ii += 1
  257. except NameError:
  258. v_ii = 0
  259. videos = [l for l in links if len(l) == 5]
  260. v_i = -1
  261. for v in videos:
  262. link, mime, thumb, poster, alt = v
  263. v_i += 1
  264. print '<div style="display:none;" id="video' + str(v_i) + '_' + str(v_ii) + '">'
  265. print '<video class="lg-video-object lg-html5" controls preload="none">'
  266. print '<source src="' + link + '" type="' + mime + '">'
  267. print '<a href="' + link + '">' + alt + '</a>'
  268. print '</video>'
  269. print '</div>'
  270. print '<div class="lightgallery">'
  271. v_i = -1
  272. for l in links:
  273. if (len(l) == 3) or (len(l) == 2):
  274. link = img = alt = ""
  275. style = img2 = ""
  276. if len(l) == 3:
  277. link, img, alt = l
  278. else:
  279. link, alt = l
  280. if "youtube.com" in link:
  281. img = "https://img.youtube.com/vi/"
  282. img += urlparse.parse_qs(urlparse.urlparse(link).query)['v'][0]
  283. img += "/0.jpg" # full size preview
  284. #img += "/default.jpg" # default thumbnail
  285. style = ' style="width:300px;"'
  286. img2 = '<img src="lg/video-play.png" class="picthumb">'
  287. else:
  288. x = link.rfind('.')
  289. img = link[:x] + '_small' + link[x:]
  290. lightgallery_check_thumbnail(link, img)
  291. print '<div class="border" style="position:relative;" data-src="' + link + '"><a href="' + link + '"><img class="pic" src="' + img + '" alt="' + alt + '"' + style + '>' + img2 + '</a></div>'
  292. elif len(l) == 5:
  293. v_i += 1
  294. link, mime, thumb, poster, alt = videos[v_i]
  295. if len(thumb) <= 0:
  296. x = link.rfind('.')
  297. thumb = link[:x] + '_thumb.png'
  298. if len(poster) <= 0:
  299. x = link.rfind('.')
  300. poster = link[:x] + '_poster.png'
  301. lightgallery_check_thumbnail_video(link, thumb, poster)
  302. print '<div class="border" data-poster="' + poster + '" data-sub-html="' + alt + '" data-html="#video' + str(v_i) + '_' + str(v_ii) + '"><a href="' + link + '"><img class="pic" src="' + thumb + '"></a></div>'
  303. else:
  304. raise NameError('Invalid number of arguments for lightgallery')
  305. print '</div>'
  306. # -----------------------------------------------------------------------------
  307. # github helper macros
  308. # -----------------------------------------------------------------------------
  309. import urllib, json, sys
  310. def restRequest(url):
  311. response = urllib.urlopen(url)
  312. if response.getcode() != 200:
  313. sys.stderr.write("\n")
  314. sys.stderr.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")
  315. sys.stderr.write("!!!!!!! WARNING !!!!!\n")
  316. sys.stderr.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")
  317. sys.stderr.write("invalid response code: " + str(response.getcode()) + "\n")
  318. sys.stderr.write("url: \"" + url + "\"\n")
  319. sys.stderr.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")
  320. sys.stderr.write("!!!!!!! WARNING !!!!!\n")
  321. sys.stderr.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")
  322. sys.stderr.write("\n")
  323. return ""
  324. data = json.loads(response.read())
  325. return data
  326. def restReleases(user, repo):
  327. s = "https://api.github.com/repos/"
  328. s += user
  329. s += "/"
  330. s += repo
  331. s += "/releases"
  332. return restRequest(s)
  333. def printLatestRelease(user, repo):
  334. repo_url = "https://github.com/" + user + "/" + repo
  335. print("<div class=\"releasecard\">")
  336. print("Release builds for " + repo + " are <a href=\"" + repo_url + "/releases\">available on GitHub</a>.<br>\n")
  337. releases = restReleases(user, repo)
  338. if len(releases) <= 0:
  339. print("No release has been published on GitHub yet.")
  340. print("</div>")
  341. return
  342. releases.sort(key=lambda x: x["published_at"], reverse=True)
  343. r = releases[0]
  344. release_url = r["html_url"]
  345. 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")
  346. if len(r["assets"]) <= 0:
  347. print("<br>No release assets have been published on GitHub for that.")
  348. print("</div>")
  349. return
  350. print("<ul>")
  351. print("Release Assets:")
  352. for a in r["assets"]:
  353. size = int(a["size"])
  354. ss = " "
  355. if size >= (1024 * 1024):
  356. ss += "(%.1f MiB)" % (size / (1024.0 * 1024.0))
  357. elif size >= 1024:
  358. ss += "(%d KiB)" % (size // 1024)
  359. else:
  360. ss += "(%d Byte)" % (size)
  361. print("<li><a href=\"" + a["browser_download_url"] + "\">" + a["name"] + "</a>" + ss)
  362. print("</ul></div>")
  363. def include_url(url):
  364. response = urllib.urlopen(url)
  365. if response.getcode() != 200:
  366. raise Exception("invalid response code", response.getcode())
  367. data = response.read()
  368. print data,
  369. # -----------------------------------------------------------------------------
  370. # preconvert hooks
  371. # -----------------------------------------------------------------------------
  372. # -----------------------------------------------------------------------------
  373. # multi language support
  374. # -----------------------------------------------------------------------------
  375. def hook_preconvert_anotherlang():
  376. MKD_PATT = r'\.(?:md|mkd|mdown|markdown)$'
  377. _re_lang = re.compile(r'^[\s+]?lang[\s+]?[:=]((?:.|\n )*)', re.MULTILINE)
  378. vpages = [] # Set of all virtual pages
  379. for p in pages:
  380. current_lang = DEFAULT_LANG # Default language
  381. langs = [] # List of languages for the current page
  382. page_vpages = {} # Set of virtual pages for the current page
  383. text_lang = re.split(_re_lang, p.source)
  384. text_grouped = dict(zip([current_lang,] + \
  385. [lang.strip() for lang in text_lang[1::2]], \
  386. text_lang[::2]))
  387. for lang, text in text_grouped.iteritems():
  388. spath = p.fname.split(os.path.sep)
  389. langs.append(lang)
  390. if lang == "en":
  391. filename = re.sub(MKD_PATT, "%s\g<0>" % "", p.fname).split(os.path.sep)[-1]
  392. else:
  393. filename = re.sub(MKD_PATT, ".%s\g<0>" % lang, p.fname).split(os.path.sep)[-1]
  394. vp = Page(filename, virtual=text)
  395. # Copy real page attributes to the virtual page
  396. for attr in p:
  397. if not vp.has_key(attr):
  398. vp[attr] = p[attr]
  399. # Define a title in the proper language
  400. vp["title"] = p["title_%s" % lang] \
  401. if p.has_key("title_%s" % lang) \
  402. else p["title"]
  403. # Keep track of the current lang of the virtual page
  404. vp["lang"] = lang
  405. page_vpages[lang] = vp
  406. # Each virtual page has to know about its sister vpages
  407. for lang, vpage in page_vpages.iteritems():
  408. vpage["lang_links"] = dict([(l, v["url"]) for l, v in page_vpages.iteritems()])
  409. vpage["other_lang"] = langs # set other langs and link
  410. vpages += page_vpages.values()
  411. pages[:] = vpages
  412. # -----------------------------------------------------------------------------
  413. # compatibility redirect for old website URLs
  414. # -----------------------------------------------------------------------------
  415. _COMPAT = """ case "%s":
  416. $loc = "%s/%s";
  417. break;
  418. """
  419. _COMPAT_404 = """ default:
  420. $loc = "%s";
  421. break;
  422. """
  423. def hook_preconvert_compat():
  424. fp = open(os.path.join(options.project, "output", "index.php"), 'w')
  425. fp.write("<?\n")
  426. fp.write("// Auto generated xyCMS compatibility index.php\n")
  427. fp.write("$loc = 'https://www.xythobuz.de/index.de.html';\n")
  428. fp.write("if (isset($_GET['p'])) {\n")
  429. fp.write(" if (isset($_GET['lang'])) {\n")
  430. fp.write(" $_GET['p'] .= 'EN';\n")
  431. fp.write(" }\n")
  432. fp.write(" switch($_GET['p']) {\n")
  433. for p in pages:
  434. if p.get("compat", "") != "":
  435. tmp = p["compat"]
  436. if p.get("lang", DEFAULT_LANG) == DEFAULT_LANG:
  437. tmp = tmp + "EN"
  438. fp.write(_COMPAT % (tmp, "https://www.xythobuz.de", p.url))
  439. fp.write("\n")
  440. fp.write(_COMPAT_404 % "/404.html")
  441. fp.write(" }\n")
  442. fp.write("}\n")
  443. fp.write("if ($_SERVER['SERVER_PROTOCOL'] == 'HTTP/1.1') {\n")
  444. fp.write(" if (php_sapi_name() == 'cgi') {\n")
  445. fp.write(" header('Status: 301 Moved Permanently');\n")
  446. fp.write(" } else {\n")
  447. fp.write(" header('HTTP/1.1 301 Moved Permanently');\n")
  448. fp.write(" }\n")
  449. fp.write("}\n");
  450. fp.write("header('Location: '.$loc);\n")
  451. fp.write("?>")
  452. fp.close()
  453. # -----------------------------------------------------------------------------
  454. # sitemap generation
  455. # -----------------------------------------------------------------------------
  456. _SITEMAP = """<?xml version="1.0" encoding="UTF-8"?>
  457. <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  458. %s
  459. </urlset>
  460. """
  461. _SITEMAP_URL = """
  462. <url>
  463. <loc>%s/%s</loc>
  464. <lastmod>%s</lastmod>
  465. <changefreq>%s</changefreq>
  466. <priority>%s</priority>
  467. </url>
  468. """
  469. def hook_preconvert_sitemap():
  470. date = datetime.strftime(datetime.now(), "%Y-%m-%d")
  471. urls = []
  472. for p in pages:
  473. urls.append(_SITEMAP_URL % (BASE_URL, p.url, date, p.get("changefreq", "monthly"), p.get("priority", "0.5")))
  474. fname = os.path.join(options.project, "output", "sitemap.xml")
  475. fp = open(fname, 'w')
  476. fp.write(_SITEMAP % "".join(urls))
  477. fp.close()
  478. # -----------------------------------------------------------------------------
  479. # postconvert hooks
  480. # -----------------------------------------------------------------------------
  481. # -----------------------------------------------------------------------------
  482. # rss feed generation
  483. # -----------------------------------------------------------------------------
  484. _RSS = """<?xml version="1.0" encoding="UTF-8"?>
  485. <?xml-stylesheet href="%s" type="text/xsl"?>
  486. <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  487. <channel>
  488. <title>%s</title>
  489. <link>%s</link>
  490. <atom:link href="%s" rel="self" type="application/rss+xml" />
  491. <description>%s</description>
  492. <language>en-us</language>
  493. <pubDate>%s</pubDate>
  494. <lastBuildDate>%s</lastBuildDate>
  495. <docs>http://blogs.law.harvard.edu/tech/rss</docs>
  496. <generator>Poole</generator>
  497. <ttl>720</ttl>
  498. %s
  499. </channel>
  500. </rss>
  501. """
  502. _RSS_ITEM = """
  503. <item>
  504. <title>%s</title>
  505. <link>%s</link>
  506. <description>%s</description>
  507. <pubDate>%s</pubDate>
  508. <atom:updated>%s</atom:updated>
  509. <guid>%s</guid>
  510. </item>
  511. """
  512. def hook_postconvert_rss():
  513. items = []
  514. # all pages with "date" get put into feed
  515. posts = [p for p in pages if "date" in p]
  516. # sort by update if available, date else
  517. posts.sort(key=lambda p: p.get("update", p.date), reverse=True)
  518. # only put 20 most recent items in feed
  519. posts = posts[:20]
  520. for p in posts:
  521. title = p.title
  522. if "post" in p:
  523. title = p.post
  524. link = "%s/%s" % (BASE_URL, p.url)
  525. desc = p.html.replace("href=\"img", "%s%s%s" % ("href=\"", BASE_URL, "/img"))
  526. desc = desc.replace("src=\"img", "%s%s%s" % ("src=\"", BASE_URL, "/img"))
  527. desc = desc.replace("href=\"/img", "%s%s%s" % ("href=\"", BASE_URL, "/img"))
  528. desc = desc.replace("src=\"/img", "%s%s%s" % ("src=\"", BASE_URL, "/img"))
  529. desc = htmlspecialchars(desc)
  530. date = time.mktime(time.strptime("%s 12" % p.date, "%Y-%m-%d %H"))
  531. date = email.utils.formatdate(date)
  532. update = time.mktime(time.strptime("%s 12" % p.get("update", p.date), "%Y-%m-%d %H"))
  533. update = email.utils.formatdate(update)
  534. items.append(_RSS_ITEM % (title, link, desc, date, update, link))
  535. items = "".join(items)
  536. style = "/css/rss.xsl"
  537. title = "xythobuz.de Blog"
  538. link = "%s" % BASE_URL
  539. feed = "%s/rss.xml" % BASE_URL
  540. desc = htmlspecialchars("xythobuz Electronics & Software Projects")
  541. date = email.utils.formatdate()
  542. rss = _RSS % (style, title, link, feed, desc, date, date, items)
  543. fp = codecs.open(os.path.join(output, "rss.xml"), "w", "utf-8")
  544. fp.write(rss)
  545. fp.close()
  546. # -----------------------------------------------------------------------------
  547. # compatibility redirect for old mobile pages
  548. # -----------------------------------------------------------------------------
  549. _COMPAT_MOB = """ case "%s":
  550. $loc = "%s/%s";
  551. break;
  552. """
  553. _COMPAT_404_MOB = """ default:
  554. $loc = "%s";
  555. break;
  556. """
  557. def hook_postconvert_mobilecompat():
  558. directory = os.path.join(output, "mobile")
  559. if not os.path.exists(directory):
  560. os.makedirs(directory)
  561. fp = codecs.open(os.path.join(directory, "index.php"), "w", "utf-8")
  562. fp.write("<?\n")
  563. fp.write("// Auto generated xyCMS compatibility mobile/index.php\n")
  564. fp.write("$loc = 'https://www.xythobuz.de/index.de.html';\n")
  565. fp.write("if (isset($_GET['p'])) {\n")
  566. fp.write(" if (isset($_GET['lang'])) {\n")
  567. fp.write(" $_GET['p'] .= 'EN';\n")
  568. fp.write(" }\n")
  569. fp.write(" switch($_GET['p']) {\n")
  570. for p in pages:
  571. if p.get("compat", "") != "":
  572. tmp = p["compat"]
  573. if p.get("lang", DEFAULT_LANG) == DEFAULT_LANG:
  574. tmp = tmp + "EN"
  575. fp.write(_COMPAT_MOB % (tmp, "https://www.xythobuz.de", re.sub(".html", ".html", p.url)))
  576. fp.write("\n")
  577. fp.write(_COMPAT_404_MOB % "/404.mob.html")
  578. fp.write(" }\n")
  579. fp.write("}\n")
  580. fp.write("if ($_SERVER['SERVER_PROTOCOL'] == 'HTTP/1.1') {\n")
  581. fp.write(" if (php_sapi_name() == 'cgi') {\n")
  582. fp.write(" header('Status: 301 Moved Permanently');\n")
  583. fp.write(" } else {\n")
  584. fp.write(" header('HTTP/1.1 301 Moved Permanently');\n")
  585. fp.write(" }\n")
  586. fp.write("}\n");
  587. fp.write("header('Location: '.$loc);\n")
  588. fp.write("?>")
  589. fp.close()
  590. # -----------------------------------------------------------------------------
  591. # displaying filesize for download links
  592. # -----------------------------------------------------------------------------
  593. def hook_postconvert_size():
  594. file_ext = '|'.join(['pdf', 'zip', 'rar', 'ods', 'odt', 'odp', 'doc', 'xls', 'ppt', 'docx', 'xlsx', 'pptx', 'exe', 'brd', 'plist'])
  595. def matched_link(matchobj):
  596. try:
  597. path = matchobj.group(1)
  598. if path.startswith("http") or path.startswith("//") or path.startswith("ftp"):
  599. return '<a href=\"%s\">%s</a>' % (matchobj.group(1), matchobj.group(3))
  600. elif path.startswith("/"):
  601. path = path.strip("/")
  602. path = os.path.join("static/", path)
  603. size = os.path.getsize(path)
  604. if size >= (1024 * 1024):
  605. return "<a href=\"%s\">%s</a>&nbsp;(%.1f MiB)" % (matchobj.group(1), matchobj.group(3), size / (1024.0 * 1024.0))
  606. elif size >= 1024:
  607. return "<a href=\"%s\">%s</a>&nbsp;(%d KiB)" % (matchobj.group(1), matchobj.group(3), size // 1024)
  608. else:
  609. return "<a href=\"%s\">%s</a>&nbsp;(%d Byte)" % (matchobj.group(1), matchobj.group(3), size)
  610. except:
  611. print "Unable to estimate file size for %s" % matchobj.group(1)
  612. return '<a href=\"%s\">%s</a>' % (matchobj.group(1), matchobj.group(3))
  613. _re_url = '<a href=\"([^\"]*?\.(%s))\">(.*?)<\/a>' % file_ext
  614. for p in pages:
  615. p.html = re.sub(_re_url, matched_link, p.html)