blogit.py 13 KB

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