AG

Angelo Gladding
lahacker.net

dlv5vbq7lzlthol5 4b942a3185b37d00

angelo@lahacker.net

South Pasadena, California, United States currently feels like 56°F

Home CodewebFilesweb

__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
"""
tools for a metamodern web environment

Strongly influenced by Aaron Swartz' "anti-framework" `web.py` this
library aims to cleanly abstract low-level web functionality through
a Pythonic API.

>   Think about the ideal way to write a web app. Write the
>   code to make it happen.

--- Aaron Swartz

"""

import cgi
import collections
import datetime
# import errno
import getpass
import hashlib
import inspect
import io
import json
import os
import pkg_resources
import pathlib
import re
import secrets
import shutil
import signal
import sys
import threading
import time
import urllib
import wsgiref.util

import Crypto.Random.random
import kv
import lxml
import lxml.html
import mm
from mm import Template
import pendulum
import pyvirtualdisplay
import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
import sh
import unidecode
import uri
try:
    import uwsgi
except ImportError:  # outside of a `uwsgi` context; websockets disabled
    pass
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer

from . import headers
from . import letsencrypt
from .newmath import nbencode, nbdecode, nbrandom, nb60_re
from .response import (Status,  # noqa
                       OK, Created, Accepted, NoContent, MultiStatus,
                       Found, SeeOther, PermanentRedirect,
                       BadRequest, Unauthorized, Forbidden, NotFound,
                         MethodNotAllowed, Conflict, Gone)

import warnings  # mf2py's beautifulsoup's unspecified parser -- force lxml?
warnings.simplefilter("ignore")

random = secrets.SystemRandom()

__all__ = ["application", "serve", "anti_csrf", "form", "secure_form",
           "get_nonce", "get_token", "best_match", "sessions", "require_auth",
           "tx", "templates", "uri", "kv", "header", "Application",
           "nbencode", "nbdecode", "Template"]


kvdb = kv.db("web", ":", {"auth:secret": "string",
                          "auth:nonces": "set",
                          "reload-lock": "string",
                          "sessions:{session_id}": "string",
                          "sessions:{session_id}:data": "string"},
             session_id=r"[a-z0-9]{,65}")
config_templates = mm.templates(__name__)
methods = ["head", "get", "post", "put", "delete", "options", "patch",
           "propfind"]
applications = {}
default_session_timeout = 86400


def ismethod(obj):
    """"""
    return (inspect.ismethod(obj) and obj.__name__.isupper() and
            obj.__name__.lower() in methods)


def application(name, *wrappers, prefix=r"", mount_prefix=r"",
                **path_args):
    if name in applications:
        app = applications[name]
        app.prefix = prefix
        app.add_wrappers(*wrappers)
        app.add_path_args(**path_args)
    else:
        app = Application(name, *wrappers, **path_args)
        app.reload_config()
        app.prefix = prefix
        app.mount_prefix = mount_prefix
        applications[name] = app
    return app


def get_host_hash(path):
    return hashlib.sha256(str(path.resolve()).encode("utf-8")).hexdigest()[:6]


def setup_servers(root, app):
    """
    initialize and configure servers (web, nginx, redis, supervisor)

    """
    root = pathlib.Path(root).resolve()
    root_hash = get_host_hash(root)
    env = pathlib.Path(os.getenv("VIRTUAL_ENV"))
    root.mkdir()
    (root / "etc").mkdir()

    with (root / "etc/redis.conf").open("w") as fp:
        fp.write(str(config_templates.redis(root)))
    with (root / "etc/supervisor.conf").open("w") as fp:
        fp.write(str(config_templates.supervisor(root, root_hash,
                                                 getpass.getuser(), env, app)))
    with (root / "etc/nginx.conf").open("w") as fp:
        fp.write(str(config_templates.nginx(root_hash)))

    (root / "var/letsencrypt-challenges").mkdir(parents=True)
    letsencrypt.generate_account_key(root)

    (root / "run").mkdir(parents=True)
    with (root / "etc/tor_stem_password").open("w") as fp:
        fp.write(str(random.getrandbits(100)))

    session_salt = Crypto.Random.random.randint(10**63, 10**64)
    cfg = {"root": str(root), "watch": str(env / "src"),
           "session": {"salt": str(session_salt)}}
    with (root / "etc/web.conf").open("w") as fp:
        json.dump(cfg, fp, indent=4, sort_keys=True)
    return root


# TODO rename
def config_servers(root, web_server_config_handler=None):
    """
    update symlinks to config files and reload nginx

    """
    root_hash = get_host_hash(root)
    # TODO FIXME XXX figure out what to do here...
    nginx_conf = pathlib.Path("/home/gaea/detritus/nginx/conf")
    sh.ln("-sf", (root / "etc/nginx.conf").resolve(),
          nginx_conf / "nginx.conf")
    if web_server_config_handler:
        web_server_config_handler(nginx_conf / "conf.d", root_hash)
    sh.sudo("ln", "-sf", (root / "etc/supervisor.conf").resolve(),
            "/etc/supervisor/conf.d/{}.conf".format(root_hash))


def serve(app_name, processes=3, threads=20, max_requests=100, lifespan=60):
    """
    serve callable `app` at given `port`

    """
    # TODO use file sockets specified as relative locations or in environ vars
    # master_fifo = os.path.expanduser("~/.web/{}-uwsgictl".format(app))

    # __import__(app)
    # for app_pkg, apps in get_apps().items():
    #     for app_name, app_instance in apps:
    #         if app == app_name:
    #             print(dir(app_pkg))
    app = applications[app_name]

    def process(line):
        # TODO log everything, filter display to relevant
        print(line.rstrip())

    root = pathlib.Path(app.cfg["root"])
    watch = app.cfg.get("watch")
    bg = False
    if watch:
        bg = True
    # XXX app_port = 8080
    proc = sh.uwsgi("-H", os.getenv("VIRTUAL_ENV"), "-w",
                    "{}.__web__:app".format(app_name),
                    "--uwsgi-socket", root / "run/web.sock",
                    "--chmod-socket=666",
                    # "--http-socket", ":{}".format(app_port),
                    "--logformat=%(method) %(host)%(uri) %(status)",
                    "--ignore-sigpipe",
                    "--max-requests", max_requests,
                    "--max-worker-lifetime", 60 * lifespan,
                    # "--master-fifo", master_fifo,
                    "-M", "-p", processes, "--async", threads, "--ugreen",
                    "--stats", root / "run/web-stats.sock",
                    # XXX "--stats", "127.0.0.1:1717", "--stats-http",
                    _bg=bg, _err=process)
    # logging.basicConfig(level=logging.INFO,
    #                     format='%(asctime)s - %(message)s',
    #                     datefmt='%Y-%m-%d %H:%M:%S')
    if watch:
        event_handler = EventHandler(proc)
        observer = Observer()
        observer.schedule(event_handler, str(watch), recursive=True)
        observer.start()
        try:
            proc.wait()
        except KeyboardInterrupt:
            observer.stop()
        observer.join()
        proc.signal(signal.SIGQUIT)


class EventHandler(FileSystemEventHandler):

    """restarts server when source directory changes"""

    def __init__(self, server_proc):
        self.server_proc = server_proc
        super(EventHandler, self).__init__()

    def _restart_server(self, event):
        if event.src_path.endswith(".py"):
            if kvdb:
                while kvdb["reload-lock"]:
                    time.sleep(2)
            self.server_proc.signal(signal.SIGHUP)

    # on_moved = on_created = on_deleted =
    on_modified = _restart_server

    # def on_moved(self, event):
    #     super(EventHandler, self).on_moved(event)
    #     # what = 'directory' if event.is_directory else 'file'
    #     # logging.info("Moved %s: from %s to %s", what, event.src_path,
    #     #              event.dest_path)

    # def on_created(self, event):
    #     super(EventHandler, self).on_created(event)
    #     # what = 'directory' if event.is_directory else 'file'
    #     # logging.info("Created %s: %s", what, event.src_path)

    # def on_deleted(self, event):
    #     super(EventHandler, self).on_deleted(event)
    #     # what = 'directory' if event.is_directory else 'file'
    #     # logging.info("Deleted %s: %s", what, event.src_path)

    # def on_modified(self, event):
    #     super(EventHandler, self).on_modified(event)
    #     # what = 'directory' if event.is_directory else 'file'
    #     # logging.info("Modified %s: %s", what, event.src_path)


def get_apps():
    """"""
    apps = collections.defaultdict(list)
    for ep in pkg_resources.iter_entry_points("web.apps"):
        handler = ep.load()
        apps[ep.dist].append((ep.name, handler))
    return apps


def header(name, value, add=False):
    """"""
    if add:
        if name not in tx.response.headers:
            tx.response.headers[name] = [value]
        else:
            tx.response.headers[name].append(value)
    else:
        tx.response.headers[name] = value


def best_match(handlers, *args, **kwargs):
    """"""
    handler_types = [handler for handler, _ in handlers.items()]
    best_match = tx.request.headers.accept.best_match(handler_types)
    tx.response.headers.content_type = best_match
    return dict(handlers)[best_match](*args, **kwargs)


def get_integrity_factory(template_pkg):
    """
    generate integrity hashes on the fly for local assets

    """
    def handler(fn):
        static_assets_dir = pathlib.Path(template_pkg).parent.parent / "static"
        return sh.base64(sh.xxd(sh.sha256sum("-b", static_assets_dir / fn),
                                "-r", "-p")).strip()
    return handler


def utcnow():
    return pendulum.now("UTC")


_punct_re = r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+'
_punct_split = re.compile(_punct_re).split


def textslug(title, delim="_", lower=True):
    """
    return a path slug containing a normalized version of `title`

    Defaults to delimiting words by "_" and enforcing all lowercase.
    Also makes intelligent path-friendly replacements (e.g. "&" to "and").

        >>> slug("Roasting with @Alice & @Bob!")
        "roasting_with_alice_and_bob"

    """
    # TODO use formal normalization tooling:

    #   import unicodedata
    #   normalized = unicodedata.normalize("NFKC", title)

    #   title.encode("punycode")

    #   from confusable_homoglyphs import confusables
    #   bool(confusables.is_dangerous(title))

    result = []
    if lower:
        title = title.lower()
    title = title.replace(" & ", " and ")
    for word in _punct_split(title):
        result.extend(unidecode.unidecode(word).split())
    return delim.join(result)


def timeslug(dt):
    """
    return a path slug containing date and time

    Date is encoded in standard YYYY/MM/DD form while the time is encoded
    as the NewBase60 equivalent of the day's centiseconds.

    """
    centiseconds = ((((dt.hour * 3600) + (dt.minute * 60) + dt.second) * 100) +
                    round(dt.microsecond / 10000))
    return "{}/{}/{}/{}".format(dt.year, dt.format("MM"), dt.format("DD"),
                                nbencode(centiseconds, 4))


def anti_csrf(handler):
    """"""
    # TODO csrf-ify forms with class name "x-secure"
    yield


def get_nonce():
    """"""
    return nbrandom(32)


def get_token(nonce):
    """
    return a token for given `secret` and `nonce`

    secret can be a string or a Redis instance in which key `secret`

    """
    secret = str(kvdb["auth:secret"])
    return hashlib.sha1(bytes(secret + nonce, "utf-8")).hexdigest()


def secure_form(*args, **kwargs):
    """"""
    args = list(args) + ["token", "nonce"]
    form = Form(*args, **kwargs)
    if not kvdb["auth:nonces"].add(form["nonce"]):
        raise OK("given `nonce` has already been used")
    if get_token(form["nonce"]) != form["token"]:
        raise OK("invalid `token` for given `nonce`")
    form.pop("token")
    form.pop("nonce")
    return form


class Form(dict):

    """

    """

    def __init__(self, *requireds, **defaults):
        _data = tx.request.body._data
        for required in requireds:
            if required not in _data:
                err_msg = "required `{}` not present in request"
                raise BadRequest(err_msg.format(required))
        super(Form, self).__init__(defaults)
        for key in _data.keys():
            if isinstance(_data[key], list):
                items = []
                for item in _data[key]:
                    if item.filename:
                        items.append(File(item.filename, item))
                    else:
                        items.append(item.value)
                self[key] = items
            else:
                if _data[key].filename:
                    value = File(key, _data[key])
                else:
                    value = _data.getfirst(key)
                if isinstance(defaults.get(key), list):
                    value = [value]
                self[key] = value

    def __getattr__(self, name):
        try:
            return self[name]
        except KeyError as e:
            raise AttributeError(e)

    def __setattr__(self, name, value):
        self[name] = value


form = Form


class Socket:

    """
    websockets

    """

    def __init__(self, key="", origin=""):
        uwsgi.websocket_handshake()

    def sleep(self, seconds):
        time.sleep(seconds)

    def recv(self, block=True):
        handler = uwsgi.websocket_recv if block else uwsgi.websocket_recv_nb
        return handler().decode("utf-8")

    def send(self, data):
        return uwsgi.websocket_send(data)


socket = Socket


class File:

    """

    """

    def __init__(self, name, fileobj):
        self.name = name
        self.fileobj = fileobj

    def save(self, filepath, **options):
        """

        """
        # TODO handle required
        required = options.pop("required", False)
        if required:
            requireds = [required]
            if required == "jpg":
                requireds.append("jpeg")
            if not self.fileobj.filename.lower().endswith(tuple(requireds)):
                raise BadRequest("`{}` not `{}`".format(self.name, required))
        # self._ensure_dir_exists(dirpath)
        self.fileobj.file.seek(0)
        # while True:
        #     sugar = nbrandom(2)
        #     path = dirpath / self.name
        #     path = path.parent / "{}-{}{}".format(path.stem, sugar,
        #                                           path.suffix)
        if required:
            suffix = "." + required
        else:
            suffix = pathlib.Path(self.fileobj.filename).suffix
        filepath = filepath.with_suffix(suffix)
        if filepath.exists():
            raise FileExistsError("{} already exists".format(filepath))
        with filepath.open("wb") as fp:
            shutil.copyfileobj(self.fileobj.file, fp)
        return filepath

    # def _ensure_dir_exists(self, dirpath):
    #     try:
    #         os.makedirs(str(dirpath))
    #     except OSError as exc:
    #         if exc.errno == errno.EEXIST and dirpath.is_dir():
    #             pass
    #         else:
    #             raise


def shift_headings(html, header_shift=1):
    """

    """
    if not html.strip():
        return ""
    dom = lxml.html.fromstring(html)
    for header in dom.cssselect("h1, h2, h3, h4, h5, h6"):
        header.tag = "h{}".format(int(header.tag[1]) + header_shift)
    output = lxml.html.tostring(dom).decode("utf-8")
    if output.startswith("<div>"):
        output = output[5:-6]
    return output


class Resource:

    """

    """

    def __init__(self, **kwargs):
        self.__dict__ = dict(kwargs)
        # XXX self._resources = ResourceData()
        # XXX for resource_name, value in kwargs.items():
        # XXX     table, _, column = resource_name.partition("_")
        # XXX     self._resources[table][column] = value

    def get_data(self):
        try:
            data = self.__dict__.pop("data")
        except KeyError:
            try:
                loader = self.load
            except AttributeError:
                def loader(): None
            data = loader()
        self.data = data

    def delegate(self, handler, *args, shift_headings=1, **kwargs):
        # TODO uhhmmm...
        kwargs.update(shift_headings=shift_headings)
        return handler().get(self, *args, **kwargs)

    @classmethod
    def get(resource, parent, **kwargs):
        """"""
        header_shift = kwargs.pop("shift_headings", None)
        if "_data" in parent.__dict__:
            parent._data.update(kwargs.get("data", {}))
        parent.__dict__.pop("data", None)  # NOTE magic name "data" is reserved
        kwargs.update(parent.__dict__)
        try:
            handler = resource(**kwargs)
            handler.get_data()
            content = handler.GET()
        except NotFound:
            return "not found"
        if header_shift:
            try:
                content._body = shift_headings(str(content), header_shift)
            except AttributeError:
                pass
        return content

    def __contains__(self, item):
        return item in dir(self)


# XXX class ResourceData(collections.OrderedDict):
# XXX
# XXX     def __missing__(self, key):
# XXX         self[key] = collections.OrderedDict()
# XXX         return self[key]


class Application:

    """
    a web application

        >>> app = Application("example")
        >>> @app.wrap
        ... def contextualize(handler, app):
        ...     yield
        >>> @app.route(r"")
        ... class Greeting:
        ...     def GET(self):
        ...         return "hello world"
        >>> response = app.get(r"")
        >>> response[0]
        '200 OK'
        >>> response[2][0]
        b'hello world'

    """

    def __init__(self, name, *wrappers, **path_args):
        self.name = name
        self.wrappers = []
        self.add_wrappers(*wrappers)
        self.path_args = {}
        self.add_path_args(**path_args)
        self.mounts = []
        self.routes = []  # TODO use ordered dict
        # for method in http.spec.request.methods[:5]:
        #     setattr(self, method, functools.partial(self.get_handler,
        #                                             method=method))
        # XXX try:
        # XXX     self.view = mm.templates(name, tx=tx)
        # XXX except ImportError:
        # XXX     try:
        # XXX         self.view = mm.templates(name + ".__web__", tx=tx)
        # XXX     except ImportError:
        # XXX         pass

    def reload_config(self, path=None):
        self.cfg = {}
        path = os.getenv("WEBCFG", path)
        try:
            with pathlib.Path(path).open() as fp:
                self.cfg = json.load(fp)
        except (FileNotFoundError, TypeError):
            pass

    def add_wrappers(self, *wrappers):
        self.wrappers.extend(wrappers)

    def add_path_args(self, **path_args):
        self.path_args.update({k: v.replace(r"\!", nb60_re)
                               for k, v in path_args.items()})

    def get(self, path):
        """"""
        env = {'HTTP_REFERER': 'http://localhost:22739/',
               'HTTP_HOST': 'lahacker.net:22739',
               'HTTP_CONNECTION': 'keep-alive',
               'HTTP_ACCEPT': 'image/png,image/*;q=0.8,*/*;q=0.5',
               'HTTP_USER_AGENT': 'Mozilla/5.0 (X11; Ubuntu; Linux i686; '
                                  'rv:21.0) Gecko/20100101 Firefox/21.0',
               'HTTP_COOKIE': 'session=99f81fd1f5e4c13b724043336f75'
                              'e81ee51d806979220cc8cebe51bc9d0de292',
               'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.5',
               'HTTP_ACCEPT_ENCODING': 'gzip, deflate',
               'PATH_INFO': path,
               'QUERY_STRING': '',
               'RAW_URI': '/',
               'REMOTE_ADDR': '127.0.0.1',
               'REMOTE_PORT': '44612',
               'REQUEST_METHOD': 'GET',
               'SCRIPT_NAME': '',
               'SERVER_PROTOCOL': 'HTTP/1.1',
               'SERVER_SOFTWARE': 'gunicorn/0.17.4',
               'SERVER_NAME': 'localhost',
               'SERVER_PORT': '22739',
               'wsgi.input': open("/dev/null"),
               'wsgi.url_scheme': 'http'}
        response = []

        def start_response(status, headers):
            response.append(status)
            response.append(headers)
        response.append(self(env, start_response))
        return tuple(response)

    def wrap(self, handler):
        """
        decorate a generator to run at various stages during the request

        """
        self.wrappers.append(handler)
        return handler
        # def register(controller):
        #     path = path_template.format(**{k: "(?P<{}>{})".format(k, v) for
        #                                    k, v in self.path_args.items()})
        #     self.routes.append((path, controller))
        #     return controller
        # return register

    # @property
    # def resource(self):
    #     class Resource(type):
    #         def __new__(cls, name, bases, attrs):
    #             resource = type(name, bases, attrs)
    #           path = attrs["path"].format(**{k: "(?P<{}>{})".format(k, v) for
    #                                          k, v in self.path_args.items()})
    #             self.routes.append((path, resourcer))
    #             controller.__web__ = path
    #             return resource
    #     return Resource

    def route(self, path_template=None):
        """
        decorate a class to run when request path matches template

        """
        def register(controller):
            # TODO allow for reuse of parent_app's path_arg definitions
            # XXX try:
            # XXX     path_args = dict(self.parent_app.path_args,
            #                          **self.path_args)
            # XXX except AttributeError:
            # XXX     path_args = self.path_args
            templates = {k: "(?P<{}>{})".format(k, v) for
                         k, v in self.path_args.items()}
            try:
                path = path_template.format(**templates)
            except KeyError as err:
                raise KeyError("undefined URI fragment"
                               " type `{}`".format(err.args[0]))

            # TODO metaclass for `__repr__` -- see `app.routes`
            class Route(controller, Resource):

                __doc__ = controller.__doc__
                __web__ = path
                handler = controller

            try:
                path = "/".join((self.prefix, path))
            except AttributeError:
                pass
            self.routes.append((path.strip("/"), Route))
            return Route
        return register

    def mount(self, *apps):
        """
        add an `application` to run when request path matches template

        """
        for app in apps:
            app.parent_app = self
            self.add_wrappers(*app.wrappers)
            path = app.mount_prefix.format(**{k: "(?P<{}>{})".format(k, v) for
                                              k, v in self.path_args.items()})
            self.mounts.append((path, app))

    def __repr__(self):
        return "<web.application: {}>".format(self.name)

    def try_socket(self):
        try:
            socket = Socket()
        except (OSError, NameError):
            return
        try:
            socket_handler = tx.request.controller.SOCKET
        except AttributeError:
            return
        # while True:
        socket_handler(socket)

    def __call__(self, environ, start_response):
        """
        WSGI callable

        """
        tx.request._contextualize(environ)
        tx.response._contextualize()
        try:
            tx.host._contextualize(tx.request.headers.host.name,
                                   tx.request.headers.host.port)
        except AttributeError:
            raise NotFound("no hostname provided")
        tx.user._contextualize(environ)
        tx.log._contextualize()
        tx.response.headers.content_type = "text/plain"
        # XXX tx.app_name = self.name
        response_hooks = []

        def exhaust_hooks():
            for hook in response_hooks:
                try:
                    next(hook)
                except StopIteration:
                    pass

        try:
            tx.request.controller = self.get_controller(tx.request.uri.path)

            for hook in self.wrappers:
                if not inspect.isgeneratorfunction(hook):
                    msg = "`{}.{}` is not an iterator, give it a yield"
                    modname = getattr(hook, "__module__", "??")
                    raise TypeError(msg.format(modname, hook.__name__))
                _hook = hook(tx.request.controller, self)
                next(_hook)
                response_hooks.append(_hook)

            self.try_socket()  # NOTE wrappers finish when socket disconnects
            tx.response.status = "200 OK"
            tx.response.headers.x_powered_by = "web.py"
            method = tx.request.method
            if method == "GET":
                forced_method = Form().get("_http_method")
                if forced_method:
                    method = forced_method.upper()

            # XXX hooks moved from here up to there

            tx.request.controller.get_data()
            body = self.get_handler(tx.request.controller, method)()
            if body is None:
                raise NoContent("")
            if isinstance(body, tuple) and isinstance(body[0], dict):
                body = best_match(body[0], *body[1:])
            tx.response.body = body
            # exhaust_hooks()  # TODO see below to pull hook exhaustion out
        except Status as exc:
            tx.response.status = str(exc)  # TODO exc.status
            tx.response.body = exc.body
            if exc.code == "201":
                tx.response.headers.location = exc.location
            if exc.code in ("301", "302", "303", "307", "308"):
                redirect_uri = str(tx.response.body)
                if redirect_uri.startswith(("http://", "https://")):
                    tx.response.headers.location = redirect_uri
                else:
                    tx.response.headers.location = \
                        urllib.parse.quote(redirect_uri)
            if exc.code == "405":
                tx.response.headers.allow = ", ".join(dict(exc.allowed))
        except Exception:
            # raise  # NOTE leave to bubble naturally -- debug in terminal
            tx.response.status = "500 Internal Server Error"
            if getattr(tx.user, "is_owner", False):
                body = self.view.error.debug(*sys.exc_info())
            else:
                body = self.view.error.internal()
                # XXX body = self.view.error.debug(*sys.exc_info())
            tx.response.body = body
            # TODO logging
            # if os.environ["WWW_DEBUG"]:
            #     raise
        exhaust_hooks()
        # try:
        #     # exhaust_hooks()
        #     pass
        # except:
        #     print("BREAK IN THE HOOK")  # TODO provide debug
        #     raise
        try:
            start_response(tx.response.status, tx.response.headers.wsgi)
        except OSError:  # websocket connection broken
            # TODO close websocket connection?
            return []
        if isinstance(tx.response.body, bytes):
            return [tx.response.body]
        # XXX elif isinstance(tx.response.body, dict):
        # XXX     return [bytes(yaml.dump(tx.response.body), "utf-8")]
        return [bytes(str(tx.response.body), "utf-8")]

    def get_controller(self, path):
        """

        """
        # TODO softcode `static/` reference
        if path.endswith("/") and not path.startswith("static/"):
            raise PermanentRedirect("/" + path.rstrip("/"))

        for mount, app in self.mounts:
            m = re.match(mount, path)
            if m:
                controller = app.get_controller(path[m.span()[1]:].lstrip("/"))
                for k, v in m.groupdict().items():
                    setattr(controller, k, v)
                return controller

        class ResourceNotFound(Resource):
            def GET(inner_self):
                error = self.view.error
                # TODO recursively ascend app ancestors
                # try:
                #     error = self.parent_app.view.error
                # except AttributeError:
                #     error = self.parent_app.parent_app.view.error
                raise NotFound(error.resource_not_found())

        def get_resource():
            for pattern, resource in self.routes:
                if isinstance(resource, str):
                    mod = __import__(resource.__module__)
                    resource = getattr(mod, resource)
                match = re.match(r"^{}$".format(pattern),
                                 urllib.parse.unquote(path))
                if match:
                    return resource, match
            return ResourceNotFound, None

        resource, match = get_resource()  # TODO for-else or try-block instead?
        unquoted = {k: urllib.parse.unquote(v) for k, v
                    in match.groupdict().items() if v} if match else {}
        return resource(**unquoted)

    def get_handler(self, controller, method="GET"):
        method = method.upper()
        try:
            handler = getattr(controller, method)
        except AttributeError:
            exc = MethodNotAllowed(self.view.error.method_not_allowed(method))
            exc.allowed = inspect.getmembers(controller, ismethod)
            raise exc
        return handler


class Context(threading.local):

    # TODO still needed?

    def __iter__(self):
        return iter(dir(self))

    def pop(self, attr):
        value = getattr(self, attr)
        delattr(self, attr)
        return value

    # def __contains__(self, attr):
    #     print(dir(self))
    #     return attr in dir(self)


class Host(Context):

    def _contextualize(self, name, port):
        self.name = name
        self.port = port


class User(Context):

    # TODO cookie/session

    def _contextualize(self, environ):
        address = environ.get("HTTP_X_FORWARDED_FOR",
                              environ.get("HTTP_X_REAL_IP",
                                          environ["REMOTE_ADDR"]))
        self.ip = address.partition(",")[0]
        self.language = "en-us"
        self.is_verified = False
        if environ.get("X-Verified", None) == "SUCCESS":
            self.is_verified = environ["X-DN"]
        # self.uri = None
        # self.roles = []


class Request(Context):

    def _contextualize(self, environ):
        self.uri = uri.parse(wsgiref.util.request_uri(environ,
                                                      include_query=1))
        self.method = environ.get("REQUEST_METHOD").upper()
        self.headers = headers.Headers()
        for name, value in environ.items():
            if name.startswith("HTTP_"):
                self.headers[name[5:]] = value
        if self.method in ("PROPFIND", "REPORT"):  # NOTE for WebDav
            self.body = lxml.etree.fromstring(environ["wsgi.input"].read())
        elif self.method in ("PUT",):
            self.body = environ["wsgi.input"].read()
        else:
            self.body = RequestBody(environ)

    def __getitem__(self, name):
        return self.body[name]  # XXX .value


class RequestBody:

    def __init__(self, environ):
        raw_data = environ["wsgi.input"].read()
        try:
            try:
                data = raw_data.decode("utf-8")
            except (AttributeError, UnicodeDecodeError):
                data = raw_data
            data = json.loads(data)
        except (json.decoder.JSONDecodeError, UnicodeDecodeError):
            try:
                environ["wsgi.input"] = io.BytesIO(raw_data)
                data = cgi.FieldStorage(fp=environ["wsgi.input"],
                                        environ=environ,
                                        keep_blank_values=True)
            except TypeError:
                try:
                    data = raw_data.decode("utf-8")
                except AttributeError:
                    data = raw_data
        self._data = data

    def items(self):
        return {k: self[k] for k in self._data.keys()}

    def get(self, name, default=None):
        return self._data.getfirst(name, default)

    def get_list(self, name):
        return self._data.getlist(name)

    def __getitem__(self, name):
        if self._data[name].filename:
            return self._data[name]
        return self._data.getfirst(name)


class Response(Context):

    def _contextualize(self):
        self.headers = headers.Headers()
        self.body = ""
        self.naked = False


class Log(Context):

    def _contextualize(self):
        self.messages = []

    def store(self, message):
        self.messages.append("{}:{}".format(time.time(), message))


class Transaction:

    host = Host()
    user = User()
    request = Request()
    response = Response()
    log = Log()

    @property
    def origin(self):
        return self.host.origin

    @property
    def owner(self):
        return self.host.owner

    @property
    def db(self):
        return self.host.db

    @property
    def kv(self):
        return self.host.kv

    @property
    def view(self):
        return self.host.view


tx = Transaction()


def sessions(**defaults):
    """
    returns an application hook for session handling using given redis `db`

    """
    def hook(handler, app):
        try:
            identifier = tx.request.headers["cookie"].morsels["session"]
        except KeyError:
            identifier = 0
        if ("sessions", identifier) not in kvdb:
            while True:
                secret = "{}{}{}{}".format(random.getrandbits(128),
                                           app.cfg["session"]["salt"],
                                           time.time(), tx.user.ip)
                secret_hash = hashlib.sha256(secret.encode("utf-8"))
                identifier = secret_hash.hexdigest()
                if kvdb["sessions", identifier].setnx("anonymous"):
                    break
        session_timeout = app.cfg["session"].get("timeout",
                                                 default_session_timeout)
        kvdb["sessions", identifier].expire(session_timeout)
        # FIXME user.session = kvdb.hgetall(kvdb(user.identifier, "data"))
        data = kvdb["sessions", identifier, "data"]
        if data:
            data = json.loads(str(data))
        else:
            data = Session(defaults)
        # XXX print(identifier, data)
        tx.user.session = data
        tx.user.identifier = identifier
        yield
        kvdb["sessions", identifier, "data"] = \
            JSONEncoder().encode(tx.user.session)
        kvdb["sessions", identifier, "data"].expire(session_timeout)
        # FIXME kvdb.delete("data")
        # FIXME if user.session:
        # FIXME     kvdb.hmset("data", **user.session)
        # XXX print(identifier, data, tx.user.identifier, tx.user.session)
        tx.response.headers["set-cookie"] = (("session", tx.user.identifier),)
        # ("Domain", tx.host.name))
    return hook


def require_auth(*roles):
    def decorate(func):
        def handler(*args, **kwargs):
            if tx.user.session["role"] not in roles:  # TODO role -> roles
                raise Unauthorized("no auth to access this resource")
            return func(*args, **kwargs)
        return handler
    return decorate


class Session(dict):

    def __getattr__(self, name):
        try:
            return self[name]
        except KeyError:
            return super(Session, self).__getattr__(name)

    def __setattr__(self, name, value):
        self[name] = value


class JSONEncoder(json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, uri.URI):
            return str(obj)
        if isinstance(obj, datetime.datetime):
            return obj.timestamp()
        return json.JSONEncoder.default(self, obj)


displays = []


class Browser:

    By = By
    EC = EC

    def __init__(self, width=1280, height=1024):
        if not len(displays):
            display = pyvirtualdisplay.Display(visible=0, size=(width, 500))
            display.start()
            displays.append(display)
        self.browser = webdriver.Firefox()
        self._width = width
        self._height = height
        self._update_window()

    @property
    def width(self):
        return self._width

    @width.setter
    def width(self, value):
        self._width = value
        self._update_window()

    @property
    def height(self):
        return self._height

    @height.setter
    def height(self, value):
        self._height = value
        self._update_window()

    def _update_window(self):
        self.browser.set_window_size(self._width, self._height)

    def go(self, *args):
        if len(args) == 1:
            url = args[0]
        elif len(args) == 2:
            url = "/".join(args)
        self.browser.get(str(uri.parse(url)))

    def wait(self, *conditions, duration=20):
        for condition in conditions:
            time.sleep(.1)
            wait = WebDriverWait(self.browser, duration)
            wait.until(condition)

    def cssel(self, selector):
        return self.browser.find_element_by_css_selector(selector)

    def cssels(self, selector):
        return self.browser.find_elements_by_css_selector(selector)

    def action(self):
        return ActionChains(self.browser)

    def shot(self, path):
        # TODO take in pieces & stitch together -- using way too much memory
        # self._height = self.browser.execute_script("return document.body."
        #                                            "scrollHeight;") + 100
        # self._update_window()
        self.browser.get_screenshot_as_file(str(path) + ".png")

    def quit(self):
        try:
            self.browser.quit()
        except selenium.common.exceptions.WebDriverException:
            pass
        if displays:
            try:
                displays[0].stop()
            except KeyError:  # raising during multi-user testing
                pass

    def __getattr__(self, attr):
        return getattr(self.browser, attr)


browser = Browser


# def shot(name, description):  # XXX , *browsers):
#     test_case = inspect.stack()[1].function
#     global shot_counter
#     shot_id = "{:03}".format(shot_counter)
#     dashed_name = name.replace(" ", "-")
#     for user, browser in sorted(browsers.items()):
#         shot_filename = "{}-{}-{}.png".format(shot_id, user, dashed_name)
#         height = browser.execute_script("return document.body.scrollHeight;")
#         browser.set_window_size(browser_width, height + 100)
#         browser.get_screenshot_as_file(str(build_dir / "features" /
#                                            shot_filename))
#     features.append((test_case, shot_id, dashed_name, name, description))
#     # XXX , shot_filename, [user for u in browsers.keys()]))
#     shot_counter += 1