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.

1247 lines
40 KiB

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