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.

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