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.

2710 lines
80 KiB

10 years ago
10 years ago
10 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 errno
  13. import functools
  14. import gzip
  15. import itertools
  16. import io
  17. import json
  18. import locale
  19. import math
  20. import operator
  21. import os
  22. import pipes
  23. import platform
  24. import re
  25. import ssl
  26. import socket
  27. import struct
  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_basestring,
  36. compat_chr,
  37. compat_etree_fromstring,
  38. compat_html_entities,
  39. compat_http_client,
  40. compat_kwargs,
  41. compat_parse_qs,
  42. compat_socket_create_connection,
  43. compat_str,
  44. compat_urllib_error,
  45. compat_urllib_parse,
  46. compat_urllib_parse_urlparse,
  47. compat_urllib_request,
  48. compat_urlparse,
  49. shlex_quote,
  50. )
  51. # This is not clearly defined otherwise
  52. compiled_regex_type = type(re.compile(''))
  53. std_headers = {
  54. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/44.0 (Chrome)',
  55. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  56. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  57. 'Accept-Encoding': 'gzip, deflate',
  58. 'Accept-Language': 'en-us,en;q=0.5',
  59. }
  60. NO_DEFAULT = object()
  61. ENGLISH_MONTH_NAMES = [
  62. 'January', 'February', 'March', 'April', 'May', 'June',
  63. 'July', 'August', 'September', 'October', 'November', 'December']
  64. KNOWN_EXTENSIONS = (
  65. 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'aac',
  66. 'flv', 'f4v', 'f4a', 'f4b',
  67. 'webm', 'ogg', 'ogv', 'oga', 'ogx', 'spx', 'opus',
  68. 'mkv', 'mka', 'mk3d',
  69. 'avi', 'divx',
  70. 'mov',
  71. 'asf', 'wmv', 'wma',
  72. '3gp', '3g2',
  73. 'mp3',
  74. 'flac',
  75. 'ape',
  76. 'wav',
  77. 'f4f', 'f4m', 'm3u8', 'smil')
  78. def preferredencoding():
  79. """Get preferred encoding.
  80. Returns the best encoding scheme for the system, based on
  81. locale.getpreferredencoding() and some further tweaks.
  82. """
  83. try:
  84. pref = locale.getpreferredencoding()
  85. 'TEST'.encode(pref)
  86. except Exception:
  87. pref = 'UTF-8'
  88. return pref
  89. def write_json_file(obj, fn):
  90. """ Encode obj as JSON and write it to fn, atomically if possible """
  91. fn = encodeFilename(fn)
  92. if sys.version_info < (3, 0) and sys.platform != 'win32':
  93. encoding = get_filesystem_encoding()
  94. # os.path.basename returns a bytes object, but NamedTemporaryFile
  95. # will fail if the filename contains non ascii characters unless we
  96. # use a unicode object
  97. path_basename = lambda f: os.path.basename(fn).decode(encoding)
  98. # the same for os.path.dirname
  99. path_dirname = lambda f: os.path.dirname(fn).decode(encoding)
  100. else:
  101. path_basename = os.path.basename
  102. path_dirname = os.path.dirname
  103. args = {
  104. 'suffix': '.tmp',
  105. 'prefix': path_basename(fn) + '.',
  106. 'dir': path_dirname(fn),
  107. 'delete': False,
  108. }
  109. # In Python 2.x, json.dump expects a bytestream.
  110. # In Python 3.x, it writes to a character stream
  111. if sys.version_info < (3, 0):
  112. args['mode'] = 'wb'
  113. else:
  114. args.update({
  115. 'mode': 'w',
  116. 'encoding': 'utf-8',
  117. })
  118. tf = tempfile.NamedTemporaryFile(**compat_kwargs(args))
  119. try:
  120. with tf:
  121. json.dump(obj, tf)
  122. if sys.platform == 'win32':
  123. # Need to remove existing file on Windows, else os.rename raises
  124. # WindowsError or FileExistsError.
  125. try:
  126. os.unlink(fn)
  127. except OSError:
  128. pass
  129. os.rename(tf.name, fn)
  130. except Exception:
  131. try:
  132. os.remove(tf.name)
  133. except OSError:
  134. pass
  135. raise
  136. if sys.version_info >= (2, 7):
  137. def find_xpath_attr(node, xpath, key, val=None):
  138. """ Find the xpath xpath[@key=val] """
  139. assert re.match(r'^[a-zA-Z_-]+$', key)
  140. expr = xpath + ('[@%s]' % key if val is None else "[@%s='%s']" % (key, val))
  141. return node.find(expr)
  142. else:
  143. def find_xpath_attr(node, xpath, key, val=None):
  144. # Here comes the crazy part: In 2.6, if the xpath is a unicode,
  145. # .//node does not match if a node is a direct child of . !
  146. if isinstance(xpath, compat_str):
  147. xpath = xpath.encode('ascii')
  148. for f in node.findall(xpath):
  149. if key not in f.attrib:
  150. continue
  151. if val is None or f.attrib.get(key) == val:
  152. return f
  153. return None
  154. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  155. # the namespace parameter
  156. def xpath_with_ns(path, ns_map):
  157. components = [c.split(':') for c in path.split('/')]
  158. replaced = []
  159. for c in components:
  160. if len(c) == 1:
  161. replaced.append(c[0])
  162. else:
  163. ns, tag = c
  164. replaced.append('{%s}%s' % (ns_map[ns], tag))
  165. return '/'.join(replaced)
  166. def xpath_element(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  167. def _find_xpath(xpath):
  168. if sys.version_info < (2, 7): # Crazy 2.6
  169. xpath = xpath.encode('ascii')
  170. return node.find(xpath)
  171. if isinstance(xpath, (str, compat_str)):
  172. n = _find_xpath(xpath)
  173. else:
  174. for xp in xpath:
  175. n = _find_xpath(xp)
  176. if n is not None:
  177. break
  178. if n is None:
  179. if default is not NO_DEFAULT:
  180. return default
  181. elif fatal:
  182. name = xpath if name is None else name
  183. raise ExtractorError('Could not find XML element %s' % name)
  184. else:
  185. return None
  186. return n
  187. def xpath_text(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  188. n = xpath_element(node, xpath, name, fatal=fatal, default=default)
  189. if n is None or n == default:
  190. return n
  191. if n.text is None:
  192. if default is not NO_DEFAULT:
  193. return default
  194. elif fatal:
  195. name = xpath if name is None else name
  196. raise ExtractorError('Could not find XML element\'s text %s' % name)
  197. else:
  198. return None
  199. return n.text
  200. def xpath_attr(node, xpath, key, name=None, fatal=False, default=NO_DEFAULT):
  201. n = find_xpath_attr(node, xpath, key)
  202. if n is None:
  203. if default is not NO_DEFAULT:
  204. return default
  205. elif fatal:
  206. name = '%s[@%s]' % (xpath, key) if name is None else name
  207. raise ExtractorError('Could not find XML attribute %s' % name)
  208. else:
  209. return None
  210. return n.attrib[key]
  211. def get_element_by_id(id, html):
  212. """Return the content of the tag with the specified ID in the passed HTML document"""
  213. return get_element_by_attribute('id', id, html)
  214. def get_element_by_attribute(attribute, value, html):
  215. """Return the content of the tag with the specified attribute in the passed HTML document"""
  216. m = re.search(r'''(?xs)
  217. <([a-zA-Z0-9:._-]+)
  218. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]+|="[^"]+"|='[^']+'))*?
  219. \s+%s=['"]?%s['"]?
  220. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]+|="[^"]+"|='[^']+'))*?
  221. \s*>
  222. (?P<content>.*?)
  223. </\1>
  224. ''' % (re.escape(attribute), re.escape(value)), html)
  225. if not m:
  226. return None
  227. res = m.group('content')
  228. if res.startswith('"') or res.startswith("'"):
  229. res = res[1:-1]
  230. return unescapeHTML(res)
  231. def clean_html(html):
  232. """Clean an HTML snippet into a readable string"""
  233. if html is None: # Convenience for sanitizing descriptions etc.
  234. return html
  235. # Newline vs <br />
  236. html = html.replace('\n', ' ')
  237. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  238. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  239. # Strip html tags
  240. html = re.sub('<.*?>', '', html)
  241. # Replace html entities
  242. html = unescapeHTML(html)
  243. return html.strip()
  244. def sanitize_open(filename, open_mode):
  245. """Try to open the given filename, and slightly tweak it if this fails.
  246. Attempts to open the given filename. If this fails, it tries to change
  247. the filename slightly, step by step, until it's either able to open it
  248. or it fails and raises a final exception, like the standard open()
  249. function.
  250. It returns the tuple (stream, definitive_file_name).
  251. """
  252. try:
  253. if filename == '-':
  254. if sys.platform == 'win32':
  255. import msvcrt
  256. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  257. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  258. stream = open(encodeFilename(filename), open_mode)
  259. return (stream, filename)
  260. except (IOError, OSError) as err:
  261. if err.errno in (errno.EACCES,):
  262. raise
  263. # In case of error, try to remove win32 forbidden chars
  264. alt_filename = sanitize_path(filename)
  265. if alt_filename == filename:
  266. raise
  267. else:
  268. # An exception here should be caught in the caller
  269. stream = open(encodeFilename(alt_filename), open_mode)
  270. return (stream, alt_filename)
  271. def timeconvert(timestr):
  272. """Convert RFC 2822 defined time string into system timestamp"""
  273. timestamp = None
  274. timetuple = email.utils.parsedate_tz(timestr)
  275. if timetuple is not None:
  276. timestamp = email.utils.mktime_tz(timetuple)
  277. return timestamp
  278. def sanitize_filename(s, restricted=False, is_id=False):
  279. """Sanitizes a string so it could be used as part of a filename.
  280. If restricted is set, use a stricter subset of allowed characters.
  281. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  282. """
  283. def replace_insane(char):
  284. if char == '?' or ord(char) < 32 or ord(char) == 127:
  285. return ''
  286. elif char == '"':
  287. return '' if restricted else '\''
  288. elif char == ':':
  289. return '_-' if restricted else ' -'
  290. elif char in '\\/|*<>':
  291. return '_'
  292. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  293. return '_'
  294. if restricted and ord(char) > 127:
  295. return '_'
  296. return char
  297. # Handle timestamps
  298. s = re.sub(r'[0-9]+(?::[0-9]+)+', lambda m: m.group(0).replace(':', '_'), s)
  299. result = ''.join(map(replace_insane, s))
  300. if not is_id:
  301. while '__' in result:
  302. result = result.replace('__', '_')
  303. result = result.strip('_')
  304. # Common case of "Foreign band name - English song title"
  305. if restricted and result.startswith('-_'):
  306. result = result[2:]
  307. if result.startswith('-'):
  308. result = '_' + result[len('-'):]
  309. result = result.lstrip('.')
  310. if not result:
  311. result = '_'
  312. return result
  313. def sanitize_path(s):
  314. """Sanitizes and normalizes path on Windows"""
  315. if sys.platform != 'win32':
  316. return s
  317. drive_or_unc, _ = os.path.splitdrive(s)
  318. if sys.version_info < (2, 7) and not drive_or_unc:
  319. drive_or_unc, _ = os.path.splitunc(s)
  320. norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
  321. if drive_or_unc:
  322. norm_path.pop(0)
  323. sanitized_path = [
  324. path_part if path_part in ['.', '..'] else re.sub('(?:[/<>:"\\|\\\\?\\*]|[\s.]$)', '#', path_part)
  325. for path_part in norm_path]
  326. if drive_or_unc:
  327. sanitized_path.insert(0, drive_or_unc + os.path.sep)
  328. return os.path.join(*sanitized_path)
  329. # Prepend protocol-less URLs with `http:` scheme in order to mitigate the number of
  330. # unwanted failures due to missing protocol
  331. def sanitized_Request(url, *args, **kwargs):
  332. return compat_urllib_request.Request(
  333. 'http:%s' % url if url.startswith('//') else url, *args, **kwargs)
  334. def orderedSet(iterable):
  335. """ Remove all duplicates from the input iterable """
  336. res = []
  337. for el in iterable:
  338. if el not in res:
  339. res.append(el)
  340. return res
  341. def _htmlentity_transform(entity):
  342. """Transforms an HTML entity to a character."""
  343. # Known non-numeric HTML entity
  344. if entity in compat_html_entities.name2codepoint:
  345. return compat_chr(compat_html_entities.name2codepoint[entity])
  346. mobj = re.match(r'#(x[0-9a-fA-F]+|[0-9]+)', entity)
  347. if mobj is not None:
  348. numstr = mobj.group(1)
  349. if numstr.startswith('x'):
  350. base = 16
  351. numstr = '0%s' % numstr
  352. else:
  353. base = 10
  354. # See https://github.com/rg3/youtube-dl/issues/7518
  355. try:
  356. return compat_chr(int(numstr, base))
  357. except ValueError:
  358. pass
  359. # Unknown entity in name, return its literal representation
  360. return '&%s;' % entity
  361. def unescapeHTML(s):
  362. if s is None:
  363. return None
  364. assert type(s) == compat_str
  365. return re.sub(
  366. r'&([^;]+);', lambda m: _htmlentity_transform(m.group(1)), s)
  367. def get_subprocess_encoding():
  368. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  369. # For subprocess calls, encode with locale encoding
  370. # Refer to http://stackoverflow.com/a/9951851/35070
  371. encoding = preferredencoding()
  372. else:
  373. encoding = sys.getfilesystemencoding()
  374. if encoding is None:
  375. encoding = 'utf-8'
  376. return encoding
  377. def encodeFilename(s, for_subprocess=False):
  378. """
  379. @param s The name of the file
  380. """
  381. assert type(s) == compat_str
  382. # Python 3 has a Unicode API
  383. if sys.version_info >= (3, 0):
  384. return s
  385. # Pass '' directly to use Unicode APIs on Windows 2000 and up
  386. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  387. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  388. if not for_subprocess and sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  389. return s
  390. # Jython assumes filenames are Unicode strings though reported as Python 2.x compatible
  391. if sys.platform.startswith('java'):
  392. return s
  393. return s.encode(get_subprocess_encoding(), 'ignore')
  394. def decodeFilename(b, for_subprocess=False):
  395. if sys.version_info >= (3, 0):
  396. return b
  397. if not isinstance(b, bytes):
  398. return b
  399. return b.decode(get_subprocess_encoding(), 'ignore')
  400. def encodeArgument(s):
  401. if not isinstance(s, compat_str):
  402. # Legacy code that uses byte strings
  403. # Uncomment the following line after fixing all post processors
  404. # assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
  405. s = s.decode('ascii')
  406. return encodeFilename(s, True)
  407. def decodeArgument(b):
  408. return decodeFilename(b, True)
  409. def decodeOption(optval):
  410. if optval is None:
  411. return optval
  412. if isinstance(optval, bytes):
  413. optval = optval.decode(preferredencoding())
  414. assert isinstance(optval, compat_str)
  415. return optval
  416. def formatSeconds(secs):
  417. if secs > 3600:
  418. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  419. elif secs > 60:
  420. return '%d:%02d' % (secs // 60, secs % 60)
  421. else:
  422. return '%d' % secs
  423. def make_HTTPS_handler(params, **kwargs):
  424. opts_no_check_certificate = params.get('nocheckcertificate', False)
  425. if hasattr(ssl, 'create_default_context'): # Python >= 3.4 or 2.7.9
  426. context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  427. if opts_no_check_certificate:
  428. context.check_hostname = False
  429. context.verify_mode = ssl.CERT_NONE
  430. try:
  431. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  432. except TypeError:
  433. # Python 2.7.8
  434. # (create_default_context present but HTTPSHandler has no context=)
  435. pass
  436. if sys.version_info < (3, 2):
  437. return YoutubeDLHTTPSHandler(params, **kwargs)
  438. else: # Python < 3.4
  439. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  440. context.verify_mode = (ssl.CERT_NONE
  441. if opts_no_check_certificate
  442. else ssl.CERT_REQUIRED)
  443. context.set_default_verify_paths()
  444. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  445. def bug_reports_message():
  446. if ytdl_is_updateable():
  447. update_cmd = 'type youtube-dl -U to update'
  448. else:
  449. update_cmd = 'see https://yt-dl.org/update on how to update'
  450. msg = '; please report this issue on https://yt-dl.org/bug .'
  451. msg += ' Make sure you are using the latest version; %s.' % update_cmd
  452. msg += ' Be sure to call youtube-dl with the --verbose flag and include its complete output.'
  453. return msg
  454. class ExtractorError(Exception):
  455. """Error during info extraction."""
  456. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  457. """ tb, if given, is the original traceback (so that it can be printed out).
  458. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  459. """
  460. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  461. expected = True
  462. if video_id is not None:
  463. msg = video_id + ': ' + msg
  464. if cause:
  465. msg += ' (caused by %r)' % cause
  466. if not expected:
  467. msg += bug_reports_message()
  468. super(ExtractorError, self).__init__(msg)
  469. self.traceback = tb
  470. self.exc_info = sys.exc_info() # preserve original exception
  471. self.cause = cause
  472. self.video_id = video_id
  473. def format_traceback(self):
  474. if self.traceback is None:
  475. return None
  476. return ''.join(traceback.format_tb(self.traceback))
  477. class UnsupportedError(ExtractorError):
  478. def __init__(self, url):
  479. super(UnsupportedError, self).__init__(
  480. 'Unsupported URL: %s' % url, expected=True)
  481. self.url = url
  482. class RegexNotFoundError(ExtractorError):
  483. """Error when a regex didn't match"""
  484. pass
  485. class DownloadError(Exception):
  486. """Download Error exception.
  487. This exception may be thrown by FileDownloader objects if they are not
  488. configured to continue on errors. They will contain the appropriate
  489. error message.
  490. """
  491. def __init__(self, msg, exc_info=None):
  492. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  493. super(DownloadError, self).__init__(msg)
  494. self.exc_info = exc_info
  495. class SameFileError(Exception):
  496. """Same File exception.
  497. This exception will be thrown by FileDownloader objects if they detect
  498. multiple files would have to be downloaded to the same file on disk.
  499. """
  500. pass
  501. class PostProcessingError(Exception):
  502. """Post Processing exception.
  503. This exception may be raised by PostProcessor's .run() method to
  504. indicate an error in the postprocessing task.
  505. """
  506. def __init__(self, msg):
  507. self.msg = msg
  508. class MaxDownloadsReached(Exception):
  509. """ --max-downloads limit has been reached. """
  510. pass
  511. class UnavailableVideoError(Exception):
  512. """Unavailable Format exception.
  513. This exception will be thrown when a video is requested
  514. in a format that is not available for that video.
  515. """
  516. pass
  517. class ContentTooShortError(Exception):
  518. """Content Too Short exception.
  519. This exception may be raised by FileDownloader objects when a file they
  520. download is too small for what the server announced first, indicating
  521. the connection was probably interrupted.
  522. """
  523. def __init__(self, downloaded, expected):
  524. # Both in bytes
  525. self.downloaded = downloaded
  526. self.expected = expected
  527. def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
  528. # Working around python 2 bug (see http://bugs.python.org/issue17849) by limiting
  529. # expected HTTP responses to meet HTTP/1.0 or later (see also
  530. # https://github.com/rg3/youtube-dl/issues/6727)
  531. if sys.version_info < (3, 0):
  532. kwargs[b'strict'] = True
  533. hc = http_class(*args, **kwargs)
  534. source_address = ydl_handler._params.get('source_address')
  535. if source_address is not None:
  536. sa = (source_address, 0)
  537. if hasattr(hc, 'source_address'): # Python 2.7+
  538. hc.source_address = sa
  539. else: # Python 2.6
  540. def _hc_connect(self, *args, **kwargs):
  541. sock = compat_socket_create_connection(
  542. (self.host, self.port), self.timeout, sa)
  543. if is_https:
  544. self.sock = ssl.wrap_socket(
  545. sock, self.key_file, self.cert_file,
  546. ssl_version=ssl.PROTOCOL_TLSv1)
  547. else:
  548. self.sock = sock
  549. hc.connect = functools.partial(_hc_connect, hc)
  550. return hc
  551. def handle_youtubedl_headers(headers):
  552. filtered_headers = headers
  553. if 'Youtubedl-no-compression' in filtered_headers:
  554. filtered_headers = dict((k, v) for k, v in filtered_headers.items() if k.lower() != 'accept-encoding')
  555. del filtered_headers['Youtubedl-no-compression']
  556. return filtered_headers
  557. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  558. """Handler for HTTP requests and responses.
  559. This class, when installed with an OpenerDirector, automatically adds
  560. the standard headers to every HTTP request and handles gzipped and
  561. deflated responses from web servers. If compression is to be avoided in
  562. a particular request, the original request in the program code only has
  563. to include the HTTP header "Youtubedl-no-compression", which will be
  564. removed before making the real request.
  565. Part of this code was copied from:
  566. http://techknack.net/python-urllib2-handlers/
  567. Andrew Rowls, the author of that code, agreed to release it to the
  568. public domain.
  569. """
  570. def __init__(self, params, *args, **kwargs):
  571. compat_urllib_request.HTTPHandler.__init__(self, *args, **kwargs)
  572. self._params = params
  573. def http_open(self, req):
  574. return self.do_open(functools.partial(
  575. _create_http_connection, self, compat_http_client.HTTPConnection, False),
  576. req)
  577. @staticmethod
  578. def deflate(data):
  579. try:
  580. return zlib.decompress(data, -zlib.MAX_WBITS)
  581. except zlib.error:
  582. return zlib.decompress(data)
  583. @staticmethod
  584. def addinfourl_wrapper(stream, headers, url, code):
  585. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  586. return compat_urllib_request.addinfourl(stream, headers, url, code)
  587. ret = compat_urllib_request.addinfourl(stream, headers, url)
  588. ret.code = code
  589. return ret
  590. def http_request(self, req):
  591. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  592. # always respected by websites, some tend to give out URLs with non percent-encoded
  593. # non-ASCII characters (see telemb.py, ard.py [#3412])
  594. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  595. # To work around aforementioned issue we will replace request's original URL with
  596. # percent-encoded one
  597. # Since redirects are also affected (e.g. http://www.southpark.de/alle-episoden/s18e09)
  598. # the code of this workaround has been moved here from YoutubeDL.urlopen()
  599. url = req.get_full_url()
  600. url_escaped = escape_url(url)
  601. # Substitute URL if any change after escaping
  602. if url != url_escaped:
  603. req_type = HEADRequest if req.get_method() == 'HEAD' else compat_urllib_request.Request
  604. new_req = req_type(
  605. url_escaped, data=req.data, headers=req.headers,
  606. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  607. new_req.timeout = req.timeout
  608. req = new_req
  609. for h, v in std_headers.items():
  610. # Capitalize is needed because of Python bug 2275: http://bugs.python.org/issue2275
  611. # The dict keys are capitalized because of this bug by urllib
  612. if h.capitalize() not in req.headers:
  613. req.add_header(h, v)
  614. req.headers = handle_youtubedl_headers(req.headers)
  615. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  616. # Python 2.6 is brain-dead when it comes to fragments
  617. req._Request__original = req._Request__original.partition('#')[0]
  618. req._Request__r_type = req._Request__r_type.partition('#')[0]
  619. return req
  620. def http_response(self, req, resp):
  621. old_resp = resp
  622. # gzip
  623. if resp.headers.get('Content-encoding', '') == 'gzip':
  624. content = resp.read()
  625. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  626. try:
  627. uncompressed = io.BytesIO(gz.read())
  628. except IOError as original_ioerror:
  629. # There may be junk add the end of the file
  630. # See http://stackoverflow.com/q/4928560/35070 for details
  631. for i in range(1, 1024):
  632. try:
  633. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  634. uncompressed = io.BytesIO(gz.read())
  635. except IOError:
  636. continue
  637. break
  638. else:
  639. raise original_ioerror
  640. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  641. resp.msg = old_resp.msg
  642. del resp.headers['Content-encoding']
  643. # deflate
  644. if resp.headers.get('Content-encoding', '') == 'deflate':
  645. gz = io.BytesIO(self.deflate(resp.read()))
  646. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  647. resp.msg = old_resp.msg
  648. del resp.headers['Content-encoding']
  649. # Percent-encode redirect URL of Location HTTP header to satisfy RFC 3986 (see
  650. # https://github.com/rg3/youtube-dl/issues/6457).
  651. if 300 <= resp.code < 400:
  652. location = resp.headers.get('Location')
  653. if location:
  654. # As of RFC 2616 default charset is iso-8859-1 that is respected by python 3
  655. if sys.version_info >= (3, 0):
  656. location = location.encode('iso-8859-1').decode('utf-8')
  657. location_escaped = escape_url(location)
  658. if location != location_escaped:
  659. del resp.headers['Location']
  660. resp.headers['Location'] = location_escaped
  661. return resp
  662. https_request = http_request
  663. https_response = http_response
  664. class YoutubeDLHTTPSHandler(compat_urllib_request.HTTPSHandler):
  665. def __init__(self, params, https_conn_class=None, *args, **kwargs):
  666. compat_urllib_request.HTTPSHandler.__init__(self, *args, **kwargs)
  667. self._https_conn_class = https_conn_class or compat_http_client.HTTPSConnection
  668. self._params = params
  669. def https_open(self, req):
  670. kwargs = {}
  671. if hasattr(self, '_context'): # python > 2.6
  672. kwargs['context'] = self._context
  673. if hasattr(self, '_check_hostname'): # python 3.x
  674. kwargs['check_hostname'] = self._check_hostname
  675. return self.do_open(functools.partial(
  676. _create_http_connection, self, self._https_conn_class, True),
  677. req, **kwargs)
  678. class YoutubeDLCookieProcessor(compat_urllib_request.HTTPCookieProcessor):
  679. def __init__(self, cookiejar=None):
  680. compat_urllib_request.HTTPCookieProcessor.__init__(self, cookiejar)
  681. def http_response(self, request, response):
  682. # Python 2 will choke on next HTTP request in row if there are non-ASCII
  683. # characters in Set-Cookie HTTP header of last response (see
  684. # https://github.com/rg3/youtube-dl/issues/6769).
  685. # In order to at least prevent crashing we will percent encode Set-Cookie
  686. # header before HTTPCookieProcessor starts processing it.
  687. # if sys.version_info < (3, 0) and response.headers:
  688. # for set_cookie_header in ('Set-Cookie', 'Set-Cookie2'):
  689. # set_cookie = response.headers.get(set_cookie_header)
  690. # if set_cookie:
  691. # set_cookie_escaped = compat_urllib_parse.quote(set_cookie, b"%/;:@&=+$,!~*'()?#[] ")
  692. # if set_cookie != set_cookie_escaped:
  693. # del response.headers[set_cookie_header]
  694. # response.headers[set_cookie_header] = set_cookie_escaped
  695. return compat_urllib_request.HTTPCookieProcessor.http_response(self, request, response)
  696. https_request = compat_urllib_request.HTTPCookieProcessor.http_request
  697. https_response = http_response
  698. def parse_iso8601(date_str, delimiter='T', timezone=None):
  699. """ Return a UNIX timestamp from the given date """
  700. if date_str is None:
  701. return None
  702. date_str = re.sub(r'\.[0-9]+', '', date_str)
  703. if timezone is None:
  704. m = re.search(
  705. r'(?:Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  706. date_str)
  707. if not m:
  708. timezone = datetime.timedelta()
  709. else:
  710. date_str = date_str[:-len(m.group(0))]
  711. if not m.group('sign'):
  712. timezone = datetime.timedelta()
  713. else:
  714. sign = 1 if m.group('sign') == '+' else -1
  715. timezone = datetime.timedelta(
  716. hours=sign * int(m.group('hours')),
  717. minutes=sign * int(m.group('minutes')))
  718. try:
  719. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  720. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  721. return calendar.timegm(dt.timetuple())
  722. except ValueError:
  723. pass
  724. def unified_strdate(date_str, day_first=True):
  725. """Return a string with the date in the format YYYYMMDD"""
  726. if date_str is None:
  727. return None
  728. upload_date = None
  729. # Replace commas
  730. date_str = date_str.replace(',', ' ')
  731. # %z (UTC offset) is only supported in python>=3.2
  732. if not re.match(r'^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$', date_str):
  733. date_str = re.sub(r' ?(\+|-)[0-9]{2}:?[0-9]{2}$', '', date_str)
  734. # Remove AM/PM + timezone
  735. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  736. format_expressions = [
  737. '%d %B %Y',
  738. '%d %b %Y',
  739. '%B %d %Y',
  740. '%b %d %Y',
  741. '%b %dst %Y %I:%M',
  742. '%b %dnd %Y %I:%M',
  743. '%b %dth %Y %I:%M',
  744. '%Y %m %d',
  745. '%Y-%m-%d',
  746. '%Y/%m/%d',
  747. '%Y/%m/%d %H:%M:%S',
  748. '%Y-%m-%d %H:%M:%S',
  749. '%Y-%m-%d %H:%M:%S.%f',
  750. '%d.%m.%Y %H:%M',
  751. '%d.%m.%Y %H.%M',
  752. '%Y-%m-%dT%H:%M:%SZ',
  753. '%Y-%m-%dT%H:%M:%S.%fZ',
  754. '%Y-%m-%dT%H:%M:%S.%f0Z',
  755. '%Y-%m-%dT%H:%M:%S',
  756. '%Y-%m-%dT%H:%M:%S.%f',
  757. '%Y-%m-%dT%H:%M',
  758. ]
  759. if day_first:
  760. format_expressions.extend([
  761. '%d-%m-%Y',
  762. '%d.%m.%Y',
  763. '%d/%m/%Y',
  764. '%d/%m/%y',
  765. '%d/%m/%Y %H:%M:%S',
  766. ])
  767. else:
  768. format_expressions.extend([
  769. '%m-%d-%Y',
  770. '%m.%d.%Y',
  771. '%m/%d/%Y',
  772. '%m/%d/%y',
  773. '%m/%d/%Y %H:%M:%S',
  774. ])
  775. for expression in format_expressions:
  776. try:
  777. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  778. except ValueError:
  779. pass
  780. if upload_date is None:
  781. timetuple = email.utils.parsedate_tz(date_str)
  782. if timetuple:
  783. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  784. if upload_date is not None:
  785. return compat_str(upload_date)
  786. def determine_ext(url, default_ext='unknown_video'):
  787. if url is None:
  788. return default_ext
  789. guess = url.partition('?')[0].rpartition('.')[2]
  790. if re.match(r'^[A-Za-z0-9]+$', guess):
  791. return guess
  792. # Try extract ext from URLs like http://example.com/foo/bar.mp4/?download
  793. elif guess.rstrip('/') in KNOWN_EXTENSIONS:
  794. return guess.rstrip('/')
  795. else:
  796. return default_ext
  797. def subtitles_filename(filename, sub_lang, sub_format):
  798. return filename.rsplit('.', 1)[0] + '.' + sub_lang + '.' + sub_format
  799. def date_from_str(date_str):
  800. """
  801. Return a datetime object from a string in the format YYYYMMDD or
  802. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  803. today = datetime.date.today()
  804. if date_str in ('now', 'today'):
  805. return today
  806. if date_str == 'yesterday':
  807. return today - datetime.timedelta(days=1)
  808. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  809. if match is not None:
  810. sign = match.group('sign')
  811. time = int(match.group('time'))
  812. if sign == '-':
  813. time = -time
  814. unit = match.group('unit')
  815. # A bad approximation?
  816. if unit == 'month':
  817. unit = 'day'
  818. time *= 30
  819. elif unit == 'year':
  820. unit = 'day'
  821. time *= 365
  822. unit += 's'
  823. delta = datetime.timedelta(**{unit: time})
  824. return today + delta
  825. return datetime.datetime.strptime(date_str, '%Y%m%d').date()
  826. def hyphenate_date(date_str):
  827. """
  828. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  829. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  830. if match is not None:
  831. return '-'.join(match.groups())
  832. else:
  833. return date_str
  834. class DateRange(object):
  835. """Represents a time interval between two dates"""
  836. def __init__(self, start=None, end=None):
  837. """start and end must be strings in the format accepted by date"""
  838. if start is not None:
  839. self.start = date_from_str(start)
  840. else:
  841. self.start = datetime.datetime.min.date()
  842. if end is not None:
  843. self.end = date_from_str(end)
  844. else:
  845. self.end = datetime.datetime.max.date()
  846. if self.start > self.end:
  847. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  848. @classmethod
  849. def day(cls, day):
  850. """Returns a range that only contains the given day"""
  851. return cls(day, day)
  852. def __contains__(self, date):
  853. """Check if the date is in the range"""
  854. if not isinstance(date, datetime.date):
  855. date = date_from_str(date)
  856. return self.start <= date <= self.end
  857. def __str__(self):
  858. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  859. def platform_name():
  860. """ Returns the platform name as a compat_str """
  861. res = platform.platform()
  862. if isinstance(res, bytes):
  863. res = res.decode(preferredencoding())
  864. assert isinstance(res, compat_str)
  865. return res
  866. def _windows_write_string(s, out):
  867. """ Returns True if the string was written using special methods,
  868. False if it has yet to be written out."""
  869. # Adapted from http://stackoverflow.com/a/3259271/35070
  870. import ctypes
  871. import ctypes.wintypes
  872. WIN_OUTPUT_IDS = {
  873. 1: -11,
  874. 2: -12,
  875. }
  876. try:
  877. fileno = out.fileno()
  878. except AttributeError:
  879. # If the output stream doesn't have a fileno, it's virtual
  880. return False
  881. except io.UnsupportedOperation:
  882. # Some strange Windows pseudo files?
  883. return False
  884. if fileno not in WIN_OUTPUT_IDS:
  885. return False
  886. GetStdHandle = ctypes.WINFUNCTYPE(
  887. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  888. (b'GetStdHandle', ctypes.windll.kernel32))
  889. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  890. WriteConsoleW = ctypes.WINFUNCTYPE(
  891. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  892. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  893. ctypes.wintypes.LPVOID)((b'WriteConsoleW', ctypes.windll.kernel32))
  894. written = ctypes.wintypes.DWORD(0)
  895. GetFileType = ctypes.WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)((b'GetFileType', ctypes.windll.kernel32))
  896. FILE_TYPE_CHAR = 0x0002
  897. FILE_TYPE_REMOTE = 0x8000
  898. GetConsoleMode = ctypes.WINFUNCTYPE(
  899. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  900. ctypes.POINTER(ctypes.wintypes.DWORD))(
  901. (b'GetConsoleMode', ctypes.windll.kernel32))
  902. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  903. def not_a_console(handle):
  904. if handle == INVALID_HANDLE_VALUE or handle is None:
  905. return True
  906. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR or
  907. GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  908. if not_a_console(h):
  909. return False
  910. def next_nonbmp_pos(s):
  911. try:
  912. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  913. except StopIteration:
  914. return len(s)
  915. while s:
  916. count = min(next_nonbmp_pos(s), 1024)
  917. ret = WriteConsoleW(
  918. h, s, count if count else 2, ctypes.byref(written), None)
  919. if ret == 0:
  920. raise OSError('Failed to write string')
  921. if not count: # We just wrote a non-BMP character
  922. assert written.value == 2
  923. s = s[1:]
  924. else:
  925. assert written.value > 0
  926. s = s[written.value:]
  927. return True
  928. def write_string(s, out=None, encoding=None):
  929. if out is None:
  930. out = sys.stderr
  931. assert type(s) == compat_str
  932. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  933. if _windows_write_string(s, out):
  934. return
  935. if ('b' in getattr(out, 'mode', '') or
  936. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  937. byt = s.encode(encoding or preferredencoding(), 'ignore')
  938. out.write(byt)
  939. elif hasattr(out, 'buffer'):
  940. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  941. byt = s.encode(enc, 'ignore')
  942. out.buffer.write(byt)
  943. else:
  944. out.write(s)
  945. out.flush()
  946. def bytes_to_intlist(bs):
  947. if not bs:
  948. return []
  949. if isinstance(bs[0], int): # Python 3
  950. return list(bs)
  951. else:
  952. return [ord(c) for c in bs]
  953. def intlist_to_bytes(xs):
  954. if not xs:
  955. return b''
  956. return struct_pack('%dB' % len(xs), *xs)
  957. # Cross-platform file locking
  958. if sys.platform == 'win32':
  959. import ctypes.wintypes
  960. import msvcrt
  961. class OVERLAPPED(ctypes.Structure):
  962. _fields_ = [
  963. ('Internal', ctypes.wintypes.LPVOID),
  964. ('InternalHigh', ctypes.wintypes.LPVOID),
  965. ('Offset', ctypes.wintypes.DWORD),
  966. ('OffsetHigh', ctypes.wintypes.DWORD),
  967. ('hEvent', ctypes.wintypes.HANDLE),
  968. ]
  969. kernel32 = ctypes.windll.kernel32
  970. LockFileEx = kernel32.LockFileEx
  971. LockFileEx.argtypes = [
  972. ctypes.wintypes.HANDLE, # hFile
  973. ctypes.wintypes.DWORD, # dwFlags
  974. ctypes.wintypes.DWORD, # dwReserved
  975. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  976. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  977. ctypes.POINTER(OVERLAPPED) # Overlapped
  978. ]
  979. LockFileEx.restype = ctypes.wintypes.BOOL
  980. UnlockFileEx = kernel32.UnlockFileEx
  981. UnlockFileEx.argtypes = [
  982. ctypes.wintypes.HANDLE, # hFile
  983. ctypes.wintypes.DWORD, # dwReserved
  984. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  985. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  986. ctypes.POINTER(OVERLAPPED) # Overlapped
  987. ]
  988. UnlockFileEx.restype = ctypes.wintypes.BOOL
  989. whole_low = 0xffffffff
  990. whole_high = 0x7fffffff
  991. def _lock_file(f, exclusive):
  992. overlapped = OVERLAPPED()
  993. overlapped.Offset = 0
  994. overlapped.OffsetHigh = 0
  995. overlapped.hEvent = 0
  996. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  997. handle = msvcrt.get_osfhandle(f.fileno())
  998. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  999. whole_low, whole_high, f._lock_file_overlapped_p):
  1000. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  1001. def _unlock_file(f):
  1002. assert f._lock_file_overlapped_p
  1003. handle = msvcrt.get_osfhandle(f.fileno())
  1004. if not UnlockFileEx(handle, 0,
  1005. whole_low, whole_high, f._lock_file_overlapped_p):
  1006. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  1007. else:
  1008. # Some platforms, such as Jython, is missing fcntl
  1009. try:
  1010. import fcntl
  1011. def _lock_file(f, exclusive):
  1012. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  1013. def _unlock_file(f):
  1014. fcntl.flock(f, fcntl.LOCK_UN)
  1015. except ImportError:
  1016. UNSUPPORTED_MSG = 'file locking is not supported on this platform'
  1017. def _lock_file(f, exclusive):
  1018. raise IOError(UNSUPPORTED_MSG)
  1019. def _unlock_file(f):
  1020. raise IOError(UNSUPPORTED_MSG)
  1021. class locked_file(object):
  1022. def __init__(self, filename, mode, encoding=None):
  1023. assert mode in ['r', 'a', 'w']
  1024. self.f = io.open(filename, mode, encoding=encoding)
  1025. self.mode = mode
  1026. def __enter__(self):
  1027. exclusive = self.mode != 'r'
  1028. try:
  1029. _lock_file(self.f, exclusive)
  1030. except IOError:
  1031. self.f.close()
  1032. raise
  1033. return self
  1034. def __exit__(self, etype, value, traceback):
  1035. try:
  1036. _unlock_file(self.f)
  1037. finally:
  1038. self.f.close()
  1039. def __iter__(self):
  1040. return iter(self.f)
  1041. def write(self, *args):
  1042. return self.f.write(*args)
  1043. def read(self, *args):
  1044. return self.f.read(*args)
  1045. def get_filesystem_encoding():
  1046. encoding = sys.getfilesystemencoding()
  1047. return encoding if encoding is not None else 'utf-8'
  1048. def shell_quote(args):
  1049. quoted_args = []
  1050. encoding = get_filesystem_encoding()
  1051. for a in args:
  1052. if isinstance(a, bytes):
  1053. # We may get a filename encoded with 'encodeFilename'
  1054. a = a.decode(encoding)
  1055. quoted_args.append(pipes.quote(a))
  1056. return ' '.join(quoted_args)
  1057. def smuggle_url(url, data):
  1058. """ Pass additional data in a URL for internal use. """
  1059. sdata = compat_urllib_parse.urlencode(
  1060. {'__youtubedl_smuggle': json.dumps(data)})
  1061. return url + '#' + sdata
  1062. def unsmuggle_url(smug_url, default=None):
  1063. if '#__youtubedl_smuggle' not in smug_url:
  1064. return smug_url, default
  1065. url, _, sdata = smug_url.rpartition('#')
  1066. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  1067. data = json.loads(jsond)
  1068. return url, data
  1069. def format_bytes(bytes):
  1070. if bytes is None:
  1071. return 'N/A'
  1072. if type(bytes) is str:
  1073. bytes = float(bytes)
  1074. if bytes == 0.0:
  1075. exponent = 0
  1076. else:
  1077. exponent = int(math.log(bytes, 1024.0))
  1078. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  1079. converted = float(bytes) / float(1024 ** exponent)
  1080. return '%.2f%s' % (converted, suffix)
  1081. def lookup_unit_table(unit_table, s):
  1082. units_re = '|'.join(re.escape(u) for u in unit_table)
  1083. m = re.match(
  1084. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)' % units_re, s)
  1085. if not m:
  1086. return None
  1087. num_str = m.group('num').replace(',', '.')
  1088. mult = unit_table[m.group('unit')]
  1089. return int(float(num_str) * mult)
  1090. def parse_filesize(s):
  1091. if s is None:
  1092. return None
  1093. # The lower-case forms are of course incorrect and unofficial,
  1094. # but we support those too
  1095. _UNIT_TABLE = {
  1096. 'B': 1,
  1097. 'b': 1,
  1098. 'KiB': 1024,
  1099. 'KB': 1000,
  1100. 'kB': 1024,
  1101. 'Kb': 1000,
  1102. 'MiB': 1024 ** 2,
  1103. 'MB': 1000 ** 2,
  1104. 'mB': 1024 ** 2,
  1105. 'Mb': 1000 ** 2,
  1106. 'GiB': 1024 ** 3,
  1107. 'GB': 1000 ** 3,
  1108. 'gB': 1024 ** 3,
  1109. 'Gb': 1000 ** 3,
  1110. 'TiB': 1024 ** 4,
  1111. 'TB': 1000 ** 4,
  1112. 'tB': 1024 ** 4,
  1113. 'Tb': 1000 ** 4,
  1114. 'PiB': 1024 ** 5,
  1115. 'PB': 1000 ** 5,
  1116. 'pB': 1024 ** 5,
  1117. 'Pb': 1000 ** 5,
  1118. 'EiB': 1024 ** 6,
  1119. 'EB': 1000 ** 6,
  1120. 'eB': 1024 ** 6,
  1121. 'Eb': 1000 ** 6,
  1122. 'ZiB': 1024 ** 7,
  1123. 'ZB': 1000 ** 7,
  1124. 'zB': 1024 ** 7,
  1125. 'Zb': 1000 ** 7,
  1126. 'YiB': 1024 ** 8,
  1127. 'YB': 1000 ** 8,
  1128. 'yB': 1024 ** 8,
  1129. 'Yb': 1000 ** 8,
  1130. }
  1131. return lookup_unit_table(_UNIT_TABLE, s)
  1132. def parse_count(s):
  1133. if s is None:
  1134. return None
  1135. s = s.strip()
  1136. if re.match(r'^[\d,.]+$', s):
  1137. return str_to_int(s)
  1138. _UNIT_TABLE = {
  1139. 'k': 1000,
  1140. 'K': 1000,
  1141. 'm': 1000 ** 2,
  1142. 'M': 1000 ** 2,
  1143. 'kk': 1000 ** 2,
  1144. 'KK': 1000 ** 2,
  1145. }
  1146. return lookup_unit_table(_UNIT_TABLE, s)
  1147. def month_by_name(name):
  1148. """ Return the number of a month by (locale-independently) English name """
  1149. try:
  1150. return ENGLISH_MONTH_NAMES.index(name) + 1
  1151. except ValueError:
  1152. return None
  1153. def month_by_abbreviation(abbrev):
  1154. """ Return the number of a month by (locale-independently) English
  1155. abbreviations """
  1156. try:
  1157. return [s[:3] for s in ENGLISH_MONTH_NAMES].index(abbrev) + 1
  1158. except ValueError:
  1159. return None
  1160. def fix_xml_ampersands(xml_str):
  1161. """Replace all the '&' by '&amp;' in XML"""
  1162. return re.sub(
  1163. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  1164. '&amp;',
  1165. xml_str)
  1166. def setproctitle(title):
  1167. assert isinstance(title, compat_str)
  1168. # ctypes in Jython is not complete
  1169. # http://bugs.jython.org/issue2148
  1170. if sys.platform.startswith('java'):
  1171. return
  1172. try:
  1173. libc = ctypes.cdll.LoadLibrary('libc.so.6')
  1174. except OSError:
  1175. return
  1176. title_bytes = title.encode('utf-8')
  1177. buf = ctypes.create_string_buffer(len(title_bytes))
  1178. buf.value = title_bytes
  1179. try:
  1180. libc.prctl(15, buf, 0, 0, 0)
  1181. except AttributeError:
  1182. return # Strange libc, just skip this
  1183. def remove_start(s, start):
  1184. if s.startswith(start):
  1185. return s[len(start):]
  1186. return s
  1187. def remove_end(s, end):
  1188. if s.endswith(end):
  1189. return s[:-len(end)]
  1190. return s
  1191. def remove_quotes(s):
  1192. if s is None or len(s) < 2:
  1193. return s
  1194. for quote in ('"', "'", ):
  1195. if s[0] == quote and s[-1] == quote:
  1196. return s[1:-1]
  1197. return s
  1198. def url_basename(url):
  1199. path = compat_urlparse.urlparse(url).path
  1200. return path.strip('/').split('/')[-1]
  1201. class HEADRequest(compat_urllib_request.Request):
  1202. def get_method(self):
  1203. return 'HEAD'
  1204. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  1205. if get_attr:
  1206. if v is not None:
  1207. v = getattr(v, get_attr, None)
  1208. if v == '':
  1209. v = None
  1210. if v is None:
  1211. return default
  1212. try:
  1213. return int(v) * invscale // scale
  1214. except ValueError:
  1215. return default
  1216. def str_or_none(v, default=None):
  1217. return default if v is None else compat_str(v)
  1218. def str_to_int(int_str):
  1219. """ A more relaxed version of int_or_none """
  1220. if int_str is None:
  1221. return None
  1222. int_str = re.sub(r'[,\.\+]', '', int_str)
  1223. return int(int_str)
  1224. def float_or_none(v, scale=1, invscale=1, default=None):
  1225. if v is None:
  1226. return default
  1227. try:
  1228. return float(v) * invscale / scale
  1229. except ValueError:
  1230. return default
  1231. def parse_duration(s):
  1232. if not isinstance(s, compat_basestring):
  1233. return None
  1234. s = s.strip()
  1235. m = re.match(
  1236. r'''(?ix)(?:P?T)?
  1237. (?:
  1238. (?P<only_mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*|
  1239. (?P<only_hours>[0-9.]+)\s*(?:hours?)|
  1240. \s*(?P<hours_reversed>[0-9]+)\s*(?:[:h]|hours?)\s*(?P<mins_reversed>[0-9]+)\s*(?:[:m]|mins?\.?|minutes?)\s*|
  1241. (?:
  1242. (?:
  1243. (?:(?P<days>[0-9]+)\s*(?:[:d]|days?)\s*)?
  1244. (?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*
  1245. )?
  1246. (?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s*
  1247. )?
  1248. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*(?:s|secs?|seconds?)?
  1249. )$''', s)
  1250. if not m:
  1251. return None
  1252. res = 0
  1253. if m.group('only_mins'):
  1254. return float_or_none(m.group('only_mins'), invscale=60)
  1255. if m.group('only_hours'):
  1256. return float_or_none(m.group('only_hours'), invscale=60 * 60)
  1257. if m.group('secs'):
  1258. res += int(m.group('secs'))
  1259. if m.group('mins_reversed'):
  1260. res += int(m.group('mins_reversed')) * 60
  1261. if m.group('mins'):
  1262. res += int(m.group('mins')) * 60
  1263. if m.group('hours'):
  1264. res += int(m.group('hours')) * 60 * 60
  1265. if m.group('hours_reversed'):
  1266. res += int(m.group('hours_reversed')) * 60 * 60
  1267. if m.group('days'):
  1268. res += int(m.group('days')) * 24 * 60 * 60
  1269. if m.group('ms'):
  1270. res += float(m.group('ms'))
  1271. return res
  1272. def prepend_extension(filename, ext, expected_real_ext=None):
  1273. name, real_ext = os.path.splitext(filename)
  1274. return (
  1275. '{0}.{1}{2}'.format(name, ext, real_ext)
  1276. if not expected_real_ext or real_ext[1:] == expected_real_ext
  1277. else '{0}.{1}'.format(filename, ext))
  1278. def replace_extension(filename, ext, expected_real_ext=None):
  1279. name, real_ext = os.path.splitext(filename)
  1280. return '{0}.{1}'.format(
  1281. name if not expected_real_ext or real_ext[1:] == expected_real_ext else filename,
  1282. ext)
  1283. def check_executable(exe, args=[]):
  1284. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  1285. args can be a list of arguments for a short output (like -version) """
  1286. try:
  1287. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  1288. except OSError:
  1289. return False
  1290. return exe
  1291. def get_exe_version(exe, args=['--version'],
  1292. version_re=None, unrecognized='present'):
  1293. """ Returns the version of the specified executable,
  1294. or False if the executable is not present """
  1295. try:
  1296. out, _ = subprocess.Popen(
  1297. [encodeArgument(exe)] + args,
  1298. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  1299. except OSError:
  1300. return False
  1301. if isinstance(out, bytes): # Python 2.x
  1302. out = out.decode('ascii', 'ignore')
  1303. return detect_exe_version(out, version_re, unrecognized)
  1304. def detect_exe_version(output, version_re=None, unrecognized='present'):
  1305. assert isinstance(output, compat_str)
  1306. if version_re is None:
  1307. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  1308. m = re.search(version_re, output)
  1309. if m:
  1310. return m.group(1)
  1311. else:
  1312. return unrecognized
  1313. class PagedList(object):
  1314. def __len__(self):
  1315. # This is only useful for tests
  1316. return len(self.getslice())
  1317. class OnDemandPagedList(PagedList):
  1318. def __init__(self, pagefunc, pagesize, use_cache=False):
  1319. self._pagefunc = pagefunc
  1320. self._pagesize = pagesize
  1321. self._use_cache = use_cache
  1322. if use_cache:
  1323. self._cache = {}
  1324. def getslice(self, start=0, end=None):
  1325. res = []
  1326. for pagenum in itertools.count(start // self._pagesize):
  1327. firstid = pagenum * self._pagesize
  1328. nextfirstid = pagenum * self._pagesize + self._pagesize
  1329. if start >= nextfirstid:
  1330. continue
  1331. page_results = None
  1332. if self._use_cache:
  1333. page_results = self._cache.get(pagenum)
  1334. if page_results is None:
  1335. page_results = list(self._pagefunc(pagenum))
  1336. if self._use_cache:
  1337. self._cache[pagenum] = page_results
  1338. startv = (
  1339. start % self._pagesize
  1340. if firstid <= start < nextfirstid
  1341. else 0)
  1342. endv = (
  1343. ((end - 1) % self._pagesize) + 1
  1344. if (end is not None and firstid <= end <= nextfirstid)
  1345. else None)
  1346. if startv != 0 or endv is not None:
  1347. page_results = page_results[startv:endv]
  1348. res.extend(page_results)
  1349. # A little optimization - if current page is not "full", ie. does
  1350. # not contain page_size videos then we can assume that this page
  1351. # is the last one - there are no more ids on further pages -
  1352. # i.e. no need to query again.
  1353. if len(page_results) + startv < self._pagesize:
  1354. break
  1355. # If we got the whole page, but the next page is not interesting,
  1356. # break out early as well
  1357. if end == nextfirstid:
  1358. break
  1359. return res
  1360. class InAdvancePagedList(PagedList):
  1361. def __init__(self, pagefunc, pagecount, pagesize):
  1362. self._pagefunc = pagefunc
  1363. self._pagecount = pagecount
  1364. self._pagesize = pagesize
  1365. def getslice(self, start=0, end=None):
  1366. res = []
  1367. start_page = start // self._pagesize
  1368. end_page = (
  1369. self._pagecount if end is None else (end // self._pagesize + 1))
  1370. skip_elems = start - start_page * self._pagesize
  1371. only_more = None if end is None else end - start
  1372. for pagenum in range(start_page, end_page):
  1373. page = list(self._pagefunc(pagenum))
  1374. if skip_elems:
  1375. page = page[skip_elems:]
  1376. skip_elems = None
  1377. if only_more is not None:
  1378. if len(page) < only_more:
  1379. only_more -= len(page)
  1380. else:
  1381. page = page[:only_more]
  1382. res.extend(page)
  1383. break
  1384. res.extend(page)
  1385. return res
  1386. def uppercase_escape(s):
  1387. unicode_escape = codecs.getdecoder('unicode_escape')
  1388. return re.sub(
  1389. r'\\U[0-9a-fA-F]{8}',
  1390. lambda m: unicode_escape(m.group(0))[0],
  1391. s)
  1392. def lowercase_escape(s):
  1393. unicode_escape = codecs.getdecoder('unicode_escape')
  1394. return re.sub(
  1395. r'\\u[0-9a-fA-F]{4}',
  1396. lambda m: unicode_escape(m.group(0))[0],
  1397. s)
  1398. def escape_rfc3986(s):
  1399. """Escape non-ASCII characters as suggested by RFC 3986"""
  1400. if sys.version_info < (3, 0) and isinstance(s, compat_str):
  1401. s = s.encode('utf-8')
  1402. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1403. def escape_url(url):
  1404. """Escape URL as suggested by RFC 3986"""
  1405. url_parsed = compat_urllib_parse_urlparse(url)
  1406. return url_parsed._replace(
  1407. path=escape_rfc3986(url_parsed.path),
  1408. params=escape_rfc3986(url_parsed.params),
  1409. query=escape_rfc3986(url_parsed.query),
  1410. fragment=escape_rfc3986(url_parsed.fragment)
  1411. ).geturl()
  1412. try:
  1413. struct.pack('!I', 0)
  1414. except TypeError:
  1415. # In Python 2.6 (and some 2.7 versions), struct requires a bytes argument
  1416. def struct_pack(spec, *args):
  1417. if isinstance(spec, compat_str):
  1418. spec = spec.encode('ascii')
  1419. return struct.pack(spec, *args)
  1420. def struct_unpack(spec, *args):
  1421. if isinstance(spec, compat_str):
  1422. spec = spec.encode('ascii')
  1423. return struct.unpack(spec, *args)
  1424. else:
  1425. struct_pack = struct.pack
  1426. struct_unpack = struct.unpack
  1427. def read_batch_urls(batch_fd):
  1428. def fixup(url):
  1429. if not isinstance(url, compat_str):
  1430. url = url.decode('utf-8', 'replace')
  1431. BOM_UTF8 = '\xef\xbb\xbf'
  1432. if url.startswith(BOM_UTF8):
  1433. url = url[len(BOM_UTF8):]
  1434. url = url.strip()
  1435. if url.startswith(('#', ';', ']')):
  1436. return False
  1437. return url
  1438. with contextlib.closing(batch_fd) as fd:
  1439. return [url for url in map(fixup, fd) if url]
  1440. def urlencode_postdata(*args, **kargs):
  1441. return compat_urllib_parse.urlencode(*args, **kargs).encode('ascii')
  1442. def update_url_query(url, query):
  1443. parsed_url = compat_urlparse.urlparse(url)
  1444. qs = compat_parse_qs(parsed_url.query)
  1445. qs.update(query)
  1446. qs = encode_dict(qs)
  1447. return compat_urlparse.urlunparse(parsed_url._replace(
  1448. query=compat_urllib_parse.urlencode(qs, True)))
  1449. def encode_dict(d, encoding='utf-8'):
  1450. def encode(v):
  1451. return v.encode(encoding) if isinstance(v, compat_basestring) else v
  1452. return dict((encode(k), encode(v)) for k, v in d.items())
  1453. def dict_get(d, key_or_keys, default=None, skip_false_values=True):
  1454. if isinstance(key_or_keys, (list, tuple)):
  1455. for key in key_or_keys:
  1456. if key not in d or d[key] is None or skip_false_values and not d[key]:
  1457. continue
  1458. return d[key]
  1459. return default
  1460. return d.get(key_or_keys, default)
  1461. def encode_compat_str(string, encoding=preferredencoding(), errors='strict'):
  1462. return string if isinstance(string, compat_str) else compat_str(string, encoding, errors)
  1463. US_RATINGS = {
  1464. 'G': 0,
  1465. 'PG': 10,
  1466. 'PG-13': 13,
  1467. 'R': 16,
  1468. 'NC': 18,
  1469. }
  1470. def parse_age_limit(s):
  1471. if s is None:
  1472. return None
  1473. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1474. return int(m.group('age')) if m else US_RATINGS.get(s)
  1475. def strip_jsonp(code):
  1476. return re.sub(
  1477. r'(?s)^[a-zA-Z0-9_.]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code)
  1478. def js_to_json(code):
  1479. def fix_kv(m):
  1480. v = m.group(0)
  1481. if v in ('true', 'false', 'null'):
  1482. return v
  1483. if v.startswith('"'):
  1484. v = re.sub(r"\\'", "'", v[1:-1])
  1485. elif v.startswith("'"):
  1486. v = v[1:-1]
  1487. v = re.sub(r"\\\\|\\'|\"", lambda m: {
  1488. '\\\\': '\\\\',
  1489. "\\'": "'",
  1490. '"': '\\"',
  1491. }[m.group(0)], v)
  1492. return '"%s"' % v
  1493. res = re.sub(r'''(?x)
  1494. "(?:[^"\\]*(?:\\\\|\\['"nu]))*[^"\\]*"|
  1495. '(?:[^'\\]*(?:\\\\|\\['"nu]))*[^'\\]*'|
  1496. [a-zA-Z_][.a-zA-Z_0-9]*
  1497. ''', fix_kv, code)
  1498. res = re.sub(r',(\s*[\]}])', lambda m: m.group(1), res)
  1499. return res
  1500. def qualities(quality_ids):
  1501. """ Get a numeric quality value out of a list of possible values """
  1502. def q(qid):
  1503. try:
  1504. return quality_ids.index(qid)
  1505. except ValueError:
  1506. return -1
  1507. return q
  1508. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1509. def limit_length(s, length):
  1510. """ Add ellipses to overly long strings """
  1511. if s is None:
  1512. return None
  1513. ELLIPSES = '...'
  1514. if len(s) > length:
  1515. return s[:length - len(ELLIPSES)] + ELLIPSES
  1516. return s
  1517. def version_tuple(v):
  1518. return tuple(int(e) for e in re.split(r'[-.]', v))
  1519. def is_outdated_version(version, limit, assume_new=True):
  1520. if not version:
  1521. return not assume_new
  1522. try:
  1523. return version_tuple(version) < version_tuple(limit)
  1524. except ValueError:
  1525. return not assume_new
  1526. def ytdl_is_updateable():
  1527. """ Returns if youtube-dl can be updated with -U """
  1528. from zipimport import zipimporter
  1529. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  1530. def args_to_str(args):
  1531. # Get a short string representation for a subprocess command
  1532. return ' '.join(shlex_quote(a) for a in args)
  1533. def error_to_compat_str(err):
  1534. err_str = str(err)
  1535. # On python 2 error byte string must be decoded with proper
  1536. # encoding rather than ascii
  1537. if sys.version_info[0] < 3:
  1538. err_str = err_str.decode(preferredencoding())
  1539. return err_str
  1540. def mimetype2ext(mt):
  1541. ext = {
  1542. 'audio/mp4': 'm4a',
  1543. }.get(mt)
  1544. if ext is not None:
  1545. return ext
  1546. _, _, res = mt.rpartition('/')
  1547. return {
  1548. '3gpp': '3gp',
  1549. 'smptett+xml': 'tt',
  1550. 'srt': 'srt',
  1551. 'ttaf+xml': 'dfxp',
  1552. 'ttml+xml': 'ttml',
  1553. 'vtt': 'vtt',
  1554. 'x-flv': 'flv',
  1555. 'x-mp4-fragmented': 'mp4',
  1556. 'x-ms-wmv': 'wmv',
  1557. }.get(res, res)
  1558. def urlhandle_detect_ext(url_handle):
  1559. try:
  1560. url_handle.headers
  1561. getheader = lambda h: url_handle.headers[h]
  1562. except AttributeError: # Python < 3
  1563. getheader = url_handle.info().getheader
  1564. cd = getheader('Content-Disposition')
  1565. if cd:
  1566. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  1567. if m:
  1568. e = determine_ext(m.group('filename'), default_ext=None)
  1569. if e:
  1570. return e
  1571. return mimetype2ext(getheader('Content-Type'))
  1572. def encode_data_uri(data, mime_type):
  1573. return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
  1574. def age_restricted(content_limit, age_limit):
  1575. """ Returns True iff the content should be blocked """
  1576. if age_limit is None: # No limit set
  1577. return False
  1578. if content_limit is None:
  1579. return False # Content available for everyone
  1580. return age_limit < content_limit
  1581. def is_html(first_bytes):
  1582. """ Detect whether a file contains HTML by examining its first bytes. """
  1583. BOMS = [
  1584. (b'\xef\xbb\xbf', 'utf-8'),
  1585. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  1586. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  1587. (b'\xff\xfe', 'utf-16-le'),
  1588. (b'\xfe\xff', 'utf-16-be'),
  1589. ]
  1590. for bom, enc in BOMS:
  1591. if first_bytes.startswith(bom):
  1592. s = first_bytes[len(bom):].decode(enc, 'replace')
  1593. break
  1594. else:
  1595. s = first_bytes.decode('utf-8', 'replace')
  1596. return re.match(r'^\s*<', s)
  1597. def determine_protocol(info_dict):
  1598. protocol = info_dict.get('protocol')
  1599. if protocol is not None:
  1600. return protocol
  1601. url = info_dict['url']
  1602. if url.startswith('rtmp'):
  1603. return 'rtmp'
  1604. elif url.startswith('mms'):
  1605. return 'mms'
  1606. elif url.startswith('rtsp'):
  1607. return 'rtsp'
  1608. ext = determine_ext(url)
  1609. if ext == 'm3u8':
  1610. return 'm3u8'
  1611. elif ext == 'f4m':
  1612. return 'f4m'
  1613. return compat_urllib_parse_urlparse(url).scheme
  1614. def render_table(header_row, data):
  1615. """ Render a list of rows, each as a list of values """
  1616. table = [header_row] + data
  1617. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  1618. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  1619. return '\n'.join(format_str % tuple(row) for row in table)
  1620. def _match_one(filter_part, dct):
  1621. COMPARISON_OPERATORS = {
  1622. '<': operator.lt,
  1623. '<=': operator.le,
  1624. '>': operator.gt,
  1625. '>=': operator.ge,
  1626. '=': operator.eq,
  1627. '!=': operator.ne,
  1628. }
  1629. operator_rex = re.compile(r'''(?x)\s*
  1630. (?P<key>[a-z_]+)
  1631. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  1632. (?:
  1633. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  1634. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  1635. )
  1636. \s*$
  1637. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  1638. m = operator_rex.search(filter_part)
  1639. if m:
  1640. op = COMPARISON_OPERATORS[m.group('op')]
  1641. if m.group('strval') is not None:
  1642. if m.group('op') not in ('=', '!='):
  1643. raise ValueError(
  1644. 'Operator %s does not support string values!' % m.group('op'))
  1645. comparison_value = m.group('strval')
  1646. else:
  1647. try:
  1648. comparison_value = int(m.group('intval'))
  1649. except ValueError:
  1650. comparison_value = parse_filesize(m.group('intval'))
  1651. if comparison_value is None:
  1652. comparison_value = parse_filesize(m.group('intval') + 'B')
  1653. if comparison_value is None:
  1654. raise ValueError(
  1655. 'Invalid integer value %r in filter part %r' % (
  1656. m.group('intval'), filter_part))
  1657. actual_value = dct.get(m.group('key'))
  1658. if actual_value is None:
  1659. return m.group('none_inclusive')
  1660. return op(actual_value, comparison_value)
  1661. UNARY_OPERATORS = {
  1662. '': lambda v: v is not None,
  1663. '!': lambda v: v is None,
  1664. }
  1665. operator_rex = re.compile(r'''(?x)\s*
  1666. (?P<op>%s)\s*(?P<key>[a-z_]+)
  1667. \s*$
  1668. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  1669. m = operator_rex.search(filter_part)
  1670. if m:
  1671. op = UNARY_OPERATORS[m.group('op')]
  1672. actual_value = dct.get(m.group('key'))
  1673. return op(actual_value)
  1674. raise ValueError('Invalid filter part %r' % filter_part)
  1675. def match_str(filter_str, dct):
  1676. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  1677. return all(
  1678. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  1679. def match_filter_func(filter_str):
  1680. def _match_func(info_dict):
  1681. if match_str(filter_str, info_dict):
  1682. return None
  1683. else:
  1684. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  1685. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  1686. return _match_func
  1687. def parse_dfxp_time_expr(time_expr):
  1688. if not time_expr:
  1689. return
  1690. mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
  1691. if mobj:
  1692. return float(mobj.group('time_offset'))
  1693. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
  1694. if mobj:
  1695. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
  1696. def srt_subtitles_timecode(seconds):
  1697. return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
  1698. def dfxp2srt(dfxp_data):
  1699. _x = functools.partial(xpath_with_ns, ns_map={
  1700. 'ttml': 'http://www.w3.org/ns/ttml',
  1701. 'ttaf1': 'http://www.w3.org/2006/10/ttaf1',
  1702. })
  1703. class TTMLPElementParser(object):
  1704. out = ''
  1705. def start(self, tag, attrib):
  1706. if tag in (_x('ttml:br'), _x('ttaf1:br'), 'br'):
  1707. self.out += '\n'
  1708. def end(self, tag):
  1709. pass
  1710. def data(self, data):
  1711. self.out += data
  1712. def close(self):
  1713. return self.out.strip()
  1714. def parse_node(node):
  1715. target = TTMLPElementParser()
  1716. parser = xml.etree.ElementTree.XMLParser(target=target)
  1717. parser.feed(xml.etree.ElementTree.tostring(node))
  1718. return parser.close()
  1719. dfxp = compat_etree_fromstring(dfxp_data.encode('utf-8'))
  1720. out = []
  1721. paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall(_x('.//ttaf1:p')) or dfxp.findall('.//p')
  1722. if not paras:
  1723. raise ValueError('Invalid dfxp/TTML subtitle')
  1724. for para, index in zip(paras, itertools.count(1)):
  1725. begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
  1726. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  1727. dur = parse_dfxp_time_expr(para.attrib.get('dur'))
  1728. if begin_time is None:
  1729. continue
  1730. if not end_time:
  1731. if not dur:
  1732. continue
  1733. end_time = begin_time + dur
  1734. out.append('%d\n%s --> %s\n%s\n\n' % (
  1735. index,
  1736. srt_subtitles_timecode(begin_time),
  1737. srt_subtitles_timecode(end_time),
  1738. parse_node(para)))
  1739. return ''.join(out)
  1740. def cli_option(params, command_option, param):
  1741. param = params.get(param)
  1742. return [command_option, param] if param is not None else []
  1743. def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
  1744. param = params.get(param)
  1745. assert isinstance(param, bool)
  1746. if separator:
  1747. return [command_option + separator + (true_value if param else false_value)]
  1748. return [command_option, true_value if param else false_value]
  1749. def cli_valueless_option(params, command_option, param, expected_value=True):
  1750. param = params.get(param)
  1751. return [command_option] if param == expected_value else []
  1752. def cli_configuration_args(params, param, default=[]):
  1753. ex_args = params.get(param)
  1754. if ex_args is None:
  1755. return default
  1756. assert isinstance(ex_args, list)
  1757. return ex_args
  1758. class ISO639Utils(object):
  1759. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  1760. _lang_map = {
  1761. 'aa': 'aar',
  1762. 'ab': 'abk',
  1763. 'ae': 'ave',
  1764. 'af': 'afr',
  1765. 'ak': 'aka',
  1766. 'am': 'amh',
  1767. 'an': 'arg',
  1768. 'ar': 'ara',
  1769. 'as': 'asm',
  1770. 'av': 'ava',
  1771. 'ay': 'aym',
  1772. 'az': 'aze',
  1773. 'ba': 'bak',
  1774. 'be': 'bel',
  1775. 'bg': 'bul',
  1776. 'bh': 'bih',
  1777. 'bi': 'bis',
  1778. 'bm': 'bam',
  1779. 'bn': 'ben',
  1780. 'bo': 'bod',
  1781. 'br': 'bre',
  1782. 'bs': 'bos',
  1783. 'ca': 'cat',
  1784. 'ce': 'che',
  1785. 'ch': 'cha',
  1786. 'co': 'cos',
  1787. 'cr': 'cre',
  1788. 'cs': 'ces',
  1789. 'cu': 'chu',
  1790. 'cv': 'chv',
  1791. 'cy': 'cym',
  1792. 'da': 'dan',
  1793. 'de': 'deu',
  1794. 'dv': 'div',
  1795. 'dz': 'dzo',
  1796. 'ee': 'ewe',
  1797. 'el': 'ell',
  1798. 'en': 'eng',
  1799. 'eo': 'epo',
  1800. 'es': 'spa',
  1801. 'et': 'est',
  1802. 'eu': 'eus',
  1803. 'fa': 'fas',
  1804. 'ff': 'ful',
  1805. 'fi': 'fin',
  1806. 'fj': 'fij',
  1807. 'fo': 'fao',
  1808. 'fr': 'fra',
  1809. 'fy': 'fry',
  1810. 'ga': 'gle',
  1811. 'gd': 'gla',
  1812. 'gl': 'glg',
  1813. 'gn': 'grn',
  1814. 'gu': 'guj',
  1815. 'gv': 'glv',
  1816. 'ha': 'hau',
  1817. 'he': 'heb',
  1818. 'hi': 'hin',
  1819. 'ho': 'hmo',
  1820. 'hr': 'hrv',
  1821. 'ht': 'hat',
  1822. 'hu': 'hun',
  1823. 'hy': 'hye',
  1824. 'hz': 'her',
  1825. 'ia': 'ina',
  1826. 'id': 'ind',
  1827. 'ie': 'ile',
  1828. 'ig': 'ibo',
  1829. 'ii': 'iii',
  1830. 'ik': 'ipk',
  1831. 'io': 'ido',
  1832. 'is': 'isl',
  1833. 'it': 'ita',
  1834. 'iu': 'iku',
  1835. 'ja': 'jpn',
  1836. 'jv': 'jav',
  1837. 'ka': 'kat',
  1838. 'kg': 'kon',
  1839. 'ki': 'kik',
  1840. 'kj': 'kua',
  1841. 'kk': 'kaz',
  1842. 'kl': 'kal',
  1843. 'km': 'khm',
  1844. 'kn': 'kan',
  1845. 'ko': 'kor',
  1846. 'kr': 'kau',
  1847. 'ks': 'kas',
  1848. 'ku': 'kur',
  1849. 'kv': 'kom',
  1850. 'kw': 'cor',
  1851. 'ky': 'kir',
  1852. 'la': 'lat',
  1853. 'lb': 'ltz',
  1854. 'lg': 'lug',
  1855. 'li': 'lim',
  1856. 'ln': 'lin',
  1857. 'lo': 'lao',
  1858. 'lt': 'lit',
  1859. 'lu': 'lub',
  1860. 'lv': 'lav',
  1861. 'mg': 'mlg',
  1862. 'mh': 'mah',
  1863. 'mi': 'mri',
  1864. 'mk': 'mkd',
  1865. 'ml': 'mal',
  1866. 'mn': 'mon',
  1867. 'mr': 'mar',
  1868. 'ms': 'msa',
  1869. 'mt': 'mlt',
  1870. 'my': 'mya',
  1871. 'na': 'nau',
  1872. 'nb': 'nob',
  1873. 'nd': 'nde',
  1874. 'ne': 'nep',
  1875. 'ng': 'ndo',
  1876. 'nl': 'nld',
  1877. 'nn': 'nno',
  1878. 'no': 'nor',
  1879. 'nr': 'nbl',
  1880. 'nv': 'nav',
  1881. 'ny': 'nya',
  1882. 'oc': 'oci',
  1883. 'oj': 'oji',
  1884. 'om': 'orm',
  1885. 'or': 'ori',
  1886. 'os': 'oss',
  1887. 'pa': 'pan',
  1888. 'pi': 'pli',
  1889. 'pl': 'pol',
  1890. 'ps': 'pus',
  1891. 'pt': 'por',
  1892. 'qu': 'que',
  1893. 'rm': 'roh',
  1894. 'rn': 'run',
  1895. 'ro': 'ron',
  1896. 'ru': 'rus',
  1897. 'rw': 'kin',
  1898. 'sa': 'san',
  1899. 'sc': 'srd',
  1900. 'sd': 'snd',
  1901. 'se': 'sme',
  1902. 'sg': 'sag',
  1903. 'si': 'sin',
  1904. 'sk': 'slk',
  1905. 'sl': 'slv',
  1906. 'sm': 'smo',
  1907. 'sn': 'sna',
  1908. 'so': 'som',
  1909. 'sq': 'sqi',
  1910. 'sr': 'srp',
  1911. 'ss': 'ssw',
  1912. 'st': 'sot',
  1913. 'su': 'sun',
  1914. 'sv': 'swe',
  1915. 'sw': 'swa',
  1916. 'ta': 'tam',
  1917. 'te': 'tel',
  1918. 'tg': 'tgk',
  1919. 'th': 'tha',
  1920. 'ti': 'tir',
  1921. 'tk': 'tuk',
  1922. 'tl': 'tgl',
  1923. 'tn': 'tsn',
  1924. 'to': 'ton',
  1925. 'tr': 'tur',
  1926. 'ts': 'tso',
  1927. 'tt': 'tat',
  1928. 'tw': 'twi',
  1929. 'ty': 'tah',
  1930. 'ug': 'uig',
  1931. 'uk': 'ukr',
  1932. 'ur': 'urd',
  1933. 'uz': 'uzb',
  1934. 've': 'ven',
  1935. 'vi': 'vie',
  1936. 'vo': 'vol',
  1937. 'wa': 'wln',
  1938. 'wo': 'wol',
  1939. 'xh': 'xho',
  1940. 'yi': 'yid',
  1941. 'yo': 'yor',
  1942. 'za': 'zha',
  1943. 'zh': 'zho',
  1944. 'zu': 'zul',
  1945. }
  1946. @classmethod
  1947. def short2long(cls, code):
  1948. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  1949. return cls._lang_map.get(code[:2])
  1950. @classmethod
  1951. def long2short(cls, code):
  1952. """Convert language code from ISO 639-2/T to ISO 639-1"""
  1953. for short_name, long_name in cls._lang_map.items():
  1954. if long_name == code:
  1955. return short_name
  1956. class ISO3166Utils(object):
  1957. # From http://data.okfn.org/data/core/country-list
  1958. _country_map = {
  1959. 'AF': 'Afghanistan',
  1960. 'AX': 'Åland Islands',
  1961. 'AL': 'Albania',
  1962. 'DZ': 'Algeria',
  1963. 'AS': 'American Samoa',
  1964. 'AD': 'Andorra',
  1965. 'AO': 'Angola',
  1966. 'AI': 'Anguilla',
  1967. 'AQ': 'Antarctica',
  1968. 'AG': 'Antigua and Barbuda',
  1969. 'AR': 'Argentina',
  1970. 'AM': 'Armenia',
  1971. 'AW': 'Aruba',
  1972. 'AU': 'Australia',
  1973. 'AT': 'Austria',
  1974. 'AZ': 'Azerbaijan',
  1975. 'BS': 'Bahamas',
  1976. 'BH': 'Bahrain',
  1977. 'BD': 'Bangladesh',
  1978. 'BB': 'Barbados',
  1979. 'BY': 'Belarus',
  1980. 'BE': 'Belgium',
  1981. 'BZ': 'Belize',
  1982. 'BJ': 'Benin',
  1983. 'BM': 'Bermuda',
  1984. 'BT': 'Bhutan',
  1985. 'BO': 'Bolivia, Plurinational State of',
  1986. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  1987. 'BA': 'Bosnia and Herzegovina',
  1988. 'BW': 'Botswana',
  1989. 'BV': 'Bouvet Island',
  1990. 'BR': 'Brazil',
  1991. 'IO': 'British Indian Ocean Territory',
  1992. 'BN': 'Brunei Darussalam',
  1993. 'BG': 'Bulgaria',
  1994. 'BF': 'Burkina Faso',
  1995. 'BI': 'Burundi',
  1996. 'KH': 'Cambodia',
  1997. 'CM': 'Cameroon',
  1998. 'CA': 'Canada',
  1999. 'CV': 'Cape Verde',
  2000. 'KY': 'Cayman Islands',
  2001. 'CF': 'Central African Republic',
  2002. 'TD': 'Chad',
  2003. 'CL': 'Chile',
  2004. 'CN': 'China',
  2005. 'CX': 'Christmas Island',
  2006. 'CC': 'Cocos (Keeling) Islands',
  2007. 'CO': 'Colombia',
  2008. 'KM': 'Comoros',
  2009. 'CG': 'Congo',
  2010. 'CD': 'Congo, the Democratic Republic of the',
  2011. 'CK': 'Cook Islands',
  2012. 'CR': 'Costa Rica',
  2013. 'CI': 'Côte d\'Ivoire',
  2014. 'HR': 'Croatia',
  2015. 'CU': 'Cuba',
  2016. 'CW': 'Curaçao',
  2017. 'CY': 'Cyprus',
  2018. 'CZ': 'Czech Republic',
  2019. 'DK': 'Denmark',
  2020. 'DJ': 'Djibouti',
  2021. 'DM': 'Dominica',
  2022. 'DO': 'Dominican Republic',
  2023. 'EC': 'Ecuador',
  2024. 'EG': 'Egypt',
  2025. 'SV': 'El Salvador',
  2026. 'GQ': 'Equatorial Guinea',
  2027. 'ER': 'Eritrea',
  2028. 'EE': 'Estonia',
  2029. 'ET': 'Ethiopia',
  2030. 'FK': 'Falkland Islands (Malvinas)',
  2031. 'FO': 'Faroe Islands',
  2032. 'FJ': 'Fiji',
  2033. 'FI': 'Finland',
  2034. 'FR': 'France',
  2035. 'GF': 'French Guiana',
  2036. 'PF': 'French Polynesia',
  2037. 'TF': 'French Southern Territories',
  2038. 'GA': 'Gabon',
  2039. 'GM': 'Gambia',
  2040. 'GE': 'Georgia',
  2041. 'DE': 'Germany',
  2042. 'GH': 'Ghana',
  2043. 'GI': 'Gibraltar',
  2044. 'GR': 'Greece',
  2045. 'GL': 'Greenland',
  2046. 'GD': 'Grenada',
  2047. 'GP': 'Guadeloupe',
  2048. 'GU': 'Guam',
  2049. 'GT': 'Guatemala',
  2050. 'GG': 'Guernsey',
  2051. 'GN': 'Guinea',
  2052. 'GW': 'Guinea-Bissau',
  2053. 'GY': 'Guyana',
  2054. 'HT': 'Haiti',
  2055. 'HM': 'Heard Island and McDonald Islands',
  2056. 'VA': 'Holy See (Vatican City State)',
  2057. 'HN': 'Honduras',
  2058. 'HK': 'Hong Kong',
  2059. 'HU': 'Hungary',
  2060. 'IS': 'Iceland',
  2061. 'IN': 'India',
  2062. 'ID': 'Indonesia',
  2063. 'IR': 'Iran, Islamic Republic of',
  2064. 'IQ': 'Iraq',
  2065. 'IE': 'Ireland',
  2066. 'IM': 'Isle of Man',
  2067. 'IL': 'Israel',
  2068. 'IT': 'Italy',
  2069. 'JM': 'Jamaica',
  2070. 'JP': 'Japan',
  2071. 'JE': 'Jersey',
  2072. 'JO': 'Jordan',
  2073. 'KZ': 'Kazakhstan',
  2074. 'KE': 'Kenya',
  2075. 'KI': 'Kiribati',
  2076. 'KP': 'Korea, Democratic People\'s Republic of',
  2077. 'KR': 'Korea, Republic of',
  2078. 'KW': 'Kuwait',
  2079. 'KG': 'Kyrgyzstan',
  2080. 'LA': 'Lao People\'s Democratic Republic',
  2081. 'LV': 'Latvia',
  2082. 'LB': 'Lebanon',
  2083. 'LS': 'Lesotho',
  2084. 'LR': 'Liberia',
  2085. 'LY': 'Libya',
  2086. 'LI': 'Liechtenstein',
  2087. 'LT': 'Lithuania',
  2088. 'LU': 'Luxembourg',
  2089. 'MO': 'Macao',
  2090. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  2091. 'MG': 'Madagascar',
  2092. 'MW': 'Malawi',
  2093. 'MY': 'Malaysia',
  2094. 'MV': 'Maldives',
  2095. 'ML': 'Mali',
  2096. 'MT': 'Malta',
  2097. 'MH': 'Marshall Islands',
  2098. 'MQ': 'Martinique',
  2099. 'MR': 'Mauritania',
  2100. 'MU': 'Mauritius',
  2101. 'YT': 'Mayotte',
  2102. 'MX': 'Mexico',
  2103. 'FM': 'Micronesia, Federated States of',
  2104. 'MD': 'Moldova, Republic of',
  2105. 'MC': 'Monaco',
  2106. 'MN': 'Mongolia',
  2107. 'ME': 'Montenegro',
  2108. 'MS': 'Montserrat',
  2109. 'MA': 'Morocco',
  2110. 'MZ': 'Mozambique',
  2111. 'MM': 'Myanmar',
  2112. 'NA': 'Namibia',
  2113. 'NR': 'Nauru',
  2114. 'NP': 'Nepal',
  2115. 'NL': 'Netherlands',
  2116. 'NC': 'New Caledonia',
  2117. 'NZ': 'New Zealand',
  2118. 'NI': 'Nicaragua',
  2119. 'NE': 'Niger',
  2120. 'NG': 'Nigeria',
  2121. 'NU': 'Niue',
  2122. 'NF': 'Norfolk Island',
  2123. 'MP': 'Northern Mariana Islands',
  2124. 'NO': 'Norway',
  2125. 'OM': 'Oman',
  2126. 'PK': 'Pakistan',
  2127. 'PW': 'Palau',
  2128. 'PS': 'Palestine, State of',
  2129. 'PA': 'Panama',
  2130. 'PG': 'Papua New Guinea',
  2131. 'PY': 'Paraguay',
  2132. 'PE': 'Peru',
  2133. 'PH': 'Philippines',
  2134. 'PN': 'Pitcairn',
  2135. 'PL': 'Poland',
  2136. 'PT': 'Portugal',
  2137. 'PR': 'Puerto Rico',
  2138. 'QA': 'Qatar',
  2139. 'RE': 'Réunion',
  2140. 'RO': 'Romania',
  2141. 'RU': 'Russian Federation',
  2142. 'RW': 'Rwanda',
  2143. 'BL': 'Saint Barthélemy',
  2144. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  2145. 'KN': 'Saint Kitts and Nevis',
  2146. 'LC': 'Saint Lucia',
  2147. 'MF': 'Saint Martin (French part)',
  2148. 'PM': 'Saint Pierre and Miquelon',
  2149. 'VC': 'Saint Vincent and the Grenadines',
  2150. 'WS': 'Samoa',
  2151. 'SM': 'San Marino',
  2152. 'ST': 'Sao Tome and Principe',
  2153. 'SA': 'Saudi Arabia',
  2154. 'SN': 'Senegal',
  2155. 'RS': 'Serbia',
  2156. 'SC': 'Seychelles',
  2157. 'SL': 'Sierra Leone',
  2158. 'SG': 'Singapore',
  2159. 'SX': 'Sint Maarten (Dutch part)',
  2160. 'SK': 'Slovakia',
  2161. 'SI': 'Slovenia',
  2162. 'SB': 'Solomon Islands',
  2163. 'SO': 'Somalia',
  2164. 'ZA': 'South Africa',
  2165. 'GS': 'South Georgia and the South Sandwich Islands',
  2166. 'SS': 'South Sudan',
  2167. 'ES': 'Spain',
  2168. 'LK': 'Sri Lanka',
  2169. 'SD': 'Sudan',
  2170. 'SR': 'Suriname',
  2171. 'SJ': 'Svalbard and Jan Mayen',
  2172. 'SZ': 'Swaziland',
  2173. 'SE': 'Sweden',
  2174. 'CH': 'Switzerland',
  2175. 'SY': 'Syrian Arab Republic',
  2176. 'TW': 'Taiwan, Province of China',
  2177. 'TJ': 'Tajikistan',
  2178. 'TZ': 'Tanzania, United Republic of',
  2179. 'TH': 'Thailand',
  2180. 'TL': 'Timor-Leste',
  2181. 'TG': 'Togo',
  2182. 'TK': 'Tokelau',
  2183. 'TO': 'Tonga',
  2184. 'TT': 'Trinidad and Tobago',
  2185. 'TN': 'Tunisia',
  2186. 'TR': 'Turkey',
  2187. 'TM': 'Turkmenistan',
  2188. 'TC': 'Turks and Caicos Islands',
  2189. 'TV': 'Tuvalu',
  2190. 'UG': 'Uganda',
  2191. 'UA': 'Ukraine',
  2192. 'AE': 'United Arab Emirates',
  2193. 'GB': 'United Kingdom',
  2194. 'US': 'United States',
  2195. 'UM': 'United States Minor Outlying Islands',
  2196. 'UY': 'Uruguay',
  2197. 'UZ': 'Uzbekistan',
  2198. 'VU': 'Vanuatu',
  2199. 'VE': 'Venezuela, Bolivarian Republic of',
  2200. 'VN': 'Viet Nam',
  2201. 'VG': 'Virgin Islands, British',
  2202. 'VI': 'Virgin Islands, U.S.',
  2203. 'WF': 'Wallis and Futuna',
  2204. 'EH': 'Western Sahara',
  2205. 'YE': 'Yemen',
  2206. 'ZM': 'Zambia',
  2207. 'ZW': 'Zimbabwe',
  2208. }
  2209. @classmethod
  2210. def short2full(cls, code):
  2211. """Convert an ISO 3166-2 country code to the corresponding full name"""
  2212. return cls._country_map.get(code.upper())
  2213. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  2214. def __init__(self, proxies=None):
  2215. # Set default handlers
  2216. for type in ('http', 'https'):
  2217. setattr(self, '%s_open' % type,
  2218. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  2219. meth(r, proxy, type))
  2220. return compat_urllib_request.ProxyHandler.__init__(self, proxies)
  2221. def proxy_open(self, req, proxy, type):
  2222. req_proxy = req.headers.get('Ytdl-request-proxy')
  2223. if req_proxy is not None:
  2224. proxy = req_proxy
  2225. del req.headers['Ytdl-request-proxy']
  2226. if proxy == '__noproxy__':
  2227. return None # No Proxy
  2228. return compat_urllib_request.ProxyHandler.proxy_open(
  2229. self, req, proxy, type)
  2230. def ohdave_rsa_encrypt(data, exponent, modulus):
  2231. '''
  2232. Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
  2233. Input:
  2234. data: data to encrypt, bytes-like object
  2235. exponent, modulus: parameter e and N of RSA algorithm, both integer
  2236. Output: hex string of encrypted data
  2237. Limitation: supports one block encryption only
  2238. '''
  2239. payload = int(binascii.hexlify(data[::-1]), 16)
  2240. encrypted = pow(payload, exponent, modulus)
  2241. return '%x' % encrypted
  2242. def encode_base_n(num, n, table=None):
  2243. FULL_TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  2244. if not table:
  2245. table = FULL_TABLE[:n]
  2246. if n > len(table):
  2247. raise ValueError('base %d exceeds table length %d' % (n, len(table)))
  2248. if num == 0:
  2249. return table[0]
  2250. ret = ''
  2251. while num:
  2252. ret = table[num % n] + ret
  2253. num = num // n
  2254. return ret
  2255. def decode_packed_codes(code):
  2256. mobj = re.search(
  2257. r"}\('(.+)',(\d+),(\d+),'([^']+)'\.split\('\|'\)",
  2258. code)
  2259. obfucasted_code, base, count, symbols = mobj.groups()
  2260. base = int(base)
  2261. count = int(count)
  2262. symbols = symbols.split('|')
  2263. symbol_table = {}
  2264. while count:
  2265. count -= 1
  2266. base_n_count = encode_base_n(count, base)
  2267. symbol_table[base_n_count] = symbols[count] or base_n_count
  2268. return re.sub(
  2269. r'\b(\w+)\b', lambda mobj: symbol_table[mobj.group(0)],
  2270. obfucasted_code)