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.

1304 lines
41 KiB

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