blogit.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8
  3. # Copyleft (C) 2010 Mir Nazim <hello@mirnazim.org>
  4. # Copyleft (C) 2013 Oz Nahum <nahumoz@gmail.com>
  5. #
  6. # Everyone is permitted to copy and distribute verbatim or modified
  7. # copies of this license document, and changing it is allowed as long
  8. # as the name is changed.
  9. #
  10. # TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  11. #
  12. # 0. You just DO WHATEVER THE FUCK YOU WANT TO. (IT'S SLOPPY CODE ANYWAY)
  13. #
  14. # WARANTIES:
  15. # 0. Are you kidding me?
  16. # 1. Seriously, Are you fucking kidding me?
  17. # 2. If anything goes wrong, sue the "The Empire".
  18. # Note about Summary
  19. # has to be 1 line, no '\n' allowed!
  20. """
  21. Summary: |
  22. some summary ...
  23. Your post
  24. """
  25. """
  26. Everything the Header can't have ":" or "..." in it, you can't have title
  27. with ":" it makes markdown break!
  28. """
  29. """
  30. The content directory can contain only mardown or txt files, no images
  31. allowed!
  32. """
  33. import os
  34. import re
  35. import datetime
  36. import yaml # in debian python-yaml
  37. from StringIO import StringIO
  38. import codecs
  39. from jinja2 import Environment, FileSystemLoader # in debian python-jinja2
  40. try:
  41. import markdown2
  42. except ImportError:
  43. import markdown as markdown2
  44. import argparse
  45. import sys
  46. from distutils import dir_util
  47. import shutil
  48. CONFIG = {
  49. 'content_root': 'content', # where the markdown files are
  50. 'output_to': 'oz123.github.com',
  51. 'templates': 'templates',
  52. 'date_format': '%Y-%m-%d',
  53. 'base_url': 'http://oz123.github.com',
  54. 'http_port': 3030,
  55. 'content_encoding': 'utf-8',
  56. }
  57. GLOBAL_TEMPLATE_CONTEXT = {
  58. 'media_base': '/media/',
  59. 'media_url': '../media/',
  60. 'site_url': 'http://oz123.github.com',
  61. 'last_build': datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ"),
  62. 'twitter': 'https://twitter.com/#!/OzNTiram',
  63. 'stackoverflow': "http://stackoverflow.com/users/492620/oz123",
  64. 'github': "https://github.com/oz123",
  65. 'side_bar': """
  66. <div id="nav">
  67. <div><img src="/media/img/me.png"></div>
  68. <a title="Home" href="/">home</a>
  69. <a title="About" class="about" href="/about.html">about</a>
  70. <a title="Archive" class="archive" href="/archive">archive</a>
  71. <a title="Atom feeds" href="/atom.xml">atom</a>
  72. <a title="Twitter" href="https://twitter.com/#!/OzNTiram">twitter</a>
  73. <a title="Stackoverflow" href="http://stackoverflow.com/users/492620/oz123">stackoverflow</a>
  74. <a title="Github" href="https://github.com/oz123">github</a>
  75. <script type="text/javascript"><!--
  76. google_ad_client = "ca-pub-2570499281263620";
  77. /* new_tower_for_oz123githubcom */
  78. google_ad_slot = "8107518414";
  79. google_ad_width = 120;
  80. google_ad_height = 600;
  81. //-->
  82. </script>
  83. <script type="text/javascript"
  84. src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
  85. </script>
  86. </div>
  87. """,
  88. 'google_analytics': """
  89. <script type="text/javascript">
  90. var _gaq = _gaq || [];
  91. _gaq.push(['_setAccount', 'UA-36587163-1']);
  92. _gaq.push(['_trackPageview']);
  93. (function() {
  94. var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  95. ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  96. var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  97. })();
  98. </script>""",
  99. 'disquss' : """<div id="disqus_thread"></div>
  100. <script type="text/javascript">
  101. /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
  102. var disqus_shortname = 'oz123githubcom'; // required: replace example with your forum shortname
  103. /* * * DON'T EDIT BELOW THIS LINE * * */
  104. (function() {
  105. var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
  106. dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
  107. (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
  108. })();
  109. </script>
  110. <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
  111. <a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
  112. """
  113. }
  114. KINDS = {
  115. 'writing': {
  116. 'name': 'writing', 'name_plural': 'writings',
  117. },
  118. 'note': {
  119. 'name': 'note', 'name_plural': 'notes',
  120. },
  121. 'link': {
  122. 'name': 'link', 'name_plural': 'links',
  123. },
  124. 'photo': {
  125. 'name': 'photo', 'name_plural': 'photos',
  126. },
  127. 'page': {
  128. 'name': 'page', 'name_plural': 'pages',
  129. },
  130. }
  131. jinja_env = Environment(loader=FileSystemLoader(CONFIG['templates']))
  132. class Tag(object):
  133. def __init__(self, name):
  134. super(Tag, self).__init__()
  135. self.name = name
  136. self.prepare()
  137. self.permalink = GLOBAL_TEMPLATE_CONTEXT["site_url"]
  138. def prepare(self):
  139. _slug = self.name.lower()
  140. _slug = re.sub(r'[;;,. ]', '-', _slug)
  141. self.slug = _slug
  142. class Entry(object):
  143. def __init__(self, path):
  144. super(Entry, self).__init__()
  145. path = path.split('content/')[-1]
  146. self.path = path
  147. self.prepare()
  148. def __str__(self):
  149. return self.path
  150. def __repr__(self):
  151. return self.path
  152. @property
  153. def name(self):
  154. return os.path.splitext(os.path.basename(self.path))[0]
  155. @property
  156. def abspath(self):
  157. return os.path.abspath(os.path.join(CONFIG['content_root'], self.path))
  158. @property
  159. def destination(self):
  160. dest = "%s/%s/index.html" % (KINDS[
  161. self.kind]['name_plural'], self.name)
  162. print dest
  163. return os.path.join(CONFIG['output_to'], dest)
  164. @property
  165. def title(self):
  166. return self.header['title']
  167. @property
  168. def summary_html(self):
  169. return "%s" % markdown2.markdown(self.header['summary'].strip())
  170. @property
  171. def credits_html(self):
  172. return "%s" % markdown2.markdown(self.header['credits'].strip())
  173. @property
  174. def summary_atom(self):
  175. summarya = markdown2.markdown(self.header['summary'].strip())
  176. summarya = re.sub("<p>|</p>", "", summarya)
  177. more = '<a href="%s"> continue reading...</a>' % (self.permalink)
  178. return summarya+more
  179. @property
  180. def published_html(self):
  181. if self.kind in ['link', 'note', 'photo']:
  182. return self.header['published'].strftime("%B %d, %Y %I:%M %p")
  183. return self.header['published'].strftime("%B %d, %Y")
  184. @property
  185. def published_atom(self):
  186. return self.published.strftime("%Y-%m-%dT%H:%M:%SZ")
  187. @property
  188. def atom_id(self):
  189. return "tag:%s,%s:%s" % \
  190. (
  191. self.published.strftime("%Y-%m-%d"),
  192. self.permalink,
  193. GLOBAL_TEMPLATE_CONTEXT["site_url"]
  194. )
  195. @property
  196. def body_html(self):
  197. return markdown2.markdown(self.body) # , extras=['code-color'])
  198. @property
  199. def permalink(self):
  200. return "/%s/%s" % (KINDS[self.kind]['name_plural'], self.name)
  201. @property
  202. def tags(self):
  203. tags = list()
  204. for t in self.header['tags']:
  205. tags.append(Tag(t))
  206. return tags
  207. def prepare(self):
  208. file = codecs.open(self.abspath, 'r')
  209. header = ['---']
  210. while True:
  211. line = file.readline()
  212. line = line.rstrip()
  213. if not line:
  214. break
  215. header.append(line)
  216. self.header = yaml.load(StringIO('\n'.join(header)))
  217. for h in self.header.items():
  218. if h:
  219. try:
  220. setattr(self, h[0], h[1])
  221. except:
  222. pass
  223. body = list()
  224. for line in file.readlines():
  225. body.append(line)
  226. self.body = ''.join(body)
  227. file.close()
  228. if self.kind == 'link':
  229. from urlparse import urlparse
  230. self.domain_name = urlparse(self.url).netloc
  231. elif self.kind == 'photo':
  232. pass
  233. elif self.kind == 'note':
  234. pass
  235. elif self.kind == 'writing':
  236. pass
  237. def render(self):
  238. if not self.header['public']:
  239. return False
  240. try:
  241. os.makedirs(os.path.dirname(self.destination))
  242. except:
  243. pass
  244. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  245. context['entry'] = self
  246. template = jinja_env.get_template("entry.html")
  247. html = template.render(context)
  248. destination = codecs.open(
  249. self.destination, 'w', CONFIG['content_encoding'])
  250. destination.write(html)
  251. destination.close()
  252. return True
  253. class Link(Entry):
  254. def __init__(self, path):
  255. super(Link, self).__init__(path)
  256. @property
  257. def permalink(self):
  258. print "self.url", self.url
  259. raw_input()
  260. return self.url
  261. def entry_factory():
  262. pass
  263. def _sort_entries(entries):
  264. _entries = dict()
  265. sorted_entries = list()
  266. for entry in entries:
  267. _published = entry.header['published'].isoformat()
  268. _entries[_published] = entry
  269. sorted_keys = sorted(_entries.keys())
  270. sorted_keys.reverse()
  271. for key in sorted_keys:
  272. sorted_entries.append(_entries[key])
  273. return sorted_entries
  274. def render_index(entries):
  275. """
  276. this function renders the main page located at index.html
  277. under oz123.github.com
  278. """
  279. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  280. context['entries'] = entries[:10]
  281. template = jinja_env.get_template('entry_index.html')
  282. html = template.render(context)
  283. destination = codecs.open("%s/index.html" % CONFIG[
  284. 'output_to'], 'w', CONFIG['content_encoding'])
  285. destination.write(html)
  286. destination.close()
  287. def render_archive(entries, render_to=None):
  288. """
  289. this function creates the archive page
  290. """
  291. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  292. context['entries'] = entries[10:]
  293. template = jinja_env.get_template('archive_index.html')
  294. html = template.render(context)
  295. if not render_to:
  296. render_to = "%s/archive/index.html" % CONFIG['output_to']
  297. dir_util.mkpath("%s/archive" % CONFIG['output_to'])
  298. destination = codecs.open("%s/archive/index.html" % CONFIG[
  299. 'output_to'], 'w', CONFIG['content_encoding'])
  300. destination.write(html)
  301. destination.close()
  302. def render_atom_feed(entries, render_to=None):
  303. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  304. context['entries'] = entries[:10]
  305. template = jinja_env.get_template('atom.xml')
  306. html = template.render(context)
  307. if not render_to:
  308. render_to = "%s/atom.xml" % CONFIG['output_to']
  309. destination = codecs.open(render_to, 'w', CONFIG['content_encoding'])
  310. destination.write(html)
  311. destination.close()
  312. def render_tag_pages(tag_tree):
  313. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  314. for t in tag_tree.items():
  315. context['tag'] = t[1]['tag']
  316. context['entries'] = _sort_entries(t[1]['entries'])
  317. destination = "%s/tags/%s" % (CONFIG['output_to'], context['tag'].slug)
  318. try:
  319. os.makedirs(destination)
  320. except:
  321. pass
  322. template = jinja_env.get_template('tag_index.html')
  323. html = template.render(context)
  324. file = codecs.open("%s/index.html" %
  325. destination, 'w', CONFIG['content_encoding'])
  326. file.write(html)
  327. file.close()
  328. render_atom_feed(context[
  329. 'entries'], render_to="%s/atom.xml" % destination)
  330. def build():
  331. print
  332. print "Rendering website now..."
  333. print
  334. print " entries:"
  335. entries = list()
  336. tags = dict()
  337. for root, dirs, files in os.walk(CONFIG['content_root']):
  338. for fileName in files:
  339. try:
  340. entry = Entry(os.path.join(root, fileName))
  341. except Exception, e:
  342. print "Found some problem in: ", fileName
  343. print e
  344. raw_input("Please correct")
  345. sys.exit()
  346. if entry.render():
  347. entries.append(entry)
  348. for tag in entry.tags:
  349. if tag.name not in tags:
  350. tags[tag.name] = {
  351. 'tag': tag,
  352. 'entries': list(),
  353. }
  354. tags[tag.name]['entries'].append(entry)
  355. print " %s" % entry.path
  356. print " :done"
  357. print
  358. print " tag pages & their atom feeds:"
  359. render_tag_pages(tags)
  360. print " :done"
  361. print
  362. print " site wide index"
  363. entries = _sort_entries(entries)
  364. render_index(entries)
  365. print "................done"
  366. print " archive index"
  367. render_archive(entries)
  368. print "................done"
  369. print " site wide atom feeds"
  370. render_atom_feed(entries)
  371. print "...........done"
  372. print
  373. print "All done "
  374. def preview(PREVIEW_ADDR='127.0.1.1', PREVIEW_PORT=11000):
  375. """
  376. launch an HTTP to preview the website
  377. """
  378. import SimpleHTTPServer
  379. import SocketServer
  380. Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
  381. httpd = SocketServer.TCPServer(("", CONFIG['http_port']), Handler)
  382. os.chdir(CONFIG['output_to'])
  383. print "and ready to test at http://127.0.0.1:%d" % CONFIG['http_port']
  384. print "Hit Ctrl+C to exit"
  385. try:
  386. httpd.serve_forever()
  387. except KeyboardInterrupt:
  388. print
  389. print "Shutting Down... Bye!."
  390. print
  391. httpd.server_close()
  392. def publish(GITDIRECTORY="oz123.github.com"):
  393. pass
  394. def clean(GITDIRECTORY="oz123.github.com"):
  395. directoriestoclean = ["writings", "notes", "links", "tags", "archive"]
  396. os.chdir(GITDIRECTORY)
  397. for directory in directoriestoclean:
  398. shutil.rmtree(directory)
  399. def dist(SOURCEDIR=os.getcwd()+"/content/", DESTDIR="oz123.github.com/writings_raw/content/"):
  400. """
  401. sync raw files from SOURCE to DEST
  402. """
  403. import subprocess as sp
  404. sp.call(["rsync", "-avP", SOURCEDIR, DESTDIR], shell=False, cwd=os.getcwd())
  405. if __name__ == '__main__':
  406. parser = argparse.ArgumentParser(
  407. description='blogit - a tool to blog on github.')
  408. parser.add_argument('-b', '--build', action="store_true",
  409. help='convert the markdown files to HTML')
  410. parser.add_argument('-p', '--preview', action="store_true",
  411. help='Launch HTTP server to preview the website')
  412. parser.add_argument('-c', '--clean', action="store_true",
  413. help='clean output files')
  414. parser.add_argument('-d', '--dist', action="store_true",
  415. help='sync raw files from SOURCE to DEST')
  416. args = parser.parse_args()
  417. if len(sys.argv) < 2:
  418. parser.print_help()
  419. sys.exit()
  420. if args.clean:
  421. clean()
  422. if args.build:
  423. build()
  424. if args.dist:
  425. dist()
  426. if args.preview:
  427. preview()