blogit2.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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 markdown or txt files, no images
  31. allowed!
  32. """
  33. import os
  34. import re
  35. import datetime
  36. import argparse
  37. import sys
  38. import operator
  39. from distutils import dir_util
  40. import shutil
  41. from StringIO import StringIO
  42. import codecs
  43. import subprocess as sp
  44. import SimpleHTTPServer
  45. import BaseHTTPServer
  46. import socket
  47. import SocketServer
  48. import thread
  49. try:
  50. import yaml # in debian python-yaml
  51. from jinja2 import Environment, FileSystemLoader # in debian python-jinja2
  52. except ImportError, e: # pragma: no coverage
  53. print e
  54. print "On Debian based system you can install the dependencies with: "
  55. print "apt-get install python-yaml python-jinja2"
  56. sys.exit(1)
  57. try:
  58. import markdown2
  59. renderer = 'md2'
  60. except ImportError, e: # pragma: no coverage
  61. try:
  62. import markdown
  63. renderer = 'md1'
  64. except ImportError, e:
  65. print e
  66. print "try: sudo pip install markdown2"
  67. sys.exit(1)
  68. import tinydb
  69. from tinydb import Query
  70. sys.path.insert(0, os.getcwd())
  71. from conf import CONFIG, ARCHIVE_SIZE, GLOBAL_TEMPLATE_CONTEXT, KINDS
  72. jinja_env = Environment(loader=FileSystemLoader(CONFIG['templates']))
  73. class DataBase(object):
  74. def __init__(self, path):
  75. _db = tinydb.TinyDB(path)
  76. self.posts = _db.table('posts')
  77. self.tags = _db.table('tags')
  78. self.pages = _db.table('pages')
  79. self.templates = _db.table('templates')
  80. self._db = _db
  81. DB = DataBase(os.path.join(CONFIG['content_root'], 'blogit.db'))
  82. class Tag(object):
  83. def __init__(self, name):
  84. self.name = name
  85. self.prepare()
  86. self.permalink = GLOBAL_TEMPLATE_CONTEXT["site_url"]
  87. self.table = DB.tags
  88. Tags = Query()
  89. tag = self.table.get(Tags.name == self.name)
  90. if not tag:
  91. self.table.insert({'name': self.name, 'post_ids': []})
  92. def prepare(self):
  93. _slug = self.name.lower()
  94. _slug = re.sub(r'[;;,. ]', '-', _slug)
  95. self.slug = _slug
  96. @property
  97. def posts(self):
  98. """
  99. return a list of posts tagged with Tag
  100. """
  101. Tags = Query()
  102. tag = self.table.get(Tags.name == self.name)
  103. return tag['post_ids']
  104. @posts.setter
  105. def posts(self, post_ids):
  106. if not isinstance(post_ids, list):
  107. raise ValueError("post_ids must be of type list")
  108. Tags = Query()
  109. tag = self.table.get(Tags.name == self.name)
  110. if not tag: # pragma: no coverage
  111. raise ValueError("Tag %s not found" % self.name)
  112. if tag:
  113. new = set(post_ids) - set(tag['post_ids'])
  114. tag['post_ids'].extend(list(new))
  115. self.table.update({'post_ids': tag['post_ids']}, eids=[tag.eid])
  116. @property
  117. def entries(self):
  118. _entries = []
  119. Posts = Query()
  120. for id in self.posts:
  121. post = DB.posts.get(eid=id)
  122. if not post: # pragma: no coverage
  123. raise ValueError("no post found for eid %s" % id)
  124. entry = Entry(os.path.join(CONFIG['content_root'],
  125. post['filename']))
  126. _entries.append(entry)
  127. return _entries
  128. def render(self):
  129. """Render html page and atom feed"""
  130. self.destination = "%s/tags/%s" % (CONFIG['output_to'],
  131. self.slug)
  132. template = jinja_env.get_template('tag_index.html')
  133. try:
  134. os.makedirs(self.destination)
  135. except OSError: # pragma: no coverage
  136. pass
  137. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  138. context['tag'] = self
  139. context['entries'] = _sort_entries(self.entries)
  140. sorted_entries = _sort_entries(self.entries)
  141. encoding = CONFIG['content_encoding']
  142. render_to = "%s/tags/%s" % (CONFIG['output_to'], self.slug)
  143. jobs = [{'tname': 'tag_index.html',
  144. 'output': codecs.open("%s/index.html" % render_to, 'w', encoding),
  145. 'entries': sorted_entries},
  146. {'tname': 'atom.xml',
  147. 'output': codecs.open("%s/atom.xml" % render_to, 'w', encoding),
  148. 'entries': sorted_entries[:10]}
  149. ]
  150. for j in jobs:
  151. template = jinja_env.get_template(j['tname'])
  152. context['entries'] = j['entries']
  153. html = template.render(context)
  154. j['output'].write(html)
  155. j['output'].close()
  156. return True
  157. class Entry(object):
  158. def __init__(self, path):
  159. super(Entry, self).__init__()
  160. path = path.split('content/')[-1]
  161. self.path = path
  162. self.entry_template = jinja_env.get_template("entry.html")
  163. self.prepare()
  164. def __str__(self):
  165. return self.path
  166. def __repr__(self):
  167. return self.path
  168. @property
  169. def name(self):
  170. return os.path.splitext(os.path.basename(self.path))[0]
  171. @property
  172. def abspath(self):
  173. return os.path.abspath(os.path.join(CONFIG['content_root'], self.path))
  174. @property
  175. def destination(self):
  176. dest = "%s/%s/index.html" % (KINDS[
  177. self.kind]['name_plural'], self.name)
  178. print dest
  179. return os.path.join(CONFIG['output_to'], dest)
  180. @property
  181. def title(self):
  182. return self.header['title']
  183. @property
  184. def summary_html(self):
  185. return "%s" % markdown2.markdown(self.header['summary'].strip())
  186. @property
  187. def credits_html(self):
  188. return "%s" % markdown2.markdown(self.header['credits'].strip())
  189. @property
  190. def summary_atom(self):
  191. summarya = markdown2.markdown(self.header['summary'].strip())
  192. summarya = re.sub("<p>|</p>", "", summarya)
  193. more = '<a href="%s"> continue reading...</a>' % (self.permalink)
  194. return summarya+more
  195. @property
  196. def published_html(self):
  197. if self.kind in ['link', 'note', 'photo']:
  198. return self.header['published'].strftime("%B %d, %Y %I:%M %p")
  199. return self.header['published'].strftime("%B %d, %Y")
  200. @property
  201. def published_atom(self):
  202. return self.published.strftime("%Y-%m-%dT%H:%M:%SZ")
  203. @property
  204. def atom_id(self):
  205. return "tag:%s,%s:%s" % \
  206. (
  207. self.published.strftime("%Y-%m-%d"),
  208. self.permalink,
  209. GLOBAL_TEMPLATE_CONTEXT["site_url"]
  210. )
  211. @property
  212. def body_html(self):
  213. if renderer == 'md2':
  214. return markdown2.markdown(self.body, extras=['fenced-code-blocks',
  215. 'hilite',
  216. "tables"])
  217. if renderer == 'md1':
  218. return markdown.markdown(self.body,
  219. extensions=['fenced_code',
  220. 'codehilite(linenums=False)',
  221. 'tables'])
  222. @property
  223. def permalink(self):
  224. return "/%s/%s" % (KINDS[self.kind]['name_plural'], self.name)
  225. @property
  226. def tags(self):
  227. return [Tag(t) for t in self.header['tags']]
  228. def _read_header(self, file):
  229. header = ['---']
  230. while True:
  231. line = file.readline()
  232. line = line.rstrip()
  233. if not line:
  234. break
  235. header.append(line)
  236. header = yaml.load(StringIO('\n'.join(header)))
  237. # todo: dispatch header to attribute
  238. # todo: parse date from string to a datetime object
  239. return header
  240. def prepare(self):
  241. file = codecs.open(self.abspath, 'r')
  242. self.header = self._read_header(file)
  243. self.date = self.header['published']
  244. for k, v in self.header.items():
  245. try:
  246. setattr(self, k, v)
  247. except:
  248. pass
  249. body = file.readlines()
  250. self.body = ''.join(body)
  251. file.close()
  252. if self.kind == 'link':
  253. from urlparse import urlparse
  254. self.domain_name = urlparse(self.url).netloc
  255. elif self.kind == 'photo':
  256. pass
  257. elif self.kind == 'note':
  258. pass
  259. elif self.kind == 'writing':
  260. pass
  261. def render(self):
  262. if not self.header['public']:
  263. return False
  264. try:
  265. os.makedirs(os.path.dirname(self.destination))
  266. except OSError:
  267. pass
  268. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  269. context['entry'] = self
  270. try:
  271. html = self.entry_template.render(context)
  272. except Exception as e: # pragma: no cover
  273. print context
  274. print self.path
  275. print e
  276. sys.exit()
  277. destination = codecs.open(
  278. self.destination, 'w', CONFIG['content_encoding'])
  279. destination.write(html)
  280. destination.close()
  281. # before returning write log to csv
  282. # file name, date first seen, date rendered
  283. # self.path , date-first-seen, if rendered datetime.now
  284. return True
  285. class Link(Entry): # pragma: no coverage
  286. def __init__(self, path):
  287. super(Link, self).__init__(path)
  288. @property
  289. def permalink(self):
  290. print "self.url", self.url
  291. return self.url
  292. def _sort_entries(entries):
  293. """Sort all entries by date and reverse the list"""
  294. return list(reversed(sorted(entries, key=operator.attrgetter('date'))))
  295. def render_archive(entries, render_to=None):
  296. """
  297. This function creates the archive page
  298. To function it need to read:
  299. - entry title
  300. - entry publish date
  301. - entry permalink
  302. Until now, this was parsed from each entry YAML...
  303. It would be more convinient to read this from the DB.
  304. This requires changes for the database
  305. """
  306. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  307. context['entries'] = entries[ARCHIVE_SIZE:]
  308. template = jinja_env.get_template('archive_index.html')
  309. html = template.render(context)
  310. if not render_to:
  311. render_to = "%s/archive/index.html" % CONFIG['output_to']
  312. dir_util.mkpath("%s/archive" % CONFIG['output_to'])
  313. destination = codecs.open("%s/archive/index.html" % CONFIG[
  314. 'output_to'], 'w', CONFIG['content_encoding'])
  315. destination.write(html)
  316. destination.close()
  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 _get_last_entries():
  329. eids = [post.eid for post in DB.posts.all()]
  330. eids = sorted(eids, reverse=True)[-10:]
  331. entries = [Entry(DB.posts.get(eid=eid)['filename']) for eid in eids]
  332. return entries
  333. def update_index():
  334. """find the last 10 entries in the database and create the main
  335. page.
  336. Each entry in has an eid, so we only get the last 10 eids.
  337. This method also updates the ATOM feed.
  338. """
  339. entries = _get_last_entries()
  340. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  341. context['entries'] = entries
  342. for name, out in {'entry_index.html': 'index.html',
  343. 'atom.xml': 'atom.xml'}.items():
  344. template = jinja_env.get_template(name)
  345. html = template.render(context)
  346. destination = codecs.open("%s/%s" % (CONFIG['output_to'], out),
  347. 'w', CONFIG['content_encoding'])
  348. destination.write(html)
  349. destination.close()
  350. def new_build():
  351. """
  352. a. For each new post:
  353. 1. render html
  354. 2. find post tags
  355. 3. update atom feeds for old tags
  356. 4. create new atom feeds for new tags
  357. b. update index page
  358. c. update archive page
  359. """
  360. print
  361. print "Rendering website now..."
  362. print
  363. print " entries:"
  364. entries = list()
  365. tags = dict()
  366. root = CONFIG['content_root']
  367. for post_id, post in find_new_posts(DB.posts):
  368. try:
  369. entry = Entry(os.path.join(root, post))
  370. if entry.render():
  371. entries.append(entry)
  372. for tag in entry.tags:
  373. tag.posts = [post_id]
  374. tags[tag.name] = tag
  375. print " %s" % entry.path
  376. except Exception as e:
  377. print "Found some problem in: ", post
  378. print e
  379. print "Please correct this problem ..."
  380. sys.exit(1)
  381. for name, to in tags.iteritems():
  382. print "updating tag %s" % name
  383. to.render()
  384. # update index
  385. print "updating index"
  386. update_index()
  387. # update archive
  388. print "updating archive"
  389. # TODO
  390. class StoppableHTTPServer(BaseHTTPServer.HTTPServer): # pragma: no coverage
  391. def server_bind(self):
  392. BaseHTTPServer.HTTPServer.server_bind(self)
  393. self.socket.settimeout(1)
  394. self.run = True
  395. def get_request(self):
  396. while self.run:
  397. try:
  398. sock, addr = self.socket.accept()
  399. sock.settimeout(None)
  400. return (sock, addr)
  401. except socket.timeout:
  402. pass
  403. def stop(self):
  404. self.run = False
  405. def serve(self):
  406. while self.run:
  407. self.handle_request()
  408. def preview(): # pragma: no coverage
  409. """launch an HTTP to preview the website"""
  410. Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
  411. SocketServer.TCPServer.allow_reuse_address = True
  412. port = CONFIG['http_port']
  413. httpd = SocketServer.TCPServer(("", port), Handler)
  414. os.chdir(CONFIG['output_to'])
  415. print "and ready to test at http://127.0.0.1:%d" % CONFIG['http_port']
  416. print "Hit Ctrl+C to exit"
  417. try:
  418. httpd.serve_forever()
  419. except KeyboardInterrupt:
  420. httpd.shutdown()
  421. def publish(GITDIRECTORY=CONFIG['output_to']): # pragma: no coverage
  422. sp.call('git push', cwd=GITDIRECTORY, shell=True)
  423. def new_post(GITDIRECTORY=CONFIG['output_to'],
  424. kind=KINDS['writing']): # pragma: no coverage
  425. """
  426. This function should create a template for a new post with a title
  427. read from the user input.
  428. Most other fields should be defaults.
  429. """
  430. title = raw_input("Give the title of the post: ")
  431. while ':' in title:
  432. title = raw_input("Give the title of the post (':' not allowed): ")
  433. author = CONFIG['author']
  434. date = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d')
  435. tags = '[' + raw_input("Give the tags, separated by ', ':") + ']'
  436. published = 'yes'
  437. chronological = 'yes'
  438. summary = ("summary: |\n Type your summary here.\n Do not change the "
  439. "indentation"
  440. "to the left\n ...\n\nStart writing your post here!")
  441. # make file name
  442. fname = os.path.join(os.getcwd(), 'content', kind['name_plural'],
  443. datetime.datetime.strftime(datetime.datetime.now(),
  444. '%Y'),
  445. date+'-'+title.replace(' ', '-')+'.markdown')
  446. with open(fname, 'w') as npost:
  447. npost.write('title: %s\n' % title)
  448. npost.write('author: %s\n' % author)
  449. npost.write('published: %s\n' % date)
  450. npost.write('tags: %s\n' % tags)
  451. npost.write('public: %s\n' % published)
  452. npost.write('chronological: %s\n' % chronological)
  453. npost.write('kind: %s\n' % kind['name'])
  454. npost.write('%s' % summary)
  455. print '%s %s' % (CONFIG['editor'], repr(fname))
  456. os.system('%s %s' % (CONFIG['editor'], fname))
  457. def clean(GITDIRECTORY=CONFIG['output_to']): # pragma: no coverage
  458. directoriestoclean = ["writings", "notes", "links", "tags", "archive"]
  459. os.chdir(GITDIRECTORY)
  460. for directory in directoriestoclean:
  461. shutil.rmtree(directory)
  462. def dist(SOURCEDIR=os.getcwd()+"/content/",
  463. DESTDIR=CONFIG['raw_content']): # pragma: no coverage
  464. """
  465. sync raw files from SOURCE to DEST
  466. """
  467. sp.call(["rsync", "-avP", SOURCEDIR, DESTDIR], shell=False,
  468. cwd=os.getcwd())
  469. def main(): # pragma: no coverage
  470. parser = argparse.ArgumentParser(
  471. description='blogit - a tool to blog on github.')
  472. parser.add_argument('-b', '--build', action="store_true",
  473. help='convert the markdown files to HTML')
  474. parser.add_argument('-p', '--preview', action="store_true",
  475. help='Launch HTTP server to preview the website')
  476. parser.add_argument('-c', '--clean', action="store_true",
  477. help='clean output files')
  478. parser.add_argument('-n', '--new', action="store_true",
  479. help='create new post')
  480. parser.add_argument('-d', '--dist', action="store_true",
  481. help='sync raw files from SOURCE to DEST')
  482. parser.add_argument('--publish', action="store_true",
  483. help='push built HTML to git upstream')
  484. args = parser.parse_args()
  485. if len(sys.argv) < 2:
  486. parser.print_help()
  487. sys.exit()
  488. if args.clean:
  489. clean()
  490. if args.build:
  491. new_build()
  492. if args.dist:
  493. dist()
  494. if args.preview:
  495. preview()
  496. if args.new:
  497. new_post()
  498. if args.publish:
  499. publish()
  500. if __name__ == '__main__': # pragma: no coverage
  501. main()