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.

2916 lines
87 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. class PUTRequest(compat_urllib_request.Request):
  1318. def get_method(self):
  1319. return 'PUT'
  1320. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  1321. if get_attr:
  1322. if v is not None:
  1323. v = getattr(v, get_attr, None)
  1324. if v == '':
  1325. v = None
  1326. if v is None:
  1327. return default
  1328. try:
  1329. return int(v) * invscale // scale
  1330. except ValueError:
  1331. return default
  1332. def str_or_none(v, default=None):
  1333. return default if v is None else compat_str(v)
  1334. def str_to_int(int_str):
  1335. """ A more relaxed version of int_or_none """
  1336. if int_str is None:
  1337. return None
  1338. int_str = re.sub(r'[,\.\+]', '', int_str)
  1339. return int(int_str)
  1340. def float_or_none(v, scale=1, invscale=1, default=None):
  1341. if v is None:
  1342. return default
  1343. try:
  1344. return float(v) * invscale / scale
  1345. except ValueError:
  1346. return default
  1347. def strip_or_none(v):
  1348. return None if v is None else v.strip()
  1349. def parse_duration(s):
  1350. if not isinstance(s, compat_basestring):
  1351. return None
  1352. s = s.strip()
  1353. days, hours, mins, secs, ms = [None] * 5
  1354. 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)
  1355. if m:
  1356. days, hours, mins, secs, ms = m.groups()
  1357. else:
  1358. m = re.match(
  1359. r'''(?ix)(?:P?T)?
  1360. (?:
  1361. (?P<days>[0-9]+)\s*d(?:ays?)?\s*
  1362. )?
  1363. (?:
  1364. (?P<hours>[0-9]+)\s*h(?:ours?)?\s*
  1365. )?
  1366. (?:
  1367. (?P<mins>[0-9]+)\s*m(?:in(?:ute)?s?)?\s*
  1368. )?
  1369. (?:
  1370. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*s(?:ec(?:ond)?s?)?\s*
  1371. )?$''', s)
  1372. if m:
  1373. days, hours, mins, secs, ms = m.groups()
  1374. else:
  1375. m = re.match(r'(?i)(?:(?P<hours>[0-9.]+)\s*(?:hours?)|(?P<mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*)$', s)
  1376. if m:
  1377. hours, mins = m.groups()
  1378. else:
  1379. return None
  1380. duration = 0
  1381. if secs:
  1382. duration += float(secs)
  1383. if mins:
  1384. duration += float(mins) * 60
  1385. if hours:
  1386. duration += float(hours) * 60 * 60
  1387. if days:
  1388. duration += float(days) * 24 * 60 * 60
  1389. if ms:
  1390. duration += float(ms)
  1391. return duration
  1392. def prepend_extension(filename, ext, expected_real_ext=None):
  1393. name, real_ext = os.path.splitext(filename)
  1394. return (
  1395. '{0}.{1}{2}'.format(name, ext, real_ext)
  1396. if not expected_real_ext or real_ext[1:] == expected_real_ext
  1397. else '{0}.{1}'.format(filename, ext))
  1398. def replace_extension(filename, ext, expected_real_ext=None):
  1399. name, real_ext = os.path.splitext(filename)
  1400. return '{0}.{1}'.format(
  1401. name if not expected_real_ext or real_ext[1:] == expected_real_ext else filename,
  1402. ext)
  1403. def check_executable(exe, args=[]):
  1404. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  1405. args can be a list of arguments for a short output (like -version) """
  1406. try:
  1407. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  1408. except OSError:
  1409. return False
  1410. return exe
  1411. def get_exe_version(exe, args=['--version'],
  1412. version_re=None, unrecognized='present'):
  1413. """ Returns the version of the specified executable,
  1414. or False if the executable is not present """
  1415. try:
  1416. out, _ = subprocess.Popen(
  1417. [encodeArgument(exe)] + args,
  1418. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  1419. except OSError:
  1420. return False
  1421. if isinstance(out, bytes): # Python 2.x
  1422. out = out.decode('ascii', 'ignore')
  1423. return detect_exe_version(out, version_re, unrecognized)
  1424. def detect_exe_version(output, version_re=None, unrecognized='present'):
  1425. assert isinstance(output, compat_str)
  1426. if version_re is None:
  1427. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  1428. m = re.search(version_re, output)
  1429. if m:
  1430. return m.group(1)
  1431. else:
  1432. return unrecognized
  1433. class PagedList(object):
  1434. def __len__(self):
  1435. # This is only useful for tests
  1436. return len(self.getslice())
  1437. class OnDemandPagedList(PagedList):
  1438. def __init__(self, pagefunc, pagesize, use_cache=False):
  1439. self._pagefunc = pagefunc
  1440. self._pagesize = pagesize
  1441. self._use_cache = use_cache
  1442. if use_cache:
  1443. self._cache = {}
  1444. def getslice(self, start=0, end=None):
  1445. res = []
  1446. for pagenum in itertools.count(start // self._pagesize):
  1447. firstid = pagenum * self._pagesize
  1448. nextfirstid = pagenum * self._pagesize + self._pagesize
  1449. if start >= nextfirstid:
  1450. continue
  1451. page_results = None
  1452. if self._use_cache:
  1453. page_results = self._cache.get(pagenum)
  1454. if page_results is None:
  1455. page_results = list(self._pagefunc(pagenum))
  1456. if self._use_cache:
  1457. self._cache[pagenum] = page_results
  1458. startv = (
  1459. start % self._pagesize
  1460. if firstid <= start < nextfirstid
  1461. else 0)
  1462. endv = (
  1463. ((end - 1) % self._pagesize) + 1
  1464. if (end is not None and firstid <= end <= nextfirstid)
  1465. else None)
  1466. if startv != 0 or endv is not None:
  1467. page_results = page_results[startv:endv]
  1468. res.extend(page_results)
  1469. # A little optimization - if current page is not "full", ie. does
  1470. # not contain page_size videos then we can assume that this page
  1471. # is the last one - there are no more ids on further pages -
  1472. # i.e. no need to query again.
  1473. if len(page_results) + startv < self._pagesize:
  1474. break
  1475. # If we got the whole page, but the next page is not interesting,
  1476. # break out early as well
  1477. if end == nextfirstid:
  1478. break
  1479. return res
  1480. class InAdvancePagedList(PagedList):
  1481. def __init__(self, pagefunc, pagecount, pagesize):
  1482. self._pagefunc = pagefunc
  1483. self._pagecount = pagecount
  1484. self._pagesize = pagesize
  1485. def getslice(self, start=0, end=None):
  1486. res = []
  1487. start_page = start // self._pagesize
  1488. end_page = (
  1489. self._pagecount if end is None else (end // self._pagesize + 1))
  1490. skip_elems = start - start_page * self._pagesize
  1491. only_more = None if end is None else end - start
  1492. for pagenum in range(start_page, end_page):
  1493. page = list(self._pagefunc(pagenum))
  1494. if skip_elems:
  1495. page = page[skip_elems:]
  1496. skip_elems = None
  1497. if only_more is not None:
  1498. if len(page) < only_more:
  1499. only_more -= len(page)
  1500. else:
  1501. page = page[:only_more]
  1502. res.extend(page)
  1503. break
  1504. res.extend(page)
  1505. return res
  1506. def uppercase_escape(s):
  1507. unicode_escape = codecs.getdecoder('unicode_escape')
  1508. return re.sub(
  1509. r'\\U[0-9a-fA-F]{8}',
  1510. lambda m: unicode_escape(m.group(0))[0],
  1511. s)
  1512. def lowercase_escape(s):
  1513. unicode_escape = codecs.getdecoder('unicode_escape')
  1514. return re.sub(
  1515. r'\\u[0-9a-fA-F]{4}',
  1516. lambda m: unicode_escape(m.group(0))[0],
  1517. s)
  1518. def escape_rfc3986(s):
  1519. """Escape non-ASCII characters as suggested by RFC 3986"""
  1520. if sys.version_info < (3, 0) and isinstance(s, compat_str):
  1521. s = s.encode('utf-8')
  1522. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1523. def escape_url(url):
  1524. """Escape URL as suggested by RFC 3986"""
  1525. url_parsed = compat_urllib_parse_urlparse(url)
  1526. return url_parsed._replace(
  1527. netloc=url_parsed.netloc.encode('idna').decode('ascii'),
  1528. path=escape_rfc3986(url_parsed.path),
  1529. params=escape_rfc3986(url_parsed.params),
  1530. query=escape_rfc3986(url_parsed.query),
  1531. fragment=escape_rfc3986(url_parsed.fragment)
  1532. ).geturl()
  1533. def read_batch_urls(batch_fd):
  1534. def fixup(url):
  1535. if not isinstance(url, compat_str):
  1536. url = url.decode('utf-8', 'replace')
  1537. BOM_UTF8 = '\xef\xbb\xbf'
  1538. if url.startswith(BOM_UTF8):
  1539. url = url[len(BOM_UTF8):]
  1540. url = url.strip()
  1541. if url.startswith(('#', ';', ']')):
  1542. return False
  1543. return url
  1544. with contextlib.closing(batch_fd) as fd:
  1545. return [url for url in map(fixup, fd) if url]
  1546. def urlencode_postdata(*args, **kargs):
  1547. return compat_urllib_parse_urlencode(*args, **kargs).encode('ascii')
  1548. def update_url_query(url, query):
  1549. if not query:
  1550. return url
  1551. parsed_url = compat_urlparse.urlparse(url)
  1552. qs = compat_parse_qs(parsed_url.query)
  1553. qs.update(query)
  1554. return compat_urlparse.urlunparse(parsed_url._replace(
  1555. query=compat_urllib_parse_urlencode(qs, True)))
  1556. def update_Request(req, url=None, data=None, headers={}, query={}):
  1557. req_headers = req.headers.copy()
  1558. req_headers.update(headers)
  1559. req_data = data or req.data
  1560. req_url = update_url_query(url or req.get_full_url(), query)
  1561. req_get_method = req.get_method()
  1562. if req_get_method == 'HEAD':
  1563. req_type = HEADRequest
  1564. elif req_get_method == 'PUT':
  1565. req_type = PUTRequest
  1566. else:
  1567. req_type = compat_urllib_request.Request
  1568. new_req = req_type(
  1569. req_url, data=req_data, headers=req_headers,
  1570. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  1571. if hasattr(req, 'timeout'):
  1572. new_req.timeout = req.timeout
  1573. return new_req
  1574. def dict_get(d, key_or_keys, default=None, skip_false_values=True):
  1575. if isinstance(key_or_keys, (list, tuple)):
  1576. for key in key_or_keys:
  1577. if key not in d or d[key] is None or skip_false_values and not d[key]:
  1578. continue
  1579. return d[key]
  1580. return default
  1581. return d.get(key_or_keys, default)
  1582. def try_get(src, getter, expected_type=None):
  1583. try:
  1584. v = getter(src)
  1585. except (AttributeError, KeyError, TypeError, IndexError):
  1586. pass
  1587. else:
  1588. if expected_type is None or isinstance(v, expected_type):
  1589. return v
  1590. def encode_compat_str(string, encoding=preferredencoding(), errors='strict'):
  1591. return string if isinstance(string, compat_str) else compat_str(string, encoding, errors)
  1592. US_RATINGS = {
  1593. 'G': 0,
  1594. 'PG': 10,
  1595. 'PG-13': 13,
  1596. 'R': 16,
  1597. 'NC': 18,
  1598. }
  1599. def parse_age_limit(s):
  1600. if s is None:
  1601. return None
  1602. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1603. return int(m.group('age')) if m else US_RATINGS.get(s)
  1604. def strip_jsonp(code):
  1605. return re.sub(
  1606. r'(?s)^[a-zA-Z0-9_.$]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code)
  1607. def js_to_json(code):
  1608. def fix_kv(m):
  1609. v = m.group(0)
  1610. if v in ('true', 'false', 'null'):
  1611. return v
  1612. elif v.startswith('/*') or v == ',':
  1613. return ""
  1614. if v[0] in ("'", '"'):
  1615. v = re.sub(r'(?s)\\.|"', lambda m: {
  1616. '"': '\\"',
  1617. "\\'": "'",
  1618. '\\\n': '',
  1619. '\\x': '\\u00',
  1620. }.get(m.group(0), m.group(0)), v[1:-1])
  1621. INTEGER_TABLE = (
  1622. (r'^0[xX][0-9a-fA-F]+', 16),
  1623. (r'^0+[0-7]+', 8),
  1624. )
  1625. for regex, base in INTEGER_TABLE:
  1626. im = re.match(regex, v)
  1627. if im:
  1628. i = int(im.group(0), base)
  1629. return '"%d":' % i if v.endswith(':') else '%d' % i
  1630. return '"%s"' % v
  1631. return re.sub(r'''(?sx)
  1632. "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
  1633. '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
  1634. /\*.*?\*/|,(?=\s*[\]}])|
  1635. [a-zA-Z_][.a-zA-Z_0-9]*|
  1636. \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:\s*:)?|
  1637. [0-9]+(?=\s*:)
  1638. ''', fix_kv, code)
  1639. def qualities(quality_ids):
  1640. """ Get a numeric quality value out of a list of possible values """
  1641. def q(qid):
  1642. try:
  1643. return quality_ids.index(qid)
  1644. except ValueError:
  1645. return -1
  1646. return q
  1647. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1648. def limit_length(s, length):
  1649. """ Add ellipses to overly long strings """
  1650. if s is None:
  1651. return None
  1652. ELLIPSES = '...'
  1653. if len(s) > length:
  1654. return s[:length - len(ELLIPSES)] + ELLIPSES
  1655. return s
  1656. def version_tuple(v):
  1657. return tuple(int(e) for e in re.split(r'[-.]', v))
  1658. def is_outdated_version(version, limit, assume_new=True):
  1659. if not version:
  1660. return not assume_new
  1661. try:
  1662. return version_tuple(version) < version_tuple(limit)
  1663. except ValueError:
  1664. return not assume_new
  1665. def ytdl_is_updateable():
  1666. """ Returns if youtube-dl can be updated with -U """
  1667. from zipimport import zipimporter
  1668. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  1669. def args_to_str(args):
  1670. # Get a short string representation for a subprocess command
  1671. return ' '.join(compat_shlex_quote(a) for a in args)
  1672. def error_to_compat_str(err):
  1673. err_str = str(err)
  1674. # On python 2 error byte string must be decoded with proper
  1675. # encoding rather than ascii
  1676. if sys.version_info[0] < 3:
  1677. err_str = err_str.decode(preferredencoding())
  1678. return err_str
  1679. def mimetype2ext(mt):
  1680. if mt is None:
  1681. return None
  1682. ext = {
  1683. 'audio/mp4': 'm4a',
  1684. # Per RFC 3003, audio/mpeg can be .mp1, .mp2 or .mp3. Here use .mp3 as
  1685. # it's the most popular one
  1686. 'audio/mpeg': 'mp3',
  1687. }.get(mt)
  1688. if ext is not None:
  1689. return ext
  1690. _, _, res = mt.rpartition('/')
  1691. return {
  1692. '3gpp': '3gp',
  1693. 'smptett+xml': 'tt',
  1694. 'srt': 'srt',
  1695. 'ttaf+xml': 'dfxp',
  1696. 'ttml+xml': 'ttml',
  1697. 'vtt': 'vtt',
  1698. 'x-flv': 'flv',
  1699. 'x-mp4-fragmented': 'mp4',
  1700. 'x-ms-wmv': 'wmv',
  1701. }.get(res, res)
  1702. def urlhandle_detect_ext(url_handle):
  1703. getheader = url_handle.headers.get
  1704. cd = getheader('Content-Disposition')
  1705. if cd:
  1706. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  1707. if m:
  1708. e = determine_ext(m.group('filename'), default_ext=None)
  1709. if e:
  1710. return e
  1711. return mimetype2ext(getheader('Content-Type'))
  1712. def encode_data_uri(data, mime_type):
  1713. return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
  1714. def age_restricted(content_limit, age_limit):
  1715. """ Returns True iff the content should be blocked """
  1716. if age_limit is None: # No limit set
  1717. return False
  1718. if content_limit is None:
  1719. return False # Content available for everyone
  1720. return age_limit < content_limit
  1721. def is_html(first_bytes):
  1722. """ Detect whether a file contains HTML by examining its first bytes. """
  1723. BOMS = [
  1724. (b'\xef\xbb\xbf', 'utf-8'),
  1725. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  1726. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  1727. (b'\xff\xfe', 'utf-16-le'),
  1728. (b'\xfe\xff', 'utf-16-be'),
  1729. ]
  1730. for bom, enc in BOMS:
  1731. if first_bytes.startswith(bom):
  1732. s = first_bytes[len(bom):].decode(enc, 'replace')
  1733. break
  1734. else:
  1735. s = first_bytes.decode('utf-8', 'replace')
  1736. return re.match(r'^\s*<', s)
  1737. def determine_protocol(info_dict):
  1738. protocol = info_dict.get('protocol')
  1739. if protocol is not None:
  1740. return protocol
  1741. url = info_dict['url']
  1742. if url.startswith('rtmp'):
  1743. return 'rtmp'
  1744. elif url.startswith('mms'):
  1745. return 'mms'
  1746. elif url.startswith('rtsp'):
  1747. return 'rtsp'
  1748. ext = determine_ext(url)
  1749. if ext == 'm3u8':
  1750. return 'm3u8'
  1751. elif ext == 'f4m':
  1752. return 'f4m'
  1753. return compat_urllib_parse_urlparse(url).scheme
  1754. def render_table(header_row, data):
  1755. """ Render a list of rows, each as a list of values """
  1756. table = [header_row] + data
  1757. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  1758. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  1759. return '\n'.join(format_str % tuple(row) for row in table)
  1760. def _match_one(filter_part, dct):
  1761. COMPARISON_OPERATORS = {
  1762. '<': operator.lt,
  1763. '<=': operator.le,
  1764. '>': operator.gt,
  1765. '>=': operator.ge,
  1766. '=': operator.eq,
  1767. '!=': operator.ne,
  1768. }
  1769. operator_rex = re.compile(r'''(?x)\s*
  1770. (?P<key>[a-z_]+)
  1771. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  1772. (?:
  1773. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  1774. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  1775. )
  1776. \s*$
  1777. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  1778. m = operator_rex.search(filter_part)
  1779. if m:
  1780. op = COMPARISON_OPERATORS[m.group('op')]
  1781. if m.group('strval') is not None:
  1782. if m.group('op') not in ('=', '!='):
  1783. raise ValueError(
  1784. 'Operator %s does not support string values!' % m.group('op'))
  1785. comparison_value = m.group('strval')
  1786. else:
  1787. try:
  1788. comparison_value = int(m.group('intval'))
  1789. except ValueError:
  1790. comparison_value = parse_filesize(m.group('intval'))
  1791. if comparison_value is None:
  1792. comparison_value = parse_filesize(m.group('intval') + 'B')
  1793. if comparison_value is None:
  1794. raise ValueError(
  1795. 'Invalid integer value %r in filter part %r' % (
  1796. m.group('intval'), filter_part))
  1797. actual_value = dct.get(m.group('key'))
  1798. if actual_value is None:
  1799. return m.group('none_inclusive')
  1800. return op(actual_value, comparison_value)
  1801. UNARY_OPERATORS = {
  1802. '': lambda v: v is not None,
  1803. '!': lambda v: v is None,
  1804. }
  1805. operator_rex = re.compile(r'''(?x)\s*
  1806. (?P<op>%s)\s*(?P<key>[a-z_]+)
  1807. \s*$
  1808. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  1809. m = operator_rex.search(filter_part)
  1810. if m:
  1811. op = UNARY_OPERATORS[m.group('op')]
  1812. actual_value = dct.get(m.group('key'))
  1813. return op(actual_value)
  1814. raise ValueError('Invalid filter part %r' % filter_part)
  1815. def match_str(filter_str, dct):
  1816. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  1817. return all(
  1818. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  1819. def match_filter_func(filter_str):
  1820. def _match_func(info_dict):
  1821. if match_str(filter_str, info_dict):
  1822. return None
  1823. else:
  1824. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  1825. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  1826. return _match_func
  1827. def parse_dfxp_time_expr(time_expr):
  1828. if not time_expr:
  1829. return
  1830. mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
  1831. if mobj:
  1832. return float(mobj.group('time_offset'))
  1833. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
  1834. if mobj:
  1835. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
  1836. def srt_subtitles_timecode(seconds):
  1837. return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
  1838. def dfxp2srt(dfxp_data):
  1839. _x = functools.partial(xpath_with_ns, ns_map={
  1840. 'ttml': 'http://www.w3.org/ns/ttml',
  1841. 'ttaf1': 'http://www.w3.org/2006/10/ttaf1',
  1842. 'ttaf1_0604': 'http://www.w3.org/2006/04/ttaf1',
  1843. })
  1844. class TTMLPElementParser(object):
  1845. out = ''
  1846. def start(self, tag, attrib):
  1847. if tag in (_x('ttml:br'), _x('ttaf1:br'), 'br'):
  1848. self.out += '\n'
  1849. def end(self, tag):
  1850. pass
  1851. def data(self, data):
  1852. self.out += data
  1853. def close(self):
  1854. return self.out.strip()
  1855. def parse_node(node):
  1856. target = TTMLPElementParser()
  1857. parser = xml.etree.ElementTree.XMLParser(target=target)
  1858. parser.feed(xml.etree.ElementTree.tostring(node))
  1859. return parser.close()
  1860. dfxp = compat_etree_fromstring(dfxp_data.encode('utf-8'))
  1861. out = []
  1862. paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall(_x('.//ttaf1:p')) or dfxp.findall(_x('.//ttaf1_0604:p')) or dfxp.findall('.//p')
  1863. if not paras:
  1864. raise ValueError('Invalid dfxp/TTML subtitle')
  1865. for para, index in zip(paras, itertools.count(1)):
  1866. begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
  1867. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  1868. dur = parse_dfxp_time_expr(para.attrib.get('dur'))
  1869. if begin_time is None:
  1870. continue
  1871. if not end_time:
  1872. if not dur:
  1873. continue
  1874. end_time = begin_time + dur
  1875. out.append('%d\n%s --> %s\n%s\n\n' % (
  1876. index,
  1877. srt_subtitles_timecode(begin_time),
  1878. srt_subtitles_timecode(end_time),
  1879. parse_node(para)))
  1880. return ''.join(out)
  1881. def cli_option(params, command_option, param):
  1882. param = params.get(param)
  1883. return [command_option, param] if param is not None else []
  1884. def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
  1885. param = params.get(param)
  1886. assert isinstance(param, bool)
  1887. if separator:
  1888. return [command_option + separator + (true_value if param else false_value)]
  1889. return [command_option, true_value if param else false_value]
  1890. def cli_valueless_option(params, command_option, param, expected_value=True):
  1891. param = params.get(param)
  1892. return [command_option] if param == expected_value else []
  1893. def cli_configuration_args(params, param, default=[]):
  1894. ex_args = params.get(param)
  1895. if ex_args is None:
  1896. return default
  1897. assert isinstance(ex_args, list)
  1898. return ex_args
  1899. class ISO639Utils(object):
  1900. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  1901. _lang_map = {
  1902. 'aa': 'aar',
  1903. 'ab': 'abk',
  1904. 'ae': 'ave',
  1905. 'af': 'afr',
  1906. 'ak': 'aka',
  1907. 'am': 'amh',
  1908. 'an': 'arg',
  1909. 'ar': 'ara',
  1910. 'as': 'asm',
  1911. 'av': 'ava',
  1912. 'ay': 'aym',
  1913. 'az': 'aze',
  1914. 'ba': 'bak',
  1915. 'be': 'bel',
  1916. 'bg': 'bul',
  1917. 'bh': 'bih',
  1918. 'bi': 'bis',
  1919. 'bm': 'bam',
  1920. 'bn': 'ben',
  1921. 'bo': 'bod',
  1922. 'br': 'bre',
  1923. 'bs': 'bos',
  1924. 'ca': 'cat',
  1925. 'ce': 'che',
  1926. 'ch': 'cha',
  1927. 'co': 'cos',
  1928. 'cr': 'cre',
  1929. 'cs': 'ces',
  1930. 'cu': 'chu',
  1931. 'cv': 'chv',
  1932. 'cy': 'cym',
  1933. 'da': 'dan',
  1934. 'de': 'deu',
  1935. 'dv': 'div',
  1936. 'dz': 'dzo',
  1937. 'ee': 'ewe',
  1938. 'el': 'ell',
  1939. 'en': 'eng',
  1940. 'eo': 'epo',
  1941. 'es': 'spa',
  1942. 'et': 'est',
  1943. 'eu': 'eus',
  1944. 'fa': 'fas',
  1945. 'ff': 'ful',
  1946. 'fi': 'fin',
  1947. 'fj': 'fij',
  1948. 'fo': 'fao',
  1949. 'fr': 'fra',
  1950. 'fy': 'fry',
  1951. 'ga': 'gle',
  1952. 'gd': 'gla',
  1953. 'gl': 'glg',
  1954. 'gn': 'grn',
  1955. 'gu': 'guj',
  1956. 'gv': 'glv',
  1957. 'ha': 'hau',
  1958. 'he': 'heb',
  1959. 'hi': 'hin',
  1960. 'ho': 'hmo',
  1961. 'hr': 'hrv',
  1962. 'ht': 'hat',
  1963. 'hu': 'hun',
  1964. 'hy': 'hye',
  1965. 'hz': 'her',
  1966. 'ia': 'ina',
  1967. 'id': 'ind',
  1968. 'ie': 'ile',
  1969. 'ig': 'ibo',
  1970. 'ii': 'iii',
  1971. 'ik': 'ipk',
  1972. 'io': 'ido',
  1973. 'is': 'isl',
  1974. 'it': 'ita',
  1975. 'iu': 'iku',
  1976. 'ja': 'jpn',
  1977. 'jv': 'jav',
  1978. 'ka': 'kat',
  1979. 'kg': 'kon',
  1980. 'ki': 'kik',
  1981. 'kj': 'kua',
  1982. 'kk': 'kaz',
  1983. 'kl': 'kal',
  1984. 'km': 'khm',
  1985. 'kn': 'kan',
  1986. 'ko': 'kor',
  1987. 'kr': 'kau',
  1988. 'ks': 'kas',
  1989. 'ku': 'kur',
  1990. 'kv': 'kom',
  1991. 'kw': 'cor',
  1992. 'ky': 'kir',
  1993. 'la': 'lat',
  1994. 'lb': 'ltz',
  1995. 'lg': 'lug',
  1996. 'li': 'lim',
  1997. 'ln': 'lin',
  1998. 'lo': 'lao',
  1999. 'lt': 'lit',
  2000. 'lu': 'lub',
  2001. 'lv': 'lav',
  2002. 'mg': 'mlg',
  2003. 'mh': 'mah',
  2004. 'mi': 'mri',
  2005. 'mk': 'mkd',
  2006. 'ml': 'mal',
  2007. 'mn': 'mon',
  2008. 'mr': 'mar',
  2009. 'ms': 'msa',
  2010. 'mt': 'mlt',
  2011. 'my': 'mya',
  2012. 'na': 'nau',
  2013. 'nb': 'nob',
  2014. 'nd': 'nde',
  2015. 'ne': 'nep',
  2016. 'ng': 'ndo',
  2017. 'nl': 'nld',
  2018. 'nn': 'nno',
  2019. 'no': 'nor',
  2020. 'nr': 'nbl',
  2021. 'nv': 'nav',
  2022. 'ny': 'nya',
  2023. 'oc': 'oci',
  2024. 'oj': 'oji',
  2025. 'om': 'orm',
  2026. 'or': 'ori',
  2027. 'os': 'oss',
  2028. 'pa': 'pan',
  2029. 'pi': 'pli',
  2030. 'pl': 'pol',
  2031. 'ps': 'pus',
  2032. 'pt': 'por',
  2033. 'qu': 'que',
  2034. 'rm': 'roh',
  2035. 'rn': 'run',
  2036. 'ro': 'ron',
  2037. 'ru': 'rus',
  2038. 'rw': 'kin',
  2039. 'sa': 'san',
  2040. 'sc': 'srd',
  2041. 'sd': 'snd',
  2042. 'se': 'sme',
  2043. 'sg': 'sag',
  2044. 'si': 'sin',
  2045. 'sk': 'slk',
  2046. 'sl': 'slv',
  2047. 'sm': 'smo',
  2048. 'sn': 'sna',
  2049. 'so': 'som',
  2050. 'sq': 'sqi',
  2051. 'sr': 'srp',
  2052. 'ss': 'ssw',
  2053. 'st': 'sot',
  2054. 'su': 'sun',
  2055. 'sv': 'swe',
  2056. 'sw': 'swa',
  2057. 'ta': 'tam',
  2058. 'te': 'tel',
  2059. 'tg': 'tgk',
  2060. 'th': 'tha',
  2061. 'ti': 'tir',
  2062. 'tk': 'tuk',
  2063. 'tl': 'tgl',
  2064. 'tn': 'tsn',
  2065. 'to': 'ton',
  2066. 'tr': 'tur',
  2067. 'ts': 'tso',
  2068. 'tt': 'tat',
  2069. 'tw': 'twi',
  2070. 'ty': 'tah',
  2071. 'ug': 'uig',
  2072. 'uk': 'ukr',
  2073. 'ur': 'urd',
  2074. 'uz': 'uzb',
  2075. 've': 'ven',
  2076. 'vi': 'vie',
  2077. 'vo': 'vol',
  2078. 'wa': 'wln',
  2079. 'wo': 'wol',
  2080. 'xh': 'xho',
  2081. 'yi': 'yid',
  2082. 'yo': 'yor',
  2083. 'za': 'zha',
  2084. 'zh': 'zho',
  2085. 'zu': 'zul',
  2086. }
  2087. @classmethod
  2088. def short2long(cls, code):
  2089. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  2090. return cls._lang_map.get(code[:2])
  2091. @classmethod
  2092. def long2short(cls, code):
  2093. """Convert language code from ISO 639-2/T to ISO 639-1"""
  2094. for short_name, long_name in cls._lang_map.items():
  2095. if long_name == code:
  2096. return short_name
  2097. class ISO3166Utils(object):
  2098. # From http://data.okfn.org/data/core/country-list
  2099. _country_map = {
  2100. 'AF': 'Afghanistan',
  2101. 'AX': 'Åland Islands',
  2102. 'AL': 'Albania',
  2103. 'DZ': 'Algeria',
  2104. 'AS': 'American Samoa',
  2105. 'AD': 'Andorra',
  2106. 'AO': 'Angola',
  2107. 'AI': 'Anguilla',
  2108. 'AQ': 'Antarctica',
  2109. 'AG': 'Antigua and Barbuda',
  2110. 'AR': 'Argentina',
  2111. 'AM': 'Armenia',
  2112. 'AW': 'Aruba',
  2113. 'AU': 'Australia',
  2114. 'AT': 'Austria',
  2115. 'AZ': 'Azerbaijan',
  2116. 'BS': 'Bahamas',
  2117. 'BH': 'Bahrain',
  2118. 'BD': 'Bangladesh',
  2119. 'BB': 'Barbados',
  2120. 'BY': 'Belarus',
  2121. 'BE': 'Belgium',
  2122. 'BZ': 'Belize',
  2123. 'BJ': 'Benin',
  2124. 'BM': 'Bermuda',
  2125. 'BT': 'Bhutan',
  2126. 'BO': 'Bolivia, Plurinational State of',
  2127. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  2128. 'BA': 'Bosnia and Herzegovina',
  2129. 'BW': 'Botswana',
  2130. 'BV': 'Bouvet Island',
  2131. 'BR': 'Brazil',
  2132. 'IO': 'British Indian Ocean Territory',
  2133. 'BN': 'Brunei Darussalam',
  2134. 'BG': 'Bulgaria',
  2135. 'BF': 'Burkina Faso',
  2136. 'BI': 'Burundi',
  2137. 'KH': 'Cambodia',
  2138. 'CM': 'Cameroon',
  2139. 'CA': 'Canada',
  2140. 'CV': 'Cape Verde',
  2141. 'KY': 'Cayman Islands',
  2142. 'CF': 'Central African Republic',
  2143. 'TD': 'Chad',
  2144. 'CL': 'Chile',
  2145. 'CN': 'China',
  2146. 'CX': 'Christmas Island',
  2147. 'CC': 'Cocos (Keeling) Islands',
  2148. 'CO': 'Colombia',
  2149. 'KM': 'Comoros',
  2150. 'CG': 'Congo',
  2151. 'CD': 'Congo, the Democratic Republic of the',
  2152. 'CK': 'Cook Islands',
  2153. 'CR': 'Costa Rica',
  2154. 'CI': 'Côte d\'Ivoire',
  2155. 'HR': 'Croatia',
  2156. 'CU': 'Cuba',
  2157. 'CW': 'Curaçao',
  2158. 'CY': 'Cyprus',
  2159. 'CZ': 'Czech Republic',
  2160. 'DK': 'Denmark',
  2161. 'DJ': 'Djibouti',
  2162. 'DM': 'Dominica',
  2163. 'DO': 'Dominican Republic',
  2164. 'EC': 'Ecuador',
  2165. 'EG': 'Egypt',
  2166. 'SV': 'El Salvador',
  2167. 'GQ': 'Equatorial Guinea',
  2168. 'ER': 'Eritrea',
  2169. 'EE': 'Estonia',
  2170. 'ET': 'Ethiopia',
  2171. 'FK': 'Falkland Islands (Malvinas)',
  2172. 'FO': 'Faroe Islands',
  2173. 'FJ': 'Fiji',
  2174. 'FI': 'Finland',
  2175. 'FR': 'France',
  2176. 'GF': 'French Guiana',
  2177. 'PF': 'French Polynesia',
  2178. 'TF': 'French Southern Territories',
  2179. 'GA': 'Gabon',
  2180. 'GM': 'Gambia',
  2181. 'GE': 'Georgia',
  2182. 'DE': 'Germany',
  2183. 'GH': 'Ghana',
  2184. 'GI': 'Gibraltar',
  2185. 'GR': 'Greece',
  2186. 'GL': 'Greenland',
  2187. 'GD': 'Grenada',
  2188. 'GP': 'Guadeloupe',
  2189. 'GU': 'Guam',
  2190. 'GT': 'Guatemala',
  2191. 'GG': 'Guernsey',
  2192. 'GN': 'Guinea',
  2193. 'GW': 'Guinea-Bissau',
  2194. 'GY': 'Guyana',
  2195. 'HT': 'Haiti',
  2196. 'HM': 'Heard Island and McDonald Islands',
  2197. 'VA': 'Holy See (Vatican City State)',
  2198. 'HN': 'Honduras',
  2199. 'HK': 'Hong Kong',
  2200. 'HU': 'Hungary',
  2201. 'IS': 'Iceland',
  2202. 'IN': 'India',
  2203. 'ID': 'Indonesia',
  2204. 'IR': 'Iran, Islamic Republic of',
  2205. 'IQ': 'Iraq',
  2206. 'IE': 'Ireland',
  2207. 'IM': 'Isle of Man',
  2208. 'IL': 'Israel',
  2209. 'IT': 'Italy',
  2210. 'JM': 'Jamaica',
  2211. 'JP': 'Japan',
  2212. 'JE': 'Jersey',
  2213. 'JO': 'Jordan',
  2214. 'KZ': 'Kazakhstan',
  2215. 'KE': 'Kenya',
  2216. 'KI': 'Kiribati',
  2217. 'KP': 'Korea, Democratic People\'s Republic of',
  2218. 'KR': 'Korea, Republic of',
  2219. 'KW': 'Kuwait',
  2220. 'KG': 'Kyrgyzstan',
  2221. 'LA': 'Lao People\'s Democratic Republic',
  2222. 'LV': 'Latvia',
  2223. 'LB': 'Lebanon',
  2224. 'LS': 'Lesotho',
  2225. 'LR': 'Liberia',
  2226. 'LY': 'Libya',
  2227. 'LI': 'Liechtenstein',
  2228. 'LT': 'Lithuania',
  2229. 'LU': 'Luxembourg',
  2230. 'MO': 'Macao',
  2231. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  2232. 'MG': 'Madagascar',
  2233. 'MW': 'Malawi',
  2234. 'MY': 'Malaysia',
  2235. 'MV': 'Maldives',
  2236. 'ML': 'Mali',
  2237. 'MT': 'Malta',
  2238. 'MH': 'Marshall Islands',
  2239. 'MQ': 'Martinique',
  2240. 'MR': 'Mauritania',
  2241. 'MU': 'Mauritius',
  2242. 'YT': 'Mayotte',
  2243. 'MX': 'Mexico',
  2244. 'FM': 'Micronesia, Federated States of',
  2245. 'MD': 'Moldova, Republic of',
  2246. 'MC': 'Monaco',
  2247. 'MN': 'Mongolia',
  2248. 'ME': 'Montenegro',
  2249. 'MS': 'Montserrat',
  2250. 'MA': 'Morocco',
  2251. 'MZ': 'Mozambique',
  2252. 'MM': 'Myanmar',
  2253. 'NA': 'Namibia',
  2254. 'NR': 'Nauru',
  2255. 'NP': 'Nepal',
  2256. 'NL': 'Netherlands',
  2257. 'NC': 'New Caledonia',
  2258. 'NZ': 'New Zealand',
  2259. 'NI': 'Nicaragua',
  2260. 'NE': 'Niger',
  2261. 'NG': 'Nigeria',
  2262. 'NU': 'Niue',
  2263. 'NF': 'Norfolk Island',
  2264. 'MP': 'Northern Mariana Islands',
  2265. 'NO': 'Norway',
  2266. 'OM': 'Oman',
  2267. 'PK': 'Pakistan',
  2268. 'PW': 'Palau',
  2269. 'PS': 'Palestine, State of',
  2270. 'PA': 'Panama',
  2271. 'PG': 'Papua New Guinea',
  2272. 'PY': 'Paraguay',
  2273. 'PE': 'Peru',
  2274. 'PH': 'Philippines',
  2275. 'PN': 'Pitcairn',
  2276. 'PL': 'Poland',
  2277. 'PT': 'Portugal',
  2278. 'PR': 'Puerto Rico',
  2279. 'QA': 'Qatar',
  2280. 'RE': 'Réunion',
  2281. 'RO': 'Romania',
  2282. 'RU': 'Russian Federation',
  2283. 'RW': 'Rwanda',
  2284. 'BL': 'Saint Barthélemy',
  2285. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  2286. 'KN': 'Saint Kitts and Nevis',
  2287. 'LC': 'Saint Lucia',
  2288. 'MF': 'Saint Martin (French part)',
  2289. 'PM': 'Saint Pierre and Miquelon',
  2290. 'VC': 'Saint Vincent and the Grenadines',
  2291. 'WS': 'Samoa',
  2292. 'SM': 'San Marino',
  2293. 'ST': 'Sao Tome and Principe',
  2294. 'SA': 'Saudi Arabia',
  2295. 'SN': 'Senegal',
  2296. 'RS': 'Serbia',
  2297. 'SC': 'Seychelles',
  2298. 'SL': 'Sierra Leone',
  2299. 'SG': 'Singapore',
  2300. 'SX': 'Sint Maarten (Dutch part)',
  2301. 'SK': 'Slovakia',
  2302. 'SI': 'Slovenia',
  2303. 'SB': 'Solomon Islands',
  2304. 'SO': 'Somalia',
  2305. 'ZA': 'South Africa',
  2306. 'GS': 'South Georgia and the South Sandwich Islands',
  2307. 'SS': 'South Sudan',
  2308. 'ES': 'Spain',
  2309. 'LK': 'Sri Lanka',
  2310. 'SD': 'Sudan',
  2311. 'SR': 'Suriname',
  2312. 'SJ': 'Svalbard and Jan Mayen',
  2313. 'SZ': 'Swaziland',
  2314. 'SE': 'Sweden',
  2315. 'CH': 'Switzerland',
  2316. 'SY': 'Syrian Arab Republic',
  2317. 'TW': 'Taiwan, Province of China',
  2318. 'TJ': 'Tajikistan',
  2319. 'TZ': 'Tanzania, United Republic of',
  2320. 'TH': 'Thailand',
  2321. 'TL': 'Timor-Leste',
  2322. 'TG': 'Togo',
  2323. 'TK': 'Tokelau',
  2324. 'TO': 'Tonga',
  2325. 'TT': 'Trinidad and Tobago',
  2326. 'TN': 'Tunisia',
  2327. 'TR': 'Turkey',
  2328. 'TM': 'Turkmenistan',
  2329. 'TC': 'Turks and Caicos Islands',
  2330. 'TV': 'Tuvalu',
  2331. 'UG': 'Uganda',
  2332. 'UA': 'Ukraine',
  2333. 'AE': 'United Arab Emirates',
  2334. 'GB': 'United Kingdom',
  2335. 'US': 'United States',
  2336. 'UM': 'United States Minor Outlying Islands',
  2337. 'UY': 'Uruguay',
  2338. 'UZ': 'Uzbekistan',
  2339. 'VU': 'Vanuatu',
  2340. 'VE': 'Venezuela, Bolivarian Republic of',
  2341. 'VN': 'Viet Nam',
  2342. 'VG': 'Virgin Islands, British',
  2343. 'VI': 'Virgin Islands, U.S.',
  2344. 'WF': 'Wallis and Futuna',
  2345. 'EH': 'Western Sahara',
  2346. 'YE': 'Yemen',
  2347. 'ZM': 'Zambia',
  2348. 'ZW': 'Zimbabwe',
  2349. }
  2350. @classmethod
  2351. def short2full(cls, code):
  2352. """Convert an ISO 3166-2 country code to the corresponding full name"""
  2353. return cls._country_map.get(code.upper())
  2354. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  2355. def __init__(self, proxies=None):
  2356. # Set default handlers
  2357. for type in ('http', 'https'):
  2358. setattr(self, '%s_open' % type,
  2359. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  2360. meth(r, proxy, type))
  2361. return compat_urllib_request.ProxyHandler.__init__(self, proxies)
  2362. def proxy_open(self, req, proxy, type):
  2363. req_proxy = req.headers.get('Ytdl-request-proxy')
  2364. if req_proxy is not None:
  2365. proxy = req_proxy
  2366. del req.headers['Ytdl-request-proxy']
  2367. if proxy == '__noproxy__':
  2368. return None # No Proxy
  2369. if compat_urlparse.urlparse(proxy).scheme.lower() in ('socks', 'socks4', 'socks4a', 'socks5'):
  2370. req.add_header('Ytdl-socks-proxy', proxy)
  2371. # youtube-dl's http/https handlers do wrapping the socket with socks
  2372. return None
  2373. return compat_urllib_request.ProxyHandler.proxy_open(
  2374. self, req, proxy, type)
  2375. def ohdave_rsa_encrypt(data, exponent, modulus):
  2376. '''
  2377. Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
  2378. Input:
  2379. data: data to encrypt, bytes-like object
  2380. exponent, modulus: parameter e and N of RSA algorithm, both integer
  2381. Output: hex string of encrypted data
  2382. Limitation: supports one block encryption only
  2383. '''
  2384. payload = int(binascii.hexlify(data[::-1]), 16)
  2385. encrypted = pow(payload, exponent, modulus)
  2386. return '%x' % encrypted
  2387. def encode_base_n(num, n, table=None):
  2388. FULL_TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  2389. if not table:
  2390. table = FULL_TABLE[:n]
  2391. if n > len(table):
  2392. raise ValueError('base %d exceeds table length %d' % (n, len(table)))
  2393. if num == 0:
  2394. return table[0]
  2395. ret = ''
  2396. while num:
  2397. ret = table[num % n] + ret
  2398. num = num // n
  2399. return ret
  2400. def decode_packed_codes(code):
  2401. mobj = re.search(
  2402. r"}\('(.+)',(\d+),(\d+),'([^']+)'\.split\('\|'\)",
  2403. code)
  2404. obfucasted_code, base, count, symbols = mobj.groups()
  2405. base = int(base)
  2406. count = int(count)
  2407. symbols = symbols.split('|')
  2408. symbol_table = {}
  2409. while count:
  2410. count -= 1
  2411. base_n_count = encode_base_n(count, base)
  2412. symbol_table[base_n_count] = symbols[count] or base_n_count
  2413. return re.sub(
  2414. r'\b(\w+)\b', lambda mobj: symbol_table[mobj.group(0)],
  2415. obfucasted_code)
  2416. def parse_m3u8_attributes(attrib):
  2417. info = {}
  2418. for (key, val) in re.findall(r'(?P<key>[A-Z0-9-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)', attrib):
  2419. if val.startswith('"'):
  2420. val = val[1:-1]
  2421. info[key] = val
  2422. return info
  2423. def urshift(val, n):
  2424. return val >> n if val >= 0 else (val + 0x100000000) >> n