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.

734 lines
25 KiB

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