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.

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