Skip to content

Commit

Permalink
redesign & refactoring
Browse files Browse the repository at this point in the history
big commit
  • Loading branch information
Andrey Rublev committed Oct 4, 2011
1 parent a765f15 commit 223ad31
Show file tree
Hide file tree
Showing 39 changed files with 876 additions and 914 deletions.
68 changes: 45 additions & 23 deletions application.py
Original file line number Diff line number Diff line change
@@ -1,47 +1,57 @@
#!/usr/bin/env python2
# all the imports

import os, sys
reload(sys)
sys.setdefaultencoding('utf-8')

import redis

from flask import Flask, request, render_template, make_response
from flask import Flask, request, render_template, make_response, url_for

from rsted.html import rst2html as _rst2html
from rsted.pdf import rst2pdf as _rst2pdf

from flaskext.redis import RedisManager
from flaskext.helpers import render_html


# create our little application :)
app = Flask(__name__)
app.config.from_pyfile(os.environ.get('RSTED_CONF', 'settings.py'))
redis = RedisManager(app).get_instance()

REDIS_EXPIRE = app.config.setdefault('REDIS_EXPIRE', 60*60*24*30*6) # Default 6 months
REDIS_PREFIX = app.config.setdefault('REDIS_PREFIX', 'rst_')

def connect_redis():
return redis.Redis(host=app.config.get('REDIS_HOST', 'localhost'), port=app.config.get('REDIS_PORT', 6379), db=app.config.get('REDIS_DB', 0))

def view_is_active(view_name):
if request.path == url_for(view_name):
return 'active'
return ''

@app.context_processor
def ctx_pro():
return {
'MEDIA_URL': '/static/'
'MEDIA_URL': '/static/',
'is_active': view_is_active
}

@app.route("/")
@render_html('index.html')
def index():
yield 'js_params', {'theme': request.args.get('theme', '')}

saved_doc_id = request.args.get('n')
rst = ''
if saved_doc_id:
r = connect_redis()
saved_doc = r.get(saved_doc_id)
if saved_doc:
rst = saved_doc
js_params = {'rst': rst, 'theme': request.args.get('theme', '')}
return render_template('index.html', js_params=js_params)
rst = redis.get('%s%s' % (REDIS_PREFIX, saved_doc_id))
if rst:
yield 'rst', rst
yield 'document', saved_doc_id

@app.route('/about/')
def about():
return render_template('about.html')
return render_template('about.html')

@app.route('/srv/rst2html/', methods=['POST'])
@app.route('/srv/rst2html/', methods=['POST', 'GET'])
def rst2html():
rst = request.form.get('rst', '')
theme = request.form.get('theme')
Expand Down Expand Up @@ -69,17 +79,29 @@ def save_rst():
rst = request.form.get('rst')
if not rst:
return ''

from hashlib import md5
r = connect_redis()

hash = md5(rst).hexdigest()
r.setnx(hash, rst)
r.save()
response = make_response(hash)

md5sum = md5(rst).hexdigest()
redis_key = '%s%s' % (REDIS_PREFIX, md5sum)

if redis.setnx(redis_key, rst) and REDIS_EXPIRE:
redis.expire(redis_key, REDIS_EXPIRE)
response = make_response(md5sum)
response.headers['Content-Type'] = 'text/plain'
return response

@app.route('/srv/del_rst/', methods=['GET'])
def del_rst():
saved_id = request.args.get('n')
if saved_id:
redis_key = '%s%s' % (REDIS_PREFIX, saved_id)
redis.delete(redis_key)

response = make_response()
response.headers['Content-Type'] = 'text/plain'
return response


if __name__ == '__main__':
app.run(host='0.0.0.0')

45 changes: 15 additions & 30 deletions rsted/html.py
Original file line number Diff line number Diff line change
@@ -1,49 +1,34 @@

import os
from os.path import join as J
import sys
from flask import current_app as app
from subprocess import Popen, PIPE
import codecs
from os.path import join as J
#import codecs

utf8codec = codecs.lookup('utf-8')
from docutils.core import publish_string

def _popen(cmd, input=None, **kwargs):
kw = dict(stdout=PIPE, stderr=PIPE, close_fds=os.name != 'nt', universal_newlines=True)
if input is not None:
kw['stdin'] = PIPE
kw.update(kwargs)
p = Popen(cmd, shell=True, **kw)
return p.communicate(input)
#utf8codec = codecs.lookup('utf-8')

default_rst_opts = {
'no-generator': None,
'no-source-link': None,
'tab-width': 4
'no_generator': True,
'no_source_link': True,
'tab_width': 4,
'file_insertion_enabled': False,
'raw_enabled': False,
'stylesheet_path': None,
}

def make_opts(d):
result = []
for key, value in d.items():
r = '='.join([str(x) for x in ('--%s' % key, value) if x is not None])
result.append(r)
return ' '.join(result)

def rst2html(rst, theme=None, opts=None):
rst_opts = default_rst_opts.copy()
if opts:
rst_opts.update(opts)
rst_opts['template'] = 'var/themes/template.txt'

stylesheets = ['basic.css']
if theme:
stylesheets.append('%s/%s.css' % (theme, theme))
rst_opts['stylesheet'] = ','.join([J('var/themes/', p) for p in stylesheets ])

cmd = '%s %s' % (app.config['RST2HTML_CMD'], make_opts(rst_opts))
out, errs = _popen(cmd, utf8codec.encode(rst)[0], cwd=app.config.root_path)
if errs and not out:
return errs


out = publish_string(rst, writer_name='html', settings_overrides=rst_opts)

return out

2 changes: 0 additions & 2 deletions settings.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@

# configuration
DEBUG = True
RST2HTML_CMD = 'rst2html.py'
RST2PDF_CMD = 'rst2pdf'

try:
from settings_local import *
Expand Down
82 changes: 63 additions & 19 deletions static/scripts/editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,25 @@ function getSelectedTheme() {
return theme;
}

function getQueryArgs(locSearch) {
locSearch = locSearch || window.location.search;
var args = {};

locSearch.replace(/(\w+)=(.+?)(&|$)/g, function(substr, key, value) {
args[key] = window.decodeURIComponent(value);
});
return args;
}

function getCurrentDocument() {
return getQueryArgs()['n'];
}


function setPreviewHtml(html) {
var iframe = $('#browse')[0];
var doc = iframe.document;

if (iframe.contentDocument) {
doc = iframe.contentDocument; // For NS6
} else if (iframe.contentWindow) {
Expand All @@ -23,6 +38,7 @@ function setPreviewHtml(html) {
doc.open();
doc.writeln(html);
doc.close();

}

var activeXhr = null;
Expand Down Expand Up @@ -59,16 +75,11 @@ function getCurrentLink(res) {
return 'http://' + window.location.host + '/?n=' + res + '&theme=' + getSelectedTheme();
}

function showLinkDialog(url) {
var showLinker = $('.showLinkDialog');

var self = $('#show_link');
var offs = self.offset();
showLinker.find('input').val(url);
showLinker.css({
'left': offs.left + self.width() - showLinker.width(),
'top': $('#navigation').offset().top + $('#navigation').height()
}).css('visibility', 'visible').show();
function adjustBrowse() {
var h = $('body').height() - $('#browse').offset().top - $('#footer').outerHeight() - 7;
$('#browse').height(h);
h -= 12;
$('#editor').height(h).css('max-height', h + 'px');
}


Expand All @@ -83,22 +94,18 @@ $(function() {

$('.themes input').bind('change', function() {
lastContent = null;
genPreview()
});

$('.showLinkDialog .hider').click(function() {
$('.showLinkDialog').hide('slow');
genPreview();
});


$('#show_link').click(function(e) {
$('#save_link').click(function(e) {

$.ajax({
'url': '/srv/save_rst/',
'type': 'POST',
'data': {'rst': $('#editor').val()},
'data': {'rst': $('textarea#editor').val()},
'success': function(response) {
showLinkDialog(getCurrentLink(response + ''));
window.location = getCurrentLink(response + '');
$('textarea#editor').focus();
}

});
Expand All @@ -107,6 +114,20 @@ $(function() {
return false;
});

$('#del_link').click(function(e) {
$.ajax({
'url': '/srv/del_rst/',
'type': 'GET',
'data': {'n': getCurrentDocument()},
'success': function(response) {
window.location = getCurrentLink();
}
});

e.preventDefault();
return false;
});

$('#as_pdf').click(function(e) {
var form = $('#save_as_pdf');
$('#as_pdf_rst').attr('value', $("#editor").val());
Expand All @@ -116,4 +137,27 @@ $(function() {
e.preventDefault();
return false;
});

//cache nav
var nav = $("#navigation");

//add indicator and hovers to submenu parents
nav.find("li").each(function() {
if ($(this).find("ul").length > 0) {
//show subnav on hover
$(this).mouseenter(function() {
$(this).find("ul").css('display', '');
});

//hide submenus on exit
$(this).mouseleave(function() {
$(this).find("ul").css('display', 'none');
});
}
});

adjustBrowse();

$(window).bind('resize', adjustBrowse);

});
Loading

0 comments on commit 223ad31

Please sign in to comment.