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.

2369 lines
70 KiB

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