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.

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