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.

3830 lines
116 KiB

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