forked from makyo/polycul.es
-
Notifications
You must be signed in to change notification settings - Fork 0
/
polycules.py
315 lines (264 loc) · 10.5 KB
/
polycules.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
import base64
import os
import sqlite3
import json
from contextlib import closing
from jsonschema import validate
from flask import (
Flask,
Response,
g,
redirect,
render_template,
request,
session,
)
from migrations import hashify
from model import Polycule
# Config
IP = os.environ.get("ip", None)
DATABASE = os.getenv('DATABASE', 'dev.db')
DEBUG = True
SECRET_KEY = os.getenv('SECRET_KEY', 'SET ME PLEASE')
# App initialization
app = Flask(__name__)
app.config.from_object(__name__)
# Database initialization
def connect_db():
return sqlite3.connect(app.config["DATABASE"])
def migrate():
migrations_dir = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "migrations"
)
with closing(connect_db()) as db:
try:
current_migration = db.execute(
"""
select * from migrations
"""
).fetchall()[0][0]
except sqlite3.OperationalError:
# If there was no migrations table, the DB does not exist yet.
current_migration = -1
for filename in sorted(os.listdir(migrations_dir)):
if filename[-3:] != "sql":
continue
migration_number = int(filename[:3])
if migration_number <= current_migration:
print("migration {} already applied".format(migration_number))
continue
with open(os.path.join(migrations_dir, filename), "r", encoding="utf-8") as f:
try:
db.cursor().executescript(f.read())
except Exception as e:
print("Got {} - maybe already applied?".format(e))
finally:
pass
if filename[:3] == "003":
hashify.migrate(db)
def generate_csrf_token():
if "_csrf_token" not in session:
session["_csrf_token"] = base64.b64encode(os.urandom(12)).decode("utf-8")
return session["_csrf_token"]
app.jinja_env.globals["csrf_token"] = generate_csrf_token
@app.before_request
def before_request():
if request.method == "POST":
token = session.pop("_csrf_token", None)
if not token or token != request.form.get("_csrf_token"):
return render_template("error.jinja2", error="Token expired :(")
g.db = connect_db()
@app.teardown_request
def teardown_request(exception):
db = getattr(g, "db", None)
if db is not None:
db.close()
# Views
@app.route("/")
def front():
""" Render the front page. """
return render_template("front.jinja2")
@app.route("/example")
def example():
""" View an example polycule. """
result = g.db.execute("select * from polycules where id = 1")
graph = result.fetchone()[1]
return render_template("embed_polycule.jinja2", graph=graph)
@app.route("/<string:polycule_id>", methods=["GET", "POST"])
def view_polycule(polycule_id):
""" View a polycule. """
try:
polycule = Polycule.get(g.db, polycule_id, request.form.get("view_pass", ""))
except Polycule.PermissionDenied:
return render_template("view_auth.jinja2")
if polycule is None:
return render_template("error.jinja2", error="Polycule not found :(")
return render_template("view_polycule.jinja2", polycule=polycule)
@app.route("/<string:polycule_id>.html", methods=["GET", "POST"])
def view_text_only(polycule_id):
""" View a polycule. """
try:
polycule = Polycule.get(g.db, polycule_id, request.form.get("view_pass", ""))
except Polycule.PermissionDenied:
return render_template("view_auth.jinja2")
if polycule is None:
return render_template("error.jinja2", error="Polycule not found :(")
return render_template("text_only.jinja2", content=polycule.as_html())
@app.route("/embed/<string:polycule_id>")
def embed_polycule(polycule_id):
""" View just a polycule for embedding in an iframe. """
polycule = Polycule.get(g.db, polycule_id, request.form.get("view_pass", ""))
if polycule is None:
return render_template("error.jinja2", error="Polycule not found :(")
return render_template("embed_polycule.jinja2", graph=polycule.graph)
@app.route("/inherit/<string:polycule_id>", methods=["GET", "POST"])
def inherit_polycule(polycule_id):
"""
Take a given polycule and enter create mode, with that polycule's contents
already in place
"""
try:
polycule = Polycule.get(g.db, polycule_id, request.form.get("view_pass", ""))
except Polycule.PermissionDenied:
return render_template("view_auth.jinja2")
if polycule is None:
return render_template("error.jinja2", error="Polycule not found :(")
return render_template("edit_polycule.jinja2", inherited=polycule.graph, creating=True)
@app.route("/create")
def create_polycule():
""" Create a new, blank polycule. """
graph = """{
"lastId": 0,
"nodes": [],
"links": []
}"""
return render_template("edit_polycule.jinja2", inherited=graph, creating=True)
@app.route("/edit/<polycule_id>", methods=["GET", "POST"])
def edit_polycule(polycule_id):
# Force, as we're relying on edit pass instead of view pass
polycule = Polycule.get(g.db, polycule_id, "", force=True)
if request.method == "GET":
return render_template("edit_auth.jinja2")
try:
polycule.can_save(request.form.get("edit_pass", ""))
except Polycule.PermissionDenied:
return render_template("edit_auth.jinja2")
except Polycule.NoPassword:
return render_template(
"error.jinja2",
error="This polycule has no password and thus cannot be edited :(",
)
session["currently_editing"] = polycule_id
return render_template(
"edit_polycule.jinja2", polycule_id=polycule_id, graph=polycule.graph, creating=False
)
@app.route("/edit/save", methods=["POST"])
def save_existing_polycule():
polycule = Polycule.get(g.db, session["currently_editing"], "", force=True)
polycule.save(
request.form.get("graph"),
request.form.get("view_pass"),
request.form.get("edit_pass"),
remove_view_pass=request.form.get("remove_view_pass"),
remove_edit_pass=request.form.get("remove_edit_pass"),
)
return redirect("/{}".format(session.pop("currently_editing")))
@app.route("/save", methods=["POST"])
def save_new_polycule():
""" Save a created polycule. """
try:
with open("schema.json") as json_data:
schema = json.load(json_data)
validate(json.loads(request.form["graph"]), schema)
except Exception:
return render_template(
"error.jinja2", error="The submitted graph could not be parsed"
)
try:
polycule = Polycule.create(
g.db,
request.form["graph"],
request.form.get("view_pass", ""),
request.form.get("edit_pass", ""),
)
except Polycule.IdenticalGraph:
return render_template(
"error.jinja2",
error="An identical polycule " "to the one you submitted already exists!",
)
return redirect("/{}".format(polycule.graph_hash))
@app.route("/delete/<string:polycule_id>", methods=["POST"])
def delete_polycule(polycule_id):
polycule = Polycule.get(g.db, polycule_id, None, force=True)
if polycule is None:
return render_template("error.jinja2", error="Polycule not found :(")
try:
polycule.delete(request.form.get("delete_pass", ""))
except Polycule.PermissionDenied:
return render_template("view_auth.jinja2", polycule_id=polycule_id)
return redirect("/")
@app.route("/export/<string:polycule_id>", methods=["GET", "POST"])
def choose_export(polycule_id):
try:
polycule = Polycule.get(g.db, polycule_id, request.form.get("view_pass", ""))
except Polycule.PermissionDenied:
return render_template("view_auth.jinja2")
if polycule is None:
return render_template("error.jinja2", error="Polycule not found :(")
return render_template("choose_export.jinja2", polycule=polycule)
@app.route("/export/<string:polycule_id>/polycule.txt", methods=["GET", "POST"])
def export_text(polycule_id):
try:
polycule = Polycule.get(g.db, polycule_id, request.form.get("view_pass", ""))
except Polycule.PermissionDenied:
return render_template("view_auth.jinja2")
if polycule is None:
return render_template("error.jinja2", error="Polycule not found :(")
return Response(polycule.as_text(), mimetype="text/plain")
@app.route("/export/<string:polycule_id>/polycule.dot", methods=["GET", "POST"])
def export_dot(polycule_id):
try:
polycule = Polycule.get(g.db, polycule_id, request.form.get("view_pass", ""))
except Polycule.PermissionDenied:
return render_template("view_auth.jinja2")
if polycule is None:
return render_template("error.jinja2", error="Polycule not found :(")
labels = request.args.get("link-labels", "") != ""
return Response(polycule.as_dot(edge_labels=labels), mimetype="text/plain")
@app.route("/export/<string:polycule_id>/polycule.svg", methods=["GET", "POST"])
def export_svg(polycule_id):
try:
polycule = Polycule.get(g.db, polycule_id, request.form.get("view_pass", ""))
except Polycule.PermissionDenied:
return render_template("view_auth.jinja2")
if polycule is None:
return render_template("error.jinja2", error="Polycule not found :(")
labels = request.args.get("link-labels", "") != ""
style = request.args.get("style", "") != ""
embed = request.args.get("embed", "") != ""
return Response(
polycule.as_svg(edge_labels=labels, include_style=style, embed=embed),
mimetype="image/svg+xml",
)
@app.route("/export/<string:polycule_id>/polycule.png", methods=["GET", "POST"])
def export_png(polycule_id):
try:
polycule = Polycule.get(g.db, polycule_id, request.form.get("view_pass", ""))
except Polycule.PermissionDenied:
return render_template("view_auth.jinja2")
if polycule is None:
return render_template("error.jinja2", error="Polycule not found :(")
labels = request.args.get("link-labels", "") != ""
source = request.args.get("from", "dot")
if source == "dot":
png = polycule.as_png_from_dot(edge_labels=labels)
elif source == "svg":
style = request.args.get("style", "") != ""
embed = request.args.get("embed", "") != ""
png = polycule.as_png_from_svg(
edge_labels=labels, include_style=style, embed=embed
)
return Response(png, mimetype="image/png")
if __name__ == "__main__":
migrate()
app.run(host=IP)