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.

1241 lines
39 KiB

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import ctypes
  4. import datetime
  5. import email.utils
  6. import errno
  7. import gzip
  8. import itertools
  9. import io
  10. import json
  11. import locale
  12. import math
  13. import os
  14. import pipes
  15. import platform
  16. import re
  17. import ssl
  18. import socket
  19. import struct
  20. import subprocess
  21. import sys
  22. import traceback
  23. import zlib
  24. try:
  25. import urllib.request as compat_urllib_request
  26. except ImportError: # Python 2
  27. import urllib2 as compat_urllib_request
  28. try:
  29. import urllib.error as compat_urllib_error
  30. except ImportError: # Python 2
  31. import urllib2 as compat_urllib_error
  32. try:
  33. import urllib.parse as compat_urllib_parse
  34. except ImportError: # Python 2
  35. import urllib as compat_urllib_parse
  36. try:
  37. from urllib.parse import urlparse as compat_urllib_parse_urlparse
  38. except ImportError: # Python 2
  39. from urlparse import urlparse as compat_urllib_parse_urlparse
  40. try:
  41. import urllib.parse as compat_urlparse
  42. except ImportError: # Python 2
  43. import urlparse as compat_urlparse
  44. try:
  45. import http.cookiejar as compat_cookiejar
  46. except ImportError: # Python 2
  47. import cookielib as compat_cookiejar
  48. try:
  49. import html.entities as compat_html_entities
  50. except ImportError: # Python 2
  51. import htmlentitydefs as compat_html_entities
  52. try:
  53. import html.parser as compat_html_parser
  54. except ImportError: # Python 2
  55. import HTMLParser as compat_html_parser
  56. try:
  57. import http.client as compat_http_client
  58. except ImportError: # Python 2
  59. import httplib as compat_http_client
  60. try:
  61. from urllib.error import HTTPError as compat_HTTPError
  62. except ImportError: # Python 2
  63. from urllib2 import HTTPError as compat_HTTPError
  64. try:
  65. from urllib.request import urlretrieve as compat_urlretrieve
  66. except ImportError: # Python 2
  67. from urllib import urlretrieve as compat_urlretrieve
  68. try:
  69. from subprocess import DEVNULL
  70. compat_subprocess_get_DEVNULL = lambda: DEVNULL
  71. except ImportError:
  72. compat_subprocess_get_DEVNULL = lambda: open(os.path.devnull, 'w')
  73. try:
  74. from urllib.parse import parse_qs as compat_parse_qs
  75. except ImportError: # Python 2
  76. # HACK: The following is the correct parse_qs implementation from cpython 3's stdlib.
  77. # Python 2's version is apparently totally broken
  78. def _unquote(string, encoding='utf-8', errors='replace'):
  79. if string == '':
  80. return string
  81. res = string.split('%')
  82. if len(res) == 1:
  83. return string
  84. if encoding is None:
  85. encoding = 'utf-8'
  86. if errors is None:
  87. errors = 'replace'
  88. # pct_sequence: contiguous sequence of percent-encoded bytes, decoded
  89. pct_sequence = b''
  90. string = res[0]
  91. for item in res[1:]:
  92. try:
  93. if not item:
  94. raise ValueError
  95. pct_sequence += item[:2].decode('hex')
  96. rest = item[2:]
  97. if not rest:
  98. # This segment was just a single percent-encoded character.
  99. # May be part of a sequence of code units, so delay decoding.
  100. # (Stored in pct_sequence).
  101. continue
  102. except ValueError:
  103. rest = '%' + item
  104. # Encountered non-percent-encoded characters. Flush the current
  105. # pct_sequence.
  106. string += pct_sequence.decode(encoding, errors) + rest
  107. pct_sequence = b''
  108. if pct_sequence:
  109. # Flush the final pct_sequence
  110. string += pct_sequence.decode(encoding, errors)
  111. return string
  112. def _parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
  113. encoding='utf-8', errors='replace'):
  114. qs, _coerce_result = qs, unicode
  115. pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
  116. r = []
  117. for name_value in pairs:
  118. if not name_value and not strict_parsing:
  119. continue
  120. nv = name_value.split('=', 1)
  121. if len(nv) != 2:
  122. if strict_parsing:
  123. raise ValueError("bad query field: %r" % (name_value,))
  124. # Handle case of a control-name with no equal sign
  125. if keep_blank_values:
  126. nv.append('')
  127. else:
  128. continue
  129. if len(nv[1]) or keep_blank_values:
  130. name = nv[0].replace('+', ' ')
  131. name = _unquote(name, encoding=encoding, errors=errors)
  132. name = _coerce_result(name)
  133. value = nv[1].replace('+', ' ')
  134. value = _unquote(value, encoding=encoding, errors=errors)
  135. value = _coerce_result(value)
  136. r.append((name, value))
  137. return r
  138. def compat_parse_qs(qs, keep_blank_values=False, strict_parsing=False,
  139. encoding='utf-8', errors='replace'):
  140. parsed_result = {}
  141. pairs = _parse_qsl(qs, keep_blank_values, strict_parsing,
  142. encoding=encoding, errors=errors)
  143. for name, value in pairs:
  144. if name in parsed_result:
  145. parsed_result[name].append(value)
  146. else:
  147. parsed_result[name] = [value]
  148. return parsed_result
  149. try:
  150. compat_str = unicode # Python 2
  151. except NameError:
  152. compat_str = str
  153. try:
  154. compat_chr = unichr # Python 2
  155. except NameError:
  156. compat_chr = chr
  157. def compat_ord(c):
  158. if type(c) is int: return c
  159. else: return ord(c)
  160. # This is not clearly defined otherwise
  161. compiled_regex_type = type(re.compile(''))
  162. std_headers = {
  163. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0 (Chrome)',
  164. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  165. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  166. 'Accept-Encoding': 'gzip, deflate',
  167. 'Accept-Language': 'en-us,en;q=0.5',
  168. }
  169. def preferredencoding():
  170. """Get preferred encoding.
  171. Returns the best encoding scheme for the system, based on
  172. locale.getpreferredencoding() and some further tweaks.
  173. """
  174. try:
  175. pref = locale.getpreferredencoding()
  176. u'TEST'.encode(pref)
  177. except:
  178. pref = 'UTF-8'
  179. return pref
  180. if sys.version_info < (3,0):
  181. def compat_print(s):
  182. print(s.encode(preferredencoding(), 'xmlcharrefreplace'))
  183. else:
  184. def compat_print(s):
  185. assert type(s) == type(u'')
  186. print(s)
  187. # In Python 2.x, json.dump expects a bytestream.
  188. # In Python 3.x, it writes to a character stream
  189. if sys.version_info < (3,0):
  190. def write_json_file(obj, fn):
  191. with open(fn, 'wb') as f:
  192. json.dump(obj, f)
  193. else:
  194. def write_json_file(obj, fn):
  195. with open(fn, 'w', encoding='utf-8') as f:
  196. json.dump(obj, f)
  197. if sys.version_info >= (2,7):
  198. def find_xpath_attr(node, xpath, key, val):
  199. """ Find the xpath xpath[@key=val] """
  200. assert re.match(r'^[a-zA-Z]+$', key)
  201. assert re.match(r'^[a-zA-Z0-9@\s:._]*$', val)
  202. expr = xpath + u"[@%s='%s']" % (key, val)
  203. return node.find(expr)
  204. else:
  205. def find_xpath_attr(node, xpath, key, val):
  206. for f in node.findall(xpath):
  207. if f.attrib.get(key) == val:
  208. return f
  209. return None
  210. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  211. # the namespace parameter
  212. def xpath_with_ns(path, ns_map):
  213. components = [c.split(':') for c in path.split('/')]
  214. replaced = []
  215. for c in components:
  216. if len(c) == 1:
  217. replaced.append(c[0])
  218. else:
  219. ns, tag = c
  220. replaced.append('{%s}%s' % (ns_map[ns], tag))
  221. return '/'.join(replaced)
  222. def htmlentity_transform(matchobj):
  223. """Transforms an HTML entity to a character.
  224. This function receives a match object and is intended to be used with
  225. the re.sub() function.
  226. """
  227. entity = matchobj.group(1)
  228. # Known non-numeric HTML entity
  229. if entity in compat_html_entities.name2codepoint:
  230. return compat_chr(compat_html_entities.name2codepoint[entity])
  231. mobj = re.match(u'(?u)#(x?\\d+)', entity)
  232. if mobj is not None:
  233. numstr = mobj.group(1)
  234. if numstr.startswith(u'x'):
  235. base = 16
  236. numstr = u'0%s' % numstr
  237. else:
  238. base = 10
  239. return compat_chr(int(numstr, base))
  240. # Unknown entity in name, return its literal representation
  241. return (u'&%s;' % entity)
  242. compat_html_parser.locatestarttagend = re.compile(r"""<[a-zA-Z][-.a-zA-Z0-9:_]*(?:\s+(?:(?<=['"\s])[^\s/>][^\s/=>]*(?:\s*=+\s*(?:'[^']*'|"[^"]*"|(?!['"])[^>\s]*))?\s*)*)?\s*""", re.VERBOSE) # backport bugfix
  243. class BaseHTMLParser(compat_html_parser.HTMLParser):
  244. def __init(self):
  245. compat_html_parser.HTMLParser.__init__(self)
  246. self.html = None
  247. def loads(self, html):
  248. self.html = html
  249. self.feed(html)
  250. self.close()
  251. class AttrParser(BaseHTMLParser):
  252. """Modified HTMLParser that isolates a tag with the specified attribute"""
  253. def __init__(self, attribute, value):
  254. self.attribute = attribute
  255. self.value = value
  256. self.result = None
  257. self.started = False
  258. self.depth = {}
  259. self.watch_startpos = False
  260. self.error_count = 0
  261. BaseHTMLParser.__init__(self)
  262. def error(self, message):
  263. if self.error_count > 10 or self.started:
  264. raise compat_html_parser.HTMLParseError(message, self.getpos())
  265. self.rawdata = '\n'.join(self.html.split('\n')[self.getpos()[0]:]) # skip one line
  266. self.error_count += 1
  267. self.goahead(1)
  268. def handle_starttag(self, tag, attrs):
  269. attrs = dict(attrs)
  270. if self.started:
  271. self.find_startpos(None)
  272. if self.attribute in attrs and attrs[self.attribute] == self.value:
  273. self.result = [tag]
  274. self.started = True
  275. self.watch_startpos = True
  276. if self.started:
  277. if not tag in self.depth: self.depth[tag] = 0
  278. self.depth[tag] += 1
  279. def handle_endtag(self, tag):
  280. if self.started:
  281. if tag in self.depth: self.depth[tag] -= 1
  282. if self.depth[self.result[0]] == 0:
  283. self.started = False
  284. self.result.append(self.getpos())
  285. def find_startpos(self, x):
  286. """Needed to put the start position of the result (self.result[1])
  287. after the opening tag with the requested id"""
  288. if self.watch_startpos:
  289. self.watch_startpos = False
  290. self.result.append(self.getpos())
  291. handle_entityref = handle_charref = handle_data = handle_comment = \
  292. handle_decl = handle_pi = unknown_decl = find_startpos
  293. def get_result(self):
  294. if self.result is None:
  295. return None
  296. if len(self.result) != 3:
  297. return None
  298. lines = self.html.split('\n')
  299. lines = lines[self.result[1][0]-1:self.result[2][0]]
  300. lines[0] = lines[0][self.result[1][1]:]
  301. if len(lines) == 1:
  302. lines[-1] = lines[-1][:self.result[2][1]-self.result[1][1]]
  303. lines[-1] = lines[-1][:self.result[2][1]]
  304. return '\n'.join(lines).strip()
  305. # Hack for https://github.com/rg3/youtube-dl/issues/662
  306. if sys.version_info < (2, 7, 3):
  307. AttrParser.parse_endtag = (lambda self, i:
  308. i + len("</scr'+'ipt>")
  309. if self.rawdata[i:].startswith("</scr'+'ipt>")
  310. else compat_html_parser.HTMLParser.parse_endtag(self, i))
  311. def get_element_by_id(id, html):
  312. """Return the content of the tag with the specified ID in the passed HTML document"""
  313. return get_element_by_attribute("id", id, html)
  314. def get_element_by_attribute(attribute, value, html):
  315. """Return the content of the tag with the specified attribute in the passed HTML document"""
  316. parser = AttrParser(attribute, value)
  317. try:
  318. parser.loads(html)
  319. except compat_html_parser.HTMLParseError:
  320. pass
  321. return parser.get_result()
  322. class MetaParser(BaseHTMLParser):
  323. """
  324. Modified HTMLParser that isolates a meta tag with the specified name
  325. attribute.
  326. """
  327. def __init__(self, name):
  328. BaseHTMLParser.__init__(self)
  329. self.name = name
  330. self.content = None
  331. self.result = None
  332. def handle_starttag(self, tag, attrs):
  333. if tag != 'meta':
  334. return
  335. attrs = dict(attrs)
  336. if attrs.get('name') == self.name:
  337. self.result = attrs.get('content')
  338. def get_result(self):
  339. return self.result
  340. def get_meta_content(name, html):
  341. """
  342. Return the content attribute from the meta tag with the given name attribute.
  343. """
  344. parser = MetaParser(name)
  345. try:
  346. parser.loads(html)
  347. except compat_html_parser.HTMLParseError:
  348. pass
  349. return parser.get_result()
  350. def clean_html(html):
  351. """Clean an HTML snippet into a readable string"""
  352. # Newline vs <br />
  353. html = html.replace('\n', ' ')
  354. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  355. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  356. # Strip html tags
  357. html = re.sub('<.*?>', '', html)
  358. # Replace html entities
  359. html = unescapeHTML(html)
  360. return html.strip()
  361. def sanitize_open(filename, open_mode):
  362. """Try to open the given filename, and slightly tweak it if this fails.
  363. Attempts to open the given filename. If this fails, it tries to change
  364. the filename slightly, step by step, until it's either able to open it
  365. or it fails and raises a final exception, like the standard open()
  366. function.
  367. It returns the tuple (stream, definitive_file_name).
  368. """
  369. try:
  370. if filename == u'-':
  371. if sys.platform == 'win32':
  372. import msvcrt
  373. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  374. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  375. stream = open(encodeFilename(filename), open_mode)
  376. return (stream, filename)
  377. except (IOError, OSError) as err:
  378. if err.errno in (errno.EACCES,):
  379. raise
  380. # In case of error, try to remove win32 forbidden chars
  381. alt_filename = os.path.join(
  382. re.sub(u'[/<>:"\\|\\\\?\\*]', u'#', path_part)
  383. for path_part in os.path.split(filename)
  384. )
  385. if alt_filename == filename:
  386. raise
  387. else:
  388. # An exception here should be caught in the caller
  389. stream = open(encodeFilename(filename), open_mode)
  390. return (stream, alt_filename)
  391. def timeconvert(timestr):
  392. """Convert RFC 2822 defined time string into system timestamp"""
  393. timestamp = None
  394. timetuple = email.utils.parsedate_tz(timestr)
  395. if timetuple is not None:
  396. timestamp = email.utils.mktime_tz(timetuple)
  397. return timestamp
  398. def sanitize_filename(s, restricted=False, is_id=False):
  399. """Sanitizes a string so it could be used as part of a filename.
  400. If restricted is set, use a stricter subset of allowed characters.
  401. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  402. """
  403. def replace_insane(char):
  404. if char == '?' or ord(char) < 32 or ord(char) == 127:
  405. return ''
  406. elif char == '"':
  407. return '' if restricted else '\''
  408. elif char == ':':
  409. return '_-' if restricted else ' -'
  410. elif char in '\\/|*<>':
  411. return '_'
  412. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  413. return '_'
  414. if restricted and ord(char) > 127:
  415. return '_'
  416. return char
  417. result = u''.join(map(replace_insane, s))
  418. if not is_id:
  419. while '__' in result:
  420. result = result.replace('__', '_')
  421. result = result.strip('_')
  422. # Common case of "Foreign band name - English song title"
  423. if restricted and result.startswith('-_'):
  424. result = result[2:]
  425. if not result:
  426. result = '_'
  427. return result
  428. def orderedSet(iterable):
  429. """ Remove all duplicates from the input iterable """
  430. res = []
  431. for el in iterable:
  432. if el not in res:
  433. res.append(el)
  434. return res
  435. def unescapeHTML(s):
  436. """
  437. @param s a string
  438. """
  439. assert type(s) == type(u'')
  440. result = re.sub(u'(?u)&(.+?);', htmlentity_transform, s)
  441. return result
  442. def encodeFilename(s, for_subprocess=False):
  443. """
  444. @param s The name of the file
  445. """
  446. assert type(s) == compat_str
  447. # Python 3 has a Unicode API
  448. if sys.version_info >= (3, 0):
  449. return s
  450. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  451. # Pass u'' directly to use Unicode APIs on Windows 2000 and up
  452. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  453. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  454. if not for_subprocess:
  455. return s
  456. else:
  457. # For subprocess calls, encode with locale encoding
  458. # Refer to http://stackoverflow.com/a/9951851/35070
  459. encoding = preferredencoding()
  460. else:
  461. encoding = sys.getfilesystemencoding()
  462. if encoding is None:
  463. encoding = 'utf-8'
  464. return s.encode(encoding, 'ignore')
  465. def decodeOption(optval):
  466. if optval is None:
  467. return optval
  468. if isinstance(optval, bytes):
  469. optval = optval.decode(preferredencoding())
  470. assert isinstance(optval, compat_str)
  471. return optval
  472. def formatSeconds(secs):
  473. if secs > 3600:
  474. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  475. elif secs > 60:
  476. return '%d:%02d' % (secs // 60, secs % 60)
  477. else:
  478. return '%d' % secs
  479. def make_HTTPS_handler(opts_no_check_certificate, **kwargs):
  480. if sys.version_info < (3, 2):
  481. import httplib
  482. class HTTPSConnectionV3(httplib.HTTPSConnection):
  483. def __init__(self, *args, **kwargs):
  484. httplib.HTTPSConnection.__init__(self, *args, **kwargs)
  485. def connect(self):
  486. sock = socket.create_connection((self.host, self.port), self.timeout)
  487. if getattr(self, '_tunnel_host', False):
  488. self.sock = sock
  489. self._tunnel()
  490. try:
  491. self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_SSLv3)
  492. except ssl.SSLError:
  493. self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_SSLv23)
  494. class HTTPSHandlerV3(compat_urllib_request.HTTPSHandler):
  495. def https_open(self, req):
  496. return self.do_open(HTTPSConnectionV3, req)
  497. return HTTPSHandlerV3(**kwargs)
  498. else:
  499. context = ssl.SSLContext(ssl.PROTOCOL_SSLv3)
  500. context.verify_mode = (ssl.CERT_NONE
  501. if opts_no_check_certificate
  502. else ssl.CERT_REQUIRED)
  503. context.set_default_verify_paths()
  504. try:
  505. context.load_default_certs()
  506. except AttributeError:
  507. pass # Python < 3.4
  508. return compat_urllib_request.HTTPSHandler(context=context, **kwargs)
  509. class ExtractorError(Exception):
  510. """Error during info extraction."""
  511. def __init__(self, msg, tb=None, expected=False, cause=None):
  512. """ tb, if given, is the original traceback (so that it can be printed out).
  513. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  514. """
  515. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  516. expected = True
  517. if not expected:
  518. msg = msg + u'; please report this issue on https://yt-dl.org/bug . Be sure to call youtube-dl with the --verbose flag and include its complete output. Make sure you are using the latest version; type youtube-dl -U to update.'
  519. super(ExtractorError, self).__init__(msg)
  520. self.traceback = tb
  521. self.exc_info = sys.exc_info() # preserve original exception
  522. self.cause = cause
  523. def format_traceback(self):
  524. if self.traceback is None:
  525. return None
  526. return u''.join(traceback.format_tb(self.traceback))
  527. class RegexNotFoundError(ExtractorError):
  528. """Error when a regex didn't match"""
  529. pass
  530. class DownloadError(Exception):
  531. """Download Error exception.
  532. This exception may be thrown by FileDownloader objects if they are not
  533. configured to continue on errors. They will contain the appropriate
  534. error message.
  535. """
  536. def __init__(self, msg, exc_info=None):
  537. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  538. super(DownloadError, self).__init__(msg)
  539. self.exc_info = exc_info
  540. class SameFileError(Exception):
  541. """Same File exception.
  542. This exception will be thrown by FileDownloader objects if they detect
  543. multiple files would have to be downloaded to the same file on disk.
  544. """
  545. pass
  546. class PostProcessingError(Exception):
  547. """Post Processing exception.
  548. This exception may be raised by PostProcessor's .run() method to
  549. indicate an error in the postprocessing task.
  550. """
  551. def __init__(self, msg):
  552. self.msg = msg
  553. class MaxDownloadsReached(Exception):
  554. """ --max-downloads limit has been reached. """
  555. pass
  556. class UnavailableVideoError(Exception):
  557. """Unavailable Format exception.
  558. This exception will be thrown when a video is requested
  559. in a format that is not available for that video.
  560. """
  561. pass
  562. class ContentTooShortError(Exception):
  563. """Content Too Short exception.
  564. This exception may be raised by FileDownloader objects when a file they
  565. download is too small for what the server announced first, indicating
  566. the connection was probably interrupted.
  567. """
  568. # Both in bytes
  569. downloaded = None
  570. expected = None
  571. def __init__(self, downloaded, expected):
  572. self.downloaded = downloaded
  573. self.expected = expected
  574. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  575. """Handler for HTTP requests and responses.
  576. This class, when installed with an OpenerDirector, automatically adds
  577. the standard headers to every HTTP request and handles gzipped and
  578. deflated responses from web servers. If compression is to be avoided in
  579. a particular request, the original request in the program code only has
  580. to include the HTTP header "Youtubedl-No-Compression", which will be
  581. removed before making the real request.
  582. Part of this code was copied from:
  583. http://techknack.net/python-urllib2-handlers/
  584. Andrew Rowls, the author of that code, agreed to release it to the
  585. public domain.
  586. """
  587. @staticmethod
  588. def deflate(data):
  589. try:
  590. return zlib.decompress(data, -zlib.MAX_WBITS)
  591. except zlib.error:
  592. return zlib.decompress(data)
  593. @staticmethod
  594. def addinfourl_wrapper(stream, headers, url, code):
  595. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  596. return compat_urllib_request.addinfourl(stream, headers, url, code)
  597. ret = compat_urllib_request.addinfourl(stream, headers, url)
  598. ret.code = code
  599. return ret
  600. def http_request(self, req):
  601. for h,v in std_headers.items():
  602. if h in req.headers:
  603. del req.headers[h]
  604. req.add_header(h, v)
  605. if 'Youtubedl-no-compression' in req.headers:
  606. if 'Accept-encoding' in req.headers:
  607. del req.headers['Accept-encoding']
  608. del req.headers['Youtubedl-no-compression']
  609. if 'Youtubedl-user-agent' in req.headers:
  610. if 'User-agent' in req.headers:
  611. del req.headers['User-agent']
  612. req.headers['User-agent'] = req.headers['Youtubedl-user-agent']
  613. del req.headers['Youtubedl-user-agent']
  614. return req
  615. def http_response(self, req, resp):
  616. old_resp = resp
  617. # gzip
  618. if resp.headers.get('Content-encoding', '') == 'gzip':
  619. content = resp.read()
  620. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  621. try:
  622. uncompressed = io.BytesIO(gz.read())
  623. except IOError as original_ioerror:
  624. # There may be junk add the end of the file
  625. # See http://stackoverflow.com/q/4928560/35070 for details
  626. for i in range(1, 1024):
  627. try:
  628. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  629. uncompressed = io.BytesIO(gz.read())
  630. except IOError:
  631. continue
  632. break
  633. else:
  634. raise original_ioerror
  635. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  636. resp.msg = old_resp.msg
  637. # deflate
  638. if resp.headers.get('Content-encoding', '') == 'deflate':
  639. gz = io.BytesIO(self.deflate(resp.read()))
  640. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  641. resp.msg = old_resp.msg
  642. return resp
  643. https_request = http_request
  644. https_response = http_response
  645. def unified_strdate(date_str):
  646. """Return a string with the date in the format YYYYMMDD"""
  647. upload_date = None
  648. #Replace commas
  649. date_str = date_str.replace(',', ' ')
  650. # %z (UTC offset) is only supported in python>=3.2
  651. date_str = re.sub(r' ?(\+|-)[0-9]{2}:?[0-9]{2}$', '', date_str)
  652. format_expressions = [
  653. '%d %B %Y',
  654. '%d %b %Y',
  655. '%B %d %Y',
  656. '%b %d %Y',
  657. '%Y-%m-%d',
  658. '%d/%m/%Y',
  659. '%Y/%m/%d %H:%M:%S',
  660. '%Y-%m-%d %H:%M:%S',
  661. '%d.%m.%Y %H:%M',
  662. '%Y-%m-%dT%H:%M:%SZ',
  663. '%Y-%m-%dT%H:%M:%S.%fZ',
  664. '%Y-%m-%dT%H:%M:%S.%f0Z',
  665. '%Y-%m-%dT%H:%M:%S',
  666. '%Y-%m-%dT%H:%M',
  667. ]
  668. for expression in format_expressions:
  669. try:
  670. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  671. except ValueError:
  672. pass
  673. if upload_date is None:
  674. timetuple = email.utils.parsedate_tz(date_str)
  675. if timetuple:
  676. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  677. return upload_date
  678. def determine_ext(url, default_ext=u'unknown_video'):
  679. guess = url.partition(u'?')[0].rpartition(u'.')[2]
  680. if re.match(r'^[A-Za-z0-9]+$', guess):
  681. return guess
  682. else:
  683. return default_ext
  684. def subtitles_filename(filename, sub_lang, sub_format):
  685. return filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  686. def date_from_str(date_str):
  687. """
  688. Return a datetime object from a string in the format YYYYMMDD or
  689. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  690. today = datetime.date.today()
  691. if date_str == 'now'or date_str == 'today':
  692. return today
  693. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  694. if match is not None:
  695. sign = match.group('sign')
  696. time = int(match.group('time'))
  697. if sign == '-':
  698. time = -time
  699. unit = match.group('unit')
  700. #A bad aproximation?
  701. if unit == 'month':
  702. unit = 'day'
  703. time *= 30
  704. elif unit == 'year':
  705. unit = 'day'
  706. time *= 365
  707. unit += 's'
  708. delta = datetime.timedelta(**{unit: time})
  709. return today + delta
  710. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  711. def hyphenate_date(date_str):
  712. """
  713. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  714. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  715. if match is not None:
  716. return '-'.join(match.groups())
  717. else:
  718. return date_str
  719. class DateRange(object):
  720. """Represents a time interval between two dates"""
  721. def __init__(self, start=None, end=None):
  722. """start and end must be strings in the format accepted by date"""
  723. if start is not None:
  724. self.start = date_from_str(start)
  725. else:
  726. self.start = datetime.datetime.min.date()
  727. if end is not None:
  728. self.end = date_from_str(end)
  729. else:
  730. self.end = datetime.datetime.max.date()
  731. if self.start > self.end:
  732. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  733. @classmethod
  734. def day(cls, day):
  735. """Returns a range that only contains the given day"""
  736. return cls(day,day)
  737. def __contains__(self, date):
  738. """Check if the date is in the range"""
  739. if not isinstance(date, datetime.date):
  740. date = date_from_str(date)
  741. return self.start <= date <= self.end
  742. def __str__(self):
  743. return '%s - %s' % ( self.start.isoformat(), self.end.isoformat())
  744. def platform_name():
  745. """ Returns the platform name as a compat_str """
  746. res = platform.platform()
  747. if isinstance(res, bytes):
  748. res = res.decode(preferredencoding())
  749. assert isinstance(res, compat_str)
  750. return res
  751. def write_string(s, out=None):
  752. if out is None:
  753. out = sys.stderr
  754. assert type(s) == compat_str
  755. if ('b' in getattr(out, 'mode', '') or
  756. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  757. s = s.encode(preferredencoding(), 'ignore')
  758. try:
  759. out.write(s)
  760. except UnicodeEncodeError:
  761. # In Windows shells, this can fail even when the codec is just charmap!?
  762. # See https://wiki.python.org/moin/PrintFails#Issue
  763. if sys.platform == 'win32' and hasattr(out, 'encoding'):
  764. s = s.encode(out.encoding, 'ignore').decode(out.encoding)
  765. out.write(s)
  766. else:
  767. raise
  768. out.flush()
  769. def bytes_to_intlist(bs):
  770. if not bs:
  771. return []
  772. if isinstance(bs[0], int): # Python 3
  773. return list(bs)
  774. else:
  775. return [ord(c) for c in bs]
  776. def intlist_to_bytes(xs):
  777. if not xs:
  778. return b''
  779. if isinstance(chr(0), bytes): # Python 2
  780. return ''.join([chr(x) for x in xs])
  781. else:
  782. return bytes(xs)
  783. def get_cachedir(params={}):
  784. cache_root = os.environ.get('XDG_CACHE_HOME',
  785. os.path.expanduser('~/.cache'))
  786. return params.get('cachedir', os.path.join(cache_root, 'youtube-dl'))
  787. # Cross-platform file locking
  788. if sys.platform == 'win32':
  789. import ctypes.wintypes
  790. import msvcrt
  791. class OVERLAPPED(ctypes.Structure):
  792. _fields_ = [
  793. ('Internal', ctypes.wintypes.LPVOID),
  794. ('InternalHigh', ctypes.wintypes.LPVOID),
  795. ('Offset', ctypes.wintypes.DWORD),
  796. ('OffsetHigh', ctypes.wintypes.DWORD),
  797. ('hEvent', ctypes.wintypes.HANDLE),
  798. ]
  799. kernel32 = ctypes.windll.kernel32
  800. LockFileEx = kernel32.LockFileEx
  801. LockFileEx.argtypes = [
  802. ctypes.wintypes.HANDLE, # hFile
  803. ctypes.wintypes.DWORD, # dwFlags
  804. ctypes.wintypes.DWORD, # dwReserved
  805. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  806. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  807. ctypes.POINTER(OVERLAPPED) # Overlapped
  808. ]
  809. LockFileEx.restype = ctypes.wintypes.BOOL
  810. UnlockFileEx = kernel32.UnlockFileEx
  811. UnlockFileEx.argtypes = [
  812. ctypes.wintypes.HANDLE, # hFile
  813. ctypes.wintypes.DWORD, # dwReserved
  814. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  815. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  816. ctypes.POINTER(OVERLAPPED) # Overlapped
  817. ]
  818. UnlockFileEx.restype = ctypes.wintypes.BOOL
  819. whole_low = 0xffffffff
  820. whole_high = 0x7fffffff
  821. def _lock_file(f, exclusive):
  822. overlapped = OVERLAPPED()
  823. overlapped.Offset = 0
  824. overlapped.OffsetHigh = 0
  825. overlapped.hEvent = 0
  826. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  827. handle = msvcrt.get_osfhandle(f.fileno())
  828. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  829. whole_low, whole_high, f._lock_file_overlapped_p):
  830. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  831. def _unlock_file(f):
  832. assert f._lock_file_overlapped_p
  833. handle = msvcrt.get_osfhandle(f.fileno())
  834. if not UnlockFileEx(handle, 0,
  835. whole_low, whole_high, f._lock_file_overlapped_p):
  836. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  837. else:
  838. import fcntl
  839. def _lock_file(f, exclusive):
  840. fcntl.lockf(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  841. def _unlock_file(f):
  842. fcntl.lockf(f, fcntl.LOCK_UN)
  843. class locked_file(object):
  844. def __init__(self, filename, mode, encoding=None):
  845. assert mode in ['r', 'a', 'w']
  846. self.f = io.open(filename, mode, encoding=encoding)
  847. self.mode = mode
  848. def __enter__(self):
  849. exclusive = self.mode != 'r'
  850. try:
  851. _lock_file(self.f, exclusive)
  852. except IOError:
  853. self.f.close()
  854. raise
  855. return self
  856. def __exit__(self, etype, value, traceback):
  857. try:
  858. _unlock_file(self.f)
  859. finally:
  860. self.f.close()
  861. def __iter__(self):
  862. return iter(self.f)
  863. def write(self, *args):
  864. return self.f.write(*args)
  865. def read(self, *args):
  866. return self.f.read(*args)
  867. def shell_quote(args):
  868. quoted_args = []
  869. encoding = sys.getfilesystemencoding()
  870. if encoding is None:
  871. encoding = 'utf-8'
  872. for a in args:
  873. if isinstance(a, bytes):
  874. # We may get a filename encoded with 'encodeFilename'
  875. a = a.decode(encoding)
  876. quoted_args.append(pipes.quote(a))
  877. return u' '.join(quoted_args)
  878. def takewhile_inclusive(pred, seq):
  879. """ Like itertools.takewhile, but include the latest evaluated element
  880. (the first element so that Not pred(e)) """
  881. for e in seq:
  882. yield e
  883. if not pred(e):
  884. return
  885. def smuggle_url(url, data):
  886. """ Pass additional data in a URL for internal use. """
  887. sdata = compat_urllib_parse.urlencode(
  888. {u'__youtubedl_smuggle': json.dumps(data)})
  889. return url + u'#' + sdata
  890. def unsmuggle_url(smug_url, default=None):
  891. if not '#__youtubedl_smuggle' in smug_url:
  892. return smug_url, default
  893. url, _, sdata = smug_url.rpartition(u'#')
  894. jsond = compat_parse_qs(sdata)[u'__youtubedl_smuggle'][0]
  895. data = json.loads(jsond)
  896. return url, data
  897. def format_bytes(bytes):
  898. if bytes is None:
  899. return u'N/A'
  900. if type(bytes) is str:
  901. bytes = float(bytes)
  902. if bytes == 0.0:
  903. exponent = 0
  904. else:
  905. exponent = int(math.log(bytes, 1024.0))
  906. suffix = [u'B', u'KiB', u'MiB', u'GiB', u'TiB', u'PiB', u'EiB', u'ZiB', u'YiB'][exponent]
  907. converted = float(bytes) / float(1024 ** exponent)
  908. return u'%.2f%s' % (converted, suffix)
  909. def str_to_int(int_str):
  910. int_str = re.sub(r'[,\.]', u'', int_str)
  911. return int(int_str)
  912. def get_term_width():
  913. columns = os.environ.get('COLUMNS', None)
  914. if columns:
  915. return int(columns)
  916. try:
  917. sp = subprocess.Popen(
  918. ['stty', 'size'],
  919. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  920. out, err = sp.communicate()
  921. return int(out.split()[1])
  922. except:
  923. pass
  924. return None
  925. def month_by_name(name):
  926. """ Return the number of a month by (locale-independently) English name """
  927. ENGLISH_NAMES = [
  928. u'January', u'February', u'March', u'April', u'May', u'June',
  929. u'July', u'August', u'September', u'October', u'November', u'December']
  930. try:
  931. return ENGLISH_NAMES.index(name) + 1
  932. except ValueError:
  933. return None
  934. def fix_xml_ampersands(xml_str):
  935. """Replace all the '&' by '&amp;' in XML"""
  936. return re.sub(
  937. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  938. u'&amp;',
  939. xml_str)
  940. def setproctitle(title):
  941. assert isinstance(title, compat_str)
  942. try:
  943. libc = ctypes.cdll.LoadLibrary("libc.so.6")
  944. except OSError:
  945. return
  946. title = title
  947. buf = ctypes.create_string_buffer(len(title) + 1)
  948. buf.value = title.encode('utf-8')
  949. try:
  950. libc.prctl(15, ctypes.byref(buf), 0, 0, 0)
  951. except AttributeError:
  952. return # Strange libc, just skip this
  953. def remove_start(s, start):
  954. if s.startswith(start):
  955. return s[len(start):]
  956. return s
  957. def url_basename(url):
  958. path = compat_urlparse.urlparse(url).path
  959. return path.strip(u'/').split(u'/')[-1]
  960. class HEADRequest(compat_urllib_request.Request):
  961. def get_method(self):
  962. return "HEAD"
  963. def int_or_none(v, scale=1):
  964. return v if v is None else (int(v) // scale)
  965. def parse_duration(s):
  966. if s is None:
  967. return None
  968. m = re.match(
  969. r'(?:(?:(?P<hours>[0-9]+)[:h])?(?P<mins>[0-9]+)[:m])?(?P<secs>[0-9]+)s?$', s)
  970. if not m:
  971. return None
  972. res = int(m.group('secs'))
  973. if m.group('mins'):
  974. res += int(m.group('mins')) * 60
  975. if m.group('hours'):
  976. res += int(m.group('hours')) * 60 * 60
  977. return res
  978. def prepend_extension(filename, ext):
  979. name, real_ext = os.path.splitext(filename)
  980. return u'{0}.{1}{2}'.format(name, ext, real_ext)
  981. def check_executable(exe, args=[]):
  982. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  983. args can be a list of arguments for a short output (like -version) """
  984. try:
  985. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  986. except OSError:
  987. return False
  988. return exe
  989. class PagedList(object):
  990. def __init__(self, pagefunc, pagesize):
  991. self._pagefunc = pagefunc
  992. self._pagesize = pagesize
  993. def __len__(self):
  994. # This is only useful for tests
  995. return len(self.getslice())
  996. def getslice(self, start=0, end=None):
  997. res = []
  998. for pagenum in itertools.count(start // self._pagesize):
  999. firstid = pagenum * self._pagesize
  1000. nextfirstid = pagenum * self._pagesize + self._pagesize
  1001. if start >= nextfirstid:
  1002. continue
  1003. page_results = list(self._pagefunc(pagenum))
  1004. startv = (
  1005. start % self._pagesize
  1006. if firstid <= start < nextfirstid
  1007. else 0)
  1008. endv = (
  1009. ((end - 1) % self._pagesize) + 1
  1010. if (end is not None and firstid <= end <= nextfirstid)
  1011. else None)
  1012. if startv != 0 or endv is not None:
  1013. page_results = page_results[startv:endv]
  1014. res.extend(page_results)
  1015. # A little optimization - if current page is not "full", ie. does
  1016. # not contain page_size videos then we can assume that this page
  1017. # is the last one - there are no more ids on further pages -
  1018. # i.e. no need to query again.
  1019. if len(page_results) + startv < self._pagesize:
  1020. break
  1021. # If we got the whole page, but the next page is not interesting,
  1022. # break out early as well
  1023. if end == nextfirstid:
  1024. break
  1025. return res
  1026. def uppercase_escape(s):
  1027. return re.sub(
  1028. r'\\U([0-9a-fA-F]{8})',
  1029. lambda m: compat_chr(int(m.group(1), base=16)), s)
  1030. try:
  1031. struct.pack(u'!I', 0)
  1032. except TypeError:
  1033. # In Python 2.6 (and some 2.7 versions), struct requires a bytes argument
  1034. def struct_pack(spec, *args):
  1035. if isinstance(spec, compat_str):
  1036. spec = spec.encode('ascii')
  1037. return struct.pack(spec, *args)
  1038. def struct_unpack(spec, *args):
  1039. if isinstance(spec, compat_str):
  1040. spec = spec.encode('ascii')
  1041. return struct.unpack(spec, *args)
  1042. else:
  1043. struct_pack = struct.pack
  1044. struct_unpack = struct.unpack