blogit.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. #!/usr/bin/env python
  2. # ============================================================================
  3. # Blogit.py is free software; you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License, version 3
  5. # as published by the Free Software Foundation;
  6. #
  7. # Blogit.py is distributed in the hope that it will be useful,
  8. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. # GNU General Public License for more details.
  11. #
  12. # You should have received a copy of the GNU General Public License
  13. # along with Blogit.py; if not, write to the Free Software
  14. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  15. # ============================================================================
  16. # Copyright (C) 2013 Oz Nahum Tiram <nahumoz@gmail.com>
  17. # ============================================================================
  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 argparse
  37. import sys
  38. from distutils import dir_util
  39. import shutil
  40. from StringIO import StringIO
  41. import codecs
  42. import subprocess as sp
  43. import SimpleHTTPServer
  44. import BaseHTTPServer
  45. import socket
  46. import thread
  47. try:
  48. import yaml # in debian python-yaml
  49. from jinja2 import Environment, FileSystemLoader # in debian python-jinja2
  50. except ImportError, e:
  51. print e
  52. print "On Debian based system you can install the dependencies with: "
  53. print "apt-get install python-yaml python-jinja2"
  54. sys.exit(1)
  55. try:
  56. import markdown2
  57. renderer = 'md2'
  58. except ImportError, e:
  59. try:
  60. import markdown
  61. renderer = 'md1'
  62. except ImportError, e:
  63. print e
  64. print "try: sudo pip install markdown2"
  65. sys.exit(1)
  66. sys.path.insert(0, os.getcwdu())
  67. from conf import CONFIG, ARCHIVE_SIZE, GLOBAL_TEMPLATE_CONTEXT, KINDS
  68. jinja_env = Environment(loader=FileSystemLoader(CONFIG['templates']))
  69. class Tag(object):
  70. def __init__(self, name):
  71. super(Tag, self).__init__()
  72. self.name = name
  73. self.prepare()
  74. self.permalink = GLOBAL_TEMPLATE_CONTEXT["site_url"]
  75. def prepare(self):
  76. _slug = self.name.lower()
  77. _slug = re.sub(r'[;;,. ]', '-', _slug)
  78. self.slug = _slug
  79. class Entry(object):
  80. def __init__(self, path):
  81. super(Entry, self).__init__()
  82. path = path.split('content/')[-1]
  83. self.path = path
  84. self.prepare()
  85. def __str__(self):
  86. return self.path
  87. def __repr__(self):
  88. return self.path
  89. @property
  90. def name(self):
  91. return os.path.splitext(os.path.basename(self.path))[0]
  92. @property
  93. def abspath(self):
  94. return os.path.abspath(os.path.join(CONFIG['content_root'], self.path))
  95. @property
  96. def destination(self):
  97. dest = "%s/%s/index.html" % (KINDS[
  98. self.kind]['name_plural'], self.name)
  99. print dest
  100. return os.path.join(CONFIG['output_to'], dest)
  101. @property
  102. def title(self):
  103. return self.header['title']
  104. @property
  105. def summary_html(self):
  106. return "%s" % markdown2.markdown(self.header['summary'].strip())
  107. @property
  108. def credits_html(self):
  109. return "%s" % markdown2.markdown(self.header['credits'].strip())
  110. @property
  111. def summary_atom(self):
  112. summarya = markdown2.markdown(self.header['summary'].strip())
  113. summarya = re.sub("<p>|</p>", "", summarya)
  114. more = '<a href="%s"> continue reading...</a>' % (self.permalink)
  115. return summarya+more
  116. @property
  117. def published_html(self):
  118. if self.kind in ['link', 'note', 'photo']:
  119. return self.header['published'].strftime("%B %d, %Y %I:%M %p")
  120. return self.header['published'].strftime("%B %d, %Y")
  121. @property
  122. def published_atom(self):
  123. return self.published.strftime("%Y-%m-%dT%H:%M:%SZ")
  124. @property
  125. def atom_id(self):
  126. return "tag:%s,%s:%s" % \
  127. (
  128. self.published.strftime("%Y-%m-%d"),
  129. self.permalink,
  130. GLOBAL_TEMPLATE_CONTEXT["site_url"]
  131. )
  132. @property
  133. def body_html(self):
  134. if renderer == 'md2':
  135. return markdown2.markdown(self.body, extras=['fenced-code-blocks',
  136. 'hilite'])
  137. if renderer == 'md1':
  138. return markdown.markdown(self.body,
  139. extensions=['fenced_code',
  140. 'codehilite(linenums=False)'])
  141. @property
  142. def permalink(self):
  143. return "/%s/%s" % (KINDS[self.kind]['name_plural'], self.name)
  144. @property
  145. def tags(self):
  146. tags = list()
  147. for t in self.header['tags']:
  148. tags.append(Tag(t))
  149. return tags
  150. def prepare(self):
  151. file = codecs.open(self.abspath, 'r')
  152. header = ['---']
  153. while True:
  154. line = file.readline()
  155. line = line.rstrip()
  156. if not line:
  157. break
  158. header.append(line)
  159. self.header = yaml.load(StringIO('\n'.join(header)))
  160. for h in self.header.items():
  161. if h:
  162. try:
  163. setattr(self, h[0], h[1])
  164. except:
  165. pass
  166. body = list()
  167. for line in file.readlines():
  168. body.append(line)
  169. self.body = ''.join(body)
  170. file.close()
  171. if self.kind == 'link':
  172. from urlparse import urlparse
  173. self.domain_name = urlparse(self.url).netloc
  174. elif self.kind == 'photo':
  175. pass
  176. elif self.kind == 'note':
  177. pass
  178. elif self.kind == 'writing':
  179. pass
  180. def render(self):
  181. if not self.header['public']:
  182. return False
  183. try:
  184. os.makedirs(os.path.dirname(self.destination))
  185. except:
  186. pass
  187. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  188. context['entry'] = self
  189. # this is redundant ! every time we render entry we get_template?
  190. # todo: make template class property !
  191. template = jinja_env.get_template("entry.html")
  192. try:
  193. html = template.render(context)
  194. except Exception, e:
  195. print context
  196. print self.path
  197. print e
  198. sys.exit()
  199. destination = codecs.open(
  200. self.destination, 'w', CONFIG['content_encoding'])
  201. destination.write(html)
  202. destination.close()
  203. # before returning write log to csv
  204. # file name, date first seen, date rendered
  205. # self.path , date-first-seen, if rendered datetime.now
  206. return True
  207. class Link(Entry):
  208. def __init__(self, path):
  209. super(Link, self).__init__(path)
  210. @property
  211. def permalink(self):
  212. print "self.url", self.url
  213. raw_input()
  214. return self.url
  215. def entry_factory():
  216. pass
  217. def _sort_entries(entries):
  218. _entries = dict()
  219. sorted_entries = list()
  220. for entry in entries:
  221. _published = entry.header['published'].isoformat()
  222. _entries[_published] = entry
  223. sorted_keys = sorted(_entries.keys())
  224. sorted_keys.reverse()
  225. for key in sorted_keys:
  226. sorted_entries.append(_entries[key])
  227. return sorted_entries
  228. def render_index(entries):
  229. """
  230. this function renders the main page located at index.html
  231. under oz123.github.com
  232. """
  233. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  234. context['entries'] = entries[:10]
  235. template = jinja_env.get_template('entry_index.html')
  236. html = template.render(context)
  237. destination = codecs.open("%s/index.html" % CONFIG[
  238. 'output_to'], 'w', CONFIG['content_encoding'])
  239. destination.write(html)
  240. destination.close()
  241. def render_archive(entries, render_to=None):
  242. """
  243. this function creates the archive page
  244. """
  245. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  246. context['entries'] = entries[ARCHIVE_SIZE:]
  247. template = jinja_env.get_template('archive_index.html')
  248. html = template.render(context)
  249. if not render_to:
  250. render_to = "%s/archive/index.html" % CONFIG['output_to']
  251. dir_util.mkpath("%s/archive" % CONFIG['output_to'])
  252. destination = codecs.open("%s/archive/index.html" % CONFIG[
  253. 'output_to'], 'w', CONFIG['content_encoding'])
  254. destination.write(html)
  255. destination.close()
  256. def render_atom_feed(entries, render_to=None):
  257. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  258. context['entries'] = entries[:10]
  259. template = jinja_env.get_template('atom.xml')
  260. html = template.render(context)
  261. if not render_to:
  262. render_to = "%s/atom.xml" % CONFIG['output_to']
  263. destination = codecs.open(render_to, 'w', CONFIG['content_encoding'])
  264. destination.write(html)
  265. destination.close()
  266. def render_tag_pages(tag_tree):
  267. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  268. for t in tag_tree.items():
  269. context['tag'] = t[1]['tag']
  270. context['entries'] = _sort_entries(t[1]['entries'])
  271. destination = "%s/tags/%s" % (CONFIG['output_to'], context['tag'].slug)
  272. try:
  273. os.makedirs(destination)
  274. except:
  275. pass
  276. template = jinja_env.get_template('tag_index.html')
  277. html = template.render(context)
  278. file = codecs.open("%s/index.html" %
  279. destination, 'w', CONFIG['content_encoding'])
  280. file.write(html)
  281. file.close()
  282. render_atom_feed(context[
  283. 'entries'], render_to="%s/atom.xml" % destination)
  284. def build():
  285. print
  286. print "Rendering website now..."
  287. print
  288. print " entries:"
  289. entries = list()
  290. tags = dict()
  291. for root, dirs, files in os.walk(CONFIG['content_root']):
  292. for fileName in files:
  293. try:
  294. if fileName.endswith('md') or fileName.endswith('markdown'):
  295. entry = Entry(os.path.join(root, fileName))
  296. except Exception, e:
  297. print "Found some problem in: ", entry.path
  298. print e
  299. print "Please correct this problem ..."
  300. sys.exit()
  301. if entry.render():
  302. entries.append(entry)
  303. for tag in entry.tags:
  304. if tag.name not in tags:
  305. tags[tag.name] = {
  306. 'tag': tag,
  307. 'entries': list(),
  308. }
  309. tags[tag.name]['entries'].append(entry)
  310. print " %s" % entry.path
  311. print " :done"
  312. print
  313. print " tag pages & their atom feeds:"
  314. render_tag_pages(tags)
  315. print " :done"
  316. print
  317. print " site wide index"
  318. entries = _sort_entries(entries)
  319. render_index(entries)
  320. print "................done"
  321. print " archive index"
  322. render_archive(entries)
  323. print "................done"
  324. print " site wide atom feeds"
  325. render_atom_feed(entries)
  326. print "...........done"
  327. print
  328. print "All done "
  329. class StoppableHTTPServer(BaseHTTPServer.HTTPServer):
  330. def server_bind(self):
  331. BaseHTTPServer.HTTPServer.server_bind(self)
  332. self.socket.settimeout(1)
  333. self.run = True
  334. def get_request(self):
  335. while self.run:
  336. try:
  337. sock, addr = self.socket.accept()
  338. sock.settimeout(None)
  339. return (sock, addr)
  340. except socket.timeout:
  341. pass
  342. def stop(self):
  343. self.run = False
  344. def serve(self):
  345. while self.run:
  346. self.handle_request()
  347. def preview(PREVIEW_ADDR='127.0.1.1', PREVIEW_PORT=11000):
  348. """
  349. launch an HTTP to preview the website
  350. """
  351. os.chdir(CONFIG['output_to'])
  352. print "and ready to test at http://127.0.0.1:%d" % CONFIG['http_port']
  353. print "Hit Ctrl+C to exit"
  354. try:
  355. httpd = StoppableHTTPServer(("127.0.0.1", CONFIG['http_port']),
  356. SimpleHTTPServer.SimpleHTTPRequestHandler)
  357. thread.start_new_thread(httpd.serve, ())
  358. sp.call('open http://127.0.0.1:%d' % CONFIG['http_port'], shell=True)
  359. while True:
  360. continue
  361. except KeyboardInterrupt:
  362. print
  363. print "Shutting Down... Bye!."
  364. print
  365. httpd.stop()
  366. def publish(GITDIRECTORY=CONFIG['output_to']):
  367. sp.call('git push', cwd=GITDIRECTORY, shell=True)
  368. def new_post(GITDIRECTORY=CONFIG['output_to'],
  369. kind=KINDS['writing']):
  370. """
  371. This function should create a template for a new post with a title
  372. read from the user input.
  373. Most other fields should be defaults.
  374. """
  375. title = raw_input("Give the title of the post: ")
  376. while ':' in title:
  377. title = raw_input("Give the title of the post (':' not allowed): ")
  378. author = CONFIG['author']
  379. date = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d')
  380. tags = '['+raw_input("Give the tags, separated by ', ':")+']'
  381. published = 'yes'
  382. chronological = 'yes'
  383. summary = ("summary: |\n Type your summary here.\n Do not change the "
  384. "indentation"
  385. "to the left\n ...\n\nStart writing your post here!")
  386. # make file name
  387. fname = os.path.join(os.getcwd(), 'content', kind['name_plural'],
  388. datetime.datetime.strftime(datetime.datetime.now(),
  389. '%Y'),
  390. date+'-'+title.replace(' ', '-')+'.markdown')
  391. with open(fname, 'w') as npost:
  392. npost.write('title: %s\n' % title)
  393. npost.write('author: %s\n' % author)
  394. npost.write('published: %s\n' % date)
  395. npost.write('tags: %s\n' % tags)
  396. npost.write('public: %s\n' % published)
  397. npost.write('chronological: %s\n' % chronological)
  398. npost.write('kind: %s\n' % kind['name'])
  399. npost.write('%s' % summary)
  400. os.system('%s %s' % (CONFIG['editor'], fname))
  401. def clean(GITDIRECTORY=CONFIG['output_to']):
  402. directoriestoclean = ["writings", "notes", "links", "tags", "archive"]
  403. os.chdir(GITDIRECTORY)
  404. for directory in directoriestoclean:
  405. shutil.rmtree(directory)
  406. def dist(SOURCEDIR=os.getcwd()+"/content/",
  407. DESTDIR=CONFIG['raw_content']):
  408. """
  409. sync raw files from SOURCE to DEST
  410. """
  411. sp.call(["rsync", "-avP", SOURCEDIR, DESTDIR], shell=False,
  412. cwd=os.getcwd())
  413. if __name__ == '__main__':
  414. parser = argparse.ArgumentParser(
  415. description='blogit - a tool to blog on github.')
  416. parser.add_argument('-b', '--build', action="store_true",
  417. help='convert the markdown files to HTML')
  418. parser.add_argument('-p', '--preview', action="store_true",
  419. help='Launch HTTP server to preview the website')
  420. parser.add_argument('-c', '--clean', action="store_true",
  421. help='clean output files')
  422. parser.add_argument('-n', '--new', action="store_true",
  423. help='create new post')
  424. parser.add_argument('-d', '--dist', action="store_true",
  425. help='sync raw files from SOURCE to DEST')
  426. parser.add_argument('--publish', action="store_true",
  427. help='push built HTML to git upstream')
  428. args = parser.parse_args()
  429. if len(sys.argv) < 2:
  430. parser.print_help()
  431. sys.exit()
  432. if args.clean:
  433. clean()
  434. if args.build:
  435. build()
  436. if args.dist:
  437. dist()
  438. if args.preview:
  439. preview()
  440. if args.new:
  441. new_post()
  442. if args.publish:
  443. publish()