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.

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