-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.py
383 lines (321 loc) · 9.35 KB
/
main.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
from flask import Flask, render_template, request, g, abort, redirect, url_for
import sqlite3
import time
from textwrap import dedent
app = Flask(__name__)
# Singleton pattern (because threading)
def get_db(name):
if app.config["DEBUG"]:
name = "{}_debug".format(name)
db = getattr(g, "_database_{}".format(name), None)
db_list = getattr(g, "_db_list", [])
if db is None:
db = g._database = sqlite3.connect("{}.db".format(name))
db_list.append(name)
return db
def get_ip():
ip_forward = request.headers.getlist("X-Forwarded-For")
if ip_forward:
return ip_forward[0]
else:
return request.remote_addr
@app.route("/")
def index():
conn = get_db("notes")
c = conn.cursor()
c.execute("SELECT COUNT(*) FROM notes")
count = c.fetchone()[0]
return render_template("index.html", count=count)
def edit_impl(name, template):
note = ""
if name:
conn = get_db("notes")
c = conn.cursor()
c.execute("SELECT note FROM notes WHERE name=?", (name,))
result = c.fetchone()
note = result[0] if result else ""
return render_template(template, name=name, note=note)
@app.route("/edit/note/")
@app.route("/edit/note/<name>")
def edit_note(name=""):
return edit_impl(name, "edit.html")
@app.route("/edit")
@app.route("/edit/")
@app.route("/note")
@app.route("/note/")
def redirect_note():
return redirect(url_for("edit_note", _external=True))
@app.route("/edit/texdown/")
@app.route("/edit/texdown/<name>")
def edit_texdown(name=""):
return edit_impl(name, "edit_texdown.html")
@app.route("/edit/animation/")
@app.route("/edit/animation/<name>")
def edit_animation(name=""):
return edit_impl(name, "edit_animation.html")
@app.route("/texdown")
@app.route("/texdown/")
def redirect_texdown():
return redirect(url_for("edit_texdown", _external=True))
# Used by both save_note and save_raw
def save_note_impl(name, note, key):
if len(name) > 99 or len(name) < 1:
return "Note name length must be between 1 and 100 characters\n", 403
if len(key) > 99:
return "Note key length must be under 100 characters\n", 403
if len(note) > 10000:
return "Note length must be under 10K characters\n", 403
conn = get_db("notes")
c = conn.cursor()
c.execute("SELECT key FROM notes WHERE name=?", (name,))
saved_key = c.fetchone()
if saved_key and saved_key[0] != key:
return "Note already saved with different key\n", 403
ip = get_ip()
date = int(time.time())
c.execute(
"""
SELECT count, date FROM ips WHERE ip=?
""",
(ip,),
)
count_lookup = c.fetchone()
if count_lookup:
time_since = date - count_lookup[1]
count = count_lookup[0] + 1
if time_since < 5:
return "Rate limit reached. Please try again later.\n", 403
else:
count = 1
c.execute(
"""
INSERT INTO ips VALUES (?, ?, ?)
""",
(ip, count, date),
)
c.execute(
"""
UPDATE ips SET count=?, date=? WHERE ip=?
""",
(count, date, ip),
)
c.execute(
"""
DELETE FROM notes WHERE name=?
""",
(name,),
)
c.execute(
"""
INSERT INTO notes VALUES (?, ?, ?, ?, ?)
""",
(name, note, key, ip, date),
)
conn.commit()
return "https://jott.live/note/{}\n".format(name)
@app.route("/save/<name>", methods=["POST"])
@app.route("/save/<name>/", methods=["POST"])
@app.route("/save/<name>/<key>", methods=["POST"])
@app.route("/save/raw/<name>/", methods=["POST"])
@app.route("/save/raw/<name>/<key>", methods=["POST"])
@app.route("/save/note/<name>/", methods=["POST"])
@app.route("/save/note/<name>/<key>", methods=["POST"])
def save(name, key=""):
if request.json:
note = request.json["note"]
elif request.form:
note = request.form["note"]
else:
return "Invalid payload\n", 403
return save_note_impl(name, note, key)
@app.route("/delete/note/<name>/", methods=["GET"])
@app.route("/delete/note/<name>/<key>", methods=["GET"])
def delete_note(name, key=""):
conn = get_db("notes")
c = conn.cursor()
c.execute("SELECT key FROM notes WHERE name=?", (name,))
saved_key = c.fetchone()
if saved_key and saved_key[0] != key:
return "Incorrect key\n", 403
c.execute(
"""
DELETE FROM notes WHERE name=?
""",
(name,),
)
conn.commit()
return 'Success! Note "{}" deleted\n'.format(name)
@app.route("/note/<name>")
def note(name):
conn = get_db("notes")
c = conn.cursor()
c.execute("SELECT note FROM notes WHERE name=?", (name,))
result = c.fetchone()
note = result[0] if result else ""
return render_template("render.html", name=name, note=note)
@app.route("/texdown/<name>")
@app.route("/texdown/note/<name>")
def texdown_note(name):
conn = get_db("notes")
c = conn.cursor()
c.execute("SELECT note FROM notes WHERE name=?", (name,))
result = c.fetchone()
note = result[0] if result else ""
return render_template("texdown.html", name=name, note=note)
@app.route("/code/<name>")
@app.route("/code/note/<name>")
def code_note(name):
conn = get_db("notes")
c = conn.cursor()
c.execute("SELECT note FROM notes WHERE name=?", (name,))
result = c.fetchone()
note = result[0] if result else ""
return render_template("code.html", name=name, note=note)
@app.route("/raw/<name>")
@app.route("/raw/note/<name>")
def raw_note(name):
conn = get_db("notes")
c = conn.cursor()
c.execute("SELECT note FROM notes WHERE name=?", (name,))
result = c.fetchone()
note = result[0] if result else ""
return note
@app.before_request
def track():
ip = get_ip()
path = request.full_path
if path[-1] == "?":
path = path[:-1]
referrer = request.referrer if request.referrer else "None"
conn = get_db("notes")
c = conn.cursor()
# Update ip -> path stats
c.execute("SELECT count FROM visits WHERE ip=? AND path=?", (ip, path))
result = c.fetchone()
if result:
count = result[0] + 1
else:
count = 1
c.execute(
"""
INSERT INTO visits VALUES (?, ?, ?)
""",
(ip, path, count),
)
c.execute(
"""
UPDATE visits SET count=? WHERE ip=? AND path=?
""",
(count, ip, path),
)
# Update referrer -> path stats
c.execute(
"""
SELECT COUNT(*) FROM referrals
WHERE referrer=? AND ip=? AND path=?
""",
(referrer, ip, path),
)
result = c.fetchone()
if result[0] == 0:
c.execute(
"""
INSERT INTO referrals VALUES (?, ?, ?)
""",
(referrer, ip, path),
)
conn.commit()
@app.route("/stats")
def stats():
conn = get_db("notes")
c = conn.cursor()
c.execute("SELECT COUNT(*) FROM ips")
result = c.fetchone()
author_count = result[0] if result else 0
c.execute("SELECT COUNT(*) FROM notes")
result = c.fetchone()
note_count = result[0] if result else 0
c.execute("SELECT COUNT(DISTINCT ip) FROM visits")
result = c.fetchone()
visit_count = result[0] if result else 0
# Top most visited paths
c.execute(
"""
SELECT path, COUNT(DISTINCT ip) as sum
FROM visits
WHERE
path NOT LIKE '/save/%' AND
path NOT LIKE '/static/%'
GROUP BY path
ORDER BY sum DESC
"""
)
top_paths = []
for i in range(10):
result = c.fetchone()
if result:
top_paths.append(result)
top_paths_str = "\n".join(
[" {}: {}".format(path, count) for path, count in top_paths]
)
# Top referrers
c.execute(
"""
SELECT referrer, COUNT(DISTINCT ip) as sum
FROM referrals
GROUP BY referrer
ORDER BY sum DESC
"""
)
top_referrers = []
for i in range(10):
result = c.fetchone()
if result:
if str(result[0]) == 'None':
continue
top_referrers.append(result)
top_referrers_str = "\n".join(
[" {}: {}".format(referrer, count) for referrer, count in top_referrers]
)
return dedent(
"""\
visitors: {}
notes: {}
authors: {}
top paths:
{}
top referrers:
{}
"""
).format(visit_count, note_count, author_count, top_paths_str, top_referrers_str)
@app.before_first_request
def initialize_dbs():
db = get_db("notes")
db.execute(
"""
CREATE TABLE IF NOT EXISTS notes (name text, note text, key text, author_ip text, date integer)
"""
)
db.execute(
"""
CREATE TABLE IF NOT EXISTS ips (ip text, count integer, date integer)
"""
)
db.execute(
"""
CREATE TABLE IF NOT EXISTS visits (ip text, path text, count integer)
"""
)
db.execute(
"""
CREATE TABLE IF NOT EXISTS referrals (referrer text, ip text, path text)
"""
)
db.commit()
@app.teardown_appcontext
def close_connection(exception):
db_list = getattr(g, "_db_list", [])
for db_name in db_list:
db = get_db(db_name)
db.close()
app.run("0.0.0.0", port=8000 if app.config["DEBUG"] else 5000)