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.

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