blogit2.py 20 KB

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