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.

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