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.

228 lines
9.2 KiB

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