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.

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