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.

3918 lines
119 KiB

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