-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathutil.py
2029 lines (1584 loc) · 59.3 KB
/
util.py
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
"""Misc utilities.
Should not depend on App Engine API or SDK packages.
"""
import calendar
import collections
from collections.abc import Iterator
import contextlib
import base64
from datetime import datetime, timedelta, timezone
import http.client
import humanize
import inspect
import logging
import mimetypes
import numbers
import os
import re
import socket
import ssl
import string
import sys
import threading
import traceback
import urllib.error, urllib.parse, urllib.request
from urllib.parse import urlparse
from xml.sax import saxutils
from cachetools import cached, TTLCache
from domain2idna import domain2idna
from flask import abort
try:
import ujson
json = ujson
except ImportError:
ujson = None
import json
# These are used in interpret_http_exception() and is_connection_failure(). They
# use dependencies that we may or may not have, so degrade gracefully if they're
# not available.
try:
import apiclient
import apiclient.errors
except ImportError:
apiclient = None
try:
from oauth2client.client import AccessTokenRefreshError
except ImportError:
AccessTokenRefreshError = None
try:
import requests
except ImportError:
requests = None
try:
import urllib3
except ImportError:
if requests:
try:
from requests.packages import urllib3
except ImportError:
urllib3 = None
try:
import webob
from webob import exc
# webob doesn't know about HTTP 429 for rate limiting. Tell it.
try:
webob.util.status_reasons[429] = 'Rate limited' # webob <= 0.9
except AttributeError:
webob.status_reasons[429] = 'Rate limited' # webob >= 1.1.1
except ImportError:
exc = None
try:
import werkzeug
import werkzeug.exceptions
except ImportError:
werkzeug = None
# Used in parse_html() and friends.
try:
import bs4
except ImportError:
bs4 = None
try:
import mf2py
except ImportError:
mf2py = None
try:
import prawcore
except ImportError:
prawcore = None
try:
import tumblpy
except ImportError:
tumblpy = None
try:
import tweepy
except ImportError:
tweepy = None
logger = logging.getLogger(__name__)
# set with set_user_agent()
user_agent = 'webutil (https://github.com/snarfed/webutil)'
EPOCH = datetime.fromtimestamp(0, timezone.utc)
EPOCH_ISO = EPOCH.isoformat()
# from https://stackoverflow.com/a/53140944/186123
ISO8601_DURATION_RE = re.compile(
r'^ *P(?!$)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)? *$')
# default HTTP request timeout
HTTP_TIMEOUT = 15
socket.setdefaulttimeout(HTTP_TIMEOUT)
# monkey-patch socket.getdefaulttimeout() because it often gets reset, e.g. by
# socket.setblocking() and maybe other operations.
# http://stackoverflow.com/a/8465202/186123
socket.getdefaulttimeout = lambda: HTTP_TIMEOUT
# Average HTML page size as of 2015-10-15 is 56K, so this is very generous and
# conservative.
# http://www.sitepoint.com/average-page-weight-increases-15-2014/
# http://httparchive.org/interesting.php#bytesperpage
MAX_HTTP_RESPONSE_SIZE = 1000000 # 1MB
HTTP_RESPONSE_TOO_BIG_STATUS_CODE = 422 # Unprocessable Entity
FOLLOW_REDIRECTS_CACHE_TIME = 60 * 60 * 24 # 1d expiration
follow_redirects_cache = TTLCache(1000, FOLLOW_REDIRECTS_CACHE_TIME)
follow_redirects_cache_lock = threading.RLock()
# https://en.wikipedia.org/wiki/Top-level_domain#Reserved_domains
# Currently used in granary.source.Source.original_post_discovery, not here.
RESERVED_TLDS = {
'corp',
'example',
'internal',
'invalid',
'onion',
'test',
}
LOCAL_TLDS = {
'local',
'localhost',
}
"""Global config, string parser nae for BeautifulSoup to use, e.g. 'lxml'.
May be set at runtime.
https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser
"""
beautifulsoup_parser = None
# Regexps for domains, hostnames, and URLs.
#
# Based on kylewm's from redwind:
# https://github.com/snarfed/bridgy/issues/209#issuecomment-47583528
# https://github.com/kylewm/redwind/blob/863989d48b97a85a1c1a92c6d79753d2fbb70775/redwind/util.py#L39
#
# I used to use a more complicated regexp based on
# https://github.com/silas/huck/blob/master/huck/utils.py#L59 , but i kept
# finding new input strings that would make it hang the regexp engine.
#
# more complicated alternatives:
# http://stackoverflow.com/questions/720113#comment23297770_2102648
# https://daringfireball.net/2010/07/improved_regex_for_matching_urls
#
# list of TLDs:
# https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains#ICANN-era_generic_top-level_domains
#
# Allows emoji and other unicode chars in all domain labels *except* TLDs.
# TODO: support IDN TLDs:
# https://en.wikipedia.org/wiki/Top-level_domain#Internationalized_country_code_TLDs
# https://www.iana.org/domains/root/db
#
# TODO: fix bug in LINK_RE that makes it miss emoji domain links without scheme,
# eg '☕⊙.ws'. bug is that the \b at the beginning of SCHEME_RE doesn't apply to
# emoji, since they're not word-constituent characters, and that the '?' added
# in LINK_RE only applies to the parenthesized group in SCHEME_RE, not the \b.
# I tried changing \b to '(?:^|[\s%s])' % PUNCT, but that broke other things.
PUNCT = string.punctuation.replace('-', '').replace('.', '')
SCHEME_RE = r'\b(?:[a-z]{3,9}:/{1,3})'
HOST_RE = r'(?:[^\s%s])+(?::\d{2,6})?' % PUNCT
DOMAIN_RE = r'(?:[^\s.%s]+\.)+[a-z]{2,}(?::\d{2,6})?' % PUNCT
PATH_QUERY_RE = r'(?:(?:/[\w/.\-_~.;:%?@$#&()=+]*)|\b)'
URL_RE = re.compile(SCHEME_RE + HOST_RE + PATH_QUERY_RE, # scheme required
re.UNICODE | re.IGNORECASE)
LINK_RE = re.compile(SCHEME_RE + '?' + DOMAIN_RE + PATH_QUERY_RE, # scheme optional
re.UNICODE | re.IGNORECASE)
class Struct(object):
"""A generic class that initializes its attributes from constructor kwargs."""
def __init__(self, **kwargs):
vars(self).update(**kwargs)
class CacheDict(dict):
"""A dict that also implements memcache's get_multi() and set_multi() methods.
Useful as a simple in memory replacement for App Engine's memcache API for
e.g. get_activities_response() in granary.
"""
def get_multi(self, keys):
keys = set(keys)
return {k: v for k, v in list(self.items()) if k in keys}
def set(self, key, val, **kwargs):
self[key] = val
def set_multi(self, updates, **kwargs):
super(CacheDict, self).update(updates)
def to_xml(value):
"""Renders a dict (usually from JSON) as an XML snippet."""
if isinstance(value, dict):
if not value:
return ''
elems = []
for key, vals in sorted(value.items()):
if not isinstance(vals, (list, tuple)):
vals = [vals]
elems.extend(f'<{key}>{to_xml(val)}</{key}>' for val in vals)
return '\n' + '\n'.join(elems) + '\n'
else:
if value is None:
value = ''
return str(value)
def trim_nulls(value, ignore=()):
"""Recursively removes dict and list elements with None or empty values.
Args:
value: dict or list
ignore: optional sequence of keys to allow to have None/empty values
"""
NULLS = (None, {}, [], (), '', set(), frozenset())
if isinstance(value, dict):
trimmed = {k: trim_nulls(v, ignore=ignore) for k, v in value.items()}
return {k: v for k, v in trimmed.items() if k in ignore or v not in NULLS}
elif (isinstance(value, (tuple, list, set, frozenset, Iterator)) or
inspect.isgenerator(value)):
trimmed = [trim_nulls(v, ignore=ignore) for v in value]
ret = (v for v in trimmed if v if v not in NULLS)
if isinstance(value, Iterator) or inspect.isgenerator(value):
return ret
else:
return type(value)(list(ret))
else:
return value
def uniquify(input):
"""Returns a list with duplicate items removed.
Like list(set(...)), but preserves order.
"""
if not input:
return []
return list(collections.OrderedDict([x, 0] for x in input).keys())
def get_list(obj, key):
"""Returns a value from a dict as a list.
If the value is a list or tuple, it's converted to a list. If it's something
else, it's returned as a single-element list. If the key doesn't exist,
returns [].
"""
val = obj.get(key, [])
return (list(val) if isinstance(val, (list, tuple, set))
else [val] if val
else [])
def pop_list(obj, key):
"""Like get_list(), but also removes the item."""
val = get_list(obj, key)
obj.pop(key, None)
return val
def encode(obj, encoding='utf-8'):
"""Character encodes all unicode strings in a collection, recursively.
Args:
obj: list, tuple, dict, set, or primitive
encoding: string character encoding
Returns:
sequence or dict version of obj with all unicode strings encoded
"""
if isinstance(obj, str):
return obj.encode(encoding)
elif isinstance(obj, tuple):
return tuple(encode(v) for v in obj)
elif isinstance(obj, list):
return [encode(v) for v in obj]
elif isinstance(obj, set):
return {encode(v) for v in obj}
elif isinstance(obj, dict):
return {encode(k): encode(v) for k, v in obj.items()}
else:
return obj
def get_first(obj, key, default=None):
"""Returns the first element of a dict value.
If the value is a list or tuple, returns the first value. If it's something
else, returns the value itself. If the key doesn't exist, returns None.
"""
val = obj.get(key)
if not val:
return default
return val[0] if isinstance(val, (list, tuple)) else val
def get_url(val, key=None):
"""Returns val['url'] if val is a dict, otherwise val.
If key is not None, looks in val[key] instead of val.
"""
if key is not None:
val = get_first(val, key)
return val.get('url') if isinstance(val, dict) else val
def get_urls(obj, key, inner_key=None):
"""Returns elem['url'] if dict, otherwise elem, for each elem in obj[key].
If inner_key is provided, the returned values are elem[inner_key]['url'].
"""
return dedupe_urls(get_url(elem, key=inner_key) for elem in get_list(obj, key))
def tag_uri(domain, name, year=None):
"""Returns a tag URI string for the given domain and name.
Example return value: 'tag:twitter.com,2012:snarfed_org/172417043893731329'
Background on tag URIs: http://taguri.org/
"""
year = f',{year}' if year else ''
return f'tag:{domain}{year}:{name}'
_TAG_URI_RE = re.compile(r'tag:([^,]+)(?:,\d+)?:(.+)$')
def parse_tag_uri(uri):
"""Returns the domain and name in a tag URI string.
Inverse of :func:`tag_uri()`.
Returns:
(string domain, string name) tuple, or None if the tag URI couldn't
be parsed
"""
match = _TAG_URI_RE.match(uri)
return match.groups() if match else None
def parse_acct_uri(uri, hosts=None):
"""Parses acct: URIs of the form acct:[email protected] .
Background: http://hueniverse.com/2009/08/making-the-case-for-a-new-acct-uri-scheme/
Args:
uri: string
hosts: sequence of allowed hosts (usually domains). None means allow all.
Returns:
(username, host) tuple
Raises: ValueError if the uri is invalid or the host isn't allowed.
"""
parsed = urlparse(uri)
if parsed.scheme and parsed.scheme != 'acct':
raise ValueError(f'Acct URI {uri} has unsupported scheme: {parsed.scheme}')
try:
username, host = parsed.path.split('@')
assert host
except (ValueError, AssertionError):
raise ValueError(f'Bad acct URI: {uri}')
if hosts is not None and host not in hosts:
raise ValueError(f'Acct URI {uri} has unsupported host {host}; expected {hosts!r}.')
return username, host
def favicon_for_url(url):
return f'http://{urlparse(url).netloc}/favicon.ico'
FULL_HOST_RE = re.compile(HOST_RE + '$')
def domain_from_link(url, minimize=True):
"""Extracts and returns the meaningful domain from a URL.
Args:
url: string
minimize: bool; if true, strips www., mobile., and m. subdomains from the
beginning of the domain
Returns:
string
"""
try:
parsed = urlparse(url)
if not parsed.hostname and '//' not in url:
parsed = urlparse('http://' + url)
except ValueError:
return None
domain = parsed.hostname
if domain and minimize:
for subdomain in ('www.', 'mobile.', 'm.'):
if domain.startswith(subdomain):
domain = domain[len(subdomain):]
if domain and FULL_HOST_RE.match(domain):
return domain
return None
def domain_or_parent_in(input, domains):
"""Returns True if an input domain or its parent is in a set of domains.
Examples:
* foo, [] => False
* foo, [foo] => True
* foo.bar.com, [bar.com] => True
* foobar.com, [bar.com] => False
* foo.bar.com, [.bar.com] => True
* foo.bar.com, [fux.bar.com] => False
* bar.com, [fux.bar.com] => False
Args:
input: string domain
domains: sequence of string domains
Returns:
boolean
"""
if not input or not domains:
return False
elif input in domains:
return True
for domain in domains:
if not domain.startswith('.'):
domain = '.' + domain
if input.endswith(domain):
return True
return False
def update_scheme(url, request):
"""Returns a modified URL with the current request's scheme.
Useful for converting URLs to https if and only if the current request itself
is being served over https.
Args:
url: string
request: :class:`flask.Request` or :class:`webob.Request`
Returns: string, url
"""
return urllib.parse.urlunparse((request.scheme,) + urlparse(url)[1:])
def schemeless(url, slashes=True):
"""Strips the scheme (e.g. 'https:') from a URL.
Args:
url: string
leading_slashes: if False, also strips leading slashes and trailing slash,
e.g. 'http://example.com/' becomes 'example.com'
Returns:
string URL
"""
url = urllib.parse.urlunparse(('',) + urlparse(url)[1:])
if not slashes:
url = url.strip('/')
return url
def fragmentless(url):
"""Strips the fragment (e.g. '#foo') from a URL.
Args:
url: string
Returns:
string URL
"""
return urllib.parse.urlunparse(urlparse(url)[:5] + ('',))
def clean_url(url):
"""Removes transient query params (e.g. utm_*) from a URL.
The utm_* (Urchin Tracking Metrics?) params come from Google Analytics.
https://support.google.com/analytics/answer/1033867
The source=rss-... params are on all links in Medium's RSS feeds.
Args:
url: string
Returns:
string, the cleaned url, or None if it can't be parsed
"""
if not url:
return url
utm_params = set(('utm_campaign', 'utm_content', 'utm_medium', 'utm_source',
'utm_term'))
try:
parts = list(urlparse(url))
except (AttributeError, TypeError, ValueError):
return None
query = urllib.parse.unquote_plus(parts[4])
params = [(name, value) for name, value in urllib.parse.parse_qsl(query)
if name not in utm_params
and not (name == 'source' and value.startswith('rss-'))]
parts[4] = urllib.parse.urlencode(params)
return urllib.parse.urlunparse(parts)
def quote_path(url):
"""Quotes (URL-encodes) just the path part of a URL.
Args:
url: string
Returns:
string, the quoted url, or None if it can't be parsed
"""
try:
parts = list(urlparse(url))
except (AttributeError, TypeError, ValueError):
return None
parts[2] = urllib.parse.quote(parts[2])
return urllib.parse.urlunparse(parts)
def base_url(url):
"""Returns the base of a given URL.
For example, returns 'http://site/posts/' for 'http://site/posts/123'.
Args:
url: string
"""
return urllib.parse.urljoin(url, ' ')[:-1] if url else None
def extract_links(text):
"""Returns a list of unique string URLs in the given text.
URLs in the returned list are in the order they first appear in the text.
"""
if not text:
return []
return uniquify(tokenize_links(text, skip_html_links=False, require_scheme=True)[0])
def tokenize_links(text, skip_bare_cc_tlds=False, skip_html_links=True,
require_scheme=False):
"""Splits text into link and non-link text.
Args:
text: string to linkify
skip_bare_cc_tlds: boolean, whether to skip links of the form
[domain].[2-letter TLD] with no schema and no path
skip_html_links: boolean, whether to skip links in HTML <a> tags (
both href and text)
require_scheme: boolean, whether to require scheme (eg http:// )
Returns:
a tuple containing two lists of strings, a list of links and list of
non-link text. Roughly equivalent to the output of re.findall and re.split,
with some post-processing.
"""
regexp = URL_RE if require_scheme else LINK_RE
links = regexp.findall(text)
splits = regexp.split(text)
for ii in range(len(links)):
# trim trailing punctuation from links
link = links[ii]
jj = len(link) - 1
while (jj >= 0 and link[jj] in '.!?,;:)'
# allow 1 () pair
and (link[jj] != ')' or '(' not in link)):
jj -= 1
links[ii] = link[:jj + 1]
splits[ii + 1] = link[jj + 1:] + splits[ii + 1]
link = links[ii]
# avoid double linking by looking at preceeding 2 chars
if ((skip_html_links and (splits[ii].strip().endswith('="')
or splits[ii].strip().endswith("='")
or splits[ii + 1].strip().startswith('</a')))
# skip domains with 2-letter TLDs and no schema or path
or (skip_bare_cc_tlds and re.match(r'[^\s%s]+\.[a-z]{2}$' % PUNCT, link))):
# collapse link into before text
splits[ii] = splits[ii] + links[ii]
links[ii] = None
continue
# clean up the output by collapsing removed links
ii = len(links) - 1
while ii >= 0:
if links[ii] is None:
splits[ii] = splits[ii] + splits[ii + 1]
del links[ii]
del splits[ii + 1]
ii -= 1
return links, splits
def linkify(text, pretty=False, skip_bare_cc_tlds=False, **kwargs):
"""Adds HTML links to URLs in the given plain text.
For example: ``linkify('Hello http://tornadoweb.org!')`` would return
'Hello <a href="http://tornadoweb.org">http://tornadoweb.org</a>!'
Ignores URLs that are inside HTML links, ie anchor tags that look like
<a href="..."> .
Args:
text: string, input
pretty: if True, uses :func:`pretty_link()` for link text
skip_bare_cc_tlds: boolean, whether to skip links of the form
[domain].[2-letter TLD] with no schema and no path
Returns:
string, linkified input
"""
links, splits = tokenize_links(text, skip_bare_cc_tlds)
result = []
for ii in range(len(links)):
result.append(splits[ii])
url = href = links[ii]
if not href.startswith('http://') and not href.startswith('https://'):
href = 'http://' + href
if pretty:
result.append(pretty_link(href, **kwargs))
else:
result.append(f'<a href="{href}">{url}</a>')
result.append(splits[-1])
return ''.join(result)
def pretty_link(url, text=None, keep_host=True, glyphicon=None, attrs=None,
new_tab=False, max_length=None):
"""Renders a pretty, short HTML link to a URL.
If text is not provided, the link text is the URL without the leading
http(s)://[www.], ellipsized at the end if necessary. URL escape characters
and UTF-8 are decoded.
The default maximum length follow's Twitter's rules: full domain plus 15
characters of path (including leading slash).
* https://dev.twitter.com/docs/tco-link-wrapper/faq
* https://dev.twitter.com/docs/counting-characters
Args:
url: string
text: string, optional
keep_host: if False, remove the host from the link text
glyphicon: string glyphicon to render after the link text, if provided.
Details: http://glyphicons.com/
attrs: dict of attributes => values to include in the a tag. optional
new_tab: boolean, include target="_blank" if True
max_length: int, max link text length in characters. ellipsized beyond this.
Returns:
unicode string HTML snippet with <a> tag
"""
if text:
if max_length is None:
max_length = 30
else:
# use shortened version of URL as link text
parsed = urlparse(url)
text = url[len(parsed.scheme) + 3:] # strip scheme and ://
host_len = len(parsed.netloc)
if (keep_host and not parsed.params and not parsed.query and not parsed.fragment):
text = text.strip('/') # drop trailing slash
elif not keep_host:
text = text[host_len + 1:]
host_len = 0
if text.startswith('www.'):
text = text[4:]
host_len -= 4
if max_length is None:
max_length = host_len + 15
try:
text = urllib.parse.unquote_plus(str(text))
except ValueError:
pass
if max_length and len(text) > max_length:
text = text[:max_length] + '...'
escaped_text = saxutils.escape(text)
if glyphicon is not None:
escaped_text += f' <span class="glyphicon glyphicon-{glyphicon}"></span>'
attr_str = (''.join(f'{attr}="{val}" ' for attr, val in list(attrs.items()))
if attrs else '')
target = 'target="_blank" ' if new_tab else ''
return ('<a %s%shref="%s">%s</a>' %
(attr_str, target,
# not using urllib.parse.quote because it quotes a ton of chars we
# want to pass through, including most unicode chars
url.replace('<', '%3C').replace('>', '%3E'),
escaped_text))
TIMEZONE_OFFSET_RE = re.compile(r'[+-]\d{2}:?\d{2}$')
def parse_iso8601(val):
"""Parses an ISO 8601 or RFC 3339 date/time string and returns a datetime.
Time zone designator is optional. If present, the returned datetime will be
time zone aware.
Args:
val: string ISO 8601 or RFC 3339, e.g. '2012-07-23T05:54:49+00:00'
Returns:
datetime
"""
# grr, this would be way easier if strptime supported %z, but evidently that
# was only added in python 3.2.
# http://stackoverflow.com/questions/9959778/is-there-a-wildcard-format-directive-for-strptime
assert val
val = val.replace('T', ' ')
tz = None
zone = TIMEZONE_OFFSET_RE.search(val)
if zone:
offset_str = zone.group()
val = val[:-len(offset_str)]
offset = (datetime.strptime(offset_str[1:].replace(':', ''), '%H%M') -
datetime.strptime('', ''))
if offset_str[0] == '-':
offset = -offset
tz = timezone(offset)
elif val[-1] == 'Z':
val = val[:-1]
tz = timezone.utc
# fractional seconds are optional. add them if they're not already there to
# make strptime parsing below easier.
if '.' not in val:
val += '.0'
return datetime.strptime(val, '%Y-%m-%d %H:%M:%S.%f').replace(tzinfo=tz)
def parse_iso8601_duration(input):
"""Parses an ISO 8601 duration.
Note: converts months to 30 days each. (ISO 8601 doesn't seem to define the
number of days in a month. Background:
https://stackoverflow.com/a/29458514/186123 )
Args:
input: string ISO 8601 duration, e.g. 'P3Y6M4DT12H30M5S'
https://en.wikipedia.org/wiki/ISO_8601#Durations
Returns:
:class:`datetime.timedelta`, or None if input cannot be parsed as an ISO
8601 duration
"""
if not input:
return None
match = ISO8601_DURATION_RE.match(input)
if not match:
return None
def g(i):
val = match.group(i)
return int(val[:-1]) if val else 0
return timedelta(weeks=g(3),
days=365 * g(1) + 30 * g(2) + g(4),
hours=g(6), minutes=g(7), seconds=g(8))
def to_iso8601_duration(input):
"""Converts a timedelta to an ISO 8601 duration.
Returns a fairly strict format: 'PnMTnS'. Fractional seconds are silently
dropped.
Args:
input: :class:`datetime.timedelta`
https://en.wikipedia.org/wiki/ISO_8601#Durations
Returns:
string ISO 8601 duration, e.g. 'P3DT4S'
Raises: :class:`TypeError` if delta is not a :class:`datetime.timedelta`
"""
if not isinstance(input, timedelta):
raise TypeError(f'Expected timedelta, got {input.__class__}')
return f'P{input.days}DT{input.seconds}S'
def maybe_iso8601_to_rfc3339(input):
"""Tries to convert an ISO 8601 date/time string to RFC 3339.
The formats are similar, but not identical, eg. RFC 3339 includes a colon in
the timezone offset at the end (+0000 instead of +00:00), but ISO 8601
doesn't.
If the input can't be parsed as ISO 8601, it's silently returned, unchanged!
http://www.rfc-editor.org/rfc/rfc3339.txt
"""
try:
return parse_iso8601(input).isoformat('T')
except (AssertionError, ValueError, TypeError):
return input
def maybe_timestamp_to_rfc3339(input):
"""Tries to convert a string or int UNIX timestamp to RFC 3339.
Assumes UNIX timestamps are always UTC. (They're generally supposed to be.)
"""
try:
dt = datetime.utcfromtimestamp(float(input)).replace(tzinfo=timezone.utc)
return dt.isoformat('T', 'milliseconds' if dt.microsecond else 'seconds')
except (ValueError, TypeError):
return input
def maybe_timestamp_to_iso8601(input):
"""Tries to convert a string or int UNIX timestamp to ISO 8601.
Assumes UNIX timestamps are always UTC. (They're generally supposed to be.)
"""
ret = maybe_timestamp_to_rfc3339(input)
return ret if ret == input else ret.replace('+00:00', 'Z')
def to_utc_timestamp(input):
"""Converts a datetime to a float POSIX timestamp (seconds since epoch)."""
if not input:
return None
timetuple = list(input.timetuple())
# timetuple() usually strips microsecond
timetuple[5] += input.microsecond / 1000000
return calendar.timegm(timetuple)
def as_utc(input):
"""Converts a timezone-aware datetime to a naive UTC datetime.
If input is timezone-naive, it's returned as is.
Doesn't support DST!
"""
if not input.tzinfo:
return input
utc = input - input.tzinfo.utcoffset(None)
return utc.replace(tzinfo=None)
def naturaltime(val, when=None, **kwargs):
"""Wrapper for humanize.naturaltime that handles timezone-aware datetimes.
...since humanize currently doesn't. :(
https://github.com/python-humanize/humanize/issues/17
"""
val = val.replace(tzinfo=None)
if when is not None:
when = when.replace(tzinfo=None)
return humanize.naturaltime(val, when=when, **kwargs)
def ellipsize(str, words=14, chars=140):
"""Truncates and ellipsizes str if it's longer than words or chars.
Words are simply tokenized on whitespace, nothing smart.
"""
split = str.split()
if len(split) <= words and len(str) <= chars:
return str
return ' '.join(split[:words])[:chars - 3] + '...'
def add_query_params(url, params):
"""Adds new query parameters to a URL. Encodes as UTF-8 and URL-safe.
Args:
url: string URL or :class:`urllib.request.Request`. May already have query
parameters.
params: dict or list of (string key, string value) tuples. Keys may repeat.
Returns:
string URL
"""
is_request = isinstance(url, urllib.request.Request)
if is_request:
req = url
url = req.get_full_url()
if isinstance(params, dict):
params = list(params.items())
# convert to list so we can modify later
parsed = list(urlparse(url))
# query params are in index 4
params = [(k, str(v).encode('utf-8')) for k, v in params]
parsed[4] += ('&' if parsed[4] else '') + urllib.parse.urlencode(params)
updated = urllib.parse.urlunparse(parsed)
if is_request:
return urllib.request.Request(updated, data=req.data, headers=req.headers)
else:
return updated
def remove_query_param(url, param):
"""Removes query parameter(s) from a URL. Decodes URL escapes and UTF-8.
If the query parameter is not present in the URL, the URL is returned
unchanged, and the returned value is None.
If the query parameter is present multiple times, *only the last value is
returned*.
Args:
url: string URL
param: string name of query parameter to remove
Returns:
(string URL without the given param, string param value)
"""
# convert to list so we can modify later
parsed = list(urlparse(url))
# query params are in index 4
removed = None
rest = []
for name, val in urllib.parse.parse_qsl(parsed[4], keep_blank_values=True):
if name == param:
removed = val
else:
rest.append((name, val))
parsed[4] = urllib.parse.urlencode(rest)
url = urllib.parse.urlunparse(parsed)
return url, removed
def get_required_param(handler, name):