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.

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