You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

763 lines
25 KiB

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import datetime
  4. import email.utils
  5. import errno
  6. import gzip
  7. import io
  8. import json
  9. import locale
  10. import os
  11. import platform
  12. import re
  13. import socket
  14. import sys
  15. import traceback
  16. import zlib
  17. try:
  18. import urllib.request as compat_urllib_request
  19. except ImportError: # Python 2
  20. import urllib2 as compat_urllib_request
  21. try:
  22. import urllib.error as compat_urllib_error
  23. except ImportError: # Python 2
  24. import urllib2 as compat_urllib_error
  25. try:
  26. import urllib.parse as compat_urllib_parse
  27. except ImportError: # Python 2
  28. import urllib as compat_urllib_parse
  29. try:
  30. from urllib.parse import urlparse as compat_urllib_parse_urlparse
  31. except ImportError: # Python 2
  32. from urlparse import urlparse as compat_urllib_parse_urlparse
  33. try:
  34. import urllib.parse as compat_urlparse
  35. except ImportError: # Python 2
  36. import urlparse as compat_urlparse
  37. try:
  38. import http.cookiejar as compat_cookiejar
  39. except ImportError: # Python 2
  40. import cookielib as compat_cookiejar
  41. try:
  42. import html.entities as compat_html_entities
  43. except ImportError: # Python 2
  44. import htmlentitydefs as compat_html_entities
  45. try:
  46. import html.parser as compat_html_parser
  47. except ImportError: # Python 2
  48. import HTMLParser as compat_html_parser
  49. try:
  50. import http.client as compat_http_client
  51. except ImportError: # Python 2
  52. import httplib as compat_http_client
  53. try:
  54. from urllib.error import HTTPError as compat_HTTPError
  55. except ImportError: # Python 2
  56. from urllib2 import HTTPError as compat_HTTPError
  57. try:
  58. from subprocess import DEVNULL
  59. compat_subprocess_get_DEVNULL = lambda: DEVNULL
  60. except ImportError:
  61. compat_subprocess_get_DEVNULL = lambda: open(os.path.devnull, 'w')
  62. try:
  63. from urllib.parse import parse_qs as compat_parse_qs
  64. except ImportError: # Python 2
  65. # HACK: The following is the correct parse_qs implementation from cpython 3's stdlib.
  66. # Python 2's version is apparently totally broken
  67. def _unquote(string, encoding='utf-8', errors='replace'):
  68. if string == '':
  69. return string
  70. res = string.split('%')
  71. if len(res) == 1:
  72. return string
  73. if encoding is None:
  74. encoding = 'utf-8'
  75. if errors is None:
  76. errors = 'replace'
  77. # pct_sequence: contiguous sequence of percent-encoded bytes, decoded
  78. pct_sequence = b''
  79. string = res[0]
  80. for item in res[1:]:
  81. try:
  82. if not item:
  83. raise ValueError
  84. pct_sequence += item[:2].decode('hex')
  85. rest = item[2:]
  86. if not rest:
  87. # This segment was just a single percent-encoded character.
  88. # May be part of a sequence of code units, so delay decoding.
  89. # (Stored in pct_sequence).
  90. continue
  91. except ValueError:
  92. rest = '%' + item
  93. # Encountered non-percent-encoded characters. Flush the current
  94. # pct_sequence.
  95. string += pct_sequence.decode(encoding, errors) + rest
  96. pct_sequence = b''
  97. if pct_sequence:
  98. # Flush the final pct_sequence
  99. string += pct_sequence.decode(encoding, errors)
  100. return string
  101. def _parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
  102. encoding='utf-8', errors='replace'):
  103. qs, _coerce_result = qs, unicode
  104. pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
  105. r = []
  106. for name_value in pairs:
  107. if not name_value and not strict_parsing:
  108. continue
  109. nv = name_value.split('=', 1)
  110. if len(nv) != 2:
  111. if strict_parsing:
  112. raise ValueError("bad query field: %r" % (name_value,))
  113. # Handle case of a control-name with no equal sign
  114. if keep_blank_values:
  115. nv.append('')
  116. else:
  117. continue
  118. if len(nv[1]) or keep_blank_values:
  119. name = nv[0].replace('+', ' ')
  120. name = _unquote(name, encoding=encoding, errors=errors)
  121. name = _coerce_result(name)
  122. value = nv[1].replace('+', ' ')
  123. value = _unquote(value, encoding=encoding, errors=errors)
  124. value = _coerce_result(value)
  125. r.append((name, value))
  126. return r
  127. def compat_parse_qs(qs, keep_blank_values=False, strict_parsing=False,
  128. encoding='utf-8', errors='replace'):
  129. parsed_result = {}
  130. pairs = _parse_qsl(qs, keep_blank_values, strict_parsing,
  131. encoding=encoding, errors=errors)
  132. for name, value in pairs:
  133. if name in parsed_result:
  134. parsed_result[name].append(value)
  135. else:
  136. parsed_result[name] = [value]
  137. return parsed_result
  138. try:
  139. compat_str = unicode # Python 2
  140. except NameError:
  141. compat_str = str
  142. try:
  143. compat_chr = unichr # Python 2
  144. except NameError:
  145. compat_chr = chr
  146. def compat_ord(c):
  147. if type(c) is int: return c
  148. else: return ord(c)
  149. # This is not clearly defined otherwise
  150. compiled_regex_type = type(re.compile(''))
  151. std_headers = {
  152. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0',
  153. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  154. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  155. 'Accept-Encoding': 'gzip, deflate',
  156. 'Accept-Language': 'en-us,en;q=0.5',
  157. }
  158. def preferredencoding():
  159. """Get preferred encoding.
  160. Returns the best encoding scheme for the system, based on
  161. locale.getpreferredencoding() and some further tweaks.
  162. """
  163. try:
  164. pref = locale.getpreferredencoding()
  165. u'TEST'.encode(pref)
  166. except:
  167. pref = 'UTF-8'
  168. return pref
  169. if sys.version_info < (3,0):
  170. def compat_print(s):
  171. print(s.encode(preferredencoding(), 'xmlcharrefreplace'))
  172. else:
  173. def compat_print(s):
  174. assert type(s) == type(u'')
  175. print(s)
  176. # In Python 2.x, json.dump expects a bytestream.
  177. # In Python 3.x, it writes to a character stream
  178. if sys.version_info < (3,0):
  179. def write_json_file(obj, fn):
  180. with open(fn, 'wb') as f:
  181. json.dump(obj, f)
  182. else:
  183. def write_json_file(obj, fn):
  184. with open(fn, 'w', encoding='utf-8') as f:
  185. json.dump(obj, f)
  186. if sys.version_info >= (2,7):
  187. def find_xpath_attr(node, xpath, key, val):
  188. """ Find the xpath xpath[@key=val] """
  189. assert re.match(r'^[a-zA-Z]+$', key)
  190. assert re.match(r'^[a-zA-Z0-9@\s]*$', val)
  191. expr = xpath + u"[@%s='%s']" % (key, val)
  192. return node.find(expr)
  193. else:
  194. def find_xpath_attr(node, xpath, key, val):
  195. for f in node.findall(xpath):
  196. if f.attrib.get(key) == val:
  197. return f
  198. return None
  199. def htmlentity_transform(matchobj):
  200. """Transforms an HTML entity to a character.
  201. This function receives a match object and is intended to be used with
  202. the re.sub() function.
  203. """
  204. entity = matchobj.group(1)
  205. # Known non-numeric HTML entity
  206. if entity in compat_html_entities.name2codepoint:
  207. return compat_chr(compat_html_entities.name2codepoint[entity])
  208. mobj = re.match(u'(?u)#(x?\\d+)', entity)
  209. if mobj is not None:
  210. numstr = mobj.group(1)
  211. if numstr.startswith(u'x'):
  212. base = 16
  213. numstr = u'0%s' % numstr
  214. else:
  215. base = 10
  216. return compat_chr(int(numstr, base))
  217. # Unknown entity in name, return its literal representation
  218. return (u'&%s;' % entity)
  219. compat_html_parser.locatestarttagend = re.compile(r"""<[a-zA-Z][-.a-zA-Z0-9:_]*(?:\s+(?:(?<=['"\s])[^\s/>][^\s/=>]*(?:\s*=+\s*(?:'[^']*'|"[^"]*"|(?!['"])[^>\s]*))?\s*)*)?\s*""", re.VERBOSE) # backport bugfix
  220. class AttrParser(compat_html_parser.HTMLParser):
  221. """Modified HTMLParser that isolates a tag with the specified attribute"""
  222. def __init__(self, attribute, value):
  223. self.attribute = attribute
  224. self.value = value
  225. self.result = None
  226. self.started = False
  227. self.depth = {}
  228. self.html = None
  229. self.watch_startpos = False
  230. self.error_count = 0
  231. compat_html_parser.HTMLParser.__init__(self)
  232. def error(self, message):
  233. if self.error_count > 10 or self.started:
  234. raise compat_html_parser.HTMLParseError(message, self.getpos())
  235. self.rawdata = '\n'.join(self.html.split('\n')[self.getpos()[0]:]) # skip one line
  236. self.error_count += 1
  237. self.goahead(1)
  238. def loads(self, html):
  239. self.html = html
  240. self.feed(html)
  241. self.close()
  242. def handle_starttag(self, tag, attrs):
  243. attrs = dict(attrs)
  244. if self.started:
  245. self.find_startpos(None)
  246. if self.attribute in attrs and attrs[self.attribute] == self.value:
  247. self.result = [tag]
  248. self.started = True
  249. self.watch_startpos = True
  250. if self.started:
  251. if not tag in self.depth: self.depth[tag] = 0
  252. self.depth[tag] += 1
  253. def handle_endtag(self, tag):
  254. if self.started:
  255. if tag in self.depth: self.depth[tag] -= 1
  256. if self.depth[self.result[0]] == 0:
  257. self.started = False
  258. self.result.append(self.getpos())
  259. def find_startpos(self, x):
  260. """Needed to put the start position of the result (self.result[1])
  261. after the opening tag with the requested id"""
  262. if self.watch_startpos:
  263. self.watch_startpos = False
  264. self.result.append(self.getpos())
  265. handle_entityref = handle_charref = handle_data = handle_comment = \
  266. handle_decl = handle_pi = unknown_decl = find_startpos
  267. def get_result(self):
  268. if self.result is None:
  269. return None
  270. if len(self.result) != 3:
  271. return None
  272. lines = self.html.split('\n')
  273. lines = lines[self.result[1][0]-1:self.result[2][0]]
  274. lines[0] = lines[0][self.result[1][1]:]
  275. if len(lines) == 1:
  276. lines[-1] = lines[-1][:self.result[2][1]-self.result[1][1]]
  277. lines[-1] = lines[-1][:self.result[2][1]]
  278. return '\n'.join(lines).strip()
  279. # Hack for https://github.com/rg3/youtube-dl/issues/662
  280. if sys.version_info < (2, 7, 3):
  281. AttrParser.parse_endtag = (lambda self, i:
  282. i + len("</scr'+'ipt>")
  283. if self.rawdata[i:].startswith("</scr'+'ipt>")
  284. else compat_html_parser.HTMLParser.parse_endtag(self, i))
  285. def get_element_by_id(id, html):
  286. """Return the content of the tag with the specified ID in the passed HTML document"""
  287. return get_element_by_attribute("id", id, html)
  288. def get_element_by_attribute(attribute, value, html):
  289. """Return the content of the tag with the specified attribute in the passed HTML document"""
  290. parser = AttrParser(attribute, value)
  291. try:
  292. parser.loads(html)
  293. except compat_html_parser.HTMLParseError:
  294. pass
  295. return parser.get_result()
  296. def clean_html(html):
  297. """Clean an HTML snippet into a readable string"""
  298. # Newline vs <br />
  299. html = html.replace('\n', ' ')
  300. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  301. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  302. # Strip html tags
  303. html = re.sub('<.*?>', '', html)
  304. # Replace html entities
  305. html = unescapeHTML(html)
  306. return html.strip()
  307. def sanitize_open(filename, open_mode):
  308. """Try to open the given filename, and slightly tweak it if this fails.
  309. Attempts to open the given filename. If this fails, it tries to change
  310. the filename slightly, step by step, until it's either able to open it
  311. or it fails and raises a final exception, like the standard open()
  312. function.
  313. It returns the tuple (stream, definitive_file_name).
  314. """
  315. try:
  316. if filename == u'-':
  317. if sys.platform == 'win32':
  318. import msvcrt
  319. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  320. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  321. stream = open(encodeFilename(filename), open_mode)
  322. return (stream, filename)
  323. except (IOError, OSError) as err:
  324. if err.errno in (errno.EACCES,):
  325. raise
  326. # In case of error, try to remove win32 forbidden chars
  327. alt_filename = os.path.join(
  328. re.sub(u'[/<>:"\\|\\\\?\\*]', u'#', path_part)
  329. for path_part in os.path.split(filename)
  330. )
  331. if alt_filename == filename:
  332. raise
  333. else:
  334. # An exception here should be caught in the caller
  335. stream = open(encodeFilename(filename), open_mode)
  336. return (stream, alt_filename)
  337. def timeconvert(timestr):
  338. """Convert RFC 2822 defined time string into system timestamp"""
  339. timestamp = None
  340. timetuple = email.utils.parsedate_tz(timestr)
  341. if timetuple is not None:
  342. timestamp = email.utils.mktime_tz(timetuple)
  343. return timestamp
  344. def sanitize_filename(s, restricted=False, is_id=False):
  345. """Sanitizes a string so it could be used as part of a filename.
  346. If restricted is set, use a stricter subset of allowed characters.
  347. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  348. """
  349. def replace_insane(char):
  350. if char == '?' or ord(char) < 32 or ord(char) == 127:
  351. return ''
  352. elif char == '"':
  353. return '' if restricted else '\''
  354. elif char == ':':
  355. return '_-' if restricted else ' -'
  356. elif char in '\\/|*<>':
  357. return '_'
  358. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  359. return '_'
  360. if restricted and ord(char) > 127:
  361. return '_'
  362. return char
  363. result = u''.join(map(replace_insane, s))
  364. if not is_id:
  365. while '__' in result:
  366. result = result.replace('__', '_')
  367. result = result.strip('_')
  368. # Common case of "Foreign band name - English song title"
  369. if restricted and result.startswith('-_'):
  370. result = result[2:]
  371. if not result:
  372. result = '_'
  373. return result
  374. def orderedSet(iterable):
  375. """ Remove all duplicates from the input iterable """
  376. res = []
  377. for el in iterable:
  378. if el not in res:
  379. res.append(el)
  380. return res
  381. def unescapeHTML(s):
  382. """
  383. @param s a string
  384. """
  385. assert type(s) == type(u'')
  386. result = re.sub(u'(?u)&(.+?);', htmlentity_transform, s)
  387. return result
  388. def encodeFilename(s):
  389. """
  390. @param s The name of the file
  391. """
  392. assert type(s) == type(u'')
  393. # Python 3 has a Unicode API
  394. if sys.version_info >= (3, 0):
  395. return s
  396. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  397. # Pass u'' directly to use Unicode APIs on Windows 2000 and up
  398. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  399. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  400. return s
  401. else:
  402. encoding = sys.getfilesystemencoding()
  403. if encoding is None:
  404. encoding = 'utf-8'
  405. return s.encode(encoding, 'ignore')
  406. def decodeOption(optval):
  407. if optval is None:
  408. return optval
  409. if isinstance(optval, bytes):
  410. optval = optval.decode(preferredencoding())
  411. assert isinstance(optval, compat_str)
  412. return optval
  413. def formatSeconds(secs):
  414. if secs > 3600:
  415. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  416. elif secs > 60:
  417. return '%d:%02d' % (secs // 60, secs % 60)
  418. else:
  419. return '%d' % secs
  420. def make_HTTPS_handler(opts):
  421. if sys.version_info < (3,2):
  422. # Python's 2.x handler is very simplistic
  423. return compat_urllib_request.HTTPSHandler()
  424. else:
  425. import ssl
  426. context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
  427. context.set_default_verify_paths()
  428. context.verify_mode = (ssl.CERT_NONE
  429. if opts.no_check_certificate
  430. else ssl.CERT_REQUIRED)
  431. return compat_urllib_request.HTTPSHandler(context=context)
  432. class ExtractorError(Exception):
  433. """Error during info extraction."""
  434. def __init__(self, msg, tb=None, expected=False, cause=None):
  435. """ tb, if given, is the original traceback (so that it can be printed out).
  436. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  437. """
  438. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  439. expected = True
  440. if not expected:
  441. msg = msg + u'; please report this issue on https://yt-dl.org/bug . Be sure to call youtube-dl with the --verbose flag and include its complete output. Make sure you are using the latest version; type youtube-dl -U to update.'
  442. super(ExtractorError, self).__init__(msg)
  443. self.traceback = tb
  444. self.exc_info = sys.exc_info() # preserve original exception
  445. self.cause = cause
  446. def format_traceback(self):
  447. if self.traceback is None:
  448. return None
  449. return u''.join(traceback.format_tb(self.traceback))
  450. class DownloadError(Exception):
  451. """Download Error exception.
  452. This exception may be thrown by FileDownloader objects if they are not
  453. configured to continue on errors. They will contain the appropriate
  454. error message.
  455. """
  456. def __init__(self, msg, exc_info=None):
  457. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  458. super(DownloadError, self).__init__(msg)
  459. self.exc_info = exc_info
  460. class SameFileError(Exception):
  461. """Same File exception.
  462. This exception will be thrown by FileDownloader objects if they detect
  463. multiple files would have to be downloaded to the same file on disk.
  464. """
  465. pass
  466. class PostProcessingError(Exception):
  467. """Post Processing exception.
  468. This exception may be raised by PostProcessor's .run() method to
  469. indicate an error in the postprocessing task.
  470. """
  471. def __init__(self, msg):
  472. self.msg = msg
  473. class MaxDownloadsReached(Exception):
  474. """ --max-downloads limit has been reached. """
  475. pass
  476. class UnavailableVideoError(Exception):
  477. """Unavailable Format exception.
  478. This exception will be thrown when a video is requested
  479. in a format that is not available for that video.
  480. """
  481. pass
  482. class ContentTooShortError(Exception):
  483. """Content Too Short exception.
  484. This exception may be raised by FileDownloader objects when a file they
  485. download is too small for what the server announced first, indicating
  486. the connection was probably interrupted.
  487. """
  488. # Both in bytes
  489. downloaded = None
  490. expected = None
  491. def __init__(self, downloaded, expected):
  492. self.downloaded = downloaded
  493. self.expected = expected
  494. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  495. """Handler for HTTP requests and responses.
  496. This class, when installed with an OpenerDirector, automatically adds
  497. the standard headers to every HTTP request and handles gzipped and
  498. deflated responses from web servers. If compression is to be avoided in
  499. a particular request, the original request in the program code only has
  500. to include the HTTP header "Youtubedl-No-Compression", which will be
  501. removed before making the real request.
  502. Part of this code was copied from:
  503. http://techknack.net/python-urllib2-handlers/
  504. Andrew Rowls, the author of that code, agreed to release it to the
  505. public domain.
  506. """
  507. @staticmethod
  508. def deflate(data):
  509. try:
  510. return zlib.decompress(data, -zlib.MAX_WBITS)
  511. except zlib.error:
  512. return zlib.decompress(data)
  513. @staticmethod
  514. def addinfourl_wrapper(stream, headers, url, code):
  515. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  516. return compat_urllib_request.addinfourl(stream, headers, url, code)
  517. ret = compat_urllib_request.addinfourl(stream, headers, url)
  518. ret.code = code
  519. return ret
  520. def http_request(self, req):
  521. for h,v in std_headers.items():
  522. if h in req.headers:
  523. del req.headers[h]
  524. req.add_header(h, v)
  525. if 'Youtubedl-no-compression' in req.headers:
  526. if 'Accept-encoding' in req.headers:
  527. del req.headers['Accept-encoding']
  528. del req.headers['Youtubedl-no-compression']
  529. if 'Youtubedl-user-agent' in req.headers:
  530. if 'User-agent' in req.headers:
  531. del req.headers['User-agent']
  532. req.headers['User-agent'] = req.headers['Youtubedl-user-agent']
  533. del req.headers['Youtubedl-user-agent']
  534. return req
  535. def http_response(self, req, resp):
  536. old_resp = resp
  537. # gzip
  538. if resp.headers.get('Content-encoding', '') == 'gzip':
  539. content = resp.read()
  540. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  541. try:
  542. uncompressed = io.BytesIO(gz.read())
  543. except IOError as original_ioerror:
  544. # There may be junk add the end of the file
  545. # See http://stackoverflow.com/q/4928560/35070 for details
  546. for i in range(1, 1024):
  547. try:
  548. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  549. uncompressed = io.BytesIO(gz.read())
  550. except IOError:
  551. continue
  552. break
  553. else:
  554. raise original_ioerror
  555. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  556. resp.msg = old_resp.msg
  557. # deflate
  558. if resp.headers.get('Content-encoding', '') == 'deflate':
  559. gz = io.BytesIO(self.deflate(resp.read()))
  560. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  561. resp.msg = old_resp.msg
  562. return resp
  563. https_request = http_request
  564. https_response = http_response
  565. def unified_strdate(date_str):
  566. """Return a string with the date in the format YYYYMMDD"""
  567. upload_date = None
  568. #Replace commas
  569. date_str = date_str.replace(',',' ')
  570. # %z (UTC offset) is only supported in python>=3.2
  571. date_str = re.sub(r' (\+|-)[\d]*$', '', date_str)
  572. format_expressions = ['%d %B %Y', '%B %d %Y', '%b %d %Y', '%Y-%m-%d', '%d/%m/%Y', '%Y/%m/%d %H:%M:%S', '%d.%m.%Y %H:%M']
  573. for expression in format_expressions:
  574. try:
  575. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  576. except:
  577. pass
  578. return upload_date
  579. def determine_ext(url, default_ext=u'unknown_video'):
  580. guess = url.partition(u'?')[0].rpartition(u'.')[2]
  581. if re.match(r'^[A-Za-z0-9]+$', guess):
  582. return guess
  583. else:
  584. return default_ext
  585. def subtitles_filename(filename, sub_lang, sub_format):
  586. return filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  587. def date_from_str(date_str):
  588. """
  589. Return a datetime object from a string in the format YYYYMMDD or
  590. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  591. today = datetime.date.today()
  592. if date_str == 'now'or date_str == 'today':
  593. return today
  594. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  595. if match is not None:
  596. sign = match.group('sign')
  597. time = int(match.group('time'))
  598. if sign == '-':
  599. time = -time
  600. unit = match.group('unit')
  601. #A bad aproximation?
  602. if unit == 'month':
  603. unit = 'day'
  604. time *= 30
  605. elif unit == 'year':
  606. unit = 'day'
  607. time *= 365
  608. unit += 's'
  609. delta = datetime.timedelta(**{unit: time})
  610. return today + delta
  611. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  612. class DateRange(object):
  613. """Represents a time interval between two dates"""
  614. def __init__(self, start=None, end=None):
  615. """start and end must be strings in the format accepted by date"""
  616. if start is not None:
  617. self.start = date_from_str(start)
  618. else:
  619. self.start = datetime.datetime.min.date()
  620. if end is not None:
  621. self.end = date_from_str(end)
  622. else:
  623. self.end = datetime.datetime.max.date()
  624. if self.start > self.end:
  625. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  626. @classmethod
  627. def day(cls, day):
  628. """Returns a range that only contains the given day"""
  629. return cls(day,day)
  630. def __contains__(self, date):
  631. """Check if the date is in the range"""
  632. if not isinstance(date, datetime.date):
  633. date = date_from_str(date)
  634. return self.start <= date <= self.end
  635. def __str__(self):
  636. return '%s - %s' % ( self.start.isoformat(), self.end.isoformat())
  637. def platform_name():
  638. """ Returns the platform name as a compat_str """
  639. res = platform.platform()
  640. if isinstance(res, bytes):
  641. res = res.decode(preferredencoding())
  642. assert isinstance(res, compat_str)
  643. return res
  644. def bytes_to_intlist(bs):
  645. if not bs:
  646. return []
  647. if isinstance(bs[0], int): # Python 3
  648. return list(bs)
  649. else:
  650. return [ord(c) for c in bs]
  651. def intlist_to_bytes(xs):
  652. if not xs:
  653. return b''
  654. if isinstance(chr(0), bytes): # Python 2
  655. return ''.join([chr(x) for x in xs])
  656. else:
  657. return bytes(xs)