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.

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