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.

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