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.

1029 lines
33 KiB

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