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.

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