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.

3882 lines
118 KiB

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