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.entry_template = jinja_env.get_template("entry.html")
  85. self.prepare()
  86. def __str__(self):
  87. return self.path
  88. def __repr__(self):
  89. return self.path
  90. @property
  91. def name(self):
  92. return os.path.splitext(os.path.basename(self.path))[0]
  93. @property
  94. def abspath(self):
  95. return os.path.abspath(os.path.join(CONFIG['content_root'], self.path))
  96. @property
  97. def destination(self):
  98. dest = "%s/%s/index.html" % (KINDS[
  99. self.kind]['name_plural'], self.name)
  100. print dest
  101. return os.path.join(CONFIG['output_to'], dest)
  102. @property
  103. def title(self):
  104. return self.header['title']
  105. @property
  106. def summary_html(self):
  107. return "%s" % markdown2.markdown(self.header['summary'].strip())
  108. @property
  109. def credits_html(self):
  110. return "%s" % markdown2.markdown(self.header['credits'].strip())
  111. @property
  112. def summary_atom(self):
  113. summarya = markdown2.markdown(self.header['summary'].strip())
  114. summarya = re.sub("<p>|</p>", "", summarya)
  115. more = '<a href="%s"> continue reading...</a>' % (self.permalink)
  116. return summarya+more
  117. @property
  118. def published_html(self):
  119. if self.kind in ['link', 'note', 'photo']:
  120. return self.header['published'].strftime("%B %d, %Y %I:%M %p")
  121. return self.header['published'].strftime("%B %d, %Y")
  122. @property
  123. def published_atom(self):
  124. return self.published.strftime("%Y-%m-%dT%H:%M:%SZ")
  125. @property
  126. def atom_id(self):
  127. return "tag:%s,%s:%s" % \
  128. (
  129. self.published.strftime("%Y-%m-%d"),
  130. self.permalink,
  131. GLOBAL_TEMPLATE_CONTEXT["site_url"]
  132. )
  133. @property
  134. def body_html(self):
  135. if renderer == 'md2':
  136. return markdown2.markdown(self.body, extras=['fenced-code-blocks',
  137. 'hilite',
  138. "tables"])
  139. if renderer == 'md1':
  140. return markdown.markdown(self.body,
  141. extensions=['fenced_code',
  142. 'codehilite(linenums=False)',
  143. 'tables'])
  144. @property
  145. def permalink(self):
  146. return "/%s/%s" % (KINDS[self.kind]['name_plural'], self.name)
  147. @property
  148. def tags(self):
  149. tags = list()
  150. for t in self.header['tags']:
  151. tags.append(Tag(t))
  152. return tags
  153. def _read_header(self, file):
  154. header = ['---']
  155. while True:
  156. line = file.readline()
  157. line = line.rstrip()
  158. if not line:
  159. break
  160. header.append(line)
  161. header = yaml.load(StringIO('\n'.join(header)))
  162. return header
  163. def prepare(self):
  164. file = codecs.open(self.abspath, 'r')
  165. self.header = self._read_header(file)
  166. for h in self.header.items():
  167. if h:
  168. try:
  169. setattr(self, h[0], h[1])
  170. except:
  171. pass
  172. body = list()
  173. for line in file.readlines():
  174. body.append(line)
  175. self.body = ''.join(body)
  176. file.close()
  177. if self.kind == 'link':
  178. from urlparse import urlparse
  179. self.domain_name = urlparse(self.url).netloc
  180. elif self.kind == 'photo':
  181. pass
  182. elif self.kind == 'note':
  183. pass
  184. elif self.kind == 'writing':
  185. pass
  186. def render(self):
  187. if not self.header['public']:
  188. return False
  189. try:
  190. os.makedirs(os.path.dirname(self.destination))
  191. except:
  192. pass
  193. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  194. context['entry'] = self
  195. try:
  196. html = self.entry_template.render(context)
  197. except Exception as e:
  198. print context
  199. print self.path
  200. print e
  201. sys.exit()
  202. destination = codecs.open(
  203. self.destination, 'w', CONFIG['content_encoding'])
  204. destination.write(html)
  205. destination.close()
  206. # before returning write log to csv
  207. # file name, date first seen, date rendered
  208. # self.path , date-first-seen, if rendered datetime.now
  209. return True
  210. class Link(Entry):
  211. def __init__(self, path):
  212. super(Link, self).__init__(path)
  213. @property
  214. def permalink(self):
  215. print "self.url", self.url
  216. raw_input()
  217. return self.url
  218. def entry_factory():
  219. pass
  220. def _sort_entries(entries):
  221. _entries = dict()
  222. sorted_entries = list()
  223. for entry in entries:
  224. _published = entry.header['published'].isoformat()
  225. _entries[_published] = entry
  226. sorted_keys = sorted(_entries.keys())
  227. sorted_keys.reverse()
  228. for key in sorted_keys:
  229. sorted_entries.append(_entries[key])
  230. return sorted_entries
  231. def render_index(entries):
  232. """
  233. this function renders the main page located at index.html
  234. under oz123.github.com
  235. """
  236. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  237. context['entries'] = entries[:10]
  238. template = jinja_env.get_template('entry_index.html')
  239. html = template.render(context)
  240. destination = codecs.open("%s/index.html" % CONFIG[
  241. 'output_to'], 'w', CONFIG['content_encoding'])
  242. destination.write(html)
  243. destination.close()
  244. def render_archive(entries, render_to=None):
  245. """
  246. this function creates the archive page
  247. """
  248. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  249. context['entries'] = entries[ARCHIVE_SIZE:]
  250. template = jinja_env.get_template('archive_index.html')
  251. html = template.render(context)
  252. if not render_to:
  253. render_to = "%s/archive/index.html" % CONFIG['output_to']
  254. dir_util.mkpath("%s/archive" % CONFIG['output_to'])
  255. destination = codecs.open("%s/archive/index.html" % CONFIG[
  256. 'output_to'], 'w', CONFIG['content_encoding'])
  257. destination.write(html)
  258. destination.close()
  259. def render_atom_feed(entries, render_to=None):
  260. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  261. context['entries'] = entries[:10]
  262. template = jinja_env.get_template('atom.xml')
  263. html = template.render(context)
  264. if not render_to:
  265. render_to = "%s/atom.xml" % CONFIG['output_to']
  266. destination = codecs.open(render_to, 'w', CONFIG['content_encoding'])
  267. destination.write(html)
  268. destination.close()
  269. def render_tag_pages(tag_tree):
  270. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  271. for t in tag_tree.items():
  272. context['tag'] = t[1]['tag']
  273. context['entries'] = _sort_entries(t[1]['entries'])
  274. destination = "%s/tags/%s" % (CONFIG['output_to'], context['tag'].slug)
  275. try:
  276. os.makedirs(destination)
  277. except:
  278. pass
  279. template = jinja_env.get_template('tag_index.html')
  280. html = template.render(context)
  281. file = codecs.open("%s/index.html" %
  282. destination, 'w', CONFIG['content_encoding'])
  283. file.write(html)
  284. file.close()
  285. render_atom_feed(context[
  286. 'entries'], render_to="%s/atom.xml" % destination)
  287. def build():
  288. print
  289. print "Rendering website now..."
  290. print
  291. print " entries:"
  292. entries = list()
  293. tags = dict()
  294. for root, dirs, files in os.walk(CONFIG['content_root']):
  295. for filename in files:
  296. try:
  297. if filename.endswith(('md', 'markdown')):
  298. entry = Entry(os.path.join(root, filename))
  299. if entry.render():
  300. entries.append(entry)
  301. for tag in entry.tags:
  302. if tag.name not in tags:
  303. tags[tag.name] = {
  304. 'tag': tag,
  305. 'entries': list(),
  306. }
  307. tags[tag.name]['entries'].append(entry)
  308. print " %s" % entry.path
  309. except Exception as e:
  310. print "Found some problem in: ", filename
  311. print e
  312. print "Please correct this problem ..."
  313. sys.exit()
  314. print " :done"
  315. print
  316. print " tag pages & their atom feeds:"
  317. render_tag_pages(tags)
  318. print " :done"
  319. print
  320. print " site wide index"
  321. entries = _sort_entries(entries)
  322. render_index(entries)
  323. print "................done"
  324. print " archive index"
  325. render_archive(entries)
  326. print "................done"
  327. print " site wide atom feeds"
  328. render_atom_feed(entries)
  329. print "...........done"
  330. print
  331. print "All done "
  332. class StoppableHTTPServer(BaseHTTPServer.HTTPServer):
  333. def server_bind(self):
  334. BaseHTTPServer.HTTPServer.server_bind(self)
  335. self.socket.settimeout(1)
  336. self.run = True
  337. def get_request(self):
  338. while self.run:
  339. try:
  340. sock, addr = self.socket.accept()
  341. sock.settimeout(None)
  342. return (sock, addr)
  343. except socket.timeout:
  344. pass
  345. def stop(self):
  346. self.run = False
  347. def serve(self):
  348. while self.run:
  349. self.handle_request()
  350. def preview(PREVIEW_ADDR='127.0.1.1', PREVIEW_PORT=11000):
  351. """
  352. launch an HTTP to preview the website
  353. """
  354. os.chdir(CONFIG['output_to'])
  355. print "and ready to test at http://127.0.0.1:%d" % CONFIG['http_port']
  356. print "Hit Ctrl+C to exit"
  357. try:
  358. httpd = StoppableHTTPServer(("127.0.0.1", CONFIG['http_port']),
  359. SimpleHTTPServer.SimpleHTTPRequestHandler)
  360. thread.start_new_thread(httpd.serve, ())
  361. sp.call('xdg-open http://127.0.0.1:%d' % CONFIG['http_port'],
  362. shell=True)
  363. while True:
  364. continue
  365. except KeyboardInterrupt:
  366. print
  367. print "Shutting Down... Bye!."
  368. print
  369. httpd.stop()
  370. def publish(GITDIRECTORY=CONFIG['output_to']):
  371. sp.call('git push', cwd=GITDIRECTORY, shell=True)
  372. def new_post(GITDIRECTORY=CONFIG['output_to'],
  373. kind=KINDS['writing']):
  374. """
  375. This function should create a template for a new post with a title
  376. read from the user input.
  377. Most other fields should be defaults.
  378. """
  379. title = raw_input("Give the title of the post: ")
  380. while ':' in title:
  381. title = raw_input("Give the title of the post (':' not allowed): ")
  382. author = CONFIG['author']
  383. date = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d')
  384. tags = '[' + raw_input("Give the tags, separated by ', ':") + ']'
  385. published = 'yes'
  386. chronological = 'yes'
  387. summary = ("summary: |\n Type your summary here.\n Do not change the "
  388. "indentation"
  389. "to the left\n ...\n\nStart writing your post here!")
  390. # make file name
  391. fname = os.path.join(os.getcwd(), 'content', kind['name_plural'],
  392. datetime.datetime.strftime(datetime.datetime.now(),
  393. '%Y'),
  394. date+'-'+title.replace(' ', '-')+'.markdown')
  395. with open(fname, 'w') as npost:
  396. npost.write('title: %s\n' % title)
  397. npost.write('author: %s\n' % author)
  398. npost.write('published: %s\n' % date)
  399. npost.write('tags: %s\n' % tags)
  400. npost.write('public: %s\n' % published)
  401. npost.write('chronological: %s\n' % chronological)
  402. npost.write('kind: %s\n' % kind['name'])
  403. npost.write('%s' % summary)
  404. print '%s %s' % (CONFIG['editor'], repr(fname))
  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()