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.

3654 lines
110 KiB

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