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.

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