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.

3910 lines
119 KiB

10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
[utils] Remove Content-encoding from headers after decompression With cn_verification_proxy, our http_response() is called twice, one from PerRequestProxyHandler.proxy_open() and another from normal YoutubeDL.urlopen(). As a result, for proxies honoring Accept-Encoding, the following bug occurs: $ youtube-dl -vs --cn-verification-proxy https://secure.uku.im:993 "test:letv" [debug] System config: [] [debug] User config: [] [debug] Command-line args: ['-vs', '--cn-verification-proxy', 'https://secure.uku.im:993', 'test:letv'] [debug] Encodings: locale UTF-8, fs utf-8, out UTF-8, pref UTF-8 [debug] youtube-dl version 2015.12.23 [debug] Git HEAD: 97f18fa [debug] Python version 3.5.1 - Linux-4.3.3-1-ARCH-x86_64-with-arch-Arch-Linux [debug] exe versions: ffmpeg 2.8.4, ffprobe 2.8.4, rtmpdump 2.4 [debug] Proxy map: {} [TestURL] Test URL: http://www.letv.com/ptv/vplay/22005890.html [Letv] 22005890: Downloading webpage [Letv] 22005890: Downloading playJson data ERROR: Unable to download JSON metadata: Not a gzipped file (b'{"') (caused by OSError('Not a gzipped file (b\'{"\')',)); please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output. File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/extractor/common.py", line 330, in _request_webpage return self._downloader.urlopen(url_or_request) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/YoutubeDL.py", line 1886, in urlopen return self._opener.open(req, timeout=self._socket_timeout) File "/usr/lib/python3.5/urllib/request.py", line 471, in open response = meth(req, response) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 773, in http_response raise original_ioerror File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 761, in http_response uncompressed = io.BytesIO(gz.read()) File "/usr/lib/python3.5/gzip.py", line 274, in read return self._buffer.read(size) File "/usr/lib/python3.5/gzip.py", line 461, in read if not self._read_gzip_header(): File "/usr/lib/python3.5/gzip.py", line 409, in _read_gzip_header raise OSError('Not a gzipped file (%r)' % magic)
9 years ago
[utils] Remove Content-encoding from headers after decompression With cn_verification_proxy, our http_response() is called twice, one from PerRequestProxyHandler.proxy_open() and another from normal YoutubeDL.urlopen(). As a result, for proxies honoring Accept-Encoding, the following bug occurs: $ youtube-dl -vs --cn-verification-proxy https://secure.uku.im:993 "test:letv" [debug] System config: [] [debug] User config: [] [debug] Command-line args: ['-vs', '--cn-verification-proxy', 'https://secure.uku.im:993', 'test:letv'] [debug] Encodings: locale UTF-8, fs utf-8, out UTF-8, pref UTF-8 [debug] youtube-dl version 2015.12.23 [debug] Git HEAD: 97f18fa [debug] Python version 3.5.1 - Linux-4.3.3-1-ARCH-x86_64-with-arch-Arch-Linux [debug] exe versions: ffmpeg 2.8.4, ffprobe 2.8.4, rtmpdump 2.4 [debug] Proxy map: {} [TestURL] Test URL: http://www.letv.com/ptv/vplay/22005890.html [Letv] 22005890: Downloading webpage [Letv] 22005890: Downloading playJson data ERROR: Unable to download JSON metadata: Not a gzipped file (b'{"') (caused by OSError('Not a gzipped file (b\'{"\')',)); please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output. File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/extractor/common.py", line 330, in _request_webpage return self._downloader.urlopen(url_or_request) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/YoutubeDL.py", line 1886, in urlopen return self._opener.open(req, timeout=self._socket_timeout) File "/usr/lib/python3.5/urllib/request.py", line 471, in open response = meth(req, response) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 773, in http_response raise original_ioerror File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 761, in http_response uncompressed = io.BytesIO(gz.read()) File "/usr/lib/python3.5/gzip.py", line 274, in read return self._buffer.read(size) File "/usr/lib/python3.5/gzip.py", line 461, in read if not self._read_gzip_header(): File "/usr/lib/python3.5/gzip.py", line 409, in _read_gzip_header raise OSError('Not a gzipped file (%r)' % magic)
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. from __future__ import unicode_literals
  4. import base64
  5. import binascii
  6. import calendar
  7. import codecs
  8. import contextlib
  9. import ctypes
  10. import datetime
  11. import email.utils
  12. import email.header
  13. import errno
  14. import functools
  15. import gzip
  16. import io
  17. import itertools
  18. import json
  19. import locale
  20. import math
  21. import operator
  22. import os
  23. import platform
  24. import random
  25. import re
  26. import socket
  27. import ssl
  28. import subprocess
  29. import sys
  30. import tempfile
  31. import traceback
  32. import xml.etree.ElementTree
  33. import zlib
  34. from .compat import (
  35. compat_HTMLParseError,
  36. compat_HTMLParser,
  37. compat_basestring,
  38. compat_chr,
  39. compat_ctypes_WINFUNCTYPE,
  40. compat_etree_fromstring,
  41. compat_expanduser,
  42. compat_html_entities,
  43. compat_html_entities_html5,
  44. compat_http_client,
  45. compat_kwargs,
  46. compat_os_name,
  47. compat_parse_qs,
  48. compat_shlex_quote,
  49. compat_socket_create_connection,
  50. compat_str,
  51. compat_struct_pack,
  52. compat_struct_unpack,
  53. compat_urllib_error,
  54. compat_urllib_parse,
  55. compat_urllib_parse_urlencode,
  56. compat_urllib_parse_urlparse,
  57. compat_urllib_parse_unquote_plus,
  58. compat_urllib_request,
  59. compat_urlparse,
  60. compat_xpath,
  61. )
  62. from .socks import (
  63. ProxyType,
  64. sockssocket,
  65. )
  66. def register_socks_protocols():
  67. # "Register" SOCKS protocols
  68. # In Python < 2.6.5, urlsplit() suffers from bug https://bugs.python.org/issue7904
  69. # URLs with protocols not in urlparse.uses_netloc are not handled correctly
  70. for scheme in ('socks', 'socks4', 'socks4a', 'socks5'):
  71. if scheme not in compat_urlparse.uses_netloc:
  72. compat_urlparse.uses_netloc.append(scheme)
  73. # This is not clearly defined otherwise
  74. compiled_regex_type = type(re.compile(''))
  75. std_headers = {
  76. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:59.0) Gecko/20100101 Firefox/59.0 (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 or '.' not in url:
  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 merge_dicts(*dicts):
  1807. merged = {}
  1808. for a_dict in dicts:
  1809. for k, v in a_dict.items():
  1810. if v is None:
  1811. continue
  1812. if (k not in merged or
  1813. (isinstance(v, compat_str) and v and
  1814. isinstance(merged[k], compat_str) and
  1815. not merged[k])):
  1816. merged[k] = v
  1817. return merged
  1818. def encode_compat_str(string, encoding=preferredencoding(), errors='strict'):
  1819. return string if isinstance(string, compat_str) else compat_str(string, encoding, errors)
  1820. US_RATINGS = {
  1821. 'G': 0,
  1822. 'PG': 10,
  1823. 'PG-13': 13,
  1824. 'R': 16,
  1825. 'NC': 18,
  1826. }
  1827. TV_PARENTAL_GUIDELINES = {
  1828. 'TV-Y': 0,
  1829. 'TV-Y7': 7,
  1830. 'TV-G': 0,
  1831. 'TV-PG': 0,
  1832. 'TV-14': 14,
  1833. 'TV-MA': 17,
  1834. }
  1835. def parse_age_limit(s):
  1836. if type(s) == int:
  1837. return s if 0 <= s <= 21 else None
  1838. if not isinstance(s, compat_basestring):
  1839. return None
  1840. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1841. if m:
  1842. return int(m.group('age'))
  1843. if s in US_RATINGS:
  1844. return US_RATINGS[s]
  1845. m = re.match(r'^TV[_-]?(%s)$' % '|'.join(k[3:] for k in TV_PARENTAL_GUIDELINES), s)
  1846. if m:
  1847. return TV_PARENTAL_GUIDELINES['TV-' + m.group(1)]
  1848. return None
  1849. def strip_jsonp(code):
  1850. return re.sub(
  1851. r'''(?sx)^
  1852. (?:window\.)?(?P<func_name>[a-zA-Z0-9_.$]+)
  1853. (?:\s*&&\s*(?P=func_name))?
  1854. \s*\(\s*(?P<callback_data>.*)\);?
  1855. \s*?(?://[^\n]*)*$''',
  1856. r'\g<callback_data>', code)
  1857. def js_to_json(code):
  1858. COMMENT_RE = r'/\*(?:(?!\*/).)*?\*/|//[^\n]*'
  1859. SKIP_RE = r'\s*(?:{comment})?\s*'.format(comment=COMMENT_RE)
  1860. INTEGER_TABLE = (
  1861. (r'(?s)^(0[xX][0-9a-fA-F]+){skip}:?$'.format(skip=SKIP_RE), 16),
  1862. (r'(?s)^(0+[0-7]+){skip}:?$'.format(skip=SKIP_RE), 8),
  1863. )
  1864. def fix_kv(m):
  1865. v = m.group(0)
  1866. if v in ('true', 'false', 'null'):
  1867. return v
  1868. elif v.startswith('/*') or v.startswith('//') or v == ',':
  1869. return ""
  1870. if v[0] in ("'", '"'):
  1871. v = re.sub(r'(?s)\\.|"', lambda m: {
  1872. '"': '\\"',
  1873. "\\'": "'",
  1874. '\\\n': '',
  1875. '\\x': '\\u00',
  1876. }.get(m.group(0), m.group(0)), v[1:-1])
  1877. for regex, base in INTEGER_TABLE:
  1878. im = re.match(regex, v)
  1879. if im:
  1880. i = int(im.group(1), base)
  1881. return '"%d":' % i if v.endswith(':') else '%d' % i
  1882. return '"%s"' % v
  1883. return re.sub(r'''(?sx)
  1884. "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
  1885. '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
  1886. {comment}|,(?={skip}[\]}}])|
  1887. (?:(?<![0-9])[eE]|[a-df-zA-DF-Z_])[.a-zA-Z_0-9]*|
  1888. \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:{skip}:)?|
  1889. [0-9]+(?={skip}:)
  1890. '''.format(comment=COMMENT_RE, skip=SKIP_RE), fix_kv, code)
  1891. def qualities(quality_ids):
  1892. """ Get a numeric quality value out of a list of possible values """
  1893. def q(qid):
  1894. try:
  1895. return quality_ids.index(qid)
  1896. except ValueError:
  1897. return -1
  1898. return q
  1899. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1900. def limit_length(s, length):
  1901. """ Add ellipses to overly long strings """
  1902. if s is None:
  1903. return None
  1904. ELLIPSES = '...'
  1905. if len(s) > length:
  1906. return s[:length - len(ELLIPSES)] + ELLIPSES
  1907. return s
  1908. def version_tuple(v):
  1909. return tuple(int(e) for e in re.split(r'[-.]', v))
  1910. def is_outdated_version(version, limit, assume_new=True):
  1911. if not version:
  1912. return not assume_new
  1913. try:
  1914. return version_tuple(version) < version_tuple(limit)
  1915. except ValueError:
  1916. return not assume_new
  1917. def ytdl_is_updateable():
  1918. """ Returns if youtube-dl can be updated with -U """
  1919. from zipimport import zipimporter
  1920. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  1921. def args_to_str(args):
  1922. # Get a short string representation for a subprocess command
  1923. return ' '.join(compat_shlex_quote(a) for a in args)
  1924. def error_to_compat_str(err):
  1925. err_str = str(err)
  1926. # On python 2 error byte string must be decoded with proper
  1927. # encoding rather than ascii
  1928. if sys.version_info[0] < 3:
  1929. err_str = err_str.decode(preferredencoding())
  1930. return err_str
  1931. def mimetype2ext(mt):
  1932. if mt is None:
  1933. return None
  1934. ext = {
  1935. 'audio/mp4': 'm4a',
  1936. # Per RFC 3003, audio/mpeg can be .mp1, .mp2 or .mp3. Here use .mp3 as
  1937. # it's the most popular one
  1938. 'audio/mpeg': 'mp3',
  1939. }.get(mt)
  1940. if ext is not None:
  1941. return ext
  1942. _, _, res = mt.rpartition('/')
  1943. res = res.split(';')[0].strip().lower()
  1944. return {
  1945. '3gpp': '3gp',
  1946. 'smptett+xml': 'tt',
  1947. 'ttaf+xml': 'dfxp',
  1948. 'ttml+xml': 'ttml',
  1949. 'x-flv': 'flv',
  1950. 'x-mp4-fragmented': 'mp4',
  1951. 'x-ms-sami': 'sami',
  1952. 'x-ms-wmv': 'wmv',
  1953. 'mpegurl': 'm3u8',
  1954. 'x-mpegurl': 'm3u8',
  1955. 'vnd.apple.mpegurl': 'm3u8',
  1956. 'dash+xml': 'mpd',
  1957. 'f4m+xml': 'f4m',
  1958. 'hds+xml': 'f4m',
  1959. 'vnd.ms-sstr+xml': 'ism',
  1960. 'quicktime': 'mov',
  1961. 'mp2t': 'ts',
  1962. }.get(res, res)
  1963. def parse_codecs(codecs_str):
  1964. # http://tools.ietf.org/html/rfc6381
  1965. if not codecs_str:
  1966. return {}
  1967. splited_codecs = list(filter(None, map(
  1968. lambda str: str.strip(), codecs_str.strip().strip(',').split(','))))
  1969. vcodec, acodec = None, None
  1970. for full_codec in splited_codecs:
  1971. codec = full_codec.split('.')[0]
  1972. if codec in ('avc1', 'avc2', 'avc3', 'avc4', 'vp9', 'vp8', 'hev1', 'hev2', 'h263', 'h264', 'mp4v', 'hvc1'):
  1973. if not vcodec:
  1974. vcodec = full_codec
  1975. elif codec in ('mp4a', 'opus', 'vorbis', 'mp3', 'aac', 'ac-3', 'ec-3', 'eac3', 'dtsc', 'dtse', 'dtsh', 'dtsl'):
  1976. if not acodec:
  1977. acodec = full_codec
  1978. else:
  1979. write_string('WARNING: Unknown codec %s\n' % full_codec, sys.stderr)
  1980. if not vcodec and not acodec:
  1981. if len(splited_codecs) == 2:
  1982. return {
  1983. 'vcodec': vcodec,
  1984. 'acodec': acodec,
  1985. }
  1986. elif len(splited_codecs) == 1:
  1987. return {
  1988. 'vcodec': 'none',
  1989. 'acodec': vcodec,
  1990. }
  1991. else:
  1992. return {
  1993. 'vcodec': vcodec or 'none',
  1994. 'acodec': acodec or 'none',
  1995. }
  1996. return {}
  1997. def urlhandle_detect_ext(url_handle):
  1998. getheader = url_handle.headers.get
  1999. cd = getheader('Content-Disposition')
  2000. if cd:
  2001. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  2002. if m:
  2003. e = determine_ext(m.group('filename'), default_ext=None)
  2004. if e:
  2005. return e
  2006. return mimetype2ext(getheader('Content-Type'))
  2007. def encode_data_uri(data, mime_type):
  2008. return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
  2009. def age_restricted(content_limit, age_limit):
  2010. """ Returns True iff the content should be blocked """
  2011. if age_limit is None: # No limit set
  2012. return False
  2013. if content_limit is None:
  2014. return False # Content available for everyone
  2015. return age_limit < content_limit
  2016. def is_html(first_bytes):
  2017. """ Detect whether a file contains HTML by examining its first bytes. """
  2018. BOMS = [
  2019. (b'\xef\xbb\xbf', 'utf-8'),
  2020. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  2021. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  2022. (b'\xff\xfe', 'utf-16-le'),
  2023. (b'\xfe\xff', 'utf-16-be'),
  2024. ]
  2025. for bom, enc in BOMS:
  2026. if first_bytes.startswith(bom):
  2027. s = first_bytes[len(bom):].decode(enc, 'replace')
  2028. break
  2029. else:
  2030. s = first_bytes.decode('utf-8', 'replace')
  2031. return re.match(r'^\s*<', s)
  2032. def determine_protocol(info_dict):
  2033. protocol = info_dict.get('protocol')
  2034. if protocol is not None:
  2035. return protocol
  2036. url = info_dict['url']
  2037. if url.startswith('rtmp'):
  2038. return 'rtmp'
  2039. elif url.startswith('mms'):
  2040. return 'mms'
  2041. elif url.startswith('rtsp'):
  2042. return 'rtsp'
  2043. ext = determine_ext(url)
  2044. if ext == 'm3u8':
  2045. return 'm3u8'
  2046. elif ext == 'f4m':
  2047. return 'f4m'
  2048. return compat_urllib_parse_urlparse(url).scheme
  2049. def render_table(header_row, data):
  2050. """ Render a list of rows, each as a list of values """
  2051. table = [header_row] + data
  2052. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  2053. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  2054. return '\n'.join(format_str % tuple(row) for row in table)
  2055. def _match_one(filter_part, dct):
  2056. COMPARISON_OPERATORS = {
  2057. '<': operator.lt,
  2058. '<=': operator.le,
  2059. '>': operator.gt,
  2060. '>=': operator.ge,
  2061. '=': operator.eq,
  2062. '!=': operator.ne,
  2063. }
  2064. operator_rex = re.compile(r'''(?x)\s*
  2065. (?P<key>[a-z_]+)
  2066. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  2067. (?:
  2068. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  2069. (?P<quote>["\'])(?P<quotedstrval>(?:\\.|(?!(?P=quote)|\\).)+?)(?P=quote)|
  2070. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  2071. )
  2072. \s*$
  2073. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  2074. m = operator_rex.search(filter_part)
  2075. if m:
  2076. op = COMPARISON_OPERATORS[m.group('op')]
  2077. actual_value = dct.get(m.group('key'))
  2078. if (m.group('quotedstrval') is not None or
  2079. m.group('strval') is not None or
  2080. # If the original field is a string and matching comparisonvalue is
  2081. # a number we should respect the origin of the original field
  2082. # and process comparison value as a string (see
  2083. # https://github.com/rg3/youtube-dl/issues/11082).
  2084. actual_value is not None and m.group('intval') is not None and
  2085. isinstance(actual_value, compat_str)):
  2086. if m.group('op') not in ('=', '!='):
  2087. raise ValueError(
  2088. 'Operator %s does not support string values!' % m.group('op'))
  2089. comparison_value = m.group('quotedstrval') or m.group('strval') or m.group('intval')
  2090. quote = m.group('quote')
  2091. if quote is not None:
  2092. comparison_value = comparison_value.replace(r'\%s' % quote, quote)
  2093. else:
  2094. try:
  2095. comparison_value = int(m.group('intval'))
  2096. except ValueError:
  2097. comparison_value = parse_filesize(m.group('intval'))
  2098. if comparison_value is None:
  2099. comparison_value = parse_filesize(m.group('intval') + 'B')
  2100. if comparison_value is None:
  2101. raise ValueError(
  2102. 'Invalid integer value %r in filter part %r' % (
  2103. m.group('intval'), filter_part))
  2104. if actual_value is None:
  2105. return m.group('none_inclusive')
  2106. return op(actual_value, comparison_value)
  2107. UNARY_OPERATORS = {
  2108. '': lambda v: (v is True) if isinstance(v, bool) else (v is not None),
  2109. '!': lambda v: (v is False) if isinstance(v, bool) else (v is None),
  2110. }
  2111. operator_rex = re.compile(r'''(?x)\s*
  2112. (?P<op>%s)\s*(?P<key>[a-z_]+)
  2113. \s*$
  2114. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  2115. m = operator_rex.search(filter_part)
  2116. if m:
  2117. op = UNARY_OPERATORS[m.group('op')]
  2118. actual_value = dct.get(m.group('key'))
  2119. return op(actual_value)
  2120. raise ValueError('Invalid filter part %r' % filter_part)
  2121. def match_str(filter_str, dct):
  2122. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  2123. return all(
  2124. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  2125. def match_filter_func(filter_str):
  2126. def _match_func(info_dict):
  2127. if match_str(filter_str, info_dict):
  2128. return None
  2129. else:
  2130. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  2131. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  2132. return _match_func
  2133. def parse_dfxp_time_expr(time_expr):
  2134. if not time_expr:
  2135. return
  2136. mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
  2137. if mobj:
  2138. return float(mobj.group('time_offset'))
  2139. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
  2140. if mobj:
  2141. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
  2142. def srt_subtitles_timecode(seconds):
  2143. return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
  2144. def dfxp2srt(dfxp_data):
  2145. '''
  2146. @param dfxp_data A bytes-like object containing DFXP data
  2147. @returns A unicode object containing converted SRT data
  2148. '''
  2149. LEGACY_NAMESPACES = (
  2150. (b'http://www.w3.org/ns/ttml', [
  2151. b'http://www.w3.org/2004/11/ttaf1',
  2152. b'http://www.w3.org/2006/04/ttaf1',
  2153. b'http://www.w3.org/2006/10/ttaf1',
  2154. ]),
  2155. (b'http://www.w3.org/ns/ttml#styling', [
  2156. b'http://www.w3.org/ns/ttml#style',
  2157. ]),
  2158. )
  2159. SUPPORTED_STYLING = [
  2160. 'color',
  2161. 'fontFamily',
  2162. 'fontSize',
  2163. 'fontStyle',
  2164. 'fontWeight',
  2165. 'textDecoration'
  2166. ]
  2167. _x = functools.partial(xpath_with_ns, ns_map={
  2168. 'xml': 'http://www.w3.org/XML/1998/namespace',
  2169. 'ttml': 'http://www.w3.org/ns/ttml',
  2170. 'tts': 'http://www.w3.org/ns/ttml#styling',
  2171. })
  2172. styles = {}
  2173. default_style = {}
  2174. class TTMLPElementParser(object):
  2175. _out = ''
  2176. _unclosed_elements = []
  2177. _applied_styles = []
  2178. def start(self, tag, attrib):
  2179. if tag in (_x('ttml:br'), 'br'):
  2180. self._out += '\n'
  2181. else:
  2182. unclosed_elements = []
  2183. style = {}
  2184. element_style_id = attrib.get('style')
  2185. if default_style:
  2186. style.update(default_style)
  2187. if element_style_id:
  2188. style.update(styles.get(element_style_id, {}))
  2189. for prop in SUPPORTED_STYLING:
  2190. prop_val = attrib.get(_x('tts:' + prop))
  2191. if prop_val:
  2192. style[prop] = prop_val
  2193. if style:
  2194. font = ''
  2195. for k, v in sorted(style.items()):
  2196. if self._applied_styles and self._applied_styles[-1].get(k) == v:
  2197. continue
  2198. if k == 'color':
  2199. font += ' color="%s"' % v
  2200. elif k == 'fontSize':
  2201. font += ' size="%s"' % v
  2202. elif k == 'fontFamily':
  2203. font += ' face="%s"' % v
  2204. elif k == 'fontWeight' and v == 'bold':
  2205. self._out += '<b>'
  2206. unclosed_elements.append('b')
  2207. elif k == 'fontStyle' and v == 'italic':
  2208. self._out += '<i>'
  2209. unclosed_elements.append('i')
  2210. elif k == 'textDecoration' and v == 'underline':
  2211. self._out += '<u>'
  2212. unclosed_elements.append('u')
  2213. if font:
  2214. self._out += '<font' + font + '>'
  2215. unclosed_elements.append('font')
  2216. applied_style = {}
  2217. if self._applied_styles:
  2218. applied_style.update(self._applied_styles[-1])
  2219. applied_style.update(style)
  2220. self._applied_styles.append(applied_style)
  2221. self._unclosed_elements.append(unclosed_elements)
  2222. def end(self, tag):
  2223. if tag not in (_x('ttml:br'), 'br'):
  2224. unclosed_elements = self._unclosed_elements.pop()
  2225. for element in reversed(unclosed_elements):
  2226. self._out += '</%s>' % element
  2227. if unclosed_elements and self._applied_styles:
  2228. self._applied_styles.pop()
  2229. def data(self, data):
  2230. self._out += data
  2231. def close(self):
  2232. return self._out.strip()
  2233. def parse_node(node):
  2234. target = TTMLPElementParser()
  2235. parser = xml.etree.ElementTree.XMLParser(target=target)
  2236. parser.feed(xml.etree.ElementTree.tostring(node))
  2237. return parser.close()
  2238. for k, v in LEGACY_NAMESPACES:
  2239. for ns in v:
  2240. dfxp_data = dfxp_data.replace(ns, k)
  2241. dfxp = compat_etree_fromstring(dfxp_data)
  2242. out = []
  2243. paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall('.//p')
  2244. if not paras:
  2245. raise ValueError('Invalid dfxp/TTML subtitle')
  2246. repeat = False
  2247. while True:
  2248. for style in dfxp.findall(_x('.//ttml:style')):
  2249. style_id = style.get('id') or style.get(_x('xml:id'))
  2250. if not style_id:
  2251. continue
  2252. parent_style_id = style.get('style')
  2253. if parent_style_id:
  2254. if parent_style_id not in styles:
  2255. repeat = True
  2256. continue
  2257. styles[style_id] = styles[parent_style_id].copy()
  2258. for prop in SUPPORTED_STYLING:
  2259. prop_val = style.get(_x('tts:' + prop))
  2260. if prop_val:
  2261. styles.setdefault(style_id, {})[prop] = prop_val
  2262. if repeat:
  2263. repeat = False
  2264. else:
  2265. break
  2266. for p in ('body', 'div'):
  2267. ele = xpath_element(dfxp, [_x('.//ttml:' + p), './/' + p])
  2268. if ele is None:
  2269. continue
  2270. style = styles.get(ele.get('style'))
  2271. if not style:
  2272. continue
  2273. default_style.update(style)
  2274. for para, index in zip(paras, itertools.count(1)):
  2275. begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
  2276. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  2277. dur = parse_dfxp_time_expr(para.attrib.get('dur'))
  2278. if begin_time is None:
  2279. continue
  2280. if not end_time:
  2281. if not dur:
  2282. continue
  2283. end_time = begin_time + dur
  2284. out.append('%d\n%s --> %s\n%s\n\n' % (
  2285. index,
  2286. srt_subtitles_timecode(begin_time),
  2287. srt_subtitles_timecode(end_time),
  2288. parse_node(para)))
  2289. return ''.join(out)
  2290. def cli_option(params, command_option, param):
  2291. param = params.get(param)
  2292. if param:
  2293. param = compat_str(param)
  2294. return [command_option, param] if param is not None else []
  2295. def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
  2296. param = params.get(param)
  2297. if param is None:
  2298. return []
  2299. assert isinstance(param, bool)
  2300. if separator:
  2301. return [command_option + separator + (true_value if param else false_value)]
  2302. return [command_option, true_value if param else false_value]
  2303. def cli_valueless_option(params, command_option, param, expected_value=True):
  2304. param = params.get(param)
  2305. return [command_option] if param == expected_value else []
  2306. def cli_configuration_args(params, param, default=[]):
  2307. ex_args = params.get(param)
  2308. if ex_args is None:
  2309. return default
  2310. assert isinstance(ex_args, list)
  2311. return ex_args
  2312. class ISO639Utils(object):
  2313. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  2314. _lang_map = {
  2315. 'aa': 'aar',
  2316. 'ab': 'abk',
  2317. 'ae': 'ave',
  2318. 'af': 'afr',
  2319. 'ak': 'aka',
  2320. 'am': 'amh',
  2321. 'an': 'arg',
  2322. 'ar': 'ara',
  2323. 'as': 'asm',
  2324. 'av': 'ava',
  2325. 'ay': 'aym',
  2326. 'az': 'aze',
  2327. 'ba': 'bak',
  2328. 'be': 'bel',
  2329. 'bg': 'bul',
  2330. 'bh': 'bih',
  2331. 'bi': 'bis',
  2332. 'bm': 'bam',
  2333. 'bn': 'ben',
  2334. 'bo': 'bod',
  2335. 'br': 'bre',
  2336. 'bs': 'bos',
  2337. 'ca': 'cat',
  2338. 'ce': 'che',
  2339. 'ch': 'cha',
  2340. 'co': 'cos',
  2341. 'cr': 'cre',
  2342. 'cs': 'ces',
  2343. 'cu': 'chu',
  2344. 'cv': 'chv',
  2345. 'cy': 'cym',
  2346. 'da': 'dan',
  2347. 'de': 'deu',
  2348. 'dv': 'div',
  2349. 'dz': 'dzo',
  2350. 'ee': 'ewe',
  2351. 'el': 'ell',
  2352. 'en': 'eng',
  2353. 'eo': 'epo',
  2354. 'es': 'spa',
  2355. 'et': 'est',
  2356. 'eu': 'eus',
  2357. 'fa': 'fas',
  2358. 'ff': 'ful',
  2359. 'fi': 'fin',
  2360. 'fj': 'fij',
  2361. 'fo': 'fao',
  2362. 'fr': 'fra',
  2363. 'fy': 'fry',
  2364. 'ga': 'gle',
  2365. 'gd': 'gla',
  2366. 'gl': 'glg',
  2367. 'gn': 'grn',
  2368. 'gu': 'guj',
  2369. 'gv': 'glv',
  2370. 'ha': 'hau',
  2371. 'he': 'heb',
  2372. 'hi': 'hin',
  2373. 'ho': 'hmo',
  2374. 'hr': 'hrv',
  2375. 'ht': 'hat',
  2376. 'hu': 'hun',
  2377. 'hy': 'hye',
  2378. 'hz': 'her',
  2379. 'ia': 'ina',
  2380. 'id': 'ind',
  2381. 'ie': 'ile',
  2382. 'ig': 'ibo',
  2383. 'ii': 'iii',
  2384. 'ik': 'ipk',
  2385. 'io': 'ido',
  2386. 'is': 'isl',
  2387. 'it': 'ita',
  2388. 'iu': 'iku',
  2389. 'ja': 'jpn',
  2390. 'jv': 'jav',
  2391. 'ka': 'kat',
  2392. 'kg': 'kon',
  2393. 'ki': 'kik',
  2394. 'kj': 'kua',
  2395. 'kk': 'kaz',
  2396. 'kl': 'kal',
  2397. 'km': 'khm',
  2398. 'kn': 'kan',
  2399. 'ko': 'kor',
  2400. 'kr': 'kau',
  2401. 'ks': 'kas',
  2402. 'ku': 'kur',
  2403. 'kv': 'kom',
  2404. 'kw': 'cor',
  2405. 'ky': 'kir',
  2406. 'la': 'lat',
  2407. 'lb': 'ltz',
  2408. 'lg': 'lug',
  2409. 'li': 'lim',
  2410. 'ln': 'lin',
  2411. 'lo': 'lao',
  2412. 'lt': 'lit',
  2413. 'lu': 'lub',
  2414. 'lv': 'lav',
  2415. 'mg': 'mlg',
  2416. 'mh': 'mah',
  2417. 'mi': 'mri',
  2418. 'mk': 'mkd',
  2419. 'ml': 'mal',
  2420. 'mn': 'mon',
  2421. 'mr': 'mar',
  2422. 'ms': 'msa',
  2423. 'mt': 'mlt',
  2424. 'my': 'mya',
  2425. 'na': 'nau',
  2426. 'nb': 'nob',
  2427. 'nd': 'nde',
  2428. 'ne': 'nep',
  2429. 'ng': 'ndo',
  2430. 'nl': 'nld',
  2431. 'nn': 'nno',
  2432. 'no': 'nor',
  2433. 'nr': 'nbl',
  2434. 'nv': 'nav',
  2435. 'ny': 'nya',
  2436. 'oc': 'oci',
  2437. 'oj': 'oji',
  2438. 'om': 'orm',
  2439. 'or': 'ori',
  2440. 'os': 'oss',
  2441. 'pa': 'pan',
  2442. 'pi': 'pli',
  2443. 'pl': 'pol',
  2444. 'ps': 'pus',
  2445. 'pt': 'por',
  2446. 'qu': 'que',
  2447. 'rm': 'roh',
  2448. 'rn': 'run',
  2449. 'ro': 'ron',
  2450. 'ru': 'rus',
  2451. 'rw': 'kin',
  2452. 'sa': 'san',
  2453. 'sc': 'srd',
  2454. 'sd': 'snd',
  2455. 'se': 'sme',
  2456. 'sg': 'sag',
  2457. 'si': 'sin',
  2458. 'sk': 'slk',
  2459. 'sl': 'slv',
  2460. 'sm': 'smo',
  2461. 'sn': 'sna',
  2462. 'so': 'som',
  2463. 'sq': 'sqi',
  2464. 'sr': 'srp',
  2465. 'ss': 'ssw',
  2466. 'st': 'sot',
  2467. 'su': 'sun',
  2468. 'sv': 'swe',
  2469. 'sw': 'swa',
  2470. 'ta': 'tam',
  2471. 'te': 'tel',
  2472. 'tg': 'tgk',
  2473. 'th': 'tha',
  2474. 'ti': 'tir',
  2475. 'tk': 'tuk',
  2476. 'tl': 'tgl',
  2477. 'tn': 'tsn',
  2478. 'to': 'ton',
  2479. 'tr': 'tur',
  2480. 'ts': 'tso',
  2481. 'tt': 'tat',
  2482. 'tw': 'twi',
  2483. 'ty': 'tah',
  2484. 'ug': 'uig',
  2485. 'uk': 'ukr',
  2486. 'ur': 'urd',
  2487. 'uz': 'uzb',
  2488. 've': 'ven',
  2489. 'vi': 'vie',
  2490. 'vo': 'vol',
  2491. 'wa': 'wln',
  2492. 'wo': 'wol',
  2493. 'xh': 'xho',
  2494. 'yi': 'yid',
  2495. 'yo': 'yor',
  2496. 'za': 'zha',
  2497. 'zh': 'zho',
  2498. 'zu': 'zul',
  2499. }
  2500. @classmethod
  2501. def short2long(cls, code):
  2502. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  2503. return cls._lang_map.get(code[:2])
  2504. @classmethod
  2505. def long2short(cls, code):
  2506. """Convert language code from ISO 639-2/T to ISO 639-1"""
  2507. for short_name, long_name in cls._lang_map.items():
  2508. if long_name == code:
  2509. return short_name
  2510. class ISO3166Utils(object):
  2511. # From http://data.okfn.org/data/core/country-list
  2512. _country_map = {
  2513. 'AF': 'Afghanistan',
  2514. 'AX': 'Åland Islands',
  2515. 'AL': 'Albania',
  2516. 'DZ': 'Algeria',
  2517. 'AS': 'American Samoa',
  2518. 'AD': 'Andorra',
  2519. 'AO': 'Angola',
  2520. 'AI': 'Anguilla',
  2521. 'AQ': 'Antarctica',
  2522. 'AG': 'Antigua and Barbuda',
  2523. 'AR': 'Argentina',
  2524. 'AM': 'Armenia',
  2525. 'AW': 'Aruba',
  2526. 'AU': 'Australia',
  2527. 'AT': 'Austria',
  2528. 'AZ': 'Azerbaijan',
  2529. 'BS': 'Bahamas',
  2530. 'BH': 'Bahrain',
  2531. 'BD': 'Bangladesh',
  2532. 'BB': 'Barbados',
  2533. 'BY': 'Belarus',
  2534. 'BE': 'Belgium',
  2535. 'BZ': 'Belize',
  2536. 'BJ': 'Benin',
  2537. 'BM': 'Bermuda',
  2538. 'BT': 'Bhutan',
  2539. 'BO': 'Bolivia, Plurinational State of',
  2540. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  2541. 'BA': 'Bosnia and Herzegovina',
  2542. 'BW': 'Botswana',
  2543. 'BV': 'Bouvet Island',
  2544. 'BR': 'Brazil',
  2545. 'IO': 'British Indian Ocean Territory',
  2546. 'BN': 'Brunei Darussalam',
  2547. 'BG': 'Bulgaria',
  2548. 'BF': 'Burkina Faso',
  2549. 'BI': 'Burundi',
  2550. 'KH': 'Cambodia',
  2551. 'CM': 'Cameroon',
  2552. 'CA': 'Canada',
  2553. 'CV': 'Cape Verde',
  2554. 'KY': 'Cayman Islands',
  2555. 'CF': 'Central African Republic',
  2556. 'TD': 'Chad',
  2557. 'CL': 'Chile',
  2558. 'CN': 'China',
  2559. 'CX': 'Christmas Island',
  2560. 'CC': 'Cocos (Keeling) Islands',
  2561. 'CO': 'Colombia',
  2562. 'KM': 'Comoros',
  2563. 'CG': 'Congo',
  2564. 'CD': 'Congo, the Democratic Republic of the',
  2565. 'CK': 'Cook Islands',
  2566. 'CR': 'Costa Rica',
  2567. 'CI': 'Côte d\'Ivoire',
  2568. 'HR': 'Croatia',
  2569. 'CU': 'Cuba',
  2570. 'CW': 'Curaçao',
  2571. 'CY': 'Cyprus',
  2572. 'CZ': 'Czech Republic',
  2573. 'DK': 'Denmark',
  2574. 'DJ': 'Djibouti',
  2575. 'DM': 'Dominica',
  2576. 'DO': 'Dominican Republic',
  2577. 'EC': 'Ecuador',
  2578. 'EG': 'Egypt',
  2579. 'SV': 'El Salvador',
  2580. 'GQ': 'Equatorial Guinea',
  2581. 'ER': 'Eritrea',
  2582. 'EE': 'Estonia',
  2583. 'ET': 'Ethiopia',
  2584. 'FK': 'Falkland Islands (Malvinas)',
  2585. 'FO': 'Faroe Islands',
  2586. 'FJ': 'Fiji',
  2587. 'FI': 'Finland',
  2588. 'FR': 'France',
  2589. 'GF': 'French Guiana',
  2590. 'PF': 'French Polynesia',
  2591. 'TF': 'French Southern Territories',
  2592. 'GA': 'Gabon',
  2593. 'GM': 'Gambia',
  2594. 'GE': 'Georgia',
  2595. 'DE': 'Germany',
  2596. 'GH': 'Ghana',
  2597. 'GI': 'Gibraltar',
  2598. 'GR': 'Greece',
  2599. 'GL': 'Greenland',
  2600. 'GD': 'Grenada',
  2601. 'GP': 'Guadeloupe',
  2602. 'GU': 'Guam',
  2603. 'GT': 'Guatemala',
  2604. 'GG': 'Guernsey',
  2605. 'GN': 'Guinea',
  2606. 'GW': 'Guinea-Bissau',
  2607. 'GY': 'Guyana',
  2608. 'HT': 'Haiti',
  2609. 'HM': 'Heard Island and McDonald Islands',
  2610. 'VA': 'Holy See (Vatican City State)',
  2611. 'HN': 'Honduras',
  2612. 'HK': 'Hong Kong',
  2613. 'HU': 'Hungary',
  2614. 'IS': 'Iceland',
  2615. 'IN': 'India',
  2616. 'ID': 'Indonesia',
  2617. 'IR': 'Iran, Islamic Republic of',
  2618. 'IQ': 'Iraq',
  2619. 'IE': 'Ireland',
  2620. 'IM': 'Isle of Man',
  2621. 'IL': 'Israel',
  2622. 'IT': 'Italy',
  2623. 'JM': 'Jamaica',
  2624. 'JP': 'Japan',
  2625. 'JE': 'Jersey',
  2626. 'JO': 'Jordan',
  2627. 'KZ': 'Kazakhstan',
  2628. 'KE': 'Kenya',
  2629. 'KI': 'Kiribati',
  2630. 'KP': 'Korea, Democratic People\'s Republic of',
  2631. 'KR': 'Korea, Republic of',
  2632. 'KW': 'Kuwait',
  2633. 'KG': 'Kyrgyzstan',
  2634. 'LA': 'Lao People\'s Democratic Republic',
  2635. 'LV': 'Latvia',
  2636. 'LB': 'Lebanon',
  2637. 'LS': 'Lesotho',
  2638. 'LR': 'Liberia',
  2639. 'LY': 'Libya',
  2640. 'LI': 'Liechtenstein',
  2641. 'LT': 'Lithuania',
  2642. 'LU': 'Luxembourg',
  2643. 'MO': 'Macao',
  2644. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  2645. 'MG': 'Madagascar',
  2646. 'MW': 'Malawi',
  2647. 'MY': 'Malaysia',
  2648. 'MV': 'Maldives',
  2649. 'ML': 'Mali',
  2650. 'MT': 'Malta',
  2651. 'MH': 'Marshall Islands',
  2652. 'MQ': 'Martinique',
  2653. 'MR': 'Mauritania',
  2654. 'MU': 'Mauritius',
  2655. 'YT': 'Mayotte',
  2656. 'MX': 'Mexico',
  2657. 'FM': 'Micronesia, Federated States of',
  2658. 'MD': 'Moldova, Republic of',
  2659. 'MC': 'Monaco',
  2660. 'MN': 'Mongolia',
  2661. 'ME': 'Montenegro',
  2662. 'MS': 'Montserrat',
  2663. 'MA': 'Morocco',
  2664. 'MZ': 'Mozambique',
  2665. 'MM': 'Myanmar',
  2666. 'NA': 'Namibia',
  2667. 'NR': 'Nauru',
  2668. 'NP': 'Nepal',
  2669. 'NL': 'Netherlands',
  2670. 'NC': 'New Caledonia',
  2671. 'NZ': 'New Zealand',
  2672. 'NI': 'Nicaragua',
  2673. 'NE': 'Niger',
  2674. 'NG': 'Nigeria',
  2675. 'NU': 'Niue',
  2676. 'NF': 'Norfolk Island',
  2677. 'MP': 'Northern Mariana Islands',
  2678. 'NO': 'Norway',
  2679. 'OM': 'Oman',
  2680. 'PK': 'Pakistan',
  2681. 'PW': 'Palau',
  2682. 'PS': 'Palestine, State of',
  2683. 'PA': 'Panama',
  2684. 'PG': 'Papua New Guinea',
  2685. 'PY': 'Paraguay',
  2686. 'PE': 'Peru',
  2687. 'PH': 'Philippines',
  2688. 'PN': 'Pitcairn',
  2689. 'PL': 'Poland',
  2690. 'PT': 'Portugal',
  2691. 'PR': 'Puerto Rico',
  2692. 'QA': 'Qatar',
  2693. 'RE': 'Réunion',
  2694. 'RO': 'Romania',
  2695. 'RU': 'Russian Federation',
  2696. 'RW': 'Rwanda',
  2697. 'BL': 'Saint Barthélemy',
  2698. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  2699. 'KN': 'Saint Kitts and Nevis',
  2700. 'LC': 'Saint Lucia',
  2701. 'MF': 'Saint Martin (French part)',
  2702. 'PM': 'Saint Pierre and Miquelon',
  2703. 'VC': 'Saint Vincent and the Grenadines',
  2704. 'WS': 'Samoa',
  2705. 'SM': 'San Marino',
  2706. 'ST': 'Sao Tome and Principe',
  2707. 'SA': 'Saudi Arabia',
  2708. 'SN': 'Senegal',
  2709. 'RS': 'Serbia',
  2710. 'SC': 'Seychelles',
  2711. 'SL': 'Sierra Leone',
  2712. 'SG': 'Singapore',
  2713. 'SX': 'Sint Maarten (Dutch part)',
  2714. 'SK': 'Slovakia',
  2715. 'SI': 'Slovenia',
  2716. 'SB': 'Solomon Islands',
  2717. 'SO': 'Somalia',
  2718. 'ZA': 'South Africa',
  2719. 'GS': 'South Georgia and the South Sandwich Islands',
  2720. 'SS': 'South Sudan',
  2721. 'ES': 'Spain',
  2722. 'LK': 'Sri Lanka',
  2723. 'SD': 'Sudan',
  2724. 'SR': 'Suriname',
  2725. 'SJ': 'Svalbard and Jan Mayen',
  2726. 'SZ': 'Swaziland',
  2727. 'SE': 'Sweden',
  2728. 'CH': 'Switzerland',
  2729. 'SY': 'Syrian Arab Republic',
  2730. 'TW': 'Taiwan, Province of China',
  2731. 'TJ': 'Tajikistan',
  2732. 'TZ': 'Tanzania, United Republic of',
  2733. 'TH': 'Thailand',
  2734. 'TL': 'Timor-Leste',
  2735. 'TG': 'Togo',
  2736. 'TK': 'Tokelau',
  2737. 'TO': 'Tonga',
  2738. 'TT': 'Trinidad and Tobago',
  2739. 'TN': 'Tunisia',
  2740. 'TR': 'Turkey',
  2741. 'TM': 'Turkmenistan',
  2742. 'TC': 'Turks and Caicos Islands',
  2743. 'TV': 'Tuvalu',
  2744. 'UG': 'Uganda',
  2745. 'UA': 'Ukraine',
  2746. 'AE': 'United Arab Emirates',
  2747. 'GB': 'United Kingdom',
  2748. 'US': 'United States',
  2749. 'UM': 'United States Minor Outlying Islands',
  2750. 'UY': 'Uruguay',
  2751. 'UZ': 'Uzbekistan',
  2752. 'VU': 'Vanuatu',
  2753. 'VE': 'Venezuela, Bolivarian Republic of',
  2754. 'VN': 'Viet Nam',
  2755. 'VG': 'Virgin Islands, British',
  2756. 'VI': 'Virgin Islands, U.S.',
  2757. 'WF': 'Wallis and Futuna',
  2758. 'EH': 'Western Sahara',
  2759. 'YE': 'Yemen',
  2760. 'ZM': 'Zambia',
  2761. 'ZW': 'Zimbabwe',
  2762. }
  2763. @classmethod
  2764. def short2full(cls, code):
  2765. """Convert an ISO 3166-2 country code to the corresponding full name"""
  2766. return cls._country_map.get(code.upper())
  2767. class GeoUtils(object):
  2768. # Major IPv4 address blocks per country
  2769. _country_ip_map = {
  2770. 'AD': '85.94.160.0/19',
  2771. 'AE': '94.200.0.0/13',
  2772. 'AF': '149.54.0.0/17',
  2773. 'AG': '209.59.64.0/18',
  2774. 'AI': '204.14.248.0/21',
  2775. 'AL': '46.99.0.0/16',
  2776. 'AM': '46.70.0.0/15',
  2777. 'AO': '105.168.0.0/13',
  2778. 'AP': '159.117.192.0/21',
  2779. 'AR': '181.0.0.0/12',
  2780. 'AS': '202.70.112.0/20',
  2781. 'AT': '84.112.0.0/13',
  2782. 'AU': '1.128.0.0/11',
  2783. 'AW': '181.41.0.0/18',
  2784. 'AZ': '5.191.0.0/16',
  2785. 'BA': '31.176.128.0/17',
  2786. 'BB': '65.48.128.0/17',
  2787. 'BD': '114.130.0.0/16',
  2788. 'BE': '57.0.0.0/8',
  2789. 'BF': '129.45.128.0/17',
  2790. 'BG': '95.42.0.0/15',
  2791. 'BH': '37.131.0.0/17',
  2792. 'BI': '154.117.192.0/18',
  2793. 'BJ': '137.255.0.0/16',
  2794. 'BL': '192.131.134.0/24',
  2795. 'BM': '196.12.64.0/18',
  2796. 'BN': '156.31.0.0/16',
  2797. 'BO': '161.56.0.0/16',
  2798. 'BQ': '161.0.80.0/20',
  2799. 'BR': '152.240.0.0/12',
  2800. 'BS': '24.51.64.0/18',
  2801. 'BT': '119.2.96.0/19',
  2802. 'BW': '168.167.0.0/16',
  2803. 'BY': '178.120.0.0/13',
  2804. 'BZ': '179.42.192.0/18',
  2805. 'CA': '99.224.0.0/11',
  2806. 'CD': '41.243.0.0/16',
  2807. 'CF': '196.32.200.0/21',
  2808. 'CG': '197.214.128.0/17',
  2809. 'CH': '85.0.0.0/13',
  2810. 'CI': '154.232.0.0/14',
  2811. 'CK': '202.65.32.0/19',
  2812. 'CL': '152.172.0.0/14',
  2813. 'CM': '165.210.0.0/15',
  2814. 'CN': '36.128.0.0/10',
  2815. 'CO': '181.240.0.0/12',
  2816. 'CR': '201.192.0.0/12',
  2817. 'CU': '152.206.0.0/15',
  2818. 'CV': '165.90.96.0/19',
  2819. 'CW': '190.88.128.0/17',
  2820. 'CY': '46.198.0.0/15',
  2821. 'CZ': '88.100.0.0/14',
  2822. 'DE': '53.0.0.0/8',
  2823. 'DJ': '197.241.0.0/17',
  2824. 'DK': '87.48.0.0/12',
  2825. 'DM': '192.243.48.0/20',
  2826. 'DO': '152.166.0.0/15',
  2827. 'DZ': '41.96.0.0/12',
  2828. 'EC': '186.68.0.0/15',
  2829. 'EE': '90.190.0.0/15',
  2830. 'EG': '156.160.0.0/11',
  2831. 'ER': '196.200.96.0/20',
  2832. 'ES': '88.0.0.0/11',
  2833. 'ET': '196.188.0.0/14',
  2834. 'EU': '2.16.0.0/13',
  2835. 'FI': '91.152.0.0/13',
  2836. 'FJ': '144.120.0.0/16',
  2837. 'FM': '119.252.112.0/20',
  2838. 'FO': '88.85.32.0/19',
  2839. 'FR': '90.0.0.0/9',
  2840. 'GA': '41.158.0.0/15',
  2841. 'GB': '25.0.0.0/8',
  2842. 'GD': '74.122.88.0/21',
  2843. 'GE': '31.146.0.0/16',
  2844. 'GF': '161.22.64.0/18',
  2845. 'GG': '62.68.160.0/19',
  2846. 'GH': '45.208.0.0/14',
  2847. 'GI': '85.115.128.0/19',
  2848. 'GL': '88.83.0.0/19',
  2849. 'GM': '160.182.0.0/15',
  2850. 'GN': '197.149.192.0/18',
  2851. 'GP': '104.250.0.0/19',
  2852. 'GQ': '105.235.224.0/20',
  2853. 'GR': '94.64.0.0/13',
  2854. 'GT': '168.234.0.0/16',
  2855. 'GU': '168.123.0.0/16',
  2856. 'GW': '197.214.80.0/20',
  2857. 'GY': '181.41.64.0/18',
  2858. 'HK': '113.252.0.0/14',
  2859. 'HN': '181.210.0.0/16',
  2860. 'HR': '93.136.0.0/13',
  2861. 'HT': '148.102.128.0/17',
  2862. 'HU': '84.0.0.0/14',
  2863. 'ID': '39.192.0.0/10',
  2864. 'IE': '87.32.0.0/12',
  2865. 'IL': '79.176.0.0/13',
  2866. 'IM': '5.62.80.0/20',
  2867. 'IN': '117.192.0.0/10',
  2868. 'IO': '203.83.48.0/21',
  2869. 'IQ': '37.236.0.0/14',
  2870. 'IR': '2.176.0.0/12',
  2871. 'IS': '82.221.0.0/16',
  2872. 'IT': '79.0.0.0/10',
  2873. 'JE': '87.244.64.0/18',
  2874. 'JM': '72.27.0.0/17',
  2875. 'JO': '176.29.0.0/16',
  2876. 'JP': '126.0.0.0/8',
  2877. 'KE': '105.48.0.0/12',
  2878. 'KG': '158.181.128.0/17',
  2879. 'KH': '36.37.128.0/17',
  2880. 'KI': '103.25.140.0/22',
  2881. 'KM': '197.255.224.0/20',
  2882. 'KN': '198.32.32.0/19',
  2883. 'KP': '175.45.176.0/22',
  2884. 'KR': '175.192.0.0/10',
  2885. 'KW': '37.36.0.0/14',
  2886. 'KY': '64.96.0.0/15',
  2887. 'KZ': '2.72.0.0/13',
  2888. 'LA': '115.84.64.0/18',
  2889. 'LB': '178.135.0.0/16',
  2890. 'LC': '192.147.231.0/24',
  2891. 'LI': '82.117.0.0/19',
  2892. 'LK': '112.134.0.0/15',
  2893. 'LR': '41.86.0.0/19',
  2894. 'LS': '129.232.0.0/17',
  2895. 'LT': '78.56.0.0/13',
  2896. 'LU': '188.42.0.0/16',
  2897. 'LV': '46.109.0.0/16',
  2898. 'LY': '41.252.0.0/14',
  2899. 'MA': '105.128.0.0/11',
  2900. 'MC': '88.209.64.0/18',
  2901. 'MD': '37.246.0.0/16',
  2902. 'ME': '178.175.0.0/17',
  2903. 'MF': '74.112.232.0/21',
  2904. 'MG': '154.126.0.0/17',
  2905. 'MH': '117.103.88.0/21',
  2906. 'MK': '77.28.0.0/15',
  2907. 'ML': '154.118.128.0/18',
  2908. 'MM': '37.111.0.0/17',
  2909. 'MN': '49.0.128.0/17',
  2910. 'MO': '60.246.0.0/16',
  2911. 'MP': '202.88.64.0/20',
  2912. 'MQ': '109.203.224.0/19',
  2913. 'MR': '41.188.64.0/18',
  2914. 'MS': '208.90.112.0/22',
  2915. 'MT': '46.11.0.0/16',
  2916. 'MU': '105.16.0.0/12',
  2917. 'MV': '27.114.128.0/18',
  2918. 'MW': '105.234.0.0/16',
  2919. 'MX': '187.192.0.0/11',
  2920. 'MY': '175.136.0.0/13',
  2921. 'MZ': '197.218.0.0/15',
  2922. 'NA': '41.182.0.0/16',
  2923. 'NC': '101.101.0.0/18',
  2924. 'NE': '197.214.0.0/18',
  2925. 'NF': '203.17.240.0/22',
  2926. 'NG': '105.112.0.0/12',
  2927. 'NI': '186.76.0.0/15',
  2928. 'NL': '145.96.0.0/11',
  2929. 'NO': '84.208.0.0/13',
  2930. 'NP': '36.252.0.0/15',
  2931. 'NR': '203.98.224.0/19',
  2932. 'NU': '49.156.48.0/22',
  2933. 'NZ': '49.224.0.0/14',
  2934. 'OM': '5.36.0.0/15',
  2935. 'PA': '186.72.0.0/15',
  2936. 'PE': '186.160.0.0/14',
  2937. 'PF': '123.50.64.0/18',
  2938. 'PG': '124.240.192.0/19',
  2939. 'PH': '49.144.0.0/13',
  2940. 'PK': '39.32.0.0/11',
  2941. 'PL': '83.0.0.0/11',
  2942. 'PM': '70.36.0.0/20',
  2943. 'PR': '66.50.0.0/16',
  2944. 'PS': '188.161.0.0/16',
  2945. 'PT': '85.240.0.0/13',
  2946. 'PW': '202.124.224.0/20',
  2947. 'PY': '181.120.0.0/14',
  2948. 'QA': '37.210.0.0/15',
  2949. 'RE': '139.26.0.0/16',
  2950. 'RO': '79.112.0.0/13',
  2951. 'RS': '178.220.0.0/14',
  2952. 'RU': '5.136.0.0/13',
  2953. 'RW': '105.178.0.0/15',
  2954. 'SA': '188.48.0.0/13',
  2955. 'SB': '202.1.160.0/19',
  2956. 'SC': '154.192.0.0/11',
  2957. 'SD': '154.96.0.0/13',
  2958. 'SE': '78.64.0.0/12',
  2959. 'SG': '152.56.0.0/14',
  2960. 'SI': '188.196.0.0/14',
  2961. 'SK': '78.98.0.0/15',
  2962. 'SL': '197.215.0.0/17',
  2963. 'SM': '89.186.32.0/19',
  2964. 'SN': '41.82.0.0/15',
  2965. 'SO': '197.220.64.0/19',
  2966. 'SR': '186.179.128.0/17',
  2967. 'SS': '105.235.208.0/21',
  2968. 'ST': '197.159.160.0/19',
  2969. 'SV': '168.243.0.0/16',
  2970. 'SX': '190.102.0.0/20',
  2971. 'SY': '5.0.0.0/16',
  2972. 'SZ': '41.84.224.0/19',
  2973. 'TC': '65.255.48.0/20',
  2974. 'TD': '154.68.128.0/19',
  2975. 'TG': '196.168.0.0/14',
  2976. 'TH': '171.96.0.0/13',
  2977. 'TJ': '85.9.128.0/18',
  2978. 'TK': '27.96.24.0/21',
  2979. 'TL': '180.189.160.0/20',
  2980. 'TM': '95.85.96.0/19',
  2981. 'TN': '197.0.0.0/11',
  2982. 'TO': '175.176.144.0/21',
  2983. 'TR': '78.160.0.0/11',
  2984. 'TT': '186.44.0.0/15',
  2985. 'TV': '202.2.96.0/19',
  2986. 'TW': '120.96.0.0/11',
  2987. 'TZ': '156.156.0.0/14',
  2988. 'UA': '93.72.0.0/13',
  2989. 'UG': '154.224.0.0/13',
  2990. 'US': '3.0.0.0/8',
  2991. 'UY': '167.56.0.0/13',
  2992. 'UZ': '82.215.64.0/18',
  2993. 'VA': '212.77.0.0/19',
  2994. 'VC': '24.92.144.0/20',
  2995. 'VE': '186.88.0.0/13',
  2996. 'VG': '172.103.64.0/18',
  2997. 'VI': '146.226.0.0/16',
  2998. 'VN': '14.160.0.0/11',
  2999. 'VU': '202.80.32.0/20',
  3000. 'WF': '117.20.32.0/21',
  3001. 'WS': '202.4.32.0/19',
  3002. 'YE': '134.35.0.0/16',
  3003. 'YT': '41.242.116.0/22',
  3004. 'ZA': '41.0.0.0/11',
  3005. 'ZM': '165.56.0.0/13',
  3006. 'ZW': '41.85.192.0/19',
  3007. }
  3008. @classmethod
  3009. def random_ipv4(cls, code_or_block):
  3010. if len(code_or_block) == 2:
  3011. block = cls._country_ip_map.get(code_or_block.upper())
  3012. if not block:
  3013. return None
  3014. else:
  3015. block = code_or_block
  3016. addr, preflen = block.split('/')
  3017. addr_min = compat_struct_unpack('!L', socket.inet_aton(addr))[0]
  3018. addr_max = addr_min | (0xffffffff >> int(preflen))
  3019. return compat_str(socket.inet_ntoa(
  3020. compat_struct_pack('!L', random.randint(addr_min, addr_max))))
  3021. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  3022. def __init__(self, proxies=None):
  3023. # Set default handlers
  3024. for type in ('http', 'https'):
  3025. setattr(self, '%s_open' % type,
  3026. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  3027. meth(r, proxy, type))
  3028. return compat_urllib_request.ProxyHandler.__init__(self, proxies)
  3029. def proxy_open(self, req, proxy, type):
  3030. req_proxy = req.headers.get('Ytdl-request-proxy')
  3031. if req_proxy is not None:
  3032. proxy = req_proxy
  3033. del req.headers['Ytdl-request-proxy']
  3034. if proxy == '__noproxy__':
  3035. return None # No Proxy
  3036. if compat_urlparse.urlparse(proxy).scheme.lower() in ('socks', 'socks4', 'socks4a', 'socks5'):
  3037. req.add_header('Ytdl-socks-proxy', proxy)
  3038. # youtube-dl's http/https handlers do wrapping the socket with socks
  3039. return None
  3040. return compat_urllib_request.ProxyHandler.proxy_open(
  3041. self, req, proxy, type)
  3042. # Both long_to_bytes and bytes_to_long are adapted from PyCrypto, which is
  3043. # released into Public Domain
  3044. # https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Util/number.py#L387
  3045. def long_to_bytes(n, blocksize=0):
  3046. """long_to_bytes(n:long, blocksize:int) : string
  3047. Convert a long integer to a byte string.
  3048. If optional blocksize is given and greater than zero, pad the front of the
  3049. byte string with binary zeros so that the length is a multiple of
  3050. blocksize.
  3051. """
  3052. # after much testing, this algorithm was deemed to be the fastest
  3053. s = b''
  3054. n = int(n)
  3055. while n > 0:
  3056. s = compat_struct_pack('>I', n & 0xffffffff) + s
  3057. n = n >> 32
  3058. # strip off leading zeros
  3059. for i in range(len(s)):
  3060. if s[i] != b'\000'[0]:
  3061. break
  3062. else:
  3063. # only happens when n == 0
  3064. s = b'\000'
  3065. i = 0
  3066. s = s[i:]
  3067. # add back some pad bytes. this could be done more efficiently w.r.t. the
  3068. # de-padding being done above, but sigh...
  3069. if blocksize > 0 and len(s) % blocksize:
  3070. s = (blocksize - len(s) % blocksize) * b'\000' + s
  3071. return s
  3072. def bytes_to_long(s):
  3073. """bytes_to_long(string) : long
  3074. Convert a byte string to a long integer.
  3075. This is (essentially) the inverse of long_to_bytes().
  3076. """
  3077. acc = 0
  3078. length = len(s)
  3079. if length % 4:
  3080. extra = (4 - length % 4)
  3081. s = b'\000' * extra + s
  3082. length = length + extra
  3083. for i in range(0, length, 4):
  3084. acc = (acc << 32) + compat_struct_unpack('>I', s[i:i + 4])[0]
  3085. return acc
  3086. def ohdave_rsa_encrypt(data, exponent, modulus):
  3087. '''
  3088. Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
  3089. Input:
  3090. data: data to encrypt, bytes-like object
  3091. exponent, modulus: parameter e and N of RSA algorithm, both integer
  3092. Output: hex string of encrypted data
  3093. Limitation: supports one block encryption only
  3094. '''
  3095. payload = int(binascii.hexlify(data[::-1]), 16)
  3096. encrypted = pow(payload, exponent, modulus)
  3097. return '%x' % encrypted
  3098. def pkcs1pad(data, length):
  3099. """
  3100. Padding input data with PKCS#1 scheme
  3101. @param {int[]} data input data
  3102. @param {int} length target length
  3103. @returns {int[]} padded data
  3104. """
  3105. if len(data) > length - 11:
  3106. raise ValueError('Input data too long for PKCS#1 padding')
  3107. pseudo_random = [random.randint(0, 254) for _ in range(length - len(data) - 3)]
  3108. return [0, 2] + pseudo_random + [0] + data
  3109. def encode_base_n(num, n, table=None):
  3110. FULL_TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  3111. if not table:
  3112. table = FULL_TABLE[:n]
  3113. if n > len(table):
  3114. raise ValueError('base %d exceeds table length %d' % (n, len(table)))
  3115. if num == 0:
  3116. return table[0]
  3117. ret = ''
  3118. while num:
  3119. ret = table[num % n] + ret
  3120. num = num // n
  3121. return ret
  3122. def decode_packed_codes(code):
  3123. mobj = re.search(PACKED_CODES_RE, code)
  3124. obfucasted_code, base, count, symbols = mobj.groups()
  3125. base = int(base)
  3126. count = int(count)
  3127. symbols = symbols.split('|')
  3128. symbol_table = {}
  3129. while count:
  3130. count -= 1
  3131. base_n_count = encode_base_n(count, base)
  3132. symbol_table[base_n_count] = symbols[count] or base_n_count
  3133. return re.sub(
  3134. r'\b(\w+)\b', lambda mobj: symbol_table[mobj.group(0)],
  3135. obfucasted_code)
  3136. def parse_m3u8_attributes(attrib):
  3137. info = {}
  3138. for (key, val) in re.findall(r'(?P<key>[A-Z0-9-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)', attrib):
  3139. if val.startswith('"'):
  3140. val = val[1:-1]
  3141. info[key] = val
  3142. return info
  3143. def urshift(val, n):
  3144. return val >> n if val >= 0 else (val + 0x100000000) >> n
  3145. # Based on png2str() written by @gdkchan and improved by @yokrysty
  3146. # Originally posted at https://github.com/rg3/youtube-dl/issues/9706
  3147. def decode_png(png_data):
  3148. # Reference: https://www.w3.org/TR/PNG/
  3149. header = png_data[8:]
  3150. if png_data[:8] != b'\x89PNG\x0d\x0a\x1a\x0a' or header[4:8] != b'IHDR':
  3151. raise IOError('Not a valid PNG file.')
  3152. int_map = {1: '>B', 2: '>H', 4: '>I'}
  3153. unpack_integer = lambda x: compat_struct_unpack(int_map[len(x)], x)[0]
  3154. chunks = []
  3155. while header:
  3156. length = unpack_integer(header[:4])
  3157. header = header[4:]
  3158. chunk_type = header[:4]
  3159. header = header[4:]
  3160. chunk_data = header[:length]
  3161. header = header[length:]
  3162. header = header[4:] # Skip CRC
  3163. chunks.append({
  3164. 'type': chunk_type,
  3165. 'length': length,
  3166. 'data': chunk_data
  3167. })
  3168. ihdr = chunks[0]['data']
  3169. width = unpack_integer(ihdr[:4])
  3170. height = unpack_integer(ihdr[4:8])
  3171. idat = b''
  3172. for chunk in chunks:
  3173. if chunk['type'] == b'IDAT':
  3174. idat += chunk['data']
  3175. if not idat:
  3176. raise IOError('Unable to read PNG data.')
  3177. decompressed_data = bytearray(zlib.decompress(idat))
  3178. stride = width * 3
  3179. pixels = []
  3180. def _get_pixel(idx):
  3181. x = idx % stride
  3182. y = idx // stride
  3183. return pixels[y][x]
  3184. for y in range(height):
  3185. basePos = y * (1 + stride)
  3186. filter_type = decompressed_data[basePos]
  3187. current_row = []
  3188. pixels.append(current_row)
  3189. for x in range(stride):
  3190. color = decompressed_data[1 + basePos + x]
  3191. basex = y * stride + x
  3192. left = 0
  3193. up = 0
  3194. if x > 2:
  3195. left = _get_pixel(basex - 3)
  3196. if y > 0:
  3197. up = _get_pixel(basex - stride)
  3198. if filter_type == 1: # Sub
  3199. color = (color + left) & 0xff
  3200. elif filter_type == 2: # Up
  3201. color = (color + up) & 0xff
  3202. elif filter_type == 3: # Average
  3203. color = (color + ((left + up) >> 1)) & 0xff
  3204. elif filter_type == 4: # Paeth
  3205. a = left
  3206. b = up
  3207. c = 0
  3208. if x > 2 and y > 0:
  3209. c = _get_pixel(basex - stride - 3)
  3210. p = a + b - c
  3211. pa = abs(p - a)
  3212. pb = abs(p - b)
  3213. pc = abs(p - c)
  3214. if pa <= pb and pa <= pc:
  3215. color = (color + a) & 0xff
  3216. elif pb <= pc:
  3217. color = (color + b) & 0xff
  3218. else:
  3219. color = (color + c) & 0xff
  3220. current_row.append(color)
  3221. return width, height, pixels
  3222. def write_xattr(path, key, value):
  3223. # This mess below finds the best xattr tool for the job
  3224. try:
  3225. # try the pyxattr module...
  3226. import xattr
  3227. if hasattr(xattr, 'set'): # pyxattr
  3228. # Unicode arguments are not supported in python-pyxattr until
  3229. # version 0.5.0
  3230. # See https://github.com/rg3/youtube-dl/issues/5498
  3231. pyxattr_required_version = '0.5.0'
  3232. if version_tuple(xattr.__version__) < version_tuple(pyxattr_required_version):
  3233. # TODO: fallback to CLI tools
  3234. raise XAttrUnavailableError(
  3235. 'python-pyxattr is detected but is too old. '
  3236. 'youtube-dl requires %s or above while your version is %s. '
  3237. 'Falling back to other xattr implementations' % (
  3238. pyxattr_required_version, xattr.__version__))
  3239. setxattr = xattr.set
  3240. else: # xattr
  3241. setxattr = xattr.setxattr
  3242. try:
  3243. setxattr(path, key, value)
  3244. except EnvironmentError as e:
  3245. raise XAttrMetadataError(e.errno, e.strerror)
  3246. except ImportError:
  3247. if compat_os_name == 'nt':
  3248. # Write xattrs to NTFS Alternate Data Streams:
  3249. # http://en.wikipedia.org/wiki/NTFS#Alternate_data_streams_.28ADS.29
  3250. assert ':' not in key
  3251. assert os.path.exists(path)
  3252. ads_fn = path + ':' + key
  3253. try:
  3254. with open(ads_fn, 'wb') as f:
  3255. f.write(value)
  3256. except EnvironmentError as e:
  3257. raise XAttrMetadataError(e.errno, e.strerror)
  3258. else:
  3259. user_has_setfattr = check_executable('setfattr', ['--version'])
  3260. user_has_xattr = check_executable('xattr', ['-h'])
  3261. if user_has_setfattr or user_has_xattr:
  3262. value = value.decode('utf-8')
  3263. if user_has_setfattr:
  3264. executable = 'setfattr'
  3265. opts = ['-n', key, '-v', value]
  3266. elif user_has_xattr:
  3267. executable = 'xattr'
  3268. opts = ['-w', key, value]
  3269. cmd = ([encodeFilename(executable, True)] +
  3270. [encodeArgument(o) for o in opts] +
  3271. [encodeFilename(path, True)])
  3272. try:
  3273. p = subprocess.Popen(
  3274. cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  3275. except EnvironmentError as e:
  3276. raise XAttrMetadataError(e.errno, e.strerror)
  3277. stdout, stderr = p.communicate()
  3278. stderr = stderr.decode('utf-8', 'replace')
  3279. if p.returncode != 0:
  3280. raise XAttrMetadataError(p.returncode, stderr)
  3281. else:
  3282. # On Unix, and can't find pyxattr, setfattr, or xattr.
  3283. if sys.platform.startswith('linux'):
  3284. raise XAttrUnavailableError(
  3285. "Couldn't find a tool to set the xattrs. "
  3286. "Install either the python 'pyxattr' or 'xattr' "
  3287. "modules, or the GNU 'attr' package "
  3288. "(which contains the 'setfattr' tool).")
  3289. else:
  3290. raise XAttrUnavailableError(
  3291. "Couldn't find a tool to set the xattrs. "
  3292. "Install either the python 'xattr' module, "
  3293. "or the 'xattr' binary.")
  3294. def random_birthday(year_field, month_field, day_field):
  3295. return {
  3296. year_field: str(random.randint(1950, 1995)),
  3297. month_field: str(random.randint(1, 12)),
  3298. day_field: str(random.randint(1, 31)),
  3299. }