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.

2905 lines
86 KiB

10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
[utils] Remove Content-encoding from headers after decompression With cn_verification_proxy, our http_response() is called twice, one from PerRequestProxyHandler.proxy_open() and another from normal YoutubeDL.urlopen(). As a result, for proxies honoring Accept-Encoding, the following bug occurs: $ youtube-dl -vs --cn-verification-proxy https://secure.uku.im:993 "test:letv" [debug] System config: [] [debug] User config: [] [debug] Command-line args: ['-vs', '--cn-verification-proxy', 'https://secure.uku.im:993', 'test:letv'] [debug] Encodings: locale UTF-8, fs utf-8, out UTF-8, pref UTF-8 [debug] youtube-dl version 2015.12.23 [debug] Git HEAD: 97f18fa [debug] Python version 3.5.1 - Linux-4.3.3-1-ARCH-x86_64-with-arch-Arch-Linux [debug] exe versions: ffmpeg 2.8.4, ffprobe 2.8.4, rtmpdump 2.4 [debug] Proxy map: {} [TestURL] Test URL: http://www.letv.com/ptv/vplay/22005890.html [Letv] 22005890: Downloading webpage [Letv] 22005890: Downloading playJson data ERROR: Unable to download JSON metadata: Not a gzipped file (b'{"') (caused by OSError('Not a gzipped file (b\'{"\')',)); please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output. File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/extractor/common.py", line 330, in _request_webpage return self._downloader.urlopen(url_or_request) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/YoutubeDL.py", line 1886, in urlopen return self._opener.open(req, timeout=self._socket_timeout) File "/usr/lib/python3.5/urllib/request.py", line 471, in open response = meth(req, response) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 773, in http_response raise original_ioerror File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 761, in http_response uncompressed = io.BytesIO(gz.read()) File "/usr/lib/python3.5/gzip.py", line 274, in read return self._buffer.read(size) File "/usr/lib/python3.5/gzip.py", line 461, in read if not self._read_gzip_header(): File "/usr/lib/python3.5/gzip.py", line 409, in _read_gzip_header raise OSError('Not a gzipped file (%r)' % magic)
9 years ago
[utils] Remove Content-encoding from headers after decompression With cn_verification_proxy, our http_response() is called twice, one from PerRequestProxyHandler.proxy_open() and another from normal YoutubeDL.urlopen(). As a result, for proxies honoring Accept-Encoding, the following bug occurs: $ youtube-dl -vs --cn-verification-proxy https://secure.uku.im:993 "test:letv" [debug] System config: [] [debug] User config: [] [debug] Command-line args: ['-vs', '--cn-verification-proxy', 'https://secure.uku.im:993', 'test:letv'] [debug] Encodings: locale UTF-8, fs utf-8, out UTF-8, pref UTF-8 [debug] youtube-dl version 2015.12.23 [debug] Git HEAD: 97f18fa [debug] Python version 3.5.1 - Linux-4.3.3-1-ARCH-x86_64-with-arch-Arch-Linux [debug] exe versions: ffmpeg 2.8.4, ffprobe 2.8.4, rtmpdump 2.4 [debug] Proxy map: {} [TestURL] Test URL: http://www.letv.com/ptv/vplay/22005890.html [Letv] 22005890: Downloading webpage [Letv] 22005890: Downloading playJson data ERROR: Unable to download JSON metadata: Not a gzipped file (b'{"') (caused by OSError('Not a gzipped file (b\'{"\')',)); please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output. File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/extractor/common.py", line 330, in _request_webpage return self._downloader.urlopen(url_or_request) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/YoutubeDL.py", line 1886, in urlopen return self._opener.open(req, timeout=self._socket_timeout) File "/usr/lib/python3.5/urllib/request.py", line 471, in open response = meth(req, response) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 773, in http_response raise original_ioerror File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 761, in http_response uncompressed = io.BytesIO(gz.read()) File "/usr/lib/python3.5/gzip.py", line 274, in read return self._buffer.read(size) File "/usr/lib/python3.5/gzip.py", line 461, in read if not self._read_gzip_header(): File "/usr/lib/python3.5/gzip.py", line 409, in _read_gzip_header raise OSError('Not a gzipped file (%r)' % magic)
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import unicode_literals
  4. import base64
  5. import binascii
  6. import calendar
  7. import codecs
  8. import contextlib
  9. import ctypes
  10. import datetime
  11. import email.utils
  12. import errno
  13. import functools
  14. import gzip
  15. import io
  16. import itertools
  17. import json
  18. import locale
  19. import math
  20. import operator
  21. import os
  22. import pipes
  23. import platform
  24. import re
  25. import socket
  26. import ssl
  27. import subprocess
  28. import sys
  29. import tempfile
  30. import traceback
  31. import xml.etree.ElementTree
  32. import zlib
  33. from .compat import (
  34. compat_HTMLParser,
  35. compat_basestring,
  36. compat_chr,
  37. compat_etree_fromstring,
  38. compat_html_entities,
  39. compat_html_entities_html5,
  40. compat_http_client,
  41. compat_kwargs,
  42. compat_parse_qs,
  43. compat_shlex_quote,
  44. compat_socket_create_connection,
  45. compat_str,
  46. compat_struct_pack,
  47. compat_urllib_error,
  48. compat_urllib_parse,
  49. compat_urllib_parse_urlencode,
  50. compat_urllib_parse_urlparse,
  51. compat_urllib_parse_unquote_plus,
  52. compat_urllib_request,
  53. compat_urlparse,
  54. compat_xpath,
  55. )
  56. from .socks import (
  57. ProxyType,
  58. sockssocket,
  59. )
  60. def register_socks_protocols():
  61. # "Register" SOCKS protocols
  62. # In Python < 2.6.5, urlsplit() suffers from bug https://bugs.python.org/issue7904
  63. # URLs with protocols not in urlparse.uses_netloc are not handled correctly
  64. for scheme in ('socks', 'socks4', 'socks4a', 'socks5'):
  65. if scheme not in compat_urlparse.uses_netloc:
  66. compat_urlparse.uses_netloc.append(scheme)
  67. # This is not clearly defined otherwise
  68. compiled_regex_type = type(re.compile(''))
  69. std_headers = {
  70. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/47.0 (Chrome)',
  71. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  72. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  73. 'Accept-Encoding': 'gzip, deflate',
  74. 'Accept-Language': 'en-us,en;q=0.5',
  75. }
  76. NO_DEFAULT = object()
  77. ENGLISH_MONTH_NAMES = [
  78. 'January', 'February', 'March', 'April', 'May', 'June',
  79. 'July', 'August', 'September', 'October', 'November', 'December']
  80. KNOWN_EXTENSIONS = (
  81. 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'aac',
  82. 'flv', 'f4v', 'f4a', 'f4b',
  83. 'webm', 'ogg', 'ogv', 'oga', 'ogx', 'spx', 'opus',
  84. 'mkv', 'mka', 'mk3d',
  85. 'avi', 'divx',
  86. 'mov',
  87. 'asf', 'wmv', 'wma',
  88. '3gp', '3g2',
  89. 'mp3',
  90. 'flac',
  91. 'ape',
  92. 'wav',
  93. 'f4f', 'f4m', 'm3u8', 'smil')
  94. # needed for sanitizing filenames in restricted mode
  95. ACCENT_CHARS = dict(zip('ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ',
  96. itertools.chain('AAAAAA', ['AE'], 'CEEEEIIIIDNOOOOOOO', ['OE'], 'UUUUUYP', ['ss'],
  97. 'aaaaaa', ['ae'], 'ceeeeiiiionooooooo', ['oe'], 'uuuuuypy')))
  98. DATE_FORMATS = (
  99. '%d %B %Y',
  100. '%d %b %Y',
  101. '%B %d %Y',
  102. '%b %d %Y',
  103. '%b %dst %Y %I:%M',
  104. '%b %dnd %Y %I:%M',
  105. '%b %dth %Y %I:%M',
  106. '%Y %m %d',
  107. '%Y-%m-%d',
  108. '%Y/%m/%d',
  109. '%Y/%m/%d %H:%M:%S',
  110. '%Y-%m-%d %H:%M:%S',
  111. '%Y-%m-%d %H:%M:%S.%f',
  112. '%d.%m.%Y %H:%M',
  113. '%d.%m.%Y %H.%M',
  114. '%Y-%m-%dT%H:%M:%SZ',
  115. '%Y-%m-%dT%H:%M:%S.%fZ',
  116. '%Y-%m-%dT%H:%M:%S.%f0Z',
  117. '%Y-%m-%dT%H:%M:%S',
  118. '%Y-%m-%dT%H:%M:%S.%f',
  119. '%Y-%m-%dT%H:%M',
  120. )
  121. DATE_FORMATS_DAY_FIRST = list(DATE_FORMATS)
  122. DATE_FORMATS_DAY_FIRST.extend([
  123. '%d-%m-%Y',
  124. '%d.%m.%Y',
  125. '%d.%m.%y',
  126. '%d/%m/%Y',
  127. '%d/%m/%y',
  128. '%d/%m/%Y %H:%M:%S',
  129. ])
  130. DATE_FORMATS_MONTH_FIRST = list(DATE_FORMATS)
  131. DATE_FORMATS_MONTH_FIRST.extend([
  132. '%m-%d-%Y',
  133. '%m.%d.%Y',
  134. '%m/%d/%Y',
  135. '%m/%d/%y',
  136. '%m/%d/%Y %H:%M:%S',
  137. ])
  138. def preferredencoding():
  139. """Get preferred encoding.
  140. Returns the best encoding scheme for the system, based on
  141. locale.getpreferredencoding() and some further tweaks.
  142. """
  143. try:
  144. pref = locale.getpreferredencoding()
  145. 'TEST'.encode(pref)
  146. except Exception:
  147. pref = 'UTF-8'
  148. return pref
  149. def write_json_file(obj, fn):
  150. """ Encode obj as JSON and write it to fn, atomically if possible """
  151. fn = encodeFilename(fn)
  152. if sys.version_info < (3, 0) and sys.platform != 'win32':
  153. encoding = get_filesystem_encoding()
  154. # os.path.basename returns a bytes object, but NamedTemporaryFile
  155. # will fail if the filename contains non ascii characters unless we
  156. # use a unicode object
  157. path_basename = lambda f: os.path.basename(fn).decode(encoding)
  158. # the same for os.path.dirname
  159. path_dirname = lambda f: os.path.dirname(fn).decode(encoding)
  160. else:
  161. path_basename = os.path.basename
  162. path_dirname = os.path.dirname
  163. args = {
  164. 'suffix': '.tmp',
  165. 'prefix': path_basename(fn) + '.',
  166. 'dir': path_dirname(fn),
  167. 'delete': False,
  168. }
  169. # In Python 2.x, json.dump expects a bytestream.
  170. # In Python 3.x, it writes to a character stream
  171. if sys.version_info < (3, 0):
  172. args['mode'] = 'wb'
  173. else:
  174. args.update({
  175. 'mode': 'w',
  176. 'encoding': 'utf-8',
  177. })
  178. tf = tempfile.NamedTemporaryFile(**compat_kwargs(args))
  179. try:
  180. with tf:
  181. json.dump(obj, tf)
  182. if sys.platform == 'win32':
  183. # Need to remove existing file on Windows, else os.rename raises
  184. # WindowsError or FileExistsError.
  185. try:
  186. os.unlink(fn)
  187. except OSError:
  188. pass
  189. os.rename(tf.name, fn)
  190. except Exception:
  191. try:
  192. os.remove(tf.name)
  193. except OSError:
  194. pass
  195. raise
  196. if sys.version_info >= (2, 7):
  197. def find_xpath_attr(node, xpath, key, val=None):
  198. """ Find the xpath xpath[@key=val] """
  199. assert re.match(r'^[a-zA-Z_-]+$', key)
  200. expr = xpath + ('[@%s]' % key if val is None else "[@%s='%s']" % (key, val))
  201. return node.find(expr)
  202. else:
  203. def find_xpath_attr(node, xpath, key, val=None):
  204. for f in node.findall(compat_xpath(xpath)):
  205. if key not in f.attrib:
  206. continue
  207. if val is None or f.attrib.get(key) == val:
  208. return f
  209. return None
  210. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  211. # the namespace parameter
  212. def xpath_with_ns(path, ns_map):
  213. components = [c.split(':') for c in path.split('/')]
  214. replaced = []
  215. for c in components:
  216. if len(c) == 1:
  217. replaced.append(c[0])
  218. else:
  219. ns, tag = c
  220. replaced.append('{%s}%s' % (ns_map[ns], tag))
  221. return '/'.join(replaced)
  222. def xpath_element(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  223. def _find_xpath(xpath):
  224. return node.find(compat_xpath(xpath))
  225. if isinstance(xpath, (str, compat_str)):
  226. n = _find_xpath(xpath)
  227. else:
  228. for xp in xpath:
  229. n = _find_xpath(xp)
  230. if n is not None:
  231. break
  232. if n is None:
  233. if default is not NO_DEFAULT:
  234. return default
  235. elif fatal:
  236. name = xpath if name is None else name
  237. raise ExtractorError('Could not find XML element %s' % name)
  238. else:
  239. return None
  240. return n
  241. def xpath_text(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  242. n = xpath_element(node, xpath, name, fatal=fatal, default=default)
  243. if n is None or n == default:
  244. return n
  245. if n.text is None:
  246. if default is not NO_DEFAULT:
  247. return default
  248. elif fatal:
  249. name = xpath if name is None else name
  250. raise ExtractorError('Could not find XML element\'s text %s' % name)
  251. else:
  252. return None
  253. return n.text
  254. def xpath_attr(node, xpath, key, name=None, fatal=False, default=NO_DEFAULT):
  255. n = find_xpath_attr(node, xpath, key)
  256. if n is None:
  257. if default is not NO_DEFAULT:
  258. return default
  259. elif fatal:
  260. name = '%s[@%s]' % (xpath, key) if name is None else name
  261. raise ExtractorError('Could not find XML attribute %s' % name)
  262. else:
  263. return None
  264. return n.attrib[key]
  265. def get_element_by_id(id, html):
  266. """Return the content of the tag with the specified ID in the passed HTML document"""
  267. return get_element_by_attribute('id', id, html)
  268. def get_element_by_attribute(attribute, value, html):
  269. """Return the content of the tag with the specified attribute in the passed HTML document"""
  270. m = re.search(r'''(?xs)
  271. <([a-zA-Z0-9:._-]+)
  272. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'))*?
  273. \s+%s=['"]?%s['"]?
  274. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'))*?
  275. \s*>
  276. (?P<content>.*?)
  277. </\1>
  278. ''' % (re.escape(attribute), re.escape(value)), html)
  279. if not m:
  280. return None
  281. res = m.group('content')
  282. if res.startswith('"') or res.startswith("'"):
  283. res = res[1:-1]
  284. return unescapeHTML(res)
  285. class HTMLAttributeParser(compat_HTMLParser):
  286. """Trivial HTML parser to gather the attributes for a single element"""
  287. def __init__(self):
  288. self.attrs = {}
  289. compat_HTMLParser.__init__(self)
  290. def handle_starttag(self, tag, attrs):
  291. self.attrs = dict(attrs)
  292. def extract_attributes(html_element):
  293. """Given a string for an HTML element such as
  294. <el
  295. a="foo" B="bar" c="&98;az" d=boz
  296. empty= noval entity="&amp;"
  297. sq='"' dq="'"
  298. >
  299. Decode and return a dictionary of attributes.
  300. {
  301. 'a': 'foo', 'b': 'bar', c: 'baz', d: 'boz',
  302. 'empty': '', 'noval': None, 'entity': '&',
  303. 'sq': '"', 'dq': '\''
  304. }.
  305. NB HTMLParser is stricter in Python 2.6 & 3.2 than in later versions,
  306. but the cases in the unit test will work for all of 2.6, 2.7, 3.2-3.5.
  307. """
  308. parser = HTMLAttributeParser()
  309. parser.feed(html_element)
  310. parser.close()
  311. return parser.attrs
  312. def clean_html(html):
  313. """Clean an HTML snippet into a readable string"""
  314. if html is None: # Convenience for sanitizing descriptions etc.
  315. return html
  316. # Newline vs <br />
  317. html = html.replace('\n', ' ')
  318. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  319. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  320. # Strip html tags
  321. html = re.sub('<.*?>', '', html)
  322. # Replace html entities
  323. html = unescapeHTML(html)
  324. return html.strip()
  325. def sanitize_open(filename, open_mode):
  326. """Try to open the given filename, and slightly tweak it if this fails.
  327. Attempts to open the given filename. If this fails, it tries to change
  328. the filename slightly, step by step, until it's either able to open it
  329. or it fails and raises a final exception, like the standard open()
  330. function.
  331. It returns the tuple (stream, definitive_file_name).
  332. """
  333. try:
  334. if filename == '-':
  335. if sys.platform == 'win32':
  336. import msvcrt
  337. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  338. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  339. stream = open(encodeFilename(filename), open_mode)
  340. return (stream, filename)
  341. except (IOError, OSError) as err:
  342. if err.errno in (errno.EACCES,):
  343. raise
  344. # In case of error, try to remove win32 forbidden chars
  345. alt_filename = sanitize_path(filename)
  346. if alt_filename == filename:
  347. raise
  348. else:
  349. # An exception here should be caught in the caller
  350. stream = open(encodeFilename(alt_filename), open_mode)
  351. return (stream, alt_filename)
  352. def timeconvert(timestr):
  353. """Convert RFC 2822 defined time string into system timestamp"""
  354. timestamp = None
  355. timetuple = email.utils.parsedate_tz(timestr)
  356. if timetuple is not None:
  357. timestamp = email.utils.mktime_tz(timetuple)
  358. return timestamp
  359. def sanitize_filename(s, restricted=False, is_id=False):
  360. """Sanitizes a string so it could be used as part of a filename.
  361. If restricted is set, use a stricter subset of allowed characters.
  362. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  363. """
  364. def replace_insane(char):
  365. if restricted and char in ACCENT_CHARS:
  366. return ACCENT_CHARS[char]
  367. if char == '?' or ord(char) < 32 or ord(char) == 127:
  368. return ''
  369. elif char == '"':
  370. return '' if restricted else '\''
  371. elif char == ':':
  372. return '_-' if restricted else ' -'
  373. elif char in '\\/|*<>':
  374. return '_'
  375. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  376. return '_'
  377. if restricted and ord(char) > 127:
  378. return '_'
  379. return char
  380. # Handle timestamps
  381. s = re.sub(r'[0-9]+(?::[0-9]+)+', lambda m: m.group(0).replace(':', '_'), s)
  382. result = ''.join(map(replace_insane, s))
  383. if not is_id:
  384. while '__' in result:
  385. result = result.replace('__', '_')
  386. result = result.strip('_')
  387. # Common case of "Foreign band name - English song title"
  388. if restricted and result.startswith('-_'):
  389. result = result[2:]
  390. if result.startswith('-'):
  391. result = '_' + result[len('-'):]
  392. result = result.lstrip('.')
  393. if not result:
  394. result = '_'
  395. return result
  396. def sanitize_path(s):
  397. """Sanitizes and normalizes path on Windows"""
  398. if sys.platform != 'win32':
  399. return s
  400. drive_or_unc, _ = os.path.splitdrive(s)
  401. if sys.version_info < (2, 7) and not drive_or_unc:
  402. drive_or_unc, _ = os.path.splitunc(s)
  403. norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
  404. if drive_or_unc:
  405. norm_path.pop(0)
  406. sanitized_path = [
  407. path_part if path_part in ['.', '..'] else re.sub('(?:[/<>:"\\|\\\\?\\*]|[\s.]$)', '#', path_part)
  408. for path_part in norm_path]
  409. if drive_or_unc:
  410. sanitized_path.insert(0, drive_or_unc + os.path.sep)
  411. return os.path.join(*sanitized_path)
  412. # Prepend protocol-less URLs with `http:` scheme in order to mitigate the number of
  413. # unwanted failures due to missing protocol
  414. def sanitize_url(url):
  415. return 'http:%s' % url if url.startswith('//') else url
  416. def sanitized_Request(url, *args, **kwargs):
  417. return compat_urllib_request.Request(sanitize_url(url), *args, **kwargs)
  418. def orderedSet(iterable):
  419. """ Remove all duplicates from the input iterable """
  420. res = []
  421. for el in iterable:
  422. if el not in res:
  423. res.append(el)
  424. return res
  425. def _htmlentity_transform(entity_with_semicolon):
  426. """Transforms an HTML entity to a character."""
  427. entity = entity_with_semicolon[:-1]
  428. # Known non-numeric HTML entity
  429. if entity in compat_html_entities.name2codepoint:
  430. return compat_chr(compat_html_entities.name2codepoint[entity])
  431. # TODO: HTML5 allows entities without a semicolon. For example,
  432. # '&Eacuteric' should be decoded as 'Éric'.
  433. if entity_with_semicolon in compat_html_entities_html5:
  434. return compat_html_entities_html5[entity_with_semicolon]
  435. mobj = re.match(r'#(x[0-9a-fA-F]+|[0-9]+)', entity)
  436. if mobj is not None:
  437. numstr = mobj.group(1)
  438. if numstr.startswith('x'):
  439. base = 16
  440. numstr = '0%s' % numstr
  441. else:
  442. base = 10
  443. # See https://github.com/rg3/youtube-dl/issues/7518
  444. try:
  445. return compat_chr(int(numstr, base))
  446. except ValueError:
  447. pass
  448. # Unknown entity in name, return its literal representation
  449. return '&%s;' % entity
  450. def unescapeHTML(s):
  451. if s is None:
  452. return None
  453. assert type(s) == compat_str
  454. return re.sub(
  455. r'&([^;]+;)', lambda m: _htmlentity_transform(m.group(1)), s)
  456. def get_subprocess_encoding():
  457. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  458. # For subprocess calls, encode with locale encoding
  459. # Refer to http://stackoverflow.com/a/9951851/35070
  460. encoding = preferredencoding()
  461. else:
  462. encoding = sys.getfilesystemencoding()
  463. if encoding is None:
  464. encoding = 'utf-8'
  465. return encoding
  466. def encodeFilename(s, for_subprocess=False):
  467. """
  468. @param s The name of the file
  469. """
  470. assert type(s) == compat_str
  471. # Python 3 has a Unicode API
  472. if sys.version_info >= (3, 0):
  473. return s
  474. # Pass '' directly to use Unicode APIs on Windows 2000 and up
  475. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  476. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  477. if not for_subprocess and sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  478. return s
  479. # Jython assumes filenames are Unicode strings though reported as Python 2.x compatible
  480. if sys.platform.startswith('java'):
  481. return s
  482. return s.encode(get_subprocess_encoding(), 'ignore')
  483. def decodeFilename(b, for_subprocess=False):
  484. if sys.version_info >= (3, 0):
  485. return b
  486. if not isinstance(b, bytes):
  487. return b
  488. return b.decode(get_subprocess_encoding(), 'ignore')
  489. def encodeArgument(s):
  490. if not isinstance(s, compat_str):
  491. # Legacy code that uses byte strings
  492. # Uncomment the following line after fixing all post processors
  493. # assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
  494. s = s.decode('ascii')
  495. return encodeFilename(s, True)
  496. def decodeArgument(b):
  497. return decodeFilename(b, True)
  498. def decodeOption(optval):
  499. if optval is None:
  500. return optval
  501. if isinstance(optval, bytes):
  502. optval = optval.decode(preferredencoding())
  503. assert isinstance(optval, compat_str)
  504. return optval
  505. def formatSeconds(secs):
  506. if secs > 3600:
  507. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  508. elif secs > 60:
  509. return '%d:%02d' % (secs // 60, secs % 60)
  510. else:
  511. return '%d' % secs
  512. def make_HTTPS_handler(params, **kwargs):
  513. opts_no_check_certificate = params.get('nocheckcertificate', False)
  514. if hasattr(ssl, 'create_default_context'): # Python >= 3.4 or 2.7.9
  515. context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  516. if opts_no_check_certificate:
  517. context.check_hostname = False
  518. context.verify_mode = ssl.CERT_NONE
  519. try:
  520. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  521. except TypeError:
  522. # Python 2.7.8
  523. # (create_default_context present but HTTPSHandler has no context=)
  524. pass
  525. if sys.version_info < (3, 2):
  526. return YoutubeDLHTTPSHandler(params, **kwargs)
  527. else: # Python < 3.4
  528. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  529. context.verify_mode = (ssl.CERT_NONE
  530. if opts_no_check_certificate
  531. else ssl.CERT_REQUIRED)
  532. context.set_default_verify_paths()
  533. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  534. def bug_reports_message():
  535. if ytdl_is_updateable():
  536. update_cmd = 'type youtube-dl -U to update'
  537. else:
  538. update_cmd = 'see https://yt-dl.org/update on how to update'
  539. msg = '; please report this issue on https://yt-dl.org/bug .'
  540. msg += ' Make sure you are using the latest version; %s.' % update_cmd
  541. msg += ' Be sure to call youtube-dl with the --verbose flag and include its complete output.'
  542. return msg
  543. class ExtractorError(Exception):
  544. """Error during info extraction."""
  545. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  546. """ tb, if given, is the original traceback (so that it can be printed out).
  547. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  548. """
  549. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  550. expected = True
  551. if video_id is not None:
  552. msg = video_id + ': ' + msg
  553. if cause:
  554. msg += ' (caused by %r)' % cause
  555. if not expected:
  556. msg += bug_reports_message()
  557. super(ExtractorError, self).__init__(msg)
  558. self.traceback = tb
  559. self.exc_info = sys.exc_info() # preserve original exception
  560. self.cause = cause
  561. self.video_id = video_id
  562. def format_traceback(self):
  563. if self.traceback is None:
  564. return None
  565. return ''.join(traceback.format_tb(self.traceback))
  566. class UnsupportedError(ExtractorError):
  567. def __init__(self, url):
  568. super(UnsupportedError, self).__init__(
  569. 'Unsupported URL: %s' % url, expected=True)
  570. self.url = url
  571. class RegexNotFoundError(ExtractorError):
  572. """Error when a regex didn't match"""
  573. pass
  574. class DownloadError(Exception):
  575. """Download Error exception.
  576. This exception may be thrown by FileDownloader objects if they are not
  577. configured to continue on errors. They will contain the appropriate
  578. error message.
  579. """
  580. def __init__(self, msg, exc_info=None):
  581. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  582. super(DownloadError, self).__init__(msg)
  583. self.exc_info = exc_info
  584. class SameFileError(Exception):
  585. """Same File exception.
  586. This exception will be thrown by FileDownloader objects if they detect
  587. multiple files would have to be downloaded to the same file on disk.
  588. """
  589. pass
  590. class PostProcessingError(Exception):
  591. """Post Processing exception.
  592. This exception may be raised by PostProcessor's .run() method to
  593. indicate an error in the postprocessing task.
  594. """
  595. def __init__(self, msg):
  596. self.msg = msg
  597. class MaxDownloadsReached(Exception):
  598. """ --max-downloads limit has been reached. """
  599. pass
  600. class UnavailableVideoError(Exception):
  601. """Unavailable Format exception.
  602. This exception will be thrown when a video is requested
  603. in a format that is not available for that video.
  604. """
  605. pass
  606. class ContentTooShortError(Exception):
  607. """Content Too Short exception.
  608. This exception may be raised by FileDownloader objects when a file they
  609. download is too small for what the server announced first, indicating
  610. the connection was probably interrupted.
  611. """
  612. def __init__(self, downloaded, expected):
  613. # Both in bytes
  614. self.downloaded = downloaded
  615. self.expected = expected
  616. def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
  617. # Working around python 2 bug (see http://bugs.python.org/issue17849) by limiting
  618. # expected HTTP responses to meet HTTP/1.0 or later (see also
  619. # https://github.com/rg3/youtube-dl/issues/6727)
  620. if sys.version_info < (3, 0):
  621. kwargs[b'strict'] = True
  622. hc = http_class(*args, **kwargs)
  623. source_address = ydl_handler._params.get('source_address')
  624. if source_address is not None:
  625. sa = (source_address, 0)
  626. if hasattr(hc, 'source_address'): # Python 2.7+
  627. hc.source_address = sa
  628. else: # Python 2.6
  629. def _hc_connect(self, *args, **kwargs):
  630. sock = compat_socket_create_connection(
  631. (self.host, self.port), self.timeout, sa)
  632. if is_https:
  633. self.sock = ssl.wrap_socket(
  634. sock, self.key_file, self.cert_file,
  635. ssl_version=ssl.PROTOCOL_TLSv1)
  636. else:
  637. self.sock = sock
  638. hc.connect = functools.partial(_hc_connect, hc)
  639. return hc
  640. def handle_youtubedl_headers(headers):
  641. filtered_headers = headers
  642. if 'Youtubedl-no-compression' in filtered_headers:
  643. filtered_headers = dict((k, v) for k, v in filtered_headers.items() if k.lower() != 'accept-encoding')
  644. del filtered_headers['Youtubedl-no-compression']
  645. return filtered_headers
  646. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  647. """Handler for HTTP requests and responses.
  648. This class, when installed with an OpenerDirector, automatically adds
  649. the standard headers to every HTTP request and handles gzipped and
  650. deflated responses from web servers. If compression is to be avoided in
  651. a particular request, the original request in the program code only has
  652. to include the HTTP header "Youtubedl-no-compression", which will be
  653. removed before making the real request.
  654. Part of this code was copied from:
  655. http://techknack.net/python-urllib2-handlers/
  656. Andrew Rowls, the author of that code, agreed to release it to the
  657. public domain.
  658. """
  659. def __init__(self, params, *args, **kwargs):
  660. compat_urllib_request.HTTPHandler.__init__(self, *args, **kwargs)
  661. self._params = params
  662. def http_open(self, req):
  663. conn_class = compat_http_client.HTTPConnection
  664. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  665. if socks_proxy:
  666. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  667. del req.headers['Ytdl-socks-proxy']
  668. return self.do_open(functools.partial(
  669. _create_http_connection, self, conn_class, False),
  670. req)
  671. @staticmethod
  672. def deflate(data):
  673. try:
  674. return zlib.decompress(data, -zlib.MAX_WBITS)
  675. except zlib.error:
  676. return zlib.decompress(data)
  677. @staticmethod
  678. def addinfourl_wrapper(stream, headers, url, code):
  679. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  680. return compat_urllib_request.addinfourl(stream, headers, url, code)
  681. ret = compat_urllib_request.addinfourl(stream, headers, url)
  682. ret.code = code
  683. return ret
  684. def http_request(self, req):
  685. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  686. # always respected by websites, some tend to give out URLs with non percent-encoded
  687. # non-ASCII characters (see telemb.py, ard.py [#3412])
  688. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  689. # To work around aforementioned issue we will replace request's original URL with
  690. # percent-encoded one
  691. # Since redirects are also affected (e.g. http://www.southpark.de/alle-episoden/s18e09)
  692. # the code of this workaround has been moved here from YoutubeDL.urlopen()
  693. url = req.get_full_url()
  694. url_escaped = escape_url(url)
  695. # Substitute URL if any change after escaping
  696. if url != url_escaped:
  697. req = update_Request(req, url=url_escaped)
  698. for h, v in std_headers.items():
  699. # Capitalize is needed because of Python bug 2275: http://bugs.python.org/issue2275
  700. # The dict keys are capitalized because of this bug by urllib
  701. if h.capitalize() not in req.headers:
  702. req.add_header(h, v)
  703. req.headers = handle_youtubedl_headers(req.headers)
  704. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  705. # Python 2.6 is brain-dead when it comes to fragments
  706. req._Request__original = req._Request__original.partition('#')[0]
  707. req._Request__r_type = req._Request__r_type.partition('#')[0]
  708. return req
  709. def http_response(self, req, resp):
  710. old_resp = resp
  711. # gzip
  712. if resp.headers.get('Content-encoding', '') == 'gzip':
  713. content = resp.read()
  714. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  715. try:
  716. uncompressed = io.BytesIO(gz.read())
  717. except IOError as original_ioerror:
  718. # There may be junk add the end of the file
  719. # See http://stackoverflow.com/q/4928560/35070 for details
  720. for i in range(1, 1024):
  721. try:
  722. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  723. uncompressed = io.BytesIO(gz.read())
  724. except IOError:
  725. continue
  726. break
  727. else:
  728. raise original_ioerror
  729. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  730. resp.msg = old_resp.msg
  731. del resp.headers['Content-encoding']
  732. # deflate
  733. if resp.headers.get('Content-encoding', '') == 'deflate':
  734. gz = io.BytesIO(self.deflate(resp.read()))
  735. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  736. resp.msg = old_resp.msg
  737. del resp.headers['Content-encoding']
  738. # Percent-encode redirect URL of Location HTTP header to satisfy RFC 3986 (see
  739. # https://github.com/rg3/youtube-dl/issues/6457).
  740. if 300 <= resp.code < 400:
  741. location = resp.headers.get('Location')
  742. if location:
  743. # As of RFC 2616 default charset is iso-8859-1 that is respected by python 3
  744. if sys.version_info >= (3, 0):
  745. location = location.encode('iso-8859-1').decode('utf-8')
  746. else:
  747. location = location.decode('utf-8')
  748. location_escaped = escape_url(location)
  749. if location != location_escaped:
  750. del resp.headers['Location']
  751. if sys.version_info < (3, 0):
  752. location_escaped = location_escaped.encode('utf-8')
  753. resp.headers['Location'] = location_escaped
  754. return resp
  755. https_request = http_request
  756. https_response = http_response
  757. def make_socks_conn_class(base_class, socks_proxy):
  758. assert issubclass(base_class, (
  759. compat_http_client.HTTPConnection, compat_http_client.HTTPSConnection))
  760. url_components = compat_urlparse.urlparse(socks_proxy)
  761. if url_components.scheme.lower() == 'socks5':
  762. socks_type = ProxyType.SOCKS5
  763. elif url_components.scheme.lower() in ('socks', 'socks4'):
  764. socks_type = ProxyType.SOCKS4
  765. elif url_components.scheme.lower() == 'socks4a':
  766. socks_type = ProxyType.SOCKS4A
  767. def unquote_if_non_empty(s):
  768. if not s:
  769. return s
  770. return compat_urllib_parse_unquote_plus(s)
  771. proxy_args = (
  772. socks_type,
  773. url_components.hostname, url_components.port or 1080,
  774. True, # Remote DNS
  775. unquote_if_non_empty(url_components.username),
  776. unquote_if_non_empty(url_components.password),
  777. )
  778. class SocksConnection(base_class):
  779. def connect(self):
  780. self.sock = sockssocket()
  781. self.sock.setproxy(*proxy_args)
  782. if type(self.timeout) in (int, float):
  783. self.sock.settimeout(self.timeout)
  784. self.sock.connect((self.host, self.port))
  785. if isinstance(self, compat_http_client.HTTPSConnection):
  786. if hasattr(self, '_context'): # Python > 2.6
  787. self.sock = self._context.wrap_socket(
  788. self.sock, server_hostname=self.host)
  789. else:
  790. self.sock = ssl.wrap_socket(self.sock)
  791. return SocksConnection
  792. class YoutubeDLHTTPSHandler(compat_urllib_request.HTTPSHandler):
  793. def __init__(self, params, https_conn_class=None, *args, **kwargs):
  794. compat_urllib_request.HTTPSHandler.__init__(self, *args, **kwargs)
  795. self._https_conn_class = https_conn_class or compat_http_client.HTTPSConnection
  796. self._params = params
  797. def https_open(self, req):
  798. kwargs = {}
  799. conn_class = self._https_conn_class
  800. if hasattr(self, '_context'): # python > 2.6
  801. kwargs['context'] = self._context
  802. if hasattr(self, '_check_hostname'): # python 3.x
  803. kwargs['check_hostname'] = self._check_hostname
  804. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  805. if socks_proxy:
  806. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  807. del req.headers['Ytdl-socks-proxy']
  808. return self.do_open(functools.partial(
  809. _create_http_connection, self, conn_class, True),
  810. req, **kwargs)
  811. class YoutubeDLCookieProcessor(compat_urllib_request.HTTPCookieProcessor):
  812. def __init__(self, cookiejar=None):
  813. compat_urllib_request.HTTPCookieProcessor.__init__(self, cookiejar)
  814. def http_response(self, request, response):
  815. # Python 2 will choke on next HTTP request in row if there are non-ASCII
  816. # characters in Set-Cookie HTTP header of last response (see
  817. # https://github.com/rg3/youtube-dl/issues/6769).
  818. # In order to at least prevent crashing we will percent encode Set-Cookie
  819. # header before HTTPCookieProcessor starts processing it.
  820. # if sys.version_info < (3, 0) and response.headers:
  821. # for set_cookie_header in ('Set-Cookie', 'Set-Cookie2'):
  822. # set_cookie = response.headers.get(set_cookie_header)
  823. # if set_cookie:
  824. # set_cookie_escaped = compat_urllib_parse.quote(set_cookie, b"%/;:@&=+$,!~*'()?#[] ")
  825. # if set_cookie != set_cookie_escaped:
  826. # del response.headers[set_cookie_header]
  827. # response.headers[set_cookie_header] = set_cookie_escaped
  828. return compat_urllib_request.HTTPCookieProcessor.http_response(self, request, response)
  829. https_request = compat_urllib_request.HTTPCookieProcessor.http_request
  830. https_response = http_response
  831. def extract_timezone(date_str):
  832. m = re.search(
  833. r'^.{8,}?(?P<tz>Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  834. date_str)
  835. if not m:
  836. timezone = datetime.timedelta()
  837. else:
  838. date_str = date_str[:-len(m.group('tz'))]
  839. if not m.group('sign'):
  840. timezone = datetime.timedelta()
  841. else:
  842. sign = 1 if m.group('sign') == '+' else -1
  843. timezone = datetime.timedelta(
  844. hours=sign * int(m.group('hours')),
  845. minutes=sign * int(m.group('minutes')))
  846. return timezone, date_str
  847. def parse_iso8601(date_str, delimiter='T', timezone=None):
  848. """ Return a UNIX timestamp from the given date """
  849. if date_str is None:
  850. return None
  851. date_str = re.sub(r'\.[0-9]+', '', date_str)
  852. if timezone is None:
  853. timezone, date_str = extract_timezone(date_str)
  854. try:
  855. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  856. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  857. return calendar.timegm(dt.timetuple())
  858. except ValueError:
  859. pass
  860. def date_formats(day_first=True):
  861. return DATE_FORMATS_DAY_FIRST if day_first else DATE_FORMATS_MONTH_FIRST
  862. def unified_strdate(date_str, day_first=True):
  863. """Return a string with the date in the format YYYYMMDD"""
  864. if date_str is None:
  865. return None
  866. upload_date = None
  867. # Replace commas
  868. date_str = date_str.replace(',', ' ')
  869. # Remove AM/PM + timezone
  870. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  871. _, date_str = extract_timezone(date_str)
  872. for expression in date_formats(day_first):
  873. try:
  874. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  875. except ValueError:
  876. pass
  877. if upload_date is None:
  878. timetuple = email.utils.parsedate_tz(date_str)
  879. if timetuple:
  880. try:
  881. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  882. except ValueError:
  883. pass
  884. if upload_date is not None:
  885. return compat_str(upload_date)
  886. def unified_timestamp(date_str, day_first=True):
  887. if date_str is None:
  888. return None
  889. date_str = date_str.replace(',', ' ')
  890. pm_delta = datetime.timedelta(hours=12 if re.search(r'(?i)PM', date_str) else 0)
  891. timezone, date_str = extract_timezone(date_str)
  892. # Remove AM/PM + timezone
  893. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  894. for expression in date_formats(day_first):
  895. try:
  896. dt = datetime.datetime.strptime(date_str, expression) - timezone + pm_delta
  897. return calendar.timegm(dt.timetuple())
  898. except ValueError:
  899. pass
  900. timetuple = email.utils.parsedate_tz(date_str)
  901. if timetuple:
  902. return calendar.timegm(timetuple.timetuple())
  903. def determine_ext(url, default_ext='unknown_video'):
  904. if url is None:
  905. return default_ext
  906. guess = url.partition('?')[0].rpartition('.')[2]
  907. if re.match(r'^[A-Za-z0-9]+$', guess):
  908. return guess
  909. # Try extract ext from URLs like http://example.com/foo/bar.mp4/?download
  910. elif guess.rstrip('/') in KNOWN_EXTENSIONS:
  911. return guess.rstrip('/')
  912. else:
  913. return default_ext
  914. def subtitles_filename(filename, sub_lang, sub_format):
  915. return filename.rsplit('.', 1)[0] + '.' + sub_lang + '.' + sub_format
  916. def date_from_str(date_str):
  917. """
  918. Return a datetime object from a string in the format YYYYMMDD or
  919. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  920. today = datetime.date.today()
  921. if date_str in ('now', 'today'):
  922. return today
  923. if date_str == 'yesterday':
  924. return today - datetime.timedelta(days=1)
  925. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  926. if match is not None:
  927. sign = match.group('sign')
  928. time = int(match.group('time'))
  929. if sign == '-':
  930. time = -time
  931. unit = match.group('unit')
  932. # A bad approximation?
  933. if unit == 'month':
  934. unit = 'day'
  935. time *= 30
  936. elif unit == 'year':
  937. unit = 'day'
  938. time *= 365
  939. unit += 's'
  940. delta = datetime.timedelta(**{unit: time})
  941. return today + delta
  942. return datetime.datetime.strptime(date_str, '%Y%m%d').date()
  943. def hyphenate_date(date_str):
  944. """
  945. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  946. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  947. if match is not None:
  948. return '-'.join(match.groups())
  949. else:
  950. return date_str
  951. class DateRange(object):
  952. """Represents a time interval between two dates"""
  953. def __init__(self, start=None, end=None):
  954. """start and end must be strings in the format accepted by date"""
  955. if start is not None:
  956. self.start = date_from_str(start)
  957. else:
  958. self.start = datetime.datetime.min.date()
  959. if end is not None:
  960. self.end = date_from_str(end)
  961. else:
  962. self.end = datetime.datetime.max.date()
  963. if self.start > self.end:
  964. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  965. @classmethod
  966. def day(cls, day):
  967. """Returns a range that only contains the given day"""
  968. return cls(day, day)
  969. def __contains__(self, date):
  970. """Check if the date is in the range"""
  971. if not isinstance(date, datetime.date):
  972. date = date_from_str(date)
  973. return self.start <= date <= self.end
  974. def __str__(self):
  975. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  976. def platform_name():
  977. """ Returns the platform name as a compat_str """
  978. res = platform.platform()
  979. if isinstance(res, bytes):
  980. res = res.decode(preferredencoding())
  981. assert isinstance(res, compat_str)
  982. return res
  983. def _windows_write_string(s, out):
  984. """ Returns True if the string was written using special methods,
  985. False if it has yet to be written out."""
  986. # Adapted from http://stackoverflow.com/a/3259271/35070
  987. import ctypes
  988. import ctypes.wintypes
  989. WIN_OUTPUT_IDS = {
  990. 1: -11,
  991. 2: -12,
  992. }
  993. try:
  994. fileno = out.fileno()
  995. except AttributeError:
  996. # If the output stream doesn't have a fileno, it's virtual
  997. return False
  998. except io.UnsupportedOperation:
  999. # Some strange Windows pseudo files?
  1000. return False
  1001. if fileno not in WIN_OUTPUT_IDS:
  1002. return False
  1003. GetStdHandle = ctypes.WINFUNCTYPE(
  1004. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  1005. (b'GetStdHandle', ctypes.windll.kernel32))
  1006. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  1007. WriteConsoleW = ctypes.WINFUNCTYPE(
  1008. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  1009. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  1010. ctypes.wintypes.LPVOID)((b'WriteConsoleW', ctypes.windll.kernel32))
  1011. written = ctypes.wintypes.DWORD(0)
  1012. GetFileType = ctypes.WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)((b'GetFileType', ctypes.windll.kernel32))
  1013. FILE_TYPE_CHAR = 0x0002
  1014. FILE_TYPE_REMOTE = 0x8000
  1015. GetConsoleMode = ctypes.WINFUNCTYPE(
  1016. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  1017. ctypes.POINTER(ctypes.wintypes.DWORD))(
  1018. (b'GetConsoleMode', ctypes.windll.kernel32))
  1019. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  1020. def not_a_console(handle):
  1021. if handle == INVALID_HANDLE_VALUE or handle is None:
  1022. return True
  1023. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR or
  1024. GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  1025. if not_a_console(h):
  1026. return False
  1027. def next_nonbmp_pos(s):
  1028. try:
  1029. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  1030. except StopIteration:
  1031. return len(s)
  1032. while s:
  1033. count = min(next_nonbmp_pos(s), 1024)
  1034. ret = WriteConsoleW(
  1035. h, s, count if count else 2, ctypes.byref(written), None)
  1036. if ret == 0:
  1037. raise OSError('Failed to write string')
  1038. if not count: # We just wrote a non-BMP character
  1039. assert written.value == 2
  1040. s = s[1:]
  1041. else:
  1042. assert written.value > 0
  1043. s = s[written.value:]
  1044. return True
  1045. def write_string(s, out=None, encoding=None):
  1046. if out is None:
  1047. out = sys.stderr
  1048. assert type(s) == compat_str
  1049. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  1050. if _windows_write_string(s, out):
  1051. return
  1052. if ('b' in getattr(out, 'mode', '') or
  1053. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  1054. byt = s.encode(encoding or preferredencoding(), 'ignore')
  1055. out.write(byt)
  1056. elif hasattr(out, 'buffer'):
  1057. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  1058. byt = s.encode(enc, 'ignore')
  1059. out.buffer.write(byt)
  1060. else:
  1061. out.write(s)
  1062. out.flush()
  1063. def bytes_to_intlist(bs):
  1064. if not bs:
  1065. return []
  1066. if isinstance(bs[0], int): # Python 3
  1067. return list(bs)
  1068. else:
  1069. return [ord(c) for c in bs]
  1070. def intlist_to_bytes(xs):
  1071. if not xs:
  1072. return b''
  1073. return compat_struct_pack('%dB' % len(xs), *xs)
  1074. # Cross-platform file locking
  1075. if sys.platform == 'win32':
  1076. import ctypes.wintypes
  1077. import msvcrt
  1078. class OVERLAPPED(ctypes.Structure):
  1079. _fields_ = [
  1080. ('Internal', ctypes.wintypes.LPVOID),
  1081. ('InternalHigh', ctypes.wintypes.LPVOID),
  1082. ('Offset', ctypes.wintypes.DWORD),
  1083. ('OffsetHigh', ctypes.wintypes.DWORD),
  1084. ('hEvent', ctypes.wintypes.HANDLE),
  1085. ]
  1086. kernel32 = ctypes.windll.kernel32
  1087. LockFileEx = kernel32.LockFileEx
  1088. LockFileEx.argtypes = [
  1089. ctypes.wintypes.HANDLE, # hFile
  1090. ctypes.wintypes.DWORD, # dwFlags
  1091. ctypes.wintypes.DWORD, # dwReserved
  1092. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  1093. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  1094. ctypes.POINTER(OVERLAPPED) # Overlapped
  1095. ]
  1096. LockFileEx.restype = ctypes.wintypes.BOOL
  1097. UnlockFileEx = kernel32.UnlockFileEx
  1098. UnlockFileEx.argtypes = [
  1099. ctypes.wintypes.HANDLE, # hFile
  1100. ctypes.wintypes.DWORD, # dwReserved
  1101. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  1102. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  1103. ctypes.POINTER(OVERLAPPED) # Overlapped
  1104. ]
  1105. UnlockFileEx.restype = ctypes.wintypes.BOOL
  1106. whole_low = 0xffffffff
  1107. whole_high = 0x7fffffff
  1108. def _lock_file(f, exclusive):
  1109. overlapped = OVERLAPPED()
  1110. overlapped.Offset = 0
  1111. overlapped.OffsetHigh = 0
  1112. overlapped.hEvent = 0
  1113. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  1114. handle = msvcrt.get_osfhandle(f.fileno())
  1115. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  1116. whole_low, whole_high, f._lock_file_overlapped_p):
  1117. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  1118. def _unlock_file(f):
  1119. assert f._lock_file_overlapped_p
  1120. handle = msvcrt.get_osfhandle(f.fileno())
  1121. if not UnlockFileEx(handle, 0,
  1122. whole_low, whole_high, f._lock_file_overlapped_p):
  1123. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  1124. else:
  1125. # Some platforms, such as Jython, is missing fcntl
  1126. try:
  1127. import fcntl
  1128. def _lock_file(f, exclusive):
  1129. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  1130. def _unlock_file(f):
  1131. fcntl.flock(f, fcntl.LOCK_UN)
  1132. except ImportError:
  1133. UNSUPPORTED_MSG = 'file locking is not supported on this platform'
  1134. def _lock_file(f, exclusive):
  1135. raise IOError(UNSUPPORTED_MSG)
  1136. def _unlock_file(f):
  1137. raise IOError(UNSUPPORTED_MSG)
  1138. class locked_file(object):
  1139. def __init__(self, filename, mode, encoding=None):
  1140. assert mode in ['r', 'a', 'w']
  1141. self.f = io.open(filename, mode, encoding=encoding)
  1142. self.mode = mode
  1143. def __enter__(self):
  1144. exclusive = self.mode != 'r'
  1145. try:
  1146. _lock_file(self.f, exclusive)
  1147. except IOError:
  1148. self.f.close()
  1149. raise
  1150. return self
  1151. def __exit__(self, etype, value, traceback):
  1152. try:
  1153. _unlock_file(self.f)
  1154. finally:
  1155. self.f.close()
  1156. def __iter__(self):
  1157. return iter(self.f)
  1158. def write(self, *args):
  1159. return self.f.write(*args)
  1160. def read(self, *args):
  1161. return self.f.read(*args)
  1162. def get_filesystem_encoding():
  1163. encoding = sys.getfilesystemencoding()
  1164. return encoding if encoding is not None else 'utf-8'
  1165. def shell_quote(args):
  1166. quoted_args = []
  1167. encoding = get_filesystem_encoding()
  1168. for a in args:
  1169. if isinstance(a, bytes):
  1170. # We may get a filename encoded with 'encodeFilename'
  1171. a = a.decode(encoding)
  1172. quoted_args.append(pipes.quote(a))
  1173. return ' '.join(quoted_args)
  1174. def smuggle_url(url, data):
  1175. """ Pass additional data in a URL for internal use. """
  1176. sdata = compat_urllib_parse_urlencode(
  1177. {'__youtubedl_smuggle': json.dumps(data)})
  1178. return url + '#' + sdata
  1179. def unsmuggle_url(smug_url, default=None):
  1180. if '#__youtubedl_smuggle' not in smug_url:
  1181. return smug_url, default
  1182. url, _, sdata = smug_url.rpartition('#')
  1183. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  1184. data = json.loads(jsond)
  1185. return url, data
  1186. def format_bytes(bytes):
  1187. if bytes is None:
  1188. return 'N/A'
  1189. if type(bytes) is str:
  1190. bytes = float(bytes)
  1191. if bytes == 0.0:
  1192. exponent = 0
  1193. else:
  1194. exponent = int(math.log(bytes, 1024.0))
  1195. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  1196. converted = float(bytes) / float(1024 ** exponent)
  1197. return '%.2f%s' % (converted, suffix)
  1198. def lookup_unit_table(unit_table, s):
  1199. units_re = '|'.join(re.escape(u) for u in unit_table)
  1200. m = re.match(
  1201. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)\b' % units_re, s)
  1202. if not m:
  1203. return None
  1204. num_str = m.group('num').replace(',', '.')
  1205. mult = unit_table[m.group('unit')]
  1206. return int(float(num_str) * mult)
  1207. def parse_filesize(s):
  1208. if s is None:
  1209. return None
  1210. # The lower-case forms are of course incorrect and unofficial,
  1211. # but we support those too
  1212. _UNIT_TABLE = {
  1213. 'B': 1,
  1214. 'b': 1,
  1215. 'KiB': 1024,
  1216. 'KB': 1000,
  1217. 'kB': 1024,
  1218. 'Kb': 1000,
  1219. 'MiB': 1024 ** 2,
  1220. 'MB': 1000 ** 2,
  1221. 'mB': 1024 ** 2,
  1222. 'Mb': 1000 ** 2,
  1223. 'GiB': 1024 ** 3,
  1224. 'GB': 1000 ** 3,
  1225. 'gB': 1024 ** 3,
  1226. 'Gb': 1000 ** 3,
  1227. 'TiB': 1024 ** 4,
  1228. 'TB': 1000 ** 4,
  1229. 'tB': 1024 ** 4,
  1230. 'Tb': 1000 ** 4,
  1231. 'PiB': 1024 ** 5,
  1232. 'PB': 1000 ** 5,
  1233. 'pB': 1024 ** 5,
  1234. 'Pb': 1000 ** 5,
  1235. 'EiB': 1024 ** 6,
  1236. 'EB': 1000 ** 6,
  1237. 'eB': 1024 ** 6,
  1238. 'Eb': 1000 ** 6,
  1239. 'ZiB': 1024 ** 7,
  1240. 'ZB': 1000 ** 7,
  1241. 'zB': 1024 ** 7,
  1242. 'Zb': 1000 ** 7,
  1243. 'YiB': 1024 ** 8,
  1244. 'YB': 1000 ** 8,
  1245. 'yB': 1024 ** 8,
  1246. 'Yb': 1000 ** 8,
  1247. }
  1248. return lookup_unit_table(_UNIT_TABLE, s)
  1249. def parse_count(s):
  1250. if s is None:
  1251. return None
  1252. s = s.strip()
  1253. if re.match(r'^[\d,.]+$', s):
  1254. return str_to_int(s)
  1255. _UNIT_TABLE = {
  1256. 'k': 1000,
  1257. 'K': 1000,
  1258. 'm': 1000 ** 2,
  1259. 'M': 1000 ** 2,
  1260. 'kk': 1000 ** 2,
  1261. 'KK': 1000 ** 2,
  1262. }
  1263. return lookup_unit_table(_UNIT_TABLE, s)
  1264. def month_by_name(name):
  1265. """ Return the number of a month by (locale-independently) English name """
  1266. try:
  1267. return ENGLISH_MONTH_NAMES.index(name) + 1
  1268. except ValueError:
  1269. return None
  1270. def month_by_abbreviation(abbrev):
  1271. """ Return the number of a month by (locale-independently) English
  1272. abbreviations """
  1273. try:
  1274. return [s[:3] for s in ENGLISH_MONTH_NAMES].index(abbrev) + 1
  1275. except ValueError:
  1276. return None
  1277. def fix_xml_ampersands(xml_str):
  1278. """Replace all the '&' by '&amp;' in XML"""
  1279. return re.sub(
  1280. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  1281. '&amp;',
  1282. xml_str)
  1283. def setproctitle(title):
  1284. assert isinstance(title, compat_str)
  1285. # ctypes in Jython is not complete
  1286. # http://bugs.jython.org/issue2148
  1287. if sys.platform.startswith('java'):
  1288. return
  1289. try:
  1290. libc = ctypes.cdll.LoadLibrary('libc.so.6')
  1291. except OSError:
  1292. return
  1293. title_bytes = title.encode('utf-8')
  1294. buf = ctypes.create_string_buffer(len(title_bytes))
  1295. buf.value = title_bytes
  1296. try:
  1297. libc.prctl(15, buf, 0, 0, 0)
  1298. except AttributeError:
  1299. return # Strange libc, just skip this
  1300. def remove_start(s, start):
  1301. return s[len(start):] if s is not None and s.startswith(start) else s
  1302. def remove_end(s, end):
  1303. return s[:-len(end)] if s is not None and s.endswith(end) else s
  1304. def remove_quotes(s):
  1305. if s is None or len(s) < 2:
  1306. return s
  1307. for quote in ('"', "'", ):
  1308. if s[0] == quote and s[-1] == quote:
  1309. return s[1:-1]
  1310. return s
  1311. def url_basename(url):
  1312. path = compat_urlparse.urlparse(url).path
  1313. return path.strip('/').split('/')[-1]
  1314. class HEADRequest(compat_urllib_request.Request):
  1315. def get_method(self):
  1316. return 'HEAD'
  1317. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  1318. if get_attr:
  1319. if v is not None:
  1320. v = getattr(v, get_attr, None)
  1321. if v == '':
  1322. v = None
  1323. if v is None:
  1324. return default
  1325. try:
  1326. return int(v) * invscale // scale
  1327. except ValueError:
  1328. return default
  1329. def str_or_none(v, default=None):
  1330. return default if v is None else compat_str(v)
  1331. def str_to_int(int_str):
  1332. """ A more relaxed version of int_or_none """
  1333. if int_str is None:
  1334. return None
  1335. int_str = re.sub(r'[,\.\+]', '', int_str)
  1336. return int(int_str)
  1337. def float_or_none(v, scale=1, invscale=1, default=None):
  1338. if v is None:
  1339. return default
  1340. try:
  1341. return float(v) * invscale / scale
  1342. except ValueError:
  1343. return default
  1344. def strip_or_none(v):
  1345. return None if v is None else v.strip()
  1346. def parse_duration(s):
  1347. if not isinstance(s, compat_basestring):
  1348. return None
  1349. s = s.strip()
  1350. days, hours, mins, secs, ms = [None] * 5
  1351. m = re.match(r'(?:(?:(?:(?P<days>[0-9]+):)?(?P<hours>[0-9]+):)?(?P<mins>[0-9]+):)?(?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?$', s)
  1352. if m:
  1353. days, hours, mins, secs, ms = m.groups()
  1354. else:
  1355. m = re.match(
  1356. r'''(?ix)(?:P?T)?
  1357. (?:
  1358. (?P<days>[0-9]+)\s*d(?:ays?)?\s*
  1359. )?
  1360. (?:
  1361. (?P<hours>[0-9]+)\s*h(?:ours?)?\s*
  1362. )?
  1363. (?:
  1364. (?P<mins>[0-9]+)\s*m(?:in(?:ute)?s?)?\s*
  1365. )?
  1366. (?:
  1367. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*s(?:ec(?:ond)?s?)?\s*
  1368. )?$''', s)
  1369. if m:
  1370. days, hours, mins, secs, ms = m.groups()
  1371. else:
  1372. m = re.match(r'(?i)(?:(?P<hours>[0-9.]+)\s*(?:hours?)|(?P<mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*)$', s)
  1373. if m:
  1374. hours, mins = m.groups()
  1375. else:
  1376. return None
  1377. duration = 0
  1378. if secs:
  1379. duration += float(secs)
  1380. if mins:
  1381. duration += float(mins) * 60
  1382. if hours:
  1383. duration += float(hours) * 60 * 60
  1384. if days:
  1385. duration += float(days) * 24 * 60 * 60
  1386. if ms:
  1387. duration += float(ms)
  1388. return duration
  1389. def prepend_extension(filename, ext, expected_real_ext=None):
  1390. name, real_ext = os.path.splitext(filename)
  1391. return (
  1392. '{0}.{1}{2}'.format(name, ext, real_ext)
  1393. if not expected_real_ext or real_ext[1:] == expected_real_ext
  1394. else '{0}.{1}'.format(filename, ext))
  1395. def replace_extension(filename, ext, expected_real_ext=None):
  1396. name, real_ext = os.path.splitext(filename)
  1397. return '{0}.{1}'.format(
  1398. name if not expected_real_ext or real_ext[1:] == expected_real_ext else filename,
  1399. ext)
  1400. def check_executable(exe, args=[]):
  1401. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  1402. args can be a list of arguments for a short output (like -version) """
  1403. try:
  1404. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  1405. except OSError:
  1406. return False
  1407. return exe
  1408. def get_exe_version(exe, args=['--version'],
  1409. version_re=None, unrecognized='present'):
  1410. """ Returns the version of the specified executable,
  1411. or False if the executable is not present """
  1412. try:
  1413. out, _ = subprocess.Popen(
  1414. [encodeArgument(exe)] + args,
  1415. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  1416. except OSError:
  1417. return False
  1418. if isinstance(out, bytes): # Python 2.x
  1419. out = out.decode('ascii', 'ignore')
  1420. return detect_exe_version(out, version_re, unrecognized)
  1421. def detect_exe_version(output, version_re=None, unrecognized='present'):
  1422. assert isinstance(output, compat_str)
  1423. if version_re is None:
  1424. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  1425. m = re.search(version_re, output)
  1426. if m:
  1427. return m.group(1)
  1428. else:
  1429. return unrecognized
  1430. class PagedList(object):
  1431. def __len__(self):
  1432. # This is only useful for tests
  1433. return len(self.getslice())
  1434. class OnDemandPagedList(PagedList):
  1435. def __init__(self, pagefunc, pagesize, use_cache=False):
  1436. self._pagefunc = pagefunc
  1437. self._pagesize = pagesize
  1438. self._use_cache = use_cache
  1439. if use_cache:
  1440. self._cache = {}
  1441. def getslice(self, start=0, end=None):
  1442. res = []
  1443. for pagenum in itertools.count(start // self._pagesize):
  1444. firstid = pagenum * self._pagesize
  1445. nextfirstid = pagenum * self._pagesize + self._pagesize
  1446. if start >= nextfirstid:
  1447. continue
  1448. page_results = None
  1449. if self._use_cache:
  1450. page_results = self._cache.get(pagenum)
  1451. if page_results is None:
  1452. page_results = list(self._pagefunc(pagenum))
  1453. if self._use_cache:
  1454. self._cache[pagenum] = page_results
  1455. startv = (
  1456. start % self._pagesize
  1457. if firstid <= start < nextfirstid
  1458. else 0)
  1459. endv = (
  1460. ((end - 1) % self._pagesize) + 1
  1461. if (end is not None and firstid <= end <= nextfirstid)
  1462. else None)
  1463. if startv != 0 or endv is not None:
  1464. page_results = page_results[startv:endv]
  1465. res.extend(page_results)
  1466. # A little optimization - if current page is not "full", ie. does
  1467. # not contain page_size videos then we can assume that this page
  1468. # is the last one - there are no more ids on further pages -
  1469. # i.e. no need to query again.
  1470. if len(page_results) + startv < self._pagesize:
  1471. break
  1472. # If we got the whole page, but the next page is not interesting,
  1473. # break out early as well
  1474. if end == nextfirstid:
  1475. break
  1476. return res
  1477. class InAdvancePagedList(PagedList):
  1478. def __init__(self, pagefunc, pagecount, pagesize):
  1479. self._pagefunc = pagefunc
  1480. self._pagecount = pagecount
  1481. self._pagesize = pagesize
  1482. def getslice(self, start=0, end=None):
  1483. res = []
  1484. start_page = start // self._pagesize
  1485. end_page = (
  1486. self._pagecount if end is None else (end // self._pagesize + 1))
  1487. skip_elems = start - start_page * self._pagesize
  1488. only_more = None if end is None else end - start
  1489. for pagenum in range(start_page, end_page):
  1490. page = list(self._pagefunc(pagenum))
  1491. if skip_elems:
  1492. page = page[skip_elems:]
  1493. skip_elems = None
  1494. if only_more is not None:
  1495. if len(page) < only_more:
  1496. only_more -= len(page)
  1497. else:
  1498. page = page[:only_more]
  1499. res.extend(page)
  1500. break
  1501. res.extend(page)
  1502. return res
  1503. def uppercase_escape(s):
  1504. unicode_escape = codecs.getdecoder('unicode_escape')
  1505. return re.sub(
  1506. r'\\U[0-9a-fA-F]{8}',
  1507. lambda m: unicode_escape(m.group(0))[0],
  1508. s)
  1509. def lowercase_escape(s):
  1510. unicode_escape = codecs.getdecoder('unicode_escape')
  1511. return re.sub(
  1512. r'\\u[0-9a-fA-F]{4}',
  1513. lambda m: unicode_escape(m.group(0))[0],
  1514. s)
  1515. def escape_rfc3986(s):
  1516. """Escape non-ASCII characters as suggested by RFC 3986"""
  1517. if sys.version_info < (3, 0) and isinstance(s, compat_str):
  1518. s = s.encode('utf-8')
  1519. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1520. def escape_url(url):
  1521. """Escape URL as suggested by RFC 3986"""
  1522. url_parsed = compat_urllib_parse_urlparse(url)
  1523. return url_parsed._replace(
  1524. netloc=url_parsed.netloc.encode('idna').decode('ascii'),
  1525. path=escape_rfc3986(url_parsed.path),
  1526. params=escape_rfc3986(url_parsed.params),
  1527. query=escape_rfc3986(url_parsed.query),
  1528. fragment=escape_rfc3986(url_parsed.fragment)
  1529. ).geturl()
  1530. def read_batch_urls(batch_fd):
  1531. def fixup(url):
  1532. if not isinstance(url, compat_str):
  1533. url = url.decode('utf-8', 'replace')
  1534. BOM_UTF8 = '\xef\xbb\xbf'
  1535. if url.startswith(BOM_UTF8):
  1536. url = url[len(BOM_UTF8):]
  1537. url = url.strip()
  1538. if url.startswith(('#', ';', ']')):
  1539. return False
  1540. return url
  1541. with contextlib.closing(batch_fd) as fd:
  1542. return [url for url in map(fixup, fd) if url]
  1543. def urlencode_postdata(*args, **kargs):
  1544. return compat_urllib_parse_urlencode(*args, **kargs).encode('ascii')
  1545. def update_url_query(url, query):
  1546. if not query:
  1547. return url
  1548. parsed_url = compat_urlparse.urlparse(url)
  1549. qs = compat_parse_qs(parsed_url.query)
  1550. qs.update(query)
  1551. return compat_urlparse.urlunparse(parsed_url._replace(
  1552. query=compat_urllib_parse_urlencode(qs, True)))
  1553. def update_Request(req, url=None, data=None, headers={}, query={}):
  1554. req_headers = req.headers.copy()
  1555. req_headers.update(headers)
  1556. req_data = data or req.data
  1557. req_url = update_url_query(url or req.get_full_url(), query)
  1558. req_type = HEADRequest if req.get_method() == 'HEAD' else compat_urllib_request.Request
  1559. new_req = req_type(
  1560. req_url, data=req_data, headers=req_headers,
  1561. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  1562. if hasattr(req, 'timeout'):
  1563. new_req.timeout = req.timeout
  1564. return new_req
  1565. def dict_get(d, key_or_keys, default=None, skip_false_values=True):
  1566. if isinstance(key_or_keys, (list, tuple)):
  1567. for key in key_or_keys:
  1568. if key not in d or d[key] is None or skip_false_values and not d[key]:
  1569. continue
  1570. return d[key]
  1571. return default
  1572. return d.get(key_or_keys, default)
  1573. def try_get(src, getter, expected_type=None):
  1574. try:
  1575. v = getter(src)
  1576. except (AttributeError, KeyError, TypeError, IndexError):
  1577. pass
  1578. else:
  1579. if expected_type is None or isinstance(v, expected_type):
  1580. return v
  1581. def encode_compat_str(string, encoding=preferredencoding(), errors='strict'):
  1582. return string if isinstance(string, compat_str) else compat_str(string, encoding, errors)
  1583. US_RATINGS = {
  1584. 'G': 0,
  1585. 'PG': 10,
  1586. 'PG-13': 13,
  1587. 'R': 16,
  1588. 'NC': 18,
  1589. }
  1590. def parse_age_limit(s):
  1591. if s is None:
  1592. return None
  1593. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1594. return int(m.group('age')) if m else US_RATINGS.get(s)
  1595. def strip_jsonp(code):
  1596. return re.sub(
  1597. r'(?s)^[a-zA-Z0-9_.$]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code)
  1598. def js_to_json(code):
  1599. def fix_kv(m):
  1600. v = m.group(0)
  1601. if v in ('true', 'false', 'null'):
  1602. return v
  1603. elif v.startswith('/*') or v == ',':
  1604. return ""
  1605. if v[0] in ("'", '"'):
  1606. v = re.sub(r'(?s)\\.|"', lambda m: {
  1607. '"': '\\"',
  1608. "\\'": "'",
  1609. '\\\n': '',
  1610. '\\x': '\\u00',
  1611. }.get(m.group(0), m.group(0)), v[1:-1])
  1612. INTEGER_TABLE = (
  1613. (r'^0[xX][0-9a-fA-F]+', 16),
  1614. (r'^0+[0-7]+', 8),
  1615. )
  1616. for regex, base in INTEGER_TABLE:
  1617. im = re.match(regex, v)
  1618. if im:
  1619. i = int(im.group(0), base)
  1620. return '"%d":' % i if v.endswith(':') else '%d' % i
  1621. return '"%s"' % v
  1622. return re.sub(r'''(?sx)
  1623. "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
  1624. '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
  1625. /\*.*?\*/|,(?=\s*[\]}])|
  1626. [a-zA-Z_][.a-zA-Z_0-9]*|
  1627. \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:\s*:)?|
  1628. [0-9]+(?=\s*:)
  1629. ''', fix_kv, code)
  1630. def qualities(quality_ids):
  1631. """ Get a numeric quality value out of a list of possible values """
  1632. def q(qid):
  1633. try:
  1634. return quality_ids.index(qid)
  1635. except ValueError:
  1636. return -1
  1637. return q
  1638. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1639. def limit_length(s, length):
  1640. """ Add ellipses to overly long strings """
  1641. if s is None:
  1642. return None
  1643. ELLIPSES = '...'
  1644. if len(s) > length:
  1645. return s[:length - len(ELLIPSES)] + ELLIPSES
  1646. return s
  1647. def version_tuple(v):
  1648. return tuple(int(e) for e in re.split(r'[-.]', v))
  1649. def is_outdated_version(version, limit, assume_new=True):
  1650. if not version:
  1651. return not assume_new
  1652. try:
  1653. return version_tuple(version) < version_tuple(limit)
  1654. except ValueError:
  1655. return not assume_new
  1656. def ytdl_is_updateable():
  1657. """ Returns if youtube-dl can be updated with -U """
  1658. from zipimport import zipimporter
  1659. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  1660. def args_to_str(args):
  1661. # Get a short string representation for a subprocess command
  1662. return ' '.join(compat_shlex_quote(a) for a in args)
  1663. def error_to_compat_str(err):
  1664. err_str = str(err)
  1665. # On python 2 error byte string must be decoded with proper
  1666. # encoding rather than ascii
  1667. if sys.version_info[0] < 3:
  1668. err_str = err_str.decode(preferredencoding())
  1669. return err_str
  1670. def mimetype2ext(mt):
  1671. if mt is None:
  1672. return None
  1673. ext = {
  1674. 'audio/mp4': 'm4a',
  1675. # Per RFC 3003, audio/mpeg can be .mp1, .mp2 or .mp3. Here use .mp3 as
  1676. # it's the most popular one
  1677. 'audio/mpeg': 'mp3',
  1678. }.get(mt)
  1679. if ext is not None:
  1680. return ext
  1681. _, _, res = mt.rpartition('/')
  1682. return {
  1683. '3gpp': '3gp',
  1684. 'smptett+xml': 'tt',
  1685. 'srt': 'srt',
  1686. 'ttaf+xml': 'dfxp',
  1687. 'ttml+xml': 'ttml',
  1688. 'vtt': 'vtt',
  1689. 'x-flv': 'flv',
  1690. 'x-mp4-fragmented': 'mp4',
  1691. 'x-ms-wmv': 'wmv',
  1692. }.get(res, res)
  1693. def urlhandle_detect_ext(url_handle):
  1694. getheader = url_handle.headers.get
  1695. cd = getheader('Content-Disposition')
  1696. if cd:
  1697. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  1698. if m:
  1699. e = determine_ext(m.group('filename'), default_ext=None)
  1700. if e:
  1701. return e
  1702. return mimetype2ext(getheader('Content-Type'))
  1703. def encode_data_uri(data, mime_type):
  1704. return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
  1705. def age_restricted(content_limit, age_limit):
  1706. """ Returns True iff the content should be blocked """
  1707. if age_limit is None: # No limit set
  1708. return False
  1709. if content_limit is None:
  1710. return False # Content available for everyone
  1711. return age_limit < content_limit
  1712. def is_html(first_bytes):
  1713. """ Detect whether a file contains HTML by examining its first bytes. """
  1714. BOMS = [
  1715. (b'\xef\xbb\xbf', 'utf-8'),
  1716. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  1717. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  1718. (b'\xff\xfe', 'utf-16-le'),
  1719. (b'\xfe\xff', 'utf-16-be'),
  1720. ]
  1721. for bom, enc in BOMS:
  1722. if first_bytes.startswith(bom):
  1723. s = first_bytes[len(bom):].decode(enc, 'replace')
  1724. break
  1725. else:
  1726. s = first_bytes.decode('utf-8', 'replace')
  1727. return re.match(r'^\s*<', s)
  1728. def determine_protocol(info_dict):
  1729. protocol = info_dict.get('protocol')
  1730. if protocol is not None:
  1731. return protocol
  1732. url = info_dict['url']
  1733. if url.startswith('rtmp'):
  1734. return 'rtmp'
  1735. elif url.startswith('mms'):
  1736. return 'mms'
  1737. elif url.startswith('rtsp'):
  1738. return 'rtsp'
  1739. ext = determine_ext(url)
  1740. if ext == 'm3u8':
  1741. return 'm3u8'
  1742. elif ext == 'f4m':
  1743. return 'f4m'
  1744. return compat_urllib_parse_urlparse(url).scheme
  1745. def render_table(header_row, data):
  1746. """ Render a list of rows, each as a list of values """
  1747. table = [header_row] + data
  1748. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  1749. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  1750. return '\n'.join(format_str % tuple(row) for row in table)
  1751. def _match_one(filter_part, dct):
  1752. COMPARISON_OPERATORS = {
  1753. '<': operator.lt,
  1754. '<=': operator.le,
  1755. '>': operator.gt,
  1756. '>=': operator.ge,
  1757. '=': operator.eq,
  1758. '!=': operator.ne,
  1759. }
  1760. operator_rex = re.compile(r'''(?x)\s*
  1761. (?P<key>[a-z_]+)
  1762. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  1763. (?:
  1764. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  1765. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  1766. )
  1767. \s*$
  1768. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  1769. m = operator_rex.search(filter_part)
  1770. if m:
  1771. op = COMPARISON_OPERATORS[m.group('op')]
  1772. if m.group('strval') is not None:
  1773. if m.group('op') not in ('=', '!='):
  1774. raise ValueError(
  1775. 'Operator %s does not support string values!' % m.group('op'))
  1776. comparison_value = m.group('strval')
  1777. else:
  1778. try:
  1779. comparison_value = int(m.group('intval'))
  1780. except ValueError:
  1781. comparison_value = parse_filesize(m.group('intval'))
  1782. if comparison_value is None:
  1783. comparison_value = parse_filesize(m.group('intval') + 'B')
  1784. if comparison_value is None:
  1785. raise ValueError(
  1786. 'Invalid integer value %r in filter part %r' % (
  1787. m.group('intval'), filter_part))
  1788. actual_value = dct.get(m.group('key'))
  1789. if actual_value is None:
  1790. return m.group('none_inclusive')
  1791. return op(actual_value, comparison_value)
  1792. UNARY_OPERATORS = {
  1793. '': lambda v: v is not None,
  1794. '!': lambda v: v is None,
  1795. }
  1796. operator_rex = re.compile(r'''(?x)\s*
  1797. (?P<op>%s)\s*(?P<key>[a-z_]+)
  1798. \s*$
  1799. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  1800. m = operator_rex.search(filter_part)
  1801. if m:
  1802. op = UNARY_OPERATORS[m.group('op')]
  1803. actual_value = dct.get(m.group('key'))
  1804. return op(actual_value)
  1805. raise ValueError('Invalid filter part %r' % filter_part)
  1806. def match_str(filter_str, dct):
  1807. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  1808. return all(
  1809. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  1810. def match_filter_func(filter_str):
  1811. def _match_func(info_dict):
  1812. if match_str(filter_str, info_dict):
  1813. return None
  1814. else:
  1815. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  1816. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  1817. return _match_func
  1818. def parse_dfxp_time_expr(time_expr):
  1819. if not time_expr:
  1820. return
  1821. mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
  1822. if mobj:
  1823. return float(mobj.group('time_offset'))
  1824. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
  1825. if mobj:
  1826. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
  1827. def srt_subtitles_timecode(seconds):
  1828. return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
  1829. def dfxp2srt(dfxp_data):
  1830. _x = functools.partial(xpath_with_ns, ns_map={
  1831. 'ttml': 'http://www.w3.org/ns/ttml',
  1832. 'ttaf1': 'http://www.w3.org/2006/10/ttaf1',
  1833. 'ttaf1_0604': 'http://www.w3.org/2006/04/ttaf1',
  1834. })
  1835. class TTMLPElementParser(object):
  1836. out = ''
  1837. def start(self, tag, attrib):
  1838. if tag in (_x('ttml:br'), _x('ttaf1:br'), 'br'):
  1839. self.out += '\n'
  1840. def end(self, tag):
  1841. pass
  1842. def data(self, data):
  1843. self.out += data
  1844. def close(self):
  1845. return self.out.strip()
  1846. def parse_node(node):
  1847. target = TTMLPElementParser()
  1848. parser = xml.etree.ElementTree.XMLParser(target=target)
  1849. parser.feed(xml.etree.ElementTree.tostring(node))
  1850. return parser.close()
  1851. dfxp = compat_etree_fromstring(dfxp_data.encode('utf-8'))
  1852. out = []
  1853. paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall(_x('.//ttaf1:p')) or dfxp.findall(_x('.//ttaf1_0604:p')) or dfxp.findall('.//p')
  1854. if not paras:
  1855. raise ValueError('Invalid dfxp/TTML subtitle')
  1856. for para, index in zip(paras, itertools.count(1)):
  1857. begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
  1858. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  1859. dur = parse_dfxp_time_expr(para.attrib.get('dur'))
  1860. if begin_time is None:
  1861. continue
  1862. if not end_time:
  1863. if not dur:
  1864. continue
  1865. end_time = begin_time + dur
  1866. out.append('%d\n%s --> %s\n%s\n\n' % (
  1867. index,
  1868. srt_subtitles_timecode(begin_time),
  1869. srt_subtitles_timecode(end_time),
  1870. parse_node(para)))
  1871. return ''.join(out)
  1872. def cli_option(params, command_option, param):
  1873. param = params.get(param)
  1874. return [command_option, param] if param is not None else []
  1875. def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
  1876. param = params.get(param)
  1877. assert isinstance(param, bool)
  1878. if separator:
  1879. return [command_option + separator + (true_value if param else false_value)]
  1880. return [command_option, true_value if param else false_value]
  1881. def cli_valueless_option(params, command_option, param, expected_value=True):
  1882. param = params.get(param)
  1883. return [command_option] if param == expected_value else []
  1884. def cli_configuration_args(params, param, default=[]):
  1885. ex_args = params.get(param)
  1886. if ex_args is None:
  1887. return default
  1888. assert isinstance(ex_args, list)
  1889. return ex_args
  1890. class ISO639Utils(object):
  1891. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  1892. _lang_map = {
  1893. 'aa': 'aar',
  1894. 'ab': 'abk',
  1895. 'ae': 'ave',
  1896. 'af': 'afr',
  1897. 'ak': 'aka',
  1898. 'am': 'amh',
  1899. 'an': 'arg',
  1900. 'ar': 'ara',
  1901. 'as': 'asm',
  1902. 'av': 'ava',
  1903. 'ay': 'aym',
  1904. 'az': 'aze',
  1905. 'ba': 'bak',
  1906. 'be': 'bel',
  1907. 'bg': 'bul',
  1908. 'bh': 'bih',
  1909. 'bi': 'bis',
  1910. 'bm': 'bam',
  1911. 'bn': 'ben',
  1912. 'bo': 'bod',
  1913. 'br': 'bre',
  1914. 'bs': 'bos',
  1915. 'ca': 'cat',
  1916. 'ce': 'che',
  1917. 'ch': 'cha',
  1918. 'co': 'cos',
  1919. 'cr': 'cre',
  1920. 'cs': 'ces',
  1921. 'cu': 'chu',
  1922. 'cv': 'chv',
  1923. 'cy': 'cym',
  1924. 'da': 'dan',
  1925. 'de': 'deu',
  1926. 'dv': 'div',
  1927. 'dz': 'dzo',
  1928. 'ee': 'ewe',
  1929. 'el': 'ell',
  1930. 'en': 'eng',
  1931. 'eo': 'epo',
  1932. 'es': 'spa',
  1933. 'et': 'est',
  1934. 'eu': 'eus',
  1935. 'fa': 'fas',
  1936. 'ff': 'ful',
  1937. 'fi': 'fin',
  1938. 'fj': 'fij',
  1939. 'fo': 'fao',
  1940. 'fr': 'fra',
  1941. 'fy': 'fry',
  1942. 'ga': 'gle',
  1943. 'gd': 'gla',
  1944. 'gl': 'glg',
  1945. 'gn': 'grn',
  1946. 'gu': 'guj',
  1947. 'gv': 'glv',
  1948. 'ha': 'hau',
  1949. 'he': 'heb',
  1950. 'hi': 'hin',
  1951. 'ho': 'hmo',
  1952. 'hr': 'hrv',
  1953. 'ht': 'hat',
  1954. 'hu': 'hun',
  1955. 'hy': 'hye',
  1956. 'hz': 'her',
  1957. 'ia': 'ina',
  1958. 'id': 'ind',
  1959. 'ie': 'ile',
  1960. 'ig': 'ibo',
  1961. 'ii': 'iii',
  1962. 'ik': 'ipk',
  1963. 'io': 'ido',
  1964. 'is': 'isl',
  1965. 'it': 'ita',
  1966. 'iu': 'iku',
  1967. 'ja': 'jpn',
  1968. 'jv': 'jav',
  1969. 'ka': 'kat',
  1970. 'kg': 'kon',
  1971. 'ki': 'kik',
  1972. 'kj': 'kua',
  1973. 'kk': 'kaz',
  1974. 'kl': 'kal',
  1975. 'km': 'khm',
  1976. 'kn': 'kan',
  1977. 'ko': 'kor',
  1978. 'kr': 'kau',
  1979. 'ks': 'kas',
  1980. 'ku': 'kur',
  1981. 'kv': 'kom',
  1982. 'kw': 'cor',
  1983. 'ky': 'kir',
  1984. 'la': 'lat',
  1985. 'lb': 'ltz',
  1986. 'lg': 'lug',
  1987. 'li': 'lim',
  1988. 'ln': 'lin',
  1989. 'lo': 'lao',
  1990. 'lt': 'lit',
  1991. 'lu': 'lub',
  1992. 'lv': 'lav',
  1993. 'mg': 'mlg',
  1994. 'mh': 'mah',
  1995. 'mi': 'mri',
  1996. 'mk': 'mkd',
  1997. 'ml': 'mal',
  1998. 'mn': 'mon',
  1999. 'mr': 'mar',
  2000. 'ms': 'msa',
  2001. 'mt': 'mlt',
  2002. 'my': 'mya',
  2003. 'na': 'nau',
  2004. 'nb': 'nob',
  2005. 'nd': 'nde',
  2006. 'ne': 'nep',
  2007. 'ng': 'ndo',
  2008. 'nl': 'nld',
  2009. 'nn': 'nno',
  2010. 'no': 'nor',
  2011. 'nr': 'nbl',
  2012. 'nv': 'nav',
  2013. 'ny': 'nya',
  2014. 'oc': 'oci',
  2015. 'oj': 'oji',
  2016. 'om': 'orm',
  2017. 'or': 'ori',
  2018. 'os': 'oss',
  2019. 'pa': 'pan',
  2020. 'pi': 'pli',
  2021. 'pl': 'pol',
  2022. 'ps': 'pus',
  2023. 'pt': 'por',
  2024. 'qu': 'que',
  2025. 'rm': 'roh',
  2026. 'rn': 'run',
  2027. 'ro': 'ron',
  2028. 'ru': 'rus',
  2029. 'rw': 'kin',
  2030. 'sa': 'san',
  2031. 'sc': 'srd',
  2032. 'sd': 'snd',
  2033. 'se': 'sme',
  2034. 'sg': 'sag',
  2035. 'si': 'sin',
  2036. 'sk': 'slk',
  2037. 'sl': 'slv',
  2038. 'sm': 'smo',
  2039. 'sn': 'sna',
  2040. 'so': 'som',
  2041. 'sq': 'sqi',
  2042. 'sr': 'srp',
  2043. 'ss': 'ssw',
  2044. 'st': 'sot',
  2045. 'su': 'sun',
  2046. 'sv': 'swe',
  2047. 'sw': 'swa',
  2048. 'ta': 'tam',
  2049. 'te': 'tel',
  2050. 'tg': 'tgk',
  2051. 'th': 'tha',
  2052. 'ti': 'tir',
  2053. 'tk': 'tuk',
  2054. 'tl': 'tgl',
  2055. 'tn': 'tsn',
  2056. 'to': 'ton',
  2057. 'tr': 'tur',
  2058. 'ts': 'tso',
  2059. 'tt': 'tat',
  2060. 'tw': 'twi',
  2061. 'ty': 'tah',
  2062. 'ug': 'uig',
  2063. 'uk': 'ukr',
  2064. 'ur': 'urd',
  2065. 'uz': 'uzb',
  2066. 've': 'ven',
  2067. 'vi': 'vie',
  2068. 'vo': 'vol',
  2069. 'wa': 'wln',
  2070. 'wo': 'wol',
  2071. 'xh': 'xho',
  2072. 'yi': 'yid',
  2073. 'yo': 'yor',
  2074. 'za': 'zha',
  2075. 'zh': 'zho',
  2076. 'zu': 'zul',
  2077. }
  2078. @classmethod
  2079. def short2long(cls, code):
  2080. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  2081. return cls._lang_map.get(code[:2])
  2082. @classmethod
  2083. def long2short(cls, code):
  2084. """Convert language code from ISO 639-2/T to ISO 639-1"""
  2085. for short_name, long_name in cls._lang_map.items():
  2086. if long_name == code:
  2087. return short_name
  2088. class ISO3166Utils(object):
  2089. # From http://data.okfn.org/data/core/country-list
  2090. _country_map = {
  2091. 'AF': 'Afghanistan',
  2092. 'AX': 'Åland Islands',
  2093. 'AL': 'Albania',
  2094. 'DZ': 'Algeria',
  2095. 'AS': 'American Samoa',
  2096. 'AD': 'Andorra',
  2097. 'AO': 'Angola',
  2098. 'AI': 'Anguilla',
  2099. 'AQ': 'Antarctica',
  2100. 'AG': 'Antigua and Barbuda',
  2101. 'AR': 'Argentina',
  2102. 'AM': 'Armenia',
  2103. 'AW': 'Aruba',
  2104. 'AU': 'Australia',
  2105. 'AT': 'Austria',
  2106. 'AZ': 'Azerbaijan',
  2107. 'BS': 'Bahamas',
  2108. 'BH': 'Bahrain',
  2109. 'BD': 'Bangladesh',
  2110. 'BB': 'Barbados',
  2111. 'BY': 'Belarus',
  2112. 'BE': 'Belgium',
  2113. 'BZ': 'Belize',
  2114. 'BJ': 'Benin',
  2115. 'BM': 'Bermuda',
  2116. 'BT': 'Bhutan',
  2117. 'BO': 'Bolivia, Plurinational State of',
  2118. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  2119. 'BA': 'Bosnia and Herzegovina',
  2120. 'BW': 'Botswana',
  2121. 'BV': 'Bouvet Island',
  2122. 'BR': 'Brazil',
  2123. 'IO': 'British Indian Ocean Territory',
  2124. 'BN': 'Brunei Darussalam',
  2125. 'BG': 'Bulgaria',
  2126. 'BF': 'Burkina Faso',
  2127. 'BI': 'Burundi',
  2128. 'KH': 'Cambodia',
  2129. 'CM': 'Cameroon',
  2130. 'CA': 'Canada',
  2131. 'CV': 'Cape Verde',
  2132. 'KY': 'Cayman Islands',
  2133. 'CF': 'Central African Republic',
  2134. 'TD': 'Chad',
  2135. 'CL': 'Chile',
  2136. 'CN': 'China',
  2137. 'CX': 'Christmas Island',
  2138. 'CC': 'Cocos (Keeling) Islands',
  2139. 'CO': 'Colombia',
  2140. 'KM': 'Comoros',
  2141. 'CG': 'Congo',
  2142. 'CD': 'Congo, the Democratic Republic of the',
  2143. 'CK': 'Cook Islands',
  2144. 'CR': 'Costa Rica',
  2145. 'CI': 'Côte d\'Ivoire',
  2146. 'HR': 'Croatia',
  2147. 'CU': 'Cuba',
  2148. 'CW': 'Curaçao',
  2149. 'CY': 'Cyprus',
  2150. 'CZ': 'Czech Republic',
  2151. 'DK': 'Denmark',
  2152. 'DJ': 'Djibouti',
  2153. 'DM': 'Dominica',
  2154. 'DO': 'Dominican Republic',
  2155. 'EC': 'Ecuador',
  2156. 'EG': 'Egypt',
  2157. 'SV': 'El Salvador',
  2158. 'GQ': 'Equatorial Guinea',
  2159. 'ER': 'Eritrea',
  2160. 'EE': 'Estonia',
  2161. 'ET': 'Ethiopia',
  2162. 'FK': 'Falkland Islands (Malvinas)',
  2163. 'FO': 'Faroe Islands',
  2164. 'FJ': 'Fiji',
  2165. 'FI': 'Finland',
  2166. 'FR': 'France',
  2167. 'GF': 'French Guiana',
  2168. 'PF': 'French Polynesia',
  2169. 'TF': 'French Southern Territories',
  2170. 'GA': 'Gabon',
  2171. 'GM': 'Gambia',
  2172. 'GE': 'Georgia',
  2173. 'DE': 'Germany',
  2174. 'GH': 'Ghana',
  2175. 'GI': 'Gibraltar',
  2176. 'GR': 'Greece',
  2177. 'GL': 'Greenland',
  2178. 'GD': 'Grenada',
  2179. 'GP': 'Guadeloupe',
  2180. 'GU': 'Guam',
  2181. 'GT': 'Guatemala',
  2182. 'GG': 'Guernsey',
  2183. 'GN': 'Guinea',
  2184. 'GW': 'Guinea-Bissau',
  2185. 'GY': 'Guyana',
  2186. 'HT': 'Haiti',
  2187. 'HM': 'Heard Island and McDonald Islands',
  2188. 'VA': 'Holy See (Vatican City State)',
  2189. 'HN': 'Honduras',
  2190. 'HK': 'Hong Kong',
  2191. 'HU': 'Hungary',
  2192. 'IS': 'Iceland',
  2193. 'IN': 'India',
  2194. 'ID': 'Indonesia',
  2195. 'IR': 'Iran, Islamic Republic of',
  2196. 'IQ': 'Iraq',
  2197. 'IE': 'Ireland',
  2198. 'IM': 'Isle of Man',
  2199. 'IL': 'Israel',
  2200. 'IT': 'Italy',
  2201. 'JM': 'Jamaica',
  2202. 'JP': 'Japan',
  2203. 'JE': 'Jersey',
  2204. 'JO': 'Jordan',
  2205. 'KZ': 'Kazakhstan',
  2206. 'KE': 'Kenya',
  2207. 'KI': 'Kiribati',
  2208. 'KP': 'Korea, Democratic People\'s Republic of',
  2209. 'KR': 'Korea, Republic of',
  2210. 'KW': 'Kuwait',
  2211. 'KG': 'Kyrgyzstan',
  2212. 'LA': 'Lao People\'s Democratic Republic',
  2213. 'LV': 'Latvia',
  2214. 'LB': 'Lebanon',
  2215. 'LS': 'Lesotho',
  2216. 'LR': 'Liberia',
  2217. 'LY': 'Libya',
  2218. 'LI': 'Liechtenstein',
  2219. 'LT': 'Lithuania',
  2220. 'LU': 'Luxembourg',
  2221. 'MO': 'Macao',
  2222. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  2223. 'MG': 'Madagascar',
  2224. 'MW': 'Malawi',
  2225. 'MY': 'Malaysia',
  2226. 'MV': 'Maldives',
  2227. 'ML': 'Mali',
  2228. 'MT': 'Malta',
  2229. 'MH': 'Marshall Islands',
  2230. 'MQ': 'Martinique',
  2231. 'MR': 'Mauritania',
  2232. 'MU': 'Mauritius',
  2233. 'YT': 'Mayotte',
  2234. 'MX': 'Mexico',
  2235. 'FM': 'Micronesia, Federated States of',
  2236. 'MD': 'Moldova, Republic of',
  2237. 'MC': 'Monaco',
  2238. 'MN': 'Mongolia',
  2239. 'ME': 'Montenegro',
  2240. 'MS': 'Montserrat',
  2241. 'MA': 'Morocco',
  2242. 'MZ': 'Mozambique',
  2243. 'MM': 'Myanmar',
  2244. 'NA': 'Namibia',
  2245. 'NR': 'Nauru',
  2246. 'NP': 'Nepal',
  2247. 'NL': 'Netherlands',
  2248. 'NC': 'New Caledonia',
  2249. 'NZ': 'New Zealand',
  2250. 'NI': 'Nicaragua',
  2251. 'NE': 'Niger',
  2252. 'NG': 'Nigeria',
  2253. 'NU': 'Niue',
  2254. 'NF': 'Norfolk Island',
  2255. 'MP': 'Northern Mariana Islands',
  2256. 'NO': 'Norway',
  2257. 'OM': 'Oman',
  2258. 'PK': 'Pakistan',
  2259. 'PW': 'Palau',
  2260. 'PS': 'Palestine, State of',
  2261. 'PA': 'Panama',
  2262. 'PG': 'Papua New Guinea',
  2263. 'PY': 'Paraguay',
  2264. 'PE': 'Peru',
  2265. 'PH': 'Philippines',
  2266. 'PN': 'Pitcairn',
  2267. 'PL': 'Poland',
  2268. 'PT': 'Portugal',
  2269. 'PR': 'Puerto Rico',
  2270. 'QA': 'Qatar',
  2271. 'RE': 'Réunion',
  2272. 'RO': 'Romania',
  2273. 'RU': 'Russian Federation',
  2274. 'RW': 'Rwanda',
  2275. 'BL': 'Saint Barthélemy',
  2276. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  2277. 'KN': 'Saint Kitts and Nevis',
  2278. 'LC': 'Saint Lucia',
  2279. 'MF': 'Saint Martin (French part)',
  2280. 'PM': 'Saint Pierre and Miquelon',
  2281. 'VC': 'Saint Vincent and the Grenadines',
  2282. 'WS': 'Samoa',
  2283. 'SM': 'San Marino',
  2284. 'ST': 'Sao Tome and Principe',
  2285. 'SA': 'Saudi Arabia',
  2286. 'SN': 'Senegal',
  2287. 'RS': 'Serbia',
  2288. 'SC': 'Seychelles',
  2289. 'SL': 'Sierra Leone',
  2290. 'SG': 'Singapore',
  2291. 'SX': 'Sint Maarten (Dutch part)',
  2292. 'SK': 'Slovakia',
  2293. 'SI': 'Slovenia',
  2294. 'SB': 'Solomon Islands',
  2295. 'SO': 'Somalia',
  2296. 'ZA': 'South Africa',
  2297. 'GS': 'South Georgia and the South Sandwich Islands',
  2298. 'SS': 'South Sudan',
  2299. 'ES': 'Spain',
  2300. 'LK': 'Sri Lanka',
  2301. 'SD': 'Sudan',
  2302. 'SR': 'Suriname',
  2303. 'SJ': 'Svalbard and Jan Mayen',
  2304. 'SZ': 'Swaziland',
  2305. 'SE': 'Sweden',
  2306. 'CH': 'Switzerland',
  2307. 'SY': 'Syrian Arab Republic',
  2308. 'TW': 'Taiwan, Province of China',
  2309. 'TJ': 'Tajikistan',
  2310. 'TZ': 'Tanzania, United Republic of',
  2311. 'TH': 'Thailand',
  2312. 'TL': 'Timor-Leste',
  2313. 'TG': 'Togo',
  2314. 'TK': 'Tokelau',
  2315. 'TO': 'Tonga',
  2316. 'TT': 'Trinidad and Tobago',
  2317. 'TN': 'Tunisia',
  2318. 'TR': 'Turkey',
  2319. 'TM': 'Turkmenistan',
  2320. 'TC': 'Turks and Caicos Islands',
  2321. 'TV': 'Tuvalu',
  2322. 'UG': 'Uganda',
  2323. 'UA': 'Ukraine',
  2324. 'AE': 'United Arab Emirates',
  2325. 'GB': 'United Kingdom',
  2326. 'US': 'United States',
  2327. 'UM': 'United States Minor Outlying Islands',
  2328. 'UY': 'Uruguay',
  2329. 'UZ': 'Uzbekistan',
  2330. 'VU': 'Vanuatu',
  2331. 'VE': 'Venezuela, Bolivarian Republic of',
  2332. 'VN': 'Viet Nam',
  2333. 'VG': 'Virgin Islands, British',
  2334. 'VI': 'Virgin Islands, U.S.',
  2335. 'WF': 'Wallis and Futuna',
  2336. 'EH': 'Western Sahara',
  2337. 'YE': 'Yemen',
  2338. 'ZM': 'Zambia',
  2339. 'ZW': 'Zimbabwe',
  2340. }
  2341. @classmethod
  2342. def short2full(cls, code):
  2343. """Convert an ISO 3166-2 country code to the corresponding full name"""
  2344. return cls._country_map.get(code.upper())
  2345. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  2346. def __init__(self, proxies=None):
  2347. # Set default handlers
  2348. for type in ('http', 'https'):
  2349. setattr(self, '%s_open' % type,
  2350. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  2351. meth(r, proxy, type))
  2352. return compat_urllib_request.ProxyHandler.__init__(self, proxies)
  2353. def proxy_open(self, req, proxy, type):
  2354. req_proxy = req.headers.get('Ytdl-request-proxy')
  2355. if req_proxy is not None:
  2356. proxy = req_proxy
  2357. del req.headers['Ytdl-request-proxy']
  2358. if proxy == '__noproxy__':
  2359. return None # No Proxy
  2360. if compat_urlparse.urlparse(proxy).scheme.lower() in ('socks', 'socks4', 'socks4a', 'socks5'):
  2361. req.add_header('Ytdl-socks-proxy', proxy)
  2362. # youtube-dl's http/https handlers do wrapping the socket with socks
  2363. return None
  2364. return compat_urllib_request.ProxyHandler.proxy_open(
  2365. self, req, proxy, type)
  2366. def ohdave_rsa_encrypt(data, exponent, modulus):
  2367. '''
  2368. Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
  2369. Input:
  2370. data: data to encrypt, bytes-like object
  2371. exponent, modulus: parameter e and N of RSA algorithm, both integer
  2372. Output: hex string of encrypted data
  2373. Limitation: supports one block encryption only
  2374. '''
  2375. payload = int(binascii.hexlify(data[::-1]), 16)
  2376. encrypted = pow(payload, exponent, modulus)
  2377. return '%x' % encrypted
  2378. def encode_base_n(num, n, table=None):
  2379. FULL_TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  2380. if not table:
  2381. table = FULL_TABLE[:n]
  2382. if n > len(table):
  2383. raise ValueError('base %d exceeds table length %d' % (n, len(table)))
  2384. if num == 0:
  2385. return table[0]
  2386. ret = ''
  2387. while num:
  2388. ret = table[num % n] + ret
  2389. num = num // n
  2390. return ret
  2391. def decode_packed_codes(code):
  2392. mobj = re.search(
  2393. r"}\('(.+)',(\d+),(\d+),'([^']+)'\.split\('\|'\)",
  2394. code)
  2395. obfucasted_code, base, count, symbols = mobj.groups()
  2396. base = int(base)
  2397. count = int(count)
  2398. symbols = symbols.split('|')
  2399. symbol_table = {}
  2400. while count:
  2401. count -= 1
  2402. base_n_count = encode_base_n(count, base)
  2403. symbol_table[base_n_count] = symbols[count] or base_n_count
  2404. return re.sub(
  2405. r'\b(\w+)\b', lambda mobj: symbol_table[mobj.group(0)],
  2406. obfucasted_code)
  2407. def parse_m3u8_attributes(attrib):
  2408. info = {}
  2409. for (key, val) in re.findall(r'(?P<key>[A-Z0-9-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)', attrib):
  2410. if val.startswith('"'):
  2411. val = val[1:-1]
  2412. info[key] = val
  2413. return info
  2414. def urshift(val, n):
  2415. return val >> n if val >= 0 else (val + 0x100000000) >> n