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.

3990 lines
123 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'^(?:[a-zA-Z][a-zA-Z0-9+-.]*:)?//', 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. 'iw': 'heb', # Replaced by he in 1989 revision
  2440. 'hi': 'hin',
  2441. 'ho': 'hmo',
  2442. 'hr': 'hrv',
  2443. 'ht': 'hat',
  2444. 'hu': 'hun',
  2445. 'hy': 'hye',
  2446. 'hz': 'her',
  2447. 'ia': 'ina',
  2448. 'id': 'ind',
  2449. 'in': 'ind', # Replaced by id in 1989 revision
  2450. 'ie': 'ile',
  2451. 'ig': 'ibo',
  2452. 'ii': 'iii',
  2453. 'ik': 'ipk',
  2454. 'io': 'ido',
  2455. 'is': 'isl',
  2456. 'it': 'ita',
  2457. 'iu': 'iku',
  2458. 'ja': 'jpn',
  2459. 'jv': 'jav',
  2460. 'ka': 'kat',
  2461. 'kg': 'kon',
  2462. 'ki': 'kik',
  2463. 'kj': 'kua',
  2464. 'kk': 'kaz',
  2465. 'kl': 'kal',
  2466. 'km': 'khm',
  2467. 'kn': 'kan',
  2468. 'ko': 'kor',
  2469. 'kr': 'kau',
  2470. 'ks': 'kas',
  2471. 'ku': 'kur',
  2472. 'kv': 'kom',
  2473. 'kw': 'cor',
  2474. 'ky': 'kir',
  2475. 'la': 'lat',
  2476. 'lb': 'ltz',
  2477. 'lg': 'lug',
  2478. 'li': 'lim',
  2479. 'ln': 'lin',
  2480. 'lo': 'lao',
  2481. 'lt': 'lit',
  2482. 'lu': 'lub',
  2483. 'lv': 'lav',
  2484. 'mg': 'mlg',
  2485. 'mh': 'mah',
  2486. 'mi': 'mri',
  2487. 'mk': 'mkd',
  2488. 'ml': 'mal',
  2489. 'mn': 'mon',
  2490. 'mr': 'mar',
  2491. 'ms': 'msa',
  2492. 'mt': 'mlt',
  2493. 'my': 'mya',
  2494. 'na': 'nau',
  2495. 'nb': 'nob',
  2496. 'nd': 'nde',
  2497. 'ne': 'nep',
  2498. 'ng': 'ndo',
  2499. 'nl': 'nld',
  2500. 'nn': 'nno',
  2501. 'no': 'nor',
  2502. 'nr': 'nbl',
  2503. 'nv': 'nav',
  2504. 'ny': 'nya',
  2505. 'oc': 'oci',
  2506. 'oj': 'oji',
  2507. 'om': 'orm',
  2508. 'or': 'ori',
  2509. 'os': 'oss',
  2510. 'pa': 'pan',
  2511. 'pi': 'pli',
  2512. 'pl': 'pol',
  2513. 'ps': 'pus',
  2514. 'pt': 'por',
  2515. 'qu': 'que',
  2516. 'rm': 'roh',
  2517. 'rn': 'run',
  2518. 'ro': 'ron',
  2519. 'ru': 'rus',
  2520. 'rw': 'kin',
  2521. 'sa': 'san',
  2522. 'sc': 'srd',
  2523. 'sd': 'snd',
  2524. 'se': 'sme',
  2525. 'sg': 'sag',
  2526. 'si': 'sin',
  2527. 'sk': 'slk',
  2528. 'sl': 'slv',
  2529. 'sm': 'smo',
  2530. 'sn': 'sna',
  2531. 'so': 'som',
  2532. 'sq': 'sqi',
  2533. 'sr': 'srp',
  2534. 'ss': 'ssw',
  2535. 'st': 'sot',
  2536. 'su': 'sun',
  2537. 'sv': 'swe',
  2538. 'sw': 'swa',
  2539. 'ta': 'tam',
  2540. 'te': 'tel',
  2541. 'tg': 'tgk',
  2542. 'th': 'tha',
  2543. 'ti': 'tir',
  2544. 'tk': 'tuk',
  2545. 'tl': 'tgl',
  2546. 'tn': 'tsn',
  2547. 'to': 'ton',
  2548. 'tr': 'tur',
  2549. 'ts': 'tso',
  2550. 'tt': 'tat',
  2551. 'tw': 'twi',
  2552. 'ty': 'tah',
  2553. 'ug': 'uig',
  2554. 'uk': 'ukr',
  2555. 'ur': 'urd',
  2556. 'uz': 'uzb',
  2557. 've': 'ven',
  2558. 'vi': 'vie',
  2559. 'vo': 'vol',
  2560. 'wa': 'wln',
  2561. 'wo': 'wol',
  2562. 'xh': 'xho',
  2563. 'yi': 'yid',
  2564. 'ji': 'yid', # Replaced by yi in 1989 revision
  2565. 'yo': 'yor',
  2566. 'za': 'zha',
  2567. 'zh': 'zho',
  2568. 'zu': 'zul',
  2569. }
  2570. @classmethod
  2571. def short2long(cls, code):
  2572. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  2573. return cls._lang_map.get(code[:2])
  2574. @classmethod
  2575. def long2short(cls, code):
  2576. """Convert language code from ISO 639-2/T to ISO 639-1"""
  2577. for short_name, long_name in cls._lang_map.items():
  2578. if long_name == code:
  2579. return short_name
  2580. class ISO3166Utils(object):
  2581. # From http://data.okfn.org/data/core/country-list
  2582. _country_map = {
  2583. 'AF': 'Afghanistan',
  2584. 'AX': 'Åland Islands',
  2585. 'AL': 'Albania',
  2586. 'DZ': 'Algeria',
  2587. 'AS': 'American Samoa',
  2588. 'AD': 'Andorra',
  2589. 'AO': 'Angola',
  2590. 'AI': 'Anguilla',
  2591. 'AQ': 'Antarctica',
  2592. 'AG': 'Antigua and Barbuda',
  2593. 'AR': 'Argentina',
  2594. 'AM': 'Armenia',
  2595. 'AW': 'Aruba',
  2596. 'AU': 'Australia',
  2597. 'AT': 'Austria',
  2598. 'AZ': 'Azerbaijan',
  2599. 'BS': 'Bahamas',
  2600. 'BH': 'Bahrain',
  2601. 'BD': 'Bangladesh',
  2602. 'BB': 'Barbados',
  2603. 'BY': 'Belarus',
  2604. 'BE': 'Belgium',
  2605. 'BZ': 'Belize',
  2606. 'BJ': 'Benin',
  2607. 'BM': 'Bermuda',
  2608. 'BT': 'Bhutan',
  2609. 'BO': 'Bolivia, Plurinational State of',
  2610. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  2611. 'BA': 'Bosnia and Herzegovina',
  2612. 'BW': 'Botswana',
  2613. 'BV': 'Bouvet Island',
  2614. 'BR': 'Brazil',
  2615. 'IO': 'British Indian Ocean Territory',
  2616. 'BN': 'Brunei Darussalam',
  2617. 'BG': 'Bulgaria',
  2618. 'BF': 'Burkina Faso',
  2619. 'BI': 'Burundi',
  2620. 'KH': 'Cambodia',
  2621. 'CM': 'Cameroon',
  2622. 'CA': 'Canada',
  2623. 'CV': 'Cape Verde',
  2624. 'KY': 'Cayman Islands',
  2625. 'CF': 'Central African Republic',
  2626. 'TD': 'Chad',
  2627. 'CL': 'Chile',
  2628. 'CN': 'China',
  2629. 'CX': 'Christmas Island',
  2630. 'CC': 'Cocos (Keeling) Islands',
  2631. 'CO': 'Colombia',
  2632. 'KM': 'Comoros',
  2633. 'CG': 'Congo',
  2634. 'CD': 'Congo, the Democratic Republic of the',
  2635. 'CK': 'Cook Islands',
  2636. 'CR': 'Costa Rica',
  2637. 'CI': 'Côte d\'Ivoire',
  2638. 'HR': 'Croatia',
  2639. 'CU': 'Cuba',
  2640. 'CW': 'Curaçao',
  2641. 'CY': 'Cyprus',
  2642. 'CZ': 'Czech Republic',
  2643. 'DK': 'Denmark',
  2644. 'DJ': 'Djibouti',
  2645. 'DM': 'Dominica',
  2646. 'DO': 'Dominican Republic',
  2647. 'EC': 'Ecuador',
  2648. 'EG': 'Egypt',
  2649. 'SV': 'El Salvador',
  2650. 'GQ': 'Equatorial Guinea',
  2651. 'ER': 'Eritrea',
  2652. 'EE': 'Estonia',
  2653. 'ET': 'Ethiopia',
  2654. 'FK': 'Falkland Islands (Malvinas)',
  2655. 'FO': 'Faroe Islands',
  2656. 'FJ': 'Fiji',
  2657. 'FI': 'Finland',
  2658. 'FR': 'France',
  2659. 'GF': 'French Guiana',
  2660. 'PF': 'French Polynesia',
  2661. 'TF': 'French Southern Territories',
  2662. 'GA': 'Gabon',
  2663. 'GM': 'Gambia',
  2664. 'GE': 'Georgia',
  2665. 'DE': 'Germany',
  2666. 'GH': 'Ghana',
  2667. 'GI': 'Gibraltar',
  2668. 'GR': 'Greece',
  2669. 'GL': 'Greenland',
  2670. 'GD': 'Grenada',
  2671. 'GP': 'Guadeloupe',
  2672. 'GU': 'Guam',
  2673. 'GT': 'Guatemala',
  2674. 'GG': 'Guernsey',
  2675. 'GN': 'Guinea',
  2676. 'GW': 'Guinea-Bissau',
  2677. 'GY': 'Guyana',
  2678. 'HT': 'Haiti',
  2679. 'HM': 'Heard Island and McDonald Islands',
  2680. 'VA': 'Holy See (Vatican City State)',
  2681. 'HN': 'Honduras',
  2682. 'HK': 'Hong Kong',
  2683. 'HU': 'Hungary',
  2684. 'IS': 'Iceland',
  2685. 'IN': 'India',
  2686. 'ID': 'Indonesia',
  2687. 'IR': 'Iran, Islamic Republic of',
  2688. 'IQ': 'Iraq',
  2689. 'IE': 'Ireland',
  2690. 'IM': 'Isle of Man',
  2691. 'IL': 'Israel',
  2692. 'IT': 'Italy',
  2693. 'JM': 'Jamaica',
  2694. 'JP': 'Japan',
  2695. 'JE': 'Jersey',
  2696. 'JO': 'Jordan',
  2697. 'KZ': 'Kazakhstan',
  2698. 'KE': 'Kenya',
  2699. 'KI': 'Kiribati',
  2700. 'KP': 'Korea, Democratic People\'s Republic of',
  2701. 'KR': 'Korea, Republic of',
  2702. 'KW': 'Kuwait',
  2703. 'KG': 'Kyrgyzstan',
  2704. 'LA': 'Lao People\'s Democratic Republic',
  2705. 'LV': 'Latvia',
  2706. 'LB': 'Lebanon',
  2707. 'LS': 'Lesotho',
  2708. 'LR': 'Liberia',
  2709. 'LY': 'Libya',
  2710. 'LI': 'Liechtenstein',
  2711. 'LT': 'Lithuania',
  2712. 'LU': 'Luxembourg',
  2713. 'MO': 'Macao',
  2714. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  2715. 'MG': 'Madagascar',
  2716. 'MW': 'Malawi',
  2717. 'MY': 'Malaysia',
  2718. 'MV': 'Maldives',
  2719. 'ML': 'Mali',
  2720. 'MT': 'Malta',
  2721. 'MH': 'Marshall Islands',
  2722. 'MQ': 'Martinique',
  2723. 'MR': 'Mauritania',
  2724. 'MU': 'Mauritius',
  2725. 'YT': 'Mayotte',
  2726. 'MX': 'Mexico',
  2727. 'FM': 'Micronesia, Federated States of',
  2728. 'MD': 'Moldova, Republic of',
  2729. 'MC': 'Monaco',
  2730. 'MN': 'Mongolia',
  2731. 'ME': 'Montenegro',
  2732. 'MS': 'Montserrat',
  2733. 'MA': 'Morocco',
  2734. 'MZ': 'Mozambique',
  2735. 'MM': 'Myanmar',
  2736. 'NA': 'Namibia',
  2737. 'NR': 'Nauru',
  2738. 'NP': 'Nepal',
  2739. 'NL': 'Netherlands',
  2740. 'NC': 'New Caledonia',
  2741. 'NZ': 'New Zealand',
  2742. 'NI': 'Nicaragua',
  2743. 'NE': 'Niger',
  2744. 'NG': 'Nigeria',
  2745. 'NU': 'Niue',
  2746. 'NF': 'Norfolk Island',
  2747. 'MP': 'Northern Mariana Islands',
  2748. 'NO': 'Norway',
  2749. 'OM': 'Oman',
  2750. 'PK': 'Pakistan',
  2751. 'PW': 'Palau',
  2752. 'PS': 'Palestine, State of',
  2753. 'PA': 'Panama',
  2754. 'PG': 'Papua New Guinea',
  2755. 'PY': 'Paraguay',
  2756. 'PE': 'Peru',
  2757. 'PH': 'Philippines',
  2758. 'PN': 'Pitcairn',
  2759. 'PL': 'Poland',
  2760. 'PT': 'Portugal',
  2761. 'PR': 'Puerto Rico',
  2762. 'QA': 'Qatar',
  2763. 'RE': 'Réunion',
  2764. 'RO': 'Romania',
  2765. 'RU': 'Russian Federation',
  2766. 'RW': 'Rwanda',
  2767. 'BL': 'Saint Barthélemy',
  2768. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  2769. 'KN': 'Saint Kitts and Nevis',
  2770. 'LC': 'Saint Lucia',
  2771. 'MF': 'Saint Martin (French part)',
  2772. 'PM': 'Saint Pierre and Miquelon',
  2773. 'VC': 'Saint Vincent and the Grenadines',
  2774. 'WS': 'Samoa',
  2775. 'SM': 'San Marino',
  2776. 'ST': 'Sao Tome and Principe',
  2777. 'SA': 'Saudi Arabia',
  2778. 'SN': 'Senegal',
  2779. 'RS': 'Serbia',
  2780. 'SC': 'Seychelles',
  2781. 'SL': 'Sierra Leone',
  2782. 'SG': 'Singapore',
  2783. 'SX': 'Sint Maarten (Dutch part)',
  2784. 'SK': 'Slovakia',
  2785. 'SI': 'Slovenia',
  2786. 'SB': 'Solomon Islands',
  2787. 'SO': 'Somalia',
  2788. 'ZA': 'South Africa',
  2789. 'GS': 'South Georgia and the South Sandwich Islands',
  2790. 'SS': 'South Sudan',
  2791. 'ES': 'Spain',
  2792. 'LK': 'Sri Lanka',
  2793. 'SD': 'Sudan',
  2794. 'SR': 'Suriname',
  2795. 'SJ': 'Svalbard and Jan Mayen',
  2796. 'SZ': 'Swaziland',
  2797. 'SE': 'Sweden',
  2798. 'CH': 'Switzerland',
  2799. 'SY': 'Syrian Arab Republic',
  2800. 'TW': 'Taiwan, Province of China',
  2801. 'TJ': 'Tajikistan',
  2802. 'TZ': 'Tanzania, United Republic of',
  2803. 'TH': 'Thailand',
  2804. 'TL': 'Timor-Leste',
  2805. 'TG': 'Togo',
  2806. 'TK': 'Tokelau',
  2807. 'TO': 'Tonga',
  2808. 'TT': 'Trinidad and Tobago',
  2809. 'TN': 'Tunisia',
  2810. 'TR': 'Turkey',
  2811. 'TM': 'Turkmenistan',
  2812. 'TC': 'Turks and Caicos Islands',
  2813. 'TV': 'Tuvalu',
  2814. 'UG': 'Uganda',
  2815. 'UA': 'Ukraine',
  2816. 'AE': 'United Arab Emirates',
  2817. 'GB': 'United Kingdom',
  2818. 'US': 'United States',
  2819. 'UM': 'United States Minor Outlying Islands',
  2820. 'UY': 'Uruguay',
  2821. 'UZ': 'Uzbekistan',
  2822. 'VU': 'Vanuatu',
  2823. 'VE': 'Venezuela, Bolivarian Republic of',
  2824. 'VN': 'Viet Nam',
  2825. 'VG': 'Virgin Islands, British',
  2826. 'VI': 'Virgin Islands, U.S.',
  2827. 'WF': 'Wallis and Futuna',
  2828. 'EH': 'Western Sahara',
  2829. 'YE': 'Yemen',
  2830. 'ZM': 'Zambia',
  2831. 'ZW': 'Zimbabwe',
  2832. }
  2833. @classmethod
  2834. def short2full(cls, code):
  2835. """Convert an ISO 3166-2 country code to the corresponding full name"""
  2836. return cls._country_map.get(code.upper())
  2837. class GeoUtils(object):
  2838. # Major IPv4 address blocks per country
  2839. _country_ip_map = {
  2840. 'AD': '85.94.160.0/19',
  2841. 'AE': '94.200.0.0/13',
  2842. 'AF': '149.54.0.0/17',
  2843. 'AG': '209.59.64.0/18',
  2844. 'AI': '204.14.248.0/21',
  2845. 'AL': '46.99.0.0/16',
  2846. 'AM': '46.70.0.0/15',
  2847. 'AO': '105.168.0.0/13',
  2848. 'AP': '159.117.192.0/21',
  2849. 'AR': '181.0.0.0/12',
  2850. 'AS': '202.70.112.0/20',
  2851. 'AT': '84.112.0.0/13',
  2852. 'AU': '1.128.0.0/11',
  2853. 'AW': '181.41.0.0/18',
  2854. 'AZ': '5.191.0.0/16',
  2855. 'BA': '31.176.128.0/17',
  2856. 'BB': '65.48.128.0/17',
  2857. 'BD': '114.130.0.0/16',
  2858. 'BE': '57.0.0.0/8',
  2859. 'BF': '129.45.128.0/17',
  2860. 'BG': '95.42.0.0/15',
  2861. 'BH': '37.131.0.0/17',
  2862. 'BI': '154.117.192.0/18',
  2863. 'BJ': '137.255.0.0/16',
  2864. 'BL': '192.131.134.0/24',
  2865. 'BM': '196.12.64.0/18',
  2866. 'BN': '156.31.0.0/16',
  2867. 'BO': '161.56.0.0/16',
  2868. 'BQ': '161.0.80.0/20',
  2869. 'BR': '152.240.0.0/12',
  2870. 'BS': '24.51.64.0/18',
  2871. 'BT': '119.2.96.0/19',
  2872. 'BW': '168.167.0.0/16',
  2873. 'BY': '178.120.0.0/13',
  2874. 'BZ': '179.42.192.0/18',
  2875. 'CA': '99.224.0.0/11',
  2876. 'CD': '41.243.0.0/16',
  2877. 'CF': '196.32.200.0/21',
  2878. 'CG': '197.214.128.0/17',
  2879. 'CH': '85.0.0.0/13',
  2880. 'CI': '154.232.0.0/14',
  2881. 'CK': '202.65.32.0/19',
  2882. 'CL': '152.172.0.0/14',
  2883. 'CM': '165.210.0.0/15',
  2884. 'CN': '36.128.0.0/10',
  2885. 'CO': '181.240.0.0/12',
  2886. 'CR': '201.192.0.0/12',
  2887. 'CU': '152.206.0.0/15',
  2888. 'CV': '165.90.96.0/19',
  2889. 'CW': '190.88.128.0/17',
  2890. 'CY': '46.198.0.0/15',
  2891. 'CZ': '88.100.0.0/14',
  2892. 'DE': '53.0.0.0/8',
  2893. 'DJ': '197.241.0.0/17',
  2894. 'DK': '87.48.0.0/12',
  2895. 'DM': '192.243.48.0/20',
  2896. 'DO': '152.166.0.0/15',
  2897. 'DZ': '41.96.0.0/12',
  2898. 'EC': '186.68.0.0/15',
  2899. 'EE': '90.190.0.0/15',
  2900. 'EG': '156.160.0.0/11',
  2901. 'ER': '196.200.96.0/20',
  2902. 'ES': '88.0.0.0/11',
  2903. 'ET': '196.188.0.0/14',
  2904. 'EU': '2.16.0.0/13',
  2905. 'FI': '91.152.0.0/13',
  2906. 'FJ': '144.120.0.0/16',
  2907. 'FM': '119.252.112.0/20',
  2908. 'FO': '88.85.32.0/19',
  2909. 'FR': '90.0.0.0/9',
  2910. 'GA': '41.158.0.0/15',
  2911. 'GB': '25.0.0.0/8',
  2912. 'GD': '74.122.88.0/21',
  2913. 'GE': '31.146.0.0/16',
  2914. 'GF': '161.22.64.0/18',
  2915. 'GG': '62.68.160.0/19',
  2916. 'GH': '45.208.0.0/14',
  2917. 'GI': '85.115.128.0/19',
  2918. 'GL': '88.83.0.0/19',
  2919. 'GM': '160.182.0.0/15',
  2920. 'GN': '197.149.192.0/18',
  2921. 'GP': '104.250.0.0/19',
  2922. 'GQ': '105.235.224.0/20',
  2923. 'GR': '94.64.0.0/13',
  2924. 'GT': '168.234.0.0/16',
  2925. 'GU': '168.123.0.0/16',
  2926. 'GW': '197.214.80.0/20',
  2927. 'GY': '181.41.64.0/18',
  2928. 'HK': '113.252.0.0/14',
  2929. 'HN': '181.210.0.0/16',
  2930. 'HR': '93.136.0.0/13',
  2931. 'HT': '148.102.128.0/17',
  2932. 'HU': '84.0.0.0/14',
  2933. 'ID': '39.192.0.0/10',
  2934. 'IE': '87.32.0.0/12',
  2935. 'IL': '79.176.0.0/13',
  2936. 'IM': '5.62.80.0/20',
  2937. 'IN': '117.192.0.0/10',
  2938. 'IO': '203.83.48.0/21',
  2939. 'IQ': '37.236.0.0/14',
  2940. 'IR': '2.176.0.0/12',
  2941. 'IS': '82.221.0.0/16',
  2942. 'IT': '79.0.0.0/10',
  2943. 'JE': '87.244.64.0/18',
  2944. 'JM': '72.27.0.0/17',
  2945. 'JO': '176.29.0.0/16',
  2946. 'JP': '126.0.0.0/8',
  2947. 'KE': '105.48.0.0/12',
  2948. 'KG': '158.181.128.0/17',
  2949. 'KH': '36.37.128.0/17',
  2950. 'KI': '103.25.140.0/22',
  2951. 'KM': '197.255.224.0/20',
  2952. 'KN': '198.32.32.0/19',
  2953. 'KP': '175.45.176.0/22',
  2954. 'KR': '175.192.0.0/10',
  2955. 'KW': '37.36.0.0/14',
  2956. 'KY': '64.96.0.0/15',
  2957. 'KZ': '2.72.0.0/13',
  2958. 'LA': '115.84.64.0/18',
  2959. 'LB': '178.135.0.0/16',
  2960. 'LC': '192.147.231.0/24',
  2961. 'LI': '82.117.0.0/19',
  2962. 'LK': '112.134.0.0/15',
  2963. 'LR': '41.86.0.0/19',
  2964. 'LS': '129.232.0.0/17',
  2965. 'LT': '78.56.0.0/13',
  2966. 'LU': '188.42.0.0/16',
  2967. 'LV': '46.109.0.0/16',
  2968. 'LY': '41.252.0.0/14',
  2969. 'MA': '105.128.0.0/11',
  2970. 'MC': '88.209.64.0/18',
  2971. 'MD': '37.246.0.0/16',
  2972. 'ME': '178.175.0.0/17',
  2973. 'MF': '74.112.232.0/21',
  2974. 'MG': '154.126.0.0/17',
  2975. 'MH': '117.103.88.0/21',
  2976. 'MK': '77.28.0.0/15',
  2977. 'ML': '154.118.128.0/18',
  2978. 'MM': '37.111.0.0/17',
  2979. 'MN': '49.0.128.0/17',
  2980. 'MO': '60.246.0.0/16',
  2981. 'MP': '202.88.64.0/20',
  2982. 'MQ': '109.203.224.0/19',
  2983. 'MR': '41.188.64.0/18',
  2984. 'MS': '208.90.112.0/22',
  2985. 'MT': '46.11.0.0/16',
  2986. 'MU': '105.16.0.0/12',
  2987. 'MV': '27.114.128.0/18',
  2988. 'MW': '105.234.0.0/16',
  2989. 'MX': '187.192.0.0/11',
  2990. 'MY': '175.136.0.0/13',
  2991. 'MZ': '197.218.0.0/15',
  2992. 'NA': '41.182.0.0/16',
  2993. 'NC': '101.101.0.0/18',
  2994. 'NE': '197.214.0.0/18',
  2995. 'NF': '203.17.240.0/22',
  2996. 'NG': '105.112.0.0/12',
  2997. 'NI': '186.76.0.0/15',
  2998. 'NL': '145.96.0.0/11',
  2999. 'NO': '84.208.0.0/13',
  3000. 'NP': '36.252.0.0/15',
  3001. 'NR': '203.98.224.0/19',
  3002. 'NU': '49.156.48.0/22',
  3003. 'NZ': '49.224.0.0/14',
  3004. 'OM': '5.36.0.0/15',
  3005. 'PA': '186.72.0.0/15',
  3006. 'PE': '186.160.0.0/14',
  3007. 'PF': '123.50.64.0/18',
  3008. 'PG': '124.240.192.0/19',
  3009. 'PH': '49.144.0.0/13',
  3010. 'PK': '39.32.0.0/11',
  3011. 'PL': '83.0.0.0/11',
  3012. 'PM': '70.36.0.0/20',
  3013. 'PR': '66.50.0.0/16',
  3014. 'PS': '188.161.0.0/16',
  3015. 'PT': '85.240.0.0/13',
  3016. 'PW': '202.124.224.0/20',
  3017. 'PY': '181.120.0.0/14',
  3018. 'QA': '37.210.0.0/15',
  3019. 'RE': '139.26.0.0/16',
  3020. 'RO': '79.112.0.0/13',
  3021. 'RS': '178.220.0.0/14',
  3022. 'RU': '5.136.0.0/13',
  3023. 'RW': '105.178.0.0/15',
  3024. 'SA': '188.48.0.0/13',
  3025. 'SB': '202.1.160.0/19',
  3026. 'SC': '154.192.0.0/11',
  3027. 'SD': '154.96.0.0/13',
  3028. 'SE': '78.64.0.0/12',
  3029. 'SG': '152.56.0.0/14',
  3030. 'SI': '188.196.0.0/14',
  3031. 'SK': '78.98.0.0/15',
  3032. 'SL': '197.215.0.0/17',
  3033. 'SM': '89.186.32.0/19',
  3034. 'SN': '41.82.0.0/15',
  3035. 'SO': '197.220.64.0/19',
  3036. 'SR': '186.179.128.0/17',
  3037. 'SS': '105.235.208.0/21',
  3038. 'ST': '197.159.160.0/19',
  3039. 'SV': '168.243.0.0/16',
  3040. 'SX': '190.102.0.0/20',
  3041. 'SY': '5.0.0.0/16',
  3042. 'SZ': '41.84.224.0/19',
  3043. 'TC': '65.255.48.0/20',
  3044. 'TD': '154.68.128.0/19',
  3045. 'TG': '196.168.0.0/14',
  3046. 'TH': '171.96.0.0/13',
  3047. 'TJ': '85.9.128.0/18',
  3048. 'TK': '27.96.24.0/21',
  3049. 'TL': '180.189.160.0/20',
  3050. 'TM': '95.85.96.0/19',
  3051. 'TN': '197.0.0.0/11',
  3052. 'TO': '175.176.144.0/21',
  3053. 'TR': '78.160.0.0/11',
  3054. 'TT': '186.44.0.0/15',
  3055. 'TV': '202.2.96.0/19',
  3056. 'TW': '120.96.0.0/11',
  3057. 'TZ': '156.156.0.0/14',
  3058. 'UA': '93.72.0.0/13',
  3059. 'UG': '154.224.0.0/13',
  3060. 'US': '3.0.0.0/8',
  3061. 'UY': '167.56.0.0/13',
  3062. 'UZ': '82.215.64.0/18',
  3063. 'VA': '212.77.0.0/19',
  3064. 'VC': '24.92.144.0/20',
  3065. 'VE': '186.88.0.0/13',
  3066. 'VG': '172.103.64.0/18',
  3067. 'VI': '146.226.0.0/16',
  3068. 'VN': '14.160.0.0/11',
  3069. 'VU': '202.80.32.0/20',
  3070. 'WF': '117.20.32.0/21',
  3071. 'WS': '202.4.32.0/19',
  3072. 'YE': '134.35.0.0/16',
  3073. 'YT': '41.242.116.0/22',
  3074. 'ZA': '41.0.0.0/11',
  3075. 'ZM': '165.56.0.0/13',
  3076. 'ZW': '41.85.192.0/19',
  3077. }
  3078. @classmethod
  3079. def random_ipv4(cls, code_or_block):
  3080. if len(code_or_block) == 2:
  3081. block = cls._country_ip_map.get(code_or_block.upper())
  3082. if not block:
  3083. return None
  3084. else:
  3085. block = code_or_block
  3086. addr, preflen = block.split('/')
  3087. addr_min = compat_struct_unpack('!L', socket.inet_aton(addr))[0]
  3088. addr_max = addr_min | (0xffffffff >> int(preflen))
  3089. return compat_str(socket.inet_ntoa(
  3090. compat_struct_pack('!L', random.randint(addr_min, addr_max))))
  3091. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  3092. def __init__(self, proxies=None):
  3093. # Set default handlers
  3094. for type in ('http', 'https'):
  3095. setattr(self, '%s_open' % type,
  3096. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  3097. meth(r, proxy, type))
  3098. compat_urllib_request.ProxyHandler.__init__(self, proxies)
  3099. def proxy_open(self, req, proxy, type):
  3100. req_proxy = req.headers.get('Ytdl-request-proxy')
  3101. if req_proxy is not None:
  3102. proxy = req_proxy
  3103. del req.headers['Ytdl-request-proxy']
  3104. if proxy == '__noproxy__':
  3105. return None # No Proxy
  3106. if compat_urlparse.urlparse(proxy).scheme.lower() in ('socks', 'socks4', 'socks4a', 'socks5'):
  3107. req.add_header('Ytdl-socks-proxy', proxy)
  3108. # youtube-dl's http/https handlers do wrapping the socket with socks
  3109. return None
  3110. return compat_urllib_request.ProxyHandler.proxy_open(
  3111. self, req, proxy, type)
  3112. # Both long_to_bytes and bytes_to_long are adapted from PyCrypto, which is
  3113. # released into Public Domain
  3114. # https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Util/number.py#L387
  3115. def long_to_bytes(n, blocksize=0):
  3116. """long_to_bytes(n:long, blocksize:int) : string
  3117. Convert a long integer to a byte string.
  3118. If optional blocksize is given and greater than zero, pad the front of the
  3119. byte string with binary zeros so that the length is a multiple of
  3120. blocksize.
  3121. """
  3122. # after much testing, this algorithm was deemed to be the fastest
  3123. s = b''
  3124. n = int(n)
  3125. while n > 0:
  3126. s = compat_struct_pack('>I', n & 0xffffffff) + s
  3127. n = n >> 32
  3128. # strip off leading zeros
  3129. for i in range(len(s)):
  3130. if s[i] != b'\000'[0]:
  3131. break
  3132. else:
  3133. # only happens when n == 0
  3134. s = b'\000'
  3135. i = 0
  3136. s = s[i:]
  3137. # add back some pad bytes. this could be done more efficiently w.r.t. the
  3138. # de-padding being done above, but sigh...
  3139. if blocksize > 0 and len(s) % blocksize:
  3140. s = (blocksize - len(s) % blocksize) * b'\000' + s
  3141. return s
  3142. def bytes_to_long(s):
  3143. """bytes_to_long(string) : long
  3144. Convert a byte string to a long integer.
  3145. This is (essentially) the inverse of long_to_bytes().
  3146. """
  3147. acc = 0
  3148. length = len(s)
  3149. if length % 4:
  3150. extra = (4 - length % 4)
  3151. s = b'\000' * extra + s
  3152. length = length + extra
  3153. for i in range(0, length, 4):
  3154. acc = (acc << 32) + compat_struct_unpack('>I', s[i:i + 4])[0]
  3155. return acc
  3156. def ohdave_rsa_encrypt(data, exponent, modulus):
  3157. '''
  3158. Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
  3159. Input:
  3160. data: data to encrypt, bytes-like object
  3161. exponent, modulus: parameter e and N of RSA algorithm, both integer
  3162. Output: hex string of encrypted data
  3163. Limitation: supports one block encryption only
  3164. '''
  3165. payload = int(binascii.hexlify(data[::-1]), 16)
  3166. encrypted = pow(payload, exponent, modulus)
  3167. return '%x' % encrypted
  3168. def pkcs1pad(data, length):
  3169. """
  3170. Padding input data with PKCS#1 scheme
  3171. @param {int[]} data input data
  3172. @param {int} length target length
  3173. @returns {int[]} padded data
  3174. """
  3175. if len(data) > length - 11:
  3176. raise ValueError('Input data too long for PKCS#1 padding')
  3177. pseudo_random = [random.randint(0, 254) for _ in range(length - len(data) - 3)]
  3178. return [0, 2] + pseudo_random + [0] + data
  3179. def encode_base_n(num, n, table=None):
  3180. FULL_TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  3181. if not table:
  3182. table = FULL_TABLE[:n]
  3183. if n > len(table):
  3184. raise ValueError('base %d exceeds table length %d' % (n, len(table)))
  3185. if num == 0:
  3186. return table[0]
  3187. ret = ''
  3188. while num:
  3189. ret = table[num % n] + ret
  3190. num = num // n
  3191. return ret
  3192. def decode_packed_codes(code):
  3193. mobj = re.search(PACKED_CODES_RE, code)
  3194. obfucasted_code, base, count, symbols = mobj.groups()
  3195. base = int(base)
  3196. count = int(count)
  3197. symbols = symbols.split('|')
  3198. symbol_table = {}
  3199. while count:
  3200. count -= 1
  3201. base_n_count = encode_base_n(count, base)
  3202. symbol_table[base_n_count] = symbols[count] or base_n_count
  3203. return re.sub(
  3204. r'\b(\w+)\b', lambda mobj: symbol_table[mobj.group(0)],
  3205. obfucasted_code)
  3206. def parse_m3u8_attributes(attrib):
  3207. info = {}
  3208. for (key, val) in re.findall(r'(?P<key>[A-Z0-9-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)', attrib):
  3209. if val.startswith('"'):
  3210. val = val[1:-1]
  3211. info[key] = val
  3212. return info
  3213. def urshift(val, n):
  3214. return val >> n if val >= 0 else (val + 0x100000000) >> n
  3215. # Based on png2str() written by @gdkchan and improved by @yokrysty
  3216. # Originally posted at https://github.com/rg3/youtube-dl/issues/9706
  3217. def decode_png(png_data):
  3218. # Reference: https://www.w3.org/TR/PNG/
  3219. header = png_data[8:]
  3220. if png_data[:8] != b'\x89PNG\x0d\x0a\x1a\x0a' or header[4:8] != b'IHDR':
  3221. raise IOError('Not a valid PNG file.')
  3222. int_map = {1: '>B', 2: '>H', 4: '>I'}
  3223. unpack_integer = lambda x: compat_struct_unpack(int_map[len(x)], x)[0]
  3224. chunks = []
  3225. while header:
  3226. length = unpack_integer(header[:4])
  3227. header = header[4:]
  3228. chunk_type = header[:4]
  3229. header = header[4:]
  3230. chunk_data = header[:length]
  3231. header = header[length:]
  3232. header = header[4:] # Skip CRC
  3233. chunks.append({
  3234. 'type': chunk_type,
  3235. 'length': length,
  3236. 'data': chunk_data
  3237. })
  3238. ihdr = chunks[0]['data']
  3239. width = unpack_integer(ihdr[:4])
  3240. height = unpack_integer(ihdr[4:8])
  3241. idat = b''
  3242. for chunk in chunks:
  3243. if chunk['type'] == b'IDAT':
  3244. idat += chunk['data']
  3245. if not idat:
  3246. raise IOError('Unable to read PNG data.')
  3247. decompressed_data = bytearray(zlib.decompress(idat))
  3248. stride = width * 3
  3249. pixels = []
  3250. def _get_pixel(idx):
  3251. x = idx % stride
  3252. y = idx // stride
  3253. return pixels[y][x]
  3254. for y in range(height):
  3255. basePos = y * (1 + stride)
  3256. filter_type = decompressed_data[basePos]
  3257. current_row = []
  3258. pixels.append(current_row)
  3259. for x in range(stride):
  3260. color = decompressed_data[1 + basePos + x]
  3261. basex = y * stride + x
  3262. left = 0
  3263. up = 0
  3264. if x > 2:
  3265. left = _get_pixel(basex - 3)
  3266. if y > 0:
  3267. up = _get_pixel(basex - stride)
  3268. if filter_type == 1: # Sub
  3269. color = (color + left) & 0xff
  3270. elif filter_type == 2: # Up
  3271. color = (color + up) & 0xff
  3272. elif filter_type == 3: # Average
  3273. color = (color + ((left + up) >> 1)) & 0xff
  3274. elif filter_type == 4: # Paeth
  3275. a = left
  3276. b = up
  3277. c = 0
  3278. if x > 2 and y > 0:
  3279. c = _get_pixel(basex - stride - 3)
  3280. p = a + b - c
  3281. pa = abs(p - a)
  3282. pb = abs(p - b)
  3283. pc = abs(p - c)
  3284. if pa <= pb and pa <= pc:
  3285. color = (color + a) & 0xff
  3286. elif pb <= pc:
  3287. color = (color + b) & 0xff
  3288. else:
  3289. color = (color + c) & 0xff
  3290. current_row.append(color)
  3291. return width, height, pixels
  3292. def write_xattr(path, key, value):
  3293. # This mess below finds the best xattr tool for the job
  3294. try:
  3295. # try the pyxattr module...
  3296. import xattr
  3297. if hasattr(xattr, 'set'): # pyxattr
  3298. # Unicode arguments are not supported in python-pyxattr until
  3299. # version 0.5.0
  3300. # See https://github.com/rg3/youtube-dl/issues/5498
  3301. pyxattr_required_version = '0.5.0'
  3302. if version_tuple(xattr.__version__) < version_tuple(pyxattr_required_version):
  3303. # TODO: fallback to CLI tools
  3304. raise XAttrUnavailableError(
  3305. 'python-pyxattr is detected but is too old. '
  3306. 'youtube-dl requires %s or above while your version is %s. '
  3307. 'Falling back to other xattr implementations' % (
  3308. pyxattr_required_version, xattr.__version__))
  3309. setxattr = xattr.set
  3310. else: # xattr
  3311. setxattr = xattr.setxattr
  3312. try:
  3313. setxattr(path, key, value)
  3314. except EnvironmentError as e:
  3315. raise XAttrMetadataError(e.errno, e.strerror)
  3316. except ImportError:
  3317. if compat_os_name == 'nt':
  3318. # Write xattrs to NTFS Alternate Data Streams:
  3319. # http://en.wikipedia.org/wiki/NTFS#Alternate_data_streams_.28ADS.29
  3320. assert ':' not in key
  3321. assert os.path.exists(path)
  3322. ads_fn = path + ':' + key
  3323. try:
  3324. with open(ads_fn, 'wb') as f:
  3325. f.write(value)
  3326. except EnvironmentError as e:
  3327. raise XAttrMetadataError(e.errno, e.strerror)
  3328. else:
  3329. user_has_setfattr = check_executable('setfattr', ['--version'])
  3330. user_has_xattr = check_executable('xattr', ['-h'])
  3331. if user_has_setfattr or user_has_xattr:
  3332. value = value.decode('utf-8')
  3333. if user_has_setfattr:
  3334. executable = 'setfattr'
  3335. opts = ['-n', key, '-v', value]
  3336. elif user_has_xattr:
  3337. executable = 'xattr'
  3338. opts = ['-w', key, value]
  3339. cmd = ([encodeFilename(executable, True)] +
  3340. [encodeArgument(o) for o in opts] +
  3341. [encodeFilename(path, True)])
  3342. try:
  3343. p = subprocess.Popen(
  3344. cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  3345. except EnvironmentError as e:
  3346. raise XAttrMetadataError(e.errno, e.strerror)
  3347. stdout, stderr = p.communicate()
  3348. stderr = stderr.decode('utf-8', 'replace')
  3349. if p.returncode != 0:
  3350. raise XAttrMetadataError(p.returncode, stderr)
  3351. else:
  3352. # On Unix, and can't find pyxattr, setfattr, or xattr.
  3353. if sys.platform.startswith('linux'):
  3354. raise XAttrUnavailableError(
  3355. "Couldn't find a tool to set the xattrs. "
  3356. "Install either the python 'pyxattr' or 'xattr' "
  3357. "modules, or the GNU 'attr' package "
  3358. "(which contains the 'setfattr' tool).")
  3359. else:
  3360. raise XAttrUnavailableError(
  3361. "Couldn't find a tool to set the xattrs. "
  3362. "Install either the python 'xattr' module, "
  3363. "or the 'xattr' binary.")
  3364. def random_birthday(year_field, month_field, day_field):
  3365. start_date = datetime.date(1950, 1, 1)
  3366. end_date = datetime.date(1995, 12, 31)
  3367. offset = random.randint(0, (end_date - start_date).days)
  3368. random_date = start_date + datetime.timedelta(offset)
  3369. return {
  3370. year_field: str(random_date.year),
  3371. month_field: str(random_date.month),
  3372. day_field: str(random_date.day),
  3373. }