blogit.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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. "tables"])
  138. if renderer == 'md1':
  139. return markdown.markdown(self.body,
  140. extensions=['fenced_code',
  141. 'codehilite(linenums=False)',
  142. 'tables'])
  143. @property
  144. def permalink(self):
  145. return "/%s/%s" % (KINDS[self.kind]['name_plural'], self.name)
  146. @property
  147. def tags(self):
  148. tags = list()
  149. for t in self.header['tags']:
  150. tags.append(Tag(t))
  151. return tags
  152. def _read_header(self, file):
  153. header = ['---']
  154. while True:
  155. line = file.readline()
  156. line = line.rstrip()
  157. if not line:
  158. break
  159. header.append(line)
  160. header = yaml.load(StringIO('\n'.join(header)))
  161. return header
  162. def prepare(self):
  163. file = codecs.open(self.abspath, 'r')
  164. self.header = self._read_header(file)
  165. for h in self.header.items():
  166. if h:
  167. try:
  168. setattr(self, h[0], h[1])
  169. except:
  170. pass
  171. body = list()
  172. for line in file.readlines():
  173. body.append(line)
  174. self.body = ''.join(body)
  175. file.close()
  176. if self.kind == 'link':
  177. from urlparse import urlparse
  178. self.domain_name = urlparse(self.url).netloc
  179. elif self.kind == 'photo':
  180. pass
  181. elif self.kind == 'note':
  182. pass
  183. elif self.kind == 'writing':
  184. pass
  185. def render(self):
  186. if not self.header['public']:
  187. return False
  188. try:
  189. os.makedirs(os.path.dirname(self.destination))
  190. except:
  191. pass
  192. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  193. context['entry'] = self
  194. # this is redundant ! every time we render entry we get_template?
  195. # todo: make template class property !
  196. template = jinja_env.get_template("entry.html")
  197. try:
  198. html = template.render(context)
  199. except Exception, e:
  200. print context
  201. print self.path
  202. print e
  203. sys.exit()
  204. destination = codecs.open(
  205. self.destination, 'w', CONFIG['content_encoding'])
  206. destination.write(html)
  207. destination.close()
  208. # before returning write log to csv
  209. # file name, date first seen, date rendered
  210. # self.path , date-first-seen, if rendered datetime.now
  211. return True
  212. class Link(Entry):
  213. def __init__(self, path):
  214. super(Link, self).__init__(path)
  215. @property
  216. def permalink(self):
  217. print "self.url", self.url
  218. raw_input()
  219. return self.url
  220. def entry_factory():
  221. pass
  222. def _sort_entries(entries):
  223. _entries = dict()
  224. sorted_entries = list()
  225. for entry in entries:
  226. _published = entry.header['published'].isoformat()
  227. _entries[_published] = entry
  228. sorted_keys = sorted(_entries.keys())
  229. sorted_keys.reverse()
  230. for key in sorted_keys:
  231. sorted_entries.append(_entries[key])
  232. return sorted_entries
  233. def render_index(entries):
  234. """
  235. this function renders the main page located at index.html
  236. under oz123.github.com
  237. """
  238. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  239. context['entries'] = entries[:10]
  240. template = jinja_env.get_template('entry_index.html')
  241. html = template.render(context)
  242. destination = codecs.open("%s/index.html" % CONFIG[
  243. 'output_to'], 'w', CONFIG['content_encoding'])
  244. destination.write(html)
  245. destination.close()
  246. def render_archive(entries, render_to=None):
  247. """
  248. this function creates the archive page
  249. """
  250. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  251. context['entries'] = entries[ARCHIVE_SIZE:]
  252. template = jinja_env.get_template('archive_index.html')
  253. html = template.render(context)
  254. if not render_to:
  255. render_to = "%s/archive/index.html" % CONFIG['output_to']
  256. dir_util.mkpath("%s/archive" % CONFIG['output_to'])
  257. destination = codecs.open("%s/archive/index.html" % CONFIG[
  258. 'output_to'], 'w', CONFIG['content_encoding'])
  259. destination.write(html)
  260. destination.close()
  261. def render_atom_feed(entries, render_to=None):
  262. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  263. context['entries'] = entries[:10]
  264. template = jinja_env.get_template('atom.xml')
  265. html = template.render(context)
  266. if not render_to:
  267. render_to = "%s/atom.xml" % CONFIG['output_to']
  268. destination = codecs.open(render_to, 'w', CONFIG['content_encoding'])
  269. destination.write(html)
  270. destination.close()
  271. def render_tag_pages(tag_tree):
  272. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  273. for t in tag_tree.items():
  274. context['tag'] = t[1]['tag']
  275. context['entries'] = _sort_entries(t[1]['entries'])
  276. destination = "%s/tags/%s" % (CONFIG['output_to'], context['tag'].slug)
  277. try:
  278. os.makedirs(destination)
  279. except:
  280. pass
  281. template = jinja_env.get_template('tag_index.html')
  282. html = template.render(context)
  283. file = codecs.open("%s/index.html" %
  284. destination, 'w', CONFIG['content_encoding'])
  285. file.write(html)
  286. file.close()
  287. render_atom_feed(context[
  288. 'entries'], render_to="%s/atom.xml" % destination)
  289. def build():
  290. print
  291. print "Rendering website now..."
  292. print
  293. print " entries:"
  294. entries = list()
  295. tags = dict()
  296. for root, dirs, files in os.walk(CONFIG['content_root']):
  297. for filename in files:
  298. try:
  299. if filename.endswith('md') or filename.endswith('markdown'):
  300. entry = Entry(os.path.join(root, filename))
  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. except Exception, e:
  312. print "Found some problem in: ", filename
  313. print e
  314. print "Please correct this problem ..."
  315. sys.exit()
  316. print " :done"
  317. print
  318. print " tag pages & their atom feeds:"
  319. render_tag_pages(tags)
  320. print " :done"
  321. print
  322. print " site wide index"
  323. entries = _sort_entries(entries)
  324. render_index(entries)
  325. print "................done"
  326. print " archive index"
  327. render_archive(entries)
  328. print "................done"
  329. print " site wide atom feeds"
  330. render_atom_feed(entries)
  331. print "...........done"
  332. print
  333. print "All done "
  334. class StoppableHTTPServer(BaseHTTPServer.HTTPServer):
  335. def server_bind(self):
  336. BaseHTTPServer.HTTPServer.server_bind(self)
  337. self.socket.settimeout(1)
  338. self.run = True
  339. def get_request(self):
  340. while self.run:
  341. try:
  342. sock, addr = self.socket.accept()
  343. sock.settimeout(None)
  344. return (sock, addr)
  345. except socket.timeout:
  346. pass
  347. def stop(self):
  348. self.run = False
  349. def serve(self):
  350. while self.run:
  351. self.handle_request()
  352. def preview(PREVIEW_ADDR='127.0.1.1', PREVIEW_PORT=11000):
  353. """
  354. launch an HTTP to preview the website
  355. """
  356. os.chdir(CONFIG['output_to'])
  357. print "and ready to test at http://127.0.0.1:%d" % CONFIG['http_port']
  358. print "Hit Ctrl+C to exit"
  359. try:
  360. httpd = StoppableHTTPServer(("127.0.0.1", CONFIG['http_port']),
  361. SimpleHTTPServer.SimpleHTTPRequestHandler)
  362. thread.start_new_thread(httpd.serve, ())
  363. sp.call('open http://127.0.0.1:%d' % CONFIG['http_port'], shell=True)
  364. while True:
  365. continue
  366. except KeyboardInterrupt:
  367. print
  368. print "Shutting Down... Bye!."
  369. print
  370. httpd.stop()
  371. def publish(GITDIRECTORY=CONFIG['output_to']):
  372. sp.call('git push', cwd=GITDIRECTORY, shell=True)
  373. def new_post(GITDIRECTORY=CONFIG['output_to'],
  374. kind=KINDS['writing']):
  375. """
  376. This function should create a template for a new post with a title
  377. read from the user input.
  378. Most other fields should be defaults.
  379. """
  380. title = raw_input("Give the title of the post: ")
  381. while ':' in title:
  382. title = raw_input("Give the title of the post (':' not allowed): ")
  383. author = CONFIG['author']
  384. date = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d')
  385. tags = '[' + raw_input("Give the tags, separated by ', ':") + ']'
  386. published = 'yes'
  387. chronological = 'yes'
  388. summary = ("summary: |\n Type your summary here.\n Do not change the "
  389. "indentation"
  390. "to the left\n ...\n\nStart writing your post here!")
  391. # make file name
  392. fname = os.path.join(os.getcwd(), 'content', kind['name_plural'],
  393. datetime.datetime.strftime(datetime.datetime.now(),
  394. '%Y'),
  395. date+'-'+title.replace(' ', '-')+'.markdown')
  396. with open(fname, 'w') as npost:
  397. npost.write('title: %s\n' % title)
  398. npost.write('author: %s\n' % author)
  399. npost.write('published: %s\n' % date)
  400. npost.write('tags: %s\n' % tags)
  401. npost.write('public: %s\n' % published)
  402. npost.write('chronological: %s\n' % chronological)
  403. npost.write('kind: %s\n' % kind['name'])
  404. npost.write('%s' % summary)
  405. os.system('%s %s' % (CONFIG['editor'], fname))
  406. def clean(GITDIRECTORY=CONFIG['output_to']):
  407. directoriestoclean = ["writings", "notes", "links", "tags", "archive"]
  408. os.chdir(GITDIRECTORY)
  409. for directory in directoriestoclean:
  410. shutil.rmtree(directory)
  411. def dist(SOURCEDIR=os.getcwd()+"/content/",
  412. DESTDIR=CONFIG['raw_content']):
  413. """
  414. sync raw files from SOURCE to DEST
  415. """
  416. sp.call(["rsync", "-avP", SOURCEDIR, DESTDIR], shell=False,
  417. cwd=os.getcwd())
  418. if __name__ == '__main__':
  419. parser = argparse.ArgumentParser(
  420. description='blogit - a tool to blog on github.')
  421. parser.add_argument('-b', '--build', action="store_true",
  422. help='convert the markdown files to HTML')
  423. parser.add_argument('-p', '--preview', action="store_true",
  424. help='Launch HTTP server to preview the website')
  425. parser.add_argument('-c', '--clean', action="store_true",
  426. help='clean output files')
  427. parser.add_argument('-n', '--new', action="store_true",
  428. help='create new post')
  429. parser.add_argument('-d', '--dist', action="store_true",
  430. help='sync raw files from SOURCE to DEST')
  431. parser.add_argument('--publish', action="store_true",
  432. help='push built HTML to git upstream')
  433. args = parser.parse_args()
  434. if len(sys.argv) < 2:
  435. parser.print_help()
  436. sys.exit()
  437. if args.clean:
  438. clean()
  439. if args.build:
  440. build()
  441. if args.dist:
  442. dist()
  443. if args.preview:
  444. preview()
  445. if args.new:
  446. new_post()
  447. if args.publish:
  448. publish()