25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4007 lines
123KB

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