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.

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