My static website generator using poole https://www.xythobuz.de
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

macros.py 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  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. videos = [l for l in links if len(l) == 5]
  255. v_i = -1
  256. for v in videos:
  257. link, mime, thumb, poster, alt = v
  258. v_i += 1
  259. print '<div style="display:none;" id="video' + str(v_i) + '">'
  260. print '<video class="lg-video-object lg-html5" controls preload="none">'
  261. print '<source src="' + link + '" type="' + mime + '">'
  262. print 'Your browser does not support HTML5 video.'
  263. print '</video>'
  264. print '</div>'
  265. print '<div class="lightgallery">'
  266. v_i = -1
  267. for l in links:
  268. if (len(l) == 3) or (len(l) == 2):
  269. link = img = alt = ""
  270. style = img2 = ""
  271. if len(l) == 3:
  272. link, img, alt = l
  273. else:
  274. link, alt = l
  275. if "youtube.com" in link:
  276. img = "https://img.youtube.com/vi/"
  277. img += urlparse.parse_qs(urlparse.urlparse(link).query)['v'][0]
  278. img += "/0.jpg" # full size preview
  279. #img += "/default.jpg" # default thumbnail
  280. style = ' style="width:300px;"'
  281. img2 = '<img src="lg/video-play.png" class="picthumb">'
  282. else:
  283. x = link.rfind('.')
  284. img = link[:x] + '_small' + link[x:]
  285. lightgallery_check_thumbnail(link, img)
  286. print '<div class="border" style="position:relative;" data-src="' + link + '"><a href="' + link + '"><img class="pic" src="' + img + '" alt="' + alt + '"' + style + '>' + img2 + '</a></div>'
  287. elif len(l) == 5:
  288. v_i += 1
  289. link, mime, thumb, poster, alt = videos[v_i]
  290. if len(thumb) <= 0:
  291. x = link.rfind('.')
  292. thumb = link[:x] + '_thumb.png'
  293. if len(poster) <= 0:
  294. x = link.rfind('.')
  295. poster = link[:x] + '_poster.png'
  296. lightgallery_check_thumbnail_video(link, thumb, poster)
  297. 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>'
  298. else:
  299. raise NameError('Invalid number of arguments for lightgallery')
  300. print '</div>'
  301. # -----------------------------------------------------------------------------
  302. # github helper macros
  303. # -----------------------------------------------------------------------------
  304. import urllib, json, sys
  305. def restRequest(url):
  306. response = urllib.urlopen(url)
  307. if response.getcode() != 200:
  308. sys.stderr.write("\n")
  309. sys.stderr.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")
  310. sys.stderr.write("!!!!!!! WARNING !!!!!\n")
  311. sys.stderr.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")
  312. sys.stderr.write("invalid response code: " + str(response.getcode()) + "\n")
  313. sys.stderr.write("url: \"" + url + "\"\n")
  314. sys.stderr.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")
  315. sys.stderr.write("!!!!!!! WARNING !!!!!\n")
  316. sys.stderr.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")
  317. sys.stderr.write("\n")
  318. return ""
  319. data = json.loads(response.read())
  320. return data
  321. def restReleases(user, repo):
  322. s = "https://api.github.com/repos/"
  323. s += user
  324. s += "/"
  325. s += repo
  326. s += "/releases"
  327. return restRequest(s)
  328. def printLatestRelease(user, repo):
  329. repo_url = "https://github.com/" + user + "/" + repo
  330. print("<div class=\"releasecard\">")
  331. print("Release builds for " + repo + " are <a href=\"" + repo_url + "/releases\">available on GitHub</a>.<br>\n")
  332. releases = restReleases(user, repo)
  333. if len(releases) <= 0:
  334. print("No release has been published on GitHub yet.")
  335. print("</div>")
  336. return
  337. releases.sort(key=lambda x: x["published_at"], reverse=True)
  338. r = releases[0]
  339. release_url = r["html_url"]
  340. 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")
  341. if len(r["assets"]) <= 0:
  342. print("<br>No release assets have been published on GitHub for that.")
  343. print("</div>")
  344. return
  345. print("<ul>")
  346. print("Release Assets:")
  347. for a in r["assets"]:
  348. size = int(a["size"])
  349. ss = " "
  350. if size >= (1024 * 1024):
  351. ss += "(%.1f MiB)" % (size / (1024.0 * 1024.0))
  352. elif size >= 1024:
  353. ss += "(%d KiB)" % (size // 1024)
  354. else:
  355. ss += "(%d Byte)" % (size)
  356. print("<li><a href=\"" + a["browser_download_url"] + "\">" + a["name"] + "</a>" + ss)
  357. print("</ul></div>")
  358. def include_url(url):
  359. response = urllib.urlopen(url)
  360. if response.getcode() != 200:
  361. raise Exception("invalid response code", response.getcode())
  362. data = response.read()
  363. print data,
  364. # -----------------------------------------------------------------------------
  365. # preconvert hooks
  366. # -----------------------------------------------------------------------------
  367. # -----------------------------------------------------------------------------
  368. # multi language support
  369. # -----------------------------------------------------------------------------
  370. def hook_preconvert_anotherlang():
  371. MKD_PATT = r'\.(?:md|mkd|mdown|markdown)$'
  372. _re_lang = re.compile(r'^[\s+]?lang[\s+]?[:=]((?:.|\n )*)', re.MULTILINE)
  373. vpages = [] # Set of all virtual pages
  374. for p in pages:
  375. current_lang = DEFAULT_LANG # Default language
  376. langs = [] # List of languages for the current page
  377. page_vpages = {} # Set of virtual pages for the current page
  378. text_lang = re.split(_re_lang, p.source)
  379. text_grouped = dict(zip([current_lang,] + \
  380. [lang.strip() for lang in text_lang[1::2]], \
  381. text_lang[::2]))
  382. for lang, text in text_grouped.iteritems():
  383. spath = p.fname.split(os.path.sep)
  384. langs.append(lang)
  385. if lang == "en":
  386. filename = re.sub(MKD_PATT, "%s\g<0>" % "", p.fname).split(os.path.sep)[-1]
  387. else:
  388. filename = re.sub(MKD_PATT, ".%s\g<0>" % lang, p.fname).split(os.path.sep)[-1]
  389. vp = Page(filename, virtual=text)
  390. # Copy real page attributes to the virtual page
  391. for attr in p:
  392. if not vp.has_key(attr):
  393. vp[attr] = p[attr]
  394. # Define a title in the proper language
  395. vp["title"] = p["title_%s" % lang] \
  396. if p.has_key("title_%s" % lang) \
  397. else p["title"]
  398. # Keep track of the current lang of the virtual page
  399. vp["lang"] = lang
  400. page_vpages[lang] = vp
  401. # Each virtual page has to know about its sister vpages
  402. for lang, vpage in page_vpages.iteritems():
  403. vpage["lang_links"] = dict([(l, v["url"]) for l, v in page_vpages.iteritems()])
  404. vpage["other_lang"] = langs # set other langs and link
  405. vpages += page_vpages.values()
  406. pages[:] = vpages
  407. # -----------------------------------------------------------------------------
  408. # compatibility redirect for old website URLs
  409. # -----------------------------------------------------------------------------
  410. _COMPAT = """ case "%s":
  411. $loc = "%s/%s";
  412. break;
  413. """
  414. _COMPAT_404 = """ default:
  415. $loc = "%s";
  416. break;
  417. """
  418. def hook_preconvert_compat():
  419. fp = open(os.path.join(options.project, "output", "index.php"), 'w')
  420. fp.write("<?\n")
  421. fp.write("// Auto generated xyCMS compatibility index.php\n")
  422. fp.write("$loc = 'https://www.xythobuz.de/index.de.html';\n")
  423. fp.write("if (isset($_GET['p'])) {\n")
  424. fp.write(" if (isset($_GET['lang'])) {\n")
  425. fp.write(" $_GET['p'] .= 'EN';\n")
  426. fp.write(" }\n")
  427. fp.write(" switch($_GET['p']) {\n")
  428. for p in pages:
  429. if p.get("compat", "") != "":
  430. tmp = p["compat"]
  431. if p.get("lang", DEFAULT_LANG) == DEFAULT_LANG:
  432. tmp = tmp + "EN"
  433. fp.write(_COMPAT % (tmp, "https://www.xythobuz.de", p.url))
  434. fp.write("\n")
  435. fp.write(_COMPAT_404 % "/404.html")
  436. fp.write(" }\n")
  437. fp.write("}\n")
  438. fp.write("if ($_SERVER['SERVER_PROTOCOL'] == 'HTTP/1.1') {\n")
  439. fp.write(" if (php_sapi_name() == 'cgi') {\n")
  440. fp.write(" header('Status: 301 Moved Permanently');\n")
  441. fp.write(" } else {\n")
  442. fp.write(" header('HTTP/1.1 301 Moved Permanently');\n")
  443. fp.write(" }\n")
  444. fp.write("}\n");
  445. fp.write("header('Location: '.$loc);\n")
  446. fp.write("?>")
  447. fp.close()
  448. # -----------------------------------------------------------------------------
  449. # sitemap generation
  450. # -----------------------------------------------------------------------------
  451. _SITEMAP = """<?xml version="1.0" encoding="UTF-8"?>
  452. <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  453. %s
  454. </urlset>
  455. """
  456. _SITEMAP_URL = """
  457. <url>
  458. <loc>%s/%s</loc>
  459. <lastmod>%s</lastmod>
  460. <changefreq>%s</changefreq>
  461. <priority>%s</priority>
  462. </url>
  463. """
  464. def hook_preconvert_sitemap():
  465. date = datetime.strftime(datetime.now(), "%Y-%m-%d")
  466. urls = []
  467. for p in pages:
  468. urls.append(_SITEMAP_URL % (BASE_URL, p.url, date, p.get("changefreq", "monthly"), p.get("priority", "0.5")))
  469. fname = os.path.join(options.project, "output", "sitemap.xml")
  470. fp = open(fname, 'w')
  471. fp.write(_SITEMAP % "".join(urls))
  472. fp.close()
  473. # -----------------------------------------------------------------------------
  474. # postconvert hooks
  475. # -----------------------------------------------------------------------------
  476. # -----------------------------------------------------------------------------
  477. # rss feed generation
  478. # -----------------------------------------------------------------------------
  479. _RSS = """<?xml version="1.0" encoding="UTF-8"?>
  480. <?xml-stylesheet href="%s" type="text/xsl"?>
  481. <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  482. <channel>
  483. <title>%s</title>
  484. <link>%s</link>
  485. <atom:link href="%s" rel="self" type="application/rss+xml" />
  486. <description>%s</description>
  487. <language>en-us</language>
  488. <pubDate>%s</pubDate>
  489. <lastBuildDate>%s</lastBuildDate>
  490. <docs>http://blogs.law.harvard.edu/tech/rss</docs>
  491. <generator>Poole</generator>
  492. <ttl>720</ttl>
  493. %s
  494. </channel>
  495. </rss>
  496. """
  497. _RSS_ITEM = """
  498. <item>
  499. <title>%s</title>
  500. <link>%s</link>
  501. <description>%s</description>
  502. <pubDate>%s</pubDate>
  503. <atom:updated>%s</atom:updated>
  504. <guid>%s</guid>
  505. </item>
  506. """
  507. def hook_postconvert_rss():
  508. items = []
  509. # all pages with "date" get put into feed
  510. posts = [p for p in pages if "date" in p]
  511. # sort by update if available, date else
  512. posts.sort(key=lambda p: p.get("update", p.date), reverse=True)
  513. # only put 20 most recent items in feed
  514. posts = posts[:20]
  515. for p in posts:
  516. title = p.title
  517. if "post" in p:
  518. title = p.post
  519. link = "%s/%s" % (BASE_URL, p.url)
  520. desc = p.html.replace("href=\"img", "%s%s%s" % ("href=\"", BASE_URL, "/img"))
  521. desc = desc.replace("src=\"img", "%s%s%s" % ("src=\"", BASE_URL, "/img"))
  522. desc = desc.replace("href=\"/img", "%s%s%s" % ("href=\"", BASE_URL, "/img"))
  523. desc = desc.replace("src=\"/img", "%s%s%s" % ("src=\"", BASE_URL, "/img"))
  524. desc = htmlspecialchars(desc)
  525. date = time.mktime(time.strptime("%s 12" % p.date, "%Y-%m-%d %H"))
  526. date = email.utils.formatdate(date)
  527. update = time.mktime(time.strptime("%s 12" % p.get("update", p.date), "%Y-%m-%d %H"))
  528. update = email.utils.formatdate(update)
  529. items.append(_RSS_ITEM % (title, link, desc, date, update, link))
  530. items = "".join(items)
  531. style = "/css/rss.xsl"
  532. title = "xythobuz.de Blog"
  533. link = "%s" % BASE_URL
  534. feed = "%s/rss.xml" % BASE_URL
  535. desc = htmlspecialchars("xythobuz Electronics & Software Projects")
  536. date = email.utils.formatdate()
  537. rss = _RSS % (style, title, link, feed, desc, date, date, items)
  538. fp = codecs.open(os.path.join(output, "rss.xml"), "w", "utf-8")
  539. fp.write(rss)
  540. fp.close()
  541. # -----------------------------------------------------------------------------
  542. # compatibility redirect for old mobile pages
  543. # -----------------------------------------------------------------------------
  544. _COMPAT_MOB = """ case "%s":
  545. $loc = "%s/%s";
  546. break;
  547. """
  548. _COMPAT_404_MOB = """ default:
  549. $loc = "%s";
  550. break;
  551. """
  552. def hook_postconvert_mobilecompat():
  553. directory = os.path.join(output, "mobile")
  554. if not os.path.exists(directory):
  555. os.makedirs(directory)
  556. fp = codecs.open(os.path.join(directory, "index.php"), "w", "utf-8")
  557. fp.write("<?\n")
  558. fp.write("// Auto generated xyCMS compatibility mobile/index.php\n")
  559. fp.write("$loc = 'https://www.xythobuz.de/index.de.html';\n")
  560. fp.write("if (isset($_GET['p'])) {\n")
  561. fp.write(" if (isset($_GET['lang'])) {\n")
  562. fp.write(" $_GET['p'] .= 'EN';\n")
  563. fp.write(" }\n")
  564. fp.write(" switch($_GET['p']) {\n")
  565. for p in pages:
  566. if p.get("compat", "") != "":
  567. tmp = p["compat"]
  568. if p.get("lang", DEFAULT_LANG) == DEFAULT_LANG:
  569. tmp = tmp + "EN"
  570. fp.write(_COMPAT_MOB % (tmp, "https://www.xythobuz.de", re.sub(".html", ".html", p.url)))
  571. fp.write("\n")
  572. fp.write(_COMPAT_404_MOB % "/404.mob.html")
  573. fp.write(" }\n")
  574. fp.write("}\n")
  575. fp.write("if ($_SERVER['SERVER_PROTOCOL'] == 'HTTP/1.1') {\n")
  576. fp.write(" if (php_sapi_name() == 'cgi') {\n")
  577. fp.write(" header('Status: 301 Moved Permanently');\n")
  578. fp.write(" } else {\n")
  579. fp.write(" header('HTTP/1.1 301 Moved Permanently');\n")
  580. fp.write(" }\n")
  581. fp.write("}\n");
  582. fp.write("header('Location: '.$loc);\n")
  583. fp.write("?>")
  584. fp.close()
  585. # -----------------------------------------------------------------------------
  586. # displaying filesize for download links
  587. # -----------------------------------------------------------------------------
  588. def hook_postconvert_size():
  589. file_ext = '|'.join(['pdf', 'zip', 'rar', 'ods', 'odt', 'odp', 'doc', 'xls', 'ppt', 'docx', 'xlsx', 'pptx', 'exe', 'brd', 'plist'])
  590. def matched_link(matchobj):
  591. try:
  592. path = matchobj.group(1)
  593. if path.startswith("http") or path.startswith("//") or path.startswith("ftp"):
  594. return '<a href=\"%s\">%s</a>' % (matchobj.group(1), matchobj.group(3))
  595. elif path.startswith("/"):
  596. path = path.strip("/")
  597. path = os.path.join("static/", path)
  598. size = os.path.getsize(path)
  599. if size >= (1024 * 1024):
  600. return "<a href=\"%s\">%s</a>&nbsp;(%.1f MiB)" % (matchobj.group(1), matchobj.group(3), size / (1024.0 * 1024.0))
  601. elif size >= 1024:
  602. return "<a href=\"%s\">%s</a>&nbsp;(%d KiB)" % (matchobj.group(1), matchobj.group(3), size // 1024)
  603. else:
  604. return "<a href=\"%s\">%s</a>&nbsp;(%d Byte)" % (matchobj.group(1), matchobj.group(3), size)
  605. except:
  606. print "Unable to estimate file size for %s" % matchobj.group(1)
  607. return '<a href=\"%s\">%s</a>' % (matchobj.group(1), matchobj.group(3))
  608. _re_url = '<a href=\"([^\"]*?\.(%s))\">(.*?)<\/a>' % file_ext
  609. for p in pages:
  610. p.html = re.sub(_re_url, matched_link, p.html)