-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
app.py
316 lines (266 loc) · 9.75 KB
/
app.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
from flask import (
Flask,
redirect,
request,
render_template,
abort,
Response,
url_for,
)
from flask_mongoengine import MongoEngine
from flask_debugtoolbar import DebugToolbarExtension
from flask_login import (
current_user,
fresh_login_required,
)
from flask_wtf import FlaskForm
from werkzeug.middleware.proxy_fix import ProxyFix
from wtforms.fields import TextAreaField, SelectField, SubmitField
from wtforms.validators import Required
from datetime import datetime
import pygments
from pygments.lexers import guess_lexer, get_lexer_by_name, get_all_lexers
from markdown2 import markdown
from util import random_string
import database
import html
import pendulum
from hashlib import sha1
from werkzeug.routing import BaseConverter
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app, num_proxies=1)
class SHA1Converter(BaseConverter):
def __init__(self, map):
super(SHA1Converter, self).__init__(map)
self.regex = "[A-Za-z0-9]{40}"
app.url_map.converters["sha1"] = SHA1Converter
with app.app_context():
@app.route("/<string:id>")
@app.route("/<sha1:digest>")
def get(id=None, digest=None):
if id:
paste = database.Paste.objects(name__exact=id).first()
if digest:
paste = database.Paste.objects(digest__exact=digest).first()
if not paste:
abort(404)
elif paste.expire and paste.expire < pendulum.now("utc").naive():
paste.delete()
abort(404)
else:
return render_paste(paste, title=paste.id)
import auth # noqa: F401
import config
app.config.from_object(config)
app.config["DEBUG_TB_PANELS"] = [
"flask_debugtoolbar.panels.versions.VersionDebugPanel",
"flask_debugtoolbar.panels.timer.TimerDebugPanel",
"flask_debugtoolbar.panels.headers.HeaderDebugPanel",
"flask_debugtoolbar.panels.request_vars.RequestVarsDebugPanel",
"flask_debugtoolbar.panels.template.TemplateDebugPanel",
"flask_debugtoolbar.panels.logger.LoggingPanel",
"flask_debugtoolbar.panels.profiler.ProfilerDebugPanel",
"flask_mongoengine.panels.MongoDebugPanel",
]
@app.template_filter("prettytime")
def format_datetime(value, format="medium"):
return pendulum.instance(value).to_datetime_string()
@app.template_filter("humanize")
def humanize_date(value):
return pendulum.instance(value).diff_for_humans()
db = MongoEngine(app)
import admin # noqa: F401
toolbar = DebugToolbarExtension(app)
from api import v1 # noqa: F401
def get_lexers():
yield ("none", "Automatically Detect")
yield ("markdown", "markdown")
for lexer in sorted(get_all_lexers()):
try:
yield (lexer[1][0], lexer[0])
except IndexError:
pass
class PasteForm(FlaskForm):
text = TextAreaField("Paste Here", validators=[Required()])
expiration = SelectField(
"Expiration",
choices=[
("0", "Never"),
("1", "Fifteen Minutes"),
("2", "Thirty Minutes"),
("3", "One Hour"),
("4", "Six Hours"),
("5", "Twelve Hours"),
("6", "One Day"),
("7", "One Week"),
("8", "One Month"),
],
default="6",
)
language = SelectField("Language", choices=[i for i in get_lexers()])
class PasteFormNoAuth(PasteForm):
expiration = SelectField(
"Expiration",
choices=[
("1", "Fifteen Minutes"),
("2", "Thirty Minutes"),
("3", "One Hour"),
("4", "Six Hours"),
("5", "Twelve Hours"),
("6", "One Day"),
("7", "One Week"),
("8", "One Month"),
],
default="6",
)
class ConfirmForm(FlaskForm):
confirm = SubmitField("Click here to confirm deletion", validators=[Required()])
@app.route("/", methods=("POST", "GET"))
@app.route("/new", methods=("POST", "GET"))
def main():
if current_user.is_authenticated:
form = PasteForm(request.form)
else:
form = PasteFormNoAuth(request.form)
if form.validate_on_submit():
times = {
"0": None,
"1": {"minutes": +15},
"2": {"minutes": +30},
"3": {"hours": +1},
"4": {"hours": +6},
"5": {"hours": +12},
"6": {"days": +1},
"7": {"weeks": +1},
"8": {"months": +1},
}
paste = database.Paste()
paste.paste = form.text.data
paste.digest = sha1(paste.paste.encode("utf-8")).hexdigest()
if current_user.is_authenticated:
paste.user = current_user.to_dbref()
else:
paste.address = request.remote_addr
# Create a name and make sure it doesn't exist
paste.name = random_string()
collision_check = database.Paste.objects(name__exact=paste.name).first()
while collision_check:
paste.name = random_string()
collision_check = database.Paste.objects(name__exact=paste.name).first()
if form.language.data:
paste.language = form.language.data
else:
try:
paste.language = guess_lexer(form.text.data).name
except pygments.util.ClassNotFound:
paste.language = "text"
paste.time = datetime.utcnow()
if times.get(form.expiration.data):
paste.expire = pendulum.now("utc").add(
**times.get(form.expiration.data)
)
if (
not times.get(form.expiration.data)
and not current_user.is_authenticated
):
paste.expire = pendulum.now("utc").add(**times.get(7))
paste.save()
return redirect("/{id}".format(id=paste.name))
return render_template("new_paste.html", form=form)
@app.route("/my")
def my():
if not current_user.is_authenticated:
abort(403)
pastes = database.Paste.objects(user=current_user.to_dbref()).order_by(
"-expire", "-time"
)
if pastes.count() == 0:
pastes = None
return render_template("my_pastes.html", pastes=pastes, title="My Pastes")
@app.route("/raw/<string:id>")
@app.route("/raw/<sha1:digest>")
def raw(id=None, digest=None):
if id:
paste = database.Paste.objects(name__exact=id).first()
if digest:
paste = database.Paste.objects(digest__exact=digest).first()
if not paste:
abort(404)
else:
return Response(paste.paste, mimetype="text/plain")
@app.route("/settings")
@fresh_login_required
def settings():
keys = database.ApiKey.objects(user=current_user.to_dbref())
return render_template("settings.html", keys=keys)
@app.route("/settings/new_api_key", methods=("POST",))
@fresh_login_required
def new_api_key():
key = random_string(size=32)
api_key = database.ApiKey(user=current_user.to_dbref(), key=key)
api_key.save()
return redirect(url_for("settings"))
@app.route("/settings/delete_api_key/<string:key>", methods=("POST",))
@fresh_login_required
def delete_api_key(key):
api_key = database.ApiKey.objects(key=key).first()
if api_key and api_key.user.to_dbref() == current_user.to_dbref():
api_key.delete()
else:
abort(403)
return redirect(url_for("settings"))
@app.route("/<string:id>/delete", methods=("POST",))
def delete(id):
paste = database.Paste.objects(name=id).first()
if not paste:
abort(404)
if paste.user.to_dbref() != current_user.to_dbref():
abort(403)
paste.delete()
return redirect("/my")
def htmlify(string, language=None):
"""
Takes a string, and returns an html encoded string with color formatting
"""
if not language:
try:
lexer = guess_lexer(string)
except pygments.util.ClassNotFound:
lexer = get_lexer_by_name("text")
else:
try:
lexer = get_lexer_by_name(language)
except pygments.util.ClassNotFound:
lexer = get_lexer_by_name("text")
format = pygments.formatters.HtmlFormatter(linenos="inline")
return pygments.highlight(string, lexer, format)
def render_paste(paste, title=None):
if not title:
title = paste.id
text = paste.paste
text = text.rstrip("\n")
text += "\n"
lines = len(text.split("\n"))
if paste.language == "none" or not paste.language:
try:
paste.language = guess_lexer(text).name
except pygments.util.ClassNotFound:
paste.language = "text"
text = htmlify(text, paste.language)
elif paste.language == "markdown":
text = markdown(html.escape(text.replace("!", "\\!")))
else:
text = htmlify(text, paste.language)
paste.views += 1
paste.save()
return render_template(
"paste.html", paste=paste, title=title, text=text, lines=lines
)
@app.cli.command()
def remove_expired():
for paste in database.Paste.objects(expire__lt=pendulum.now("utc")):
print(f"delete {paste.name}")
paste.delete()
app.debug = app.config["DEBUG"]
def run():
app.run()