You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3847 lines
117 KiB

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