logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

http.py (16085B)


  1. from __future__ import unicode_literals
  2. import errno
  3. import os
  4. import socket
  5. import time
  6. import random
  7. import re
  8. from .common import FileDownloader
  9. from ..compat import (
  10. compat_str,
  11. compat_urllib_error,
  12. )
  13. from ..utils import (
  14. ContentTooShortError,
  15. encodeFilename,
  16. int_or_none,
  17. sanitize_open,
  18. sanitized_Request,
  19. write_xattr,
  20. XAttrMetadataError,
  21. XAttrUnavailableError,
  22. )
  23. class HttpFD(FileDownloader):
  24. def real_download(self, filename, info_dict):
  25. url = info_dict['url']
  26. class DownloadContext(dict):
  27. __getattr__ = dict.get
  28. __setattr__ = dict.__setitem__
  29. __delattr__ = dict.__delitem__
  30. ctx = DownloadContext()
  31. ctx.filename = filename
  32. ctx.tmpfilename = self.temp_name(filename)
  33. ctx.stream = None
  34. # Do not include the Accept-Encoding header
  35. headers = {'Youtubedl-no-compression': 'True'}
  36. add_headers = info_dict.get('http_headers')
  37. if add_headers:
  38. headers.update(add_headers)
  39. is_test = self.params.get('test', False)
  40. chunk_size = self._TEST_FILE_SIZE if is_test else (
  41. info_dict.get('downloader_options', {}).get('http_chunk_size')
  42. or self.params.get('http_chunk_size') or 0)
  43. ctx.open_mode = 'wb'
  44. ctx.resume_len = 0
  45. ctx.data_len = None
  46. ctx.block_size = self.params.get('buffersize', 1024)
  47. ctx.start_time = time.time()
  48. ctx.chunk_size = None
  49. if self.params.get('continuedl', True):
  50. # Establish possible resume length
  51. ctx.resume_len = info_dict.get('frag_resume_len')
  52. if ctx.resume_len is None:
  53. ctx.resume_len = self.filesize_or_none(ctx.tmpfilename) or 0
  54. ctx.is_resume = ctx.resume_len > 0
  55. count = 0
  56. retries = self.params.get('retries', 0)
  57. class SucceedDownload(Exception):
  58. pass
  59. class RetryDownload(Exception):
  60. def __init__(self, source_error):
  61. self.source_error = source_error
  62. class NextFragment(Exception):
  63. pass
  64. def set_range(req, start, end):
  65. range_header = 'bytes=%d-' % start
  66. if end:
  67. range_header += compat_str(end)
  68. req.add_header('Range', range_header)
  69. def establish_connection():
  70. ctx.chunk_size = (random.randint(int(chunk_size * 0.95), chunk_size)
  71. if not is_test and chunk_size else chunk_size)
  72. if ctx.resume_len > 0:
  73. range_start = ctx.resume_len
  74. if ctx.is_resume:
  75. self.report_resuming_byte(ctx.resume_len)
  76. ctx.open_mode = 'ab'
  77. elif ctx.chunk_size > 0:
  78. range_start = 0
  79. else:
  80. range_start = None
  81. ctx.is_resume = False
  82. range_end = range_start + ctx.chunk_size - 1 if ctx.chunk_size else None
  83. if range_end and ctx.data_len is not None and range_end >= ctx.data_len:
  84. range_end = ctx.data_len - 1
  85. has_range = range_start is not None
  86. ctx.has_range = has_range
  87. request = sanitized_Request(url, None, headers)
  88. if has_range:
  89. set_range(request, range_start, range_end)
  90. # Establish connection
  91. try:
  92. try:
  93. ctx.data = self.ydl.urlopen(request)
  94. except (compat_urllib_error.URLError, ) as err:
  95. # reason may not be available, e.g. for urllib2.HTTPError on python 2.6
  96. reason = getattr(err, 'reason', None)
  97. if isinstance(reason, socket.timeout):
  98. raise RetryDownload(err)
  99. raise err
  100. # When trying to resume, Content-Range HTTP header of response has to be checked
  101. # to match the value of requested Range HTTP header. This is due to webservers
  102. # that don't support resuming and serve a whole file with no Content-Range
  103. # set in response despite requested Range (see
  104. # https://github.com/ytdl-org/youtube-dl/issues/6057#issuecomment-126129799)
  105. if has_range:
  106. content_range = ctx.data.headers.get('Content-Range')
  107. if content_range:
  108. content_range_m = re.search(r'bytes (\d+)-(\d+)?(?:/(\d+))?', content_range)
  109. # Content-Range is present and matches requested Range, resume is possible
  110. if content_range_m:
  111. if range_start == int(content_range_m.group(1)):
  112. content_range_end = int_or_none(content_range_m.group(2))
  113. content_len = int_or_none(content_range_m.group(3))
  114. accept_content_len = (
  115. # Non-chunked download
  116. not ctx.chunk_size
  117. # Chunked download and requested piece or
  118. # its part is promised to be served
  119. or content_range_end == range_end
  120. or content_len < range_end)
  121. if accept_content_len:
  122. ctx.data_len = content_len
  123. return
  124. # Content-Range is either not present or invalid. Assuming remote webserver is
  125. # trying to send the whole file, resume is not possible, so wiping the local file
  126. # and performing entire redownload
  127. if range_start > 0:
  128. self.report_unable_to_resume()
  129. ctx.resume_len = 0
  130. ctx.open_mode = 'wb'
  131. ctx.data_len = int_or_none(ctx.data.info().get('Content-length', None))
  132. return
  133. except (compat_urllib_error.HTTPError, ) as err:
  134. if err.code == 416:
  135. # Unable to resume (requested range not satisfiable)
  136. try:
  137. # Open the connection again without the range header
  138. ctx.data = self.ydl.urlopen(
  139. sanitized_Request(url, None, headers))
  140. content_length = ctx.data.info()['Content-Length']
  141. except (compat_urllib_error.HTTPError, ) as err:
  142. if err.code < 500 or err.code >= 600:
  143. raise
  144. else:
  145. # Examine the reported length
  146. if (content_length is not None
  147. and (ctx.resume_len - 100 < int(content_length) < ctx.resume_len + 100)):
  148. # The file had already been fully downloaded.
  149. # Explanation to the above condition: in issue #175 it was revealed that
  150. # YouTube sometimes adds or removes a few bytes from the end of the file,
  151. # changing the file size slightly and causing problems for some users. So
  152. # I decided to implement a suggested change and consider the file
  153. # completely downloaded if the file size differs less than 100 bytes from
  154. # the one in the hard drive.
  155. self.report_file_already_downloaded(ctx.filename)
  156. self.try_rename(ctx.tmpfilename, ctx.filename)
  157. self._hook_progress({
  158. 'filename': ctx.filename,
  159. 'status': 'finished',
  160. 'downloaded_bytes': ctx.resume_len,
  161. 'total_bytes': ctx.resume_len,
  162. })
  163. raise SucceedDownload()
  164. else:
  165. # The length does not match, we start the download over
  166. self.report_unable_to_resume()
  167. ctx.resume_len = 0
  168. ctx.open_mode = 'wb'
  169. return
  170. elif err.code < 500 or err.code >= 600:
  171. # Unexpected HTTP error
  172. raise
  173. raise RetryDownload(err)
  174. except socket.error as err:
  175. if err.errno != errno.ECONNRESET:
  176. # Connection reset is no problem, just retry
  177. raise
  178. raise RetryDownload(err)
  179. def download():
  180. data_len = ctx.data.info().get('Content-length', None)
  181. # Range HTTP header may be ignored/unsupported by a webserver
  182. # (e.g. extractor/scivee.py, extractor/bambuser.py).
  183. # However, for a test we still would like to download just a piece of a file.
  184. # To achieve this we limit data_len to _TEST_FILE_SIZE and manually control
  185. # block size when downloading a file.
  186. if is_test and (data_len is None or int(data_len) > self._TEST_FILE_SIZE):
  187. data_len = self._TEST_FILE_SIZE
  188. if data_len is not None:
  189. data_len = int(data_len) + ctx.resume_len
  190. min_data_len = self.params.get('min_filesize')
  191. max_data_len = self.params.get('max_filesize')
  192. if min_data_len is not None and data_len < min_data_len:
  193. self.to_screen('\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
  194. return False
  195. if max_data_len is not None and data_len > max_data_len:
  196. self.to_screen('\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
  197. return False
  198. byte_counter = 0 + ctx.resume_len
  199. block_size = ctx.block_size
  200. start = time.time()
  201. # measure time over whole while-loop, so slow_down() and best_block_size() work together properly
  202. now = None # needed for slow_down() in the first loop run
  203. before = start # start measuring
  204. def retry(e):
  205. to_stdout = ctx.tmpfilename == '-'
  206. if ctx.stream is not None:
  207. if not to_stdout:
  208. ctx.stream.close()
  209. ctx.stream = None
  210. ctx.resume_len = byte_counter if to_stdout else os.path.getsize(encodeFilename(ctx.tmpfilename))
  211. raise RetryDownload(e)
  212. while True:
  213. try:
  214. # Download and write
  215. data_block = ctx.data.read(block_size if data_len is None else min(block_size, data_len - byte_counter))
  216. # socket.timeout is a subclass of socket.error but may not have
  217. # errno set
  218. except socket.timeout as e:
  219. retry(e)
  220. except socket.error as e:
  221. # SSLError on python 2 (inherits socket.error) may have
  222. # no errno set but this error message
  223. if e.errno in (errno.ECONNRESET, errno.ETIMEDOUT) or getattr(e, 'message', None) == 'The read operation timed out':
  224. retry(e)
  225. raise
  226. byte_counter += len(data_block)
  227. # exit loop when download is finished
  228. if len(data_block) == 0:
  229. break
  230. # Open destination file just in time
  231. if ctx.stream is None:
  232. try:
  233. ctx.stream, ctx.tmpfilename = sanitize_open(
  234. ctx.tmpfilename, ctx.open_mode)
  235. assert ctx.stream is not None
  236. ctx.filename = self.undo_temp_name(ctx.tmpfilename)
  237. self.report_destination(ctx.filename)
  238. except (OSError, IOError) as err:
  239. self.report_error('unable to open for writing: %s' % str(err))
  240. return False
  241. if self.params.get('xattr_set_filesize', False) and data_len is not None:
  242. try:
  243. write_xattr(ctx.tmpfilename, 'user.ytdl.filesize', str(data_len).encode('utf-8'))
  244. except (XAttrUnavailableError, XAttrMetadataError) as err:
  245. self.report_error('unable to set filesize xattr: %s' % str(err))
  246. try:
  247. ctx.stream.write(data_block)
  248. except (IOError, OSError) as err:
  249. self.to_stderr('\n')
  250. self.report_error('unable to write data: %s' % str(err))
  251. return False
  252. # Apply rate limit
  253. self.slow_down(start, now, byte_counter - ctx.resume_len)
  254. # end measuring of one loop run
  255. now = time.time()
  256. after = now
  257. # Adjust block size
  258. if not self.params.get('noresizebuffer', False):
  259. block_size = self.best_block_size(after - before, len(data_block))
  260. before = after
  261. # Progress message
  262. speed = self.calc_speed(start, now, byte_counter - ctx.resume_len)
  263. eta = self.calc_eta(speed, ctx.data_len and (ctx.data_len - byte_counter))
  264. self._hook_progress({
  265. 'status': 'downloading',
  266. 'downloaded_bytes': byte_counter,
  267. 'total_bytes': ctx.data_len,
  268. 'tmpfilename': ctx.tmpfilename,
  269. 'filename': ctx.filename,
  270. 'eta': eta,
  271. 'speed': speed,
  272. 'elapsed': now - ctx.start_time,
  273. })
  274. if data_len is not None and byte_counter == data_len:
  275. break
  276. if not is_test and ctx.chunk_size and ctx.data_len is not None and byte_counter < ctx.data_len:
  277. ctx.resume_len = byte_counter
  278. # ctx.block_size = block_size
  279. raise NextFragment()
  280. if ctx.stream is None:
  281. self.to_stderr('\n')
  282. self.report_error('Did not get any data blocks')
  283. return False
  284. if ctx.tmpfilename != '-':
  285. ctx.stream.close()
  286. if data_len is not None and byte_counter != data_len:
  287. err = ContentTooShortError(byte_counter, int(data_len))
  288. if count <= retries:
  289. retry(err)
  290. raise err
  291. self.try_rename(ctx.tmpfilename, ctx.filename)
  292. # Update file modification time
  293. if self.params.get('updatetime', True):
  294. info_dict['filetime'] = self.try_utime(ctx.filename, ctx.data.info().get('last-modified', None))
  295. self._hook_progress({
  296. 'downloaded_bytes': byte_counter,
  297. 'total_bytes': byte_counter,
  298. 'filename': ctx.filename,
  299. 'status': 'finished',
  300. 'elapsed': time.time() - ctx.start_time,
  301. })
  302. return True
  303. while count <= retries:
  304. try:
  305. establish_connection()
  306. return download()
  307. except RetryDownload as e:
  308. count += 1
  309. if count <= retries:
  310. self.report_retry(e.source_error, count, retries)
  311. continue
  312. except NextFragment:
  313. continue
  314. except SucceedDownload:
  315. return True
  316. self.report_error('giving up after %s retries' % retries)
  317. return False