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.

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