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.

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