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.

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