-
Notifications
You must be signed in to change notification settings - Fork 0
/
_app.py
466 lines (419 loc) · 16.6 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
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
from flask import Flask, render_template, request, make_response, redirect
import sqlite3
import os
import json
import dotenv
app = Flask(__name__)
# set static folder
app._static_folder = 'static'
dotenv.load_dotenv()
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
def get_connection():
conn = sqlite3.connect('comic.db')
conn.row_factory = dict_factory
return conn
def alternate_connection(x):
conn = sqlite3.connect(x)
conn.row_factory = dict_factory
return conn
def get_character_directory():
return open('characters.json','r+')
conn = get_connection()
# index
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html',sitename=os.getenv("SITE_TITLE"))
@app.route('/chapters')
def chapters():
# get list of chapter from comic db
chapters = get_connection().execute('SELECT * FROM chapters').fetchall()
# get number of highest issue
return render_template('chapters.html',sitename=os.getenv("SITE_TITLE"),chapters=chapters)
@app.route('/comic')
def comic():
return redirect('/comic/1')
@app.route('/socialmedia')
def socialmedia():
return render_template('socialmedia.html',sitename=os.getenv("SITE_TITLE"))
@app.route('/comic/last')
def comic_last():
highest_issue = get_connection().execute('SELECT COUNT(*) FROM comics').fetchone().get('COUNT(*)')
return redirect('/comic/'+str(highest_issue))
@app.route('/comic/first')
def comic_first():
return redirect('/comic/1')
@app.route('/comic/<int:issue>')
def comic_issue(issue):
highest_issue = get_connection().execute('SELECT COUNT(*) FROM comics').fetchone().get('COUNT(*)')
if issue > highest_issue:
return page_not_found(404)
# render comic template if issue is in database
comic = get_connection().execute('SELECT * FROM comics WHERE rowid=?', (issue,)).fetchone()
# return str(comic)
# get number of highest issue
image_path = comic.get('image_path') or 'placeholder.png'
row_id = comic.get('rowid') or 0
desc = comic.get('description') or "..."
print(highest_issue)
return render_template('comic.html',sitename=os.getenv("SITE_TITLE"),d=desc,p=image_path,issue=issue,high=highest_issue)
@app.route('/comic/<int:issue>/')
def comic_issue_slash(issue):
return redirect('/comic/'+str(issue))
@app.route('/sidecontent')
def side():
chapters=[]
# get every json file in ./side-content-data
for filename in os.listdir('./side-content-data'):
if filename.endswith('.json'):
with open('./side-content-data/'+filename) as json_file:
data = json.load(json_file)
data["filename"] = filename[:-5] # dont include the extension
chapters.append(data)
print(data)
return render_template('sidecontent.html',sitename=os.getenv("SITE_TITLE"),chapters=chapters)
#region admin
@app.route('/admin',methods=['GET','POST'])
def admin():
if request.method == 'POST':
print(request.form.get('username'))
if request.form.get('username') != os.getenv('COMIC_ADMIN_UNAME'):
return render_template('admin.html',sitename=os.getenv("SITE_TITLE"),message='Incorrect.')
if request.form.get('password') != os.getenv('COMIC_ADMIN_PW'):
return render_template('admin.html',sitename=os.getenv("SITE_TITLE"),message='Incorrect.')
resp = make_response(redirect('/adminpanel'))
resp.set_cookie('user', os.getenv('COMIC_ADMIN_COOKIE'))
return resp
return render_template('admin.html',sitename=os.getenv("SITE_TITLE"))
@app.route('/adminpanel',methods=['GET','POST'])
def adminpanel():
# check if cookie is right
if administrator_check(request):
return make_response("Unauthorized",401)
# get comics from database
comics = get_connection().execute('SELECT * FROM comics').fetchall()
chapters = get_connection().execute('SELECT * FROM chapters').fetchall()
return render_template('adminpanel.html',comics=comics,chapters=chapters)
@app.route('/adminpanel/add',methods=['POST'])
def AddComic():
if administrator_check(request):
return make_response("Unauthorized",401)
# get image path and description from form
image_path = request.form.get('image_path')
description = request.form.get('description') or "..."
print(image_path + description)
# insert into database
conn = get_connection()
conn.execute('INSERT INTO comics VALUES (NULL, ?, ?)', (image_path, description))
conn.commit()
print("comic added")
return redirect('/adminpanel')
@app.route('/adminpanel/massadd',methods=['POST'])
def MassAddComic():
if administrator_check(request):
return make_response("Unauthorized",401)
low = int(request.form.get('low'));
high = int(request.form.get('high'));
highest_issue = get_connection().execute('SELECT COUNT(*) FROM comics').fetchone().get('COUNT(*)')
conn = get_connection()
for i in range(low,high+1):
image_path = str(i) + ".png"
description = " "
conn.execute('INSERT INTO comics VALUES (NULL, ?, ?)', (image_path, description))
conn.commit()
print("comics added")
return redirect('/adminpanel')
#region
@app.route('/adminpanel/edit',methods=['POST'])
def EditComic():
if administrator_check(request):
return make_response("Unauthorized",401)
print("edit comic")
# get id, image path, and description from form
id = request.form.get('id')
image_path = request.form.get('image_path')
description = request.form.get('description') or "..."
# update database
conn = get_connection()
conn.execute('UPDATE comics SET image_path=?, description=? WHERE rowid=?', (image_path, description, id))
conn.commit()
print("comic edited")
return redirect('/adminpanel')
@app.route('/adminpanel/upload',methods=['POST'])
def UploadToStatic():
if administrator_check(request) :
return make_response("Unauthorized",401)
# get image from form
uploaded_files = request.files.getlist("file")
print(uploaded_files)
# save image to static folder
for image in uploaded_files:
print(image.filename)
image.save('static/comic-pages/'+image.filename)
return redirect('/adminpanel')
@app.route('/adminpanel/uploadchaptericon',methods=['POST'])
def UploadChapterIcon():
if administrator_check(request) :
return make_response("Unauthorized",401)
# get image from form
uploaded_files = request.files.getlist("file")
print(uploaded_files)
# save image to static folder
for image in uploaded_files:
print(image.filename)
image.save('static/chapter-icons/'+image.filename)
return redirect('/adminpanel')
@app.route('/adminpanel/uploadsidepage',methods=['POST'])
def UploadSidePage():
if administrator_check(request):
return make_response("Unauthorized",401)
# get image from form
uploaded_files = request.files.getlist("file")
print(uploaded_files)
# save image to static folder
for image in uploaded_files:
print(image.filename)
image.save('static/side-pages/'+image.filename)
return redirect('/adminpanel')
@app.route('/adminpanel/delete',methods=['POST'])
def DeleteComic():
if administrator_check(request):
return make_response("Unauthorized",401)
# get id from form
id = request.form.get('id')
# delete from database
conn = get_connection()
conn.execute('DELETE FROM comics WHERE rowid=?', (id,))
conn.commit()
print("comic deleted")
return redirect('/adminpanel')
@app.route('/adminpanel/chapteradd',methods=['POST'])
def AddChapter():
if administrator_check(request):
return make_response("Unauthorized",401)
# get image path and description from form
web_path = request.form.get('web_path')
image_path = request.form.get('image_path')
name = request.form.get('name') or "..."
print(image_path + name)
# insert into database
conn = get_connection()
conn.execute('INSERT INTO chapters VALUES (?, ?, ?)', (web_path,image_path, name))
conn.commit()
print("chapter added")
return redirect('/adminpanel')
@app.route('/adminpanel/chapteredit',methods=['POST'])
def EditChapter():
if administrator_check(request):
return make_response("Unauthorized",401)
print("edit chapter")
# get id, image path, and description from form
web_path = request.form.get('web_path')
image_path = request.form.get('image_path')
name = request.form.get('name') or "..."
# update database
conn = get_connection()
conn.execute('UPDATE chapters SET image_path=?, name=? WHERE webpage=?', (image_path, name, web_path))
conn.commit()
print("chapter edited")
return redirect('/adminpanel')
@app.route('/adminpanel/chapterdelete',methods=['POST'])
def DeleteChapter():
if administrator_check(request):
return make_response("Unauthorized",401)
# get id from form
web_path = request.form.get('web_path')
# delete from database
conn = get_connection()
conn.execute('DELETE FROM chapters WHERE webpage=?', (web_path,))
conn.commit()
print("chapter deleted")
return redirect('/adminpanel')
@app.route('/adminpanel/createsidecomic',methods=['POST'])
def CreateSideComic():
if administrator_check(request):
return make_response("Unauthorized",401)
name = request.form.get('name')
filename = request.form.get('filename')
banner_image = request.form.get('image_path')
description = request.form.get('description') or "A side comic."
# create database
conn = alternate_connection('./side-content-data/'+filename+'.db')
conn.execute('CREATE TABLE IF NOT EXISTS comics (rowid INTEGER PRIMARY KEY, image_path TEXT, description TEXT)')
conn.commit()
# make data json file
data = {
'name': name,
'banner_image': banner_image,
'description': description,
'filename': filename
}
with open('./side-content-data/'+filename+'.json', 'w') as outfile:
json.dump(data, outfile)
print("side comic created")
return redirect('/adminpanel')
@app.route("/adminpanel/editsidedata",methods=['POST'])
def EditSideData():
if administrator_check(request):
return make_response("Unauthorized",401)
name = request.form.get('name')
filename = request.form.get('filename')
banner_image = request.form.get('banner_image') or "placeholder.png"
description = request.form.get('description') or "A side comic."
# make data json file
data = {
'name': name,
'banner_image': banner_image,
'description': description
}
with open('./side-content-data/'+filename+'.json', 'w') as outfile:
json.dump(data, outfile)
print("side comic data edited")
return redirect('/adminpanel')
@app.route("/adminpanel/sideaddpage",methods=['POST'])
def SideAddPage():
if administrator_check(request):
return make_response("Unauthorized",401)
name = request.form.get('filename')
image_path = request.form.get('image_path') or "placeholder.png"
description = request.form.get('description') or "..."
conn = get_side_db(name)
conn.execute('INSERT INTO comics VALUES (NULL, ?, ?)', (image_path, description))
conn.commit()
print("side comic page added")
return redirect('/adminpanel')
@app.route("/adminpanel/sideeditpage",methods=['POST'])
def SideEditPage():
if administrator_check(request):
return make_response("Unauthorized",401)
name = request.form.get('filename')
id = request.form.get('id')
image_path = request.form.get('image_path') or "placeholder.png"
description = request.form.get('description') or "..."
conn = get_side_db(name)
conn.execute('UPDATE comics SET image_path=?, description=? WHERE rowid=?', (image_path, description, id))
conn.commit()
print("side comic page edited")
return redirect('/adminpanel')
@app.route("/adminpanel/uploadcharacter",methods=['POST'])
def UploadCharacter():
if administrator_check(request):
return make_response("Unauthorized",401)
uploaded_files = request.files.getlist("file")
print(uploaded_files)
for image in uploaded_files:
print(image.filename)
image.save('static/characters/'+image.filename)
return redirect('/adminpanel')
@app.route("/adminpanel/addcharacter",methods=['POST'])
def AddCharacter():
if administrator_check(request):
return make_response("Unauthorized",401)
name = request.form.get('name')
file = get_character_directory()
data = json.load(file)
print(data)
data['characters'].append(name)
file.seek(0)
file.write(json.dumps(data))
print("character added")
return redirect('/adminpanel')
@app.route("/adminpanel/deletecharacter",methods=['POST'])
def DeleteCharacter():
if administrator_check(request):
return make_response("Unauthorized",401)
name = request.form.get('name')
file = get_character_directory()
data = json.load(file)
if not name in data:
return make_response("Character not found",404)
data['characters'].remove(name)
file.seek(0)
file.write(json.dumps(data))
print("character deleted")
return redirect('/adminpanel')
#endregion
@app.route("/characters")
def Characters():
file = get_character_directory()
data = json.load(file)
return render_template('characters.html',sitename=os.getenv("SITE_TITLE"),characters=data['characters'])
@app.route('/<chapter>')
def direct(chapter):
if chapter == "comic":
return redirect('/comic')
if chapter.isdigit():
issue = int(chapter)
highest_issue = get_connection().execute('SELECT COUNT(*) FROM comics').fetchone().get('COUNT(*)')
print(highest_issue)
if highest_issue < issue:
return make_response("Not Found (not a chapter)",404)
return redirect('/comic/'+str(issue))
if get_side_db(chapter) != None:
return side_comic_read(chapter,1)
return page_not_found(404)
@app.route('/<chapter>/<int:issue>')
def direct_sidecomic(chapter,issue):
if get_side_db(chapter) != None:
return side_comic_read(chapter,issue)
return page_not_found(404)
@app.route('/<chapter>/last')
def last_sidecomic(chapter):
if get_side_db(chapter) != None:
return side_comic_read(chapter,"HIGH")
@app.route('/<chapter>/first')
def first_sidecomic(chapter):
if get_side_db(chapter) != None:
return side_comic_read(chapter,1)
def side_comic_read(chapter,issue):
conn = get_side_db(chapter)
highest_issue = conn.execute('SELECT COUNT(*) FROM comics').fetchone().get('COUNT(*)')
if issue == "HIGH":
return redirect('/'+chapter+'/'+str(highest_issue))
if issue > highest_issue:
return page_not_found(404)
comic = conn.execute('SELECT * FROM comics WHERE rowid=?', (issue,)).fetchone()
image_path = comic.get('image_path') or 'placeholder.png'
row_id = comic.get('rowid') or 1
data = None
# get json file and load data
with open('./side-content-data/'+chapter+'.json') as json_file:
data = json.load(json_file)
print(data)
print(highest_issue)
comname = data.get('name') or "Side Comic"
fn = data.get('filename')
desc = comic.get('description') or "..."
return render_template('view_side.html',sitename=os.getenv("SITE_TITLE"),d=desc,p=image_path,issue=issue,high=highest_issue,comname=comname,filename=fn)
def get_side_db(id):
if os.path.isfile('./side-content-data/'+id+'.db'):
return alternate_connection('./side-content-data/'+id+'.db')
return None
@app.errorhandler(404)
def page_not_found(e):
return render_template('error.html',sitename=os.getenv("SITE_TITLE")), 404
def administrator_check(data):
return data.cookies.get('user') != os.getenv('COMIC_ADMIN_COOKIE')
def setup_tables():
conn.execute('CREATE TABLE IF NOT EXISTS comics (rowid INTEGER PRIMARY KEY, image_path TEXT, description TEXT)')
conn.execute('CREATE TABLE IF NOT EXISTS chapters (webpage TEXT,image_path TEXT, name TEXT)')
def setup_app():
fcheck = os.path.exists
setup_tables()
if fcheck('./characters.json') == False:
with open('characters.json', 'w') as outfile:
json.dump({"characters":[]}, outfile)
# check for directories
checks = ['./static','./static/comic-pages','./static/chapter-icons','./static/side-pages','./static/characters', './side-content-data', ]
for directory in checks:
if fcheck(directory) == False:
os.mkdir(directory)
# check for side comic databases
if __name__ == '__main__':
# create sql database called comics with an id, image path, and description
setup_app()
app.run(debug=True)