Angelo Gladding
lahacker.net

dlv5vbq7lzlthol5 4b942a3185b37d00

South Pasadena, California, United States
76°F

CodecanopyFilescanopy__web__

__init__.py

Download raw file

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
"""
canopy web application

"""

import collections
import cProfile
import email
import json
import math
import operator
import pathlib
import pickle
import pstats
import re
import time

import geopy.distance
import isbnlib
from lxml.html import document_fromstring, fromstring, tostring
import mf
import numpy
import pendulum
from PIL import Image, ImageDraw, ImageFont
import requests
import sh
import web
from web import tx

import canopy
from .. import HostNotFound
from ..content import load_json, get_type, dump_json
from ..content.read import get_resources, get_resource
from ..content.write import quick_draft
from ..security import export_public_key, authenticate
from ..util import get_onion, get_path, if_owner, enqueue, global_kv, get_icons
from ..util import content as content_util
from .. import cache as cache_util
from .. import webmention
from .util import app, view

from . import cache
from . import chat
from . import content
from . import devices
from . import media
from . import orchards
from . import security
from . import system


__all__ = ["chat", "content", "orchards", "news", "player", "security",
           "system",
           "Sitemap", "SitemapInclusion", "RobotsExclusion",
           "Search", "OpenSearchDescription",
           "Token", "Micropub", "Mentions", "Actions"]


app.mount(cache.app)
app.mount(chat.app)
app.mount(devices.app)
app.mount(media.app)
app.mount(orchards.app)
app.mount(security.app)
app.mount(system.app)
app.view = view
subscription_lease = 60 * 60 * 24 * 90


@app.wrap
def require_hostname(handler, app):
    """
    block requests without a hostname

    """
    if re.match(r"^[\d\.]+$", tx.host.name):
        raise web.BadRequest("request must provide a hostname")
    yield


@app.wrap
def serve_orchards(handle, app):
    """
    identity registration at public suffix

    """
    try:
        slug = global_kv["orchards"][tx.host.name]
    except KeyError:
        yield
    else:
        canopy.contextualize(global_kv["admin"])
        if tx.request.method == "GET":
            web.header("Content-Type", "text/html")
            if tx.request.uri.path:
                raise web.OK(view.orchards.customer(tx.request.uri.path))
            raise web.OK(view.orchards.register(tx.kv["orchards", slug]))
        elif tx.request.method == "POST":
            form = web.form("name", "passphrase", "domain",
                            "service", "stripeToken")
            if form.service not in ("locked", "unlocked"):
                return "unknown service type"
            # TODO stripe
            # name = form.name.strip()
            # passphrase = form.passphrase.strip()
            domain = form.domain.strip()
            # enqueue(orchard.spawn_identity, name, passphrase, domain)
            raise web.SeeOther(f"https://{tx.origin}/{domain}")


@app.wrap
def serve_sites(handle, app):
    """
    page hosting at domains

    """
    try:
        page = global_kv["sites"][tx.host.name]
    except KeyError:
        yield
    else:
        canopy.contextualize(global_kv["admin"])
        if tx.request.method == "GET":
            web.header("Content-Type", "text/html")
            raise web.OK(view.site(get_resource("page", page)))


@app.wrap
def contextualize(handler, app):
    """
    update transaction context with current identity's data

    """
    try:
        canopy.contextualize(tx.host.name)
    except HostNotFound:
        raise web.NotFound("host not found")
    if not tx.host.name.endswith(".onion"):
        web.header("Alt-Svc", f'h2="{get_onion()}"; ma=60')
    # XXX if "app-mode" in tx.user.session:  # XXX
    # XXX     tx.kv["app-state"] = tx.request.uri.path
    yield


@app.wrap
def resume_session(handler, app):
    tx.user.session = {}
    try:
        identifier = tx.request.headers["cookie"].morsels["session"]
    except KeyError:
        identifier = None
    else:
        try:
            tx.user.session = json.loads(str(tx.kv["sessions", identifier]))
        except json.JSONDecodeError:
            print("SESSION ERROR", identifier)  # FIXME kill session cookie
    yield
    if tx.user.session:
        if not identifier:
            identifier = tx.user.identifier
        tx.kv["sessions", identifier] = \
            web.JSONEncoder().encode(tx.user.session)
        tx.kv["sessions", identifier].expire(web.default_session_timeout)


@app.wrap
def template(handler, app):
    tx.user.is_owner = False
    if "session" in tx.user:
        tx.user.is_owner = tx.user.session.get("uri") == tx.host.name
    tx.response.naked = False
    # XXX tx.view = view
    web.header("Content-Type", "text/html")
    yield
    is_redirect = tx.response.status.startswith("3")
    if is_redirect or tx.response.naked:
        pass
    else:
        article = view.article_template(tx.response.body)
        if str(tx.request.headers.get("X-Chromeless", "0")) == "1":
            article_content = str(article)
            tx.response.body = article_content
            tx.response.headers["Content-Length"] = len(article_content)
        elif tx.response.headers.content_type == "text/html":
            try:
                photo_path = tx.kv["photo"][tx.host.name]
            except KeyError:
                photo_path = None
            published_years = collections.defaultdict(set)
            for date in tx.db.select("entries",
                                     what="""DISTINCT strftime('%Y/%m',
                                             updated) AS updated"""):
                if date["updated"]:
                    year, _, month = date["updated"].partition("/")
                    published_years[year].add(month)
            published_types = [resource["type"] for resource in
                               tx.db.select("resources", what="DISTINCT type")]
            tx.response.body = view.template(photo_path, tx.kv["tags"],
                                             published_types, published_years,
                                             tx.response.body, article)


@app.wrap
def secure(handler, app):
    web.header("Strict-Transport-Security",
               f"max-age={60 * 60 * 24 * 365}; includeSubDomains; preload")
    if tx.request.uri.path.startswith(("system", "devices")) and \
       not tx.user.is_owner:
        raise web.Unauthorized(view.error.unauthorized())
    yield


@app.wrap
def debug(handler, app):
    """
    print SQL queries and append code profiling statistics to response

    """
    started = False
    if tx.user.is_owner and tx.kv["debug"] == "on":
        # tx.db.debug = True  # TODO log SQL queries
        started = time.time()
        pr = cProfile.Profile()
        pr.enable()
    yield
    if started:
        pr.disable()
        if tx.response.headers.content_type == "text/html":
            duration = round(time.time() - started, 2)
            stats = []
            for caller, timing in pstats.Stats(pr).stats.items():
                stats.append((*caller[:3], *timing[:4]))

            def get_outliers(index):  # index=5, total; index=6, cumulative
                median = numpy.median([s[index] for s in stats])
                std = numpy.std([s[index] for s in stats])
                threshold = median + (2 * std)
                outliers = []
                for stat in stats:
                    if stat[index] > threshold:
                        outliers.append(stat)
                data = list(reversed(sorted(outliers,
                                            key=operator.itemgetter(index))))
                return data

            html = view.debug.profiling(duration, get_outliers(5),
                                        get_outliers(6))
            doc = document_fromstring(str(tx.response.body))
            doc.find("body").find("div").append(fromstring(str(html)))
            tx.response.body = tostring(doc)


@app.route(r"update_wiki")
class UpdateWikiTest:

    @if_owner
    def GET(self):
        wiki = web.form("host")
        # indieweb.org
        # en.wikipedia.org
        s = requests.Session()
        if wiki.host == "indieweb.org":
            endpoint = "https://indieweb.org/wiki/index.php"
            login = s.get("https://sso.indieweb.org/login",
                          params={"url":
                                  "https://indieweb.org/Main_Page"}).text
            form = dict(fromstring(login).cssselect("form")[0].form_values())
            tx.kv["autosignin"] = form["state"]
            form["me"] = f"https://{tx.host.name}"
            s.get("https://indielogin.com/auth", params=form)
            page_name = "User:Lahacker.net/POSSE_test"
            # XXX page = s.get(f"https://indieweb.org/{page_name}")
        elif wiki.host == "en.wikipedia.org":
            endpoint = "https://en.wikipedia.org/w/index.php"
            login = s.get(endpoint, params={"title": "Special:UserLogin"}).text
            form = dict(fromstring(login).cssselect("form")[0].form_values())
            form["wpName"] = wiki.username
            form["wpPassword"] = wiki.password
            s.post(endpoint, params=form)
            page_name = "User:Angelogladding/POSSE_test"
            # XXX page = s.get("f"https://en.wikipedia.org/wiki/{page_name}")
        edit_page = s.get(endpoint,
                          params={"title": page_name, "action": "edit"}).text
        # from pprint import pprint
        # pprint(edit_page)
        form = dict(fromstring(edit_page).cssselect("form")[0].form_values())
        # pprint(form)
        form["wpTextbox1"] = "THIS CAME FROM MY SITE\n"
        for k, v in form.items():
            form[k] = (None, v)  # do not emit filenames
        s.post(endpoint, params={"title": page_name, "action": "submit"},
               files=form)
        return "edited page on IndieWeb wiki"


@app.route(r"pubkey.asc")
class PublicKey:

    def GET(self):
        web.header("Content-Type", "application/pgp-keys")
        return export_public_key()


@app.route(r"gaea")
class Gaea:

    def GET(self):
        tx.response.naked = True
        web.header("Content-Type", "text/x-python")
        path = pathlib.Path(__file__).parent.parent.parent / "gaea.py"
        with open(path) as fp:
            return fp.read()


@app.route(r"qr")
class QR:

    def GET(self):
        web.header("Content-Type", "image/png")
        web.header("X-Accel-Redirect", f"/X/qrcode.png")


def generate_avatar(initials, path):
    text_color = "#93a1a1"
    bg_color = "#073642"
    size = 256
    image = Image.new("RGB", (size, size), bg_color)
    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype(str((pathlib.Path(__file__).parent / "static" /
                                   "fonts/UbuntuMono/UbuntuMono-Bold.ttf")),
                              size=int(0.8 * size))
    width, height = font.getsize(initials)
    left = (size - width) / 2.0
    top = (size - height) / 5.5
    draw.text((left, top), initials, fill=text_color, font=font)
    image.save(path, format="png", optimize=True)


@app.route(r"avatar.png")
class Avatar:

    def GET(self):
        web.header("Content-Type", "image/png")
        web.header("X-Accel-Redirect", f"/X/avatar.png")


@app.route(r"asteria.xpi")
class Asteria:

    # @if_owner
    def GET(self):
        if web.form(mode="install").mode == "install":
            web.header("Content-Type", "application/x-xpinstall")
            web.header("X-Accel-Redirect", f"/X/asteria/asteria.xpi")
        else:  # develop
            asteria_dir = get_path() / "asteria"
            asteria_dir.mkdir(exist_ok=True)
            with (asteria_dir / "manifest.json").open("w") as fp:
                fp.write(str(view.asteria.manifest()))
            with (asteria_dir / "background.js").open("w") as fp:
                fp.write(str(view.asteria.background()))
            with (asteria_dir / "asteria.js").open("w") as fp:
                fp.write(str(view.asteria.asteria()))
            with (asteria_dir / "browser_action.html").open("w") as fp:
                fp.write(str(view.asteria.browser_action()))
            with (asteria_dir / "page_action.html").open("w") as fp:
                fp.write(str(view.asteria.page_action()))
            with (asteria_dir / "page_script.js").open("w") as fp:
                fp.write(str(view.asteria.page_script(get_icons())))
            sh.cp("/home/gaea/understory/src/canopy/canopy/__web__/static/"
                  "images/canopy.ico", ".", _cwd=str(asteria_dir))
            sh.zip("-FS", "asteria-dev.xpi", "manifest.json", "canopy.ico",
                   "background.js", "asteria.js", "browser_action.html",
                   "page_action.html", "page_script.js", _cwd=str(asteria_dir))
            web.header("Content-Type", "application/x-xpi")
            web.header("X-Accel-Redirect", f"/X/asteria/asteria-dev.xpi")


@app.route(r"icons")
class IconEditor:

    def GET(self):
        return view.icons.editor(get_icons())


@app.route(r"icons.svg")
class IconSpritemap:

    def GET(self):
        web.header("Content-Type", "image/svg+xml")
        return view.icons.spritemap(get_icons())


# XXX @app.route(r"app")
# XXX class App:
# XXX
# XXX     def GET(self):
# XXX         key = web.form("key").key
# XXX         if key != tx.kv["app"]:
# XXX             raise web.BadRequest("cannot authenticate")
# XXX         if tx.user.is_owner:
# XXX             return view.app.install()
# XXX         # XXX tx.user.session["uri"] = tx.host.name
# XXX         # XXX tx.user.session["id"] = 1
# XXX         # XXX tx.user.is_owner = True
# XXX         # XXX tx.user.session["app-mode"] = True
# XXX         # XXX raise web.SeeOther(f"/{tx.kv['app-state']}")
# XXX         tx.response.naked = True
# XXX         return view.app.index()


@app.route(r"debug")
class Debug:

    def GET(self):
        print(">>> GOT HERE <<<")
        return view.debug()

    def SOCKET(self, socket):
        print(">>> GOT HERE <<<")
        channel_name = "debug"
        try:
            channel = tx.kv.db.pubsub()
        except AttributeError:
            print("broken socket on redis init")
            raise web.NotFound("TODO")
        channel.subscribe(channel_name)
        websocket_fd = web.uwsgi.connection_fd()
        redis_fd = channel.connection._sock.fileno()

        def publish_message():
            try:
                message = web.uwsgi.websocket_recv_nb()
            except OSError:
                pass  # websocket timed out
            else:
                if message:
                    tx.kv.db.publish(channel_name, message)

        while True:
            web.uwsgi.wait_fd_read(websocket_fd, 3)
            try:
                web.uwsgi.wait_fd_read(redis_fd)
            except OSError:
                print("broken socket on redis read")
                raise web.NotFound("TODO")
            web.uwsgi.suspend()
            fd = web.uwsgi.ready_fd()
            if fd > -1:
                if fd == websocket_fd:  # expect message=recv_nb?
                    publish_message()
                elif fd == redis_fd:
                    message = channel.parse_response()
                    if message[0] == b"message":
                        web.uwsgi.websocket_send(message[2].decode("utf-8"))
            else:
                publish_message()  # expect message=None?


@app.route(r"sitemap")
class Sitemap:

    def GET(self):
        return view.sitemap.human(get_resources())


@app.route(r"sitemap.xml")
class SitemapInclusion:

    def GET(self):
        web.header("Content-Type", "application/xml; charset=utf-8")
        return view.sitemap.machine(get_resources())


@app.route(r"robots.txt")
class RobotsExclusion:

    def GET(self):
        web.header("Content-Type", "text/plain")
        return view.robots()


@app.route(r"help")
class Help:

    def GET(self):
        return view.help()


def parse_routes(routes):
    for route, handler in routes:
        # if not route:
        #     continue

        def repl(match):
            return (f'<span style="color:#2aa198;" title="{match.group(2)}">{{'
                    f'{match.group(1)}}}</span>')
        route_html = re.sub(r"\(\?P<(\w+?)>(.+?)\)", repl, route)

        methods = []
        for method in ("HEAD", "GET", "PUT", "DELETE", "POST"):
            if method in handler.handler.__dict__:
                methods.append(method)

        yield route_html, methods, handler.handler.__name__, handler.__doc__


@app.route(r"api")
class API:

    @if_owner
    def GET(self):
        return view.api(list(parse_routes(app.routes)),
                        list(parse_routes(media.app.routes)),
                        list(parse_routes(system.app.routes)))


@app.route(r"songs")
class Songs:

    def GET(self):
        return view.songs()


@app.route(r"locations")
class Locations:

    @if_owner
    def GET(self):
        form = web.form(every=None, start=None, end=None)
        kwargs = {}
        if form.start and form.end:
            kwargs = {"where": "timestamp >= ? AND timestamp <= ?",
                      "vals": [pendulum.parse(form.start),
                               pendulum.parse(form.end)]}
        recent = tx.db.select("location", order="timestamp DESC", **kwargs)
        if form.every:
            recent = (r for n, r in enumerate(recent)
                      if not n % int(form.every))
        return view.location(list(recent))


@app.route(r"capabilities")
class Capabilities:

    def GET(self):
        return view.capabilities()


@app.route(r"tracker/browser")
class BrowserTracker:

    def GET(self):
        web.form("url").url
        tx.response.naked = True
        return "ok"
        # tx.db.insert("visited", timestamp=pendulum.parse(p["timestamp"]),
        #              altitude=p["altitude"], latitude=lat, longitude=lng,
        #              speed=p["speed"], motion=motion, wifi=p["wifi"],
        #              battery_level=p["battery_level"],
        #              battery_state=p["battery_state"],
        #              horizontal_accuracy=p["horizontal_accuracy"],
        #              vertical_accuracy=p["vertical_accuracy"])


# TODO change to PhoneTracker
@app.route(r"tracker/device/{device_token}")
class DeviceTracker:

    def POST(self):
        for location in tx.request.body._data["locations"]:
            p = location["properties"]
            if "end_location" in p:
                print("--- TRIP ---")
                print(p)
                continue
            if "action" in p:
                print("--- ACTION ---")
                print(p)
                continue
            motion = ""
            if "motion" in p:
                if isinstance(p["motion"], list):
                    motion = ",".join(p["motion"])
                else:
                    motion = p["motion"]
            lng, lat = location["geometry"]["coordinates"]
            tx.db.insert("location", timestamp=pendulum.parse(p["timestamp"]),
                         altitude=p["altitude"], latitude=lat, longitude=lng,
                         speed=p["speed"], motion=motion, wifi=p["wifi"],
                         battery_level=p["battery_level"],
                         battery_state=p["battery_state"],
                         horizontal_accuracy=p["horizontal_accuracy"],
                         vertical_accuracy=p["vertical_accuracy"])
        web.header("Content-Type", "application/json")
        return '{"result": "ok"}'


@app.route(r"tracker/user")
class UserTracker:

    def POST(self):
        form = web.form()
        tx.response.naked = True
        web.header("Content-Type", "application/json")
        details = {}
        if "geo" in tx.owner:
            home = (tx.owner["geo"]["latitude"], tx.owner["geo"]["longitude"])
            home = (34.1023321, -118.1733567)
            current_location = (form["latitude"], form["longitude"])
            distance_from_home = geopy.distance.distance(home,
                                                         current_location)
            details["distanceFromHome"] = distance_from_home.feet
        return json.dumps(details)


@app.route(r"search")
class Search:

    # TODO Wolfram Alpha

    def GET(self):
        try:
            query = web.form("query").query
        except web.BadRequest:
            return view.search.index()

        try:
            url = web.uri.parse(query)
        except ValueError:
            pass
        else:
            if url.suffix:
                enqueue(cache_util.update, url.minimized, parse=True)
                raise web.SeeOther(f"/cache/web/"
                                   f"{url.minimized.replace('?', '/')}")
        if isbnlib.is_isbn13(query):
            raise web.SeeOther(f"/cache/books/{query}")
        if re.match(r"10\.\d{4,}/[\w.]+", query):
            raise web.SeeOther(f"/cache/articles/{query}")

        if tx.user.is_owner:
            self.handle_bang(query)

        types = set()
        try:
            resources = tx.db.select("finals", what="rank, data", order="rank",
                                     where="finals MATCH ?",
                                     vals=[f'"{query}"'])
            # where=query)
            # json_extract(data, '$.-type') = "note" AND
            # finals MATCH "something"
        except tx.db.OperationalError:
            print("  >> broken search")
            results = []
        else:
            results = []
            for resource in resources:
                data = load_json(resource["data"])
                entry = tx.db.select("entries", where="resource = ?",
                                     vals=[data["-id"]])[0]
                types.add(data["-type"])
                t = get_type(data["-type"]).view.type
                results.append(view.entry_template(entry, data,
                                                   t(entry, data)))

        article_cache = []
        for article in tx.db.select("article_cache", order="rank",
                                    what="rank, doi, metadata, text",
                                    where="article_cache MATCH ?",
                                    vals=[f'"{query}"']):
            article_details = dict(article)
            article_details["metadata"] = json.loads(article["metadata"])
            article_cache.append(article_details)

        return view.search.results(query, results, types, article_cache)

    def canopy(self, query):
        """search the entire canopy by utilizing your network's resources"""
        pass

    def calculate(self, query):
        """bang-c"""
        output = []

        def print(line):
            output.append(line)
        try:
            exec(query, {"__builtins__": {"time": time, "requests": requests,
                                          "print": print}})
        except Exception as err:
            return str(err)
        return view.search.functions.calculator(query, output)

    def books(self, query):
        books = isbnlib.goom(query)
        return view.search.functions.books(query, books)

    def duckduckgo(self, query):
        ddg = requests.get(f"https://duckduckgo.com/html?q={query}",
                           headers={"User-Agent": "Mozilla/5.0 (X11; Linux"
                                                  " x86_64; rv:69.0)"
                                                  " Gecko/20100101"
                                                  " Firefox/69.0"})
        ddg_doc = fromstring(ddg.text)
        results = []
        for result in ddg_doc.cssselect("#links .result"):
            try:
                title = result.cssselect("h2.result__title a")[0]
                desc = result.cssselect(".result__snippet")[0].text_content()
            except IndexError:
                continue
            results.append((title.attrib["href"], title.text_content(), desc))
        return view.search.functions.duckduckgo(query, results)

    def hacker_news(self, query):
        results = content_util.HackerNews().search(query)
        return view.search.functions.hacker_news(query, results)

    def the_pirate_bay(self, query):
        results = content_util.ThePirateBay().search(query)
        return view.search.functions.the_pirate_bay(query, results)

    def handle_bang(self, query):
        # XXX "imdb": "imdb.com/find?q={}",
        # XXX "iwc": "indieweb.org/wiki/index.php"
        # XXX        "?title=Special:Search&search={}",
        # XXX "w": "en.wikipedia.org/w/index.php?search={}",
        # XXX "yt": "youtube.com/results?search_query={}",
        # XXX "z": "tvlistings.zap2it.com"
        words = query.split()
        supported_functions = {"": self.duckduckgo,
                               "c": self.calculate,
                               "b": self.books,
                               "hn": self.hacker_news,
                               "tpb": self.the_pirate_bay}
        for word in words:
            if not word.startswith("!"):
                continue
            bang = word[1:]
            words.remove(word)
            query = " ".join(words)
            # XXX try:
            # XXX     search_template = supported_searches[bang]
            # XXX except KeyError:
            # XXX     pass
            # XXX else:
            # XXX     search_url = search_template.format(query)
            # XXX     raise web.SeeOther(f"https://{search_url}")
            try:
                function_handler = supported_functions[bang]
            except KeyError:
                pass
            else:
                raise web.OK(function_handler(query))
            # TODO parse and render in personal UI
            # return requests.get(search_uri).text


@app.route(r"search/suggest")
class SearchSuggestions:

    """
    provides OpenSearch suggestions

    """

    def GET(self):
        """
        return a JSON array in the OpenSearch

        """
        query = web.form("query").query
        base = f"https://{tx.host.name}/search?query="
        suggestions = []
        if query == "example":
            suggestions.append(("example code", "12 results, code examples",
                                f"{base}example+code"))
        web.header("Content-Type", "application/x-suggestions+json")
        return json.dumps([query] + list(zip(*suggestions)))


@app.route(r"opensearch.xml")
class OpenSearchDescription:

    def GET(self):
        web.header("Content-Type", "application/opensearchdescription+xml")
        return view.opensearch()


@app.route(r"token")
class Token:

    def POST(self):
        form = web.form("me", "code", "grant_type",
                        "client_id", "redirect_uri")
        if form.code != tx.kv["codes"][form.client_id]:
            return "nope"
        token = web.nbrandom(10)
        web.header("Content-Type", "application/json")
        return json.dumps({"access_token": token, "scope": "draft",
                           "me": "https://{}".format(tx.host.name)})


@app.route(r"micropub")
class Micropub:

    def POST(self):
        form = web.form("h")
        if form.h == "entry":
            if "like-of" in form:
                form = web.form()
                uri = web.uri.parse("https://{}/content/likes/"
                                    "editor".format(tx.host.name))
                uri["url"] = form["like-of"]
                uri["title"] = form["name"]
            elif "in-reply-to" in form:
                uri = web.uri.parse("https://{}/content/replies/"
                                    "editor".format(tx.host.name))
                # uri["body"] = form["body"]
                uri["in-reply-to"] = form["in-reply-to"]
            elif "bookmark-of" in form:
                form = web.form(category=[])
                uri = web.uri.parse("https://{}/content/bookmarks/"
                                    "editor".format(tx.host.name))
                uri["url"] = form["bookmark-of"]
                uri["title"] = form["name"]
                uri["category"] = form["category"]
            elif "quotation-of" in form:
                form = web.form()
                return form
                uri = web.uri.parse("https://{}/content/quotations/"
                                    "editor".format(tx.host.name))
                uri["url"] = form["quotation-of"]
                uri["content"] = form["name"]
            else:
                return "unknown entry type"
        elif form.h == "card":
            form = web.form()
            host = web.uri.parse(form.url).minimized
            uri = web.uri.parse("https://{}/network/{}/"
                                "status".format(tx.host.name, host))
            uri["name"] = form.name
        else:
            return "unknown format"
        raise web.SeeOther(uri)


@app.route(r"mentions")
class Mentions:

    def GET(self):
        # mentions = webmention.get("likes",
        #                           f"notes/2018/09/18/ZPxp")
        # return mentions
        mentions = {}
        for mention_id in tx.kv["mentioned"].keys():
            mention = pickle.loads(tx.kv["mentioned"].hgetbytes(mention_id))
            mentions[mention["received"]] = (mention_id, mention)
        return view.mentions(mentions)

    def POST(self):
        form = web.form("source", "target")
        data = pickle.dumps({"received": time.time(),
                             "source_url": form.source,
                             "target_url": form.target})
        while True:
            mention_id = web.nbrandom(9)
            if tx.kv["mentioned"].hsetnx(mention_id, data):
                break
        enqueue(webmention.receive, mention_id, form.source, form.target)
        tx.response.naked = True
        raise web.Created("webmention received",
                          f"{tx.origin}/mentions/{mention_id}")


@app.route(r"mentions/{mention}")
class Mention:

    def GET(self):
        try:
            data = pickle.loads(tx.kv["mentioned"].hgetbytes(self.mention))
        except KeyError:
            raise web.NotFound("no such mention could be found")
        return view.mention(self.mention, data)


@app.route(r"mentions/{mention_type}/{pathslug}")
class ResourceMentions:

    def GET(self):
        mentions = webmention.get(self.mention_type, self.pathslug)
        return view.mention_type(self.mention_type, self.pathslug, mentions)


@app.route(r"hub")
class Hub:

    def GET(self):
        return view.hub(tx.kv["subscriptions"])

    def POST(self):
        mode = web.form("hub.mode")["hub.mode"]
        # XXX if mode == "publish":
        # XXX     self.publish()
        # XXX elif mode == "subscribe":
        # XXX     self.subscribe()
        if mode == "subscribe":
            return self.subscribe()
        raise web.BadRequest("hub only supports subscription; "
                             '`hub.mode` must be "subscribe"')

    def subscribe(self):
        form = web.form("hub.topic", "hub.callback")
        # TODO raise web.BadRequest("topic not found")
        # TODO raise web.Accepted("subscription request accepted")

        # TODO async the following
        resource = form["hub.topic"]
        callback = form["hub.callback"]
        verification_data = {"hub.mode": "subscribe",
                             "hub.topic": resource,
                             "hub.challenge": web.nbrandom(32),
                             "hub.lease_seconds": subscription_lease}
        response = requests.get(callback, params=verification_data)
        if response.text != verification_data["hub.challenge"]:
            raise web.BadRequest("`hub.callback` returned incorrect challenge")
        path = web.uri.parse(resource).path
        tx.kv["subscriptions"].add(path)
        tx.kv["subscriptions", path].add(web.uri.parse(callback).minimized)


@app.route(r"hub/{hostslug}(/{pathslug})?")
class Subscription:

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        url = self.hostslug
        if "pathslug" in self:
            url += "/" + self.pathslug
        self.url = url

    def GET(self):
        # TODO validate request before responding with challenge
        try:
            challenge = web.form()["hub.challenge"]
        except KeyError:
            pass
        else:
            web.header("Content-Type", "text/plain")
            return challenge
        return f"show subscription details for {self.url}"

    def POST(self):
        # try:
        data = tx.request.body._data
        # except :
        #     pass
        # finally:
        # # store feed entry
        tx.kv["feeds", self.url].append(pickle.dumps(data))
        # # publish to websocket subscribers
        for tag in data.get("category", []):
            tx.kv.db.publish(f"{tx.host.identity}:channels:{tag}",
                             json.dumps(data))
        return "fat ping received"

        # TODO implement non-fat-ping functionality
        feed_id = tx.db.select("feeds", what="rowid", where="url = ?",
                               vals=[self.url])[0]["rowid"]
        tx.db.update("feeds", where="url = ?", vals=[self.url],
                     updated=pendulum.now("UTC"))
        url = f"https://{self.url}"
        cache_util.put(url, parse=True)
        for entry in cache_util.interpret(url, "feed")["entries"]:
            try:
                tx.db.insert("feeds_entries", feeds_id=feed_id,
                             url=entry["url"], entry=dump_json(entry),
                             timestamp=entry["published"])
            except tx.db.IntegrityError:
                tx.db.update("feeds_entries", where="url = ?",
                             vals=[entry["url"]], feeds_id=feed_id,
                             entry=dump_json(entry),
                             timestamp=entry["published"])


@app.route(r"viewer")
class Viewer:

    @if_owner
    def GET(self):
        return view.viewer.index(tx.kv["feeds"])


def process_message(message):
    message = dict(message)
    message["to"] = get_identities(message["rowid"], "to")
    message["from"] = get_identities(message["rowid"], "from")
    message["cc"] = get_identities(message["rowid"], "cc")
    return message


def get_identities(message_id, block_type):
    identities = []
    for identity in tx.db.select("email_identity_blocks AS ib",
                                 join="""email_identities AS i ON
                                         ib.email_identity_id = i.rowid""",
                                 where="""email_message_id = ? AND
                                          block_type = ?""",
                                 vals=[message_id, block_type]):
        identities.append((identity["name"], identity["address"]))
    return identities


@app.route(r"viewer/email")
class EmailInbox:

    @if_owner
    def GET(self):
        messages = []
        for message in tx.db.select("email_messages", what="rowid, *",
                                    order="sent DESC"):
            messages.append(process_message(message))
        return view.viewer.email.index(messages)


@app.route(r"viewer/email/{email_digest}")
class EmailMessage:

    @if_owner
    def GET(self):
        try:
            message = tx.db.select("email_messages", what="rowid, *",
                                   where="digest = ?",
                                   vals=[self.email_digest])[0]
        except IndexError:
            raise web.NotFound("message not found")
        with (get_path() / "email" / self.email_digest).open("rb") as fp:
            raw_message = email.message_from_bytes(fp.read())
        return view.viewer.email.message(process_message(message), raw_message)


@app.route(r"viewer/email/{email_digest}/payload")
class EmailMessagePayload:

    @if_owner
    def GET(self):
        with (get_path() / "email" / self.email_digest).open("rb") as fp:
            raw_message = email.message_from_bytes(fp.read())
        payload = raw_message.get_payload(decode=True)
        content_type = raw_message["content-type"]
        # TODO keep private & maintain readability -- emailprivacytester.com
        # if "text/html" in content_type:
        #     payload = clean_html(payload)
        tx.response.naked = True
        tx.response.headers.content_type = content_type
        return payload


@app.route(r"viewer/email/{email_digest}/{email_payload}")
class EmailMessageMultiPayload:

    @if_owner
    def GET(self):
        with (get_path() / "email" / self.email_digest).open("rb") as fp:
            raw_message = email.message_from_bytes(fp.read())
        payload = raw_message.get_payload(int(self.email_payload))
        tx.response.naked = True
        tx.response.headers.content_type = payload.get_content_type()
        return payload.get_payload(decode=True)


@app.route(r"viewer/feeds/{hostslug}(/{pathslug})?")
class Feed:

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        url = self.hostslug
        if "pathslug" in self:
            url += "/" + self.pathslug
        self.url = url

    @if_owner
    def GET(self):
        return view.viewer.feed("Unknown Title", self.url,
                                tx.kv["feeds", self.url])


@app.route(r"viewer/channels/{tag}")
class Channel:

    @if_owner
    def GET(self):
        # entries = template_entries(get_entries(tags=self.tags.split("+")))
        # reversed(list(entries))
        return view.viewer.channel(self.tag, tx.kv["feeds", self.tag])

    def SOCKET(self, socket):
        channel = tx.kv.db.pubsub()
        channel.subscribe(f"{tx.host.identity}:channels:{self.tag}")
        websocket_fd = web.uwsgi.connection_fd()
        redis_fd = channel.connection._sock.fileno()
        while True:
            web.uwsgi.wait_fd_read(websocket_fd, 3)
            web.uwsgi.wait_fd_read(redis_fd)
            web.uwsgi.suspend()
            fd = web.uwsgi.ready_fd()
            if fd > -1:
                if fd == websocket_fd:
                    message = web.uwsgi.websocket_recv_nb()
                    if message:
                        if message == b"PING":
                            web.uwsgi.websocket_send(b"PONG")
                        else:
                            print("WEBSOCK message", message)
                if fd == redis_fd:
                    message_type, _, message_body = channel.parse_response()
                    if message_type == b"message":
                        web.uwsgi.websocket_send(message_body)
            else:
                message = web.uwsgi.websocket_recv_nb()
                if message:
                    print("PING/PONG message", message)

    # def SOCKET(self, socket):
    #     channel = tx.kv.db.pubsub()
    #     channel.subscribe(f"{tx.host.identity}:channels:{self.tag}")
    #     # websocket_fd = web.uwsgi.connection_fd()
    #     redis_fd = channel.connection._sock.fileno()

    #     # def publish_message():
    #     #     try:
    #     #         entry = web.uwsgi.websocket_recv_nb()
    #     #     except OSError:
    #     #         pass  # websocket timed out
    #     #     else:
    #     #         if entry:
    #     #             self.publish(entry.decode())
    #     #             kv.db.publish(channel_name, entry)

    #     while True:
    #         # web.uwsgi.wait_fd_read(websocket_fd, 3)
    #         try:
    #             web.uwsgi.wait_fd_read(redis_fd)
    #         except OSError:
    #             print("broken socket on redis read")
    #             raise web.NotFound("TODO")
    #         web.uwsgi.suspend()
    #         fd = web.uwsgi.ready_fd()
    #         if fd > -1:
    #             # if fd == websocket_fd:  # expect message=recv_nb?
    #             #     publish_message()
    #             # elif fd == redis_fd:
    #             if fd == redis_fd:
    #                 message = channel.parse_response()
    #                 if message[0] == b"message":
    #                     print("CHANNEL SENT")
    #                     web.uwsgi.websocket_send(message[2])
    #         # else:
    #         #     publish_message()  # expect message=None?


@app.route(r"viewer/{tag}/settings")
class ChannelSettings:

    @if_owner
    def GET(self):
        return view.viewer.channel_settings(self.tag)


@app.route(r"actions")
class Actions:

    """
    web actions

        web+action://{action}?url={url}

    """

    def GET(self):
        try:
            form = web.form("handler")
        except web.BadRequest:
            return view.actions()
        # TODO tx.request.headers.accept.best_match(["application/json",
        # TODO                                       "text/html"])
        # TODO web.header("Content-Type", "application/json")
        # TODO return json.dumps(supported)
        handler = web.uri.parse(form.handler)

        if handler.action == "sign-in":
            uri = web.uri.parse(handler["url"][0])
            uri["identifier"] = tx.host.name
            uri["return_to"] = handler["return_to"][0]
            raise web.SeeOther(str(uri))

        if not tx.user.is_owner:
            raise web.Unauthorized("must be signed in to perform this action")

        url = web.uri.parse(handler["url"][0])
        cache_util.put(url, parse=True)
        tx.user.session["return_to"] = form.get("return_to", url)

        if handler.action in ("reply", "repost"):
            return getattr(view, handler.action)(url)

        # TODO associate->verify
        actions = {"associate": "identities", "rsvp": "events",
                   "follow": "follows",
                   "bookmark": "bookmarks", "like": "likes", "vote": "votes",
                   "issue": "issues", "quote": "quotes", "payment": "payments"}
        t = get_type(actions[handler.action])
        auto_publish = False

        if t.s == "follow":
            args = {"follow-of": url}
        elif t.s == "like":
            auto_publish = True
            args = {"like-of": url}
        elif t.s == "vote":
            args = {"vote-on": url}
        else:
            args = {"url": url}

        if handler.action == "associate":
            args = {"repost-of": url}
        elif handler.action == "rsvp":
            auto_publish = True
            ev = cache_util.interpret(url, "event")["event"]
            args = {"repost-of": url, "-attending": "yes", "name": ev["name"],
                    "start": pendulum.instance(ev["start"])}
        elif handler.action == "issue":
            args = {"in-reply-to": url}

        resource_id = quick_draft(t.s, args, publish=auto_publish)
        if auto_publish:
            return
        uri = web.uri.parse(f"{tx.origin}/editor/{resource_id}")
        # uri.update(**handler.query)
        raise web.SeeOther(uri)


@app.route(r"actions-finder")
class ActionsFinder:

    def GET(self):
        form = web.form("url", "do", "with")
        url = web.uri.parse(mf.parse(url=form["url"])["rels"]["webactions"][0])
        url["handler"] = f"web+action://{form['do']}?url={form['with']}"
        try:
            raise web.SeeOther(str(url))
        except KeyError:
            return "no webaction support"


@app.route(r".well-known/carddav")
class CardDavDiscovery:

    def PROPFIND(self):
        raise web.PermanentRedirect("/identities")


# @app.route(r"profile/photo")
# class ProfilePhoto:
#
#     @if_owner
#     def GET(self):
#         form = web.form("path")
#         photo = list(get_entries(types=["images"], where="e.path = ?",
#                                  wherevals=[form.path]))[0]
#         return view.profile.photo(photo)
#
#     @if_owner
#     def POST(self):
#         form = web.form("path", "crop", "dimensions")
#         try:
#             fullsize = Image.open(str(get_path() / "resources/images" /
#                                     (form.path.replace("/", "-") + ".jpg")))
#         except IOError:
#             return "ioerror"
#         scale_factor = fullsize.size[0] / int(form.dimensions.split(",")[0])
#         cropped = fullsize.crop(int(int(coord) * scale_factor)
#                                 for coord in form.crop.split(","))
#         cropped.thumbnail((280, 280))
#         cropped.save(str(get_path() / "avatar.jpg"), "JPEG", quality=100)
#         tx.kv["photo"][web.tx.host.name] = form.path
#         raise web.SeeOther("/images/" + form.path)


def get_daylight_hours(latitude, dayofyear):
    P = math.asin(0.39795 *
                  math.cos(0.2163108 + 2 *
                           math.atan(0.9671396 * math.tan(.00860 *
                                                          (dayofyear - 186)))))
    hours = (24 - (24 / math.pi) *
             math.acos((math.sin((0.8333 * math.pi / 180) +
                                 math.sin(latitude * math.pi / 180) *
                                 math.sin(P)) /
                       (math.cos(latitude * math.pi / 180) * math.cos(P)))))
    return hours


@app.route(r"weather")
class Weather:

    def GET(self):
        daylight_hours = get_daylight_hours(34.10277,
                                            pendulum.now("utc").day_of_year)
        return view.weather(daylight_hours)


@app.route(r"mobile-app")
class MobileApp:

    def GET(self):
        auth = web.form("auth").auth
        if auth != tx.kv["app"]:
            raise web.Unauthorized("nope")
        if tx.user.is_owner:
            return view.mobile_app()
        authenticate()
        raise web.SeeOther("/")  # TODO resume session