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.

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