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.

251 lines
10 KiB

10 years ago
10 years ago
Switch codebase to use sanitized_Request instead of compat_urllib_request.Request [downloader/dash] Use sanitized_Request [downloader/http] Use sanitized_Request [atresplayer] Use sanitized_Request [bambuser] Use sanitized_Request [bliptv] Use sanitized_Request [brightcove] Use sanitized_Request [cbs] Use sanitized_Request [ceskatelevize] Use sanitized_Request [collegerama] Use sanitized_Request [extractor/common] Use sanitized_Request [crunchyroll] Use sanitized_Request [dailymotion] Use sanitized_Request [dcn] Use sanitized_Request [dramafever] Use sanitized_Request [dumpert] Use sanitized_Request [eitb] Use sanitized_Request [escapist] Use sanitized_Request [everyonesmixtape] Use sanitized_Request [extremetube] Use sanitized_Request [facebook] Use sanitized_Request [fc2] Use sanitized_Request [flickr] Use sanitized_Request [4tube] Use sanitized_Request [gdcvault] Use sanitized_Request [extractor/generic] Use sanitized_Request [hearthisat] Use sanitized_Request [hotnewhiphop] Use sanitized_Request [hypem] Use sanitized_Request [iprima] Use sanitized_Request [ivi] Use sanitized_Request [keezmovies] Use sanitized_Request [letv] Use sanitized_Request [lynda] Use sanitized_Request [metacafe] Use sanitized_Request [minhateca] Use sanitized_Request [miomio] Use sanitized_Request [meovideo] Use sanitized_Request [mofosex] Use sanitized_Request [moniker] Use sanitized_Request [mooshare] Use sanitized_Request [movieclips] Use sanitized_Request [mtv] Use sanitized_Request [myvideo] Use sanitized_Request [neteasemusic] Use sanitized_Request [nfb] Use sanitized_Request [niconico] Use sanitized_Request [noco] Use sanitized_Request [nosvideo] Use sanitized_Request [novamov] Use sanitized_Request [nowness] Use sanitized_Request [nuvid] Use sanitized_Request [played] Use sanitized_Request [pluralsight] Use sanitized_Request [pornhub] Use sanitized_Request [pornotube] Use sanitized_Request [primesharetv] Use sanitized_Request [promptfile] Use sanitized_Request [qqmusic] Use sanitized_Request [rtve] Use sanitized_Request [safari] Use sanitized_Request [sandia] Use sanitized_Request [shared] Use sanitized_Request [sharesix] Use sanitized_Request [sina] Use sanitized_Request [smotri] Use sanitized_Request [sohu] Use sanitized_Request [spankwire] Use sanitized_Request [sportdeutschland] Use sanitized_Request [streamcloud] Use sanitized_Request [streamcz] Use sanitized_Request [tapely] Use sanitized_Request [tube8] Use sanitized_Request [tubitv] Use sanitized_Request [twitch] Use sanitized_Request [twitter] Use sanitized_Request [udemy] Use sanitized_Request [vbox7] Use sanitized_Request [veoh] Use sanitized_Request [vessel] Use sanitized_Request [vevo] Use sanitized_Request [viddler] Use sanitized_Request [videomega] Use sanitized_Request [viewvster] Use sanitized_Request [viki] Use sanitized_Request [vk] Use sanitized_Request [vodlocker] Use sanitized_Request [voicerepublic] Use sanitized_Request [wistia] Use sanitized_Request [xfileshare] Use sanitized_Request [xtube] Use sanitized_Request [xvideos] Use sanitized_Request [yandexmusic] Use sanitized_Request [youku] Use sanitized_Request [youporn] Use sanitized_Request [youtube] Use sanitized_Request [patreon] Use sanitized_Request [extractor/common] Remove unused import [nfb] PEP 8
9 years ago
Switch codebase to use sanitized_Request instead of compat_urllib_request.Request [downloader/dash] Use sanitized_Request [downloader/http] Use sanitized_Request [atresplayer] Use sanitized_Request [bambuser] Use sanitized_Request [bliptv] Use sanitized_Request [brightcove] Use sanitized_Request [cbs] Use sanitized_Request [ceskatelevize] Use sanitized_Request [collegerama] Use sanitized_Request [extractor/common] Use sanitized_Request [crunchyroll] Use sanitized_Request [dailymotion] Use sanitized_Request [dcn] Use sanitized_Request [dramafever] Use sanitized_Request [dumpert] Use sanitized_Request [eitb] Use sanitized_Request [escapist] Use sanitized_Request [everyonesmixtape] Use sanitized_Request [extremetube] Use sanitized_Request [facebook] Use sanitized_Request [fc2] Use sanitized_Request [flickr] Use sanitized_Request [4tube] Use sanitized_Request [gdcvault] Use sanitized_Request [extractor/generic] Use sanitized_Request [hearthisat] Use sanitized_Request [hotnewhiphop] Use sanitized_Request [hypem] Use sanitized_Request [iprima] Use sanitized_Request [ivi] Use sanitized_Request [keezmovies] Use sanitized_Request [letv] Use sanitized_Request [lynda] Use sanitized_Request [metacafe] Use sanitized_Request [minhateca] Use sanitized_Request [miomio] Use sanitized_Request [meovideo] Use sanitized_Request [mofosex] Use sanitized_Request [moniker] Use sanitized_Request [mooshare] Use sanitized_Request [movieclips] Use sanitized_Request [mtv] Use sanitized_Request [myvideo] Use sanitized_Request [neteasemusic] Use sanitized_Request [nfb] Use sanitized_Request [niconico] Use sanitized_Request [noco] Use sanitized_Request [nosvideo] Use sanitized_Request [novamov] Use sanitized_Request [nowness] Use sanitized_Request [nuvid] Use sanitized_Request [played] Use sanitized_Request [pluralsight] Use sanitized_Request [pornhub] Use sanitized_Request [pornotube] Use sanitized_Request [primesharetv] Use sanitized_Request [promptfile] Use sanitized_Request [qqmusic] Use sanitized_Request [rtve] Use sanitized_Request [safari] Use sanitized_Request [sandia] Use sanitized_Request [shared] Use sanitized_Request [sharesix] Use sanitized_Request [sina] Use sanitized_Request [smotri] Use sanitized_Request [sohu] Use sanitized_Request [spankwire] Use sanitized_Request [sportdeutschland] Use sanitized_Request [streamcloud] Use sanitized_Request [streamcz] Use sanitized_Request [tapely] Use sanitized_Request [tube8] Use sanitized_Request [tubitv] Use sanitized_Request [twitch] Use sanitized_Request [twitter] Use sanitized_Request [udemy] Use sanitized_Request [vbox7] Use sanitized_Request [veoh] Use sanitized_Request [vessel] Use sanitized_Request [vevo] Use sanitized_Request [viddler] Use sanitized_Request [videomega] Use sanitized_Request [viewvster] Use sanitized_Request [viki] Use sanitized_Request [vk] Use sanitized_Request [vodlocker] Use sanitized_Request [voicerepublic] Use sanitized_Request [wistia] Use sanitized_Request [xfileshare] Use sanitized_Request [xtube] Use sanitized_Request [xvideos] Use sanitized_Request [yandexmusic] Use sanitized_Request [youku] Use sanitized_Request [youporn] Use sanitized_Request [youtube] Use sanitized_Request [patreon] Use sanitized_Request [extractor/common] Remove unused import [nfb] PEP 8
9 years ago
Switch codebase to use sanitized_Request instead of compat_urllib_request.Request [downloader/dash] Use sanitized_Request [downloader/http] Use sanitized_Request [atresplayer] Use sanitized_Request [bambuser] Use sanitized_Request [bliptv] Use sanitized_Request [brightcove] Use sanitized_Request [cbs] Use sanitized_Request [ceskatelevize] Use sanitized_Request [collegerama] Use sanitized_Request [extractor/common] Use sanitized_Request [crunchyroll] Use sanitized_Request [dailymotion] Use sanitized_Request [dcn] Use sanitized_Request [dramafever] Use sanitized_Request [dumpert] Use sanitized_Request [eitb] Use sanitized_Request [escapist] Use sanitized_Request [everyonesmixtape] Use sanitized_Request [extremetube] Use sanitized_Request [facebook] Use sanitized_Request [fc2] Use sanitized_Request [flickr] Use sanitized_Request [4tube] Use sanitized_Request [gdcvault] Use sanitized_Request [extractor/generic] Use sanitized_Request [hearthisat] Use sanitized_Request [hotnewhiphop] Use sanitized_Request [hypem] Use sanitized_Request [iprima] Use sanitized_Request [ivi] Use sanitized_Request [keezmovies] Use sanitized_Request [letv] Use sanitized_Request [lynda] Use sanitized_Request [metacafe] Use sanitized_Request [minhateca] Use sanitized_Request [miomio] Use sanitized_Request [meovideo] Use sanitized_Request [mofosex] Use sanitized_Request [moniker] Use sanitized_Request [mooshare] Use sanitized_Request [movieclips] Use sanitized_Request [mtv] Use sanitized_Request [myvideo] Use sanitized_Request [neteasemusic] Use sanitized_Request [nfb] Use sanitized_Request [niconico] Use sanitized_Request [noco] Use sanitized_Request [nosvideo] Use sanitized_Request [novamov] Use sanitized_Request [nowness] Use sanitized_Request [nuvid] Use sanitized_Request [played] Use sanitized_Request [pluralsight] Use sanitized_Request [pornhub] Use sanitized_Request [pornotube] Use sanitized_Request [primesharetv] Use sanitized_Request [promptfile] Use sanitized_Request [qqmusic] Use sanitized_Request [rtve] Use sanitized_Request [safari] Use sanitized_Request [sandia] Use sanitized_Request [shared] Use sanitized_Request [sharesix] Use sanitized_Request [sina] Use sanitized_Request [smotri] Use sanitized_Request [sohu] Use sanitized_Request [spankwire] Use sanitized_Request [sportdeutschland] Use sanitized_Request [streamcloud] Use sanitized_Request [streamcz] Use sanitized_Request [tapely] Use sanitized_Request [tube8] Use sanitized_Request [tubitv] Use sanitized_Request [twitch] Use sanitized_Request [twitter] Use sanitized_Request [udemy] Use sanitized_Request [vbox7] Use sanitized_Request [veoh] Use sanitized_Request [vessel] Use sanitized_Request [vevo] Use sanitized_Request [viddler] Use sanitized_Request [videomega] Use sanitized_Request [viewvster] Use sanitized_Request [viki] Use sanitized_Request [vk] Use sanitized_Request [vodlocker] Use sanitized_Request [voicerepublic] Use sanitized_Request [wistia] Use sanitized_Request [xfileshare] Use sanitized_Request [xtube] Use sanitized_Request [xvideos] Use sanitized_Request [yandexmusic] Use sanitized_Request [youku] Use sanitized_Request [youporn] Use sanitized_Request [youtube] Use sanitized_Request [patreon] Use sanitized_Request [extractor/common] Remove unused import [nfb] PEP 8
9 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. import re
  7. from .common import FileDownloader
  8. from ..compat import compat_urllib_error
  9. from ..utils import (
  10. ContentTooShortError,
  11. encodeFilename,
  12. sanitize_open,
  13. sanitized_Request,
  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. basic_request = sanitized_Request(url, None, headers)
  26. request = sanitized_Request(url, None, headers)
  27. is_test = self.params.get('test', False)
  28. if is_test:
  29. request.add_header('Range', 'bytes=0-%s' % str(self._TEST_FILE_SIZE - 1))
  30. # Establish possible resume length
  31. if os.path.isfile(encodeFilename(tmpfilename)):
  32. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  33. else:
  34. resume_len = 0
  35. open_mode = 'wb'
  36. if resume_len != 0:
  37. if self.params.get('continuedl', True):
  38. self.report_resuming_byte(resume_len)
  39. request.add_header('Range', 'bytes=%d-' % resume_len)
  40. open_mode = 'ab'
  41. else:
  42. resume_len = 0
  43. count = 0
  44. retries = self.params.get('retries', 0)
  45. while count <= retries:
  46. # Establish connection
  47. try:
  48. data = self.ydl.urlopen(request)
  49. # When trying to resume, Content-Range HTTP header of response has to be checked
  50. # to match the value of requested Range HTTP header. This is due to a webservers
  51. # that don't support resuming and serve a whole file with no Content-Range
  52. # set in response despite of requested Range (see
  53. # https://github.com/rg3/youtube-dl/issues/6057#issuecomment-126129799)
  54. if resume_len > 0:
  55. content_range = data.headers.get('Content-Range')
  56. if content_range:
  57. content_range_m = re.search(r'bytes (\d+)-', content_range)
  58. # Content-Range is present and matches requested Range, resume is possible
  59. if content_range_m and resume_len == int(content_range_m.group(1)):
  60. break
  61. # Content-Range is either not present or invalid. Assuming remote webserver is
  62. # trying to send the whole file, resume is not possible, so wiping the local file
  63. # and performing entire redownload
  64. self.report_unable_to_resume()
  65. resume_len = 0
  66. open_mode = 'wb'
  67. break
  68. except (compat_urllib_error.HTTPError, ) as err:
  69. if (err.code < 500 or err.code >= 600) and err.code != 416:
  70. # Unexpected HTTP error
  71. raise
  72. elif err.code == 416:
  73. # Unable to resume (requested range not satisfiable)
  74. try:
  75. # Open the connection again without the range header
  76. data = self.ydl.urlopen(basic_request)
  77. content_length = data.info()['Content-Length']
  78. except (compat_urllib_error.HTTPError, ) as err:
  79. if err.code < 500 or err.code >= 600:
  80. raise
  81. else:
  82. # Examine the reported length
  83. if (content_length is not None and
  84. (resume_len - 100 < int(content_length) < resume_len + 100)):
  85. # The file had already been fully downloaded.
  86. # Explanation to the above condition: in issue #175 it was revealed that
  87. # YouTube sometimes adds or removes a few bytes from the end of the file,
  88. # changing the file size slightly and causing problems for some users. So
  89. # I decided to implement a suggested change and consider the file
  90. # completely downloaded if the file size differs less than 100 bytes from
  91. # the one in the hard drive.
  92. self.report_file_already_downloaded(filename)
  93. self.try_rename(tmpfilename, filename)
  94. self._hook_progress({
  95. 'filename': filename,
  96. 'status': 'finished',
  97. 'downloaded_bytes': resume_len,
  98. 'total_bytes': resume_len,
  99. })
  100. return True
  101. else:
  102. # The length does not match, we start the download over
  103. self.report_unable_to_resume()
  104. resume_len = 0
  105. open_mode = 'wb'
  106. break
  107. except socket.error as e:
  108. if e.errno != errno.ECONNRESET:
  109. # Connection reset is no problem, just retry
  110. raise
  111. # Retry
  112. count += 1
  113. if count <= retries:
  114. self.report_retry(count, retries)
  115. if count > retries:
  116. self.report_error('giving up after %s retries' % retries)
  117. return False
  118. data_len = data.info().get('Content-length', None)
  119. # Range HTTP header may be ignored/unsupported by a webserver
  120. # (e.g. extractor/scivee.py, extractor/bambuser.py).
  121. # However, for a test we still would like to download just a piece of a file.
  122. # To achieve this we limit data_len to _TEST_FILE_SIZE and manually control
  123. # block size when downloading a file.
  124. if is_test and (data_len is None or int(data_len) > self._TEST_FILE_SIZE):
  125. data_len = self._TEST_FILE_SIZE
  126. if data_len is not None:
  127. data_len = int(data_len) + resume_len
  128. min_data_len = self.params.get("min_filesize", None)
  129. max_data_len = self.params.get("max_filesize", None)
  130. if min_data_len is not None and data_len < min_data_len:
  131. self.to_screen('\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
  132. return False
  133. if max_data_len is not None and data_len > max_data_len:
  134. self.to_screen('\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
  135. return False
  136. byte_counter = 0 + resume_len
  137. block_size = self.params.get('buffersize', 1024)
  138. start = time.time()
  139. # measure time over whole while-loop, so slow_down() and best_block_size() work together properly
  140. now = None # needed for slow_down() in the first loop run
  141. before = start # start measuring
  142. while True:
  143. # Download and write
  144. data_block = data.read(block_size if not is_test else min(block_size, data_len - byte_counter))
  145. byte_counter += len(data_block)
  146. # exit loop when download is finished
  147. if len(data_block) == 0:
  148. break
  149. # Open destination file just in time
  150. if stream is None:
  151. try:
  152. (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
  153. assert stream is not None
  154. filename = self.undo_temp_name(tmpfilename)
  155. self.report_destination(filename)
  156. except (OSError, IOError) as err:
  157. self.report_error('unable to open for writing: %s' % str(err))
  158. return False
  159. if self.params.get('xattr_set_filesize', False) and data_len is not None:
  160. try:
  161. import xattr
  162. xattr.setxattr(tmpfilename, 'user.ytdl.filesize', str(data_len))
  163. except(OSError, IOError, ImportError) as err:
  164. self.report_error('unable to set filesize xattr: %s' % str(err))
  165. try:
  166. stream.write(data_block)
  167. except (IOError, OSError) as err:
  168. self.to_stderr('\n')
  169. self.report_error('unable to write data: %s' % str(err))
  170. return False
  171. # Apply rate limit
  172. self.slow_down(start, now, byte_counter - resume_len)
  173. # end measuring of one loop run
  174. now = time.time()
  175. after = now
  176. # Adjust block size
  177. if not self.params.get('noresizebuffer', False):
  178. block_size = self.best_block_size(after - before, len(data_block))
  179. before = after
  180. # Progress message
  181. speed = self.calc_speed(start, now, byte_counter - resume_len)
  182. if data_len is None:
  183. eta = None
  184. else:
  185. eta = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  186. self._hook_progress({
  187. 'status': 'downloading',
  188. 'downloaded_bytes': byte_counter,
  189. 'total_bytes': data_len,
  190. 'tmpfilename': tmpfilename,
  191. 'filename': filename,
  192. 'eta': eta,
  193. 'speed': speed,
  194. 'elapsed': now - start,
  195. })
  196. if is_test and byte_counter == data_len:
  197. break
  198. if stream is None:
  199. self.to_stderr('\n')
  200. self.report_error('Did not get any data blocks')
  201. return False
  202. if tmpfilename != '-':
  203. stream.close()
  204. if data_len is not None and byte_counter != data_len:
  205. raise ContentTooShortError(byte_counter, int(data_len))
  206. self.try_rename(tmpfilename, filename)
  207. # Update file modification time
  208. if self.params.get('updatetime', True):
  209. info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
  210. self._hook_progress({
  211. 'downloaded_bytes': byte_counter,
  212. 'total_bytes': byte_counter,
  213. 'filename': filename,
  214. 'status': 'finished',
  215. 'elapsed': time.time() - start,
  216. })
  217. return True