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.

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