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.

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