Skip to content

Commit

Permalink
get rid of redis, completely
Browse files Browse the repository at this point in the history
  • Loading branch information
anru committed Jul 1, 2017
1 parent 3e77065 commit 87f7c60
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 111 deletions.
38 changes: 0 additions & 38 deletions application.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
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

# handle relative path references by changing to project directory
Expand All @@ -21,10 +20,7 @@
# 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 view_is_active(view_name):
Expand All @@ -44,12 +40,6 @@ def ctx_pro():
def index():
yield 'js_params', {'theme': request.args.get('theme', '')}

saved_doc_id = request.args.get('n')
if saved_doc_id:
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():
Expand Down Expand Up @@ -78,34 +68,6 @@ def rst2pdf():
responce.headers['Content-Transfer-Encoding'] = 'binary'
return responce

@app.route('/srv/save_rst/', methods=['POST'])
def save_rst():
rst = request.form.get('rst')
if not rst:
return ''

from hashlib import md5

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=app.config.get('HOST', '0.0.0.0'),
Expand Down
1 change: 0 additions & 1 deletion pip-requirements.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
flup
flask
redis
rst2pdf

# Docutils (for rst2html)
Expand Down
110 changes: 64 additions & 46 deletions static/scripts/editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,23 @@ function getSelectedTheme() {
return theme;
}

function b64EncodeUnicode(str) {
// first we use encodeURIComponent to get percent-encoded UTF-8,
// then we convert the percent encodings into raw bytes which
// can be fed into btoa.
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
function toSolidBytes(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}

function b64DecodeUnicode(str) {
// Going backwards: from bytestream, to percent-encoding, to original string.
return decodeURIComponent(atob(str).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}

function getQueryArgs(locSearch) {
locSearch = locSearch || window.location.search;
var args = {};
Expand All @@ -21,10 +38,6 @@ function getQueryArgs(locSearch) {
return args;
}

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


function setPreviewHtml(html) {
var iframe = $('#browse')[0];
Expand Down Expand Up @@ -91,21 +104,30 @@ function syncScrollPosition() {

var activeXhr = null;
var lastContent = null;
var renderedHash = null;

function genPreview() {
var self = $('textarea#editor');
function probablyChanged() {
var self = $('#editor');
var rstContent = self.val();
if (activeXhr || lastContent == rstContent) {
//activeXhr.abort();
return;
}
syncHashAndUpdate();
}

function genPreview() {
var self = $('#editor');
var rstContent = self.val();

lastContent = rstContent;
activeXhr = $.ajax({
'url': script_root + '/srv/rst2html/',
'data': {'rst': rstContent, 'theme': getSelectedTheme()},
'type': 'POST',
'error': function(xhr) {
setPreviewHtml(xhr.responseText);
activeXhr = null;
},
'success': function(response) {
setPreviewHtml(response);
Expand All @@ -117,11 +139,40 @@ function genPreview() {

var timerId = null;

function getCurrentLink(res) {
if (!res) {
return '//' + window.location.host + script_root + '/?theme=' + getSelectedTheme();
function syncState(rst) {
location.hash = '#' + b64EncodeUnicode(rst);
}

function syncHashAndUpdate() {
var self = $('#editor');
var rstContent = self.val();
syncState(rstContent);
genPreview();
}

function getDecodedHash() {
return b64DecodeUnicode(location.hash.substr(1));
}

window.onhashchange = function(ev) {
$('textarea#editor').val(getDecodedHash());
}

window.onpopstate = function(ev) {
var doUpdate = false;
var stateTheme = getQueryArgs()['theme'] || 'basic';
if (stateTheme != getSelectedTheme()) {
$('.themes input[value='+ stateTheme + ']')[0].checked = true;
doUpdate = true;
}
if (getDecodedHash() != lastContent) {
$('#editor').val(getDecodedHash());
doUpdate = true;
}

if (doUpdate) {
genPreview();
}
return '//' + window.location.host + script_root + '/?n=' + res + '&theme=' + getSelectedTheme();
}

function adjustBrowse() {
Expand All @@ -133,54 +184,21 @@ function adjustBrowse() {


$(function() {
//$('<button>Conver!</button>').click(genPreview).appendTo($('body'));

window.baseTitle = $('head title').text();

$('textarea#editor').bind('change', genPreview).markItUp(mySettings);
timerId = window.setInterval(genPreview, 900);
$('textarea#editor').bind('change', probablyChanged).markItUp(mySettings);
timerId = window.setInterval(probablyChanged, 900);
window.setTimeout(function() {
$('#editor-td > div').css({'width': '100%', 'height': '96%'});
}, 200);

$('textarea#editor').scroll(syncScrollPosition);

$('.themes input').bind('change', function() {
lastContent = null;
history.pushState({theme: getSelectedTheme()}, document.title, '/?theme=' + getSelectedTheme() + location.hash);
genPreview();
});

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

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

});

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

$('#del_link').click(function(e) {
$.ajax({
'url': script_root + '/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 Down
3 changes: 0 additions & 3 deletions templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,8 @@
<link rel="stylesheet" href="{{ request.script_root }}{{ MEDIA_URL }}style/site.css"/>
<link rel="stylesheet" href="{{ request.script_root }}{{ MEDIA_URL }}style/menu.css"/>

<link rel="stylesheet" href="{{ request.script_root }}{{ MEDIA_URL }}style/overcast/jquery-ui-1.8.16.custom.css" />


<script src="{{ request.script_root }}{{ MEDIA_URL }}scripts/jquery-1.6.4.min.js"></script>
<script src="{{ request.script_root }}{{ MEDIA_URL }}scripts/jquery-ui-1.8.16.custom.min.js"></script>
<script src="{{ request.script_root }}{{ MEDIA_URL }}scripts/jquery.layout.min-1.2.0.js"></script>

{% endblock %}
Expand Down
27 changes: 4 additions & 23 deletions templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@
if (js_params.theme) {
$('.themes input[value='+ js_params.theme + ']')[0].checked = true;
}
if (js_params.rst) {
$('#editor').val(js_params.rst);

if (location.hash) {
$('#editor').val(getDecodedHash());
}
});

Expand All @@ -29,18 +30,6 @@
{% block editor_nav %}
<ul>
<li><a href="#" id="as_pdf" class="jslink">Export to PDF</a></li>
<li>{% if document %}
<a href="#" id="save" class="jslink">Save</a>
{% else %}
<a href="#" id="save_link" class="jslink">Save with unique link</a>
{% endif %}
</li>
<li>
{% if document %}
<a href="#" id="del_link" class="jslink">
{% else %}&nbsp;&nbsp;{% endif %}Delete
{% if document %}</a>{% endif %}
</li>
</ul>
{% endblock %}

Expand All @@ -55,16 +44,8 @@
<input id="t_basic" type="radio" value="basic" checked="checked" name="style"/><label for="t_basic">Basic</label>
<input id="t_nature" type="radio" value="nature" name="style"/><label for="t_nature">Nature</label>
</div>
<div class="actions right">
<button id="save_link">Save with unique link</button>
{% if document %}
<button id="del_link">Delete</button>
{% endif %}
</div>
</div>


<iframe src="{{ request.script_root }}/srv/rst2html/" id="browse"></iframe>
<iframe src="{{ request.script_root }}/srv/rst2html/" id="browse"></iframe>
</div>
</div>

Expand Down

0 comments on commit 87f7c60

Please sign in to comment.