staticblog / controllers / default.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, glob
from gluon.template import render
from gluon.contrib.autolinks import expand_one
from highlight import PluginHighlight

session.forget()

POSTS_PER_PAGE = 5


def splitter(x):
    a,b = x.split(':',1)
    return a.strip(),b.strip()


@cache('folders',None)
def get_folders():
    folder = os.path.join(request.folder,'source_blog')
    return folder, [f for f in os.listdir(folder)
                    if os.path.isdir(os.path.join(folder,f))]
FOLDER, FOLDERS = get_folders()


def get_subfolder(post_id):
    if not post_id:
        redirect(URL('index'))
    for f in FOLDERS:
        if f.startswith(post_id):
            return f
    redirect(URL('index'))


def get_info(subfolder):
    infofile = os.path.join(FOLDER, subfolder, 'info.txt')
    if os.path.exists(infofile):
        info = dict(splitter(line)
        for line in open(infofile).readlines()
        if ':' in line)
        return info
    return {}

highlight = PluginHighlight().install()  #We need plugin highlight installed

def convert2html(book_id,text):
    extra = {}
    def url2(*a,**b):
        b['args'] = [book_id]+b.get('args',[])
        return URL(*a,**b)
    def truncate(x): return x[:70]+'...' if len(x)>70 else x

    extra = highlight.extra
    extra['verbatim'] = lambda code: cgi.escape(code)
    extra['cite'] = lambda key: TAG.sup(
        '[',A(key,_href=URL('reference',args=(book_id,key)),
            _target='_blank'),']').xml()
    extra['inxx'] = lambda code: '<div class="inxx">'+code+'</div>'
    extra['ref'] = lambda code: '[ref:'+code+']'
    # extra['code'] = lambda code: CODE(code,language='web2py').xml()
    #rtn = MARKMIN(text.replace('\r',''),extra=extra,url=url2)
    rtn = MARKMIN(text, url=True, environment={},
        autolinks=lambda link: expand_one(link,{}))
    return rtn


def index():

    def read_extract(post_id):
        subfolder = get_subfolder(post_id)
        filename = os.path.join(FOLDER, subfolder, 'extract.markmin')
        if os.path.isfile(filename):
            content = open(filename).read()
            content = convert2html(post_id,content).xml()
            content = XML(content)
        else:
            content = ""
        return content

    try:
        page = int(request.args(0))
    except:
        page = 1

    posts = {}
    for subfolder in FOLDERS:
        posts[subfolder] = get_info(subfolder)

    count_posts = len(FOLDERS)
    lmda = page * POSTS_PER_PAGE - count_posts
    if lmda > POSTS_PER_PAGE:
        raise HTTP(400, 'Invalid page number')

    dest = os.path.join(request.folder, 'static_blog', 'posts-%s.html' % page)
    if not os.path.isfile(dest):
        filename = os.path.join(request.folder, 'views', 'posts.html')
        view_template = open(filename).read()
        content = render(view_template , context = locals())
        open(dest, 'w').write(content)
        content = XML(content)
    else:
        content = XML(open(dest).read())

    return dict(content=content)


def post():
    post_id=str(request.args(0)).split('-')[0]
    subfolder = get_subfolder(post_id)
    info = cache.ram('info_%s' % subfolder, lambda: get_info(subfolder), time_expire=60*60*24)
    filename = os.path.join(FOLDER, subfolder, 'post.markmin')
    dest = os.path.join(request.folder, 'static_blog', 'post-%s.html' % post_id)

    disqus_site = app_settings.disqus_site
    disqus_dev = app_settings.disqus_dev

    if not os.path.isfile(dest):
        content = open(filename).read()
        content = convert2html(post_id,content).xml()
        #if not os.path.exists(os.path.dirname(dest)):
        #    os.makedirs(os.path.dirname(dest))
        open(dest, 'w').write(content)
        content = XML(content)
        return locals()
    else:
        content = XML(open(dest).read())
        return locals()


def image():
    post_id = request.args(0)
    key = request.args(1)
    subfolder = get_subfolder(post_id)
    filename = os.path.join(FOLDER, subfolder, 'images', key)
    if not os.path.isfile(filename):
        raise HTTP(404)
    return response.stream(open(filename,'r'))


def reference():
    post_id = request.args(0)
    key = request.args(1)
    subfolder = get_subfolder(post_id)
    filename = os.path.join(FOLDER, subfolder, 'references', key)
    if not os.path.isfile(filename):
        raise HTTP(404)
    info = dict(splitter(line)
    for line in open(filename).readlines()
    if ':' in line)
    if info['source_url']:
        redirect(info['source_url'])
    else:
        return repr(info)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.