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.

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