My static website generator using poole https://www.xythobuz.de
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

macros.py 27KB

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