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.

257 lines
11 KiB

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