1
0

blogit2.py 19 KB

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