blogit2.py 21 KB

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