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.

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