-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·1522 lines (1314 loc) · 54 KB
/
main.py
File metadata and controls
executable file
·1522 lines (1314 loc) · 54 KB
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# This allows joining existing reviews and
# creating new ones.
# PDF Review tool, created by Francois Botman, 2017.
import glob
import html
import json
import os
import random
import re
import string
import tempfile
import time
from datetime import timedelta
from enum import Enum
from subprocess import PIPE, Popen
from typing import Annotated, Any, Awaitable, Callable, cast
from urllib.parse import quote_plus
from fastapi import Depends, FastAPI, Form, HTTPException, Query, Request, Response, UploadFile
from fastapi.openapi.docs import get_swagger_ui_html, get_swagger_ui_oauth2_redirect_html
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from sqlalchemy import Connection, create_engine, sql
from starlette.middleware.sessions import SessionMiddleware
import config
from auth import MSALAuth, UserInfo
from system_checks import check_encoding, require_db_version
app = FastAPI(docs_url=None, redoc_url=None)
app.add_middleware(SessionMiddleware, secret_key=config.config["msal_secret"])
auth = MSALAuth(
config.config["msal_client_id"],
config.config["msal_client_credential"],
config.config["msal_tenant"],
["User.Read", "email"],
)
app.include_router(auth.router)
app.mount("/cmaps", StaticFiles(directory="cmaps"), name="cmaps")
app.mount("/css", StaticFiles(directory="css"), name="css")
app.mount("/font", StaticFiles(directory="font"), name="font")
app.mount("/img", StaticFiles(directory="img"), name="img")
app.mount("/js", StaticFiles(directory="js"), name="js")
templates = Jinja2Templates(directory="templates")
db_url = "mysql://{}:{}@{}/{}?charset=utf8mb4".format(
*[
quote_plus(s)
for s in [
config.config["db_user"],
config.config["db_passwd"],
config.config["db_host"],
config.config["db_name"],
]
]
)
engine = create_engine(db_url, echo=False, pool_pre_ping=True)
check_encoding()
with engine.connect() as _conn:
require_db_version(_conn, "019af732851b")
#
# Support functions ----------------------------------------------------------------------------------
#
def gen_random_string(size: int = 128):
chars = "".join([string.ascii_uppercase, string.ascii_lowercase, string.digits])
return "".join(random.choice(chars) for _ in range(size))
def string_sanitiser(txt: str):
return "".join(txt.split("\x00"))
def escape_ps(txt: str):
substitutions = [
[r"([\(\)\[\]\{\}\%])", r"\\\1"],
[r"\<", r"<"],
[r"\>", r">"],
]
for substitution in substitutions:
(txt, _) = re.subn(substitution[0], substitution[1], txt)
return string_sanitiser(txt)
def escape_html(txt: str):
substitutions = [
[r"\<", r"<"],
[r"\>", r">"],
]
for substitution in substitutions:
(txt, _) = re.subn(substitution[0], substitution[1], txt)
return string_sanitiser(txt)
def execute_with_return(cmd: list[str]):
with Popen(cmd, stdin=PIPE, stdout=PIPE) as p:
out, _ = p.communicate()
return (p.returncode, out.decode("utf-8"))
def ensure_review_open(conn: Connection, review_id: str):
result = conn.execute(
sql.text("SELECT closed FROM reviews WHERE reviewid=:review_id"), {"review_id": review_id}
).fetchone()
if result:
if result.closed:
return JSONResponse(
{"errorCode": 3, "errorMsg": "The review has been declared closed. No further comments are accepted."}
)
else:
return JSONResponse({"errorCode": 4, "errorMsg": "The specified review could not be located."})
return None
def change_review_status(conn: Connection, current_user: UserInfo, review_id: str, closed: bool):
result = conn.execute(
sql.text("SELECT id, owner FROM reviews WHERE reviewid=:review_id"), {"review_id": review_id}
).fetchone()
if result:
if not result.owner == current_user.user_id:
return JSONResponse(
{
"errorCode": 1,
"errorMsg": f"Only the owner of a PDF review can choose to {"close" if closed else "reopen"} it.",
}
)
else:
return JSONResponse({"errorCode": 2, "errorMsg": "The specified review could not be located."})
conn.execute(
sql.text("UPDATE reviews SET closed=:closed WHERE reviewid=:review_id"),
{"closed": closed, "review_id": review_id},
)
conn.commit()
return None
def list_comments(conn: Connection, current_user: UserInfo, review_id: str):
processed_results: list[dict[str, Any]] = []
results = conn.execute(
sql.text(
"SELECT comments.id, comments.hash, comments.author, user_info.name, comments.pageId, comments.type, comments.msg, comments.status, comments.rects, comments.replyToId, comments.timestamp, comments.deleted, myread.myread FROM comments LEFT JOIN myread ON comments.hash=myread.commenthash AND comments.reviewid=myread.reviewid AND myread.reader=:uid LEFT JOIN user_info ON comments.author=user_info.uid WHERE comments.reviewid=:review_id ORDER BY comments.id ASC"
),
{"uid": current_user.user_id, "review_id": review_id},
).fetchall()
for row in results:
tmp: dict[str, Any] = {
"id": row.hash,
"author": row.name,
"msg": row.msg,
"status": row.status,
"secs_UTC": row.timestamp,
"deleted": row.deleted,
"rects": [],
"owner": (row.author == current_user.user_id),
}
if row.pageId is not None:
tmp["pageId"] = row.pageId
if row.type is not None:
tmp["type"] = row.type
if row.replyToId is not None:
tmp["replyToId"] = row.replyToId
if row.rects is not None:
tmp["rects"] = json.loads(row.rects)
if not (row.myread or row.author == current_user.user_id):
tmp["unread"] = True
processed_results.append(tmp)
return processed_results
def get_comment_export(comments: list[dict[str, Any]], comment_id: int) -> dict[str, Any]:
replies: list[dict[str, Any]] = []
this_comment = {}
for comment in comments:
if comment["id"] == comment_id:
this_comment = comment
if comment.get("replyToId") == comment_id and not comment.get("deleted"):
replies.append(get_comment_export(comments, comment["id"]))
return {
"id": this_comment.get("id"),
"author": this_comment.get("author", "Anonymous"),
"msg": this_comment.get("msg", ""),
"status": this_comment.get("status", "None"),
"secs_UTC": this_comment.get("secs_UTC"),
"read": not this_comment.get("unread", False),
"owner": this_comment.get("owner", False),
"pageId": this_comment.get("pageId"),
"type": this_comment.get("type", "reply"),
"rects": this_comment.get("rects"),
"replies": replies,
}
def ps_format_msg(message: str):
return "<p>" + escape_ps(message) + "</p>"
def get_ps_comment_reply(comments: list[dict[str, Any]], reply_to_id: int, indent: int = 1):
txt = ""
indent_spaces = "\n" + (" " * indent)
for comment in comments:
if "replyToId" in comment and comment["replyToId"] == reply_to_id:
txt += f"\n{indent_spaces}<p><b>" + cast(str, comment["author"]) + "</b></p>"
txt += indent_spaces + indent_spaces.join(ps_format_msg(comment["msg"]).split("\n"))
txt += cast(str, get_ps_comment_reply(comments, comment["id"], indent + 1))
return txt
def create_ps_from_comments(comments: list[dict[str, Any]], page_offset: int, highlights: bool):
ps_highlights = ""
ps = "%!PS\n\n"
ps += f"[ /Producer ({config.config["branding"]} PDF Review)\n"
ps += " /DOCINFO pdfmark\n\n"
for comment in comments:
if not "replyToId" in comment and not comment.get("deleted"):
bounding = {"x1": 10000000, "x2": 0, "y1": 10000000, "y2": 0}
quadpoints = ""
page_num = comment["pageId"] + 1 - page_offset
for rect in comment["rects"]:
if comment["type"] in ["highlight", "strike"]:
# Annoyingly, acrobat does not follow the PDF spec.
# It should be [bl, br, tr, tl], but it is actually
# [tl, tr, bl, br]. Grrrr.
quadpoints += "%s %s %s %s %s %s %s %s " % (
min(rect["tl"][0], rect["br"][0]), # x1 -- tl
max(rect["tl"][1], rect["br"][1]), # y1 -- tl
max(rect["tl"][0], rect["br"][0]), # x2 -- tr
max(rect["tl"][1], rect["br"][1]), # y2 -- tr
min(rect["tl"][0], rect["br"][0]), # x3 -- bl
min(rect["tl"][1], rect["br"][1]), # y3 -- bl
max(rect["tl"][0], rect["br"][0]), # x4 -- br
min(rect["tl"][1], rect["br"][1]), # y5 -- br
)
bounding["x1"] = min(bounding["x1"], rect["tl"][0], rect["br"][0])
bounding["y1"] = min(bounding["y1"], rect["tl"][1], rect["br"][1])
bounding["x2"] = max(bounding["x2"], rect["tl"][0], rect["br"][0])
bounding["y2"] = max(bounding["y2"], rect["tl"][1], rect["br"][1])
else:
bounding["x1"] = rect["tl"][0]
bounding["y1"] = rect["tl"][1]
bounding["x2"] = rect["tl"][0]
bounding["y2"] = rect["tl"][1]
ps += "[ /Rect [%s %s %s %s]\n" % (
bounding["x1"],
bounding["y1"],
bounding["x2"],
bounding["y2"],
) # [llx, lly, urx, ury]
if comment["type"] == "highlight":
ps += " /Subtype /Highlight\n"
ps += " /Color [1 0.95 0.66]\n" # fff2a8
elif comment["type"] == "strike":
ps += " /Subtype /StrikeOut\n"
ps += " /Color [1 0.7 0.7]\n" # ffb7b7
else:
ps += " /Subtype /Text\n"
ps += " /Color [1 0.95 0.66]\n" # fff2a8
ps += f" /SrcPg {page_num}\n"
if len(quadpoints) > 0:
ps += f" /QuadPoints [{quadpoints}]\n"
status = f" \\({comment["status"]}\\)" if not comment["status"] == "None" else ""
ps += f" /Title ({escape_ps(comment["author"])}{status})\n"
msg = ps_format_msg(comment["msg"]) + get_ps_comment_reply(comments, comment["id"])
ps += f""" /RC (<?xml version="1.0"?><body xmlns="http://www.w3.org/1999/xhtml" xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/" xfa:APIVersion="Acrobat:15.23.0" xfa:spec="2.0.2">{msg}</body>)\n"""
ps += " /ANN pdfmark\n\n"
ps_highlights += f" pageNum {page_num} eq {{\n"
ps_highlights += " {} {} {} {} {} highlight\n".format(
bounding["x1"],
bounding["y1"],
bounding["x2"],
bounding["y2"],
(
"1 0.95 0.66"
if comment["type"] == "highlight"
else "1 0.7 0.7" if comment["type"] == "strike" else "1 0.95 0.66"
),
)
ps_highlights += " } if\n"
if highlights:
ps += "/roundbox { % needs width, height and corner radius\n"
ps += " /radius exch def /height exch def /width exch def\n"
ps += " radius 1 lt { /radius 1 def } if\n"
ps += " width 2 lt { /width 10 def } if\n"
ps += " height 2 lt { /height 10 def } if\n"
ps += " 0 radius moveto\n"
ps += " 0 height width height radius arcto 4 {pop} repeat\n"
ps += " width height width 0 radius arcto 4 {pop} repeat\n"
ps += " width 0 0 0 radius arcto 4 {pop} repeat\n"
ps += " 0 0 0 height radius arcto 4 {pop} repeat\n"
ps += " closepath\n"
ps += "} def\n\n"
ps += "/highlight { % xll yll xur yur r g b\n"
ps += " /colb exch def /colg exch def /colr exch def\n"
ps += " /yur exch def /xur exch def /yll exch def /xll exch def\n"
ps += " xll yll moveto\n"
ps += " gsave\n"
ps += " currentpoint translate\n"
ps += " xur xll sub yur yll sub 1 roundbox\n"
ps += " colr colg colb setrgbcolor fill\n"
ps += " grestore\n"
ps += "} def\n\n"
ps += "globaldict /pageNum 1 put\n\n"
ps += "<< /BeginPage {\n"
ps += " /showCount exch def\n"
ps += ps_highlights
ps += " showCount 1 eq {\n"
ps += " globaldict /pageNum pageNum 1 add put\n"
ps += " } if\n"
ps += "} bind\n"
ps += ">> setpagedevice\n\n"
return ps
def list_my_reviews(conn: Connection, current_user: UserInfo):
reviews: list[dict[str, Any]] = []
result = conn.execute(
sql.text("SELECT reviewid FROM myreviews WHERE reader=:uid GROUP BY reviewid ORDER BY reviewid DESC"),
{"uid": current_user.user_id},
).fetchall()
for row in result:
reviewdetails = conn.execute(
sql.text("SELECT reviewid, owner, closed, title, pdffile FROM reviews WHERE reviewid=:review_id"),
{"review_id": row.reviewid},
).fetchone()
if reviewdetails:
reviews.append(
{
"id": reviewdetails.reviewid,
"owner": reviewdetails.owner == current_user.user_id,
"title": reviewdetails.title,
"closed": reviewdetails.closed,
"pdf": reviewdetails.pdffile,
}
)
return reviews
def get_user_or_login(request: Request):
current_user = auth.get_current_user(request)
if not current_user:
path_param = auth.handler.sign_path(request.url.path + ("?" if request.url.query else "") + request.url.query)
return RedirectResponse(request.url_for("_login_route").include_query_params(**{"next": path_param}))
if not current_user.user_id or not current_user.display_name or not current_user.email:
return JSONResponse({"errorCode": 1, "errorMsg": "Invalid user"})
with engine.connect() as conn:
conn.execute(
sql.text(
"INSERT INTO user_info (uid, name, email, last_active) VALUES (:uid, :name, :email, :last_active) ON DUPLICATE KEY UPDATE name=VALUES(name), email=VALUES(email), last_active=VALUES(last_active)"
),
{
"uid": current_user.user_id,
"name": current_user.display_name,
"email": current_user.email.lower(),
"last_active": time.time(),
},
)
conn.commit()
return current_user
# TODO: Not currently used or tested, but demonstrates how this should work
def can_access_review(current_user: UserInfo, review_id: str):
with engine.connect() as conn:
result = conn.execute(
sql.text("SELECT owner FROM reviews WHERE reviewid=:review"),
{"review": review_id},
).fetchone()
if result and result.owner == current_user.user_id:
return True
for result in conn.execute(
sql.text("SELECT uid, gid FROM acl WHERE reviewid=:review"),
{"review": review_id},
).fetchall():
if result.uid and result.uid == current_user.user_id:
return True
if result.gid and result.gid in current_user.groups:
return True
return False
#
# Static resources -----------------------------------------------------------------------------------
#
@app.get("/favicon.png", include_in_schema=False)
async def favicon():
return FileResponse("favicon.png")
@app.get("/favicon256.png", include_in_schema=False)
async def favicon256():
return FileResponse("favicon256.png")
@app.get("/favicon512.png", include_in_schema=False)
async def favicon512():
return FileResponse("favicon512.png")
@app.get("/faq.html", include_in_schema=False)
async def faq():
return FileResponse("faq.html")
@app.get("/unsupported.html", include_in_schema=False)
async def unsupported():
return FileResponse("unsupported.html")
@app.get("/manifest.json", include_in_schema=False)
async def manifest_json():
return FileResponse("manifest.json")
#
# Middleware -----------------------------------------------------------------------------------------
#
@app.middleware("http")
async def noop_serviceworker(request: Request, call_next: Callable[[Request], Awaitable[Response]]):
service_worker = request.headers.get("Service-Worker")
if service_worker and request.url.path != "/serviceworker":
return FileResponse(
"noop-service-worker.js",
media_type="application/javascript",
)
return await call_next(request)
#
# Handle API calls -----------------------------------------------------------------------------------
#
@app.post(
"/api/add-comment",
response_model=UserInfo,
response_model_exclude_none=True,
response_model_by_alias=False,
)
async def api_add_comment(
review: Annotated[str, Form()],
comment: Annotated[str, Form()],
current_user: UserInfo = Depends(auth.scheme),
):
comment_json = json.loads(string_sanitiser(comment))
if not comment_json.get("replyToId") and not comment_json.get("rects"):
return JSONResponse({"errorCode": 2, "errorMsg": "Missing parameters for comment :("})
if not comment_json.get("id"):
comment_json["id"] = gen_random_string(64)
with engine.connect() as conn:
response = ensure_review_open(conn, review)
if response:
return response
conn.execute(
sql.text(
"INSERT INTO activity (msg, owner, url, reviewid, timestamp) VALUES (:msg, :owner, :url, :review_id, :timestamp)"
),
{
"msg": "<B>"
+ str(current_user.display_name)
+ "</B> "
+ ("added a comment: " if not comment_json.get("replyToId") else "replied to a comment: ")
+ escape_html(comment_json.get("msg", "")),
"owner": current_user.user_id,
"url": config.config["url"] + "?review=" + review,
"review_id": review,
"timestamp": time.time(),
},
)
# Some comments might inadvertently be uploaded multiple times (interrupted syncs, etc).
# While this is not a problem, let's make it cleaner.
result = conn.execute(
sql.text("SELECT hash FROM comments WHERE hash=:hash AND reviewid=:review_id"),
{"hash": comment_json.get("id"), "review_id": review},
).fetchone()
if not result:
conn.execute(
sql.text(
"INSERT INTO comments (hash, author, pageId, type, msg, status, rects, replyToId, reviewid, timestamp, deleted) VALUES (:hash, :author, :page_id, :type, :msg, 'None', :rects, :reply_to_id, :review_id, :timestamp, :deleted)"
),
{
"hash": comment_json.get("id"),
"author": current_user.user_id,
"page_id": comment_json.get("pageId"),
"type": comment_json.get("type"),
"msg": comment_json.get("msg", ""),
"rects": json.dumps(comment_json["rects"]) if "rects" in comment_json else None,
"reply_to_id": comment_json.get("replyToId"),
"review_id": review,
"timestamp": time.time(),
"deleted": False,
},
)
conn.commit()
if not result or len(result) == 0:
return JSONResponse({"errorCode": 0, "errorMsg": "Success"})
return JSONResponse({"errorCode": 0, "errorMsg": "Ignored", "ignored": "yes"})
@app.post(
"/api/delete-comment",
response_model=UserInfo,
response_model_exclude_none=True,
response_model_by_alias=False,
)
async def api_delete_comment(
review: Annotated[str, Form()],
commentid: Annotated[str, Form()],
current_user: UserInfo = Depends(auth.scheme),
):
with engine.connect() as conn:
response = ensure_review_open(conn, review)
if response:
return response
conn.execute(
sql.text(
"INSERT INTO activity (msg, owner, url, reviewid, timestamp) VALUES (:msg, :owner, :url, :review_id, :timestamp)"
),
{
"msg": "<B>" + str(current_user.display_name) + "</B> deleted a comment.",
"owner": current_user.user_id,
"url": config.config["url"] + "?review=" + review,
"review_id": review,
"timestamp": time.time(),
},
)
conn.execute(
sql.text(
"UPDATE comments SET deleted=:deleted WHERE hash=:hash AND reviewid=:review_id AND author=:author"
),
{"deleted": True, "hash": commentid, "review_id": review, "author": current_user.user_id},
)
conn.commit()
return JSONResponse({"errorCode": 0, "errorMsg": "Success"})
@app.post(
"/api/update-comment-status",
response_model=UserInfo,
response_model_exclude_none=True,
response_model_by_alias=False,
)
async def api_update_comment_status(
review: Annotated[str, Form()],
commentid: Annotated[str, Form()],
status: Annotated[str, Form()],
_: UserInfo = Depends(auth.scheme),
):
with engine.connect() as conn:
# This is allowed even when reviews are closed
conn.execute(
sql.text("UPDATE comments SET status=:status WHERE hash=:hash AND reviewid=:review_id"),
{
"status": string_sanitiser(status),
"hash": commentid,
"review_id": review,
},
)
conn.commit()
return JSONResponse({"errorCode": 0, "errorMsg": "Success"})
@app.post(
"/api/update-comment-message",
response_model=UserInfo,
response_model_exclude_none=True,
response_model_by_alias=False,
)
async def api_update_comment_message(
review: Annotated[str, Form()],
commentid: Annotated[str, Form()],
message: Annotated[str, Form()],
current_user: UserInfo = Depends(auth.scheme),
):
with engine.connect() as conn:
response = ensure_review_open(conn, review)
if response:
return response
conn.execute(
sql.text(
"INSERT INTO activity (msg, owner, url, reviewid, timestamp) VALUES (:msg, :owner, :url, :review_id, :timestamp)"
),
{
"msg": "<B>"
+ str(current_user.display_name)
+ "</B> updated a comment's message. New message: "
+ escape_html(message),
"owner": current_user.user_id,
"url": config.config["url"] + "?review=" + review,
"review_id": review,
"timestamp": time.time(),
},
)
conn.execute(
sql.text("UPDATE comments SET msg=:msg WHERE hash=:hash AND reviewid=:review_id AND author=:author"),
{
"msg": string_sanitiser(message),
"hash": commentid,
"review_id": review,
"author": current_user.user_id,
},
)
conn.commit()
return JSONResponse({"errorCode": 0, "errorMsg": "Success"})
@app.post(
"/api/list-comments",
response_model=UserInfo,
response_model_exclude_none=True,
response_model_by_alias=False,
)
async def api_list_comments(
review: Annotated[str, Form()],
current_user: UserInfo = Depends(auth.scheme),
):
with engine.connect() as conn:
comments = list_comments(conn, current_user, review)
result = conn.execute(
sql.text("SELECT id, closed FROM reviews WHERE reviewid=:review_id"), {"review_id": review}
).fetchone()
review_status = "closed"
if result and not result.closed:
review_status = "open"
return JSONResponse({"errorCode": 0, "errorMsg": "Success", "comments": comments, "status": review_status})
@app.post(
"/api/user-mark-comment",
response_model=UserInfo,
response_model_exclude_none=True,
response_model_by_alias=False,
)
async def api_user_mark_comment(
review: Annotated[str, Form()],
commentid: Annotated[str, Form(alias="id")],
commentas: Annotated[str, Form(alias="as")],
current_user: UserInfo = Depends(auth.scheme),
):
if commentas not in ["read", "unread"]:
return JSONResponse({"errorCode": 1, "errorMsg": "Missing parameters: mark state :("})
with engine.connect() as conn:
conn.execute(
sql.text("DELETE FROM myread WHERE commenthash=:hash AND reviewid=:review_id AND reader=:reader"),
{"hash": commentid, "review_id": review, "reader": current_user.user_id},
)
if commentas == "read":
conn.execute(
sql.text(
"INSERT INTO myread (commenthash, reviewid, reader, myread) VALUES (:hash, :review_id, :reader, :my_read)"
),
{"hash": commentid, "review_id": review, "reader": current_user.user_id, "my_read": True},
)
conn.commit()
return JSONResponse({"errorCode": 0, "errorMsg": "Success"})
@app.get(
"/api/close-review",
response_model=UserInfo,
response_model_exclude_none=True,
response_model_by_alias=False,
)
async def api_close_review(
review: str,
current_user: UserInfo = Depends(auth.scheme),
):
with engine.connect() as conn:
response = change_review_status(conn, current_user, review, True)
if response:
return response
return JSONResponse({"errorCode": 0, "errorMsg": "Success"})
@app.get(
"/api/reopen-review",
response_model=UserInfo,
response_model_exclude_none=True,
response_model_by_alias=False,
)
async def api_reopen_review(
review: str,
current_user: UserInfo = Depends(auth.scheme),
):
with engine.connect() as conn:
response = change_review_status(conn, current_user, review, False)
if response:
return response
return JSONResponse({"errorCode": 0, "errorMsg": "Success"})
@app.get(
"/api/remove-review",
response_model=UserInfo,
response_model_exclude_none=True,
response_model_by_alias=False,
)
async def api_remove_review(
review: str,
current_user: UserInfo = Depends(auth.scheme),
):
with engine.connect() as conn:
result = conn.execute(
sql.text("SELECT owner FROM reviews WHERE reviewid=:review_id"), {"review_id": review}
).fetchone()
if result:
if result.owner == current_user.user_id:
return JSONResponse(
{
"errorCode": 1,
"errorMsg": "As an owner, you must close/delete a review instead of just removing it from your list",
}
)
else:
return JSONResponse({"errorCode": 2, "errorMsg": "The specified review could not be located."})
conn.execute(
sql.text("DELETE FROM myreviews WHERE reviewid=:review_id AND reader=:uid"),
{"review_id": review, "uid": current_user.user_id},
)
conn.commit()
return JSONResponse({"errorCode": 0, "errorMsg": "Success"})
@app.get(
"/api/delete-review",
response_model=UserInfo,
response_model_exclude_none=True,
response_model_by_alias=False,
)
async def api_delete_review(
review: str,
current_user: UserInfo = Depends(auth.scheme),
):
with engine.connect() as conn:
response = change_review_status(conn, current_user, review, False)
if response:
return response
result = conn.execute(
sql.text("SELECT owner, pdffile FROM reviews WHERE reviewid=:review_id"),
{"review_id": review},
).fetchone()
if result:
if result.owner != current_user.user_id:
raise HTTPException(status_code=403, detail="Cannot delete a review you do not own")
if os.path.lexists(result.pdffile):
os.remove(result.pdffile)
result = conn.execute(
sql.text("SELECT filename FROM archives WHERE reviewid=:review_id"),
{"review_id": review},
).fetchone()
if result:
if os.path.lexists(result.filename):
os.remove(result.filename)
conn.execute(sql.text("DELETE FROM reviews WHERE reviewid=:review_id"), {"review_id": review})
conn.execute(sql.text("DELETE FROM archives WHERE reviewid=:review_id"), {"review_id": review})
conn.execute(sql.text("DELETE FROM comments WHERE reviewid=:review_id"), {"review_id": review})
conn.execute(sql.text("DELETE FROM myread WHERE reviewid=:review_id"), {"review_id": review})
conn.execute(sql.text("DELETE FROM myreviews WHERE reviewid=:review_id"), {"review_id": review})
conn.execute(sql.text("DELETE FROM activity WHERE reviewid=:review_id"), {"review_id": review})
conn.execute(sql.text("DELETE FROM errors WHERE reviewid=:review_id"), {"review_id": review})
conn.commit()
return JSONResponse({"errorCode": 0, "errorMsg": "Success"})
@app.get(
"/api/export-comments",
response_model=UserInfo,
response_model_exclude_none=True,
response_model_by_alias=False,
)
async def api_export_comments(
review: str,
output_format: Annotated[str, Query(alias="as")],
current_user: UserInfo = Depends(auth.scheme),
):
if output_format not in ["json"]:
return JSONResponse({"errorCode": 1, "errorMsg": "Invalid requested output format :("})
with engine.connect() as conn:
comments = list_comments(conn, current_user, review)
exported_comments: list[dict[str, Any]] = []
for comment in comments:
if not comment.get("replyToId") and not comment.get("deleted"):
exported_comments.append(get_comment_export(comments, comment["id"]))
return JSONResponse(exported_comments)
class OutputFormat(str, Enum):
PNG = "png"
PDF = "pdf"
@app.get(
"/api/pdf-archive",
response_model=UserInfo,
response_model_exclude_none=True,
response_model_by_alias=False,
)
async def api_pdf_archive_get(
review: str,
commentid: str | None = None,
output_format: OutputFormat | None = None,
password: str | None = None,
highlights: bool = False,
current_user: UserInfo = Depends(auth.scheme),
):
return api_pdf_archive(review, commentid, output_format, password, highlights, current_user)
@app.post(
"/api/pdf-archive",
response_model=UserInfo,
response_model_exclude_none=True,
response_model_by_alias=False,
)
async def api_pdf_archive_post(
review: Annotated[str, Form()],
commentid: Annotated[str, Form()] | None = None,
output_format: Annotated[OutputFormat, Form(alias="format")] | None = None,
password: Annotated[str, Form()] | None = None,
highlights: Annotated[bool, Form()] = False,
current_user: UserInfo = Depends(auth.scheme),
):
return api_pdf_archive(review, commentid, output_format, password, highlights, current_user)
def api_pdf_archive(
review: str,
commentid: str | None,
output_format: OutputFormat | None,
password: str | None,
highlights: bool,
current_user: UserInfo,
):
if output_format == OutputFormat.PNG:
highlights = True
with engine.connect() as conn:
result = conn.execute(
sql.text("SELECT pdffile FROM reviews WHERE reviewid=:review_id"), {"review_id": review}
).fetchone()
if result:
pdffile = result.pdffile
comments = list_comments(conn, current_user, review)
else:
return JSONResponse({"errorCode": 2, "errorMsg": "The specified review could not be located."})
with tempfile.NamedTemporaryFile(delete_on_close=False) as f_psinput:
f_psinput.close()
while True:
filename = (
config.config["archive_path"]
+ gen_random_string(64)
+ (".png" if output_format == OutputFormat.PNG else ".pdf")
)
if not os.path.isfile(filename):
break
# Create postscript annotations
cmd: list[str] = [
config.config["ghostscript_path"],
"-dSAFER",
"-dBATCH",
"-dNOPAUSE",
"-q",
"-sOutputFile=" + filename,
"-sDEVICE=png16m" if output_format == OutputFormat.PNG else "-sDEVICE=pdfwrite",
"-dPDFSETTINGS=/prepress",
]
if password:
cmd.append("-sPDFPassword=" + html.escape(password))
cmd.append("-sOwnerPassword=" + html.escape(password))
cmd.append("-sUserPassword=" + html.escape(password))
# The whole thing, or just a specific comment?
page_num = 0
if commentid:
newcomments = [x for x in comments if x.get("id") == commentid or x.get("replyToId") == commentid]
comments = newcomments
if len(comments) == 0:
return JSONResponse({"errorCode": 4, "errorMsg": "No suitable comments could be found."})
for x in comments:
page_num = int(x.get("pageId", page_num))
cmd.append("-r250")
cmd.append("-dPrinted=false")
cmd.append("-dFirstPage=" + str(page_num + 1))
cmd.append("-dLastPage=" + str(page_num + 1))
cmd.append(f_psinput.name)
cmd.append(pdffile)
ps = create_ps_from_comments(comments, page_num, highlights)
with open(f_psinput.name, "w", encoding="utf-8") as output_file:
output_file.write(ps)
output_file.write(f"%% {" ".join(cmd)}\n")
# Run ghostscript
(retcode, output) = execute_with_return(cmd)
archive_id = gen_random_string(16)
with engine.connect() as conn:
result = conn.execute(
sql.text(
"INSERT INTO archives (archiveid, reviewid, type, filename, created) VALUES (:archive_id, :review, :type, :filename, :created)"
),
{
"archive_id": archive_id,
"review": review,
"type": output_format or OutputFormat.PDF,
"filename": filename,
"created": time.time(),
},
)
# Remove archives >1h old
for result in conn.execute(
sql.text("SELECT id, filename FROM archives WHERE created<=:created"),
{"created": time.time() - timedelta(hours=1).seconds},
).fetchall():
if os.path.lexists(result.filename):
os.remove(result.filename)
conn.execute(
sql.text("DELETE FROM archives WHERE id=:id"),
{"id": result.id},
)
conn.commit()
if retcode == 0:
return JSONResponse(
{"errorCode": 0, "errorMsg": "Success", "url": f"/api/review/{review}/archive/{archive_id}"}
)
return JSONResponse({"errorCode": 3, "errorMsg": "Could not process archive file.", "debug": output})
@app.post(
"/api/report-error",
response_model=UserInfo,
response_model_exclude_none=True,
response_model_by_alias=False,
include_in_schema=False,
)
async def api_report_error(
review: Annotated[str, Form()],
details: Annotated[str, Form()],
msg: Annotated[str, Form()],
current_user: UserInfo = Depends(auth.scheme),
):
with engine.connect() as conn:
conn.execute(
sql.text("INSERT INTO errors (reviewid, owner, details, msg) VALUES (:review_id, :owner, :details, :msg)"),
{
"review_id": review,
"owner": current_user.user_id,
"details": details,
"msg": msg,
},
)