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.

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