PageRenderTime 59ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/youtube_dl/utils.py

https://gitlab.com/angelbirth/youtube-dl
Python | 1539 lines | 1491 code | 36 blank | 12 comment | 42 complexity | 9efd42e706a9467e3b9b4b44c6119a07 MD5 | raw file
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import unicode_literals
  4. import base64
  5. import binascii
  6. import calendar
  7. import codecs
  8. import contextlib
  9. import ctypes
  10. import datetime
  11. import email.utils
  12. import errno
  13. import functools
  14. import gzip
  15. import io
  16. import itertools
  17. import json
  18. import locale
  19. import math
  20. import operator
  21. import os
  22. import pipes
  23. import platform
  24. import re
  25. import socket
  26. import ssl
  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_HTMLParser,
  35. compat_basestring,
  36. compat_chr,
  37. compat_etree_fromstring,
  38. compat_html_entities,
  39. compat_html_entities_html5,
  40. compat_http_client,
  41. compat_kwargs,
  42. compat_os_name,
  43. compat_parse_qs,
  44. compat_shlex_quote,
  45. compat_socket_create_connection,
  46. compat_str,
  47. compat_struct_pack,
  48. compat_struct_unpack,
  49. compat_urllib_error,
  50. compat_urllib_parse,
  51. compat_urllib_parse_urlencode,
  52. compat_urllib_parse_urlparse,
  53. compat_urllib_parse_unquote_plus,
  54. compat_urllib_request,
  55. compat_urlparse,
  56. compat_xpath,
  57. )
  58. from .socks import (
  59. ProxyType,
  60. sockssocket,
  61. )
  62. def register_socks_protocols():
  63. # "Register" SOCKS protocols
  64. # In Python < 2.6.5, urlsplit() suffers from bug https://bugs.python.org/issue7904
  65. # URLs with protocols not in urlparse.uses_netloc are not handled correctly
  66. for scheme in ('socks', 'socks4', 'socks4a', 'socks5'):
  67. if scheme not in compat_urlparse.uses_netloc:
  68. compat_urlparse.uses_netloc.append(scheme)
  69. # This is not clearly defined otherwise
  70. compiled_regex_type = type(re.compile(''))
  71. std_headers = {
  72. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/47.0 (Chrome)',
  73. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  74. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  75. 'Accept-Encoding': 'gzip, deflate',
  76. 'Accept-Language': 'en-us,en;q=0.5',
  77. }
  78. NO_DEFAULT = object()
  79. ENGLISH_MONTH_NAMES = [
  80. 'January', 'February', 'March', 'April', 'May', 'June',
  81. 'July', 'August', 'September', 'October', 'November', 'December']
  82. MONTH_NAMES = {
  83. 'en': ENGLISH_MONTH_NAMES,
  84. 'fr': [
  85. 'janvier', 'février', 'mars', 'avril', 'mai', 'juin',
  86. 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
  87. }
  88. KNOWN_EXTENSIONS = (
  89. 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'aac',
  90. 'flv', 'f4v', 'f4a', 'f4b',
  91. 'webm', 'ogg', 'ogv', 'oga', 'ogx', 'spx', 'opus',
  92. 'mkv', 'mka', 'mk3d',
  93. 'avi', 'divx',
  94. 'mov',
  95. 'asf', 'wmv', 'wma',
  96. '3gp', '3g2',
  97. 'mp3',
  98. 'flac',
  99. 'ape',
  100. 'wav',
  101. 'f4f', 'f4m', 'm3u8', 'smil')
  102. # needed for sanitizing filenames in restricted mode
  103. ACCENT_CHARS = dict(zip('ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ',
  104. itertools.chain('AAAAAA', ['AE'], 'CEEEEIIIIDNOOOOOOO', ['OE'], 'UUUUUYP', ['ss'],
  105. 'aaaaaa', ['ae'], 'ceeeeiiiionooooooo', ['oe'], 'uuuuuypy')))
  106. DATE_FORMATS = (
  107. '%d %B %Y',
  108. '%d %b %Y',
  109. '%B %d %Y',
  110. '%b %d %Y',
  111. '%b %dst %Y %I:%M',
  112. '%b %dnd %Y %I:%M',
  113. '%b %dth %Y %I:%M',
  114. '%Y %m %d',
  115. '%Y-%m-%d',
  116. '%Y/%m/%d',
  117. '%Y/%m/%d %H:%M',
  118. '%Y/%m/%d %H:%M:%S',
  119. '%Y-%m-%d %H:%M:%S',
  120. '%Y-%m-%d %H:%M:%S.%f',
  121. '%d.%m.%Y %H:%M',
  122. '%d.%m.%Y %H.%M',
  123. '%Y-%m-%dT%H:%M:%SZ',
  124. '%Y-%m-%dT%H:%M:%S.%fZ',
  125. '%Y-%m-%dT%H:%M:%S.%f0Z',
  126. '%Y-%m-%dT%H:%M:%S',
  127. '%Y-%m-%dT%H:%M:%S.%f',
  128. '%Y-%m-%dT%H:%M',
  129. '%b %d %Y at %H:%M',
  130. '%b %d %Y at %H:%M:%S',
  131. )
  132. DATE_FORMATS_DAY_FIRST = list(DATE_FORMATS)
  133. DATE_FORMATS_DAY_FIRST.extend([
  134. '%d-%m-%Y',
  135. '%d.%m.%Y',
  136. '%d.%m.%y',
  137. '%d/%m/%Y',
  138. '%d/%m/%y',
  139. '%d/%m/%Y %H:%M:%S',
  140. ])
  141. DATE_FORMATS_MONTH_FIRST = list(DATE_FORMATS)
  142. DATE_FORMATS_MONTH_FIRST.extend([
  143. '%m-%d-%Y',
  144. '%m.%d.%Y',
  145. '%m/%d/%Y',
  146. '%m/%d/%y',
  147. '%m/%d/%Y %H:%M:%S',
  148. ])
  149. def preferredencoding():
  150. """Get preferred encoding.
  151. Returns the best encoding scheme for the system, based on
  152. locale.getpreferredencoding() and some further tweaks.
  153. """
  154. try:
  155. pref = locale.getpreferredencoding()
  156. 'TEST'.encode(pref)
  157. except Exception:
  158. pref = 'UTF-8'
  159. return pref
  160. def write_json_file(obj, fn):
  161. """ Encode obj as JSON and write it to fn, atomically if possible """
  162. fn = encodeFilename(fn)
  163. if sys.version_info < (3, 0) and sys.platform != 'win32':
  164. encoding = get_filesystem_encoding()
  165. # os.path.basename returns a bytes object, but NamedTemporaryFile
  166. # will fail if the filename contains non ascii characters unless we
  167. # use a unicode object
  168. path_basename = lambda f: os.path.basename(fn).decode(encoding)
  169. # the same for os.path.dirname
  170. path_dirname = lambda f: os.path.dirname(fn).decode(encoding)
  171. else:
  172. path_basename = os.path.basename
  173. path_dirname = os.path.dirname
  174. args = {
  175. 'suffix': '.tmp',
  176. 'prefix': path_basename(fn) + '.',
  177. 'dir': path_dirname(fn),
  178. 'delete': False,
  179. }
  180. # In Python 2.x, json.dump expects a bytestream.
  181. # In Python 3.x, it writes to a character stream
  182. if sys.version_info < (3, 0):
  183. args['mode'] = 'wb'
  184. else:
  185. args.update({
  186. 'mode': 'w',
  187. 'encoding': 'utf-8',
  188. })
  189. tf = tempfile.NamedTemporaryFile(**compat_kwargs(args))
  190. try:
  191. with tf:
  192. json.dump(obj, tf)
  193. if sys.platform == 'win32':
  194. # Need to remove existing file on Windows, else os.rename raises
  195. # WindowsError or FileExistsError.
  196. try:
  197. os.unlink(fn)
  198. except OSError:
  199. pass
  200. os.rename(tf.name, fn)
  201. except Exception:
  202. try:
  203. os.remove(tf.name)
  204. except OSError:
  205. pass
  206. raise
  207. if sys.version_info >= (2, 7):
  208. def find_xpath_attr(node, xpath, key, val=None):
  209. """ Find the xpath xpath[@key=val] """
  210. assert re.match(r'^[a-zA-Z_-]+$', key)
  211. expr = xpath + ('[@%s]' % key if val is None else "[@%s='%s']" % (key, val))
  212. return node.find(expr)
  213. else:
  214. def find_xpath_attr(node, xpath, key, val=None):
  215. for f in node.findall(compat_xpath(xpath)):
  216. if key not in f.attrib:
  217. continue
  218. if val is None or f.attrib.get(key) == val:
  219. return f
  220. return None
  221. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  222. # the namespace parameter
  223. def xpath_with_ns(path, ns_map):
  224. components = [c.split(':') for c in path.split('/')]
  225. replaced = []
  226. for c in components:
  227. if len(c) == 1:
  228. replaced.append(c[0])
  229. else:
  230. ns, tag = c
  231. replaced.append('{%s}%s' % (ns_map[ns], tag))
  232. return '/'.join(replaced)
  233. def xpath_element(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  234. def _find_xpath(xpath):
  235. return node.find(compat_xpath(xpath))
  236. if isinstance(xpath, (str, compat_str)):
  237. n = _find_xpath(xpath)
  238. else:
  239. for xp in xpath:
  240. n = _find_xpath(xp)
  241. if n is not None:
  242. break
  243. if n is None:
  244. if default is not NO_DEFAULT:
  245. return default
  246. elif fatal:
  247. name = xpath if name is None else name
  248. raise ExtractorError('Could not find XML element %s' % name)
  249. else:
  250. return None
  251. return n
  252. def xpath_text(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  253. n = xpath_element(node, xpath, name, fatal=fatal, default=default)
  254. if n is None or n == default:
  255. return n
  256. if n.text is None:
  257. if default is not NO_DEFAULT:
  258. return default
  259. elif fatal:
  260. name = xpath if name is None else name
  261. raise ExtractorError('Could not find XML element\'s text %s' % name)
  262. else:
  263. return None
  264. return n.text
  265. def xpath_attr(node, xpath, key, name=None, fatal=False, default=NO_DEFAULT):
  266. n = find_xpath_attr(node, xpath, key)
  267. if n is None:
  268. if default is not NO_DEFAULT:
  269. return default
  270. elif fatal:
  271. name = '%s[@%s]' % (xpath, key) if name is None else name
  272. raise ExtractorError('Could not find XML attribute %s' % name)
  273. else:
  274. return None
  275. return n.attrib[key]
  276. def get_element_by_id(id, html):
  277. """Return the content of the tag with the specified ID in the passed HTML document"""
  278. return get_element_by_attribute('id', id, html)
  279. def get_element_by_class(class_name, html):
  280. return get_element_by_attribute(
  281. 'class', r'[^\'"]*\b%s\b[^\'"]*' % re.escape(class_name),
  282. html, escape_value=False)
  283. def get_element_by_attribute(attribute, value, html, escape_value=True):
  284. """Return the content of the tag with the specified attribute in the passed HTML document"""
  285. value = re.escape(value) if escape_value else value
  286. m = re.search(r'''(?xs)
  287. <([a-zA-Z0-9:._-]+)
  288. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'))*?
  289. \s+%s=['"]?%s['"]?
  290. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'))*?
  291. \s*>
  292. (?P<content>.*?)
  293. </\1>
  294. ''' % (re.escape(attribute), value), html)
  295. if not m:
  296. return None
  297. res = m.group('content')
  298. if res.startswith('"') or res.startswith("'"):
  299. res = res[1:-1]
  300. return unescapeHTML(res)
  301. class HTMLAttributeParser(compat_HTMLParser):
  302. """Trivial HTML parser to gather the attributes for a single element"""
  303. def __init__(self):
  304. self.attrs = {}
  305. compat_HTMLParser.__init__(self)
  306. def handle_starttag(self, tag, attrs):
  307. self.attrs = dict(attrs)
  308. def extract_attributes(html_element):
  309. """Given a string for an HTML element such as
  310. <el
  311. a="foo" B="bar" c="&98;az" d=boz
  312. empty= noval entity="&amp;"
  313. sq='"' dq="'"
  314. >
  315. Decode and return a dictionary of attributes.
  316. {
  317. 'a': 'foo', 'b': 'bar', c: 'baz', d: 'boz',
  318. 'empty': '', 'noval': None, 'entity': '&',
  319. 'sq': '"', 'dq': '\''
  320. }.
  321. NB HTMLParser is stricter in Python 2.6 & 3.2 than in later versions,
  322. but the cases in the unit test will work for all of 2.6, 2.7, 3.2-3.5.
  323. """
  324. parser = HTMLAttributeParser()
  325. parser.feed(html_element)
  326. parser.close()
  327. return parser.attrs
  328. def clean_html(html):
  329. """Clean an HTML snippet into a readable string"""
  330. if html is None: # Convenience for sanitizing descriptions etc.
  331. return html
  332. # Newline vs <br />
  333. html = html.replace('\n', ' ')
  334. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  335. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  336. # Strip html tags
  337. html = re.sub('<.*?>', '', html)
  338. # Replace html entities
  339. html = unescapeHTML(html)
  340. return html.strip()
  341. def sanitize_open(filename, open_mode):
  342. """Try to open the given filename, and slightly tweak it if this fails.
  343. Attempts to open the given filename. If this fails, it tries to change
  344. the filename slightly, step by step, until it's either able to open it
  345. or it fails and raises a final exception, like the standard open()
  346. function.
  347. It returns the tuple (stream, definitive_file_name).
  348. """
  349. try:
  350. if filename == '-':
  351. if sys.platform == 'win32':
  352. import msvcrt
  353. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  354. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  355. stream = open(encodeFilename(filename), open_mode)
  356. return (stream, filename)
  357. except (IOError, OSError) as err:
  358. if err.errno in (errno.EACCES,):
  359. raise
  360. # In case of error, try to remove win32 forbidden chars
  361. alt_filename = sanitize_path(filename)
  362. if alt_filename == filename:
  363. raise
  364. else:
  365. # An exception here should be caught in the caller
  366. stream = open(encodeFilename(alt_filename), open_mode)
  367. return (stream, alt_filename)
  368. def timeconvert(timestr):
  369. """Convert RFC 2822 defined time string into system timestamp"""
  370. timestamp = None
  371. timetuple = email.utils.parsedate_tz(timestr)
  372. if timetuple is not None:
  373. timestamp = email.utils.mktime_tz(timetuple)
  374. return timestamp
  375. def sanitize_filename(s, restricted=False, is_id=False):
  376. """Sanitizes a string so it could be used as part of a filename.
  377. If restricted is set, use a stricter subset of allowed characters.
  378. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  379. """
  380. def replace_insane(char):
  381. if restricted and char in ACCENT_CHARS:
  382. return ACCENT_CHARS[char]
  383. if char == '?' or ord(char) < 32 or ord(char) == 127:
  384. return ''
  385. elif char == '"':
  386. return '' if restricted else '\''
  387. elif char == ':':
  388. return '_-' if restricted else ' -'
  389. elif char in '\\/|*<>':
  390. return '_'
  391. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  392. return '_'
  393. if restricted and ord(char) > 127:
  394. return '_'
  395. return char
  396. # Handle timestamps
  397. s = re.sub(r'[0-9]+(?::[0-9]+)+', lambda m: m.group(0).replace(':', '_'), s)
  398. result = ''.join(map(replace_insane, s))
  399. if not is_id:
  400. while '__' in result:
  401. result = result.replace('__', '_')
  402. result = result.strip('_')
  403. # Common case of "Foreign band name - English song title"
  404. if restricted and result.startswith('-_'):
  405. result = result[2:]
  406. if result.startswith('-'):
  407. result = '_' + result[len('-'):]
  408. result = result.lstrip('.')
  409. if not result:
  410. result = '_'
  411. return result
  412. def sanitize_path(s):
  413. """Sanitizes and normalizes path on Windows"""
  414. if sys.platform != 'win32':
  415. return s
  416. drive_or_unc, _ = os.path.splitdrive(s)
  417. if sys.version_info < (2, 7) and not drive_or_unc:
  418. drive_or_unc, _ = os.path.splitunc(s)
  419. norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
  420. if drive_or_unc:
  421. norm_path.pop(0)
  422. sanitized_path = [
  423. path_part if path_part in ['.', '..'] else re.sub('(?:[/<>:"\\|\\\\?\\*]|[\s.]$)', '#', path_part)
  424. for path_part in norm_path]
  425. if drive_or_unc:
  426. sanitized_path.insert(0, drive_or_unc + os.path.sep)
  427. return os.path.join(*sanitized_path)
  428. # Prepend protocol-less URLs with `http:` scheme in order to mitigate the number of
  429. # unwanted failures due to missing protocol
  430. def sanitize_url(url):
  431. return 'http:%s' % url if url.startswith('//') else url
  432. def sanitized_Request(url, *args, **kwargs):
  433. return compat_urllib_request.Request(sanitize_url(url), *args, **kwargs)
  434. def orderedSet(iterable):
  435. """ Remove all duplicates from the input iterable """
  436. res = []
  437. for el in iterable:
  438. if el not in res:
  439. res.append(el)
  440. return res
  441. def _htmlentity_transform(entity_with_semicolon):
  442. """Transforms an HTML entity to a character."""
  443. entity = entity_with_semicolon[:-1]
  444. # Known non-numeric HTML entity
  445. if entity in compat_html_entities.name2codepoint:
  446. return compat_chr(compat_html_entities.name2codepoint[entity])
  447. # TODO: HTML5 allows entities without a semicolon. For example,
  448. # '&Eacuteric' should be decoded as 'Éric'.
  449. if entity_with_semicolon in compat_html_entities_html5:
  450. return compat_html_entities_html5[entity_with_semicolon]
  451. mobj = re.match(r'#(x[0-9a-fA-F]+|[0-9]+)', entity)
  452. if mobj is not None:
  453. numstr = mobj.group(1)
  454. if numstr.startswith('x'):
  455. base = 16
  456. numstr = '0%s' % numstr
  457. else:
  458. base = 10
  459. # See https://github.com/rg3/youtube-dl/issues/7518
  460. try:
  461. return compat_chr(int(numstr, base))
  462. except ValueError:
  463. pass
  464. # Unknown entity in name, return its literal representation
  465. return '&%s;' % entity
  466. def unescapeHTML(s):
  467. if s is None:
  468. return None
  469. assert type(s) == compat_str
  470. return re.sub(
  471. r'&([^;]+;)', lambda m: _htmlentity_transform(m.group(1)), s)
  472. def get_subprocess_encoding():
  473. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  474. # For subprocess calls, encode with locale encoding
  475. # Refer to http://stackoverflow.com/a/9951851/35070
  476. encoding = preferredencoding()
  477. else:
  478. encoding = sys.getfilesystemencoding()
  479. if encoding is None:
  480. encoding = 'utf-8'
  481. return encoding
  482. def encodeFilename(s, for_subprocess=False):
  483. """
  484. @param s The name of the file
  485. """
  486. assert type(s) == compat_str
  487. # Python 3 has a Unicode API
  488. if sys.version_info >= (3, 0):
  489. return s
  490. # Pass '' directly to use Unicode APIs on Windows 2000 and up
  491. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  492. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  493. if not for_subprocess and sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  494. return s
  495. # Jython assumes filenames are Unicode strings though reported as Python 2.x compatible
  496. if sys.platform.startswith('java'):
  497. return s
  498. return s.encode(get_subprocess_encoding(), 'ignore')
  499. def decodeFilename(b, for_subprocess=False):
  500. if sys.version_info >= (3, 0):
  501. return b
  502. if not isinstance(b, bytes):
  503. return b
  504. return b.decode(get_subprocess_encoding(), 'ignore')
  505. def encodeArgument(s):
  506. if not isinstance(s, compat_str):
  507. # Legacy code that uses byte strings
  508. # Uncomment the following line after fixing all post processors
  509. # assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
  510. s = s.decode('ascii')
  511. return encodeFilename(s, True)
  512. def decodeArgument(b):
  513. return decodeFilename(b, True)
  514. def decodeOption(optval):
  515. if optval is None:
  516. return optval
  517. if isinstance(optval, bytes):
  518. optval = optval.decode(preferredencoding())
  519. assert isinstance(optval, compat_str)
  520. return optval
  521. def formatSeconds(secs):
  522. if secs > 3600:
  523. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  524. elif secs > 60:
  525. return '%d:%02d' % (secs // 60, secs % 60)
  526. else:
  527. return '%d' % secs
  528. def make_HTTPS_handler(params, **kwargs):
  529. opts_no_check_certificate = params.get('nocheckcertificate', False)
  530. if hasattr(ssl, 'create_default_context'): # Python >= 3.4 or 2.7.9
  531. context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  532. if opts_no_check_certificate:
  533. context.check_hostname = False
  534. context.verify_mode = ssl.CERT_NONE
  535. try:
  536. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  537. except TypeError:
  538. # Python 2.7.8
  539. # (create_default_context present but HTTPSHandler has no context=)
  540. pass
  541. if sys.version_info < (3, 2):
  542. return YoutubeDLHTTPSHandler(params, **kwargs)
  543. else: # Python < 3.4
  544. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  545. context.verify_mode = (ssl.CERT_NONE
  546. if opts_no_check_certificate
  547. else ssl.CERT_REQUIRED)
  548. context.set_default_verify_paths()
  549. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  550. def bug_reports_message():
  551. if ytdl_is_updateable():
  552. update_cmd = 'type youtube-dl -U to update'
  553. else:
  554. update_cmd = 'see https://yt-dl.org/update on how to update'
  555. msg = '; please report this issue on https://yt-dl.org/bug .'
  556. msg += ' Make sure you are using the latest version; %s.' % update_cmd
  557. msg += ' Be sure to call youtube-dl with the --verbose flag and include its complete output.'
  558. return msg
  559. class ExtractorError(Exception):
  560. """Error during info extraction."""
  561. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  562. """ tb, if given, is the original traceback (so that it can be printed out).
  563. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  564. """
  565. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  566. expected = True
  567. if video_id is not None:
  568. msg = video_id + ': ' + msg
  569. if cause:
  570. msg += ' (caused by %r)' % cause
  571. if not expected:
  572. msg += bug_reports_message()
  573. super(ExtractorError, self).__init__(msg)
  574. self.traceback = tb
  575. self.exc_info = sys.exc_info() # preserve original exception
  576. self.cause = cause
  577. self.video_id = video_id
  578. def format_traceback(self):
  579. if self.traceback is None:
  580. return None
  581. return ''.join(traceback.format_tb(self.traceback))
  582. class UnsupportedError(ExtractorError):
  583. def __init__(self, url):
  584. super(UnsupportedError, self).__init__(
  585. 'Unsupported URL: %s' % url, expected=True)
  586. self.url = url
  587. class RegexNotFoundError(ExtractorError):
  588. """Error when a regex didn't match"""
  589. pass
  590. class DownloadError(Exception):
  591. """Download Error exception.
  592. This exception may be thrown by FileDownloader objects if they are not
  593. configured to continue on errors. They will contain the appropriate
  594. error message.
  595. """
  596. def __init__(self, msg, exc_info=None):
  597. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  598. super(DownloadError, self).__init__(msg)
  599. self.exc_info = exc_info
  600. class SameFileError(Exception):
  601. """Same File exception.
  602. This exception will be thrown by FileDownloader objects if they detect
  603. multiple files would have to be downloaded to the same file on disk.
  604. """
  605. pass
  606. class PostProcessingError(Exception):
  607. """Post Processing exception.
  608. This exception may be raised by PostProcessor's .run() method to
  609. indicate an error in the postprocessing task.
  610. """
  611. def __init__(self, msg):
  612. self.msg = msg
  613. class MaxDownloadsReached(Exception):
  614. """ --max-downloads limit has been reached. """
  615. pass
  616. class UnavailableVideoError(Exception):
  617. """Unavailable Format exception.
  618. This exception will be thrown when a video is requested
  619. in a format that is not available for that video.
  620. """
  621. pass
  622. class ContentTooShortError(Exception):
  623. """Content Too Short exception.
  624. This exception may be raised by FileDownloader objects when a file they
  625. download is too small for what the server announced first, indicating
  626. the connection was probably interrupted.
  627. """
  628. def __init__(self, downloaded, expected):
  629. # Both in bytes
  630. self.downloaded = downloaded
  631. self.expected = expected
  632. class XAttrMetadataError(Exception):
  633. def __init__(self, code=None, msg='Unknown error'):
  634. super(XAttrMetadataError, self).__init__(msg)
  635. self.code = code
  636. # Parsing code and msg
  637. if (self.code in (errno.ENOSPC, errno.EDQUOT) or
  638. 'No space left' in self.msg or 'Disk quota excedded' in self.msg):
  639. self.reason = 'NO_SPACE'
  640. elif self.code == errno.E2BIG or 'Argument list too long' in self.msg:
  641. self.reason = 'VALUE_TOO_LONG'
  642. else:
  643. self.reason = 'NOT_SUPPORTED'
  644. class XAttrUnavailableError(Exception):
  645. pass
  646. def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
  647. # Working around python 2 bug (see http://bugs.python.org/issue17849) by limiting
  648. # expected HTTP responses to meet HTTP/1.0 or later (see also
  649. # https://github.com/rg3/youtube-dl/issues/6727)
  650. if sys.version_info < (3, 0):
  651. kwargs[b'strict'] = True
  652. hc = http_class(*args, **kwargs)
  653. source_address = ydl_handler._params.get('source_address')
  654. if source_address is not None:
  655. sa = (source_address, 0)
  656. if hasattr(hc, 'source_address'): # Python 2.7+
  657. hc.source_address = sa
  658. else: # Python 2.6
  659. def _hc_connect(self, *args, **kwargs):
  660. sock = compat_socket_create_connection(
  661. (self.host, self.port), self.timeout, sa)
  662. if is_https:
  663. self.sock = ssl.wrap_socket(
  664. sock, self.key_file, self.cert_file,
  665. ssl_version=ssl.PROTOCOL_TLSv1)
  666. else:
  667. self.sock = sock
  668. hc.connect = functools.partial(_hc_connect, hc)
  669. return hc
  670. def handle_youtubedl_headers(headers):
  671. filtered_headers = headers
  672. if 'Youtubedl-no-compression' in filtered_headers:
  673. filtered_headers = dict((k, v) for k, v in filtered_headers.items() if k.lower() != 'accept-encoding')
  674. del filtered_headers['Youtubedl-no-compression']
  675. return filtered_headers
  676. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  677. """Handler for HTTP requests and responses.
  678. This class, when installed with an OpenerDirector, automatically adds
  679. the standard headers to every HTTP request and handles gzipped and
  680. deflated responses from web servers. If compression is to be avoided in
  681. a particular request, the original request in the program code only has
  682. to include the HTTP header "Youtubedl-no-compression", which will be
  683. removed before making the real request.
  684. Part of this code was copied from:
  685. http://techknack.net/python-urllib2-handlers/
  686. Andrew Rowls, the author of that code, agreed to release it to the
  687. public domain.
  688. """
  689. def __init__(self, params, *args, **kwargs):
  690. compat_urllib_request.HTTPHandler.__init__(self, *args, **kwargs)
  691. self._params = params
  692. def http_open(self, req):
  693. conn_class = compat_http_client.HTTPConnection
  694. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  695. if socks_proxy:
  696. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  697. del req.headers['Ytdl-socks-proxy']
  698. return self.do_open(functools.partial(
  699. _create_http_connection, self, conn_class, False),
  700. req)
  701. @staticmethod
  702. def deflate(data):
  703. try:
  704. return zlib.decompress(data, -zlib.MAX_WBITS)
  705. except zlib.error:
  706. return zlib.decompress(data)
  707. @staticmethod
  708. def addinfourl_wrapper(stream, headers, url, code):
  709. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  710. return compat_urllib_request.addinfourl(stream, headers, url, code)
  711. ret = compat_urllib_request.addinfourl(stream, headers, url)
  712. ret.code = code
  713. return ret
  714. def http_request(self, req):
  715. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  716. # always respected by websites, some tend to give out URLs with non percent-encoded
  717. # non-ASCII characters (see telemb.py, ard.py [#3412])
  718. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  719. # To work around aforementioned issue we will replace request's original URL with
  720. # percent-encoded one
  721. # Since redirects are also affected (e.g. http://www.southpark.de/alle-episoden/s18e09)
  722. # the code of this workaround has been moved here from YoutubeDL.urlopen()
  723. url = req.get_full_url()
  724. url_escaped = escape_url(url)
  725. # Substitute URL if any change after escaping
  726. if url != url_escaped:
  727. req = update_Request(req, url=url_escaped)
  728. for h, v in std_headers.items():
  729. # Capitalize is needed because of Python bug 2275: http://bugs.python.org/issue2275
  730. # The dict keys are capitalized because of this bug by urllib
  731. if h.capitalize() not in req.headers:
  732. req.add_header(h, v)
  733. req.headers = handle_youtubedl_headers(req.headers)
  734. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  735. # Python 2.6 is brain-dead when it comes to fragments
  736. req._Request__original = req._Request__original.partition('#')[0]
  737. req._Request__r_type = req._Request__r_type.partition('#')[0]
  738. return req
  739. def http_response(self, req, resp):
  740. old_resp = resp
  741. # gzip
  742. if resp.headers.get('Content-encoding', '') == 'gzip':
  743. content = resp.read()
  744. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  745. try:
  746. uncompressed = io.BytesIO(gz.read())
  747. except IOError as original_ioerror:
  748. # There may be junk add the end of the file
  749. # See http://stackoverflow.com/q/4928560/35070 for details
  750. for i in range(1, 1024):
  751. try:
  752. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  753. uncompressed = io.BytesIO(gz.read())
  754. except IOError:
  755. continue
  756. break
  757. else:
  758. raise original_ioerror
  759. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  760. resp.msg = old_resp.msg
  761. del resp.headers['Content-encoding']
  762. # deflate
  763. if resp.headers.get('Content-encoding', '') == 'deflate':
  764. gz = io.BytesIO(self.deflate(resp.read()))
  765. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  766. resp.msg = old_resp.msg
  767. del resp.headers['Content-encoding']
  768. # Percent-encode redirect URL of Location HTTP header to satisfy RFC 3986 (see
  769. # https://github.com/rg3/youtube-dl/issues/6457).
  770. if 300 <= resp.code < 400:
  771. location = resp.headers.get('Location')
  772. if location:
  773. # As of RFC 2616 default charset is iso-8859-1 that is respected by python 3
  774. if sys.version_info >= (3, 0):
  775. location = location.encode('iso-8859-1').decode('utf-8')
  776. else:
  777. location = location.decode('utf-8')
  778. location_escaped = escape_url(location)
  779. if location != location_escaped:
  780. del resp.headers['Location']
  781. if sys.version_info < (3, 0):
  782. location_escaped = location_escaped.encode('utf-8')
  783. resp.headers['Location'] = location_escaped
  784. return resp
  785. https_request = http_request
  786. https_response = http_response
  787. def make_socks_conn_class(base_class, socks_proxy):
  788. assert issubclass(base_class, (
  789. compat_http_client.HTTPConnection, compat_http_client.HTTPSConnection))
  790. url_components = compat_urlparse.urlparse(socks_proxy)
  791. if url_components.scheme.lower() == 'socks5':
  792. socks_type = ProxyType.SOCKS5
  793. elif url_components.scheme.lower() in ('socks', 'socks4'):
  794. socks_type = ProxyType.SOCKS4
  795. elif url_components.scheme.lower() == 'socks4a':
  796. socks_type = ProxyType.SOCKS4A
  797. def unquote_if_non_empty(s):
  798. if not s:
  799. return s
  800. return compat_urllib_parse_unquote_plus(s)
  801. proxy_args = (
  802. socks_type,
  803. url_components.hostname, url_components.port or 1080,
  804. True, # Remote DNS
  805. unquote_if_non_empty(url_components.username),
  806. unquote_if_non_empty(url_components.password),
  807. )
  808. class SocksConnection(base_class):
  809. def connect(self):
  810. self.sock = sockssocket()
  811. self.sock.setproxy(*proxy_args)
  812. if type(self.timeout) in (int, float):
  813. self.sock.settimeout(self.timeout)
  814. self.sock.connect((self.host, self.port))
  815. if isinstance(self, compat_http_client.HTTPSConnection):
  816. if hasattr(self, '_context'): # Python > 2.6
  817. self.sock = self._context.wrap_socket(
  818. self.sock, server_hostname=self.host)
  819. else:
  820. self.sock = ssl.wrap_socket(self.sock)
  821. return SocksConnection
  822. class YoutubeDLHTTPSHandler(compat_urllib_request.HTTPSHandler):
  823. def __init__(self, params, https_conn_class=None, *args, **kwargs):
  824. compat_urllib_request.HTTPSHandler.__init__(self, *args, **kwargs)
  825. self._https_conn_class = https_conn_class or compat_http_client.HTTPSConnection
  826. self._params = params
  827. def https_open(self, req):
  828. kwargs = {}
  829. conn_class = self._https_conn_class
  830. if hasattr(self, '_context'): # python > 2.6
  831. kwargs['context'] = self._context
  832. if hasattr(self, '_check_hostname'): # python 3.x
  833. kwargs['check_hostname'] = self._check_hostname
  834. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  835. if socks_proxy:
  836. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  837. del req.headers['Ytdl-socks-proxy']
  838. return self.do_open(functools.partial(
  839. _create_http_connection, self, conn_class, True),
  840. req, **kwargs)
  841. class YoutubeDLCookieProcessor(compat_urllib_request.HTTPCookieProcessor):
  842. def __init__(self, cookiejar=None):
  843. compat_urllib_request.HTTPCookieProcessor.__init__(self, cookiejar)
  844. def http_response(self, request, response):
  845. # Python 2 will choke on next HTTP request in row if there are non-ASCII
  846. # characters in Set-Cookie HTTP header of last response (see
  847. # https://github.com/rg3/youtube-dl/issues/6769).
  848. # In order to at least prevent crashing we will percent encode Set-Cookie
  849. # header before HTTPCookieProcessor starts processing it.
  850. # if sys.version_info < (3, 0) and response.headers:
  851. # for set_cookie_header in ('Set-Cookie', 'Set-Cookie2'):
  852. # set_cookie = response.headers.get(set_cookie_header)
  853. # if set_cookie:
  854. # set_cookie_escaped = compat_urllib_parse.quote(set_cookie, b"%/;:@&=+$,!~*'()?#[] ")
  855. # if set_cookie != set_cookie_escaped:
  856. # del response.headers[set_cookie_header]
  857. # response.headers[set_cookie_header] = set_cookie_escaped
  858. return compat_urllib_request.HTTPCookieProcessor.http_response(self, request, response)
  859. https_request = compat_urllib_request.HTTPCookieProcessor.http_request
  860. https_response = http_response
  861. def extract_timezone(date_str):
  862. m = re.search(
  863. r'^.{8,}?(?P<tz>Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  864. date_str)
  865. if not m:
  866. timezone = datetime.timedelta()
  867. else:
  868. date_str = date_str[:-len(m.group('tz'))]
  869. if not m.group('sign'):
  870. timezone = datetime.timedelta()
  871. else:
  872. sign = 1 if m.group('sign') == '+' else -1
  873. timezone = datetime.timedelta(
  874. hours=sign * int(m.group('hours')),
  875. minutes=sign * int(m.group('minutes')))
  876. return timezone, date_str
  877. def parse_iso8601(date_str, delimiter='T', timezone=None):
  878. """ Return a UNIX timestamp from the given date """
  879. if date_str is None:
  880. return None
  881. date_str = re.sub(r'\.[0-9]+', '', date_str)
  882. if timezone is None:
  883. timezone, date_str = extract_timezone(date_str)
  884. try:
  885. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  886. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  887. return calendar.timegm(dt.timetuple())
  888. except ValueError:
  889. pass
  890. def date_formats(day_first=True):
  891. return DATE_FORMATS_DAY_FIRST if day_first else DATE_FORMATS_MONTH_FIRST
  892. def unified_strdate(date_str, day_first=True):
  893. """Return a string with the date in the format YYYYMMDD"""
  894. if date_str is None:
  895. return None
  896. upload_date = None
  897. # Replace commas
  898. date_str = date_str.replace(',', ' ')
  899. # Remove AM/PM + timezone
  900. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  901. _, date_str = extract_timezone(date_str)
  902. for expression in date_formats(day_first):
  903. try:
  904. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  905. except ValueError:
  906. pass
  907. if upload_date is None:
  908. timetuple = email.utils.parsedate_tz(date_str)
  909. if timetuple:
  910. try:
  911. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  912. except ValueError:
  913. pass
  914. if upload_date is not None:
  915. return compat_str(upload_date)
  916. def unified_timestamp(date_str, day_first=True):
  917. if date_str is None:
  918. return None
  919. date_str = date_str.replace(',', ' ')
  920. pm_delta = 12 if re.search(r'(?i)PM', date_str) else 0
  921. timezone, date_str = extract_timezone(date_str)
  922. # Remove AM/PM + timezone
  923. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  924. for expression in date_formats(day_first):
  925. try:
  926. dt = datetime.datetime.strptime(date_str, expression) - timezone + datetime.timedelta(hours=pm_delta)
  927. return calendar.timegm(dt.timetuple())
  928. except ValueError:
  929. pass
  930. timetuple = email.utils.parsedate_tz(date_str)
  931. if timetuple:
  932. return calendar.timegm(timetuple) + pm_delta * 3600
  933. def determine_ext(url, default_ext='unknown_video'):
  934. if url is None:
  935. return default_ext
  936. guess = url.partition('?')[0].rpartition('.')[2]
  937. if re.match(r'^[A-Za-z0-9]+$', guess):
  938. return guess
  939. # Try extract ext from URLs like http://example.com/foo/bar.mp4/?download
  940. elif guess.rstrip('/') in KNOWN_EXTENSIONS:
  941. return guess.rstrip('/')
  942. else:
  943. return default_ext
  944. def subtitles_filename(filename, sub_lang, sub_format):
  945. return filename.rsplit('.', 1)[0] + '.' + sub_lang + '.' + sub_format
  946. def date_from_str(date_str):
  947. """
  948. Return a datetime object from a string in the format YYYYMMDD or
  949. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  950. today = datetime.date.today()
  951. if date_str in ('now', 'today'):
  952. return today
  953. if date_str == 'yesterday':
  954. return today - datetime.timedelta(days=1)
  955. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  956. if match is not None:
  957. sign = match.group('sign')
  958. time = int(match.group('time'))
  959. if sign == '-':
  960. time = -time
  961. unit = match.group('unit')
  962. # A bad approximation?
  963. if unit == 'month':
  964. unit = 'day'
  965. time *= 30
  966. elif unit == 'year':
  967. unit = 'day'
  968. time *= 365
  969. unit += 's'
  970. delta = datetime.timedelta(**{unit: time})
  971. return today + delta
  972. return datetime.datetime.strptime(date_str, '%Y%m%d').date()
  973. def hyphenate_date(date_str):
  974. """
  975. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  976. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  977. if match is not None:
  978. return '-'.join(match.groups())
  979. else:
  980. return date_str
  981. class DateRange(object):
  982. """Represents a time interval between two dates"""
  983. def __init__(self, start=None, end=None):
  984. """start and end must be strings in the format accepted by date"""
  985. if start is not None:
  986. self.start = date_from_str(start)
  987. else:
  988. self.start = datetime.datetime.min.date()
  989. if end is not None:
  990. self.end = date_from_str(end)
  991. else:
  992. self.end = datetime.datetime.max.date()
  993. if self.start > self.end:
  994. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  995. @classmethod
  996. def day(cls, day):
  997. """Returns a range that only contains the given day"""
  998. return cls(day, day)
  999. def __contains__(self, date):
  1000. """Check if the date is in the range"""
  1001. if not isinstance(date, datetime.date):
  1002. date = date_from_str(date)
  1003. return self.start <= date <= self.end
  1004. def __str__(self):
  1005. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  1006. def platform_name():
  1007. """ Returns the platform name as a compat_str """
  1008. res = platform.platform()
  1009. if isinstance(res, bytes):
  1010. res = res.decode(preferredencoding())
  1011. assert isinstance(res, compat_str)
  1012. return res
  1013. def _windows_write_string(s, out):
  1014. """ Returns True if the string was written using special methods,
  1015. False if it has yet to be written out."""
  1016. # Adapted from http://stackoverflow.com/a/3259271/35070
  1017. import ctypes
  1018. import ctypes.wintypes
  1019. WIN_OUTPUT_IDS = {
  1020. 1: -11,
  1021. 2: -12,
  1022. }
  1023. try:
  1024. fileno = out.fileno()
  1025. except AttributeError:
  1026. # If the output stream doesn't have a fileno, it's virtual
  1027. return False
  1028. except io.UnsupportedOperation:
  1029. # Some strange Windows pseudo files?
  1030. return False
  1031. if fileno not in WIN_OUTPUT_IDS:
  1032. return False
  1033. GetStdHandle = ctypes.WINFUNCTYPE(
  1034. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  1035. (b'GetStdHandle', ctypes.windll.kernel32))
  1036. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  1037. WriteConsoleW = ctypes.WINFUNCTYPE(
  1038. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  1039. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  1040. ctypes.wintypes.LPVOID)((b'WriteConsoleW', ctypes.windll.kernel32))
  1041. written = ctypes.wintypes.DWORD(0)
  1042. GetFileType = ctypes.WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)((b'GetFileType', ctypes.windll.kernel32))
  1043. FILE_TYPE_CHAR = 0x0002
  1044. FILE_TYPE_REMOTE = 0x8000
  1045. GetConsoleMode = ctypes.WINFUNCTYPE(
  1046. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  1047. ctypes.POINTER(ctypes.wintypes.DWORD))(
  1048. (b'GetConsoleMode', ctypes.windll.kernel32))
  1049. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  1050. def not_a_console(handle):
  1051. if handle == INVALID_HANDLE_VALUE or handle is None:
  1052. return True
  1053. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR or
  1054. GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  1055. if not_a_console(h):
  1056. return False
  1057. def next_nonbmp_pos(s):
  1058. try:
  1059. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  1060. except StopIteration:
  1061. return len(s)
  1062. while s:
  1063. count = min(next_nonbmp_pos(s), 1024)
  1064. ret = WriteConsoleW(
  1065. h, s, count if count else 2, ctypes.byref(written), None)
  1066. if ret == 0:
  1067. raise OSError('Failed to write string')
  1068. if not count: # We just wrote a non-BMP character
  1069. assert written.value == 2
  1070. s = s[1:]
  1071. else:
  1072. assert written.value > 0
  1073. s = s[written.value:]
  1074. return True
  1075. def write_string(s, out=None, encoding=None):
  1076. if out is None:
  1077. out = sys.stderr
  1078. assert type(s) == compat_str
  1079. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  1080. if _windows_write_string(s, out):
  1081. return
  1082. if ('b' in getattr(out, 'mode', '') or
  1083. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  1084. byt = s.encode(encoding or preferredencoding(), 'ignore')
  1085. out.write(byt)
  1086. elif hasattr(out, 'buffer'):
  1087. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  1088. byt = s.encode(enc, 'ignore')
  1089. out.buffer.write(byt)
  1090. else:
  1091. out.write(s)
  1092. out.flush()
  1093. def bytes_to_intlist(bs):
  1094. if not bs:
  1095. return []
  1096. if isinstance(bs[0], int): # Python 3
  1097. return list(bs)
  1098. else:
  1099. return [ord(c) for c in bs]
  1100. def intlist_to_bytes(xs):
  1101. if not xs:
  1102. return b''
  1103. return compat_struct_pack('%dB' % len(xs), *xs)
  1104. # Cross-platform file locking
  1105. if sys.platform == 'win32':
  1106. import ctypes.wintypes
  1107. import msvcrt
  1108. class OVERLAPPED(ctypes.Structure):
  1109. _fields_ = [
  1110. ('Internal', ctypes.wintypes.LPVOID),
  1111. ('InternalHigh', ctypes.wintypes.LPVOID),
  1112. ('Offset', ctypes.wintypes.DWORD),
  1113. ('OffsetHigh', ctypes.wintypes.DWORD),
  1114. ('hEvent', ctypes.wintypes.HANDLE),
  1115. ]
  1116. kernel32 = ctypes.windll.kernel32
  1117. LockFileEx = kernel32.LockFileEx
  1118. LockFileEx.argtypes = [
  1119. ctypes.wintypes.HANDLE, # hFile
  1120. ctypes.wintypes.DWORD, # dwFlags
  1121. ctypes.wintypes.DWORD, # dwReserved
  1122. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  1123. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  1124. ctypes.POINTER(OVERLAPPED) # Overlapped
  1125. ]
  1126. LockFileEx.restype = ctypes.wintypes.BOOL
  1127. UnlockFileEx = kernel32.UnlockFileEx
  1128. UnlockFileEx.argtypes = [
  1129. ctypes.wintypes.HANDLE, # hFile
  1130. ctypes.wintypes.DWORD, # dwReserved
  1131. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  1132. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  1133. ctypes.POINTER(OVERLAPPED) # Overlapped
  1134. ]
  1135. UnlockFileEx.restype = ctypes.wintypes.BOOL
  1136. whole_low = 0xffffffff
  1137. whole_high = 0x7fffffff
  1138. def _lock_file(f, exclusive):
  1139. overlapped = OVERLAPPED()
  1140. overlapped.Offset = 0
  1141. overlapped.OffsetHigh = 0
  1142. overlapped.hEvent = 0
  1143. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  1144. handle = msvcrt.get_osfhandle(f.fileno())
  1145. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  1146. whole_low, whole_high, f._lock_file_overlapped_p):
  1147. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  1148. def _unlock_file(f):
  1149. assert f._lock_file_overlapped_p
  1150. handle = msvcrt.get_osfhandle(f.fileno())
  1151. if not UnlockFileEx(handle, 0,
  1152. whole_low, whole_high, f._lock_file_overlapped_p):
  1153. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  1154. else:
  1155. # Some platforms, such as Jython, is missing fcntl
  1156. try:
  1157. import fcntl
  1158. def _lock_file(f, exclusive):
  1159. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  1160. def _unlock_file(f):
  1161. fcntl.flock(f, fcntl.LOCK_UN)
  1162. except ImportError:
  1163. UNSUPPORTED_MSG = 'file locking is not supported on this platform'
  1164. def _lock_file(f, exclusive):
  1165. raise IOError(UNSUPPORTED_MSG)
  1166. def _unlock_file(f):
  1167. raise IOError(UNSUPPORTED_MSG)
  1168. class locked_file(object):
  1169. def __init__(self, filename, mode, encoding=None):
  1170. assert mode in ['r', 'a', 'w']
  1171. self.f = io.open(filename, mode, encoding=encoding)
  1172. self.mode = mode
  1173. def __enter__(self):
  1174. exclusive = self.mode != 'r'
  1175. try:
  1176. _lock_file(self.f, exclusive)
  1177. except IOError:
  1178. self.f.close()
  1179. raise
  1180. return self
  1181. def __exit__(self, etype, value, traceback):
  1182. try:
  1183. _unlock_file(self.f)
  1184. finally:
  1185. self.f.close()
  1186. def __iter__(self):
  1187. return iter(self.f)
  1188. def write(self, *args):
  1189. return self.f.write(*args)
  1190. def read(self, *args):
  1191. return self.f.read(*args)
  1192. def get_filesystem_encoding():
  1193. encoding = sys.getfilesystemencoding()
  1194. return encoding if encoding is not None else 'utf-8'
  1195. def shell_quote(args):
  1196. quoted_args = []
  1197. encoding = get_filesystem_encoding()
  1198. for a in args:
  1199. if isinstance(a, bytes):
  1200. # We may get a filename encoded with 'encodeFilename'
  1201. a = a.decode(encoding)
  1202. quoted_args.append(pipes.quote(a))
  1203. return ' '.join(quoted_args)
  1204. def smuggle_url(url, data):
  1205. """ Pass additional data in a URL for internal use. """
  1206. url, idata = unsmuggle_url(url, {})
  1207. data.update(idata)
  1208. sdata = compat_urllib_parse_urlencode(
  1209. {'__youtubedl_smuggle': json.dumps(data)})
  1210. return url + '#' + sdata
  1211. def unsmuggle_url(smug_url, default=None):
  1212. if '#__youtubedl_smuggle' not in smug_url:
  1213. return smug_url, default
  1214. url, _, sdata = smug_url.rpartition('#')
  1215. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  1216. data = json.loads(jsond)
  1217. return url, data
  1218. def format_bytes(bytes):
  1219. if bytes is None:
  1220. return 'N/A'
  1221. if type(bytes) is str:
  1222. bytes = float(bytes)
  1223. if bytes == 0.0:
  1224. exponent = 0
  1225. else:
  1226. exponent = int(math.log(bytes, 1024.0))
  1227. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  1228. converted = float(bytes) / float(1024 ** exponent)
  1229. return '%.2f%s' % (converted, suffix)
  1230. def lookup_unit_table(unit_table, s):
  1231. units_re = '|'.join(re.escape(u) for u in unit_table)
  1232. m = re.match(
  1233. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)\b' % units_re, s)
  1234. if not m:
  1235. return None
  1236. num_str = m.group('num').replace(',', '.')
  1237. mult = unit_table[m.group('unit')]
  1238. return int(float(num_str) * mult)
  1239. def parse_filesize(s):
  1240. if s is None:
  1241. return None
  1242. # The lower-case forms are of course incorrect and unofficial,
  1243. # but we support those too
  1244. _UNIT_TABLE = {
  1245. 'B': 1,
  1246. 'b': 1,
  1247. 'bytes': 1,
  1248. 'KiB': 1024,
  1249. 'KB': 1000,
  1250. 'kB':