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.

3133 lines
92 KiB

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