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.

3987 lines
122 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 email.header
  13. import errno
  14. import functools
  15. import gzip
  16. import io
  17. import itertools
  18. import json
  19. import locale
  20. import math
  21. import operator
  22. import os
  23. import platform
  24. import random
  25. import re
  26. import socket
  27. import ssl
  28. import subprocess
  29. import sys
  30. import tempfile
  31. import traceback
  32. import xml.etree.ElementTree
  33. import zlib
  34. from .compat import (
  35. compat_HTMLParseError,
  36. compat_HTMLParser,
  37. compat_basestring,
  38. compat_chr,
  39. compat_cookiejar,
  40. compat_ctypes_WINFUNCTYPE,
  41. compat_etree_fromstring,
  42. compat_expanduser,
  43. compat_html_entities,
  44. compat_html_entities_html5,
  45. compat_http_client,
  46. compat_kwargs,
  47. compat_os_name,
  48. compat_parse_qs,
  49. compat_shlex_quote,
  50. compat_str,
  51. compat_struct_pack,
  52. compat_struct_unpack,
  53. compat_urllib_error,
  54. compat_urllib_parse,
  55. compat_urllib_parse_urlencode,
  56. compat_urllib_parse_urlparse,
  57. compat_urllib_parse_unquote_plus,
  58. compat_urllib_request,
  59. compat_urlparse,
  60. compat_xpath,
  61. )
  62. from .socks import (
  63. ProxyType,
  64. sockssocket,
  65. )
  66. def register_socks_protocols():
  67. # "Register" SOCKS protocols
  68. # In Python < 2.6.5, urlsplit() suffers from bug https://bugs.python.org/issue7904
  69. # URLs with protocols not in urlparse.uses_netloc are not handled correctly
  70. for scheme in ('socks', 'socks4', 'socks4a', 'socks5'):
  71. if scheme not in compat_urlparse.uses_netloc:
  72. compat_urlparse.uses_netloc.append(scheme)
  73. # This is not clearly defined otherwise
  74. compiled_regex_type = type(re.compile(''))
  75. std_headers = {
  76. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:59.0) Gecko/20100101 Firefox/59.0',
  77. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  78. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  79. 'Accept-Encoding': 'gzip, deflate',
  80. 'Accept-Language': 'en-us,en;q=0.5',
  81. }
  82. USER_AGENTS = {
  83. 'Safari': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27',
  84. }
  85. NO_DEFAULT = object()
  86. ENGLISH_MONTH_NAMES = [
  87. 'January', 'February', 'March', 'April', 'May', 'June',
  88. 'July', 'August', 'September', 'October', 'November', 'December']
  89. MONTH_NAMES = {
  90. 'en': ENGLISH_MONTH_NAMES,
  91. 'fr': [
  92. 'janvier', 'février', 'mars', 'avril', 'mai', 'juin',
  93. 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
  94. }
  95. KNOWN_EXTENSIONS = (
  96. 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'aac',
  97. 'flv', 'f4v', 'f4a', 'f4b',
  98. 'webm', 'ogg', 'ogv', 'oga', 'ogx', 'spx', 'opus',
  99. 'mkv', 'mka', 'mk3d',
  100. 'avi', 'divx',
  101. 'mov',
  102. 'asf', 'wmv', 'wma',
  103. '3gp', '3g2',
  104. 'mp3',
  105. 'flac',
  106. 'ape',
  107. 'wav',
  108. 'f4f', 'f4m', 'm3u8', 'smil')
  109. # needed for sanitizing filenames in restricted mode
  110. ACCENT_CHARS = dict(zip('ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ',
  111. itertools.chain('AAAAAA', ['AE'], 'CEEEEIIIIDNOOOOOOO', ['OE'], 'UUUUUYP', ['ss'],
  112. 'aaaaaa', ['ae'], 'ceeeeiiiionooooooo', ['oe'], 'uuuuuypy')))
  113. DATE_FORMATS = (
  114. '%d %B %Y',
  115. '%d %b %Y',
  116. '%B %d %Y',
  117. '%B %dst %Y',
  118. '%B %dnd %Y',
  119. '%B %dth %Y',
  120. '%b %d %Y',
  121. '%b %dst %Y',
  122. '%b %dnd %Y',
  123. '%b %dth %Y',
  124. '%b %dst %Y %I:%M',
  125. '%b %dnd %Y %I:%M',
  126. '%b %dth %Y %I:%M',
  127. '%Y %m %d',
  128. '%Y-%m-%d',
  129. '%Y/%m/%d',
  130. '%Y/%m/%d %H:%M',
  131. '%Y/%m/%d %H:%M:%S',
  132. '%Y-%m-%d %H:%M',
  133. '%Y-%m-%d %H:%M:%S',
  134. '%Y-%m-%d %H:%M:%S.%f',
  135. '%d.%m.%Y %H:%M',
  136. '%d.%m.%Y %H.%M',
  137. '%Y-%m-%dT%H:%M:%SZ',
  138. '%Y-%m-%dT%H:%M:%S.%fZ',
  139. '%Y-%m-%dT%H:%M:%S.%f0Z',
  140. '%Y-%m-%dT%H:%M:%S',
  141. '%Y-%m-%dT%H:%M:%S.%f',
  142. '%Y-%m-%dT%H:%M',
  143. '%b %d %Y at %H:%M',
  144. '%b %d %Y at %H:%M:%S',
  145. '%B %d %Y at %H:%M',
  146. '%B %d %Y at %H:%M:%S',
  147. )
  148. DATE_FORMATS_DAY_FIRST = list(DATE_FORMATS)
  149. DATE_FORMATS_DAY_FIRST.extend([
  150. '%d-%m-%Y',
  151. '%d.%m.%Y',
  152. '%d.%m.%y',
  153. '%d/%m/%Y',
  154. '%d/%m/%y',
  155. '%d/%m/%Y %H:%M:%S',
  156. ])
  157. DATE_FORMATS_MONTH_FIRST = list(DATE_FORMATS)
  158. DATE_FORMATS_MONTH_FIRST.extend([
  159. '%m-%d-%Y',
  160. '%m.%d.%Y',
  161. '%m/%d/%Y',
  162. '%m/%d/%y',
  163. '%m/%d/%Y %H:%M:%S',
  164. ])
  165. PACKED_CODES_RE = r"}\('(.+)',(\d+),(\d+),'([^']+)'\.split\('\|'\)"
  166. JSON_LD_RE = r'(?is)<script[^>]+type=(["\'])application/ld\+json\1[^>]*>(?P<json_ld>.+?)</script>'
  167. def preferredencoding():
  168. """Get preferred encoding.
  169. Returns the best encoding scheme for the system, based on
  170. locale.getpreferredencoding() and some further tweaks.
  171. """
  172. try:
  173. pref = locale.getpreferredencoding()
  174. 'TEST'.encode(pref)
  175. except Exception:
  176. pref = 'UTF-8'
  177. return pref
  178. def write_json_file(obj, fn):
  179. """ Encode obj as JSON and write it to fn, atomically if possible """
  180. fn = encodeFilename(fn)
  181. if sys.version_info < (3, 0) and sys.platform != 'win32':
  182. encoding = get_filesystem_encoding()
  183. # os.path.basename returns a bytes object, but NamedTemporaryFile
  184. # will fail if the filename contains non ascii characters unless we
  185. # use a unicode object
  186. path_basename = lambda f: os.path.basename(fn).decode(encoding)
  187. # the same for os.path.dirname
  188. path_dirname = lambda f: os.path.dirname(fn).decode(encoding)
  189. else:
  190. path_basename = os.path.basename
  191. path_dirname = os.path.dirname
  192. args = {
  193. 'suffix': '.tmp',
  194. 'prefix': path_basename(fn) + '.',
  195. 'dir': path_dirname(fn),
  196. 'delete': False,
  197. }
  198. # In Python 2.x, json.dump expects a bytestream.
  199. # In Python 3.x, it writes to a character stream
  200. if sys.version_info < (3, 0):
  201. args['mode'] = 'wb'
  202. else:
  203. args.update({
  204. 'mode': 'w',
  205. 'encoding': 'utf-8',
  206. })
  207. tf = tempfile.NamedTemporaryFile(**compat_kwargs(args))
  208. try:
  209. with tf:
  210. json.dump(obj, tf)
  211. if sys.platform == 'win32':
  212. # Need to remove existing file on Windows, else os.rename raises
  213. # WindowsError or FileExistsError.
  214. try:
  215. os.unlink(fn)
  216. except OSError:
  217. pass
  218. os.rename(tf.name, fn)
  219. except Exception:
  220. try:
  221. os.remove(tf.name)
  222. except OSError:
  223. pass
  224. raise
  225. if sys.version_info >= (2, 7):
  226. def find_xpath_attr(node, xpath, key, val=None):
  227. """ Find the xpath xpath[@key=val] """
  228. assert re.match(r'^[a-zA-Z_-]+$', key)
  229. expr = xpath + ('[@%s]' % key if val is None else "[@%s='%s']" % (key, val))
  230. return node.find(expr)
  231. else:
  232. def find_xpath_attr(node, xpath, key, val=None):
  233. for f in node.findall(compat_xpath(xpath)):
  234. if key not in f.attrib:
  235. continue
  236. if val is None or f.attrib.get(key) == val:
  237. return f
  238. return None
  239. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  240. # the namespace parameter
  241. def xpath_with_ns(path, ns_map):
  242. components = [c.split(':') for c in path.split('/')]
  243. replaced = []
  244. for c in components:
  245. if len(c) == 1:
  246. replaced.append(c[0])
  247. else:
  248. ns, tag = c
  249. replaced.append('{%s}%s' % (ns_map[ns], tag))
  250. return '/'.join(replaced)
  251. def xpath_element(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  252. def _find_xpath(xpath):
  253. return node.find(compat_xpath(xpath))
  254. if isinstance(xpath, (str, compat_str)):
  255. n = _find_xpath(xpath)
  256. else:
  257. for xp in xpath:
  258. n = _find_xpath(xp)
  259. if n is not None:
  260. break
  261. if n is None:
  262. if default is not NO_DEFAULT:
  263. return default
  264. elif fatal:
  265. name = xpath if name is None else name
  266. raise ExtractorError('Could not find XML element %s' % name)
  267. else:
  268. return None
  269. return n
  270. def xpath_text(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  271. n = xpath_element(node, xpath, name, fatal=fatal, default=default)
  272. if n is None or n == default:
  273. return n
  274. if n.text is None:
  275. if default is not NO_DEFAULT:
  276. return default
  277. elif fatal:
  278. name = xpath if name is None else name
  279. raise ExtractorError('Could not find XML element\'s text %s' % name)
  280. else:
  281. return None
  282. return n.text
  283. def xpath_attr(node, xpath, key, name=None, fatal=False, default=NO_DEFAULT):
  284. n = find_xpath_attr(node, xpath, key)
  285. if n is None:
  286. if default is not NO_DEFAULT:
  287. return default
  288. elif fatal:
  289. name = '%s[@%s]' % (xpath, key) if name is None else name
  290. raise ExtractorError('Could not find XML attribute %s' % name)
  291. else:
  292. return None
  293. return n.attrib[key]
  294. def get_element_by_id(id, html):
  295. """Return the content of the tag with the specified ID in the passed HTML document"""
  296. return get_element_by_attribute('id', id, html)
  297. def get_element_by_class(class_name, html):
  298. """Return the content of the first tag with the specified class in the passed HTML document"""
  299. retval = get_elements_by_class(class_name, html)
  300. return retval[0] if retval else None
  301. def get_element_by_attribute(attribute, value, html, escape_value=True):
  302. retval = get_elements_by_attribute(attribute, value, html, escape_value)
  303. return retval[0] if retval else None
  304. def get_elements_by_class(class_name, html):
  305. """Return the content of all tags with the specified class in the passed HTML document as a list"""
  306. return get_elements_by_attribute(
  307. 'class', r'[^\'"]*\b%s\b[^\'"]*' % re.escape(class_name),
  308. html, escape_value=False)
  309. def get_elements_by_attribute(attribute, value, html, escape_value=True):
  310. """Return the content of the tag with the specified attribute in the passed HTML document"""
  311. value = re.escape(value) if escape_value else value
  312. retlist = []
  313. for m in re.finditer(r'''(?xs)
  314. <([a-zA-Z0-9:._-]+)
  315. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
  316. \s+%s=['"]?%s['"]?
  317. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
  318. \s*>
  319. (?P<content>.*?)
  320. </\1>
  321. ''' % (re.escape(attribute), value), html):
  322. res = m.group('content')
  323. if res.startswith('"') or res.startswith("'"):
  324. res = res[1:-1]
  325. retlist.append(unescapeHTML(res))
  326. return retlist
  327. class HTMLAttributeParser(compat_HTMLParser):
  328. """Trivial HTML parser to gather the attributes for a single element"""
  329. def __init__(self):
  330. self.attrs = {}
  331. compat_HTMLParser.__init__(self)
  332. def handle_starttag(self, tag, attrs):
  333. self.attrs = dict(attrs)
  334. def extract_attributes(html_element):
  335. """Given a string for an HTML element such as
  336. <el
  337. a="foo" B="bar" c="&98;az" d=boz
  338. empty= noval entity="&amp;"
  339. sq='"' dq="'"
  340. >
  341. Decode and return a dictionary of attributes.
  342. {
  343. 'a': 'foo', 'b': 'bar', c: 'baz', d: 'boz',
  344. 'empty': '', 'noval': None, 'entity': '&',
  345. 'sq': '"', 'dq': '\''
  346. }.
  347. NB HTMLParser is stricter in Python 2.6 & 3.2 than in later versions,
  348. but the cases in the unit test will work for all of 2.6, 2.7, 3.2-3.5.
  349. """
  350. parser = HTMLAttributeParser()
  351. try:
  352. parser.feed(html_element)
  353. parser.close()
  354. # Older Python may throw HTMLParseError in case of malformed HTML
  355. except compat_HTMLParseError:
  356. pass
  357. return parser.attrs
  358. def clean_html(html):
  359. """Clean an HTML snippet into a readable string"""
  360. if html is None: # Convenience for sanitizing descriptions etc.
  361. return html
  362. # Newline vs <br />
  363. html = html.replace('\n', ' ')
  364. html = re.sub(r'(?u)\s*<\s*br\s*/?\s*>\s*', '\n', html)
  365. html = re.sub(r'(?u)<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  366. # Strip html tags
  367. html = re.sub('<.*?>', '', html)
  368. # Replace html entities
  369. html = unescapeHTML(html)
  370. return html.strip()
  371. def sanitize_open(filename, open_mode):
  372. """Try to open the given filename, and slightly tweak it if this fails.
  373. Attempts to open the given filename. If this fails, it tries to change
  374. the filename slightly, step by step, until it's either able to open it
  375. or it fails and raises a final exception, like the standard open()
  376. function.
  377. It returns the tuple (stream, definitive_file_name).
  378. """
  379. try:
  380. if filename == '-':
  381. if sys.platform == 'win32':
  382. import msvcrt
  383. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  384. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  385. stream = open(encodeFilename(filename), open_mode)
  386. return (stream, filename)
  387. except (IOError, OSError) as err:
  388. if err.errno in (errno.EACCES,):
  389. raise
  390. # In case of error, try to remove win32 forbidden chars
  391. alt_filename = sanitize_path(filename)
  392. if alt_filename == filename:
  393. raise
  394. else:
  395. # An exception here should be caught in the caller
  396. stream = open(encodeFilename(alt_filename), open_mode)
  397. return (stream, alt_filename)
  398. def timeconvert(timestr):
  399. """Convert RFC 2822 defined time string into system timestamp"""
  400. timestamp = None
  401. timetuple = email.utils.parsedate_tz(timestr)
  402. if timetuple is not None:
  403. timestamp = email.utils.mktime_tz(timetuple)
  404. return timestamp
  405. def sanitize_filename(s, restricted=False, is_id=False):
  406. """Sanitizes a string so it could be used as part of a filename.
  407. If restricted is set, use a stricter subset of allowed characters.
  408. Set is_id if this is not an arbitrary string, but an ID that should be kept
  409. if possible.
  410. """
  411. def replace_insane(char):
  412. if restricted and char in ACCENT_CHARS:
  413. return ACCENT_CHARS[char]
  414. if char == '?' or ord(char) < 32 or ord(char) == 127:
  415. return ''
  416. elif char == '"':
  417. return '' if restricted else '\''
  418. elif char == ':':
  419. return '_-' if restricted else ' -'
  420. elif char in '\\/|*<>':
  421. return '_'
  422. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  423. return '_'
  424. if restricted and ord(char) > 127:
  425. return '_'
  426. return char
  427. # Handle timestamps
  428. s = re.sub(r'[0-9]+(?::[0-9]+)+', lambda m: m.group(0).replace(':', '_'), s)
  429. result = ''.join(map(replace_insane, s))
  430. if not is_id:
  431. while '__' in result:
  432. result = result.replace('__', '_')
  433. result = result.strip('_')
  434. # Common case of "Foreign band name - English song title"
  435. if restricted and result.startswith('-_'):
  436. result = result[2:]
  437. if result.startswith('-'):
  438. result = '_' + result[len('-'):]
  439. result = result.lstrip('.')
  440. if not result:
  441. result = '_'
  442. return result
  443. def sanitize_path(s):
  444. """Sanitizes and normalizes path on Windows"""
  445. if sys.platform != 'win32':
  446. return s
  447. drive_or_unc, _ = os.path.splitdrive(s)
  448. if sys.version_info < (2, 7) and not drive_or_unc:
  449. drive_or_unc, _ = os.path.splitunc(s)
  450. norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
  451. if drive_or_unc:
  452. norm_path.pop(0)
  453. sanitized_path = [
  454. path_part if path_part in ['.', '..'] else re.sub(r'(?:[/<>:"\|\\?\*]|[\s.]$)', '#', path_part)
  455. for path_part in norm_path]
  456. if drive_or_unc:
  457. sanitized_path.insert(0, drive_or_unc + os.path.sep)
  458. return os.path.join(*sanitized_path)
  459. def sanitize_url(url):
  460. # Prepend protocol-less URLs with `http:` scheme in order to mitigate
  461. # the number of unwanted failures due to missing protocol
  462. if url.startswith('//'):
  463. return 'http:%s' % url
  464. # Fix some common typos seen so far
  465. COMMON_TYPOS = (
  466. # https://github.com/rg3/youtube-dl/issues/15649
  467. (r'^httpss://', r'https://'),
  468. # https://bx1.be/lives/direct-tv/
  469. (r'^rmtp([es]?)://', r'rtmp\1://'),
  470. )
  471. for mistake, fixup in COMMON_TYPOS:
  472. if re.match(mistake, url):
  473. return re.sub(mistake, fixup, url)
  474. return url
  475. def sanitized_Request(url, *args, **kwargs):
  476. return compat_urllib_request.Request(sanitize_url(url), *args, **kwargs)
  477. def expand_path(s):
  478. """Expand shell variables and ~"""
  479. return os.path.expandvars(compat_expanduser(s))
  480. def orderedSet(iterable):
  481. """ Remove all duplicates from the input iterable """
  482. res = []
  483. for el in iterable:
  484. if el not in res:
  485. res.append(el)
  486. return res
  487. def _htmlentity_transform(entity_with_semicolon):
  488. """Transforms an HTML entity to a character."""
  489. entity = entity_with_semicolon[:-1]
  490. # Known non-numeric HTML entity
  491. if entity in compat_html_entities.name2codepoint:
  492. return compat_chr(compat_html_entities.name2codepoint[entity])
  493. # TODO: HTML5 allows entities without a semicolon. For example,
  494. # '&Eacuteric' should be decoded as 'Éric'.
  495. if entity_with_semicolon in compat_html_entities_html5:
  496. return compat_html_entities_html5[entity_with_semicolon]
  497. mobj = re.match(r'#(x[0-9a-fA-F]+|[0-9]+)', entity)
  498. if mobj is not None:
  499. numstr = mobj.group(1)
  500. if numstr.startswith('x'):
  501. base = 16
  502. numstr = '0%s' % numstr
  503. else:
  504. base = 10
  505. # See https://github.com/rg3/youtube-dl/issues/7518
  506. try:
  507. return compat_chr(int(numstr, base))
  508. except ValueError:
  509. pass
  510. # Unknown entity in name, return its literal representation
  511. return '&%s;' % entity
  512. def unescapeHTML(s):
  513. if s is None:
  514. return None
  515. assert type(s) == compat_str
  516. return re.sub(
  517. r'&([^&;]+;)', lambda m: _htmlentity_transform(m.group(1)), s)
  518. def get_subprocess_encoding():
  519. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  520. # For subprocess calls, encode with locale encoding
  521. # Refer to http://stackoverflow.com/a/9951851/35070
  522. encoding = preferredencoding()
  523. else:
  524. encoding = sys.getfilesystemencoding()
  525. if encoding is None:
  526. encoding = 'utf-8'
  527. return encoding
  528. def encodeFilename(s, for_subprocess=False):
  529. """
  530. @param s The name of the file
  531. """
  532. assert type(s) == compat_str
  533. # Python 3 has a Unicode API
  534. if sys.version_info >= (3, 0):
  535. return s
  536. # Pass '' directly to use Unicode APIs on Windows 2000 and up
  537. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  538. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  539. if not for_subprocess and sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  540. return s
  541. # Jython assumes filenames are Unicode strings though reported as Python 2.x compatible
  542. if sys.platform.startswith('java'):
  543. return s
  544. return s.encode(get_subprocess_encoding(), 'ignore')
  545. def decodeFilename(b, for_subprocess=False):
  546. if sys.version_info >= (3, 0):
  547. return b
  548. if not isinstance(b, bytes):
  549. return b
  550. return b.decode(get_subprocess_encoding(), 'ignore')
  551. def encodeArgument(s):
  552. if not isinstance(s, compat_str):
  553. # Legacy code that uses byte strings
  554. # Uncomment the following line after fixing all post processors
  555. # assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
  556. s = s.decode('ascii')
  557. return encodeFilename(s, True)
  558. def decodeArgument(b):
  559. return decodeFilename(b, True)
  560. def decodeOption(optval):
  561. if optval is None:
  562. return optval
  563. if isinstance(optval, bytes):
  564. optval = optval.decode(preferredencoding())
  565. assert isinstance(optval, compat_str)
  566. return optval
  567. def formatSeconds(secs):
  568. if secs > 3600:
  569. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  570. elif secs > 60:
  571. return '%d:%02d' % (secs // 60, secs % 60)
  572. else:
  573. return '%d' % secs
  574. def make_HTTPS_handler(params, **kwargs):
  575. opts_no_check_certificate = params.get('nocheckcertificate', False)
  576. if hasattr(ssl, 'create_default_context'): # Python >= 3.4 or 2.7.9
  577. context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  578. if opts_no_check_certificate:
  579. context.check_hostname = False
  580. context.verify_mode = ssl.CERT_NONE
  581. try:
  582. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  583. except TypeError:
  584. # Python 2.7.8
  585. # (create_default_context present but HTTPSHandler has no context=)
  586. pass
  587. if sys.version_info < (3, 2):
  588. return YoutubeDLHTTPSHandler(params, **kwargs)
  589. else: # Python < 3.4
  590. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  591. context.verify_mode = (ssl.CERT_NONE
  592. if opts_no_check_certificate
  593. else ssl.CERT_REQUIRED)
  594. context.set_default_verify_paths()
  595. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  596. def bug_reports_message():
  597. if ytdl_is_updateable():
  598. update_cmd = 'type youtube-dl -U to update'
  599. else:
  600. update_cmd = 'see https://yt-dl.org/update on how to update'
  601. msg = '; please report this issue on https://yt-dl.org/bug .'
  602. msg += ' Make sure you are using the latest version; %s.' % update_cmd
  603. msg += ' Be sure to call youtube-dl with the --verbose flag and include its complete output.'
  604. return msg
  605. class YoutubeDLError(Exception):
  606. """Base exception for YoutubeDL errors."""
  607. pass
  608. class ExtractorError(YoutubeDLError):
  609. """Error during info extraction."""
  610. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  611. """ tb, if given, is the original traceback (so that it can be printed out).
  612. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  613. """
  614. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  615. expected = True
  616. if video_id is not None:
  617. msg = video_id + ': ' + msg
  618. if cause:
  619. msg += ' (caused by %r)' % cause
  620. if not expected:
  621. msg += bug_reports_message()
  622. super(ExtractorError, self).__init__(msg)
  623. self.traceback = tb
  624. self.exc_info = sys.exc_info() # preserve original exception
  625. self.cause = cause
  626. self.video_id = video_id
  627. def format_traceback(self):
  628. if self.traceback is None:
  629. return None
  630. return ''.join(traceback.format_tb(self.traceback))
  631. class UnsupportedError(ExtractorError):
  632. def __init__(self, url):
  633. super(UnsupportedError, self).__init__(
  634. 'Unsupported URL: %s' % url, expected=True)
  635. self.url = url
  636. class RegexNotFoundError(ExtractorError):
  637. """Error when a regex didn't match"""
  638. pass
  639. class GeoRestrictedError(ExtractorError):
  640. """Geographic restriction Error exception.
  641. This exception may be thrown when a video is not available from your
  642. geographic location due to geographic restrictions imposed by a website.
  643. """
  644. def __init__(self, msg, countries=None):
  645. super(GeoRestrictedError, self).__init__(msg, expected=True)
  646. self.msg = msg
  647. self.countries = countries
  648. class DownloadError(YoutubeDLError):
  649. """Download Error exception.
  650. This exception may be thrown by FileDownloader objects if they are not
  651. configured to continue on errors. They will contain the appropriate
  652. error message.
  653. """
  654. def __init__(self, msg, exc_info=None):
  655. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  656. super(DownloadError, self).__init__(msg)
  657. self.exc_info = exc_info
  658. class SameFileError(YoutubeDLError):
  659. """Same File exception.
  660. This exception will be thrown by FileDownloader objects if they detect
  661. multiple files would have to be downloaded to the same file on disk.
  662. """
  663. pass
  664. class PostProcessingError(YoutubeDLError):
  665. """Post Processing exception.
  666. This exception may be raised by PostProcessor's .run() method to
  667. indicate an error in the postprocessing task.
  668. """
  669. def __init__(self, msg):
  670. super(PostProcessingError, self).__init__(msg)
  671. self.msg = msg
  672. class MaxDownloadsReached(YoutubeDLError):
  673. """ --max-downloads limit has been reached. """
  674. pass
  675. class UnavailableVideoError(YoutubeDLError):
  676. """Unavailable Format exception.
  677. This exception will be thrown when a video is requested
  678. in a format that is not available for that video.
  679. """
  680. pass
  681. class ContentTooShortError(YoutubeDLError):
  682. """Content Too Short exception.
  683. This exception may be raised by FileDownloader objects when a file they
  684. download is too small for what the server announced first, indicating
  685. the connection was probably interrupted.
  686. """
  687. def __init__(self, downloaded, expected):
  688. super(ContentTooShortError, self).__init__(
  689. 'Downloaded {0} bytes, expected {1} bytes'.format(downloaded, expected)
  690. )
  691. # Both in bytes
  692. self.downloaded = downloaded
  693. self.expected = expected
  694. class XAttrMetadataError(YoutubeDLError):
  695. def __init__(self, code=None, msg='Unknown error'):
  696. super(XAttrMetadataError, self).__init__(msg)
  697. self.code = code
  698. self.msg = msg
  699. # Parsing code and msg
  700. if (self.code in (errno.ENOSPC, errno.EDQUOT) or
  701. 'No space left' in self.msg or 'Disk quota excedded' in self.msg):
  702. self.reason = 'NO_SPACE'
  703. elif self.code == errno.E2BIG or 'Argument list too long' in self.msg:
  704. self.reason = 'VALUE_TOO_LONG'
  705. else:
  706. self.reason = 'NOT_SUPPORTED'
  707. class XAttrUnavailableError(YoutubeDLError):
  708. pass
  709. def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
  710. # Working around python 2 bug (see http://bugs.python.org/issue17849) by limiting
  711. # expected HTTP responses to meet HTTP/1.0 or later (see also
  712. # https://github.com/rg3/youtube-dl/issues/6727)
  713. if sys.version_info < (3, 0):
  714. kwargs['strict'] = True
  715. hc = http_class(*args, **compat_kwargs(kwargs))
  716. source_address = ydl_handler._params.get('source_address')
  717. if source_address is not None:
  718. # This is to workaround _create_connection() from socket where it will try all
  719. # address data from getaddrinfo() including IPv6. This filters the result from
  720. # getaddrinfo() based on the source_address value.
  721. # This is based on the cpython socket.create_connection() function.
  722. # https://github.com/python/cpython/blob/master/Lib/socket.py#L691
  723. def _create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None):
  724. host, port = address
  725. err = None
  726. addrs = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
  727. af = socket.AF_INET if '.' in source_address[0] else socket.AF_INET6
  728. ip_addrs = [addr for addr in addrs if addr[0] == af]
  729. if addrs and not ip_addrs:
  730. ip_version = 'v4' if af == socket.AF_INET else 'v6'
  731. raise socket.error(
  732. "No remote IP%s addresses available for connect, can't use '%s' as source address"
  733. % (ip_version, source_address[0]))
  734. for res in ip_addrs:
  735. af, socktype, proto, canonname, sa = res
  736. sock = None
  737. try:
  738. sock = socket.socket(af, socktype, proto)
  739. if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
  740. sock.settimeout(timeout)
  741. sock.bind(source_address)
  742. sock.connect(sa)
  743. err = None # Explicitly break reference cycle
  744. return sock
  745. except socket.error as _:
  746. err = _
  747. if sock is not None:
  748. sock.close()
  749. if err is not None:
  750. raise err
  751. else:
  752. raise socket.error('getaddrinfo returns an empty list')
  753. if hasattr(hc, '_create_connection'):
  754. hc._create_connection = _create_connection
  755. sa = (source_address, 0)
  756. if hasattr(hc, 'source_address'): # Python 2.7+
  757. hc.source_address = sa
  758. else: # Python 2.6
  759. def _hc_connect(self, *args, **kwargs):
  760. sock = _create_connection(
  761. (self.host, self.port), self.timeout, sa)
  762. if is_https:
  763. self.sock = ssl.wrap_socket(
  764. sock, self.key_file, self.cert_file,
  765. ssl_version=ssl.PROTOCOL_TLSv1)
  766. else:
  767. self.sock = sock
  768. hc.connect = functools.partial(_hc_connect, hc)
  769. return hc
  770. def handle_youtubedl_headers(headers):
  771. filtered_headers = headers
  772. if 'Youtubedl-no-compression' in filtered_headers:
  773. filtered_headers = dict((k, v) for k, v in filtered_headers.items() if k.lower() != 'accept-encoding')
  774. del filtered_headers['Youtubedl-no-compression']
  775. return filtered_headers
  776. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  777. """Handler for HTTP requests and responses.
  778. This class, when installed with an OpenerDirector, automatically adds
  779. the standard headers to every HTTP request and handles gzipped and
  780. deflated responses from web servers. If compression is to be avoided in
  781. a particular request, the original request in the program code only has
  782. to include the HTTP header "Youtubedl-no-compression", which will be
  783. removed before making the real request.
  784. Part of this code was copied from:
  785. http://techknack.net/python-urllib2-handlers/
  786. Andrew Rowls, the author of that code, agreed to release it to the
  787. public domain.
  788. """
  789. def __init__(self, params, *args, **kwargs):
  790. compat_urllib_request.HTTPHandler.__init__(self, *args, **kwargs)
  791. self._params = params
  792. def http_open(self, req):
  793. conn_class = compat_http_client.HTTPConnection
  794. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  795. if socks_proxy:
  796. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  797. del req.headers['Ytdl-socks-proxy']
  798. return self.do_open(functools.partial(
  799. _create_http_connection, self, conn_class, False),
  800. req)
  801. @staticmethod
  802. def deflate(data):
  803. try:
  804. return zlib.decompress(data, -zlib.MAX_WBITS)
  805. except zlib.error:
  806. return zlib.decompress(data)
  807. def http_request(self, req):
  808. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  809. # always respected by websites, some tend to give out URLs with non percent-encoded
  810. # non-ASCII characters (see telemb.py, ard.py [#3412])
  811. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  812. # To work around aforementioned issue we will replace request's original URL with
  813. # percent-encoded one
  814. # Since redirects are also affected (e.g. http://www.southpark.de/alle-episoden/s18e09)
  815. # the code of this workaround has been moved here from YoutubeDL.urlopen()
  816. url = req.get_full_url()
  817. url_escaped = escape_url(url)
  818. # Substitute URL if any change after escaping
  819. if url != url_escaped:
  820. req = update_Request(req, url=url_escaped)
  821. for h, v in std_headers.items():
  822. # Capitalize is needed because of Python bug 2275: http://bugs.python.org/issue2275
  823. # The dict keys are capitalized because of this bug by urllib
  824. if h.capitalize() not in req.headers:
  825. req.add_header(h, v)
  826. req.headers = handle_youtubedl_headers(req.headers)
  827. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  828. # Python 2.6 is brain-dead when it comes to fragments
  829. req._Request__original = req._Request__original.partition('#')[0]
  830. req._Request__r_type = req._Request__r_type.partition('#')[0]
  831. return req
  832. def http_response(self, req, resp):
  833. old_resp = resp
  834. # gzip
  835. if resp.headers.get('Content-encoding', '') == 'gzip':
  836. content = resp.read()
  837. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  838. try:
  839. uncompressed = io.BytesIO(gz.read())
  840. except IOError as original_ioerror:
  841. # There may be junk add the end of the file
  842. # See http://stackoverflow.com/q/4928560/35070 for details
  843. for i in range(1, 1024):
  844. try:
  845. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  846. uncompressed = io.BytesIO(gz.read())
  847. except IOError:
  848. continue
  849. break
  850. else:
  851. raise original_ioerror
  852. resp = compat_urllib_request.addinfourl(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  853. resp.msg = old_resp.msg
  854. del resp.headers['Content-encoding']
  855. # deflate
  856. if resp.headers.get('Content-encoding', '') == 'deflate':
  857. gz = io.BytesIO(self.deflate(resp.read()))
  858. resp = compat_urllib_request.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code)
  859. resp.msg = old_resp.msg
  860. del resp.headers['Content-encoding']
  861. # Percent-encode redirect URL of Location HTTP header to satisfy RFC 3986 (see
  862. # https://github.com/rg3/youtube-dl/issues/6457).
  863. if 300 <= resp.code < 400:
  864. location = resp.headers.get('Location')
  865. if location:
  866. # As of RFC 2616 default charset is iso-8859-1 that is respected by python 3
  867. if sys.version_info >= (3, 0):
  868. location = location.encode('iso-8859-1').decode('utf-8')
  869. else:
  870. location = location.decode('utf-8')
  871. location_escaped = escape_url(location)
  872. if location != location_escaped:
  873. del resp.headers['Location']
  874. if sys.version_info < (3, 0):
  875. location_escaped = location_escaped.encode('utf-8')
  876. resp.headers['Location'] = location_escaped
  877. return resp
  878. https_request = http_request
  879. https_response = http_response
  880. def make_socks_conn_class(base_class, socks_proxy):
  881. assert issubclass(base_class, (
  882. compat_http_client.HTTPConnection, compat_http_client.HTTPSConnection))
  883. url_components = compat_urlparse.urlparse(socks_proxy)
  884. if url_components.scheme.lower() == 'socks5':
  885. socks_type = ProxyType.SOCKS5
  886. elif url_components.scheme.lower() in ('socks', 'socks4'):
  887. socks_type = ProxyType.SOCKS4
  888. elif url_components.scheme.lower() == 'socks4a':
  889. socks_type = ProxyType.SOCKS4A
  890. def unquote_if_non_empty(s):
  891. if not s:
  892. return s
  893. return compat_urllib_parse_unquote_plus(s)
  894. proxy_args = (
  895. socks_type,
  896. url_components.hostname, url_components.port or 1080,
  897. True, # Remote DNS
  898. unquote_if_non_empty(url_components.username),
  899. unquote_if_non_empty(url_components.password),
  900. )
  901. class SocksConnection(base_class):
  902. def connect(self):
  903. self.sock = sockssocket()
  904. self.sock.setproxy(*proxy_args)
  905. if type(self.timeout) in (int, float):
  906. self.sock.settimeout(self.timeout)
  907. self.sock.connect((self.host, self.port))
  908. if isinstance(self, compat_http_client.HTTPSConnection):
  909. if hasattr(self, '_context'): # Python > 2.6
  910. self.sock = self._context.wrap_socket(
  911. self.sock, server_hostname=self.host)
  912. else:
  913. self.sock = ssl.wrap_socket(self.sock)
  914. return SocksConnection
  915. class YoutubeDLHTTPSHandler(compat_urllib_request.HTTPSHandler):
  916. def __init__(self, params, https_conn_class=None, *args, **kwargs):
  917. compat_urllib_request.HTTPSHandler.__init__(self, *args, **kwargs)
  918. self._https_conn_class = https_conn_class or compat_http_client.HTTPSConnection
  919. self._params = params
  920. def https_open(self, req):
  921. kwargs = {}
  922. conn_class = self._https_conn_class
  923. if hasattr(self, '_context'): # python > 2.6
  924. kwargs['context'] = self._context
  925. if hasattr(self, '_check_hostname'): # python 3.x
  926. kwargs['check_hostname'] = self._check_hostname
  927. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  928. if socks_proxy:
  929. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  930. del req.headers['Ytdl-socks-proxy']
  931. return self.do_open(functools.partial(
  932. _create_http_connection, self, conn_class, True),
  933. req, **kwargs)
  934. class YoutubeDLCookieJar(compat_cookiejar.MozillaCookieJar):
  935. def save(self, filename=None, ignore_discard=False, ignore_expires=False):
  936. # Store session cookies with `expires` set to 0 instead of an empty
  937. # string
  938. for cookie in self:
  939. if cookie.expires is None:
  940. cookie.expires = 0
  941. compat_cookiejar.MozillaCookieJar.save(self, filename, ignore_discard, ignore_expires)
  942. def load(self, filename=None, ignore_discard=False, ignore_expires=False):
  943. compat_cookiejar.MozillaCookieJar.load(self, filename, ignore_discard, ignore_expires)
  944. # Session cookies are denoted by either `expires` field set to
  945. # an empty string or 0. MozillaCookieJar only recognizes the former
  946. # (see [1]). So we need force the latter to be recognized as session
  947. # cookies on our own.
  948. # Session cookies may be important for cookies-based authentication,
  949. # e.g. usually, when user does not check 'Remember me' check box while
  950. # logging in on a site, some important cookies are stored as session
  951. # cookies so that not recognizing them will result in failed login.
  952. # 1. https://bugs.python.org/issue17164
  953. for cookie in self:
  954. # Treat `expires=0` cookies as session cookies
  955. if cookie.expires == 0:
  956. cookie.expires = None
  957. cookie.discard = True
  958. class YoutubeDLCookieProcessor(compat_urllib_request.HTTPCookieProcessor):
  959. def __init__(self, cookiejar=None):
  960. compat_urllib_request.HTTPCookieProcessor.__init__(self, cookiejar)
  961. def http_response(self, request, response):
  962. # Python 2 will choke on next HTTP request in row if there are non-ASCII
  963. # characters in Set-Cookie HTTP header of last response (see
  964. # https://github.com/rg3/youtube-dl/issues/6769).
  965. # In order to at least prevent crashing we will percent encode Set-Cookie
  966. # header before HTTPCookieProcessor starts processing it.
  967. # if sys.version_info < (3, 0) and response.headers:
  968. # for set_cookie_header in ('Set-Cookie', 'Set-Cookie2'):
  969. # set_cookie = response.headers.get(set_cookie_header)
  970. # if set_cookie:
  971. # set_cookie_escaped = compat_urllib_parse.quote(set_cookie, b"%/;:@&=+$,!~*'()?#[] ")
  972. # if set_cookie != set_cookie_escaped:
  973. # del response.headers[set_cookie_header]
  974. # response.headers[set_cookie_header] = set_cookie_escaped
  975. return compat_urllib_request.HTTPCookieProcessor.http_response(self, request, response)
  976. https_request = compat_urllib_request.HTTPCookieProcessor.http_request
  977. https_response = http_response
  978. def extract_timezone(date_str):
  979. m = re.search(
  980. r'^.{8,}?(?P<tz>Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  981. date_str)
  982. if not m:
  983. timezone = datetime.timedelta()
  984. else:
  985. date_str = date_str[:-len(m.group('tz'))]
  986. if not m.group('sign'):
  987. timezone = datetime.timedelta()
  988. else:
  989. sign = 1 if m.group('sign') == '+' else -1
  990. timezone = datetime.timedelta(
  991. hours=sign * int(m.group('hours')),
  992. minutes=sign * int(m.group('minutes')))
  993. return timezone, date_str
  994. def parse_iso8601(date_str, delimiter='T', timezone=None):
  995. """ Return a UNIX timestamp from the given date """
  996. if date_str is None:
  997. return None
  998. date_str = re.sub(r'\.[0-9]+', '', date_str)
  999. if timezone is None:
  1000. timezone, date_str = extract_timezone(date_str)
  1001. try:
  1002. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  1003. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  1004. return calendar.timegm(dt.timetuple())
  1005. except ValueError:
  1006. pass
  1007. def date_formats(day_first=True):
  1008. return DATE_FORMATS_DAY_FIRST if day_first else DATE_FORMATS_MONTH_FIRST
  1009. def unified_strdate(date_str, day_first=True):
  1010. """Return a string with the date in the format YYYYMMDD"""
  1011. if date_str is None:
  1012. return None
  1013. upload_date = None
  1014. # Replace commas
  1015. date_str = date_str.replace(',', ' ')
  1016. # Remove AM/PM + timezone
  1017. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  1018. _, date_str = extract_timezone(date_str)
  1019. for expression in date_formats(day_first):
  1020. try:
  1021. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  1022. except ValueError:
  1023. pass
  1024. if upload_date is None:
  1025. timetuple = email.utils.parsedate_tz(date_str)
  1026. if timetuple:
  1027. try:
  1028. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  1029. except ValueError:
  1030. pass
  1031. if upload_date is not None:
  1032. return compat_str(upload_date)
  1033. def unified_timestamp(date_str, day_first=True):
  1034. if date_str is None:
  1035. return None
  1036. date_str = re.sub(r'[,|]', '', date_str)
  1037. pm_delta = 12 if re.search(r'(?i)PM', date_str) else 0
  1038. timezone, date_str = extract_timezone(date_str)
  1039. # Remove AM/PM + timezone
  1040. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  1041. # Remove unrecognized timezones from ISO 8601 alike timestamps
  1042. m = re.search(r'\d{1,2}:\d{1,2}(?:\.\d+)?(?P<tz>\s*[A-Z]+)$', date_str)
  1043. if m:
  1044. date_str = date_str[:-len(m.group('tz'))]
  1045. # Python only supports microseconds, so remove nanoseconds
  1046. m = re.search(r'^([0-9]{4,}-[0-9]{1,2}-[0-9]{1,2}T[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}\.[0-9]{6})[0-9]+$', date_str)
  1047. if m:
  1048. date_str = m.group(1)
  1049. for expression in date_formats(day_first):
  1050. try:
  1051. dt = datetime.datetime.strptime(date_str, expression) - timezone + datetime.timedelta(hours=pm_delta)
  1052. return calendar.timegm(dt.timetuple())
  1053. except ValueError:
  1054. pass
  1055. timetuple = email.utils.parsedate_tz(date_str)
  1056. if timetuple:
  1057. return calendar.timegm(timetuple) + pm_delta * 3600
  1058. def determine_ext(url, default_ext='unknown_video'):
  1059. if url is None or '.' not in url:
  1060. return default_ext
  1061. guess = url.partition('?')[0].rpartition('.')[2]
  1062. if re.match(r'^[A-Za-z0-9]+$', guess):
  1063. return guess
  1064. # Try extract ext from URLs like http://example.com/foo/bar.mp4/?download
  1065. elif guess.rstrip('/') in KNOWN_EXTENSIONS:
  1066. return guess.rstrip('/')
  1067. else:
  1068. return default_ext
  1069. def subtitles_filename(filename, sub_lang, sub_format):
  1070. return filename.rsplit('.', 1)[0] + '.' + sub_lang + '.' + sub_format
  1071. def date_from_str(date_str):
  1072. """
  1073. Return a datetime object from a string in the format YYYYMMDD or
  1074. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  1075. today = datetime.date.today()
  1076. if date_str in ('now', 'today'):
  1077. return today
  1078. if date_str == 'yesterday':
  1079. return today - datetime.timedelta(days=1)
  1080. match = re.match(r'(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  1081. if match is not None:
  1082. sign = match.group('sign')
  1083. time = int(match.group('time'))
  1084. if sign == '-':
  1085. time = -time
  1086. unit = match.group('unit')
  1087. # A bad approximation?
  1088. if unit == 'month':
  1089. unit = 'day'
  1090. time *= 30
  1091. elif unit == 'year':
  1092. unit = 'day'
  1093. time *= 365
  1094. unit += 's'
  1095. delta = datetime.timedelta(**{unit: time})
  1096. return today + delta
  1097. return datetime.datetime.strptime(date_str, '%Y%m%d').date()
  1098. def hyphenate_date(date_str):
  1099. """
  1100. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  1101. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  1102. if match is not None:
  1103. return '-'.join(match.groups())
  1104. else:
  1105. return date_str
  1106. class DateRange(object):
  1107. """Represents a time interval between two dates"""
  1108. def __init__(self, start=None, end=None):
  1109. """start and end must be strings in the format accepted by date"""
  1110. if start is not None:
  1111. self.start = date_from_str(start)
  1112. else:
  1113. self.start = datetime.datetime.min.date()
  1114. if end is not None:
  1115. self.end = date_from_str(end)
  1116. else:
  1117. self.end = datetime.datetime.max.date()
  1118. if self.start > self.end:
  1119. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  1120. @classmethod
  1121. def day(cls, day):
  1122. """Returns a range that only contains the given day"""
  1123. return cls(day, day)
  1124. def __contains__(self, date):
  1125. """Check if the date is in the range"""
  1126. if not isinstance(date, datetime.date):
  1127. date = date_from_str(date)
  1128. return self.start <= date <= self.end
  1129. def __str__(self):
  1130. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  1131. def platform_name():
  1132. """ Returns the platform name as a compat_str """
  1133. res = platform.platform()
  1134. if isinstance(res, bytes):
  1135. res = res.decode(preferredencoding())
  1136. assert isinstance(res, compat_str)
  1137. return res
  1138. def _windows_write_string(s, out):
  1139. """ Returns True if the string was written using special methods,
  1140. False if it has yet to be written out."""
  1141. # Adapted from http://stackoverflow.com/a/3259271/35070
  1142. import ctypes
  1143. import ctypes.wintypes
  1144. WIN_OUTPUT_IDS = {
  1145. 1: -11,
  1146. 2: -12,
  1147. }
  1148. try:
  1149. fileno = out.fileno()
  1150. except AttributeError:
  1151. # If the output stream doesn't have a fileno, it's virtual
  1152. return False
  1153. except io.UnsupportedOperation:
  1154. # Some strange Windows pseudo files?
  1155. return False
  1156. if fileno not in WIN_OUTPUT_IDS:
  1157. return False
  1158. GetStdHandle = compat_ctypes_WINFUNCTYPE(
  1159. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  1160. ('GetStdHandle', ctypes.windll.kernel32))
  1161. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  1162. WriteConsoleW = compat_ctypes_WINFUNCTYPE(
  1163. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  1164. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  1165. ctypes.wintypes.LPVOID)(('WriteConsoleW', ctypes.windll.kernel32))
  1166. written = ctypes.wintypes.DWORD(0)
  1167. GetFileType = compat_ctypes_WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)(('GetFileType', ctypes.windll.kernel32))
  1168. FILE_TYPE_CHAR = 0x0002
  1169. FILE_TYPE_REMOTE = 0x8000
  1170. GetConsoleMode = compat_ctypes_WINFUNCTYPE(
  1171. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  1172. ctypes.POINTER(ctypes.wintypes.DWORD))(
  1173. ('GetConsoleMode', ctypes.windll.kernel32))
  1174. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  1175. def not_a_console(handle):
  1176. if handle == INVALID_HANDLE_VALUE or handle is None:
  1177. return True
  1178. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR or
  1179. GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  1180. if not_a_console(h):
  1181. return False
  1182. def next_nonbmp_pos(s):
  1183. try:
  1184. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  1185. except StopIteration:
  1186. return len(s)
  1187. while s:
  1188. count = min(next_nonbmp_pos(s), 1024)
  1189. ret = WriteConsoleW(
  1190. h, s, count if count else 2, ctypes.byref(written), None)
  1191. if ret == 0:
  1192. raise OSError('Failed to write string')
  1193. if not count: # We just wrote a non-BMP character
  1194. assert written.value == 2
  1195. s = s[1:]
  1196. else:
  1197. assert written.value > 0
  1198. s = s[written.value:]
  1199. return True
  1200. def write_string(s, out=None, encoding=None):
  1201. if out is None:
  1202. out = sys.stderr
  1203. assert type(s) == compat_str
  1204. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  1205. if _windows_write_string(s, out):
  1206. return
  1207. if ('b' in getattr(out, 'mode', '') or
  1208. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  1209. byt = s.encode(encoding or preferredencoding(), 'ignore')
  1210. out.write(byt)
  1211. elif hasattr(out, 'buffer'):
  1212. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  1213. byt = s.encode(enc, 'ignore')
  1214. out.buffer.write(byt)
  1215. else:
  1216. out.write(s)
  1217. out.flush()
  1218. def bytes_to_intlist(bs):
  1219. if not bs:
  1220. return []
  1221. if isinstance(bs[0], int): # Python 3
  1222. return list(bs)
  1223. else:
  1224. return [ord(c) for c in bs]
  1225. def intlist_to_bytes(xs):
  1226. if not xs:
  1227. return b''
  1228. return compat_struct_pack('%dB' % len(xs), *xs)
  1229. # Cross-platform file locking
  1230. if sys.platform == 'win32':
  1231. import ctypes.wintypes
  1232. import msvcrt
  1233. class OVERLAPPED(ctypes.Structure):
  1234. _fields_ = [
  1235. ('Internal', ctypes.wintypes.LPVOID),
  1236. ('InternalHigh', ctypes.wintypes.LPVOID),
  1237. ('Offset', ctypes.wintypes.DWORD),
  1238. ('OffsetHigh', ctypes.wintypes.DWORD),
  1239. ('hEvent', ctypes.wintypes.HANDLE),
  1240. ]
  1241. kernel32 = ctypes.windll.kernel32
  1242. LockFileEx = kernel32.LockFileEx
  1243. LockFileEx.argtypes = [
  1244. ctypes.wintypes.HANDLE, # hFile
  1245. ctypes.wintypes.DWORD, # dwFlags
  1246. ctypes.wintypes.DWORD, # dwReserved
  1247. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  1248. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  1249. ctypes.POINTER(OVERLAPPED) # Overlapped
  1250. ]
  1251. LockFileEx.restype = ctypes.wintypes.BOOL
  1252. UnlockFileEx = kernel32.UnlockFileEx
  1253. UnlockFileEx.argtypes = [
  1254. ctypes.wintypes.HANDLE, # hFile
  1255. ctypes.wintypes.DWORD, # dwReserved
  1256. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  1257. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  1258. ctypes.POINTER(OVERLAPPED) # Overlapped
  1259. ]
  1260. UnlockFileEx.restype = ctypes.wintypes.BOOL
  1261. whole_low = 0xffffffff
  1262. whole_high = 0x7fffffff
  1263. def _lock_file(f, exclusive):
  1264. overlapped = OVERLAPPED()
  1265. overlapped.Offset = 0
  1266. overlapped.OffsetHigh = 0
  1267. overlapped.hEvent = 0
  1268. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  1269. handle = msvcrt.get_osfhandle(f.fileno())
  1270. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  1271. whole_low, whole_high, f._lock_file_overlapped_p):
  1272. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  1273. def _unlock_file(f):
  1274. assert f._lock_file_overlapped_p
  1275. handle = msvcrt.get_osfhandle(f.fileno())
  1276. if not UnlockFileEx(handle, 0,
  1277. whole_low, whole_high, f._lock_file_overlapped_p):
  1278. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  1279. else:
  1280. # Some platforms, such as Jython, is missing fcntl
  1281. try:
  1282. import fcntl
  1283. def _lock_file(f, exclusive):
  1284. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  1285. def _unlock_file(f):
  1286. fcntl.flock(f, fcntl.LOCK_UN)
  1287. except ImportError:
  1288. UNSUPPORTED_MSG = 'file locking is not supported on this platform'
  1289. def _lock_file(f, exclusive):
  1290. raise IOError(UNSUPPORTED_MSG)
  1291. def _unlock_file(f):
  1292. raise IOError(UNSUPPORTED_MSG)
  1293. class locked_file(object):
  1294. def __init__(self, filename, mode, encoding=None):
  1295. assert mode in ['r', 'a', 'w']
  1296. self.f = io.open(filename, mode, encoding=encoding)
  1297. self.mode = mode
  1298. def __enter__(self):
  1299. exclusive = self.mode != 'r'
  1300. try:
  1301. _lock_file(self.f, exclusive)
  1302. except IOError:
  1303. self.f.close()
  1304. raise
  1305. return self
  1306. def __exit__(self, etype, value, traceback):
  1307. try:
  1308. _unlock_file(self.f)
  1309. finally:
  1310. self.f.close()
  1311. def __iter__(self):
  1312. return iter(self.f)
  1313. def write(self, *args):
  1314. return self.f.write(*args)
  1315. def read(self, *args):
  1316. return self.f.read(*args)
  1317. def get_filesystem_encoding():
  1318. encoding = sys.getfilesystemencoding()
  1319. return encoding if encoding is not None else 'utf-8'
  1320. def shell_quote(args):
  1321. quoted_args = []
  1322. encoding = get_filesystem_encoding()
  1323. for a in args:
  1324. if isinstance(a, bytes):
  1325. # We may get a filename encoded with 'encodeFilename'
  1326. a = a.decode(encoding)
  1327. quoted_args.append(compat_shlex_quote(a))
  1328. return ' '.join(quoted_args)
  1329. def smuggle_url(url, data):
  1330. """ Pass additional data in a URL for internal use. """
  1331. url, idata = unsmuggle_url(url, {})
  1332. data.update(idata)
  1333. sdata = compat_urllib_parse_urlencode(
  1334. {'__youtubedl_smuggle': json.dumps(data)})
  1335. return url + '#' + sdata
  1336. def unsmuggle_url(smug_url, default=None):
  1337. if '#__youtubedl_smuggle' not in smug_url:
  1338. return smug_url, default
  1339. url, _, sdata = smug_url.rpartition('#')
  1340. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  1341. data = json.loads(jsond)
  1342. return url, data
  1343. def format_bytes(bytes):
  1344. if bytes is None:
  1345. return 'N/A'
  1346. if type(bytes) is str:
  1347. bytes = float(bytes)
  1348. if bytes == 0.0:
  1349. exponent = 0
  1350. else:
  1351. exponent = int(math.log(bytes, 1024.0))
  1352. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  1353. converted = float(bytes) / float(1024 ** exponent)
  1354. return '%.2f%s' % (converted, suffix)
  1355. def lookup_unit_table(unit_table, s):
  1356. units_re = '|'.join(re.escape(u) for u in unit_table)
  1357. m = re.match(
  1358. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)\b' % units_re, s)
  1359. if not m:
  1360. return None
  1361. num_str = m.group('num').replace(',', '.')
  1362. mult = unit_table[m.group('unit')]
  1363. return int(float(num_str) * mult)
  1364. def parse_filesize(s):
  1365. if s is None:
  1366. return None
  1367. # The lower-case forms are of course incorrect and unofficial,
  1368. # but we support those too
  1369. _UNIT_TABLE = {
  1370. 'B': 1,
  1371. 'b': 1,
  1372. 'bytes': 1,
  1373. 'KiB': 1024,
  1374. 'KB': 1000,
  1375. 'kB': 1024,
  1376. 'Kb': 1000,
  1377. 'kb': 1000,
  1378. 'kilobytes': 1000,
  1379. 'kibibytes': 1024,
  1380. 'MiB': 1024 ** 2,
  1381. 'MB': 1000 ** 2,
  1382. 'mB': 1024 ** 2,
  1383. 'Mb': 1000 ** 2,
  1384. 'mb': 1000 ** 2,
  1385. 'megabytes': 1000 ** 2,
  1386. 'mebibytes': 1024 ** 2,
  1387. 'GiB': 1024 ** 3,
  1388. 'GB': 1000 ** 3,
  1389. 'gB': 1024 ** 3,
  1390. 'Gb': 1000 ** 3,
  1391. 'gb': 1000 ** 3,
  1392. 'gigabytes': 1000 ** 3,
  1393. 'gibibytes': 1024 ** 3,
  1394. 'TiB': 1024 ** 4,
  1395. 'TB': 1000 ** 4,
  1396. 'tB': 1024 ** 4,
  1397. 'Tb': 1000 ** 4,
  1398. 'tb': 1000 ** 4,
  1399. 'terabytes': 1000 ** 4,
  1400. 'tebibytes': 1024 ** 4,
  1401. 'PiB': 1024 ** 5,
  1402. 'PB': 1000 ** 5,
  1403. 'pB': 1024 ** 5,
  1404. 'Pb': 1000 ** 5,
  1405. 'pb': 1000 ** 5,
  1406. 'petabytes': 1000 ** 5,
  1407. 'pebibytes': 1024 ** 5,
  1408. 'EiB': 1024 ** 6,
  1409. 'EB': 1000 ** 6,
  1410. 'eB': 1024 ** 6,
  1411. 'Eb': 1000 ** 6,
  1412. 'eb': 1000 ** 6,
  1413. 'exabytes': 1000 ** 6,
  1414. 'exbibytes': 1024 ** 6,
  1415. 'ZiB': 1024 ** 7,
  1416. 'ZB': 1000 ** 7,
  1417. 'zB': 1024 ** 7,
  1418. 'Zb': 1000 ** 7,
  1419. 'zb': 1000 ** 7,
  1420. 'zettabytes': 1000 ** 7,
  1421. 'zebibytes': 1024 ** 7,
  1422. 'YiB': 1024 ** 8,
  1423. 'YB': 1000 ** 8,
  1424. 'yB': 1024 ** 8,
  1425. 'Yb': 1000 ** 8,
  1426. 'yb': 1000 ** 8,
  1427. 'yottabytes': 1000 ** 8,
  1428. 'yobibytes': 1024 ** 8,
  1429. }
  1430. return lookup_unit_table(_UNIT_TABLE, s)
  1431. def parse_count(s):
  1432. if s is None:
  1433. return None
  1434. s = s.strip()
  1435. if re.match(r'^[\d,.]+$', s):
  1436. return str_to_int(s)
  1437. _UNIT_TABLE = {
  1438. 'k': 1000,
  1439. 'K': 1000,
  1440. 'm': 1000 ** 2,
  1441. 'M': 1000 ** 2,
  1442. 'kk': 1000 ** 2,
  1443. 'KK': 1000 ** 2,
  1444. }
  1445. return lookup_unit_table(_UNIT_TABLE, s)
  1446. def parse_resolution(s):
  1447. if s is None:
  1448. return {}
  1449. mobj = re.search(r'\b(?P<w>\d+)\s*[xX×]\s*(?P<h>\d+)\b', s)
  1450. if mobj:
  1451. return {
  1452. 'width': int(mobj.group('w')),
  1453. 'height': int(mobj.group('h')),
  1454. }
  1455. mobj = re.search(r'\b(\d+)[pPiI]\b', s)
  1456. if mobj:
  1457. return {'height': int(mobj.group(1))}
  1458. mobj = re.search(r'\b([48])[kK]\b', s)
  1459. if mobj:
  1460. return {'height': int(mobj.group(1)) * 540}
  1461. return {}
  1462. def month_by_name(name, lang='en'):
  1463. """ Return the number of a month by (locale-independently) English name """
  1464. month_names = MONTH_NAMES.get(lang, MONTH_NAMES['en'])
  1465. try:
  1466. return month_names.index(name) + 1
  1467. except ValueError:
  1468. return None
  1469. def month_by_abbreviation(abbrev):
  1470. """ Return the number of a month by (locale-independently) English
  1471. abbreviations """
  1472. try:
  1473. return [s[:3] for s in ENGLISH_MONTH_NAMES].index(abbrev) + 1
  1474. except ValueError:
  1475. return None
  1476. def fix_xml_ampersands(xml_str):
  1477. """Replace all the '&' by '&amp;' in XML"""
  1478. return re.sub(
  1479. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  1480. '&amp;',
  1481. xml_str)
  1482. def setproctitle(title):
  1483. assert isinstance(title, compat_str)
  1484. # ctypes in Jython is not complete
  1485. # http://bugs.jython.org/issue2148
  1486. if sys.platform.startswith('java'):
  1487. return
  1488. try:
  1489. libc = ctypes.cdll.LoadLibrary('libc.so.6')
  1490. except OSError:
  1491. return
  1492. except TypeError:
  1493. # LoadLibrary in Windows Python 2.7.13 only expects
  1494. # a bytestring, but since unicode_literals turns
  1495. # every string into a unicode string, it fails.
  1496. return
  1497. title_bytes = title.encode('utf-8')
  1498. buf = ctypes.create_string_buffer(len(title_bytes))
  1499. buf.value = title_bytes
  1500. try:
  1501. libc.prctl(15, buf, 0, 0, 0)
  1502. except AttributeError:
  1503. return # Strange libc, just skip this
  1504. def remove_start(s, start):
  1505. return s[len(start):] if s is not None and s.startswith(start) else s
  1506. def remove_end(s, end):
  1507. return s[:-len(end)] if s is not None and s.endswith(end) else s
  1508. def remove_quotes(s):
  1509. if s is None or len(s) < 2:
  1510. return s
  1511. for quote in ('"', "'", ):
  1512. if s[0] == quote and s[-1] == quote:
  1513. return s[1:-1]
  1514. return s
  1515. def url_basename(url):
  1516. path = compat_urlparse.urlparse(url).path
  1517. return path.strip('/').split('/')[-1]
  1518. def base_url(url):
  1519. return re.match(r'https?://[^?#&]+/', url).group()
  1520. def urljoin(base, path):
  1521. if isinstance(path, bytes):
  1522. path = path.decode('utf-8')
  1523. if not isinstance(path, compat_str) or not path:
  1524. return None
  1525. if re.match(r'^(?:https?:)?//', path):
  1526. return path
  1527. if isinstance(base, bytes):
  1528. base = base.decode('utf-8')
  1529. if not isinstance(base, compat_str) or not re.match(
  1530. r'^(?:https?:)?//', base):
  1531. return None
  1532. return compat_urlparse.urljoin(base, path)
  1533. class HEADRequest(compat_urllib_request.Request):
  1534. def get_method(self):
  1535. return 'HEAD'
  1536. class PUTRequest(compat_urllib_request.Request):
  1537. def get_method(self):
  1538. return 'PUT'
  1539. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  1540. if get_attr:
  1541. if v is not None:
  1542. v = getattr(v, get_attr, None)
  1543. if v == '':
  1544. v = None
  1545. if v is None:
  1546. return default
  1547. try:
  1548. return int(v) * invscale // scale
  1549. except ValueError:
  1550. return default
  1551. def str_or_none(v, default=None):
  1552. return default if v is None else compat_str(v)
  1553. def str_to_int(int_str):
  1554. """ A more relaxed version of int_or_none """
  1555. if int_str is None:
  1556. return None
  1557. int_str = re.sub(r'[,\.\+]', '', int_str)
  1558. return int(int_str)
  1559. def float_or_none(v, scale=1, invscale=1, default=None):
  1560. if v is None:
  1561. return default
  1562. try:
  1563. return float(v) * invscale / scale
  1564. except ValueError:
  1565. return default
  1566. def bool_or_none(v, default=None):
  1567. return v if isinstance(v, bool) else default
  1568. def strip_or_none(v):
  1569. return None if v is None else v.strip()
  1570. def url_or_none(url):
  1571. if not url or not isinstance(url, compat_str):
  1572. return None
  1573. url = url.strip()
  1574. return url if re.match(r'^(?:[a-zA-Z][\da-zA-Z.+-]*:)?//', url) else None
  1575. def parse_duration(s):
  1576. if not isinstance(s, compat_basestring):
  1577. return None
  1578. s = s.strip()
  1579. days, hours, mins, secs, ms = [None] * 5
  1580. m = re.match(r'(?:(?:(?:(?P<days>[0-9]+):)?(?P<hours>[0-9]+):)?(?P<mins>[0-9]+):)?(?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?Z?$', s)
  1581. if m:
  1582. days, hours, mins, secs, ms = m.groups()
  1583. else:
  1584. m = re.match(
  1585. r'''(?ix)(?:P?
  1586. (?:
  1587. [0-9]+\s*y(?:ears?)?\s*
  1588. )?
  1589. (?:
  1590. [0-9]+\s*m(?:onths?)?\s*
  1591. )?
  1592. (?:
  1593. [0-9]+\s*w(?:eeks?)?\s*
  1594. )?
  1595. (?:
  1596. (?P<days>[0-9]+)\s*d(?:ays?)?\s*
  1597. )?
  1598. T)?
  1599. (?:
  1600. (?P<hours>[0-9]+)\s*h(?:ours?)?\s*
  1601. )?
  1602. (?:
  1603. (?P<mins>[0-9]+)\s*m(?:in(?:ute)?s?)?\s*
  1604. )?
  1605. (?:
  1606. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*s(?:ec(?:ond)?s?)?\s*
  1607. )?Z?$''', s)
  1608. if m:
  1609. days, hours, mins, secs, ms = m.groups()
  1610. else:
  1611. m = re.match(r'(?i)(?:(?P<hours>[0-9.]+)\s*(?:hours?)|(?P<mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*)Z?$', s)
  1612. if m:
  1613. hours, mins = m.groups()
  1614. else:
  1615. return None
  1616. duration = 0
  1617. if secs:
  1618. duration += float(secs)
  1619. if mins:
  1620. duration += float(mins) * 60
  1621. if hours:
  1622. duration += float(hours) * 60 * 60
  1623. if days:
  1624. duration += float(days) * 24 * 60 * 60
  1625. if ms:
  1626. duration += float(ms)
  1627. return duration
  1628. def prepend_extension(filename, ext, expected_real_ext=None):
  1629. name, real_ext = os.path.splitext(filename)
  1630. return (
  1631. '{0}.{1}{2}'.format(name, ext, real_ext)
  1632. if not expected_real_ext or real_ext[1:] == expected_real_ext
  1633. else '{0}.{1}'.format(filename, ext))
  1634. def replace_extension(filename, ext, expected_real_ext=None):
  1635. name, real_ext = os.path.splitext(filename)
  1636. return '{0}.{1}'.format(
  1637. name if not expected_real_ext or real_ext[1:] == expected_real_ext else filename,
  1638. ext)
  1639. def check_executable(exe, args=[]):
  1640. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  1641. args can be a list of arguments for a short output (like -version) """
  1642. try:
  1643. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  1644. except OSError:
  1645. return False
  1646. return exe
  1647. def get_exe_version(exe, args=['--version'],
  1648. version_re=None, unrecognized='present'):
  1649. """ Returns the version of the specified executable,
  1650. or False if the executable is not present """
  1651. try:
  1652. # STDIN should be redirected too. On UNIX-like systems, ffmpeg triggers
  1653. # SIGTTOU if youtube-dl is run in the background.
  1654. # See https://github.com/rg3/youtube-dl/issues/955#issuecomment-209789656
  1655. out, _ = subprocess.Popen(
  1656. [encodeArgument(exe)] + args,
  1657. stdin=subprocess.PIPE,
  1658. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  1659. except OSError:
  1660. return False
  1661. if isinstance(out, bytes): # Python 2.x
  1662. out = out.decode('ascii', 'ignore')
  1663. return detect_exe_version(out, version_re, unrecognized)
  1664. def detect_exe_version(output, version_re=None, unrecognized='present'):
  1665. assert isinstance(output, compat_str)
  1666. if version_re is None:
  1667. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  1668. m = re.search(version_re, output)
  1669. if m:
  1670. return m.group(1)
  1671. else:
  1672. return unrecognized
  1673. class PagedList(object):
  1674. def __len__(self):
  1675. # This is only useful for tests
  1676. return len(self.getslice())
  1677. class OnDemandPagedList(PagedList):
  1678. def __init__(self, pagefunc, pagesize, use_cache=True):
  1679. self._pagefunc = pagefunc
  1680. self._pagesize = pagesize
  1681. self._use_cache = use_cache
  1682. if use_cache:
  1683. self._cache = {}
  1684. def getslice(self, start=0, end=None):
  1685. res = []
  1686. for pagenum in itertools.count(start // self._pagesize):
  1687. firstid = pagenum * self._pagesize
  1688. nextfirstid = pagenum * self._pagesize + self._pagesize
  1689. if start >= nextfirstid:
  1690. continue
  1691. page_results = None
  1692. if self._use_cache:
  1693. page_results = self._cache.get(pagenum)
  1694. if page_results is None:
  1695. page_results = list(self._pagefunc(pagenum))
  1696. if self._use_cache:
  1697. self._cache[pagenum] = page_results
  1698. startv = (
  1699. start % self._pagesize
  1700. if firstid <= start < nextfirstid
  1701. else 0)
  1702. endv = (
  1703. ((end - 1) % self._pagesize) + 1
  1704. if (end is not None and firstid <= end <= nextfirstid)
  1705. else None)
  1706. if startv != 0 or endv is not None:
  1707. page_results = page_results[startv:endv]
  1708. res.extend(page_results)
  1709. # A little optimization - if current page is not "full", ie. does
  1710. # not contain page_size videos then we can assume that this page
  1711. # is the last one - there are no more ids on further pages -
  1712. # i.e. no need to query again.
  1713. if len(page_results) + startv < self._pagesize:
  1714. break
  1715. # If we got the whole page, but the next page is not interesting,
  1716. # break out early as well
  1717. if end == nextfirstid:
  1718. break
  1719. return res
  1720. class InAdvancePagedList(PagedList):
  1721. def __init__(self, pagefunc, pagecount, pagesize):
  1722. self._pagefunc = pagefunc
  1723. self._pagecount = pagecount
  1724. self._pagesize = pagesize
  1725. def getslice(self, start=0, end=None):
  1726. res = []
  1727. start_page = start // self._pagesize
  1728. end_page = (
  1729. self._pagecount if end is None else (end // self._pagesize + 1))
  1730. skip_elems = start - start_page * self._pagesize
  1731. only_more = None if end is None else end - start
  1732. for pagenum in range(start_page, end_page):
  1733. page = list(self._pagefunc(pagenum))
  1734. if skip_elems:
  1735. page = page[skip_elems:]
  1736. skip_elems = None
  1737. if only_more is not None:
  1738. if len(page) < only_more:
  1739. only_more -= len(page)
  1740. else:
  1741. page = page[:only_more]
  1742. res.extend(page)
  1743. break
  1744. res.extend(page)
  1745. return res
  1746. def uppercase_escape(s):
  1747. unicode_escape = codecs.getdecoder('unicode_escape')
  1748. return re.sub(
  1749. r'\\U[0-9a-fA-F]{8}',
  1750. lambda m: unicode_escape(m.group(0))[0],
  1751. s)
  1752. def lowercase_escape(s):
  1753. unicode_escape = codecs.getdecoder('unicode_escape')
  1754. return re.sub(
  1755. r'\\u[0-9a-fA-F]{4}',
  1756. lambda m: unicode_escape(m.group(0))[0],
  1757. s)
  1758. def escape_rfc3986(s):
  1759. """Escape non-ASCII characters as suggested by RFC 3986"""
  1760. if sys.version_info < (3, 0) and isinstance(s, compat_str):
  1761. s = s.encode('utf-8')
  1762. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1763. def escape_url(url):
  1764. """Escape URL as suggested by RFC 3986"""
  1765. url_parsed = compat_urllib_parse_urlparse(url)
  1766. return url_parsed._replace(
  1767. netloc=url_parsed.netloc.encode('idna').decode('ascii'),
  1768. path=escape_rfc3986(url_parsed.path),
  1769. params=escape_rfc3986(url_parsed.params),
  1770. query=escape_rfc3986(url_parsed.query),
  1771. fragment=escape_rfc3986(url_parsed.fragment)
  1772. ).geturl()
  1773. def read_batch_urls(batch_fd):
  1774. def fixup(url):
  1775. if not isinstance(url, compat_str):
  1776. url = url.decode('utf-8', 'replace')
  1777. BOM_UTF8 = '\xef\xbb\xbf'
  1778. if url.startswith(BOM_UTF8):
  1779. url = url[len(BOM_UTF8):]
  1780. url = url.strip()
  1781. if url.startswith(('#', ';', ']')):
  1782. return False
  1783. return url
  1784. with contextlib.closing(batch_fd) as fd:
  1785. return [url for url in map(fixup, fd) if url]
  1786. def urlencode_postdata(*args, **kargs):
  1787. return compat_urllib_parse_urlencode(*args, **kargs).encode('ascii')
  1788. def update_url_query(url, query):
  1789. if not query:
  1790. return url
  1791. parsed_url = compat_urlparse.urlparse(url)
  1792. qs = compat_parse_qs(parsed_url.query)
  1793. qs.update(query)
  1794. return compat_urlparse.urlunparse(parsed_url._replace(
  1795. query=compat_urllib_parse_urlencode(qs, True)))
  1796. def update_Request(req, url=None, data=None, headers={}, query={}):
  1797. req_headers = req.headers.copy()
  1798. req_headers.update(headers)
  1799. req_data = data or req.data
  1800. req_url = update_url_query(url or req.get_full_url(), query)
  1801. req_get_method = req.get_method()
  1802. if req_get_method == 'HEAD':
  1803. req_type = HEADRequest
  1804. elif req_get_method == 'PUT':
  1805. req_type = PUTRequest
  1806. else:
  1807. req_type = compat_urllib_request.Request
  1808. new_req = req_type(
  1809. req_url, data=req_data, headers=req_headers,
  1810. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  1811. if hasattr(req, 'timeout'):
  1812. new_req.timeout = req.timeout
  1813. return new_req
  1814. def _multipart_encode_impl(data, boundary):
  1815. content_type = 'multipart/form-data; boundary=%s' % boundary
  1816. out = b''
  1817. for k, v in data.items():
  1818. out += b'--' + boundary.encode('ascii') + b'\r\n'
  1819. if isinstance(k, compat_str):
  1820. k = k.encode('utf-8')
  1821. if isinstance(v, compat_str):
  1822. v = v.encode('utf-8')
  1823. # RFC 2047 requires non-ASCII field names to be encoded, while RFC 7578
  1824. # suggests sending UTF-8 directly. Firefox sends UTF-8, too
  1825. content = b'Content-Disposition: form-data; name="' + k + b'"\r\n\r\n' + v + b'\r\n'
  1826. if boundary.encode('ascii') in content:
  1827. raise ValueError('Boundary overlaps with data')
  1828. out += content
  1829. out += b'--' + boundary.encode('ascii') + b'--\r\n'
  1830. return out, content_type
  1831. def multipart_encode(data, boundary=None):
  1832. '''
  1833. Encode a dict to RFC 7578-compliant form-data
  1834. data:
  1835. A dict where keys and values can be either Unicode or bytes-like
  1836. objects.
  1837. boundary:
  1838. If specified a Unicode object, it's used as the boundary. Otherwise
  1839. a random boundary is generated.
  1840. Reference: https://tools.ietf.org/html/rfc7578
  1841. '''
  1842. has_specified_boundary = boundary is not None
  1843. while True:
  1844. if boundary is None:
  1845. boundary = '---------------' + str(random.randrange(0x0fffffff, 0xffffffff))
  1846. try:
  1847. out, content_type = _multipart_encode_impl(data, boundary)
  1848. break
  1849. except ValueError:
  1850. if has_specified_boundary:
  1851. raise
  1852. boundary = None
  1853. return out, content_type
  1854. def dict_get(d, key_or_keys, default=None, skip_false_values=True):
  1855. if isinstance(key_or_keys, (list, tuple)):
  1856. for key in key_or_keys:
  1857. if key not in d or d[key] is None or skip_false_values and not d[key]:
  1858. continue
  1859. return d[key]
  1860. return default
  1861. return d.get(key_or_keys, default)
  1862. def try_get(src, getter, expected_type=None):
  1863. if not isinstance(getter, (list, tuple)):
  1864. getter = [getter]
  1865. for get in getter:
  1866. try:
  1867. v = get(src)
  1868. except (AttributeError, KeyError, TypeError, IndexError):
  1869. pass
  1870. else:
  1871. if expected_type is None or isinstance(v, expected_type):
  1872. return v
  1873. def merge_dicts(*dicts):
  1874. merged = {}
  1875. for a_dict in dicts:
  1876. for k, v in a_dict.items():
  1877. if v is None:
  1878. continue
  1879. if (k not in merged or
  1880. (isinstance(v, compat_str) and v and
  1881. isinstance(merged[k], compat_str) and
  1882. not merged[k])):
  1883. merged[k] = v
  1884. return merged
  1885. def encode_compat_str(string, encoding=preferredencoding(), errors='strict'):
  1886. return string if isinstance(string, compat_str) else compat_str(string, encoding, errors)
  1887. US_RATINGS = {
  1888. 'G': 0,
  1889. 'PG': 10,
  1890. 'PG-13': 13,
  1891. 'R': 16,
  1892. 'NC': 18,
  1893. }
  1894. TV_PARENTAL_GUIDELINES = {
  1895. 'TV-Y': 0,
  1896. 'TV-Y7': 7,
  1897. 'TV-G': 0,
  1898. 'TV-PG': 0,
  1899. 'TV-14': 14,
  1900. 'TV-MA': 17,
  1901. }
  1902. def parse_age_limit(s):
  1903. if type(s) == int:
  1904. return s if 0 <= s <= 21 else None
  1905. if not isinstance(s, compat_basestring):
  1906. return None
  1907. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1908. if m:
  1909. return int(m.group('age'))
  1910. if s in US_RATINGS:
  1911. return US_RATINGS[s]
  1912. m = re.match(r'^TV[_-]?(%s)$' % '|'.join(k[3:] for k in TV_PARENTAL_GUIDELINES), s)
  1913. if m:
  1914. return TV_PARENTAL_GUIDELINES['TV-' + m.group(1)]
  1915. return None
  1916. def strip_jsonp(code):
  1917. return re.sub(
  1918. r'''(?sx)^
  1919. (?:window\.)?(?P<func_name>[a-zA-Z0-9_.$]*)
  1920. (?:\s*&&\s*(?P=func_name))?
  1921. \s*\(\s*(?P<callback_data>.*)\);?
  1922. \s*?(?://[^\n]*)*$''',
  1923. r'\g<callback_data>', code)
  1924. def js_to_json(code):
  1925. COMMENT_RE = r'/\*(?:(?!\*/).)*?\*/|//[^\n]*'
  1926. SKIP_RE = r'\s*(?:{comment})?\s*'.format(comment=COMMENT_RE)
  1927. INTEGER_TABLE = (
  1928. (r'(?s)^(0[xX][0-9a-fA-F]+){skip}:?$'.format(skip=SKIP_RE), 16),
  1929. (r'(?s)^(0+[0-7]+){skip}:?$'.format(skip=SKIP_RE), 8),
  1930. )
  1931. def fix_kv(m):
  1932. v = m.group(0)
  1933. if v in ('true', 'false', 'null'):
  1934. return v
  1935. elif v.startswith('/*') or v.startswith('//') or v == ',':
  1936. return ""
  1937. if v[0] in ("'", '"'):
  1938. v = re.sub(r'(?s)\\.|"', lambda m: {
  1939. '"': '\\"',
  1940. "\\'": "'",
  1941. '\\\n': '',
  1942. '\\x': '\\u00',
  1943. }.get(m.group(0), m.group(0)), v[1:-1])
  1944. for regex, base in INTEGER_TABLE:
  1945. im = re.match(regex, v)
  1946. if im:
  1947. i = int(im.group(1), base)
  1948. return '"%d":' % i if v.endswith(':') else '%d' % i
  1949. return '"%s"' % v
  1950. return re.sub(r'''(?sx)
  1951. "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
  1952. '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
  1953. {comment}|,(?={skip}[\]}}])|
  1954. (?:(?<![0-9])[eE]|[a-df-zA-DF-Z_])[.a-zA-Z_0-9]*|
  1955. \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:{skip}:)?|
  1956. [0-9]+(?={skip}:)
  1957. '''.format(comment=COMMENT_RE, skip=SKIP_RE), fix_kv, code)
  1958. def qualities(quality_ids):
  1959. """ Get a numeric quality value out of a list of possible values """
  1960. def q(qid):
  1961. try:
  1962. return quality_ids.index(qid)
  1963. except ValueError:
  1964. return -1
  1965. return q
  1966. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1967. def limit_length(s, length):
  1968. """ Add ellipses to overly long strings """
  1969. if s is None:
  1970. return None
  1971. ELLIPSES = '...'
  1972. if len(s) > length:
  1973. return s[:length - len(ELLIPSES)] + ELLIPSES
  1974. return s
  1975. def version_tuple(v):
  1976. return tuple(int(e) for e in re.split(r'[-.]', v))
  1977. def is_outdated_version(version, limit, assume_new=True):
  1978. if not version:
  1979. return not assume_new
  1980. try:
  1981. return version_tuple(version) < version_tuple(limit)
  1982. except ValueError:
  1983. return not assume_new
  1984. def ytdl_is_updateable():
  1985. """ Returns if youtube-dl can be updated with -U """
  1986. from zipimport import zipimporter
  1987. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  1988. def args_to_str(args):
  1989. # Get a short string representation for a subprocess command
  1990. return ' '.join(compat_shlex_quote(a) for a in args)
  1991. def error_to_compat_str(err):
  1992. err_str = str(err)
  1993. # On python 2 error byte string must be decoded with proper
  1994. # encoding rather than ascii
  1995. if sys.version_info[0] < 3:
  1996. err_str = err_str.decode(preferredencoding())
  1997. return err_str
  1998. def mimetype2ext(mt):
  1999. if mt is None:
  2000. return None
  2001. ext = {
  2002. 'audio/mp4': 'm4a',
  2003. # Per RFC 3003, audio/mpeg can be .mp1, .mp2 or .mp3. Here use .mp3 as
  2004. # it's the most popular one
  2005. 'audio/mpeg': 'mp3',
  2006. }.get(mt)
  2007. if ext is not None:
  2008. return ext
  2009. _, _, res = mt.rpartition('/')
  2010. res = res.split(';')[0].strip().lower()
  2011. return {
  2012. '3gpp': '3gp',
  2013. 'smptett+xml': 'tt',
  2014. 'ttaf+xml': 'dfxp',
  2015. 'ttml+xml': 'ttml',
  2016. 'x-flv': 'flv',
  2017. 'x-mp4-fragmented': 'mp4',
  2018. 'x-ms-sami': 'sami',
  2019. 'x-ms-wmv': 'wmv',
  2020. 'mpegurl': 'm3u8',
  2021. 'x-mpegurl': 'm3u8',
  2022. 'vnd.apple.mpegurl': 'm3u8',
  2023. 'dash+xml': 'mpd',
  2024. 'f4m+xml': 'f4m',
  2025. 'hds+xml': 'f4m',
  2026. 'vnd.ms-sstr+xml': 'ism',
  2027. 'quicktime': 'mov',
  2028. 'mp2t': 'ts',
  2029. }.get(res, res)
  2030. def parse_codecs(codecs_str):
  2031. # http://tools.ietf.org/html/rfc6381
  2032. if not codecs_str:
  2033. return {}
  2034. splited_codecs = list(filter(None, map(
  2035. lambda str: str.strip(), codecs_str.strip().strip(',').split(','))))
  2036. vcodec, acodec = None, None
  2037. for full_codec in splited_codecs:
  2038. codec = full_codec.split('.')[0]
  2039. if codec in ('avc1', 'avc2', 'avc3', 'avc4', 'vp9', 'vp8', 'hev1', 'hev2', 'h263', 'h264', 'mp4v', 'hvc1', 'av01'):
  2040. if not vcodec:
  2041. vcodec = full_codec
  2042. elif codec in ('mp4a', 'opus', 'vorbis', 'mp3', 'aac', 'ac-3', 'ec-3', 'eac3', 'dtsc', 'dtse', 'dtsh', 'dtsl'):
  2043. if not acodec:
  2044. acodec = full_codec
  2045. else:
  2046. write_string('WARNING: Unknown codec %s\n' % full_codec, sys.stderr)
  2047. if not vcodec and not acodec:
  2048. if len(splited_codecs) == 2:
  2049. return {
  2050. 'vcodec': vcodec,
  2051. 'acodec': acodec,
  2052. }
  2053. elif len(splited_codecs) == 1:
  2054. return {
  2055. 'vcodec': 'none',
  2056. 'acodec': vcodec,
  2057. }
  2058. else:
  2059. return {
  2060. 'vcodec': vcodec or 'none',
  2061. 'acodec': acodec or 'none',
  2062. }
  2063. return {}
  2064. def urlhandle_detect_ext(url_handle):
  2065. getheader = url_handle.headers.get
  2066. cd = getheader('Content-Disposition')
  2067. if cd:
  2068. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  2069. if m:
  2070. e = determine_ext(m.group('filename'), default_ext=None)
  2071. if e:
  2072. return e
  2073. return mimetype2ext(getheader('Content-Type'))
  2074. def encode_data_uri(data, mime_type):
  2075. return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
  2076. def age_restricted(content_limit, age_limit):
  2077. """ Returns True iff the content should be blocked """
  2078. if age_limit is None: # No limit set
  2079. return False
  2080. if content_limit is None:
  2081. return False # Content available for everyone
  2082. return age_limit < content_limit
  2083. def is_html(first_bytes):
  2084. """ Detect whether a file contains HTML by examining its first bytes. """
  2085. BOMS = [
  2086. (b'\xef\xbb\xbf', 'utf-8'),
  2087. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  2088. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  2089. (b'\xff\xfe', 'utf-16-le'),
  2090. (b'\xfe\xff', 'utf-16-be'),
  2091. ]
  2092. for bom, enc in BOMS:
  2093. if first_bytes.startswith(bom):
  2094. s = first_bytes[len(bom):].decode(enc, 'replace')
  2095. break
  2096. else:
  2097. s = first_bytes.decode('utf-8', 'replace')
  2098. return re.match(r'^\s*<', s)
  2099. def determine_protocol(info_dict):
  2100. protocol = info_dict.get('protocol')
  2101. if protocol is not None:
  2102. return protocol
  2103. url = info_dict['url']
  2104. if url.startswith('rtmp'):
  2105. return 'rtmp'
  2106. elif url.startswith('mms'):
  2107. return 'mms'
  2108. elif url.startswith('rtsp'):
  2109. return 'rtsp'
  2110. ext = determine_ext(url)
  2111. if ext == 'm3u8':
  2112. return 'm3u8'
  2113. elif ext == 'f4m':
  2114. return 'f4m'
  2115. return compat_urllib_parse_urlparse(url).scheme
  2116. def render_table(header_row, data):
  2117. """ Render a list of rows, each as a list of values """
  2118. table = [header_row] + data
  2119. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  2120. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  2121. return '\n'.join(format_str % tuple(row) for row in table)
  2122. def _match_one(filter_part, dct):
  2123. COMPARISON_OPERATORS = {
  2124. '<': operator.lt,
  2125. '<=': operator.le,
  2126. '>': operator.gt,
  2127. '>=': operator.ge,
  2128. '=': operator.eq,
  2129. '!=': operator.ne,
  2130. }
  2131. operator_rex = re.compile(r'''(?x)\s*
  2132. (?P<key>[a-z_]+)
  2133. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  2134. (?:
  2135. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  2136. (?P<quote>["\'])(?P<quotedstrval>(?:\\.|(?!(?P=quote)|\\).)+?)(?P=quote)|
  2137. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  2138. )
  2139. \s*$
  2140. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  2141. m = operator_rex.search(filter_part)
  2142. if m:
  2143. op = COMPARISON_OPERATORS[m.group('op')]
  2144. actual_value = dct.get(m.group('key'))
  2145. if (m.group('quotedstrval') is not None or
  2146. m.group('strval') is not None or
  2147. # If the original field is a string and matching comparisonvalue is
  2148. # a number we should respect the origin of the original field
  2149. # and process comparison value as a string (see
  2150. # https://github.com/rg3/youtube-dl/issues/11082).
  2151. actual_value is not None and m.group('intval') is not None and
  2152. isinstance(actual_value, compat_str)):
  2153. if m.group('op') not in ('=', '!='):
  2154. raise ValueError(
  2155. 'Operator %s does not support string values!' % m.group('op'))
  2156. comparison_value = m.group('quotedstrval') or m.group('strval') or m.group('intval')
  2157. quote = m.group('quote')
  2158. if quote is not None:
  2159. comparison_value = comparison_value.replace(r'\%s' % quote, quote)
  2160. else:
  2161. try:
  2162. comparison_value = int(m.group('intval'))
  2163. except ValueError:
  2164. comparison_value = parse_filesize(m.group('intval'))
  2165. if comparison_value is None:
  2166. comparison_value = parse_filesize(m.group('intval') + 'B')
  2167. if comparison_value is None:
  2168. raise ValueError(
  2169. 'Invalid integer value %r in filter part %r' % (
  2170. m.group('intval'), filter_part))
  2171. if actual_value is None:
  2172. return m.group('none_inclusive')
  2173. return op(actual_value, comparison_value)
  2174. UNARY_OPERATORS = {
  2175. '': lambda v: (v is True) if isinstance(v, bool) else (v is not None),
  2176. '!': lambda v: (v is False) if isinstance(v, bool) else (v is None),
  2177. }
  2178. operator_rex = re.compile(r'''(?x)\s*
  2179. (?P<op>%s)\s*(?P<key>[a-z_]+)
  2180. \s*$
  2181. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  2182. m = operator_rex.search(filter_part)
  2183. if m:
  2184. op = UNARY_OPERATORS[m.group('op')]
  2185. actual_value = dct.get(m.group('key'))
  2186. return op(actual_value)
  2187. raise ValueError('Invalid filter part %r' % filter_part)
  2188. def match_str(filter_str, dct):
  2189. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  2190. return all(
  2191. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  2192. def match_filter_func(filter_str):
  2193. def _match_func(info_dict):
  2194. if match_str(filter_str, info_dict):
  2195. return None
  2196. else:
  2197. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  2198. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  2199. return _match_func
  2200. def parse_dfxp_time_expr(time_expr):
  2201. if not time_expr:
  2202. return
  2203. mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
  2204. if mobj:
  2205. return float(mobj.group('time_offset'))
  2206. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
  2207. if mobj:
  2208. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
  2209. def srt_subtitles_timecode(seconds):
  2210. return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
  2211. def dfxp2srt(dfxp_data):
  2212. '''
  2213. @param dfxp_data A bytes-like object containing DFXP data
  2214. @returns A unicode object containing converted SRT data
  2215. '''
  2216. LEGACY_NAMESPACES = (
  2217. (b'http://www.w3.org/ns/ttml', [
  2218. b'http://www.w3.org/2004/11/ttaf1',
  2219. b'http://www.w3.org/2006/04/ttaf1',
  2220. b'http://www.w3.org/2006/10/ttaf1',
  2221. ]),
  2222. (b'http://www.w3.org/ns/ttml#styling', [
  2223. b'http://www.w3.org/ns/ttml#style',
  2224. ]),
  2225. )
  2226. SUPPORTED_STYLING = [
  2227. 'color',
  2228. 'fontFamily',
  2229. 'fontSize',
  2230. 'fontStyle',
  2231. 'fontWeight',
  2232. 'textDecoration'
  2233. ]
  2234. _x = functools.partial(xpath_with_ns, ns_map={
  2235. 'xml': 'http://www.w3.org/XML/1998/namespace',
  2236. 'ttml': 'http://www.w3.org/ns/ttml',
  2237. 'tts': 'http://www.w3.org/ns/ttml#styling',
  2238. })
  2239. styles = {}
  2240. default_style = {}
  2241. class TTMLPElementParser(object):
  2242. _out = ''
  2243. _unclosed_elements = []
  2244. _applied_styles = []
  2245. def start(self, tag, attrib):
  2246. if tag in (_x('ttml:br'), 'br'):
  2247. self._out += '\n'
  2248. else:
  2249. unclosed_elements = []
  2250. style = {}
  2251. element_style_id = attrib.get('style')
  2252. if default_style:
  2253. style.update(default_style)
  2254. if element_style_id:
  2255. style.update(styles.get(element_style_id, {}))
  2256. for prop in SUPPORTED_STYLING:
  2257. prop_val = attrib.get(_x('tts:' + prop))
  2258. if prop_val:
  2259. style[prop] = prop_val
  2260. if style:
  2261. font = ''
  2262. for k, v in sorted(style.items()):
  2263. if self._applied_styles and self._applied_styles[-1].get(k) == v:
  2264. continue
  2265. if k == 'color':
  2266. font += ' color="%s"' % v
  2267. elif k == 'fontSize':
  2268. font += ' size="%s"' % v
  2269. elif k == 'fontFamily':
  2270. font += ' face="%s"' % v
  2271. elif k == 'fontWeight' and v == 'bold':
  2272. self._out += '<b>'
  2273. unclosed_elements.append('b')
  2274. elif k == 'fontStyle' and v == 'italic':
  2275. self._out += '<i>'
  2276. unclosed_elements.append('i')
  2277. elif k == 'textDecoration' and v == 'underline':
  2278. self._out += '<u>'
  2279. unclosed_elements.append('u')
  2280. if font:
  2281. self._out += '<font' + font + '>'
  2282. unclosed_elements.append('font')
  2283. applied_style = {}
  2284. if self._applied_styles:
  2285. applied_style.update(self._applied_styles[-1])
  2286. applied_style.update(style)
  2287. self._applied_styles.append(applied_style)
  2288. self._unclosed_elements.append(unclosed_elements)
  2289. def end(self, tag):
  2290. if tag not in (_x('ttml:br'), 'br'):
  2291. unclosed_elements = self._unclosed_elements.pop()
  2292. for element in reversed(unclosed_elements):
  2293. self._out += '</%s>' % element
  2294. if unclosed_elements and self._applied_styles:
  2295. self._applied_styles.pop()
  2296. def data(self, data):
  2297. self._out += data
  2298. def close(self):
  2299. return self._out.strip()
  2300. def parse_node(node):
  2301. target = TTMLPElementParser()
  2302. parser = xml.etree.ElementTree.XMLParser(target=target)
  2303. parser.feed(xml.etree.ElementTree.tostring(node))
  2304. return parser.close()
  2305. for k, v in LEGACY_NAMESPACES:
  2306. for ns in v:
  2307. dfxp_data = dfxp_data.replace(ns, k)
  2308. dfxp = compat_etree_fromstring(dfxp_data)
  2309. out = []
  2310. paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall('.//p')
  2311. if not paras:
  2312. raise ValueError('Invalid dfxp/TTML subtitle')
  2313. repeat = False
  2314. while True:
  2315. for style in dfxp.findall(_x('.//ttml:style')):
  2316. style_id = style.get('id') or style.get(_x('xml:id'))
  2317. if not style_id:
  2318. continue
  2319. parent_style_id = style.get('style')
  2320. if parent_style_id:
  2321. if parent_style_id not in styles:
  2322. repeat = True
  2323. continue
  2324. styles[style_id] = styles[parent_style_id].copy()
  2325. for prop in SUPPORTED_STYLING:
  2326. prop_val = style.get(_x('tts:' + prop))
  2327. if prop_val:
  2328. styles.setdefault(style_id, {})[prop] = prop_val
  2329. if repeat:
  2330. repeat = False
  2331. else:
  2332. break
  2333. for p in ('body', 'div'):
  2334. ele = xpath_element(dfxp, [_x('.//ttml:' + p), './/' + p])
  2335. if ele is None:
  2336. continue
  2337. style = styles.get(ele.get('style'))
  2338. if not style:
  2339. continue
  2340. default_style.update(style)
  2341. for para, index in zip(paras, itertools.count(1)):
  2342. begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
  2343. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  2344. dur = parse_dfxp_time_expr(para.attrib.get('dur'))
  2345. if begin_time is None:
  2346. continue
  2347. if not end_time:
  2348. if not dur:
  2349. continue
  2350. end_time = begin_time + dur
  2351. out.append('%d\n%s --> %s\n%s\n\n' % (
  2352. index,
  2353. srt_subtitles_timecode(begin_time),
  2354. srt_subtitles_timecode(end_time),
  2355. parse_node(para)))
  2356. return ''.join(out)
  2357. def cli_option(params, command_option, param):
  2358. param = params.get(param)
  2359. if param:
  2360. param = compat_str(param)
  2361. return [command_option, param] if param is not None else []
  2362. def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
  2363. param = params.get(param)
  2364. if param is None:
  2365. return []
  2366. assert isinstance(param, bool)
  2367. if separator:
  2368. return [command_option + separator + (true_value if param else false_value)]
  2369. return [command_option, true_value if param else false_value]
  2370. def cli_valueless_option(params, command_option, param, expected_value=True):
  2371. param = params.get(param)
  2372. return [command_option] if param == expected_value else []
  2373. def cli_configuration_args(params, param, default=[]):
  2374. ex_args = params.get(param)
  2375. if ex_args is None:
  2376. return default
  2377. assert isinstance(ex_args, list)
  2378. return ex_args
  2379. class ISO639Utils(object):
  2380. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  2381. _lang_map = {
  2382. 'aa': 'aar',
  2383. 'ab': 'abk',
  2384. 'ae': 'ave',
  2385. 'af': 'afr',
  2386. 'ak': 'aka',
  2387. 'am': 'amh',
  2388. 'an': 'arg',
  2389. 'ar': 'ara',
  2390. 'as': 'asm',
  2391. 'av': 'ava',
  2392. 'ay': 'aym',
  2393. 'az': 'aze',
  2394. 'ba': 'bak',
  2395. 'be': 'bel',
  2396. 'bg': 'bul',
  2397. 'bh': 'bih',
  2398. 'bi': 'bis',
  2399. 'bm': 'bam',
  2400. 'bn': 'ben',
  2401. 'bo': 'bod',
  2402. 'br': 'bre',
  2403. 'bs': 'bos',
  2404. 'ca': 'cat',
  2405. 'ce': 'che',
  2406. 'ch': 'cha',
  2407. 'co': 'cos',
  2408. 'cr': 'cre',
  2409. 'cs': 'ces',
  2410. 'cu': 'chu',
  2411. 'cv': 'chv',
  2412. 'cy': 'cym',
  2413. 'da': 'dan',
  2414. 'de': 'deu',
  2415. 'dv': 'div',
  2416. 'dz': 'dzo',
  2417. 'ee': 'ewe',
  2418. 'el': 'ell',
  2419. 'en': 'eng',
  2420. 'eo': 'epo',
  2421. 'es': 'spa',
  2422. 'et': 'est',
  2423. 'eu': 'eus',
  2424. 'fa': 'fas',
  2425. 'ff': 'ful',
  2426. 'fi': 'fin',
  2427. 'fj': 'fij',
  2428. 'fo': 'fao',
  2429. 'fr': 'fra',
  2430. 'fy': 'fry',
  2431. 'ga': 'gle',
  2432. 'gd': 'gla',
  2433. 'gl': 'glg',
  2434. 'gn': 'grn',
  2435. 'gu': 'guj',
  2436. 'gv': 'glv',
  2437. 'ha': 'hau',
  2438. 'he': 'heb',
  2439. 'hi': 'hin',
  2440. 'ho': 'hmo',
  2441. 'hr': 'hrv',
  2442. 'ht': 'hat',
  2443. 'hu': 'hun',
  2444. 'hy': 'hye',
  2445. 'hz': 'her',
  2446. 'ia': 'ina',
  2447. 'id': 'ind',
  2448. 'ie': 'ile',
  2449. 'ig': 'ibo',
  2450. 'ii': 'iii',
  2451. 'ik': 'ipk',
  2452. 'io': 'ido',
  2453. 'is': 'isl',
  2454. 'it': 'ita',
  2455. 'iu': 'iku',
  2456. 'ja': 'jpn',
  2457. 'jv': 'jav',
  2458. 'ka': 'kat',
  2459. 'kg': 'kon',
  2460. 'ki': 'kik',
  2461. 'kj': 'kua',
  2462. 'kk': 'kaz',
  2463. 'kl': 'kal',
  2464. 'km': 'khm',
  2465. 'kn': 'kan',
  2466. 'ko': 'kor',
  2467. 'kr': 'kau',
  2468. 'ks': 'kas',
  2469. 'ku': 'kur',
  2470. 'kv': 'kom',
  2471. 'kw': 'cor',
  2472. 'ky': 'kir',
  2473. 'la': 'lat',
  2474. 'lb': 'ltz',
  2475. 'lg': 'lug',
  2476. 'li': 'lim',
  2477. 'ln': 'lin',
  2478. 'lo': 'lao',
  2479. 'lt': 'lit',
  2480. 'lu': 'lub',
  2481. 'lv': 'lav',
  2482. 'mg': 'mlg',
  2483. 'mh': 'mah',
  2484. 'mi': 'mri',
  2485. 'mk': 'mkd',
  2486. 'ml': 'mal',
  2487. 'mn': 'mon',
  2488. 'mr': 'mar',
  2489. 'ms': 'msa',
  2490. 'mt': 'mlt',
  2491. 'my': 'mya',
  2492. 'na': 'nau',
  2493. 'nb': 'nob',
  2494. 'nd': 'nde',
  2495. 'ne': 'nep',
  2496. 'ng': 'ndo',
  2497. 'nl': 'nld',
  2498. 'nn': 'nno',
  2499. 'no': 'nor',
  2500. 'nr': 'nbl',
  2501. 'nv': 'nav',
  2502. 'ny': 'nya',
  2503. 'oc': 'oci',
  2504. 'oj': 'oji',
  2505. 'om': 'orm',
  2506. 'or': 'ori',
  2507. 'os': 'oss',
  2508. 'pa': 'pan',
  2509. 'pi': 'pli',
  2510. 'pl': 'pol',
  2511. 'ps': 'pus',
  2512. 'pt': 'por',
  2513. 'qu': 'que',
  2514. 'rm': 'roh',
  2515. 'rn': 'run',
  2516. 'ro': 'ron',
  2517. 'ru': 'rus',
  2518. 'rw': 'kin',
  2519. 'sa': 'san',
  2520. 'sc': 'srd',
  2521. 'sd': 'snd',
  2522. 'se': 'sme',
  2523. 'sg': 'sag',
  2524. 'si': 'sin',
  2525. 'sk': 'slk',
  2526. 'sl': 'slv',
  2527. 'sm': 'smo',
  2528. 'sn': 'sna',
  2529. 'so': 'som',
  2530. 'sq': 'sqi',
  2531. 'sr': 'srp',
  2532. 'ss': 'ssw',
  2533. 'st': 'sot',
  2534. 'su': 'sun',
  2535. 'sv': 'swe',
  2536. 'sw': 'swa',
  2537. 'ta': 'tam',
  2538. 'te': 'tel',
  2539. 'tg': 'tgk',
  2540. 'th': 'tha',
  2541. 'ti': 'tir',
  2542. 'tk': 'tuk',
  2543. 'tl': 'tgl',
  2544. 'tn': 'tsn',
  2545. 'to': 'ton',
  2546. 'tr': 'tur',
  2547. 'ts': 'tso',
  2548. 'tt': 'tat',
  2549. 'tw': 'twi',
  2550. 'ty': 'tah',
  2551. 'ug': 'uig',
  2552. 'uk': 'ukr',
  2553. 'ur': 'urd',
  2554. 'uz': 'uzb',
  2555. 've': 'ven',
  2556. 'vi': 'vie',
  2557. 'vo': 'vol',
  2558. 'wa': 'wln',
  2559. 'wo': 'wol',
  2560. 'xh': 'xho',
  2561. 'yi': 'yid',
  2562. 'yo': 'yor',
  2563. 'za': 'zha',
  2564. 'zh': 'zho',
  2565. 'zu': 'zul',
  2566. }
  2567. @classmethod
  2568. def short2long(cls, code):
  2569. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  2570. return cls._lang_map.get(code[:2])
  2571. @classmethod
  2572. def long2short(cls, code):
  2573. """Convert language code from ISO 639-2/T to ISO 639-1"""
  2574. for short_name, long_name in cls._lang_map.items():
  2575. if long_name == code:
  2576. return short_name
  2577. class ISO3166Utils(object):
  2578. # From http://data.okfn.org/data/core/country-list
  2579. _country_map = {
  2580. 'AF': 'Afghanistan',
  2581. 'AX': 'Åland Islands',
  2582. 'AL': 'Albania',
  2583. 'DZ': 'Algeria',
  2584. 'AS': 'American Samoa',
  2585. 'AD': 'Andorra',
  2586. 'AO': 'Angola',
  2587. 'AI': 'Anguilla',
  2588. 'AQ': 'Antarctica',
  2589. 'AG': 'Antigua and Barbuda',
  2590. 'AR': 'Argentina',
  2591. 'AM': 'Armenia',
  2592. 'AW': 'Aruba',
  2593. 'AU': 'Australia',
  2594. 'AT': 'Austria',
  2595. 'AZ': 'Azerbaijan',
  2596. 'BS': 'Bahamas',
  2597. 'BH': 'Bahrain',
  2598. 'BD': 'Bangladesh',
  2599. 'BB': 'Barbados',
  2600. 'BY': 'Belarus',
  2601. 'BE': 'Belgium',
  2602. 'BZ': 'Belize',
  2603. 'BJ': 'Benin',
  2604. 'BM': 'Bermuda',
  2605. 'BT': 'Bhutan',
  2606. 'BO': 'Bolivia, Plurinational State of',
  2607. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  2608. 'BA': 'Bosnia and Herzegovina',
  2609. 'BW': 'Botswana',
  2610. 'BV': 'Bouvet Island',
  2611. 'BR': 'Brazil',
  2612. 'IO': 'British Indian Ocean Territory',
  2613. 'BN': 'Brunei Darussalam',
  2614. 'BG': 'Bulgaria',
  2615. 'BF': 'Burkina Faso',
  2616. 'BI': 'Burundi',
  2617. 'KH': 'Cambodia',
  2618. 'CM': 'Cameroon',
  2619. 'CA': 'Canada',
  2620. 'CV': 'Cape Verde',
  2621. 'KY': 'Cayman Islands',
  2622. 'CF': 'Central African Republic',
  2623. 'TD': 'Chad',
  2624. 'CL': 'Chile',
  2625. 'CN': 'China',
  2626. 'CX': 'Christmas Island',
  2627. 'CC': 'Cocos (Keeling) Islands',
  2628. 'CO': 'Colombia',
  2629. 'KM': 'Comoros',
  2630. 'CG': 'Congo',
  2631. 'CD': 'Congo, the Democratic Republic of the',
  2632. 'CK': 'Cook Islands',
  2633. 'CR': 'Costa Rica',
  2634. 'CI': 'Côte d\'Ivoire',
  2635. 'HR': 'Croatia',
  2636. 'CU': 'Cuba',
  2637. 'CW': 'Curaçao',
  2638. 'CY': 'Cyprus',
  2639. 'CZ': 'Czech Republic',
  2640. 'DK': 'Denmark',
  2641. 'DJ': 'Djibouti',
  2642. 'DM': 'Dominica',
  2643. 'DO': 'Dominican Republic',
  2644. 'EC': 'Ecuador',
  2645. 'EG': 'Egypt',
  2646. 'SV': 'El Salvador',
  2647. 'GQ': 'Equatorial Guinea',
  2648. 'ER': 'Eritrea',
  2649. 'EE': 'Estonia',
  2650. 'ET': 'Ethiopia',
  2651. 'FK': 'Falkland Islands (Malvinas)',
  2652. 'FO': 'Faroe Islands',
  2653. 'FJ': 'Fiji',
  2654. 'FI': 'Finland',
  2655. 'FR': 'France',
  2656. 'GF': 'French Guiana',
  2657. 'PF': 'French Polynesia',
  2658. 'TF': 'French Southern Territories',
  2659. 'GA': 'Gabon',
  2660. 'GM': 'Gambia',
  2661. 'GE': 'Georgia',
  2662. 'DE': 'Germany',
  2663. 'GH': 'Ghana',
  2664. 'GI': 'Gibraltar',
  2665. 'GR': 'Greece',
  2666. 'GL': 'Greenland',
  2667. 'GD': 'Grenada',
  2668. 'GP': 'Guadeloupe',
  2669. 'GU': 'Guam',
  2670. 'GT': 'Guatemala',
  2671. 'GG': 'Guernsey',
  2672. 'GN': 'Guinea',
  2673. 'GW': 'Guinea-Bissau',
  2674. 'GY': 'Guyana',
  2675. 'HT': 'Haiti',
  2676. 'HM': 'Heard Island and McDonald Islands',
  2677. 'VA': 'Holy See (Vatican City State)',
  2678. 'HN': 'Honduras',
  2679. 'HK': 'Hong Kong',
  2680. 'HU': 'Hungary',
  2681. 'IS': 'Iceland',
  2682. 'IN': 'India',
  2683. 'ID': 'Indonesia',
  2684. 'IR': 'Iran, Islamic Republic of',
  2685. 'IQ': 'Iraq',
  2686. 'IE': 'Ireland',
  2687. 'IM': 'Isle of Man',
  2688. 'IL': 'Israel',
  2689. 'IT': 'Italy',
  2690. 'JM': 'Jamaica',
  2691. 'JP': 'Japan',
  2692. 'JE': 'Jersey',
  2693. 'JO': 'Jordan',
  2694. 'KZ': 'Kazakhstan',
  2695. 'KE': 'Kenya',
  2696. 'KI': 'Kiribati',
  2697. 'KP': 'Korea, Democratic People\'s Republic of',
  2698. 'KR': 'Korea, Republic of',
  2699. 'KW': 'Kuwait',
  2700. 'KG': 'Kyrgyzstan',
  2701. 'LA': 'Lao People\'s Democratic Republic',
  2702. 'LV': 'Latvia',
  2703. 'LB': 'Lebanon',
  2704. 'LS': 'Lesotho',
  2705. 'LR': 'Liberia',
  2706. 'LY': 'Libya',
  2707. 'LI': 'Liechtenstein',
  2708. 'LT': 'Lithuania',
  2709. 'LU': 'Luxembourg',
  2710. 'MO': 'Macao',
  2711. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  2712. 'MG': 'Madagascar',
  2713. 'MW': 'Malawi',
  2714. 'MY': 'Malaysia',
  2715. 'MV': 'Maldives',
  2716. 'ML': 'Mali',
  2717. 'MT': 'Malta',
  2718. 'MH': 'Marshall Islands',
  2719. 'MQ': 'Martinique',
  2720. 'MR': 'Mauritania',
  2721. 'MU': 'Mauritius',
  2722. 'YT': 'Mayotte',
  2723. 'MX': 'Mexico',
  2724. 'FM': 'Micronesia, Federated States of',
  2725. 'MD': 'Moldova, Republic of',
  2726. 'MC': 'Monaco',
  2727. 'MN': 'Mongolia',
  2728. 'ME': 'Montenegro',
  2729. 'MS': 'Montserrat',
  2730. 'MA': 'Morocco',
  2731. 'MZ': 'Mozambique',
  2732. 'MM': 'Myanmar',
  2733. 'NA': 'Namibia',
  2734. 'NR': 'Nauru',
  2735. 'NP': 'Nepal',
  2736. 'NL': 'Netherlands',
  2737. 'NC': 'New Caledonia',
  2738. 'NZ': 'New Zealand',
  2739. 'NI': 'Nicaragua',
  2740. 'NE': 'Niger',
  2741. 'NG': 'Nigeria',
  2742. 'NU': 'Niue',
  2743. 'NF': 'Norfolk Island',
  2744. 'MP': 'Northern Mariana Islands',
  2745. 'NO': 'Norway',
  2746. 'OM': 'Oman',
  2747. 'PK': 'Pakistan',
  2748. 'PW': 'Palau',
  2749. 'PS': 'Palestine, State of',
  2750. 'PA': 'Panama',
  2751. 'PG': 'Papua New Guinea',
  2752. 'PY': 'Paraguay',
  2753. 'PE': 'Peru',
  2754. 'PH': 'Philippines',
  2755. 'PN': 'Pitcairn',
  2756. 'PL': 'Poland',
  2757. 'PT': 'Portugal',
  2758. 'PR': 'Puerto Rico',
  2759. 'QA': 'Qatar',
  2760. 'RE': 'Réunion',
  2761. 'RO': 'Romania',
  2762. 'RU': 'Russian Federation',
  2763. 'RW': 'Rwanda',
  2764. 'BL': 'Saint Barthélemy',
  2765. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  2766. 'KN': 'Saint Kitts and Nevis',
  2767. 'LC': 'Saint Lucia',
  2768. 'MF': 'Saint Martin (French part)',
  2769. 'PM': 'Saint Pierre and Miquelon',
  2770. 'VC': 'Saint Vincent and the Grenadines',
  2771. 'WS': 'Samoa',
  2772. 'SM': 'San Marino',
  2773. 'ST': 'Sao Tome and Principe',
  2774. 'SA': 'Saudi Arabia',
  2775. 'SN': 'Senegal',
  2776. 'RS': 'Serbia',
  2777. 'SC': 'Seychelles',
  2778. 'SL': 'Sierra Leone',
  2779. 'SG': 'Singapore',
  2780. 'SX': 'Sint Maarten (Dutch part)',
  2781. 'SK': 'Slovakia',
  2782. 'SI': 'Slovenia',
  2783. 'SB': 'Solomon Islands',
  2784. 'SO': 'Somalia',
  2785. 'ZA': 'South Africa',
  2786. 'GS': 'South Georgia and the South Sandwich Islands',
  2787. 'SS': 'South Sudan',
  2788. 'ES': 'Spain',
  2789. 'LK': 'Sri Lanka',
  2790. 'SD': 'Sudan',
  2791. 'SR': 'Suriname',
  2792. 'SJ': 'Svalbard and Jan Mayen',
  2793. 'SZ': 'Swaziland',
  2794. 'SE': 'Sweden',
  2795. 'CH': 'Switzerland',
  2796. 'SY': 'Syrian Arab Republic',
  2797. 'TW': 'Taiwan, Province of China',
  2798. 'TJ': 'Tajikistan',
  2799. 'TZ': 'Tanzania, United Republic of',
  2800. 'TH': 'Thailand',
  2801. 'TL': 'Timor-Leste',
  2802. 'TG': 'Togo',
  2803. 'TK': 'Tokelau',
  2804. 'TO': 'Tonga',
  2805. 'TT': 'Trinidad and Tobago',
  2806. 'TN': 'Tunisia',
  2807. 'TR': 'Turkey',
  2808. 'TM': 'Turkmenistan',
  2809. 'TC': 'Turks and Caicos Islands',
  2810. 'TV': 'Tuvalu',
  2811. 'UG': 'Uganda',
  2812. 'UA': 'Ukraine',
  2813. 'AE': 'United Arab Emirates',
  2814. 'GB': 'United Kingdom',
  2815. 'US': 'United States',
  2816. 'UM': 'United States Minor Outlying Islands',
  2817. 'UY': 'Uruguay',
  2818. 'UZ': 'Uzbekistan',
  2819. 'VU': 'Vanuatu',
  2820. 'VE': 'Venezuela, Bolivarian Republic of',
  2821. 'VN': 'Viet Nam',
  2822. 'VG': 'Virgin Islands, British',
  2823. 'VI': 'Virgin Islands, U.S.',
  2824. 'WF': 'Wallis and Futuna',
  2825. 'EH': 'Western Sahara',
  2826. 'YE': 'Yemen',
  2827. 'ZM': 'Zambia',
  2828. 'ZW': 'Zimbabwe',
  2829. }
  2830. @classmethod
  2831. def short2full(cls, code):
  2832. """Convert an ISO 3166-2 country code to the corresponding full name"""
  2833. return cls._country_map.get(code.upper())
  2834. class GeoUtils(object):
  2835. # Major IPv4 address blocks per country
  2836. _country_ip_map = {
  2837. 'AD': '85.94.160.0/19',
  2838. 'AE': '94.200.0.0/13',
  2839. 'AF': '149.54.0.0/17',
  2840. 'AG': '209.59.64.0/18',
  2841. 'AI': '204.14.248.0/21',
  2842. 'AL': '46.99.0.0/16',
  2843. 'AM': '46.70.0.0/15',
  2844. 'AO': '105.168.0.0/13',
  2845. 'AP': '159.117.192.0/21',
  2846. 'AR': '181.0.0.0/12',
  2847. 'AS': '202.70.112.0/20',
  2848. 'AT': '84.112.0.0/13',
  2849. 'AU': '1.128.0.0/11',
  2850. 'AW': '181.41.0.0/18',
  2851. 'AZ': '5.191.0.0/16',
  2852. 'BA': '31.176.128.0/17',
  2853. 'BB': '65.48.128.0/17',
  2854. 'BD': '114.130.0.0/16',
  2855. 'BE': '57.0.0.0/8',
  2856. 'BF': '129.45.128.0/17',
  2857. 'BG': '95.42.0.0/15',
  2858. 'BH': '37.131.0.0/17',
  2859. 'BI': '154.117.192.0/18',
  2860. 'BJ': '137.255.0.0/16',
  2861. 'BL': '192.131.134.0/24',
  2862. 'BM': '196.12.64.0/18',
  2863. 'BN': '156.31.0.0/16',
  2864. 'BO': '161.56.0.0/16',
  2865. 'BQ': '161.0.80.0/20',
  2866. 'BR': '152.240.0.0/12',
  2867. 'BS': '24.51.64.0/18',
  2868. 'BT': '119.2.96.0/19',
  2869. 'BW': '168.167.0.0/16',
  2870. 'BY': '178.120.0.0/13',
  2871. 'BZ': '179.42.192.0/18',
  2872. 'CA': '99.224.0.0/11',
  2873. 'CD': '41.243.0.0/16',
  2874. 'CF': '196.32.200.0/21',
  2875. 'CG': '197.214.128.0/17',
  2876. 'CH': '85.0.0.0/13',
  2877. 'CI': '154.232.0.0/14',
  2878. 'CK': '202.65.32.0/19',
  2879. 'CL': '152.172.0.0/14',
  2880. 'CM': '165.210.0.0/15',
  2881. 'CN': '36.128.0.0/10',
  2882. 'CO': '181.240.0.0/12',
  2883. 'CR': '201.192.0.0/12',
  2884. 'CU': '152.206.0.0/15',
  2885. 'CV': '165.90.96.0/19',
  2886. 'CW': '190.88.128.0/17',
  2887. 'CY': '46.198.0.0/15',
  2888. 'CZ': '88.100.0.0/14',
  2889. 'DE': '53.0.0.0/8',
  2890. 'DJ': '197.241.0.0/17',
  2891. 'DK': '87.48.0.0/12',
  2892. 'DM': '192.243.48.0/20',
  2893. 'DO': '152.166.0.0/15',
  2894. 'DZ': '41.96.0.0/12',
  2895. 'EC': '186.68.0.0/15',
  2896. 'EE': '90.190.0.0/15',
  2897. 'EG': '156.160.0.0/11',
  2898. 'ER': '196.200.96.0/20',
  2899. 'ES': '88.0.0.0/11',
  2900. 'ET': '196.188.0.0/14',
  2901. 'EU': '2.16.0.0/13',
  2902. 'FI': '91.152.0.0/13',
  2903. 'FJ': '144.120.0.0/16',
  2904. 'FM': '119.252.112.0/20',
  2905. 'FO': '88.85.32.0/19',
  2906. 'FR': '90.0.0.0/9',
  2907. 'GA': '41.158.0.0/15',
  2908. 'GB': '25.0.0.0/8',
  2909. 'GD': '74.122.88.0/21',
  2910. 'GE': '31.146.0.0/16',
  2911. 'GF': '161.22.64.0/18',
  2912. 'GG': '62.68.160.0/19',
  2913. 'GH': '45.208.0.0/14',
  2914. 'GI': '85.115.128.0/19',
  2915. 'GL': '88.83.0.0/19',
  2916. 'GM': '160.182.0.0/15',
  2917. 'GN': '197.149.192.0/18',
  2918. 'GP': '104.250.0.0/19',
  2919. 'GQ': '105.235.224.0/20',
  2920. 'GR': '94.64.0.0/13',
  2921. 'GT': '168.234.0.0/16',
  2922. 'GU': '168.123.0.0/16',
  2923. 'GW': '197.214.80.0/20',
  2924. 'GY': '181.41.64.0/18',
  2925. 'HK': '113.252.0.0/14',
  2926. 'HN': '181.210.0.0/16',
  2927. 'HR': '93.136.0.0/13',
  2928. 'HT': '148.102.128.0/17',
  2929. 'HU': '84.0.0.0/14',
  2930. 'ID': '39.192.0.0/10',
  2931. 'IE': '87.32.0.0/12',
  2932. 'IL': '79.176.0.0/13',
  2933. 'IM': '5.62.80.0/20',
  2934. 'IN': '117.192.0.0/10',
  2935. 'IO': '203.83.48.0/21',
  2936. 'IQ': '37.236.0.0/14',
  2937. 'IR': '2.176.0.0/12',
  2938. 'IS': '82.221.0.0/16',
  2939. 'IT': '79.0.0.0/10',
  2940. 'JE': '87.244.64.0/18',
  2941. 'JM': '72.27.0.0/17',
  2942. 'JO': '176.29.0.0/16',
  2943. 'JP': '126.0.0.0/8',
  2944. 'KE': '105.48.0.0/12',
  2945. 'KG': '158.181.128.0/17',
  2946. 'KH': '36.37.128.0/17',
  2947. 'KI': '103.25.140.0/22',
  2948. 'KM': '197.255.224.0/20',
  2949. 'KN': '198.32.32.0/19',
  2950. 'KP': '175.45.176.0/22',
  2951. 'KR': '175.192.0.0/10',
  2952. 'KW': '37.36.0.0/14',
  2953. 'KY': '64.96.0.0/15',
  2954. 'KZ': '2.72.0.0/13',
  2955. 'LA': '115.84.64.0/18',
  2956. 'LB': '178.135.0.0/16',
  2957. 'LC': '192.147.231.0/24',
  2958. 'LI': '82.117.0.0/19',
  2959. 'LK': '112.134.0.0/15',
  2960. 'LR': '41.86.0.0/19',
  2961. 'LS': '129.232.0.0/17',
  2962. 'LT': '78.56.0.0/13',
  2963. 'LU': '188.42.0.0/16',
  2964. 'LV': '46.109.0.0/16',
  2965. 'LY': '41.252.0.0/14',
  2966. 'MA': '105.128.0.0/11',
  2967. 'MC': '88.209.64.0/18',
  2968. 'MD': '37.246.0.0/16',
  2969. 'ME': '178.175.0.0/17',
  2970. 'MF': '74.112.232.0/21',
  2971. 'MG': '154.126.0.0/17',
  2972. 'MH': '117.103.88.0/21',
  2973. 'MK': '77.28.0.0/15',
  2974. 'ML': '154.118.128.0/18',
  2975. 'MM': '37.111.0.0/17',
  2976. 'MN': '49.0.128.0/17',
  2977. 'MO': '60.246.0.0/16',
  2978. 'MP': '202.88.64.0/20',
  2979. 'MQ': '109.203.224.0/19',
  2980. 'MR': '41.188.64.0/18',
  2981. 'MS': '208.90.112.0/22',
  2982. 'MT': '46.11.0.0/16',
  2983. 'MU': '105.16.0.0/12',
  2984. 'MV': '27.114.128.0/18',
  2985. 'MW': '105.234.0.0/16',
  2986. 'MX': '187.192.0.0/11',
  2987. 'MY': '175.136.0.0/13',
  2988. 'MZ': '197.218.0.0/15',
  2989. 'NA': '41.182.0.0/16',
  2990. 'NC': '101.101.0.0/18',
  2991. 'NE': '197.214.0.0/18',
  2992. 'NF': '203.17.240.0/22',
  2993. 'NG': '105.112.0.0/12',
  2994. 'NI': '186.76.0.0/15',
  2995. 'NL': '145.96.0.0/11',
  2996. 'NO': '84.208.0.0/13',
  2997. 'NP': '36.252.0.0/15',
  2998. 'NR': '203.98.224.0/19',
  2999. 'NU': '49.156.48.0/22',
  3000. 'NZ': '49.224.0.0/14',
  3001. 'OM': '5.36.0.0/15',
  3002. 'PA': '186.72.0.0/15',
  3003. 'PE': '186.160.0.0/14',
  3004. 'PF': '123.50.64.0/18',
  3005. 'PG': '124.240.192.0/19',
  3006. 'PH': '49.144.0.0/13',
  3007. 'PK': '39.32.0.0/11',
  3008. 'PL': '83.0.0.0/11',
  3009. 'PM': '70.36.0.0/20',
  3010. 'PR': '66.50.0.0/16',
  3011. 'PS': '188.161.0.0/16',
  3012. 'PT': '85.240.0.0/13',
  3013. 'PW': '202.124.224.0/20',
  3014. 'PY': '181.120.0.0/14',
  3015. 'QA': '37.210.0.0/15',
  3016. 'RE': '139.26.0.0/16',
  3017. 'RO': '79.112.0.0/13',
  3018. 'RS': '178.220.0.0/14',
  3019. 'RU': '5.136.0.0/13',
  3020. 'RW': '105.178.0.0/15',
  3021. 'SA': '188.48.0.0/13',
  3022. 'SB': '202.1.160.0/19',
  3023. 'SC': '154.192.0.0/11',
  3024. 'SD': '154.96.0.0/13',
  3025. 'SE': '78.64.0.0/12',
  3026. 'SG': '152.56.0.0/14',
  3027. 'SI': '188.196.0.0/14',
  3028. 'SK': '78.98.0.0/15',
  3029. 'SL': '197.215.0.0/17',
  3030. 'SM': '89.186.32.0/19',
  3031. 'SN': '41.82.0.0/15',
  3032. 'SO': '197.220.64.0/19',
  3033. 'SR': '186.179.128.0/17',
  3034. 'SS': '105.235.208.0/21',
  3035. 'ST': '197.159.160.0/19',
  3036. 'SV': '168.243.0.0/16',
  3037. 'SX': '190.102.0.0/20',
  3038. 'SY': '5.0.0.0/16',
  3039. 'SZ': '41.84.224.0/19',
  3040. 'TC': '65.255.48.0/20',
  3041. 'TD': '154.68.128.0/19',
  3042. 'TG': '196.168.0.0/14',
  3043. 'TH': '171.96.0.0/13',
  3044. 'TJ': '85.9.128.0/18',
  3045. 'TK': '27.96.24.0/21',
  3046. 'TL': '180.189.160.0/20',
  3047. 'TM': '95.85.96.0/19',
  3048. 'TN': '197.0.0.0/11',
  3049. 'TO': '175.176.144.0/21',
  3050. 'TR': '78.160.0.0/11',
  3051. 'TT': '186.44.0.0/15',
  3052. 'TV': '202.2.96.0/19',
  3053. 'TW': '120.96.0.0/11',
  3054. 'TZ': '156.156.0.0/14',
  3055. 'UA': '93.72.0.0/13',
  3056. 'UG': '154.224.0.0/13',
  3057. 'US': '3.0.0.0/8',
  3058. 'UY': '167.56.0.0/13',
  3059. 'UZ': '82.215.64.0/18',
  3060. 'VA': '212.77.0.0/19',
  3061. 'VC': '24.92.144.0/20',
  3062. 'VE': '186.88.0.0/13',
  3063. 'VG': '172.103.64.0/18',
  3064. 'VI': '146.226.0.0/16',
  3065. 'VN': '14.160.0.0/11',
  3066. 'VU': '202.80.32.0/20',
  3067. 'WF': '117.20.32.0/21',
  3068. 'WS': '202.4.32.0/19',
  3069. 'YE': '134.35.0.0/16',
  3070. 'YT': '41.242.116.0/22',
  3071. 'ZA': '41.0.0.0/11',
  3072. 'ZM': '165.56.0.0/13',
  3073. 'ZW': '41.85.192.0/19',
  3074. }
  3075. @classmethod
  3076. def random_ipv4(cls, code_or_block):
  3077. if len(code_or_block) == 2:
  3078. block = cls._country_ip_map.get(code_or_block.upper())
  3079. if not block:
  3080. return None
  3081. else:
  3082. block = code_or_block
  3083. addr, preflen = block.split('/')
  3084. addr_min = compat_struct_unpack('!L', socket.inet_aton(addr))[0]
  3085. addr_max = addr_min | (0xffffffff >> int(preflen))
  3086. return compat_str(socket.inet_ntoa(
  3087. compat_struct_pack('!L', random.randint(addr_min, addr_max))))
  3088. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  3089. def __init__(self, proxies=None):
  3090. # Set default handlers
  3091. for type in ('http', 'https'):
  3092. setattr(self, '%s_open' % type,
  3093. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  3094. meth(r, proxy, type))
  3095. compat_urllib_request.ProxyHandler.__init__(self, proxies)
  3096. def proxy_open(self, req, proxy, type):
  3097. req_proxy = req.headers.get('Ytdl-request-proxy')
  3098. if req_proxy is not None:
  3099. proxy = req_proxy
  3100. del req.headers['Ytdl-request-proxy']
  3101. if proxy == '__noproxy__':
  3102. return None # No Proxy
  3103. if compat_urlparse.urlparse(proxy).scheme.lower() in ('socks', 'socks4', 'socks4a', 'socks5'):
  3104. req.add_header('Ytdl-socks-proxy', proxy)
  3105. # youtube-dl's http/https handlers do wrapping the socket with socks
  3106. return None
  3107. return compat_urllib_request.ProxyHandler.proxy_open(
  3108. self, req, proxy, type)
  3109. # Both long_to_bytes and bytes_to_long are adapted from PyCrypto, which is
  3110. # released into Public Domain
  3111. # https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Util/number.py#L387
  3112. def long_to_bytes(n, blocksize=0):
  3113. """long_to_bytes(n:long, blocksize:int) : string
  3114. Convert a long integer to a byte string.
  3115. If optional blocksize is given and greater than zero, pad the front of the
  3116. byte string with binary zeros so that the length is a multiple of
  3117. blocksize.
  3118. """
  3119. # after much testing, this algorithm was deemed to be the fastest
  3120. s = b''
  3121. n = int(n)
  3122. while n > 0:
  3123. s = compat_struct_pack('>I', n & 0xffffffff) + s
  3124. n = n >> 32
  3125. # strip off leading zeros
  3126. for i in range(len(s)):
  3127. if s[i] != b'\000'[0]:
  3128. break
  3129. else:
  3130. # only happens when n == 0
  3131. s = b'\000'
  3132. i = 0
  3133. s = s[i:]
  3134. # add back some pad bytes. this could be done more efficiently w.r.t. the
  3135. # de-padding being done above, but sigh...
  3136. if blocksize > 0 and len(s) % blocksize:
  3137. s = (blocksize - len(s) % blocksize) * b'\000' + s
  3138. return s
  3139. def bytes_to_long(s):
  3140. """bytes_to_long(string) : long
  3141. Convert a byte string to a long integer.
  3142. This is (essentially) the inverse of long_to_bytes().
  3143. """
  3144. acc = 0
  3145. length = len(s)
  3146. if length % 4:
  3147. extra = (4 - length % 4)
  3148. s = b'\000' * extra + s
  3149. length = length + extra
  3150. for i in range(0, length, 4):
  3151. acc = (acc << 32) + compat_struct_unpack('>I', s[i:i + 4])[0]
  3152. return acc
  3153. def ohdave_rsa_encrypt(data, exponent, modulus):
  3154. '''
  3155. Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
  3156. Input:
  3157. data: data to encrypt, bytes-like object
  3158. exponent, modulus: parameter e and N of RSA algorithm, both integer
  3159. Output: hex string of encrypted data
  3160. Limitation: supports one block encryption only
  3161. '''
  3162. payload = int(binascii.hexlify(data[::-1]), 16)
  3163. encrypted = pow(payload, exponent, modulus)
  3164. return '%x' % encrypted
  3165. def pkcs1pad(data, length):
  3166. """
  3167. Padding input data with PKCS#1 scheme
  3168. @param {int[]} data input data
  3169. @param {int} length target length
  3170. @returns {int[]} padded data
  3171. """
  3172. if len(data) > length - 11:
  3173. raise ValueError('Input data too long for PKCS#1 padding')
  3174. pseudo_random = [random.randint(0, 254) for _ in range(length - len(data) - 3)]
  3175. return [0, 2] + pseudo_random + [0] + data
  3176. def encode_base_n(num, n, table=None):
  3177. FULL_TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  3178. if not table:
  3179. table = FULL_TABLE[:n]
  3180. if n > len(table):
  3181. raise ValueError('base %d exceeds table length %d' % (n, len(table)))
  3182. if num == 0:
  3183. return table[0]
  3184. ret = ''
  3185. while num:
  3186. ret = table[num % n] + ret
  3187. num = num // n
  3188. return ret
  3189. def decode_packed_codes(code):
  3190. mobj = re.search(PACKED_CODES_RE, code)
  3191. obfucasted_code, base, count, symbols = mobj.groups()
  3192. base = int(base)
  3193. count = int(count)
  3194. symbols = symbols.split('|')
  3195. symbol_table = {}
  3196. while count:
  3197. count -= 1
  3198. base_n_count = encode_base_n(count, base)
  3199. symbol_table[base_n_count] = symbols[count] or base_n_count
  3200. return re.sub(
  3201. r'\b(\w+)\b', lambda mobj: symbol_table[mobj.group(0)],
  3202. obfucasted_code)
  3203. def parse_m3u8_attributes(attrib):
  3204. info = {}
  3205. for (key, val) in re.findall(r'(?P<key>[A-Z0-9-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)', attrib):
  3206. if val.startswith('"'):
  3207. val = val[1:-1]
  3208. info[key] = val
  3209. return info
  3210. def urshift(val, n):
  3211. return val >> n if val >= 0 else (val + 0x100000000) >> n
  3212. # Based on png2str() written by @gdkchan and improved by @yokrysty
  3213. # Originally posted at https://github.com/rg3/youtube-dl/issues/9706
  3214. def decode_png(png_data):
  3215. # Reference: https://www.w3.org/TR/PNG/
  3216. header = png_data[8:]
  3217. if png_data[:8] != b'\x89PNG\x0d\x0a\x1a\x0a' or header[4:8] != b'IHDR':
  3218. raise IOError('Not a valid PNG file.')
  3219. int_map = {1: '>B', 2: '>H', 4: '>I'}
  3220. unpack_integer = lambda x: compat_struct_unpack(int_map[len(x)], x)[0]
  3221. chunks = []
  3222. while header:
  3223. length = unpack_integer(header[:4])
  3224. header = header[4:]
  3225. chunk_type = header[:4]
  3226. header = header[4:]
  3227. chunk_data = header[:length]
  3228. header = header[length:]
  3229. header = header[4:] # Skip CRC
  3230. chunks.append({
  3231. 'type': chunk_type,
  3232. 'length': length,
  3233. 'data': chunk_data
  3234. })
  3235. ihdr = chunks[0]['data']
  3236. width = unpack_integer(ihdr[:4])
  3237. height = unpack_integer(ihdr[4:8])
  3238. idat = b''
  3239. for chunk in chunks:
  3240. if chunk['type'] == b'IDAT':
  3241. idat += chunk['data']
  3242. if not idat:
  3243. raise IOError('Unable to read PNG data.')
  3244. decompressed_data = bytearray(zlib.decompress(idat))
  3245. stride = width * 3
  3246. pixels = []
  3247. def _get_pixel(idx):
  3248. x = idx % stride
  3249. y = idx // stride
  3250. return pixels[y][x]
  3251. for y in range(height):
  3252. basePos = y * (1 + stride)
  3253. filter_type = decompressed_data[basePos]
  3254. current_row = []
  3255. pixels.append(current_row)
  3256. for x in range(stride):
  3257. color = decompressed_data[1 + basePos + x]
  3258. basex = y * stride + x
  3259. left = 0
  3260. up = 0
  3261. if x > 2:
  3262. left = _get_pixel(basex - 3)
  3263. if y > 0:
  3264. up = _get_pixel(basex - stride)
  3265. if filter_type == 1: # Sub
  3266. color = (color + left) & 0xff
  3267. elif filter_type == 2: # Up
  3268. color = (color + up) & 0xff
  3269. elif filter_type == 3: # Average
  3270. color = (color + ((left + up) >> 1)) & 0xff
  3271. elif filter_type == 4: # Paeth
  3272. a = left
  3273. b = up
  3274. c = 0
  3275. if x > 2 and y > 0:
  3276. c = _get_pixel(basex - stride - 3)
  3277. p = a + b - c
  3278. pa = abs(p - a)
  3279. pb = abs(p - b)
  3280. pc = abs(p - c)
  3281. if pa <= pb and pa <= pc:
  3282. color = (color + a) & 0xff
  3283. elif pb <= pc:
  3284. color = (color + b) & 0xff
  3285. else:
  3286. color = (color + c) & 0xff
  3287. current_row.append(color)
  3288. return width, height, pixels
  3289. def write_xattr(path, key, value):
  3290. # This mess below finds the best xattr tool for the job
  3291. try:
  3292. # try the pyxattr module...
  3293. import xattr
  3294. if hasattr(xattr, 'set'): # pyxattr
  3295. # Unicode arguments are not supported in python-pyxattr until
  3296. # version 0.5.0
  3297. # See https://github.com/rg3/youtube-dl/issues/5498
  3298. pyxattr_required_version = '0.5.0'
  3299. if version_tuple(xattr.__version__) < version_tuple(pyxattr_required_version):
  3300. # TODO: fallback to CLI tools
  3301. raise XAttrUnavailableError(
  3302. 'python-pyxattr is detected but is too old. '
  3303. 'youtube-dl requires %s or above while your version is %s. '
  3304. 'Falling back to other xattr implementations' % (
  3305. pyxattr_required_version, xattr.__version__))
  3306. setxattr = xattr.set
  3307. else: # xattr
  3308. setxattr = xattr.setxattr
  3309. try:
  3310. setxattr(path, key, value)
  3311. except EnvironmentError as e:
  3312. raise XAttrMetadataError(e.errno, e.strerror)
  3313. except ImportError:
  3314. if compat_os_name == 'nt':
  3315. # Write xattrs to NTFS Alternate Data Streams:
  3316. # http://en.wikipedia.org/wiki/NTFS#Alternate_data_streams_.28ADS.29
  3317. assert ':' not in key
  3318. assert os.path.exists(path)
  3319. ads_fn = path + ':' + key
  3320. try:
  3321. with open(ads_fn, 'wb') as f:
  3322. f.write(value)
  3323. except EnvironmentError as e:
  3324. raise XAttrMetadataError(e.errno, e.strerror)
  3325. else:
  3326. user_has_setfattr = check_executable('setfattr', ['--version'])
  3327. user_has_xattr = check_executable('xattr', ['-h'])
  3328. if user_has_setfattr or user_has_xattr:
  3329. value = value.decode('utf-8')
  3330. if user_has_setfattr:
  3331. executable = 'setfattr'
  3332. opts = ['-n', key, '-v', value]
  3333. elif user_has_xattr:
  3334. executable = 'xattr'
  3335. opts = ['-w', key, value]
  3336. cmd = ([encodeFilename(executable, True)] +
  3337. [encodeArgument(o) for o in opts] +
  3338. [encodeFilename(path, True)])
  3339. try:
  3340. p = subprocess.Popen(
  3341. cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  3342. except EnvironmentError as e:
  3343. raise XAttrMetadataError(e.errno, e.strerror)
  3344. stdout, stderr = p.communicate()
  3345. stderr = stderr.decode('utf-8', 'replace')
  3346. if p.returncode != 0:
  3347. raise XAttrMetadataError(p.returncode, stderr)
  3348. else:
  3349. # On Unix, and can't find pyxattr, setfattr, or xattr.
  3350. if sys.platform.startswith('linux'):
  3351. raise XAttrUnavailableError(
  3352. "Couldn't find a tool to set the xattrs. "
  3353. "Install either the python 'pyxattr' or 'xattr' "
  3354. "modules, or the GNU 'attr' package "
  3355. "(which contains the 'setfattr' tool).")
  3356. else:
  3357. raise XAttrUnavailableError(
  3358. "Couldn't find a tool to set the xattrs. "
  3359. "Install either the python 'xattr' module, "
  3360. "or the 'xattr' binary.")
  3361. def random_birthday(year_field, month_field, day_field):
  3362. start_date = datetime.date(1950, 1, 1)
  3363. end_date = datetime.date(1995, 12, 31)
  3364. offset = random.randint(0, (end_date - start_date).days)
  3365. random_date = start_date + datetime.timedelta(offset)
  3366. return {
  3367. year_field: str(random_date.year),
  3368. month_field: str(random_date.month),
  3369. day_field: str(random_date.day),
  3370. }