my eye

request.py

Raw

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
"""

"""

# XXX import configparser
# XXX import os
import base64
import re

import httpagentparser
import mimeparse

from . import util

__all__ = [
    "Accept",
    "AcceptCharset",
    "AcceptEncoding",
    "AcceptLanguage",
    "Authorization",
    "Cookie",
    "Expect",
    "From",
    "Host",
    "IfMatch",
    "IfModifiedSince",
    "IfNoneMatch",
    "IfRange",
    "IfUnmodifiedSince",
    "KeepAlive",
    "MaxForwards",
    "ProxyAuthorization",
    "Range",
    "Referer",
    "TE",
    "UserAgent",
    "XBehavioralAdOptOut",
    "XDoNotTrack",
    "XForwardedFor",
    "XRequestedWith",
]


class Request(util.Header):

    """"""


class _Accept(Request):

    """"""

    def parse(self):
        acceptables = []
        noq = 1
        for acceptable in self.header.split(","):
            value, _, params = acceptable.strip().lower().partition(";")
            parameters = {}
            if params.strip():
                for param in params.split(";"):
                    k, _, v = param.partition("=")
                    parameters[k.strip()] = v.strip()
            noq -= 0.00001
            q = float(parameters.pop("q", noq))
            acceptables.append((q, (value.strip(), parameters)))
        self.acceptables = [
            self.type(a[0], _q, **a[1]) for _q, a in list(reversed(sorted(acceptables)))
        ]

    class _Acceptable:

        """"""

        def __init__(self, value, quality, **params):
            self.value = value.lower()
            self.quality = quality
            self.params = {k.lower(): v.lower() for k, v in params.items()}
            self.parse()

        def __repr__(self):
            return repr(self.value)


class Accept(_Accept):

    """
    The "Accept" request-header field can be used by user agents to specify
    response media types that are acceptable. Accept header fields can be
    used to indicate that the request is specifically limited to a small
    set of desired types, as in the case of a request for an in-line image.

        >>> header = '''text/*;q=0.3, text/html;q=0.7, text/html;level=1,
        ...             text/html;level=2;q=0.4, */*;q=0.5'''
        >>> accept = Accept(header)
        >>> accept.acceptables
        ['text/html', 'text/html', '*/*', 'text/html', 'text/*']
        >>> type(accept.acceptables[0])
        <class 'web.headers.request.Accept.Media'>

    # TODO >>> accept.best_match(["image/png", "text/plain", "text/html"])
    # TODO 'text/html'

    """

    def best_match(self, supported):
        return mimeparse.best_match(supported, self.header)

    class Media(_Accept._Acceptable):

        """"""

        def parse(self):
            self.canonical = self.value

    type = Media

    _meta = "TYPE"


class AcceptCharset(_Accept):

    """
    The "Accept-Charset" request-header field can be used by user agents
    to indicate what response character sets are acceptable. This field
    allows clients capable of understanding more comprehensive or
    special-purpose character sets to signal that capability to a server
    which is capable of representing documents in those character sets.

    """

    class Charset(_Accept._Acceptable):

        """"""

        def parse(self):
            self.canonical = self.value

    type = Charset

    _meta = "CHARSET"


class AcceptEncoding(_Accept):

    """"""

    # def best_match(self, supported):
    #   acceptable = [p.lower().strip() for p in self.header.split(",")]
    #   for encoding in supported:
    #     if encoding in acceptable:
    #       return encoding
    #   raise http.NotAcceptable("asdf")

    class Encoding(_Accept._Acceptable):

        """"""

        def parse(self):
            self.canonical = self.value

    type = Encoding

    _meta = "ENCODING"


class AcceptLanguage(_Accept):

    """"""

    class Language(_Accept._Acceptable):

        """"""

        def parse(self):
            self.canonical = self.value

    type = Language

    _meta = "LANGUAGE"


class Authorization(Request):

    """"""

    def __str__(self):
        if self.header.startswith("Basic "):
            return self.basic
        elif self.header.startswith("Bearer "):
            return self.bearer

    @property
    def basic(self):
        return base64.b64decode(self.header.removeprefix("Basic ")).decode()

    @property
    def bearer(self):
        return self.header.removeprefix("Bearer ")

    _meta = ""


class Cookie(Request):

    """"""

    def parse(self):
        self.morsels = {}
        for morsel in self.header.split(";"):
            k, _, v = morsel.lstrip().partition("=")
            self.morsels[k] = v

    def get(self, key, default=None):
        return self.morsels.get(key, default)


class Expect(Request):

    """"""


class From(Request):

    """"""


class Host(Request):

    """"""

    # TODO support for IP addresses and lazy determination

    def parse(self):
        self.header = self.header.lower()
        self.name, _, port = self.header.partition(":")
        if port is None:
            port = "80"
        self.port = port

    @property
    def is_hostname(self):
        """"""
        if len(self.name) > 255:
            return False
        allowed = re.compile(r"^(?!-)[a-z\d-]{1,63}(?<!-)$")  # TODO raw ok?
        return all(allowed.match(l) for l in self.name.strip(".").split("."))


class IfMatch(Request):

    """"""


class IfModifiedSince(Request):

    """"""


class IfNoneMatch(Request):

    """"""


class IfRange(Request):

    """"""


class IfUnmodifiedSince(Request):

    """"""


class KeepAlive(Request):

    """"""


class MaxForwards(Request):

    """"""


class ProxyAuthorization(Request):

    """"""


class Range(Request):

    """"""


class Referer(Request):

    """"""


class TE(Request):

    """"""


class UserAgent(Request):

    """"""

    def parse(self):
        self.features = httpagentparser.simple_detect(self.header)

    # _agents = {}
    # _re_agents = {}
    # _defaults = None

    # def parse(self):
    #     if not self._agents:
    #         self._initialize_browscap()
    #     possibles = list(name for pattern, name in self._re_agents.items()
    #                      if pattern.match(self.header))
    #     self.features = self._defaults
    #     if possibles:
    #         self.features = self._agents[max(possibles,
    #                                          key=lambda n: len(n))]

    # @property
    # def is_js_compatible(self):
    #     return self.features["javascript"] == "true"

    # @classmethod
    # def _initialize_browscap(cls, path=None):
    #     if path is None:
    #         path = cls._get_filename()
    #     browscap = configparser.ConfigParser()
    #     if not browscap.read(path):
    #         return
    #     browscap.remove_section("GJK_Browscap_Version")
    #     defaults = dict(browscap.items("DefaultProperties"))
    #     browscap.remove_section("DefaultProperties")
    #     browscap.remove_section("*")  # TODO fall back to default browser
    #     families = {}
    #     for sect in browscap.sections():
    #         if browscap.get(sect, "Parent") == "DefaultProperties":
    #             families[sect] = dict(defaults, **dict(browscap.items(sect)))
    #             browscap.remove_section(sect)
    #     for sect in browscap.sections():
    #         parent = browscap.get(sect, "Parent")
    #         cls._agents[sect] = dict(families[parent],
    #                                  **dict(browscap.items(sect)))
    #         pattern = sect
    #         for unsafe in "().-":
    #             pattern = pattern.replace(unsafe, "\\" + unsafe)
    #         pattern = pattern.replace("?", ".").replace("*", ".*?")
    #         cls._re_agents[re.compile(r"^" + pattern + r"$")] = sect
    #     cls._defaults = defaults

    # @staticmethod
    # def _get_filename():
    #     return os.path.join(os.path.dirname(__file__), "browscap.ini")

    # @staticmethod
    # def _update_browscap():
    #     import httplib2
    #     agent = httplib2.Http()
    #     print("Updating browscap file..")

    #     uri = "http://browsers.garykeith.com/stream.asp?BrowsCapINI"
    #     print("Downloading from:", uri)
    #     content = agent.request(uri)[1]

    #     path = UserAgent._get_filename()
    #     print("Saving to:", path)
    #     with open(path, "w") as file:
    #         file.write(content)

    #     print("Success.")


# XXX UserAgent._initialize_browscap()


class XBehavioralAdOptOut(Request):

    """"""

    def __repr__(self):
        return repr(bool(self.header))


class XDoNotTrack(Request):

    """"""

    def __repr__(self):
        return repr(bool(self.header))


class XForwardedFor(Request):

    """"""


class XRequestedWith(Request):

    """"""

    @property
    def ajax(self):
        return self.header == "XMLHttpRequest"

    def __repr__(self):
        return repr(self.header)