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.

3576 lines
108 KiB

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