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.

3240 lines
97 KiB

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