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.

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