9ba760116153ad2fe0fc97179ed22b0a895c787a
# Copyright (C) 2001-2004 Python Software Foundation
# Contact: email-sig@python.org
"""Miscellaneous utilities."""
from cStringIO
import StringIO
from email
._parseaddr
import quote
from email
._parseaddr
import AddressList
as _AddressList
from email
._parseaddr
import mktime_tz
# We need wormarounds for bugs in these methods in older Pythons (see below)
from email
._parseaddr
import parsedate
as _parsedate
from email
._parseaddr
import parsedate_tz
as _parsedate_tz
from quopri
import decodestring
as _qdecode
from email
.Encoders
import _bencode
, _qencode
specialsre
= re
.compile(r
'[][\\()<>@,:;".]')
escapesre
= re
.compile(r
'[][\\()"]')
# We can't quite use base64.encodestring() since it tacks on a "courtesy
value
= base64
.decodestring(s
)
if not s
.endswith('\n') and value
.endswith('\n'):
"""Replace all line-ending characters with \r\n."""
# Fix newlines with no preceding carriage return
s
= re
.sub(r
'(?<!\r)\n', CRLF
, s
)
# Fix carriage returns with no following newline
s
= re
.sub(r
'\r(?!\n)', CRLF
, s
)
"""The inverse of parseaddr(), this takes a 2-tuple of the form
(realname, email_address) and returns the string value suitable
for an RFC 2822 From, To or Cc header.
If the first element of pair is false, then the second element is
if specialsre
.search(name
):
name
= escapesre
.sub(r
'\\\g<0>', name
)
return '%s%s%s <%s>' % (quotes
, name
, quotes
, address
)
def getaddresses(fieldvalues
):
"""Return a list of (REALNAME, EMAIL) for each fieldvalue."""
all
= COMMASPACE
.join(fieldvalues
)
(?P<charset>[^?]*?) # non-greedy up to the next ? is the charset
(?P<encoding>[qb]) # either a "q" or a "b", case insensitive
(?P<atom>.*?) # non-greedy up to the next ?= is the atom
''', re
.VERBOSE | re
.IGNORECASE
)
def formatdate(timeval
=None, localtime
=False, usegmt
=False):
"""Returns a date string as specified by RFC 2822, e.g.:
Fri, 09 Nov 2001 01:08:47 -0000
Optional timeval if given is a floating point time value as accepted by
gmtime() and localtime(), otherwise the current time is used.
Optional localtime is a flag that when True, interprets timeval, and
returns a date relative to the local timezone instead of UTC, properly
taking daylight savings time into account.
Optional argument usegmt means that the timezone is written out as
an ascii string, not numeric one (so "GMT" instead of "+0000"). This
is needed for HTTP, and is only used when localtime==False.
# Note: we cannot use strftime() because that honors the locale and RFC
# 2822 requires that day and month names be the English abbreviations.
now
= time
.localtime(timeval
)
# Calculate timezone offset, based on whether the local zone has
# daylight savings time, and whether DST is in effect.
if time
.daylight
and now
[-1]:
hours
, minutes
= divmod(abs(offset
), 3600)
# Remember offset is in seconds west of UTC, but the timezone is in
# minutes east of UTC, so the signs differ.
zone
= '%s%02d%02d' % (sign
, hours
, minutes
// 60)
now
= time
.gmtime(timeval
)
# Timezone offset is always -0000
return '%s, %02d %s %04d %02d:%02d:%02d %s' % (
['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][now
[6]],
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][now
[1] - 1],
now
[0], now
[3], now
[4], now
[5],
def make_msgid(idstring
=None):
"""Returns a string suitable for RFC 2822 compliant Message-ID, e.g:
<20020201195627.33539.96671@nightshade.la.mastaler.com>
Optional idstring if given is a string used to strengthen the
uniqueness of the message id.
utcdate
= time
.strftime('%Y%m%d%H%M%S', time
.gmtime(timeval
))
randint
= random
.randrange(100000)
idstring
= '.' + idstring
idhost
= socket
.getfqdn()
msgid
= '<%s.%s.%s%s@%s>' % (utcdate
, pid
, randint
, idstring
, idhost
)
# These functions are in the standalone mimelib version only because they've
# subsequently been fixed in the latest Python versions. We use this to worm
# around broken older Pythons.
return _parsedate_tz(data
)
addrs
= _AddressList(addr
).addresslist
# rfc822.unquote() doesn't properly de-backslash-ify in Python pre-2.3.
"""Remove quotes from a string."""
if str.startswith('"') and str.endswith('"'):
return str[1:-1].replace('\\\\', '\\').replace('\\"', '"')
if str.startswith('<') and str.endswith('>'):
# RFC2231-related functions - parameter encoding and decoding
"""Decode string according to RFC 2231"""
return None, None, urllib
.unquote(s
)
charset
, language
, s
= parts
return charset
, language
, urllib
.unquote(s
)
def encode_rfc2231(s
, charset
=None, language
=None):
"""Encode string according to RFC 2231.
If neither charset nor language is given, then s is returned as-is. If
charset is given but not language, the string is encoded using the empty
s
= urllib
.quote(s
, safe
='')
if charset
is None and language
is None:
return "%s'%s'%s" % (charset
, language
, s
)
rfc2231_continuation
= re
.compile(r
'^(?P<name>\w+)\*((?P<num>[0-9]+)\*?)?$')
def decode_params(params
):
"""Decode parameters list according to RFC 2231.
params is a sequence of 2-tuples containing (content type, string value).
# maps parameter's name to a list of continuations
# params is a sequence of 2-tuples containing (content_type, string value)
new_params
.append((name
, value
))
# Cycle through each of the rest of the parameters.
for name
, value
in params
[1:]:
mo
= rfc2231_continuation
.match(name
)
name
, num
= mo
.group('name', 'num')
rfc2231_param1
= rfc2231_params
.setdefault(name
, [])
rfc2231_param1
.append((num
, value
))
new_params
.append((name
, '"%s"' % quote(value
)))
for name
, continuations
in rfc2231_params
.items():
# And now append all values in num order
for num
, continuation
in continuations
:
value
.append(continuation
)
charset
, language
, value
= decode_rfc2231(EMPTYSTRING
.join(value
))
(name
, (charset
, language
, '"%s"' % quote(value
))))
def collapse_rfc2231_value(value
, errors
='replace',
fallback_charset
='us-ascii'):
if isinstance(value
, tuple):
rawval
= unquote(value
[2])
charset
= value
[0] or 'us-ascii'
return unicode(rawval
, charset
, errors
)
# XXX charset is unknown to Python.
return unicode(rawval
, fallback_charset
, errors
)