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.

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