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.

1330 lines
42 KiB

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