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.

189 lines
7.8 KiB

  1. import os
  2. import time
  3. from .common import FileDownloader
  4. from ..utils import (
  5. compat_urllib_request,
  6. compat_urllib_error,
  7. ContentTooShortError,
  8. encodeFilename,
  9. sanitize_open,
  10. format_bytes,
  11. )
  12. class HttpFD(FileDownloader):
  13. def real_download(self, filename, info_dict):
  14. url = info_dict['url']
  15. tmpfilename = self.temp_name(filename)
  16. stream = None
  17. # Do not include the Accept-Encoding header
  18. headers = {'Youtubedl-no-compression': 'True'}
  19. if 'user_agent' in info_dict:
  20. headers['Youtubedl-user-agent'] = info_dict['user_agent']
  21. if 'http_referer' in info_dict:
  22. headers['Referer'] = info_dict['http_referer']
  23. basic_request = compat_urllib_request.Request(url, None, headers)
  24. request = compat_urllib_request.Request(url, None, headers)
  25. if self.params.get('test', False):
  26. request.add_header('Range', 'bytes=0-10240')
  27. # Establish possible resume length
  28. if os.path.isfile(encodeFilename(tmpfilename)):
  29. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  30. else:
  31. resume_len = 0
  32. open_mode = 'wb'
  33. if resume_len != 0:
  34. if self.params.get('continuedl', False):
  35. self.report_resuming_byte(resume_len)
  36. request.add_header('Range', 'bytes=%d-' % resume_len)
  37. open_mode = 'ab'
  38. else:
  39. resume_len = 0
  40. count = 0
  41. retries = self.params.get('retries', 0)
  42. while count <= retries:
  43. # Establish connection
  44. try:
  45. data = self.ydl.urlopen(request)
  46. break
  47. except (compat_urllib_error.HTTPError, ) as err:
  48. if (err.code < 500 or err.code >= 600) and err.code != 416:
  49. # Unexpected HTTP error
  50. raise
  51. elif err.code == 416:
  52. # Unable to resume (requested range not satisfiable)
  53. try:
  54. # Open the connection again without the range header
  55. data = self.ydl.urlopen(basic_request)
  56. content_length = data.info()['Content-Length']
  57. except (compat_urllib_error.HTTPError, ) as err:
  58. if err.code < 500 or err.code >= 600:
  59. raise
  60. else:
  61. # Examine the reported length
  62. if (content_length is not None and
  63. (resume_len - 100 < int(content_length) < resume_len + 100)):
  64. # The file had already been fully downloaded.
  65. # Explanation to the above condition: in issue #175 it was revealed that
  66. # YouTube sometimes adds or removes a few bytes from the end of the file,
  67. # changing the file size slightly and causing problems for some users. So
  68. # I decided to implement a suggested change and consider the file
  69. # completely downloaded if the file size differs less than 100 bytes from
  70. # the one in the hard drive.
  71. self.report_file_already_downloaded(filename)
  72. self.try_rename(tmpfilename, filename)
  73. self._hook_progress({
  74. 'filename': filename,
  75. 'status': 'finished',
  76. })
  77. return True
  78. else:
  79. # The length does not match, we start the download over
  80. self.report_unable_to_resume()
  81. resume_len = 0
  82. open_mode = 'wb'
  83. break
  84. # Retry
  85. count += 1
  86. if count <= retries:
  87. self.report_retry(count, retries)
  88. if count > retries:
  89. self.report_error(u'giving up after %s retries' % retries)
  90. return False
  91. data_len = data.info().get('Content-length', None)
  92. if data_len is not None:
  93. data_len = int(data_len) + resume_len
  94. min_data_len = self.params.get("min_filesize", None)
  95. max_data_len = self.params.get("max_filesize", None)
  96. if min_data_len is not None and data_len < min_data_len:
  97. self.to_screen(u'\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
  98. return False
  99. if max_data_len is not None and data_len > max_data_len:
  100. self.to_screen(u'\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
  101. return False
  102. data_len_str = format_bytes(data_len)
  103. byte_counter = 0 + resume_len
  104. block_size = self.params.get('buffersize', 1024)
  105. start = time.time()
  106. while True:
  107. # Download and write
  108. before = time.time()
  109. data_block = data.read(block_size)
  110. after = time.time()
  111. if len(data_block) == 0:
  112. break
  113. byte_counter += len(data_block)
  114. # Open file just in time
  115. if stream is None:
  116. try:
  117. (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
  118. assert stream is not None
  119. filename = self.undo_temp_name(tmpfilename)
  120. self.report_destination(filename)
  121. except (OSError, IOError) as err:
  122. self.report_error(u'unable to open for writing: %s' % str(err))
  123. return False
  124. try:
  125. stream.write(data_block)
  126. except (IOError, OSError) as err:
  127. self.to_stderr(u"\n")
  128. self.report_error(u'unable to write data: %s' % str(err))
  129. return False
  130. if not self.params.get('noresizebuffer', False):
  131. block_size = self.best_block_size(after - before, len(data_block))
  132. # Progress message
  133. speed = self.calc_speed(start, time.time(), byte_counter - resume_len)
  134. if data_len is None:
  135. eta = percent = None
  136. else:
  137. percent = self.calc_percent(byte_counter, data_len)
  138. eta = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  139. self.report_progress(percent, data_len_str, speed, eta)
  140. self._hook_progress({
  141. 'downloaded_bytes': byte_counter,
  142. 'total_bytes': data_len,
  143. 'tmpfilename': tmpfilename,
  144. 'filename': filename,
  145. 'status': 'downloading',
  146. 'eta': eta,
  147. 'speed': speed,
  148. })
  149. # Apply rate limit
  150. self.slow_down(start, byte_counter - resume_len)
  151. if stream is None:
  152. self.to_stderr(u"\n")
  153. self.report_error(u'Did not get any data blocks')
  154. return False
  155. stream.close()
  156. self.report_finish(data_len_str, (time.time() - start))
  157. if data_len is not None and byte_counter != data_len:
  158. raise ContentTooShortError(byte_counter, int(data_len))
  159. self.try_rename(tmpfilename, filename)
  160. # Update file modification time
  161. if self.params.get('updatetime', True):
  162. info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
  163. self._hook_progress({
  164. 'downloaded_bytes': byte_counter,
  165. 'total_bytes': byte_counter,
  166. 'filename': filename,
  167. 'status': 'finished',
  168. })
  169. return True