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.

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