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.

3834 lines
116 KiB

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