aboutsummaryrefslogtreecommitdiffstats
path: root/python/fatcat_web/routes.py
blob: e2c90d52489efb0ab4a75e8083c4c42710d3abfb (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
import json
import os
from typing import Any, Callable, Dict, List, Optional

import citeproc_styles
import sentry_sdk
from fatcat_openapi_client import EditgroupAnnotation
from fatcat_openapi_client.rest import ApiException, ApiValueError
from flask import (
    Response,
    abort,
    jsonify,
    make_response,
    redirect,
    render_template,
    request,
    send_from_directory,
    session,
    url_for,
)
from flask_login import login_required
from flask_wtf.csrf import CSRFError

from fatcat_tools.normal import (
    clean_arxiv_id,
    clean_doi,
    clean_isbn13,
    clean_issn,
    clean_orcid,
    clean_pmcid,
    clean_sha1,
    clean_sha256,
)
from fatcat_tools.search.common import FatcatSearchError
from fatcat_tools.transforms import citeproc_csl, release_to_csl
from fatcat_web import AnyResponse, Config, api, app, auth_api, mwoauth, priv_api
from fatcat_web.auth import (
    handle_ia_xauth,
    handle_logout,
    handle_token_login,
    handle_wmoauth,
    load_user,
)
from fatcat_web.cors import crossdomain
from fatcat_web.entity_helpers import (
    editgroup_get_diffs,
    generic_get_editgroup_entity,
    generic_get_entity,
    generic_get_entity_revision,
)
from fatcat_web.forms import SavePaperNowForm
from fatcat_web.graphics import (
    ia_coverage_histogram,
    preservation_by_date_histogram,
    preservation_by_volume_histogram,
    preservation_by_year_histogram,
)
from fatcat_web.kafka import kafka_pixy_produce
from fatcat_web.search import (
    GenericQuery,
    ReleaseQuery,
    do_container_search,
    do_release_search,
    get_elastic_container_browse_year_volume_issue,
    get_elastic_container_histogram_legacy,
    get_elastic_container_preservation_by_volume,
    get_elastic_container_random_releases,
    get_elastic_container_stats,
    get_elastic_entity_stats,
    get_elastic_preservation_by_date,
    get_elastic_preservation_by_type,
    get_elastic_preservation_by_year,
    get_elastic_search_coverage,
)

### Generic Entity Views ####################################################


@app.route("/container/<string(length=26):ident>/history", methods=["GET"])
def container_history(ident: str) -> AnyResponse:
    try:
        entity = api.get_container(ident)
        history = api.get_container_history(ident)
    except ApiException as ae:
        app.log.info(ae)
        abort(ae.status)
    return render_template(
        "entity_history.html", entity_type="container", entity=entity, history=history
    )


@app.route("/creator/<string(length=26):ident>/history", methods=["GET"])
def creator_history(ident: str) -> AnyResponse:
    try:
        entity = api.get_creator(ident)
        history = api.get_creator_history(ident)
    except ApiException as ae:
        abort(ae.status)
    return render_template(
        "entity_history.html", entity_type="creator", entity=entity, history=history
    )


@app.route("/file/<string(length=26):ident>/history", methods=["GET"])
def file_history(ident: str) -> AnyResponse:
    try:
        entity = api.get_file(ident)
        history = api.get_file_history(ident)
    except ApiException as ae:
        abort(ae.status)
    return render_template(
        "entity_history.html", entity_type="file", entity=entity, history=history
    )


@app.route("/fileset/<string(length=26):ident>/history", methods=["GET"])
def fileset_history(ident: str) -> AnyResponse:
    try:
        entity = api.get_fileset(ident)
        history = api.get_fileset_history(ident)
    except ApiException as ae:
        abort(ae.status)
    return render_template(
        "entity_history.html", entity_type="fileset", entity=entity, history=history
    )


@app.route("/webcapture/<string(length=26):ident>/history", methods=["GET"])
def webcapture_history(ident: str) -> AnyResponse:
    try:
        entity = api.get_webcapture(ident)
        history = api.get_webcapture_history(ident)
    except ApiException as ae:
        abort(ae.status)
    return render_template(
        "entity_history.html", entity_type="webcapture", entity=entity, history=history
    )


@app.route("/release/<string(length=26):ident>/history", methods=["GET"])
def release_history(ident: str) -> AnyResponse:
    try:
        entity = api.get_release(ident)
        history = api.get_release_history(ident)
    except ApiException as ae:
        abort(ae.status)
    return render_template(
        "entity_history.html", entity_type="release", entity=entity, history=history
    )


@app.route("/work/<string(length=26):ident>/history", methods=["GET"])
def work_history(ident: str) -> AnyResponse:
    try:
        entity = api.get_work(ident)
        history = api.get_work_history(ident)
    except ApiException as ae:
        abort(ae.status)
    return render_template(
        "entity_history.html", entity_type="work", entity=entity, history=history
    )


def generic_lookup_view(
    entity_type: str, lookup_template: str, extid_types: List[str], lookup_lambda: Callable
) -> AnyResponse:
    extid = None
    for key in extid_types:
        if request.args.get(key):
            extid = key
            extid_value = request.args.get(extid)
            if extid_value:
                extid_value = extid_value.strip()
                break
    if extid is None:
        return render_template(lookup_template)
    try:
        resp = lookup_lambda({extid: extid_value})
    except ValueError:
        return make_response(
            render_template(
                lookup_template, lookup_key=extid, lookup_value=extid_value, lookup_error=400
            ),
            400,
        )
    except ApiException as ae:
        if ae.status == 404 or ae.status == 400:
            return make_response(
                render_template(
                    lookup_template,
                    lookup_key=extid,
                    lookup_value=extid_value,
                    lookup_error=ae.status,
                ),
                ae.status,
            )
        else:
            app.log.info(ae)
            raise ae
    return redirect("/{}/{}".format(entity_type, resp.ident))


@app.route("/container/lookup", methods=["GET"])
def container_lookup() -> AnyResponse:
    return generic_lookup_view(
        "container",
        "container_lookup.html",
        ["issn", "issne", "issnp", "issnl", "wikidata_qid"],
        lambda p: api.lookup_container(**p),
    )


@app.route("/creator/lookup", methods=["GET"])
def creator_lookup() -> AnyResponse:
    return generic_lookup_view(
        "creator",
        "creator_lookup.html",
        ["orcid", "wikidata_qid"],
        lambda p: api.lookup_creator(**p),
    )


@app.route("/file/lookup", methods=["GET"])
def file_lookup() -> AnyResponse:
    return generic_lookup_view(
        "file", "file_lookup.html", ["md5", "sha1", "sha256"], lambda p: api.lookup_file(**p)
    )


@app.route("/fileset/lookup", methods=["GET"])
def fileset_lookup() -> AnyResponse:
    abort(404)


@app.route("/webcapture/lookup", methods=["GET"])
def webcapture_lookup() -> AnyResponse:
    abort(404)


@app.route("/release/lookup", methods=["GET"])
def release_lookup() -> AnyResponse:
    return generic_lookup_view(
        "release",
        "release_lookup.html",
        [
            "doi",
            "wikidata_qid",
            "pmid",
            "pmcid",
            "isbn13",
            "jstor",
            "arxiv",
            "core",
            "ark",
            "mag",
            "oai",
            "hdl",
        ],
        lambda p: api.lookup_release(**p),
    )


@app.route("/work/lookup", methods=["GET"])
def work_lookup() -> AnyResponse:
    abort(404)


### More Generic Entity Views ###############################################

GENERIC_ENTITY_FIELDS = ["extra", "edit_extra", "revision", "redirect", "state", "ident"]


def generic_entity_view(entity_type: str, ident: str, view_template: str) -> AnyResponse:
    entity = generic_get_entity(entity_type, ident)

    if entity.state == "redirect":
        return redirect("/{}/{}".format(entity_type, entity.redirect))
    elif entity.state == "deleted":
        return render_template("deleted_entity.html", entity_type=entity_type, entity=entity)

    metadata = entity.to_dict()
    for k in GENERIC_ENTITY_FIELDS:
        metadata.pop(k)
    entity._metadata = metadata

    if view_template == "container_view.html":
        entity._stats = get_elastic_container_stats(entity.ident, issnl=entity.issnl)
        entity._random_releases = get_elastic_container_random_releases(entity.ident)
    if view_template == "container_view_coverage.html":
        entity._stats = get_elastic_container_stats(entity.ident, issnl=entity.issnl)
        entity._type_preservation = get_elastic_preservation_by_type(
            ReleaseQuery(container_id=ident),
        )

    return render_template(
        view_template, entity_type=entity_type, entity=entity, editgroup_id=None
    )


def generic_entity_revision_view(
    entity_type: str, revision_id: str, view_template: str
) -> AnyResponse:
    entity = generic_get_entity_revision(entity_type, revision_id)

    metadata = entity.to_dict()
    for k in GENERIC_ENTITY_FIELDS:
        metadata.pop(k)
    entity._metadata = metadata

    return render_template(
        view_template, entity_type=entity_type, entity=entity, editgroup_id=None
    )


def generic_editgroup_entity_view(
    editgroup_id: Optional[str], entity_type: str, ident: str, view_template: str
) -> AnyResponse:
    try:
        editgroup = api.get_editgroup(editgroup_id)
    except ApiException as ae:
        abort(ae.status)

    entity, edit = generic_get_editgroup_entity(editgroup, entity_type, ident)

    if entity.revision is None or entity.state == "deleted":
        return render_template(
            "deleted_entity.html", entity=entity, entity_type=entity_type, editgroup=editgroup
        )

    metadata = entity.to_dict()
    for k in GENERIC_ENTITY_FIELDS:
        metadata.pop(k)
    entity._metadata = metadata

    return render_template(
        view_template, entity_type=entity_type, entity=entity, editgroup=editgroup
    )


@app.route("/container/<string(length=26):ident>", methods=["GET"])
def container_view(ident: str) -> AnyResponse:
    return generic_entity_view("container", ident, "container_view.html")


@app.route("/container_<string(length=26):ident>", methods=["GET"])
def container_underscore_view(ident: str) -> AnyResponse:
    return redirect("/container/{}".format(ident))


@app.route("/container/<string(length=26):ident>/coverage", methods=["GET"])
def container_view_coverage(ident: str) -> AnyResponse:
    # note: there is a special hack to add entity._type_preservation for this endpoint
    return generic_entity_view("container", ident, "container_view_coverage.html")


@app.route("/container/<string(length=26):ident>/browse", methods=["GET"])
def container_view_browse(ident: str) -> AnyResponse:
    entity = generic_get_entity("container", ident)

    if entity.state == "redirect":
        return redirect(f"/container/{entity.redirect}")
    elif entity.state == "deleted":
        return render_template("deleted_entity.html", entity_type="container", entity=entity)

    query_sort: Optional[List[str]]
    if request.args.get("year") and "volume" in request.args and "issue" in request.args:
        # year, volume, issue specified; browse-by-page
        year = int(request.args["year"])
        volume = request.args.get("volume", "")
        issue = request.args.get("issue", "")
        if volume:
            volume = f'volume:"{volume}"'
        else:
            volume = "!volume:*"
        if issue:
            issue = f'issue:"{issue}"'
        else:
            issue = "!issue:*"
        query_string = f"year:{year} {volume} {issue}"
        query_sort = ["first_page", "pages", "release_date"]
    elif request.args.get("year") and "volume" in request.args:
        # year, volume specified (no issue); browse-by-page
        year = int(request.args["year"])
        volume = request.args.get("volume", "")
        if volume:
            volume = f'volume:"{volume}"'
        else:
            volume = "!volume:*"
        query_string = f"year:{year} {volume}"
        query_sort = ["issue", "first_page", "pages", "release_date"]
    elif request.args.get("year"):
        # year specified, not anything else; browse-by-date
        year = int(request.args["year"])
        query_string = f"year:{year}"
        query_sort = ["release_date"]
    elif request.args.get("volume"):
        # volume specified, not anything else; browse-by-page
        query_string = f'volume:{request.args["volume"]}'
        query_sort = ["issue", "first_page", "pages", "release_date"]
    else:
        entity._browse_year_volume_issue = get_elastic_container_browse_year_volume_issue(
            entity.ident
        )
        # print(entity._browse_year_volume_issue)
        return render_template(
            "container_view_browse.html",
            entity_type="container",
            entity=entity,
            editgroup_id=None,
        )

    # print(query_string)
    query = ReleaseQuery(
        q=query_string,
        limit=300,
        offset=0,
        container_id=ident,
        fulltext_only=False,
        recent=False,
        exclude_stubs=True,
        sort=query_sort,
    )

    try:
        found = do_release_search(query)
    except FatcatSearchError as fse:
        return (
            render_template(
                "container_view_search.html",
                query=query,
                es_error=fse,
                entity_type="container",
                entity=entity,
                editgroup_id=None,
            ),
            fse.status_code,
        )

    # HACK: re-sort by first page *numerically*
    if found.results and query_sort and "first_page" in query_sort:
        for doc in found.results:
            if doc.get("first_page") and doc["first_page"].isdigit():
                doc["first_page"] = int(doc["first_page"])
        found.results = sorted(found.results, key=lambda d: d.get("first_page") or 99999999)

    return render_template(
        "container_view_browse.html",
        query=query,
        releases_found=found,
        entity_type="container",
        entity=entity,
        editgroup_id=None,
    )


@app.route("/container/<string(length=26):ident>/metadata", methods=["GET"])
def container_view_metadata(ident: str) -> AnyResponse:
    return generic_entity_view("container", ident, "entity_view_metadata.html")


@app.route("/container/rev/<uuid:revision_id>", methods=["GET"])
def container_revision_view(revision_id: str) -> AnyResponse:
    return generic_entity_revision_view("container", str(revision_id), "container_view.html")


@app.route("/container/rev/<uuid:revision_id>/metadata", methods=["GET"])
def container_revision_view_metadata(revision_id: str) -> AnyResponse:
    return generic_entity_revision_view(
        "container", str(revision_id), "entity_view_metadata.html"
    )


@app.route("/editgroup/<editgroup_id>/container/<string(length=26):ident>", methods=["GET"])
def container_editgroup_view(editgroup_id: str, ident: str) -> AnyResponse:
    return generic_editgroup_entity_view(
        editgroup_id, "container", ident, "container_view.html"
    )


@app.route(
    "/editgroup/<editgroup_id>/container/<string(length=26):ident>/metadata", methods=["GET"]
)
def container_editgroup_view_metadata(editgroup_id: str, ident: str) -> AnyResponse:
    return generic_editgroup_entity_view(
        editgroup_id, "container", ident, "entity_view_metadata.html"
    )


@app.route("/creator/<string(length=26):ident>", methods=["GET"])
def creator_view(ident: str) -> AnyResponse:
    return generic_entity_view("creator", ident, "creator_view.html")


@app.route("/creator_<string(length=26):ident>", methods=["GET"])
def creator_underscore_view(ident: str) -> AnyResponse:
    return redirect("/creator/{}".format(ident))


@app.route("/creator/<string(length=26):ident>/metadata", methods=["GET"])
def creator_view_metadata(ident: str) -> AnyResponse:
    return generic_entity_view("creator", ident, "entity_view_metadata.html")


@app.route("/creator/rev/<uuid:revision_id>", methods=["GET"])
def creator_revision_view(revision_id: str) -> AnyResponse:
    return generic_entity_revision_view("creator", str(revision_id), "creator_view.html")


@app.route("/creator/rev/<uuid:revision_id>/metadata", methods=["GET"])
def creator_revision_view_metadata(revision_id: str) -> AnyResponse:
    return generic_entity_revision_view(
        "creator", str(revision_id), "entity_view_metadata.html"
    )


@app.route("/editgroup/<editgroup_id>/creator/<string(length=26):ident>", methods=["GET"])
def creator_editgroup_view(editgroup_id: str, ident: str) -> AnyResponse:
    return generic_editgroup_entity_view(editgroup_id, "creator", ident, "creator_view.html")


@app.route(
    "/editgroup/<editgroup_id>/creator/<string(length=26):ident>/metadata", methods=["GET"]
)
def creator_editgroup_view_metadata(editgroup_id: str, ident: str) -> AnyResponse:
    return generic_editgroup_entity_view(
        editgroup_id, "creator", ident, "entity_view_metadata.html"
    )


@app.route("/file/<string(length=26):ident>", methods=["GET"])
def file_view(ident: str) -> AnyResponse:
    return generic_entity_view("file", ident, "file_view.html")


@app.route("/file_<string(length=26):ident>", methods=["GET"])
def file_underscore_view(ident: str) -> AnyResponse:
    return redirect("/file/{}".format(ident))


@app.route("/file/<string(length=26):ident>/metadata", methods=["GET"])
def file_view_metadata(ident: str) -> AnyResponse:
    return generic_entity_view("file", ident, "entity_view_metadata.html")


@app.route("/file/rev/<uuid:revision_id>", methods=["GET"])
def file_revision_view(revision_id: str) -> AnyResponse:
    return generic_entity_revision_view("file", str(revision_id), "file_view.html")


@app.route("/file/rev/<uuid:revision_id>/metadata", methods=["GET"])
def file_revision_view_metadata(revision_id: str) -> AnyResponse:
    return generic_entity_revision_view("file", str(revision_id), "entity_view_metadata.html")


@app.route("/editgroup/<editgroup_id>/file/<string(length=26):ident>", methods=["GET"])
def file_editgroup_view(editgroup_id: str, ident: str) -> AnyResponse:
    return generic_editgroup_entity_view(editgroup_id, "file", ident, "file_view.html")


@app.route("/editgroup/<editgroup_id>/file/<string(length=26):ident>/metadata", methods=["GET"])
def file_editgroup_view_metadata(editgroup_id: str, ident: str) -> AnyResponse:
    return generic_editgroup_entity_view(
        editgroup_id, "file", ident, "entity_view_metadata.html"
    )


@app.route("/fileset/<string(length=26):ident>", methods=["GET"])
def fileset_view(ident: str) -> AnyResponse:
    return generic_entity_view("fileset", ident, "fileset_view.html")


@app.route("/fileset_<string(length=26):ident>", methods=["GET"])
def fileset_underscore_view(ident: str) -> AnyResponse:
    return redirect("/fileset/{}".format(ident))


@app.route("/fileset/<string(length=26):ident>/metadata", methods=["GET"])
def fileset_view_metadata(ident: str) -> AnyResponse:
    return generic_entity_view("fileset", ident, "entity_view_metadata.html")


@app.route("/fileset/rev/<uuid:revision_id>", methods=["GET"])
def fileset_revision_view(revision_id: str) -> AnyResponse:
    return generic_entity_revision_view("fileset", str(revision_id), "fileset_view.html")


@app.route("/fileset/rev/<uuid:revision_id>/metadata", methods=["GET"])
def fileset_revision_view_metadata(revision_id: str) -> AnyResponse:
    return generic_entity_revision_view(
        "fileset", str(revision_id), "entity_view_metadata.html"
    )


@app.route("/editgroup/<editgroup_id>/fileset/<string(length=26):ident>", methods=["GET"])
def fileset_editgroup_view(editgroup_id: str, ident: str) -> AnyResponse:
    return generic_editgroup_entity_view(editgroup_id, "fileset", ident, "fileset_view.html")


@app.route(
    "/editgroup/<editgroup_id>/fileset/<string(length=26):ident>/metadata", methods=["GET"]
)
def fileset_editgroup_view_metadata(editgroup_id: str, ident: str) -> AnyResponse:
    return generic_editgroup_entity_view(
        editgroup_id, "fileset", ident, "entity_view_metadata.html"
    )


@app.route("/webcapture/<string(length=26):ident>", methods=["GET"])
def webcapture_view(ident: str) -> AnyResponse:
    return generic_entity_view("webcapture", ident, "webcapture_view.html")


@app.route("/webcapture_<string(length=26):ident>", methods=["GET"])
def webcapture_underscore_view(ident: str) -> AnyResponse:
    return redirect("/webcapture/{}".format(ident))


@app.route("/webcapture/<string(length=26):ident>/metadata", methods=["GET"])
def webcapture_view_metadata(ident: str) -> AnyResponse:
    return generic_entity_view("webcapture", ident, "entity_view_metadata.html")


@app.route("/webcapture/rev/<uuid:revision_id>", methods=["GET"])
def webcapture_revision_view(revision_id: str) -> AnyResponse:
    return generic_entity_revision_view("webcapture", str(revision_id), "webcapture_view.html")


@app.route("/webcapture/rev/<uuid:revision_id>/metadata", methods=["GET"])
def webcapture_revision_view_metadata(revision_id: str) -> AnyResponse:
    return generic_entity_revision_view(
        "webcapture", str(revision_id), "entity_view_metadata.html"
    )


@app.route("/editgroup/<editgroup_id>/webcapture/<string(length=26):ident>", methods=["GET"])
def webcapture_editgroup_view(editgroup_id: str, ident: str) -> AnyResponse:
    return generic_editgroup_entity_view(
        editgroup_id, "webcapture", ident, "webcapture_view.html"
    )


@app.route(
    "/editgroup/<editgroup_id>/webcapture/<string(length=26):ident>/metadata", methods=["GET"]
)
def webcapture_editgroup_view_metadata(editgroup_id: str, ident: str) -> AnyResponse:
    return generic_editgroup_entity_view(
        editgroup_id, "webcapture", ident, "entity_view_metadata.html"
    )


@app.route("/release/<string(length=26):ident>", methods=["GET"])
def release_view(ident: str) -> AnyResponse:
    return generic_entity_view("release", ident, "release_view.html")


@app.route("/release_<string(length=26):ident>", methods=["GET"])
def release_underscore_view(ident: str) -> AnyResponse:
    return redirect("/release/{}".format(ident))


@app.route("/release/<string(length=26):ident>/contribs", methods=["GET"])
def release_view_contribs(ident: str) -> AnyResponse:
    return generic_entity_view("release", ident, "release_view_contribs.html")


@app.route("/release/<string(length=26):ident>/references", methods=["GET"])
def release_view_references(ident: str) -> AnyResponse:
    return generic_entity_view("release", ident, "release_view_references.html")


@app.route("/release/<string(length=26):ident>/metadata", methods=["GET"])
def release_view_metadata(ident: str) -> AnyResponse:
    return generic_entity_view("release", ident, "entity_view_metadata.html")


@app.route("/release/rev/<uuid:revision_id>", methods=["GET"])
def release_revision_view(revision_id: str) -> AnyResponse:
    return generic_entity_revision_view("release", str(revision_id), "release_view.html")


@app.route("/release/rev/<uuid:revision_id>/contribs", methods=["GET"])
def release_revision_view_contribs(revision_id: str) -> AnyResponse:
    return generic_entity_revision_view(
        "release", str(revision_id), "release_view_contribs.html"
    )


@app.route("/release/rev/<uuid:revision_id>/references", methods=["GET"])
def release_revision_view_references(revision_id: str) -> AnyResponse:
    return generic_entity_revision_view(
        "release", str(revision_id), "release_view_references.html"
    )


@app.route("/release/rev/<uuid:revision_id>/metadata", methods=["GET"])
def release_revision_view_metadata(revision_id: str) -> AnyResponse:
    return generic_entity_revision_view(
        "release", str(revision_id), "entity_view_metadata.html"
    )


@app.route("/editgroup/<editgroup_id>/release/<string(length=26):ident>", methods=["GET"])
def release_editgroup_view(editgroup_id: str, ident: str) -> AnyResponse:
    return generic_editgroup_entity_view(editgroup_id, "release", ident, "release_view.html")


@app.route(
    "/editgroup/<editgroup_id>/release/<string(length=26):ident>/contribs", methods=["GET"]
)
def release_editgroup_view_contribs(editgroup_id: str, ident: str) -> AnyResponse:
    return generic_editgroup_entity_view(
        editgroup_id, "release", ident, "release_view_contribs.html"
    )


@app.route(
    "/editgroup/<editgroup_id>/release/<string(length=26):ident>/references", methods=["GET"]
)
def release_editgroup_view_references(editgroup_id: str, ident: str) -> AnyResponse:
    return generic_editgroup_entity_view(
        editgroup_id, "release", ident, "release_view_references.html"
    )


@app.route(
    "/editgroup/<editgroup_id>/release/<string(length=26):ident>/metadata", methods=["GET"]
)
def release_editgroup_view_metadata(editgroup_id: str, ident: str) -> AnyResponse:
    return generic_editgroup_entity_view(
        editgroup_id, "release", ident, "entity_view_metadata.html"
    )


@app.route("/work/<string(length=26):ident>", methods=["GET"])
def work_view(ident: str) -> AnyResponse:
    return generic_entity_view("work", ident, "work_view.html")


@app.route("/work_<string(length=26):ident>", methods=["GET"])
def work_underscore_view(ident: str) -> AnyResponse:
    return redirect("/work/{}".format(ident))


@app.route("/work/<string(length=26):ident>/metadata", methods=["GET"])
def work_view_metadata(ident: str) -> AnyResponse:
    return generic_entity_view("work", ident, "entity_view_metadata.html")


@app.route("/work/rev/<uuid:revision_id>", methods=["GET"])
def work_revision_view(revision_id: str) -> AnyResponse:
    return generic_entity_revision_view("work", str(revision_id), "work_view.html")


@app.route("/work/rev/<uuid:revision_id>/metadata", methods=["GET"])
def work_revision_view_metadata(revision_id: str) -> AnyResponse:
    return generic_entity_revision_view("work", str(revision_id), "entity_view_metadata.html")


@app.route("/editgroup/<editgroup_id>/work/<string(length=26):ident>", methods=["GET"])
def work_editgroup_view(editgroup_id: str, ident: str) -> AnyResponse:
    return generic_editgroup_entity_view(editgroup_id, "work", ident, "work_view.html")


@app.route("/editgroup/<editgroup_id>/work/<string(length=26):ident>/metadata", methods=["GET"])
def work_editgroup_view_metadata(editgroup_id: str, ident: str) -> AnyResponse:
    return generic_editgroup_entity_view(
        editgroup_id, "work", ident, "entity_view_metadata.html"
    )


### Views ###################################################################


@app.route("/editgroup/<string(length=26):ident>", methods=["GET"])
def editgroup_view(ident: str) -> AnyResponse:
    try:
        eg = api.get_editgroup(str(ident))
        eg.editor = api.get_editor(eg.editor_id)
        eg.annotations = api.get_editgroup_annotations(eg.editgroup_id, expand="editors")
    except ApiException as ae:
        abort(ae.status)
    # TODO: idomatic check for login?
    auth_to = dict(
        submit=False,
        accept=False,
        edit=False,
        annotate=False,
    )
    if session.get("editor"):
        user = load_user(session["editor"]["editor_id"])
        auth_to["annotate"] = True
        if user.is_admin or user.editor_id == eg.editor_id:
            auth_to["submit"] = True
            auth_to["edit"] = True
        if user.is_admin:
            auth_to["accept"] = True
    return render_template("editgroup_view.html", editgroup=eg, auth_to=auth_to)


@app.route("/editgroup_<string(length=26):ident>", methods=["GET"])
def editgroup_underscore_view(ident: str) -> AnyResponse:
    return redirect(f"/editgroup/{ident}")


@app.route("/editgroup/<string(length=26):ident>/diff", methods=["GET"])
def editgroup_diff_view(ident: str) -> AnyResponse:
    try:
        eg = api.get_editgroup(str(ident))
        eg.editor = api.get_editor(eg.editor_id)
        eg.annotations = api.get_editgroup_annotations(eg.editgroup_id, expand="editors")
    except ApiException as ae:
        abort(ae.status)
    # TODO: idomatic check for login?
    auth_to = dict(
        submit=False,
        accept=False,
        edit=False,
        annotate=False,
    )
    if session.get("editor"):
        user = load_user(session["editor"]["editor_id"])
        auth_to["annotate"] = True
        if user.is_admin or user.editor_id == eg.editor_id:
            auth_to["submit"] = True
            auth_to["edit"] = True
        if user.is_admin:
            auth_to["accept"] = True
    diffs = editgroup_get_diffs(eg)
    return render_template(
        "editgroup_diff.html", editgroup=eg, auth_to=auth_to, editgroup_diffs=diffs
    )


@app.route("/editgroup/<string(length=26):ident>/annotation", methods=["POST"])
@login_required
def editgroup_create_annotation(ident: str) -> AnyResponse:
    if not app.testing:
        app.csrf.protect()
    comment_markdown = request.form.get("comment_markdown")
    if not comment_markdown:
        app.log.info("empty comment field")
        abort(400)
    # on behalf of user...
    user_api = auth_api(session["api_token"])
    try:
        eg = user_api.get_editgroup(str(ident))
        if eg.changelog_index:
            abort(400, "Editgroup already accepted")
        ega = EditgroupAnnotation(
            comment_markdown=comment_markdown,
            extra=None,
        )
        user_api.create_editgroup_annotation(eg.editgroup_id, ega)
    except ApiException as ae:
        app.log.info(ae)
        raise ae
    return redirect("/editgroup/{}".format(ident))


@app.route("/editgroup/<string(length=26):ident>/accept", methods=["POST"])
@login_required
def editgroup_accept(ident: str) -> AnyResponse:
    if not app.testing:
        app.csrf.protect()
    # on behalf of user...
    user_api = auth_api(session["api_token"])
    try:
        eg = user_api.get_editgroup(str(ident))
        if eg.changelog_index:
            abort(400, "Editgroup already accepted")
        user_api.accept_editgroup(str(ident))
    except ApiException as ae:
        app.log.info(ae)
        abort(ae.status)
    return redirect("/editgroup/{}".format(ident))


@app.route("/editgroup/<string(length=26):ident>/unsubmit", methods=["POST"])
@login_required
def editgroup_unsubmit(ident: str) -> AnyResponse:
    if not app.testing:
        app.csrf.protect()
    # on behalf of user...
    user_api = auth_api(session["api_token"])
    try:
        eg = user_api.get_editgroup(str(ident))
        if eg.changelog_index:
            abort(400, "Editgroup already accepted")
        user_api.update_editgroup(eg.editgroup_id, eg, submit=False)
    except ApiException as ae:
        app.log.info(ae)
        abort(ae.status)
    return redirect("/editgroup/{}".format(ident))


@app.route("/editgroup/<string(length=26):ident>/submit", methods=["POST"])
@login_required
def editgroup_submit(ident: str) -> AnyResponse:
    if not app.testing:
        app.csrf.protect()
    # on behalf of user...
    user_api = auth_api(session["api_token"])
    try:
        eg = user_api.get_editgroup(str(ident))
        if eg.changelog_index:
            abort(400, "Editgroup already accepted")
        user_api.update_editgroup(eg.editgroup_id, eg, submit=True)
    except ApiException as ae:
        app.log.info(ae)
        abort(ae.status)
    return redirect("/editgroup/{}".format(ident))


@app.route("/editor/<string(length=26):ident>", methods=["GET"])
def editor_view(ident: str) -> AnyResponse:
    try:
        entity = api.get_editor(ident)
    except ApiException as ae:
        abort(ae.status)
    return render_template("editor_view.html", editor=entity)


@app.route("/editor_<string(length=26):ident>", methods=["GET"])
def editor(ident: str) -> AnyResponse:
    return redirect(f"/editor/{ident}")


@app.route("/editor/<string(length=26):ident>/editgroups", methods=["GET"])
def editor_editgroups(ident: str) -> AnyResponse:
    try:
        editor = api.get_editor(ident)
        editgroups = api.get_editor_editgroups(ident, limit=50)
        # cheaper than API-side expand?
        for eg in editgroups:
            eg.editor = editor
    except ApiException as ae:
        abort(ae.status)
    return render_template("editor_editgroups.html", editor=editor, editgroups=editgroups)


@app.route("/editor/<string(length=26):ident>/annotations", methods=["GET"])
def editor_annotations(ident: str) -> AnyResponse:
    try:
        editor = api.get_editor(ident)
        annotations = api.get_editor_annotations(ident, limit=50)
    except ApiException as ae:
        abort(ae.status)
    return render_template("editor_annotations.html", editor=editor, annotations=annotations)


@app.route("/u/<string:username>", methods=["GET", "HEAD"])
def editor_username_redirect(username: str) -> AnyResponse:
    try:
        editor = api.lookup_editor(username=username)
    except ApiException as ae:
        abort(ae.status)
    return redirect(f"/editor/{editor.editor_id}")


@app.route("/changelog", methods=["GET"])
def changelog_view() -> AnyResponse:
    try:
        # limit = int(request.args.get('limit', 10))
        entries = api.get_changelog()  # TODO: expand="editors"
    except ApiException as ae:
        abort(ae.status)
    return render_template("changelog.html", entries=entries)


@app.route("/changelog/<int:index>", methods=["GET"])
def changelog_entry_view(index: int) -> AnyResponse:
    try:
        entry = api.get_changelog_entry(int(index))
        entry.editgroup.editor = api.get_editor(entry.editgroup.editor_id)
        entry.editgroup.annotations = api.get_editgroup_annotations(
            entry.editgroup_id, expand="editors"
        )
    except ApiException as ae:
        abort(ae.status)
    return render_template("changelog_view.html", entry=entry, editgroup=entry.editgroup)


@app.route("/reviewable", methods=["GET"])
def reviewable_view() -> AnyResponse:
    try:
        # limit = int(request.args.get('limit', 10))
        entries = api.get_editgroups_reviewable(expand="editors")
    except ApiException as ae:
        abort(ae.status)
    return render_template("editgroup_reviewable.html", entries=entries)


@app.route("/release/<string(length=26):ident>/save", methods=["GET", "POST"])
def release_save(ident: str) -> AnyResponse:

    form = SavePaperNowForm()

    # lookup release ident, ensure it exists
    try:
        release = api.get_release(ident)
    except ApiException as ae:
        abort(ae.status)

    if not Config.KAFKA_PIXY_ENDPOINT:
        return (
            render_template(
                "release_save.html", entity=release, form=form, spn_status="not-configured"
            ),
            501,
        )

    if form.is_submitted():
        if form.validate_on_submit():
            # got a valid spn request! try to send to kafka-pixy
            msg = form.to_ingest_request(release, ingest_request_source="savepapernow-web")
            try:
                kafka_pixy_produce(
                    Config.KAFKA_SAVEPAPERNOW_TOPIC,
                    json.dumps(msg, sort_keys=True),
                )
            except Exception:
                return (
                    render_template(
                        "release_save.html", entity=release, form=form, spn_status="kafka-error"
                    ),
                    500,
                )
            return (
                render_template(
                    "release_save.html", entity=release, form=form, spn_status="success"
                ),
                200,
            )
        elif form.errors:
            return render_template("release_save.html", entity=release, form=form), 400

    # form was not submitted; populate defaults
    if release.release_stage:
        form.release_stage.data = release.release_stage
    if release.ext_ids.doi:
        form.base_url.data = "https://doi.org/{}".format(release.ext_ids.doi)
    elif release.ext_ids.arxiv:
        form.base_url.data = "https://arxiv.org/pdf/{}.pdf".format(release.ext_ids.arxiv)
    elif release.ext_ids.pmcid:
        form.base_url.data = (
            "https://europepmc.org/backend/ptpmcrender.fcgi?accid={}&blobtype=pdf".format(
                release.ext_ids.pmcid
            )
        )
    elif release.ext_ids.hdl:
        form.base_url.data = "https://hdl.handle.net/{}".format(release.ext_ids.hdl)
    return render_template("release_save.html", entity=release, form=form), 200


### Search ##################################################################


@app.route("/search", methods=["GET", "POST"])
def generic_search() -> AnyResponse:
    if "q" not in request.args.keys():
        return redirect("/release/search")
    query = request.args["q"].strip()

    if len(query.split()) != 1:
        # multi-term? must be a real search
        return redirect(url_for("release_search", q=query, generic=1))

    if clean_doi(query):
        return redirect(url_for("release_lookup", doi=clean_doi(query)))
    if clean_pmcid(query):
        return redirect(url_for("release_lookup", pmcid=clean_pmcid(query)))
    if clean_sha1(query):
        return redirect(url_for("file_lookup", sha1=clean_sha1(query)))
    if clean_sha256(query):
        return redirect(url_for("file_lookup", sha256=clean_sha256(query)))
    if clean_issn(query):
        return redirect(url_for("container_lookup", issnl=clean_issn(query)))
    if clean_isbn13(query):
        return redirect(url_for("release_lookup", isbn13=clean_isbn13(query)))
    if clean_arxiv_id(query):
        return redirect(url_for("release_lookup", arxiv=clean_arxiv_id(query)))
    if clean_orcid(query):
        return redirect(url_for("creator_lookup", orcid=clean_orcid(query)))

    return redirect(url_for("release_search", q=query, generic=1))


@app.route("/release/search", methods=["GET", "POST"])
def release_search() -> AnyResponse:

    if "q" not in request.args.keys():
        return render_template("release_search.html", query=ReleaseQuery(), found=None)

    # if this is a "generic" query (eg, from front page or top-of page bar),
    # and the query is not all filters/paramters (aka, there is an actual
    # term/phrase in the query), then also try querying containers, and display
    # a "were you looking for" box with a single result
    container_found = None
    filter_only_query = True
    for p in request.args.get("q", "").split():
        if ":" not in p:
            filter_only_query = False
            break
    if request.args.get("generic") and not filter_only_query:
        container_query = GenericQuery.from_args(request.args)
        container_query.limit = 1
        try:
            container_found = do_container_search(container_query)
        except Exception:
            pass

    query = ReleaseQuery.from_args(request.args)
    try:
        found = do_release_search(query)
    except FatcatSearchError as fse:
        return (
            render_template("release_search.html", query=query, es_error=fse),
            fse.status_code,
        )
    return render_template(
        "release_search.html", query=query, found=found, container_found=container_found
    )


@app.route("/container/search", methods=["GET", "POST"])
def container_search() -> AnyResponse:

    if "q" not in request.args.keys():
        return render_template("container_search.html", query=GenericQuery(), found=None)

    query = GenericQuery.from_args(request.args)
    try:
        found = do_container_search(query)
    except FatcatSearchError as fse:
        return (
            render_template("container_search.html", query=query, es_error=fse),
            fse.status_code,
        )
    return render_template("container_search.html", query=query, found=found)


@app.route("/coverage/search", methods=["GET", "POST"])
def coverage_search() -> AnyResponse:

    if "q" not in request.args.keys():
        return render_template(
            "coverage_search.html",
            query=ReleaseQuery(),
            coverage_stats=None,
            coverage_type_preservation=None,
            year_histogram_svg=None,
            date_histogram_svg=None,
        )

    query = ReleaseQuery.from_args(request.args)
    try:
        coverage_stats = get_elastic_search_coverage(query)
    except FatcatSearchError as fse:
        return (
            render_template(
                "coverage_search.html",
                query=query,
                coverage_stats=None,
                coverage_type_preservation=None,
                year_histogram_svg=None,
                date_histogram_svg=None,
                es_error=fse,
            ),
            fse.status_code,
        )
    year_histogram_svg = None
    date_histogram_svg = None
    coverage_type_preservation = None
    if coverage_stats["total"] > 1:
        coverage_type_preservation = get_elastic_preservation_by_type(query)
        if query.recent:
            date_histogram = get_elastic_preservation_by_date(query)
            date_histogram_svg = preservation_by_date_histogram(
                date_histogram,
                merge_shadows=Config.FATCAT_MERGE_SHADOW_PRESERVATION,
            ).render_data_uri()
        else:
            year_histogram = get_elastic_preservation_by_year(query)
            year_histogram_svg = preservation_by_year_histogram(
                year_histogram,
                merge_shadows=Config.FATCAT_MERGE_SHADOW_PRESERVATION,
            ).render_data_uri()
    return render_template(
        "coverage_search.html",
        query=query,
        coverage_stats=coverage_stats,
        coverage_type_preservation=coverage_type_preservation,
        year_histogram_svg=year_histogram_svg,
        date_histogram_svg=date_histogram_svg,
    )


@app.route("/container/<string(length=26):ident>/search", methods=["GET", "POST"])
def container_view_search(ident: str) -> AnyResponse:
    entity = generic_get_entity("container", ident)

    if entity.state == "redirect":
        return redirect(f"/container/{entity.redirect}")
    elif entity.state == "deleted":
        return render_template("deleted_entity.html", entity_type="container", entity=entity)

    if "q" not in request.args.keys():
        return render_template(
            "container_view_search.html",
            query=ReleaseQuery(),
            found=None,
            entity_type="container",
            entity=entity,
            editgroup_id=None,
        )

    query = ReleaseQuery.from_args(request.args)
    query.container_id = ident
    try:
        found = do_release_search(query)
    except FatcatSearchError as fse:
        return (
            render_template(
                "container_view_search.html",
                query=query,
                es_error=fse,
                entity_type="container",
                entity=entity,
                editgroup_id=None,
            ),
            fse.status_code,
        )

    return render_template(
        "container_view_search.html",
        query=query,
        found=found,
        entity_type="container",
        entity=entity,
        editgroup_id=None,
    )


def get_changelog_stats() -> Dict[str, Any]:
    stats = {}
    latest_changelog = api.get_changelog(limit=1)[0]
    stats["changelog"] = {
        "latest": {
            "index": latest_changelog.index,
            "timestamp": latest_changelog.timestamp.isoformat(),
        }
    }
    return stats


@app.route("/stats", methods=["GET"])
def stats_page() -> AnyResponse:
    try:
        stats = get_elastic_entity_stats()
        stats.update(get_changelog_stats())
    except Exception as ae:
        app.log.error(ae)
        abort(503)
    return render_template("stats.html", stats=stats)


### Pseudo-APIs #############################################################


@app.route("/stats.json", methods=["GET", "OPTIONS"])
@crossdomain(origin="*", headers=["access-control-allow-origin", "Content-Type"])
def stats_json() -> AnyResponse:
    try:
        stats = get_elastic_entity_stats()
        stats.update(get_changelog_stats())
    except Exception as ae:
        app.log.error(ae)
        abort(503)
    return jsonify(stats)


@app.route("/container/issnl/<issnl>/stats.json", methods=["GET", "OPTIONS"])
@crossdomain(origin="*", headers=["access-control-allow-origin", "Content-Type"])
def container_issnl_stats(issnl: str) -> AnyResponse:
    if not (len(issnl) == 9 and issnl[4] == "-"):
        abort(400, "Not a valid ISSN-L: {}".format(issnl))
    try:
        container = api.lookup_container(issnl=issnl)
    except ApiException as ae:
        raise ae
    try:
        stats = get_elastic_container_stats(container.ident, issnl=container.issnl)
    except (ValueError, IOError) as ae:
        app.log.error(ae)
        abort(503)
    return jsonify(stats)


@app.route("/container/<string(length=26):ident>/stats.json", methods=["GET", "OPTIONS"])
@crossdomain(origin="*", headers=["access-control-allow-origin", "Content-Type"])
def container_ident_stats(ident: str) -> AnyResponse:
    try:
        container = api.get_container(ident)
    except ApiException as ae:
        abort(ae.status)
    try:
        stats = get_elastic_container_stats(container.ident, issnl=container.issnl)
    except Exception as ae:
        app.log.error(ae)
        abort(503)
    return jsonify(stats)


@app.route(
    "/container/<string(length=26):ident>/ia_coverage_years.json", methods=["GET", "OPTIONS"]
)
@crossdomain(origin="*", headers=["access-control-allow-origin", "Content-Type"])
def container_ident_ia_coverage_years_json(ident: str) -> AnyResponse:
    try:
        container = api.get_container(ident)
    except ApiException as ae:
        abort(ae.status)
    try:
        histogram = get_elastic_container_histogram_legacy(container.ident)
    except Exception as ae:
        app.log.error(ae)
        abort(503)
    histogram_dicts = [dict(year=h[0], in_ia=h[1], count=h[2]) for h in histogram]
    return jsonify({"container_id": ident, "histogram": histogram_dicts})


@app.route(
    "/container/<string(length=26):ident>/ia_coverage_years.svg", methods=["GET", "OPTIONS"]
)
@crossdomain(origin="*", headers=["access-control-allow-origin", "Content-Type"])
def container_ident_ia_coverage_years_svg(ident: str) -> AnyResponse:
    try:
        container = api.get_container(ident)
    except ApiException as ae:
        abort(ae.status)
    try:
        histogram = get_elastic_container_histogram_legacy(container.ident)
    except Exception as ae:
        app.log.error(ae)
        abort(503)
    return ia_coverage_histogram(histogram).render_response()


@app.route(
    "/container/<string(length=26):ident>/preservation_by_year.json", methods=["GET", "OPTIONS"]
)
@crossdomain(origin="*", headers=["access-control-allow-origin", "Content-Type"])
def container_ident_preservation_by_year_json(ident: str) -> AnyResponse:
    try:
        container = api.get_container(ident)
    except ApiException as ae:
        abort(ae.status)
    query = ReleaseQuery(container_id=container.ident, exclude_stubs=True)
    try:
        histogram = get_elastic_preservation_by_year(query)
    except Exception as ae:
        app.log.error(ae)
        abort(503)
    return jsonify({"container_id": ident, "histogram": histogram})


@app.route(
    "/container/<string(length=26):ident>/preservation_by_year.svg", methods=["GET", "OPTIONS"]
)
@crossdomain(origin="*", headers=["access-control-allow-origin", "Content-Type"])
def container_ident_preservation_by_year_svg(ident: str) -> AnyResponse:
    try:
        container = api.get_container(ident)
    except ApiException as ae:
        abort(ae.status)
    query = ReleaseQuery(container_id=container.ident, exclude_stubs=True)
    try:
        histogram = get_elastic_preservation_by_year(query)
    except Exception as ae:
        app.log.error(ae)
        abort(503)
    return preservation_by_year_histogram(
        histogram,
        merge_shadows=Config.FATCAT_MERGE_SHADOW_PRESERVATION,
    ).render_response()


@app.route(
    "/container/<string(length=26):ident>/preservation_by_volume.json",
    methods=["GET", "OPTIONS"],
)
@crossdomain(origin="*", headers=["access-control-allow-origin", "Content-Type"])
def container_ident_preservation_by_volume_json(ident: str) -> AnyResponse:
    try:
        container = api.get_container(ident)
    except ApiException as ae:
        abort(ae.status)
    query = ReleaseQuery(container_id=container.ident, exclude_stubs=True)
    try:
        histogram = get_elastic_container_preservation_by_volume(query)
    except Exception as ae:
        app.log.error(ae)
        abort(503)
    return jsonify({"container_id": ident, "histogram": histogram})


@app.route(
    "/container/<string(length=26):ident>/preservation_by_volume.svg",
    methods=["GET", "OPTIONS"],
)
@crossdomain(origin="*", headers=["access-control-allow-origin", "Content-Type"])
def container_ident_preservation_by_volume_svg(ident: str) -> AnyResponse:
    try:
        container = api.get_container(ident)
    except ApiException as ae:
        abort(ae.status)
    query = ReleaseQuery(container_id=container.ident, exclude_stubs=True)
    try:
        histogram = get_elastic_container_preservation_by_volume(query)
    except Exception as ae:
        app.log.error(ae)
        abort(503)
    return preservation_by_volume_histogram(
        histogram,
        merge_shadows=Config.FATCAT_MERGE_SHADOW_PRESERVATION,
    ).render_response()


@app.route(
    "/container/<string(length=26):ident>/preservation_by_type.json",
    methods=["GET", "OPTIONS"],
)
@crossdomain(origin="*", headers=["access-control-allow-origin", "Content-Type"])
def container_ident_preservation_by_type_json(ident: str) -> AnyResponse:
    try:
        container = api.get_container(ident)
    except ApiException as ae:
        abort(ae.status)
    query = ReleaseQuery(container_id=container.ident)
    try:
        histogram = get_elastic_preservation_by_type(query)
    except Exception as ae:
        app.log.error(ae)
        abort(503)
    return jsonify({"container_id": ident, "histogram": histogram})


@app.route("/release/<string(length=26):ident>.bib", methods=["GET"])
def release_bibtex(ident: str) -> AnyResponse:
    try:
        entity = api.get_release(ident)
    except ApiException as ae:
        raise ae
    csl = release_to_csl(entity)
    bibtex = citeproc_csl(csl, "bibtex")
    return Response(bibtex, mimetype="text/plain")


@app.route("/release/<string(length=26):ident>/citeproc", methods=["GET"])
def release_citeproc(ident: str) -> AnyResponse:
    style = request.args.get("style", "harvard1")
    is_html_arg = request.args.get("html", "false")
    if is_html_arg and is_html_arg.lower() in ("yes", "1", "true", "y", "t"):
        is_html = True
    else:
        is_html = False

    try:
        entity = api.get_release(ident)
    except ApiException as ae:
        raise ae
    try:
        csl = release_to_csl(entity)
    except ValueError as e:
        # "handle" the missing author/surname path, so we don't get exception
        # reports about it. these are not linked to, only show up from bots.
        sentry_sdk.set_level("warning")
        sentry_sdk.capture_exception(e)
        abort(500, e)
    try:
        cite = citeproc_csl(csl, style, is_html)
    except citeproc_styles.StyleNotFoundError as e:
        abort(400, e)
    if is_html:
        return Response(cite)
    elif style == "csl-json":
        return jsonify(json.loads(cite))
    else:
        return Response(cite, mimetype="text/plain")


@app.route("/health.json", methods=["GET", "OPTIONS"])
@crossdomain(origin="*", headers=["access-control-allow-origin", "Content-Type"])
def health_json() -> AnyResponse:
    return jsonify({"ok": True})


### Auth ####################################################################


@app.route("/auth/login")
def login() -> AnyResponse:
    # show the user a list of login options
    if not priv_api:
        app.log.warn(
            "This web interface not configured with credentials to actually allow login (other than via token)"
        )
    return render_template("auth_login.html")


@app.route("/auth/ia/login", methods=["GET", "POST"])
def ia_xauth_login() -> AnyResponse:
    if "email" in request.form and "password" in request.form:
        # if a login attempt...
        return handle_ia_xauth(request.form["email"], request.form["password"])
    # else show form
    return render_template("auth_ia_login.html")


@app.route("/auth/token_login", methods=["GET", "POST"])
def token_login() -> AnyResponse:
    # show the user a list of login options
    if "token" in request.args:
        return handle_token_login(request.args["token"])
    if "token" in request.form:
        return handle_token_login(request.form["token"])
    return render_template("auth_token_login.html")


@app.route("/auth/change_username", methods=["POST"])
@login_required
def change_username() -> AnyResponse:
    if not app.testing:
        app.csrf.protect()
    # show the user a list of login options
    if "username" not in request.form:
        abort(400)
    # on behalf of user...
    user_api = auth_api(session["api_token"])
    try:
        editor = user_api.get_editor(session["editor"]["editor_id"])
        editor.username = request.form["username"]
        editor = user_api.update_editor(editor.editor_id, editor)
    except ApiException as ae:
        app.log.info(ae)
        raise ae
    # update our session
    session["editor"] = editor.to_dict()
    load_user(editor.editor_id)
    return redirect("/auth/account")


@app.route("/auth/create_token", methods=["POST"])
@login_required
def create_auth_token() -> AnyResponse:
    if not app.testing:
        app.csrf.protect()

    duration_seconds = request.form.get("duration_seconds", None)
    if duration_seconds:
        try:
            duration_seconds_int = int(duration_seconds)
            assert duration_seconds_int >= 1
        except (ValueError, AssertionError):
            abort(400, "duration_seconds must be a positive non-zero integer")

    # check user's auth. api_token and editor_id are signed together in session
    # cookie, so if api_token is valid editor_id is assumed to match. If that
    # wasn't true, users could manipulate session cookies and create tokens for
    # any user
    user_api = auth_api(session["api_token"])
    resp = user_api.auth_check()
    assert resp.success

    # generate token using *superuser* privs
    editor_id = session["editor"]["editor_id"]
    try:
        resp = priv_api.create_auth_token(editor_id, duration_seconds=duration_seconds)
    except ApiException as ae:
        app.log.info(ae)
        raise ae
    return render_template("auth_token.html", auth_token=resp.token)


@app.route("/auth/logout")
def logout() -> AnyResponse:
    handle_logout()
    return render_template("auth_logout.html")


@app.route("/auth/account")
@login_required
def auth_account() -> AnyResponse:
    # auth check on account page
    user_api = auth_api(session["api_token"])
    resp = user_api.auth_check()
    assert resp.success
    editor = user_api.get_editor(session["editor"]["editor_id"])
    session["editor"] = editor.to_dict()
    load_user(editor.editor_id)
    return render_template("auth_account.html")


@app.route("/auth/wikipedia/auth")
def wp_oauth_rewrite() -> AnyResponse:
    """
    This is a dirty hack to rewrite '/auth/wikipedia/auth' to '/auth/wikipedia/oauth-callback'
    """
    return redirect(
        (b"/auth/wikipedia/oauth-callback?" + request.query_string).decode("utf-8"),
        307,
    )


@app.route("/auth/wikipedia/finish-login")
def wp_oauth_finish_login() -> AnyResponse:
    wp_username = mwoauth.get_current_user(cached=True)
    assert wp_username
    return handle_wmoauth(wp_username)


### Static Routes ###########################################################


@app.errorhandler(404)
def page_not_found(e: Exception) -> AnyResponse:
    return render_template("404.html"), 404


@app.errorhandler(401)
@app.errorhandler(403)
def page_not_authorized(e: Exception) -> AnyResponse:
    return render_template("403.html"), 403


@app.errorhandler(405)
def page_method_not_allowed(e: Exception) -> AnyResponse:
    return render_template("405.html"), 405


@app.errorhandler(400)
def page_bad_request(e: Exception) -> AnyResponse:
    return render_template("400.html", err=e), 400


@app.errorhandler(409)
def page_edit_conflict(e: Exception) -> AnyResponse:
    return render_template("409.html"), 409


@app.errorhandler(500)
def page_server_error(e: Exception) -> AnyResponse:
    app.log.error(e)
    return render_template("500.html"), 500


@app.errorhandler(502)
@app.errorhandler(503)
@app.errorhandler(504)
def page_server_down(e: Exception) -> AnyResponse:
    app.log.error(e)
    return render_template("503.html"), 503


@app.errorhandler(ApiException)
def page_fatcat_api_error(ae: ApiException) -> AnyResponse:
    """
    Generic error handler for fatcat API problems. With this error handler,
    don't need to explicitly catch API exceptions: they should get caught and
    routed correctly here.
    """
    if ae.status == 404:
        return page_not_found(ae)
    elif ae.status in [401, 403]:
        return page_not_authorized(ae)
    elif ae.status in [405]:
        return page_method_not_allowed(ae)
    elif ae.status in [409]:
        return page_edit_conflict(ae)
    try:
        json_body = json.loads(ae.body)
        ae.error_name = json_body.get("error")
        ae.message = json_body.get("message")
    except ValueError:
        pass
    return render_template("api_error.html", api_error=ae), ae.status


@app.errorhandler(ApiValueError)
def page_fatcat_api_value_error(ae: ApiValueError) -> AnyResponse:
    ae.status = 400
    ae.error_name = "ValueError"
    ae.message = str(ae)
    return render_template("api_error.html", api_error=ae), 400


@app.errorhandler(CSRFError)
def page_csrf_error(e: CSRFError) -> AnyResponse:
    return render_template("csrf_error.html", reason=e.description), 400


@app.route("/", methods=["GET"])
def page_home() -> AnyResponse:
    return render_template("home.html")


@app.route("/about", methods=["GET"])
def page_about() -> AnyResponse:
    return render_template("about.html")


@app.route("/rfc", methods=["GET"])
def page_rfc() -> AnyResponse:
    return render_template("rfc.html")


@app.route("/robots.txt", methods=["GET"])
def page_robots_txt() -> AnyResponse:
    if app.config["FATCAT_DOMAIN"] == "fatcat.wiki":
        robots_path = "robots.txt"
    else:
        robots_path = "robots.deny_all.txt"
    return send_from_directory(
        os.path.join(app.root_path, "static"), robots_path, mimetype="text/plain"
    )


@app.route("/sitemap.xml", methods=["GET"])
def page_sitemap_xml() -> AnyResponse:
    return send_from_directory(
        os.path.join(app.root_path, "static"), "sitemap.xml", mimetype="text/xml"
    )