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.

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