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.

3295 lines
99 KiB

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