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.

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