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.

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