Source

reddish / reddish / lib / helpers.py

Full commit
  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
"""Helper functions

Consists of functions to typically be used within templates, but also
available to Controllers. This module is available to templates as 'h'.
"""

import base64
import datetime
import hashlib
import hmac
import os
import re
from pylons import app_globals as g, request, url as pylons_url, tmpl_context as c
from Stemmer import Stemmer
import time
from webhelpers.html import literal, url_escape

from .errors import ClientError
from .sundown import markdown as _markdown

TIME_FORMAT = '%a %b %d %H:%M:%S %Y UTC'

def ago(d):
    '''
    Return a literal for an HTML element giving a human-readable
    representation of a date in the past.

    d:
        datetime.datetime object
    '''
    if d is None:
        s = 'never'
    elif not isinstance(d, datetime.datetime):
        raise TypeError('ago: expected datetime, got ' + type(d).__name__)
    else:
        now = datetime.datetime.utcnow()

        if d > now:
            s = 'in the future'
        else:
            s = duration(now - d) + ' ago'

    return literal('<span title="%s">%s</span>') % (
        d.strftime(TIME_FORMAT), s)

def since(d):
    if d is None:
        s = 'never'
    elif not isinstance(d, datetime.datetime):
        raise TypeError('since: expected datetime, got ' + type(d).__name__)
    else:
        now = datetime.datetime.utcnow()

        if d > now:
            s = 'in the future'
        else:
            s = duration(now - d)

    return literal('<span title="%s">%s</span>') % (
        d.strftime(TIME_FORMAT), s)

def page(results):
    if results.filtered():
        c.num_items = -1
    else:
        c.num_items = min(len(results), c.MAX_ITEMS)
    if c.offset:
        results.skip(c.offset)
    return results.limit(c.prefs.n_items)

def to_base(n, alphabet):
    if n == 0:
        return alphabet[0]

    base = len(alphabet)
    chars = []

    while n:
        n, c = divmod(n, base)
        chars.insert(0, alphabet[c])

    return ''.join(chars)

def to36(n):
    return to_base(n, '0123456789abcdefghijklmnopqrstuvwxyz')

def until(d):
    '''
    Return a literal for an HTML element giving a human-readable
    representation of a date in the future.

    d:
        datetime.datetime object
    '''
    if d is None:
        return 'never'
    if not isinstance(d, datetime.datetime):
        raise TypeError('until: expected datetime, got ' + type(d).__name__)

    now = datetime.datetime.utcnow()
    delta = d - now

    # This is to ensure sane displays when a future time has arrived (and passed)
    # but e.g. a cron job has not yet handled it
    if delta < datetime.timedelta(minutes = 1):
        s = 'in less than 1 minute'

    s = 'in ' + duration(delta)

    return literal('<span title="%s">%s</span>') % (
        d.strftime(TIME_FORMAT), s)

def duration(d):
    '''
    Return a str representation of a duration of time

    d:
        datetime.timedelta object
    '''
    if d.days:
        days = d.days
        if days == 1:
            return '1 day'
        elif days >= 365:
            # TODO: Properly account for leap years. Yes, it's that important.
            if days < 365 * 2:
                return '1 year'
            return '%d years' % (days // 365)
        elif days >= 30:
            if days < (365.25 / 12) * 2:
                return '1 month'
            return '%d months' % (days // (365.25 / 12))

        return '%d days' % days
    if d.seconds:
        seconds = d.seconds
        hours = seconds // 3600
        if hours:
            if hours == 1:
                return '1 hour'
            return '%d hours' % hours

        minutes = seconds // 60
        if minutes:
            if minutes == 1:
                return '1 minute'
            return '%d minutes' % minutes

        if seconds == 1:
            return '1 second'
        return '%d seconds' % seconds

    return 'less than 1 second'

def make_key():
    return hmac.HMAC(g.secret,
        repr(time.time()) + str(os.getpid()) + os.urandom(8),
        hashlib.sha1).hexdigest()

def merge(a, *b):
    '''
    Merge a dict in place with values from another dict.
    If a key exists in another dict with a different value, a ValueError will
    be raised and the target dict will be left in an undefined state.

    a:
        dict to be merged, modified **IN-PLACE**

    b:
        dicts whose values are to be merged, not modified
    '''
    for d in b:
        for k in d.keys():
            if k in a:
                av = a[k]
                bv = d[k]

                if isinstance(av, dict) and isinstance(bv, dict):
                    merge(av, bv)
                elif av != bv:
                    raise ValueError('Conflicting values in merge')
            else:
                a[k] = d[k]

    return a

def parse_duration(dur, P = re.compile('^([0-9]+[ywdhms]?)+$'),
        G = re.compile('[0-9]+[ywdhms]?')):
    if dur is None:
        return
    if P.match(dur) is None:
        raise ValueError('Invalid duration: ' + dur)

    units = {}

    for s in G.findall(dur):
        if s.isdigit():
            unit = 's'
        else:
            unit = s[-1]
            s = s[:-1]

        if unit in units:
            raise ValueError('Duplicate duration unit: ' + unit)

        units[unit] = int(s)

    return datetime.timedelta(
        days = units.get('y', 0) * 365 +
            units.get('w', 0) * 7 +
            units.get('d', 0),
        seconds = 
            units.get('h', 0) * (60 * 60) + 
            units.get('m', 0) * 60 + 
            units.get('s', 0)
    )

def gen_salt(n):
    '''
    Return a random string of the given length
    '''
    return base64.standard_b64encode(os.urandom(n))[:n]

def md5(s):
    return hashlib.md5(s.encode('utf8')).hexdigest()

def sha1(s):
    return hashlib.sha1(s.encode('utf8')).hexdigest()

def hash_password(p, salt = None, salt_len = 4):
    '''
    Compute hash of a password

    p:
        str to hash

    salt:
        Salt str or password containing salt in format '$[salt]$...'
        If omitted, a salt will be generated

    salt_len:
        Length of generated salt in absence of salt argument
    '''
    if salt is None:
        salt = gen_salt(salt_len)
    elif salt.startswith('$'):
        ind = salt.find('$', 1)
        if ind != -1:
            salt = salt[1:ind]
    return '$%s$%s' % (salt, sha1(salt + p))

def vb_hash(p, salt):
    '''
    Hashes a password using vBulletin's algorithm
    '''
    # vBulletin salt may contain the '$' character, so we must use NUL bytes here
    if salt.startswith('vb:\0'):
        end = salt.find('\0', 4)
        if end != -1:
            salt = salt[4:end]

    return 'vb:\0%s\0%s' % (salt, md5(md5(p) + salt))

def keywords(text, SEP = re.compile(r'\W+', re.UNICODE)):
    s = Stemmer('english') # TODO: Internationalization support
    res = set()

    for w in SEP.split(text.lower()):
        if w:
            w = s.stemWord(w)
            res.add(w)

    return list(res)

def lookahead(i):
    '''
    Yields (element, last) pairs for each element in an iterable,
    where last is whether the yielded element is the final element in the iterable.

    i:
        Iterable
    '''
    i = iter(i)
    a = i.next()
    try:
        while 1:
            b = i.next()
            yield a, False
            a = b
    except StopIteration:
        yield a, True

def markdown(text):
    return literal(_markdown(text, new_window = c.prefs.new_window or False))

def to_timestamp(d, localtime = False):
    '''
    Convert a datetime.datetime to a Unix timestamp

    d:
        datetime.datetime object

    localtime:
        True if the given datetime is of local time
    '''
    ts = int(time.mktime(d.timetuple()))

    if not localtime:
        ts -= time.timezone

    return ts

## Valid characters in name validation
VALID_CHARS = frozenset('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-')

def valid_name(n, min_len = 2, max_len = 64):
    '''
    Check whether a name is valid under certain constraints

    Raises a ClientError on invalid name
    '''
    n = n.strip()

    ln = len(n)

    if ln < min_len:
        raise ClientError('Name must be at least %d characters' % min_len)
    if ln > max_len:
        raise ClientError('Name must be no greater than %d characters' % max_len)

    invalid = []

    for c in n:
        if c not in VALID_CHARS:
            invalid.append(c)

    if invalid:
        raise ClientError('Invalid characters in name: %s' % ''.join(invalid))

    return n

def urlencode(q):
    return '&'.join(
        url_escape(k.encode('utf8')) + '=' + url_escape(
            v.encode('utf8') if isinstance(v, basestring) else str(v))
        for k, v in q.iteritems())

class URLWrapper(object):
    '''
    Wraps pylons.url object to enable UTF8-encoded URLs
    '''

    def __call__(self, *args, **kws):
        if kws.pop('secure', None):
            if g.enable_https:
                kws['protocol'] = 'https'
                if g.https_domain:
                    kws['host'] = g.https_domain.encode('utf8')

        if args:
            args = (args[0].encode('utf8'),) + args[1:]

        return pylons_url(*args, **kws).decode('utf8')

    def current(self, **kws):
        res = pylons_url.current()
        if c.render_ext:
            res += c.render_ext
        if kws and request.GET:
            k = request.GET.copy()
            k.update(kws)
            res += '?' + urlencode(k)
        else:
            k = request.GET or kws
            if k:
                res += '?' + urlencode(k)
        return res.decode('utf8')

    def __getattr__(self, key):
        return getattr(pylons_url, key)

url = URLWrapper()

class URL(object):

    PATTERN = re.compile(
        r'^'
        r'(?:'
            r'(?:([a-z]+://|mailto:))?' # Scheme
            r'(?:([^:]+):([^@]+)@)?'    # User, password
            r'('
                r'[^\.:/?#]+(?:\.[^\.:/?#]+)+\.?|' # Hostname
                r'\[[A-Fa-f0-9:]+\]'    # Or IPv6 address
            r')'
            r'(?::([0-9]+))?'           # Port
        r')?'
        r'(?:(/[^?]*))?'                # Path
        r'(\?[^#]*)?'                   # Query
        r'(#.*)?'                       # Fragment
        r'$') 

    def __init__(self, url):
        m = self.PATTERN.match(url)

        if m is None:
            raise ClientError('Invalid URL')

        (self.scheme, self.user, self.password, self.hostname, self.port,
            self.path, self.query, self.fragment) = m.groups()

        if self.scheme:
            self.scheme = self.scheme.lower()

        if self.hostname:
            self.hostname = self.hostname.lower()
            if self.hostname[-1] == '.':
                self.hostname = self.hostname[:-1]

        if self.port:
            self.port = int(self.port)

    def __unicode__(self):
        return (
            ((self.scheme if self.scheme else '') +
                (self.user + ':' + self.password + '@'
                    if self.user and self.password else '') +
                (self.hostname + (':%d' % self.port if self.port else ''))
                    if self.hostname else '') +
            (self.path or '') +
            (self.query or '') +
            (self.fragment or ''))

    def __repr__(self):
        return 'URL(%r)' % unicode(self)

    def reverse_domain(self):
        if self.hostname and ':' not in self.hostname:
            return reverse_domain(self.hostname)

    def allow_access(self):
        '''
        Return whether to allow cross-origin access from this domain.
        '''
        return self.hostname in g.domains

    def valid_destination(self):
        '''
        Return whether this is a valid URL for internal redirection,
        i.e. is a relative URL or shares our domain
        '''
        return not self.hostname or self.allow_access()

def reverse_domain(domain):
    return '.'.join(reversed(domain.split('.'))) + '.'

def match_domain(domain):
    return re.compile('^' + re.escape(reverse_domain(domain)))