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.

186 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 = compat_urllib_request.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 = compat_urllib_request.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. open_mode = 'wb'
  80. break
  81. # Retry
  82. count += 1
  83. if count <= retries:
  84. self.report_retry(count, retries)
  85. if count > retries:
  86. self.report_error(u'giving up after %s retries' % retries)
  87. return False
  88. data_len = data.info().get('Content-length', None)
  89. if data_len is not None:
  90. data_len = int(data_len) + resume_len
  91. min_data_len = self.params.get("min_filesize", None)
  92. max_data_len = self.params.get("max_filesize", None)
  93. if min_data_len is not None and data_len < min_data_len:
  94. self.to_screen(u'\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
  95. return False
  96. if max_data_len is not None and data_len > max_data_len:
  97. self.to_screen(u'\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
  98. return False
  99. data_len_str = format_bytes(data_len)
  100. byte_counter = 0 + resume_len
  101. block_size = self.params.get('buffersize', 1024)
  102. start = time.time()
  103. while True:
  104. # Download and write
  105. before = time.time()
  106. data_block = data.read(block_size)
  107. after = time.time()
  108. if len(data_block) == 0:
  109. break
  110. byte_counter += len(data_block)
  111. # Open file just in time
  112. if stream is None:
  113. try:
  114. (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
  115. assert stream is not None
  116. filename = self.undo_temp_name(tmpfilename)
  117. self.report_destination(filename)
  118. except (OSError, IOError) as err:
  119. self.report_error(u'unable to open for writing: %s' % str(err))
  120. return False
  121. try:
  122. stream.write(data_block)
  123. except (IOError, OSError):
  124. self.to_stderr(u"\n")
  125. self.report_error(u'unable to write data: %s' % str(err))
  126. return False
  127. if not self.params.get('noresizebuffer', False):
  128. block_size = self.best_block_size(after - before, len(data_block))
  129. # Progress message
  130. speed = self.calc_speed(start, time.time(), byte_counter - resume_len)
  131. if data_len is None:
  132. eta = percent = None
  133. else:
  134. percent = self.calc_percent(byte_counter, data_len)
  135. eta = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  136. self.report_progress(percent, data_len_str, speed, eta)
  137. self._hook_progress({
  138. 'downloaded_bytes': byte_counter,
  139. 'total_bytes': data_len,
  140. 'tmpfilename': tmpfilename,
  141. 'filename': filename,
  142. 'status': 'downloading',
  143. 'eta': eta,
  144. 'speed': speed,
  145. })
  146. # Apply rate limit
  147. self.slow_down(start, byte_counter - resume_len)
  148. if stream is None:
  149. self.to_stderr(u"\n")
  150. self.report_error(u'Did not get any data blocks')
  151. return False
  152. stream.close()
  153. self.report_finish(data_len_str, (time.time() - start))
  154. if data_len is not None and byte_counter != data_len:
  155. raise ContentTooShortError(byte_counter, int(data_len))
  156. self.try_rename(tmpfilename, filename)
  157. # Update file modification time
  158. if self.params.get('updatetime', True):
  159. info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
  160. self._hook_progress({
  161. 'downloaded_bytes': byte_counter,
  162. 'total_bytes': byte_counter,
  163. 'filename': filename,
  164. 'status': 'finished',
  165. })
  166. return True