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.

1269 lines
40 KiB

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