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.

3275 lines
98 KiB

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