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.

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