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.

3648 lines
110 KiB

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