-
Notifications
You must be signed in to change notification settings - Fork 5
/
kirby.py
268 lines (190 loc) · 6.6 KB
/
kirby.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
from __future__ import print_function
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash, Response
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.exc import IntegrityError
from os import urandom
from datetime import datetime
from flask_wtf import Form
from flask_wtf.csrf import CsrfProtect
from wtforms import TextAreaField, BooleanField, SelectField
from wtforms.validators import Length, InputRequired
import pygments
from pygments.lexers import get_lexer_by_name, guess_lexer, get_all_lexers
from pygments.formatters import HtmlFormatter
from pygments.util import ClassNotFound
import string
CHARS = string.digits + string.ascii_letters
# TODO:
# * recent public pastes
# * download paste
app = Flask(__name__)
app.debug = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///thedb.db'
# Don't use this exact key on your (public) instance
app.secret_key = '\xecm\xba)I\xd8m\xc4(\x94\xf5\xf2\x1e\xff\xcap\x0cls\xe0\xc3k\x00\x86'
db = SQLAlchemy(app)
csrf = CsrfProtect(app)
LANGS = []
for x in get_all_lexers():
LANGS.append(x[1][0])
#LANGS[x[1][0]] = x[0]
LANGS = sorted(LANGS)
THEMES = {
'default' : 'Kirby',
'plain' : 'Plain',
'clear' : 'Clear',
'clear_dark' : 'Clear (dark)'
}
# Lodge It db:
# CREATE TABLE pastes (
# paste_id INTEGER NOT NULL,
# code TEXT,
# parent_id INTEGER,
# pub_date DATETIME,
# language VARCHAR(30),
# user_hash VARCHAR(40),
# handled BOOLEAN,
# private_id VARCHAR(40),
# PRIMARY KEY (paste_id),
# UNIQUE (private_id),
# FOREIGN KEY(parent_id) REFERENCES pastes (paste_id),
# CHECK (handled IN (0, 1))
#);
#XXX To get syntax.css: HtmlFormatter().get_style_defs('.highlight')),
class Paste(db.Model):
__tablename__ = 'pastes'
paste_id = db.Column(db.Integer, primary_key=True)
code = db.Column(db.UnicodeText)
parent_id = db.Column(db.ForeignKey('pastes.paste_id'), nullable=True)
pub_date = db.Column(db.DateTime)
language = db.Column(db.String(30))
user_hash = db.Column(db.String(40), nullable=True)
# ???
handled = db.Column(db.Boolean)
private_id = db.Column(db.String(40), unique=True, nullable=True)
# Children
#children = db.relation('Paste', cascade='all',
# primaryjoin=parent_id == paste_id,
# backref=db.backref('parent', remote_side=[paste_id]))
# TODO: Parent handling, language handling
def __init__(self, code, lang, private=None, parent=None):
if lang not in LANGS:
lang = 'text'
self.language = lang
self.code = u'\n'.join(code.splitlines())
if private is not None:
self.private_id = private
self.pub_date = datetime.now()
#if parent is not None:
# if isinstance(parent, Paste):
# pass
# # TODO
# else:
# self.parent_id = parent
def __repr__(self):
return 'Paste(%s, %s)' % (self.paste_id, self.private_id)
def get_pid(self):
if self.private_id:
return self.private_id
return str(self.paste_id)
class PasteForm(Form):
private = BooleanField('private', [])
paste = TextAreaField('paste', [InputRequired(), Length(min=5)])
lang = SelectField('language', choices=([(x, x) for x in LANGS]))
def get_theme():
if 't' in request.args:
theme = request.args['t']
if theme in THEMES:
session['theme'] = theme
return theme
if 'theme' in session:
return session['theme']
return 'default'
@app.route('/')
def main():
form = PasteForm()
return render_template('newpaste.html', form=form,
theme=get_theme(), langs=LANGS)
def get_paste(paste):
r = None
priv_provided = False
try:
pid = int(paste)
r = db.session.query(Paste).filter(Paste.paste_id == pid).first()
except ValueError:
pid = paste
r = db.session.query(Paste).filter(Paste.private_id == pid).first()
priv_provided = True
if r is None:
abort(404, 'No such paste')
if not priv_provided and r.private_id is not None:
abort(403, 'Resource denied')
return r
@app.route('/raw/<paste>/', methods=['GET'])
def raw_paste(paste):
r = get_paste(paste)
return Response(r.code, mimetype='text/plain')
@app.route('/show/<paste>/', methods=['GET'])
def view_paste(paste):
r = get_paste(paste)
lang = request.args.get('l') if 'l' in request.args else r.language
paste = r.code
lexer = None
if lang == None:
try:
lexer = guess_lexer(paste)
except ClassNotFound:
pass
if lexer is None:
try:
lexer = get_lexer_by_name(lang)
except:
abort(500, 'Invalid lexer: %s' % lang)
if lexer is None:
try:
lexer = get_lexer_by_name('text')
except:
abort(500, 'Invalid lexer: %s' % lang)
formatter = HtmlFormatter(linenos=True)#, cssclass='syntax')#, style='friendly')
h = pygments.highlight(paste, lexer, formatter)
pasteid = r.private_id if r.private_id else r.paste_id
return render_template('viewpaste.html', data=h, theme=get_theme(),
langs=LANGS, pasteid=pasteid, currlang=lexer.aliases[0])
@app.route('/usage/', methods=['GET'])
def usage():
theme = request.args.get('t', 'default')
return render_template('usage.html', theme=get_theme(), langs=LANGS,
themes=THEMES)
@app.route('/theme/', methods=['GET'])
def themes():
theme = request.args.get('t', 'default')
return render_template('theme.html', theme=get_theme(),
themes=THEMES)
@csrf.exempt
@app.route('/paste/', methods=['GET'])
def pasteget():
return redirect('/')
@app.route('/paste/', methods=['POST'])
def paste():
form = PasteForm(request.form)
if form.validate():
for _ in xrange(10):
if form.private.data:
priv_id = ''.join(map(lambda x: CHARS[ord(x) % len(CHARS)], urandom(40)))
code = form.paste.data
try:
p = Paste(code, lang=form.lang.data, private=priv_id if form.private.data
else None)
db.session.add(p)
db.session.commit()
return redirect('/show/%s' % p.get_pid())
except IntegrityError as e:
print('Failed to add paste:', p, e)
s = ''
for k, v in form.errors.items():
s += "%s;" % v
abort(418, 'Failed to add paste: %s' % s)
if __name__ == '__main__':
db.create_all()
app.run(port=5001)