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.

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