blogit2.py 18 KB

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