This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
utils.py
1976 lines (1576 loc) · 61.1 KB
/
utils.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
# The contents of this file are subject to the Common Public Attribution
# License Version 1.0. (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://code.reddit.com/LICENSE. The License is based on the Mozilla Public
# License Version 1.1, but Sections 14 and 15 have been added to cover use of
# software over a computer network and provide for limited attribution for the
# Original Developer. In addition, Exhibit A has been modified to be consistent
# with Exhibit B.
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
# the specific language governing rights and limitations under the License.
#
# The Original Code is reddit.
#
# The Original Developer is the Initial Developer. The Initial Developer of
# the Original Code is reddit Inc.
#
# All portions of the code written by reddit are Copyright (c) 2006-2015 reddit
# Inc. All Rights Reserved.
###############################################################################
import base64
import codecs
import ConfigParser
import cPickle as pickle
import functools
import itertools
import math
import os
import random
import re
import signal
import time
import traceback
from collections import OrderedDict
from copy import deepcopy
from datetime import date, datetime, timedelta
from decimal import Decimal
from urllib import unquote_plus, unquote
from urllib2 import urlopen, Request
from urlparse import urlparse, urlunparse
import pytz
import snudown
import unidecode
from r2.lib.utils import reddit_agent_parser
from babel.dates import TIMEDELTA_UNITS
from BeautifulSoup import BeautifulSoup, SoupStrainer
from mako.filters import url_escape
from pylons import request, config
from pylons import tmpl_context as c
from pylons import app_globals as g
from pylons.i18n import ungettext, _
from r2.lib.contrib import ipaddress
from r2.lib.filters import _force_unicode, _force_utf8
from r2.lib.require import require, require_split, RequirementException
from r2.lib.utils._utils import *
iters = (list, tuple, set)
def randstr(length,
alphabet='abcdefghijklmnopqrstuvwxyz0123456789'):
"""Return a string made up of random chars from alphabet."""
return ''.join(random.choice(alphabet) for _ in xrange(length))
class Storage(dict):
"""
A Storage object is like a dictionary except `obj.foo` can be used
in addition to `obj['foo']`.
>>> o = storage(a=1)
>>> o.a
1
>>> o['a']
1
>>> o.a = 2
>>> o['a']
2
>>> del o.a
>>> o.a
Traceback (most recent call last):
...
AttributeError: 'a'
"""
def __getattr__(self, key):
try:
return self[key]
except KeyError, k:
raise AttributeError, k
def __setattr__(self, key, value):
self[key] = value
def __delattr__(self, key):
try:
del self[key]
except KeyError, k:
raise AttributeError, k
def __repr__(self):
return '<Storage ' + dict.__repr__(self) + '>'
storage = Storage
class Enum(Storage):
def __init__(self, *a):
self.name = tuple(a)
Storage.__init__(self, ((e, i) for i, e in enumerate(a)))
def __contains__(self, item):
if isinstance(item, int):
return item in self.values()
else:
return Storage.__contains__(self, item)
class class_property(object):
"""A decorator that combines @classmethod and @property.
http://stackoverflow.com/a/8198300/120999
"""
def __init__(self, function):
self.function = function
def __get__(self, instance, cls):
return self.function(cls)
class Results():
def __init__(self, sa_ResultProxy, build_fn, do_batch=False):
self.rp = sa_ResultProxy
self.fn = build_fn
self.do_batch = do_batch
@property
def rowcount(self):
return self.rp.rowcount
def _fetch(self, res):
if self.do_batch:
return self.fn(res)
else:
return [self.fn(row) for row in res]
def fetchall(self):
return self._fetch(self.rp.fetchall())
def fetchmany(self, n):
rows = self._fetch(self.rp.fetchmany(n))
if rows:
return rows
else:
raise StopIteration
def fetchone(self):
row = self.rp.fetchone()
if row:
if self.do_batch:
if isinstance(row, Storage):
rows = (row,)
else:
rows = tup(row)
return self.fn(rows)[0]
else:
return self.fn(row)
else:
raise StopIteration
r_base_url = re.compile("(?i)(?:.+?://)?([^#]*[^#/])/?")
r_domain = re.compile("(?i)(?:.+?://)?([^/:#?]*)")
r_domain_prefix = re.compile('^www\d*\.')
def strip_www(domain):
stripped = domain
if domain.count('.') > 1:
prefix = r_domain_prefix.findall(domain)
if domain.startswith("www") and len(prefix):
stripped = '.'.join(domain.split('.')[1:])
return stripped
def is_subdomain(subdomain, base):
"""Check if a domain is equal to or a subdomain of a base domain."""
return subdomain == base or (
subdomain is not None and subdomain.endswith('.' + base))
lang_re = re.compile(r"\A\w\w(-\w\w)?\Z")
def is_language_subdomain(subdomain):
return lang_re.match(subdomain)
def base_url(url):
res = r_base_url.findall(url)
if res and res[0]:
base = strip_www(res[0])
else:
base = url
return base.lower()
def domain(url):
"""
Takes a URL and returns the domain part, minus www., if
present
"""
match = r_domain.search(url)
if match:
domain = strip_www(match.group(1))
else:
domain = url
return domain.lower()
def extract_subdomain(host=None, base_domain=None):
"""Try to extract a subdomain from the request, as compared to g.domain.
host and base_domain exist as arguments primarily for the sake of unit
tests, although their usage should not be considered restrained to that.
"""
# These would be the argument defaults, but we need them evaluated at
# run-time, not definition-time.
if host is None:
host = request.host
if base_domain is None:
base_domain = g.domain
if not host:
return ''
end_index = host.find(base_domain) - 1 # For the conjoining dot.
# Is either the requested domain the same as the base domain, or the
# base is not a substring?
if end_index < 0:
return ''
return host[:end_index]
r_path_component = re.compile(".*?/(.*)")
def path_component(s):
"""
takes a url http://www.foo.com/i/like/cheese and returns
i/like/cheese
"""
res = r_path_component.findall(base_url(s))
return (res and res[0]) or s
def get_title(url):
"""Fetch the contents of url and try to extract the page's title."""
if not url or not url.startswith(('http://', 'https://')):
return None
try:
req = Request(url)
if g.useragent:
req.add_header('User-Agent', g.useragent)
opener = urlopen(req, timeout=15)
# determine the encoding of the response
for param in opener.info().getplist():
if param.startswith("charset="):
param_name, sep, charset = param.partition("=")
codec = codecs.getreader(charset)
break
else:
codec = codecs.getreader("utf-8")
with codec(opener, "ignore") as reader:
# Attempt to find the title in the first 1kb
data = reader.read(1024)
title = extract_title(data)
# Title not found in the first kb, try searching an additional 10kb
if not title:
data += reader.read(10240)
title = extract_title(data)
return title
except:
return None
def extract_title(data):
"""Try to extract the page title from a string of HTML.
An og:title meta tag is preferred, but will fall back to using
the <title> tag instead if one is not found. If using <title>,
also attempts to trim off the site's name from the end.
"""
bs = BeautifulSoup(data, convertEntities=BeautifulSoup.HTML_ENTITIES)
if not bs or not bs.html.head:
return
head_soup = bs.html.head
title = None
# try to find an og:title meta tag to use
og_title = (head_soup.find("meta", attrs={"property": "og:title"}) or
head_soup.find("meta", attrs={"name": "og:title"}))
if og_title:
title = og_title.get("content")
# if that failed, look for a <title> tag to use instead
if not title and head_soup.title and head_soup.title.string:
title = head_soup.title.string
# remove end part that's likely to be the site's name
# looks for last delimiter char between spaces in strings
# delimiters: |, -, emdash, endash,
# left- and right-pointing double angle quotation marks
reverse_title = title[::-1]
to_trim = re.search(u'\s[\u00ab\u00bb\u2013\u2014|-]\s',
reverse_title,
flags=re.UNICODE)
# only trim if it won't take off over half the title
if to_trim and to_trim.end() < len(title) / 2:
title = title[:-(to_trim.end())]
if not title:
return
# get rid of extraneous whitespace in the title
title = re.sub(r'\s+', ' ', title, flags=re.UNICODE)
return title.encode('utf-8').strip()
VALID_SCHEMES = ('http', 'https', 'ftp', 'mailto')
valid_dns = re.compile('\A[-a-zA-Z0-9_]+\Z')
def sanitize_url(url, require_scheme=False, valid_schemes=VALID_SCHEMES):
"""Validates that the url is of the form
scheme://domain/path/to/content#anchor?cruft
using the python built-in urlparse. If the url fails to validate,
returns None. If no scheme is provided and 'require_scheme =
False' is set, the url is returned with scheme 'http', provided it
otherwise validates"""
if not url:
return None
url = url.strip()
if url.lower() == 'self':
return url
try:
u = urlparse(url)
# first pass: make sure a scheme has been specified
if not require_scheme and not u.scheme:
# "//example.com/"
if u.hostname:
prepend = "https:" if c.secure else "http:"
# "example.com/"
else:
prepend = "http://"
url = prepend + url
u = urlparse(url)
except ValueError:
return None
if not u.scheme:
return None
if valid_schemes is not None and u.scheme not in valid_schemes:
return None
# if there is a scheme and no hostname, it is a bad url.
if not u.hostname:
return None
# work around CRBUG-464270
if len(u.hostname) > 255:
return None
# work around for Chrome crash with "%%30%30" - Sep 2015
if "%00" in unquote(u.path):
return None
if u.username is not None or u.password is not None:
return None
try:
idna_hostname = u.hostname.encode('idna')
except TypeError as e:
g.log.warning("Bad hostname given [%r]: %s", u.hostname, e)
raise
except UnicodeError:
return None
# Make sure FQDNs like google.com. (with trailing dot) are allowed. This
# is necessary to support linking to bare TLDs.
if idna_hostname.endswith('.'):
idna_hostname = idna_hostname[:-1]
for label in idna_hostname.split('.'):
if not re.match(valid_dns, label):
return None
if idna_hostname != u.hostname:
url = urlunparse((u[0], idna_hostname, u[2], u[3], u[4], u[5]))
return url
def trunc_string(text, max_length, suffix='...'):
"""Truncate a string, attempting to split on a word-break.
If the first word is longer than max_length, then truncate within the word.
Adapted from http://stackoverflow.com/a/250406/120999 .
"""
if len(text) <= max_length:
return text
else:
hard_truncated = text[:(max_length - len(suffix))]
word_truncated = hard_truncated.rsplit(' ', 1)[0]
return word_truncated + suffix
# Truncate a time to a certain number of minutes
# e.g, trunc_time(5:52, 30) == 5:30
def trunc_time(time, mins, hours=None):
if hours is not None:
if hours < 1 or hours > 60:
raise ValueError("Hours %d is weird" % mins)
time = time.replace(hour = hours * (time.hour / hours))
if mins < 1 or mins > 60:
raise ValueError("Mins %d is weird" % mins)
return time.replace(minute = mins * (time.minute / mins),
second = 0,
microsecond = 0)
def long_datetime(datetime):
return datetime.astimezone(g.tz).ctime() + " " + str(g.tz)
def median(l):
if l:
s = sorted(l)
i = len(s) / 2
return s[i]
def query_string(dict):
pairs = []
for k,v in dict.iteritems():
if v is not None:
try:
k = url_escape(_force_unicode(k))
v = url_escape(_force_unicode(v))
pairs.append(k + '=' + v)
except UnicodeDecodeError:
continue
if pairs:
return '?' + '&'.join(pairs)
else:
return ''
# Characters that might cause parsing differences in different implementations
# Spaces only seem to cause parsing differences when occurring directly before
# the scheme
URL_PROBLEMATIC_RE = re.compile(
ur'(\A\x20|[\x00-\x19\xA0\u1680\u180E\u2000-\u2029\u205f\u3000\\])',
re.UNICODE
)
def paranoid_urlparser_method(check):
"""
Decorator for checks on `UrlParser` instances that need to be paranoid
"""
def check_wrapper(parser, *args, **kwargs):
return UrlParser.perform_paranoid_check(parser, check, *args, **kwargs)
return check_wrapper
class UrlParser(object):
"""
Wrapper for urlparse and urlunparse for making changes to urls.
All attributes present on the tuple-like object returned by
urlparse are present on this class, and are setable, with the
exception of netloc, which is instead treated via a getter method
as a concatenation of hostname and port.
Unlike urlparse, this class allows the query parameters to be
converted to a dictionary via the query_dict method (and
correspondingly updated via update_query). The extension of the
path can also be set and queried.
The class also contains reddit-specific functions for setting,
checking, and getting a path's subreddit.
"""
__slots__ = ['scheme', 'path', 'params', 'query',
'fragment', 'username', 'password', 'hostname', 'port',
'_orig_url', '_orig_netloc', '_query_dict']
valid_schemes = ('http', 'https', 'ftp', 'mailto')
def __init__(self, url):
u = urlparse(url)
for s in self.__slots__:
if hasattr(u, s):
setattr(self, s, getattr(u, s))
self._orig_url = url
self._orig_netloc = getattr(u, 'netloc', '')
self._query_dict = None
def __eq__(self, other):
"""A loose equality method for UrlParsers.
In particular, this returns true for UrlParsers whose resultant urls
have the same query parameters, but in a different order. These are
treated the same most of the time, but if you need strict equality,
compare the string results of unparse().
"""
if not isinstance(other, UrlParser):
return False
(s_scheme, s_netloc, s_path, s_params, s_query, s_fragment) = self._unparse()
(o_scheme, o_netloc, o_path, o_params, o_query, o_fragment) = other._unparse()
# Check all the parsed components for equality, except the query, which
# is easier to check in its pure-dictionary form.
if (s_scheme != o_scheme or
s_netloc != o_netloc or
s_path != o_path or
s_params != o_params or
s_fragment != o_fragment):
return False
# Coerce query dicts from OrderedDicts to standard dicts to avoid an
# order-sensitive comparison.
if dict(self.query_dict) != dict(other.query_dict):
return False
return True
def update_query(self, **updates):
"""Add or change query parameters."""
# Since in HTTP everything's a string, coercing values to strings now
# makes equality testing easier. Python will throw an error if you try
# to pass in a non-string key, so that's already taken care of for us.
updates = {k: _force_unicode(v) for k, v in updates.iteritems()}
self.query_dict.update(updates)
@property
def query_dict(self):
"""A dictionary of the current query parameters.
Keys and values pulled from the original url are un-url-escaped.
Modifying this function's return value will result in changes to the
unparse()-d url, but it's recommended instead to make any changes via
`update_query()`.
"""
if self._query_dict is None:
def _split(param):
p = param.split('=')
return (unquote_plus(p[0]),
unquote_plus('='.join(p[1:])))
self._query_dict = OrderedDict(
_split(p) for p in self.query.split('&') if p)
return self._query_dict
def path_extension(self):
"""Fetches the current extension of the path.
If the url does not end in a file or the file has no extension, returns
an empty string.
"""
filename = self.path.split('/')[-1]
filename_parts = filename.split('.')
if len(filename_parts) == 1:
return ''
return filename_parts[-1]
def has_image_extension(self):
"""Guess if the url leads to an image."""
extension = self.path_extension().lower()
return extension in {'gif', 'jpeg', 'jpg', 'png', 'tiff'}
def has_static_image_extension(self):
"""Guess if the url leads to a non-animated image."""
extension = self.path_extension().lower()
return extension in {'jpeg', 'jpg', 'png', 'tiff'}
def set_extension(self, extension):
"""
Changes the extension of the path to the provided value (the
"." should not be included in the extension as a "." is
provided)
"""
pieces = self.path.split('/')
dirs = pieces[:-1]
base = pieces[-1].split('.')
base = '.'.join(base[:-1] if len(base) > 1 else base)
if extension:
base += '.' + extension
dirs.append(base)
self.path = '/'.join(dirs)
return self
def canonicalize(self):
subdomain = extract_subdomain(self.hostname)
if subdomain == '' or is_language_subdomain(subdomain):
self.hostname = 'www.{0}'.format(g.domain)
if not self.path.endswith('/'):
self.path += '/'
self.scheme = 'https'
def switch_subdomain_by_extension(self, extension=None):
"""Change the subdomain to the one that fits an extension.
This should only be used on reddit URLs.
Arguments:
* extension: the template extension to which the middleware hints when
parsing the subdomain resulting from this function.
>>> u = UrlParser('http://www.reddit.com/r/redditdev')
>>> u.switch_subdomain_by_extension('compact')
>>> u.unparse()
'http://i.reddit.com/r/redditdev'
If `extension` is not provided or does not match any known extensions,
the default subdomain (`g.domain_prefix`) will be used.
Note that this will not remove any existing extensions; if you want to
ensure the explicit extension does not override the subdomain hint, you
should call `set_extension('')` first.
"""
new_subdomain = g.domain_prefix
for subdomain, subdomain_extension in g.extension_subdomains.iteritems():
if extension == subdomain_extension:
new_subdomain = subdomain
break
self.hostname = '%s.%s' % (new_subdomain, g.domain)
def unparse(self):
"""
Converts the url back to a string, applying all updates made
to the fields thereof.
Note: if a host name has been added and none was present
before, will enforce scheme -> "http" unless otherwise
specified. Double-slashes are removed from the resultant
path, and the query string is reconstructed only if the
query_dict has been modified/updated.
"""
return urlunparse(self._unparse())
def _unparse(self):
q = query_string(self.query_dict).lstrip('?')
# make sure the port is not doubly specified
if getattr(self, 'port', None) and ":" in self.hostname:
self.hostname = self.hostname.split(':')[0]
# if there is a netloc, there had better be a scheme
if self.netloc and not self.scheme:
self.scheme = "http"
return (self.scheme, self.netloc,
self.path.replace('//', '/'),
self.params, q, self.fragment)
def path_has_subreddit(self):
"""
utility method for checking if the path starts with a
subreddit specifier (namely /r/ or /subreddits/).
"""
return self.path.startswith(('/r/', '/subreddits/', '/reddits/'))
def get_subreddit(self):
"""checks if the current url refers to a subreddit and returns
that subreddit object. The cases here are:
* the hostname is unset or is g.domain, in which case it
looks for /r/XXXX or /subreddits. The default in this case
is Default.
* the hostname is a cname to a known subreddit.
On failure to find a subreddit, returns None.
"""
from r2.models import Subreddit, NotFound, DefaultSR
try:
if (not self.hostname or
is_subdomain(self.hostname, g.domain) or
self.hostname.startswith(g.domain)):
if self.path.startswith('/r/'):
return Subreddit._by_name(self.path.split('/')[2])
else:
return DefaultSR()
elif self.hostname:
return Subreddit._by_domain(self.hostname)
except NotFound:
pass
return None
def perform_paranoid_check(self, check, *args, **kwargs):
"""
Perform a check on a URL that needs to account for bugs in `unparse()`
If you need to account for quirks in browser URL parsers, you should
use this along with `is_web_safe_url()`. Trying to parse URLs like
a browser would just makes things really hairy.
"""
variants_to_check = (
self,
UrlParser(self.unparse())
)
# If the check doesn't pass on *every* variant, it's a fail.
return all(
check(variant, *args, **kwargs) for variant in variants_to_check
)
@paranoid_urlparser_method
def is_web_safe_url(self):
"""Determine if this URL could cause issues with different parsers"""
# There's no valid reason for this, and just serves to confuse UAs.
# and urllib2.
if self._orig_url.startswith("///"):
return False
# Double-checking the above
if not self.hostname and self.path.startswith('//'):
return False
# A host-relative link with a scheme like `https:/baz` or `https:?quux`
if self.scheme and not self.hostname:
return False
# Credentials in the netloc? Not on reddit!
if "@" in self._orig_netloc:
return False
# `javascript://www.reddit.com/%0D%Aalert(1)` is not safe, obviously
if self.scheme and self.scheme.lower() not in self.valid_schemes:
return False
# Reject any URLs that contain characters known to cause parsing
# differences between parser implementations
for match in re.finditer(URL_PROBLEMATIC_RE, self._orig_url):
# XXX: Yuck. We have non-breaking spaces in title slugs! They
# should be safe enough to allow after three slashes. Opera 12's the
# only browser that trips over them, and it doesn't fall for
# `http:///foo.com/`.
# Check both in case unicode promotion fails
if match.group(0) in {u'\xa0', '\xa0'}:
if match.string[0:match.start(0)].count('/') < 3:
return False
else:
return False
return True
def is_reddit_url(self, subreddit=None):
"""utility method for seeing if the url is associated with
reddit as we don't necessarily want to mangle non-reddit
domains
returns true only if hostname is nonexistant, a subdomain of
g.domain, or a subdomain of the provided subreddit's cname.
"""
valid_subdomain = (
not self.hostname or
is_subdomain(self.hostname, g.domain) or
(subreddit and subreddit.domain and
is_subdomain(self.hostname, subreddit.domain))
)
if not valid_subdomain or not self.hostname or not g.offsite_subdomains:
return valid_subdomain
return not any(
is_subdomain(self.hostname, "%s.%s" % (subdomain, g.domain))
for subdomain in g.offsite_subdomains
)
def path_add_subreddit(self, subreddit):
"""
Adds the subreddit's path to the path if another subreddit's
prefix is not already present.
"""
if not (self.path_has_subreddit()
or self.path.startswith(subreddit.user_path)):
self.path = (subreddit.user_path + self.path)
return self
@property
def netloc(self):
"""
Getter method which returns the hostname:port, or empty string
if no hostname is present.
"""
if not self.hostname:
return ""
elif getattr(self, "port", None):
return self.hostname + ":" + str(self.port)
return self.hostname
def __repr__(self):
return "<URL %s>" % repr(self.unparse())
def domain_permutations(self, fragments=False, subdomains=True):
"""
Takes a domain like `www.reddit.com`, and returns a list of ways
that a user might search for it, like:
* www
* reddit
* com
* www.reddit.com
* reddit.com
* com
"""
ret = set()
if self.hostname:
r = self.hostname.split('.')
if subdomains:
for x in xrange(len(r)-1):
ret.add('.'.join(r[x:len(r)]))
if fragments:
for x in r:
ret.add(x)
return ret
@classmethod
def base_url(cls, url):
u = cls(url)
# strip off any www and lowercase the hostname:
netloc = strip_www(u.netloc.lower())
# http://code.google.com/web/ajaxcrawling/docs/specification.html
fragment = u.fragment if u.fragment.startswith("!") else ""
return urlunparse((u.scheme.lower(), netloc,
u.path, u.params, u.query, fragment))
def coerce_url_to_protocol(url, protocol='http'):
'''Given an absolute (but potentially protocol-relative) url, coerce it to
a protocol.'''
parsed_url = UrlParser(url)
parsed_url.scheme = protocol
return parsed_url.unparse()
def url_is_embeddable_image(url):
"""The url is on an oembed-friendly domain and looks like an image."""
parsed_url = UrlParser(url)
if parsed_url.path_extension().lower() in {"jpg", "gif", "png", "jpeg"}:
if parsed_url.hostname not in g.known_image_domains:
return False
return True
return False
def url_to_thing(url):
"""Given a reddit URL, return the Thing to which it associates.
Examples:
/r/somesr - Subreddit
/r/somesr/comments/j2jx - Link
/r/somesr/comments/j2jx/slug/k2js - Comment
"""
from r2.models import Comment, Link, Message, NotFound, Subreddit, Thing
from r2.config.middleware import SubredditMiddleware
sr_pattern = SubredditMiddleware.sr_pattern
urlparser = UrlParser(_force_utf8(url))
if not urlparser.is_reddit_url():
return None
try:
sr_name = sr_pattern.match(urlparser.path).group(1)
except AttributeError:
sr_name = None
path = sr_pattern.sub('', urlparser.path)
if not path or path == '/':
if not sr_name:
return None
try:
return Subreddit._by_name(sr_name, data=True)
except NotFound:
return None
# potential TypeError raised here because of environ being None
# when calling outside of app context
try:
route_dict = config['routes.map'].match(path)
except TypeError:
return None
if not route_dict:
return None
try:
comment = route_dict.get('comment')
if comment:
return Comment._byID36(comment, data=True)
article = route_dict.get('article')
if article:
return Link._byID36(article, data=True)
msg = route_dict.get('mid')
if msg:
return Message._byID36(msg, data=True)
except (NotFound, ValueError):
return None
return None
def pload(fname, default = None):
"Load a pickled object from a file"
try:
f = file(fname, 'r')
d = pickle.load(f)
except IOError:
d = default
else:
f.close()
return d
def psave(fname, d):
"Save a pickled object into a file"
f = file(fname, 'w')
pickle.dump(d, f)
f.close()
def unicode_safe(res):
try:
return str(res)
except UnicodeEncodeError:
try:
return unicode(res).encode('utf-8')
except UnicodeEncodeError:
return res.decode('utf-8').encode('utf-8')
def decompose_fullname(fullname):
"""
decompose_fullname("t3_e4fa") ->
(Thing, 3, 658918)
"""
from r2.lib.db.thing import Thing,Relation
if fullname[0] == 't':
type_class = Thing
elif fullname[0] == 'r':
type_class = Relation
type_id36, thing_id36 = fullname[1:].split('_')
type_id = int(type_id36,36)
id = int(thing_id36,36)
return (type_class, type_id, id)
def cols(lst, ncols):
"""divides a list into columns, and returns the
rows. e.g. cols('abcdef', 2) returns (('a', 'd'), ('b', 'e'), ('c',
'f'))"""
nrows = int(math.ceil(1.*len(lst) / ncols))
lst = lst + [None for i in range(len(lst), nrows*ncols)]
cols = [lst[i:i+nrows] for i in range(0, nrows*ncols, nrows)]
rows = zip(*cols)
rows = [filter(lambda x: x is not None, r) for r in rows]
return rows
def fetch_things(t_class,since,until,batch_fn=None,
*query_params, **extra_query_dict):
"""
Simple utility function to fetch all Things of class t_class
(spam or not, but not deleted) that were created from 'since'
to 'until'
"""
from r2.lib.db.operators import asc
if not batch_fn:
batch_fn = lambda x: x
query_params = ([t_class.c._date >= since,
t_class.c._date < until,
t_class.c._spam == (True,False)]
+ list(query_params))
query_dict = {'sort': asc('_date'),