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.

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