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.

1216 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 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' ?(\+|-)[0-9:]*$', '', 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. '%Y-%m-%dT%H:%M',
  665. ]
  666. for expression in format_expressions:
  667. try:
  668. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  669. except ValueError:
  670. pass
  671. if upload_date is None:
  672. timetuple = email.utils.parsedate_tz(date_str)
  673. if timetuple:
  674. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  675. return upload_date
  676. def determine_ext(url, default_ext=u'unknown_video'):
  677. guess = url.partition(u'?')[0].rpartition(u'.')[2]
  678. if re.match(r'^[A-Za-z0-9]+$', guess):
  679. return guess
  680. else:
  681. return default_ext
  682. def subtitles_filename(filename, sub_lang, sub_format):
  683. return filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  684. def date_from_str(date_str):
  685. """
  686. Return a datetime object from a string in the format YYYYMMDD or
  687. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  688. today = datetime.date.today()
  689. if date_str == 'now'or date_str == 'today':
  690. return today
  691. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  692. if match is not None:
  693. sign = match.group('sign')
  694. time = int(match.group('time'))
  695. if sign == '-':
  696. time = -time
  697. unit = match.group('unit')
  698. #A bad aproximation?
  699. if unit == 'month':
  700. unit = 'day'
  701. time *= 30
  702. elif unit == 'year':
  703. unit = 'day'
  704. time *= 365
  705. unit += 's'
  706. delta = datetime.timedelta(**{unit: time})
  707. return today + delta
  708. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  709. def hyphenate_date(date_str):
  710. """
  711. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  712. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  713. if match is not None:
  714. return '-'.join(match.groups())
  715. else:
  716. return date_str
  717. class DateRange(object):
  718. """Represents a time interval between two dates"""
  719. def __init__(self, start=None, end=None):
  720. """start and end must be strings in the format accepted by date"""
  721. if start is not None:
  722. self.start = date_from_str(start)
  723. else:
  724. self.start = datetime.datetime.min.date()
  725. if end is not None:
  726. self.end = date_from_str(end)
  727. else:
  728. self.end = datetime.datetime.max.date()
  729. if self.start > self.end:
  730. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  731. @classmethod
  732. def day(cls, day):
  733. """Returns a range that only contains the given day"""
  734. return cls(day,day)
  735. def __contains__(self, date):
  736. """Check if the date is in the range"""
  737. if not isinstance(date, datetime.date):
  738. date = date_from_str(date)
  739. return self.start <= date <= self.end
  740. def __str__(self):
  741. return '%s - %s' % ( self.start.isoformat(), self.end.isoformat())
  742. def platform_name():
  743. """ Returns the platform name as a compat_str """
  744. res = platform.platform()
  745. if isinstance(res, bytes):
  746. res = res.decode(preferredencoding())
  747. assert isinstance(res, compat_str)
  748. return res
  749. def write_string(s, out=None):
  750. if out is None:
  751. out = sys.stderr
  752. assert type(s) == compat_str
  753. if ('b' in getattr(out, 'mode', '') or
  754. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  755. s = s.encode(preferredencoding(), 'ignore')
  756. try:
  757. out.write(s)
  758. except UnicodeEncodeError:
  759. # In Windows shells, this can fail even when the codec is just charmap!?
  760. # See https://wiki.python.org/moin/PrintFails#Issue
  761. if sys.platform == 'win32' and hasattr(out, 'encoding'):
  762. s = s.encode(out.encoding, 'ignore').decode(out.encoding)
  763. out.write(s)
  764. else:
  765. raise
  766. out.flush()
  767. def bytes_to_intlist(bs):
  768. if not bs:
  769. return []
  770. if isinstance(bs[0], int): # Python 3
  771. return list(bs)
  772. else:
  773. return [ord(c) for c in bs]
  774. def intlist_to_bytes(xs):
  775. if not xs:
  776. return b''
  777. if isinstance(chr(0), bytes): # Python 2
  778. return ''.join([chr(x) for x in xs])
  779. else:
  780. return bytes(xs)
  781. def get_cachedir(params={}):
  782. cache_root = os.environ.get('XDG_CACHE_HOME',
  783. os.path.expanduser('~/.cache'))
  784. return params.get('cachedir', os.path.join(cache_root, 'youtube-dl'))
  785. # Cross-platform file locking
  786. if sys.platform == 'win32':
  787. import ctypes.wintypes
  788. import msvcrt
  789. class OVERLAPPED(ctypes.Structure):
  790. _fields_ = [
  791. ('Internal', ctypes.wintypes.LPVOID),
  792. ('InternalHigh', ctypes.wintypes.LPVOID),
  793. ('Offset', ctypes.wintypes.DWORD),
  794. ('OffsetHigh', ctypes.wintypes.DWORD),
  795. ('hEvent', ctypes.wintypes.HANDLE),
  796. ]
  797. kernel32 = ctypes.windll.kernel32
  798. LockFileEx = kernel32.LockFileEx
  799. LockFileEx.argtypes = [
  800. ctypes.wintypes.HANDLE, # hFile
  801. ctypes.wintypes.DWORD, # dwFlags
  802. ctypes.wintypes.DWORD, # dwReserved
  803. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  804. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  805. ctypes.POINTER(OVERLAPPED) # Overlapped
  806. ]
  807. LockFileEx.restype = ctypes.wintypes.BOOL
  808. UnlockFileEx = kernel32.UnlockFileEx
  809. UnlockFileEx.argtypes = [
  810. ctypes.wintypes.HANDLE, # hFile
  811. ctypes.wintypes.DWORD, # dwReserved
  812. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  813. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  814. ctypes.POINTER(OVERLAPPED) # Overlapped
  815. ]
  816. UnlockFileEx.restype = ctypes.wintypes.BOOL
  817. whole_low = 0xffffffff
  818. whole_high = 0x7fffffff
  819. def _lock_file(f, exclusive):
  820. overlapped = OVERLAPPED()
  821. overlapped.Offset = 0
  822. overlapped.OffsetHigh = 0
  823. overlapped.hEvent = 0
  824. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  825. handle = msvcrt.get_osfhandle(f.fileno())
  826. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  827. whole_low, whole_high, f._lock_file_overlapped_p):
  828. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  829. def _unlock_file(f):
  830. assert f._lock_file_overlapped_p
  831. handle = msvcrt.get_osfhandle(f.fileno())
  832. if not UnlockFileEx(handle, 0,
  833. whole_low, whole_high, f._lock_file_overlapped_p):
  834. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  835. else:
  836. import fcntl
  837. def _lock_file(f, exclusive):
  838. fcntl.lockf(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  839. def _unlock_file(f):
  840. fcntl.lockf(f, fcntl.LOCK_UN)
  841. class locked_file(object):
  842. def __init__(self, filename, mode, encoding=None):
  843. assert mode in ['r', 'a', 'w']
  844. self.f = io.open(filename, mode, encoding=encoding)
  845. self.mode = mode
  846. def __enter__(self):
  847. exclusive = self.mode != 'r'
  848. try:
  849. _lock_file(self.f, exclusive)
  850. except IOError:
  851. self.f.close()
  852. raise
  853. return self
  854. def __exit__(self, etype, value, traceback):
  855. try:
  856. _unlock_file(self.f)
  857. finally:
  858. self.f.close()
  859. def __iter__(self):
  860. return iter(self.f)
  861. def write(self, *args):
  862. return self.f.write(*args)
  863. def read(self, *args):
  864. return self.f.read(*args)
  865. def shell_quote(args):
  866. quoted_args = []
  867. encoding = sys.getfilesystemencoding()
  868. if encoding is None:
  869. encoding = 'utf-8'
  870. for a in args:
  871. if isinstance(a, bytes):
  872. # We may get a filename encoded with 'encodeFilename'
  873. a = a.decode(encoding)
  874. quoted_args.append(pipes.quote(a))
  875. return u' '.join(quoted_args)
  876. def takewhile_inclusive(pred, seq):
  877. """ Like itertools.takewhile, but include the latest evaluated element
  878. (the first element so that Not pred(e)) """
  879. for e in seq:
  880. yield e
  881. if not pred(e):
  882. return
  883. def smuggle_url(url, data):
  884. """ Pass additional data in a URL for internal use. """
  885. sdata = compat_urllib_parse.urlencode(
  886. {u'__youtubedl_smuggle': json.dumps(data)})
  887. return url + u'#' + sdata
  888. def unsmuggle_url(smug_url, default=None):
  889. if not '#__youtubedl_smuggle' in smug_url:
  890. return smug_url, default
  891. url, _, sdata = smug_url.rpartition(u'#')
  892. jsond = compat_parse_qs(sdata)[u'__youtubedl_smuggle'][0]
  893. data = json.loads(jsond)
  894. return url, data
  895. def format_bytes(bytes):
  896. if bytes is None:
  897. return u'N/A'
  898. if type(bytes) is str:
  899. bytes = float(bytes)
  900. if bytes == 0.0:
  901. exponent = 0
  902. else:
  903. exponent = int(math.log(bytes, 1024.0))
  904. suffix = [u'B', u'KiB', u'MiB', u'GiB', u'TiB', u'PiB', u'EiB', u'ZiB', u'YiB'][exponent]
  905. converted = float(bytes) / float(1024 ** exponent)
  906. return u'%.2f%s' % (converted, suffix)
  907. def str_to_int(int_str):
  908. int_str = re.sub(r'[,\.]', u'', int_str)
  909. return int(int_str)
  910. def get_term_width():
  911. columns = os.environ.get('COLUMNS', None)
  912. if columns:
  913. return int(columns)
  914. try:
  915. sp = subprocess.Popen(
  916. ['stty', 'size'],
  917. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  918. out, err = sp.communicate()
  919. return int(out.split()[1])
  920. except:
  921. pass
  922. return None
  923. def month_by_name(name):
  924. """ Return the number of a month by (locale-independently) English name """
  925. ENGLISH_NAMES = [
  926. u'January', u'February', u'March', u'April', u'May', u'June',
  927. u'July', u'August', u'September', u'October', u'November', u'December']
  928. try:
  929. return ENGLISH_NAMES.index(name) + 1
  930. except ValueError:
  931. return None
  932. def fix_xml_ampersands(xml_str):
  933. """Replace all the '&' by '&amp;' in XML"""
  934. return re.sub(
  935. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  936. u'&amp;',
  937. xml_str)
  938. def setproctitle(title):
  939. assert isinstance(title, compat_str)
  940. try:
  941. libc = ctypes.cdll.LoadLibrary("libc.so.6")
  942. except OSError:
  943. return
  944. title = title
  945. buf = ctypes.create_string_buffer(len(title) + 1)
  946. buf.value = title.encode('utf-8')
  947. try:
  948. libc.prctl(15, ctypes.byref(buf), 0, 0, 0)
  949. except AttributeError:
  950. return # Strange libc, just skip this
  951. def remove_start(s, start):
  952. if s.startswith(start):
  953. return s[len(start):]
  954. return s
  955. def url_basename(url):
  956. path = compat_urlparse.urlparse(url).path
  957. return path.strip(u'/').split(u'/')[-1]
  958. class HEADRequest(compat_urllib_request.Request):
  959. def get_method(self):
  960. return "HEAD"
  961. def int_or_none(v, scale=1):
  962. return v if v is None else (int(v) // scale)
  963. def parse_duration(s):
  964. if s is None:
  965. return None
  966. m = re.match(
  967. r'(?:(?:(?P<hours>[0-9]+):)?(?P<mins>[0-9]+):)?(?P<secs>[0-9]+)$', s)
  968. if not m:
  969. return None
  970. res = int(m.group('secs'))
  971. if m.group('mins'):
  972. res += int(m.group('mins')) * 60
  973. if m.group('hours'):
  974. res += int(m.group('hours')) * 60 * 60
  975. return res
  976. def prepend_extension(filename, ext):
  977. name, real_ext = os.path.splitext(filename)
  978. return u'{0}.{1}{2}'.format(name, ext, real_ext)
  979. def check_executable(exe, args=[]):
  980. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  981. args can be a list of arguments for a short output (like -version) """
  982. try:
  983. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  984. except OSError:
  985. return False
  986. return exe
  987. class PagedList(object):
  988. def __init__(self, pagefunc, pagesize):
  989. self._pagefunc = pagefunc
  990. self._pagesize = pagesize
  991. def __len__(self):
  992. # This is only useful for tests
  993. return len(self.getslice())
  994. def getslice(self, start=0, end=None):
  995. res = []
  996. for pagenum in itertools.count(start // self._pagesize):
  997. firstid = pagenum * self._pagesize
  998. nextfirstid = pagenum * self._pagesize + self._pagesize
  999. if start >= nextfirstid:
  1000. continue
  1001. page_results = list(self._pagefunc(pagenum))
  1002. startv = (
  1003. start % self._pagesize
  1004. if firstid <= start < nextfirstid
  1005. else 0)
  1006. endv = (
  1007. ((end - 1) % self._pagesize) + 1
  1008. if (end is not None and firstid <= end <= nextfirstid)
  1009. else None)
  1010. if startv != 0 or endv is not None:
  1011. page_results = page_results[startv:endv]
  1012. res.extend(page_results)
  1013. # A little optimization - if current page is not "full", ie. does
  1014. # not contain page_size videos then we can assume that this page
  1015. # is the last one - there are no more ids on further pages -
  1016. # i.e. no need to query again.
  1017. if len(page_results) + startv < self._pagesize:
  1018. break
  1019. # If we got the whole page, but the next page is not interesting,
  1020. # break out early as well
  1021. if end == nextfirstid:
  1022. break
  1023. return res