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.

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