blogit2.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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. from tinydb import Query
  67. sys.path.insert(0, os.getcwdu())
  68. from conf import CONFIG, ARCHIVE_SIZE, GLOBAL_TEMPLATE_CONTEXT, KINDS, DB
  69. jinja_env = Environment(loader=FileSystemLoader(CONFIG['templates']))
  70. class Tag(object):
  71. def __init__(self, name):
  72. self.name = name
  73. self.prepare()
  74. self.permalink = GLOBAL_TEMPLATE_CONTEXT["site_url"]
  75. self.table = DB['tags']
  76. Tags = Query()
  77. tag = self.table.get(Tags.name == self.name)
  78. if not tag:
  79. self.table.insert({'name': self.name, 'post_ids': []})
  80. def prepare(self):
  81. _slug = self.name.lower()
  82. _slug = re.sub(r'[;;,. ]', '-', _slug)
  83. self.slug = _slug
  84. @property
  85. def posts(self):
  86. """
  87. return a list of posts tagged with Tag
  88. """
  89. #import pdb; pdb.set_trace()
  90. Tags = Query()
  91. tag = self.table.get(Tags.name == self.name)
  92. return tag['post_ids']
  93. @posts.setter
  94. def posts(self, post_ids):
  95. if not isinstance(post_ids, list):
  96. raise ValueError("post_ids must be of type list")
  97. Tags = Query()
  98. tag = self.table.get(Tags.name == self.name)
  99. if tag:
  100. new = set(post_ids) - set(tag['post_ids'])
  101. tag['post_ids'].extend(list(new))
  102. self.table.update({'post_ids': tag['post_ids']}, eids=[tag.eid])
  103. else:
  104. self.table.insert({'name': self.name, 'post_ids': post_ids})
  105. class Entry(object):
  106. def __init__(self, path):
  107. super(Entry, self).__init__()
  108. path = path.split('content/')[-1]
  109. self.path = path
  110. self.entry_template = jinja_env.get_template("entry.html")
  111. self.prepare()
  112. def __str__(self):
  113. return self.path
  114. def __repr__(self):
  115. return self.path
  116. @property
  117. def name(self):
  118. return os.path.splitext(os.path.basename(self.path))[0]
  119. @property
  120. def abspath(self):
  121. return os.path.abspath(os.path.join(CONFIG['content_root'], self.path))
  122. @property
  123. def destination(self):
  124. dest = "%s/%s/index.html" % (KINDS[
  125. self.kind]['name_plural'], self.name)
  126. print dest
  127. return os.path.join(CONFIG['output_to'], dest)
  128. @property
  129. def title(self):
  130. return self.header['title']
  131. @property
  132. def summary_html(self):
  133. return "%s" % markdown2.markdown(self.header['summary'].strip())
  134. @property
  135. def credits_html(self):
  136. return "%s" % markdown2.markdown(self.header['credits'].strip())
  137. @property
  138. def summary_atom(self):
  139. summarya = markdown2.markdown(self.header['summary'].strip())
  140. summarya = re.sub("<p>|</p>", "", summarya)
  141. more = '<a href="%s"> continue reading...</a>' % (self.permalink)
  142. return summarya+more
  143. @property
  144. def published_html(self):
  145. if self.kind in ['link', 'note', 'photo']:
  146. return self.header['published'].strftime("%B %d, %Y %I:%M %p")
  147. return self.header['published'].strftime("%B %d, %Y")
  148. @property
  149. def published_atom(self):
  150. return self.published.strftime("%Y-%m-%dT%H:%M:%SZ")
  151. @property
  152. def atom_id(self):
  153. return "tag:%s,%s:%s" % \
  154. (
  155. self.published.strftime("%Y-%m-%d"),
  156. self.permalink,
  157. GLOBAL_TEMPLATE_CONTEXT["site_url"]
  158. )
  159. @property
  160. def body_html(self):
  161. if renderer == 'md2':
  162. return markdown2.markdown(self.body, extras=['fenced-code-blocks',
  163. 'hilite',
  164. "tables"])
  165. if renderer == 'md1':
  166. return markdown.markdown(self.body,
  167. extensions=['fenced_code',
  168. 'codehilite(linenums=False)',
  169. 'tables'])
  170. @property
  171. def permalink(self):
  172. return "/%s/%s" % (KINDS[self.kind]['name_plural'], self.name)
  173. @property
  174. def tags(self):
  175. return [Tag(t) for t in self.header['tags']]
  176. def _read_header(self, file):
  177. header = ['---']
  178. while True:
  179. line = file.readline()
  180. line = line.rstrip()
  181. if not line:
  182. break
  183. header.append(line)
  184. header = yaml.load(StringIO('\n'.join(header)))
  185. return header
  186. def prepare(self):
  187. file = codecs.open(self.abspath, 'r')
  188. self.header = self._read_header(file)
  189. for h in self.header.items():
  190. if h:
  191. try:
  192. setattr(self, h[0], h[1])
  193. except:
  194. pass
  195. body = file.readlines()
  196. self.body = ''.join(body)
  197. file.close()
  198. if self.kind == 'link':
  199. from urlparse import urlparse
  200. self.domain_name = urlparse(self.url).netloc
  201. elif self.kind == 'photo':
  202. pass
  203. elif self.kind == 'note':
  204. pass
  205. elif self.kind == 'writing':
  206. pass
  207. def render(self):
  208. if not self.header['public']:
  209. return False
  210. try:
  211. os.makedirs(os.path.dirname(self.destination))
  212. except:
  213. pass
  214. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  215. context['entry'] = self
  216. try:
  217. html = self.entry_template.render(context)
  218. except Exception as e:
  219. print context
  220. print self.path
  221. print e
  222. sys.exit()
  223. destination = codecs.open(
  224. self.destination, 'w', CONFIG['content_encoding'])
  225. destination.write(html)
  226. destination.close()
  227. # before returning write log to csv
  228. # file name, date first seen, date rendered
  229. # self.path , date-first-seen, if rendered datetime.now
  230. return True
  231. class Link(Entry):
  232. def __init__(self, path):
  233. super(Link, self).__init__(path)
  234. @property
  235. def permalink(self):
  236. print "self.url", self.url
  237. raw_input()
  238. return self.url
  239. def entry_factory():
  240. pass
  241. def _sort_entries(entries):
  242. _entries = dict()
  243. sorted_entries = list()
  244. for entry in entries:
  245. _published = entry.header['published'].isoformat()
  246. _entries[_published] = entry
  247. sorted_keys = sorted(_entries.keys())
  248. sorted_keys.reverse()
  249. for key in sorted_keys:
  250. sorted_entries.append(_entries[key])
  251. return sorted_entries
  252. def render_index(entries):
  253. """
  254. this function renders the main page located at index.html
  255. under oz123.github.com
  256. """
  257. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  258. context['entries'] = entries[:10]
  259. template = jinja_env.get_template('entry_index.html')
  260. html = template.render(context)
  261. destination = codecs.open("%s/index.html" % CONFIG[
  262. 'output_to'], 'w', CONFIG['content_encoding'])
  263. destination.write(html)
  264. destination.close()
  265. def render_archive(entries, render_to=None):
  266. """
  267. this function creates the archive page
  268. """
  269. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  270. context['entries'] = entries[ARCHIVE_SIZE:]
  271. template = jinja_env.get_template('archive_index.html')
  272. html = template.render(context)
  273. if not render_to:
  274. render_to = "%s/archive/index.html" % CONFIG['output_to']
  275. dir_util.mkpath("%s/archive" % CONFIG['output_to'])
  276. destination = codecs.open("%s/archive/index.html" % CONFIG[
  277. 'output_to'], 'w', CONFIG['content_encoding'])
  278. destination.write(html)
  279. destination.close()
  280. def render_atom_feed(entries, render_to=None):
  281. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  282. context['entries'] = entries[:10]
  283. template = jinja_env.get_template('atom.xml')
  284. html = template.render(context)
  285. if not render_to:
  286. render_to = "%s/atom.xml" % CONFIG['output_to']
  287. destination = codecs.open(render_to, 'w', CONFIG['content_encoding'])
  288. destination.write(html)
  289. destination.close()
  290. def render_tag_pages(tag_tree):
  291. """
  292. tag_tree is a dictionary witht the following structure:
  293. {'python': {'tag': <__main__.Tag object at 0x7f0e56200ed0>,
  294. 'entries': [post1.md, post2.md, post3.md]},
  295. 'git': {'tag': <__main__.Tag object at 0x7f0e5623c2d0>,
  296. 'entries': [post1.md, post2.md, post3.md]},
  297. 'bash': {'tag': <__main__.Tag object at 0x7f0e5623c0d0>,
  298. 'entries': [post1.md, post2.md, post3.md]}}
  299. """
  300. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  301. for k, v in tag_tree.items():
  302. context['tag'] = v['tag']
  303. context['entries'] = _sort_entries(v['entries'])
  304. destination = "%s/tags/%s" % (CONFIG['output_to'], context['tag'].slug)
  305. try:
  306. os.makedirs(destination)
  307. except:
  308. pass
  309. template = jinja_env.get_template('tag_index.html')
  310. html = template.render(context)
  311. file = codecs.open("%s/index.html" %
  312. destination, 'w', CONFIG['content_encoding'])
  313. file.write(html)
  314. file.close()
  315. render_atom_feed(context[
  316. 'entries'], render_to="%s/atom.xml" % destination)
  317. def find_new_posts(posts_table):
  318. """
  319. Walk content dir, put each post in the database
  320. """
  321. Posts = Query()
  322. for root, dirs, files in os.walk(CONFIG['content_root']):
  323. for filename in files:
  324. if filename.endswith(('md', 'markdown')):
  325. if not posts_table.contains(Posts.filename == filename):
  326. post_id = posts_table.insert({'filename': filename})
  327. yield post_id, filename
  328. def update_tags(tags):
  329. try:
  330. tags['python']['tag'].posts
  331. except KeyError:
  332. pass
  333. for t in tags:
  334. pass
  335. def new_build():
  336. """
  337. a. For each new post:
  338. 1. render html
  339. 2. find post tags
  340. 3. update atom feeds for old tags
  341. 4. create new atom feeds for new tags
  342. b. update index page
  343. c. update archive page
  344. """
  345. print
  346. print "Rendering website now..."
  347. print
  348. print " entries:"
  349. entries = list()
  350. tags = dict()
  351. root = CONFIG['content_root']
  352. for post_id, post in find_new_posts(DB['posts']):
  353. try:
  354. entry = Entry(os.path.join(root, post))
  355. if entry.render():
  356. entries.append(entry)
  357. for tag in entry.tags:
  358. if tag.name not in tags:
  359. tags[tag.name] = {
  360. 'tag': tag,
  361. 'entries': list(),
  362. }
  363. tags[tag.name]['entries'].append(entry)
  364. print " %s" % entry.path
  365. except Exception as e:
  366. print "Found some problem in: ", post
  367. print e
  368. print "Please correct this problem ..."
  369. sys.exit()
  370. update_tags(tags)
  371. render_tag_pages(tags)
  372. def build():
  373. print
  374. print "Rendering website now..."
  375. print
  376. print " entries:"
  377. entries = list()
  378. tags = dict()
  379. for root, dirs, files in os.walk(CONFIG['content_root']):
  380. for filename in files:
  381. try:
  382. if filename.endswith(('md', 'markdown')):
  383. entry = Entry(os.path.join(root, filename))
  384. if entry.render():
  385. entries.append(entry)
  386. for tag in entry.tags:
  387. if tag.name not in tags:
  388. tags[tag.name] = {
  389. 'tag': tag,
  390. 'entries': list(),
  391. }
  392. tags[tag.name]['entries'].append(entry)
  393. print " %s" % entry.path
  394. except Exception as e:
  395. print "Found some problem in: ", filename
  396. print e
  397. print "Please correct this problem ..."
  398. sys.exit()
  399. print " :done"
  400. print
  401. print " tag pages & their atom feeds:"
  402. render_tag_pages(tags)
  403. print " :done"
  404. print
  405. print " site wide index"
  406. entries = _sort_entries(entries)
  407. render_index(entries)
  408. print "................done"
  409. print " archive index"
  410. render_archive(entries)
  411. print "................done"
  412. print " site wide atom feeds"
  413. render_atom_feed(entries)
  414. print "...........done"
  415. print
  416. print "All done "
  417. class StoppableHTTPServer(BaseHTTPServer.HTTPServer):
  418. def server_bind(self):
  419. BaseHTTPServer.HTTPServer.server_bind(self)
  420. self.socket.settimeout(1)
  421. self.run = True
  422. def get_request(self):
  423. while self.run:
  424. try:
  425. sock, addr = self.socket.accept()
  426. sock.settimeout(None)
  427. return (sock, addr)
  428. except socket.timeout:
  429. pass
  430. def stop(self):
  431. self.run = False
  432. def serve(self):
  433. while self.run:
  434. self.handle_request()
  435. def preview(PREVIEW_ADDR='127.0.1.1', PREVIEW_PORT=11000):
  436. """
  437. launch an HTTP to preview the website
  438. """
  439. os.chdir(CONFIG['output_to'])
  440. print "and ready to test at http://127.0.0.1:%d" % CONFIG['http_port']
  441. print "Hit Ctrl+C to exit"
  442. try:
  443. httpd = StoppableHTTPServer(("127.0.0.1", CONFIG['http_port']),
  444. SimpleHTTPServer.SimpleHTTPRequestHandler)
  445. thread.start_new_thread(httpd.serve, ())
  446. sp.call('xdg-open http://127.0.0.1:%d' % CONFIG['http_port'],
  447. shell=True)
  448. while True:
  449. continue
  450. except KeyboardInterrupt:
  451. print
  452. print "Shutting Down... Bye!."
  453. print
  454. httpd.stop()
  455. def publish(GITDIRECTORY=CONFIG['output_to']):
  456. sp.call('git push', cwd=GITDIRECTORY, shell=True)
  457. def new_post(GITDIRECTORY=CONFIG['output_to'],
  458. kind=KINDS['writing']):
  459. """
  460. This function should create a template for a new post with a title
  461. read from the user input.
  462. Most other fields should be defaults.
  463. """
  464. title = raw_input("Give the title of the post: ")
  465. while ':' in title:
  466. title = raw_input("Give the title of the post (':' not allowed): ")
  467. author = CONFIG['author']
  468. date = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d')
  469. tags = '[' + raw_input("Give the tags, separated by ', ':") + ']'
  470. published = 'yes'
  471. chronological = 'yes'
  472. summary = ("summary: |\n Type your summary here.\n Do not change the "
  473. "indentation"
  474. "to the left\n ...\n\nStart writing your post here!")
  475. # make file name
  476. fname = os.path.join(os.getcwd(), 'content', kind['name_plural'],
  477. datetime.datetime.strftime(datetime.datetime.now(),
  478. '%Y'),
  479. date+'-'+title.replace(' ', '-')+'.markdown')
  480. with open(fname, 'w') as npost:
  481. npost.write('title: %s\n' % title)
  482. npost.write('author: %s\n' % author)
  483. npost.write('published: %s\n' % date)
  484. npost.write('tags: %s\n' % tags)
  485. npost.write('public: %s\n' % published)
  486. npost.write('chronological: %s\n' % chronological)
  487. npost.write('kind: %s\n' % kind['name'])
  488. npost.write('%s' % summary)
  489. print '%s %s' % (CONFIG['editor'], repr(fname))
  490. os.system('%s %s' % (CONFIG['editor'], fname))
  491. def clean(GITDIRECTORY=CONFIG['output_to']):
  492. directoriestoclean = ["writings", "notes", "links", "tags", "archive"]
  493. os.chdir(GITDIRECTORY)
  494. for directory in directoriestoclean:
  495. shutil.rmtree(directory)
  496. def dist(SOURCEDIR=os.getcwd()+"/content/",
  497. DESTDIR=CONFIG['raw_content']):
  498. """
  499. sync raw files from SOURCE to DEST
  500. """
  501. sp.call(["rsync", "-avP", SOURCEDIR, DESTDIR], shell=False,
  502. cwd=os.getcwd())
  503. if __name__ == '__main__':
  504. parser = argparse.ArgumentParser(
  505. description='blogit - a tool to blog on github.')
  506. parser.add_argument('-b', '--build', action="store_true",
  507. help='convert the markdown files to HTML')
  508. parser.add_argument('-p', '--preview', action="store_true",
  509. help='Launch HTTP server to preview the website')
  510. parser.add_argument('-c', '--clean', action="store_true",
  511. help='clean output files')
  512. parser.add_argument('-n', '--new', action="store_true",
  513. help='create new post')
  514. parser.add_argument('-d', '--dist', action="store_true",
  515. help='sync raw files from SOURCE to DEST')
  516. parser.add_argument('--publish', action="store_true",
  517. help='push built HTML to git upstream')
  518. args = parser.parse_args()
  519. if len(sys.argv) < 2:
  520. parser.print_help()
  521. sys.exit()
  522. if args.clean:
  523. clean()
  524. if args.build:
  525. build()
  526. if args.dist:
  527. dist()
  528. if args.preview:
  529. preview()
  530. if args.new:
  531. new_post()
  532. if args.publish:
  533. publish()