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.

298 lines
13 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
  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. class DownloadContext(dict):
  22. __getattr__ = dict.get
  23. __setattr__ = dict.__setitem__
  24. __delattr__ = dict.__delitem__
  25. ctx = DownloadContext()
  26. ctx.filename = filename
  27. ctx.tmpfilename = self.temp_name(filename)
  28. ctx.stream = None
  29. # Do not include the Accept-Encoding header
  30. headers = {'Youtubedl-no-compression': 'True'}
  31. add_headers = info_dict.get('http_headers')
  32. if add_headers:
  33. headers.update(add_headers)
  34. basic_request = sanitized_Request(url, None, headers)
  35. request = sanitized_Request(url, None, headers)
  36. is_test = self.params.get('test', False)
  37. if is_test:
  38. request.add_header('Range', 'bytes=0-%s' % str(self._TEST_FILE_SIZE - 1))
  39. ctx.open_mode = 'wb'
  40. ctx.resume_len = 0
  41. if self.params.get('continuedl', True):
  42. # Establish possible resume length
  43. if os.path.isfile(encodeFilename(ctx.tmpfilename)):
  44. ctx.resume_len = os.path.getsize(encodeFilename(ctx.tmpfilename))
  45. count = 0
  46. retries = self.params.get('retries', 0)
  47. class SucceedDownload(Exception):
  48. pass
  49. class RetryDownload(Exception):
  50. def __init__(self, source_error):
  51. self.source_error = source_error
  52. def establish_connection():
  53. if ctx.resume_len != 0:
  54. self.report_resuming_byte(ctx.resume_len)
  55. request.add_header('Range', 'bytes=%d-' % ctx.resume_len)
  56. ctx.open_mode = 'ab'
  57. # Establish connection
  58. try:
  59. ctx.data = self.ydl.urlopen(request)
  60. # When trying to resume, Content-Range HTTP header of response has to be checked
  61. # to match the value of requested Range HTTP header. This is due to a webservers
  62. # that don't support resuming and serve a whole file with no Content-Range
  63. # set in response despite of requested Range (see
  64. # https://github.com/rg3/youtube-dl/issues/6057#issuecomment-126129799)
  65. if ctx.resume_len > 0:
  66. content_range = ctx.data.headers.get('Content-Range')
  67. if content_range:
  68. content_range_m = re.search(r'bytes (\d+)-', content_range)
  69. # Content-Range is present and matches requested Range, resume is possible
  70. if content_range_m and ctx.resume_len == int(content_range_m.group(1)):
  71. return
  72. # Content-Range is either not present or invalid. Assuming remote webserver is
  73. # trying to send the whole file, resume is not possible, so wiping the local file
  74. # and performing entire redownload
  75. self.report_unable_to_resume()
  76. ctx.resume_len = 0
  77. ctx.open_mode = 'wb'
  78. return
  79. except (compat_urllib_error.HTTPError, ) as err:
  80. if (err.code < 500 or err.code >= 600) and err.code != 416:
  81. # Unexpected HTTP error
  82. raise
  83. elif err.code == 416:
  84. # Unable to resume (requested range not satisfiable)
  85. try:
  86. # Open the connection again without the range header
  87. ctx.data = self.ydl.urlopen(basic_request)
  88. content_length = ctx.data.info()['Content-Length']
  89. except (compat_urllib_error.HTTPError, ) as err:
  90. if err.code < 500 or err.code >= 600:
  91. raise
  92. else:
  93. # Examine the reported length
  94. if (content_length is not None and
  95. (ctx.resume_len - 100 < int(content_length) < ctx.resume_len + 100)):
  96. # The file had already been fully downloaded.
  97. # Explanation to the above condition: in issue #175 it was revealed that
  98. # YouTube sometimes adds or removes a few bytes from the end of the file,
  99. # changing the file size slightly and causing problems for some users. So
  100. # I decided to implement a suggested change and consider the file
  101. # completely downloaded if the file size differs less than 100 bytes from
  102. # the one in the hard drive.
  103. self.report_file_already_downloaded(ctx.filename)
  104. self.try_rename(ctx.tmpfilename, ctx.filename)
  105. self._hook_progress({
  106. 'filename': ctx.filename,
  107. 'status': 'finished',
  108. 'downloaded_bytes': ctx.resume_len,
  109. 'total_bytes': ctx.resume_len,
  110. })
  111. raise SucceedDownload()
  112. else:
  113. # The length does not match, we start the download over
  114. self.report_unable_to_resume()
  115. ctx.resume_len = 0
  116. ctx.open_mode = 'wb'
  117. return
  118. raise RetryDownload(err)
  119. except socket.error as err:
  120. if err.errno != errno.ECONNRESET:
  121. # Connection reset is no problem, just retry
  122. raise
  123. raise RetryDownload(err)
  124. def download():
  125. data_len = ctx.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) + ctx.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 + ctx.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. def retry(e):
  150. if ctx.tmpfilename != '-':
  151. ctx.stream.close()
  152. ctx.stream = None
  153. ctx.resume_len = os.path.getsize(encodeFilename(ctx.tmpfilename))
  154. raise RetryDownload(e)
  155. while True:
  156. try:
  157. # Download and write
  158. data_block = ctx.data.read(block_size if not is_test else min(block_size, data_len - byte_counter))
  159. # socket.timeout is a subclass of socket.error but may not have
  160. # errno set
  161. except socket.timeout as e:
  162. retry(e)
  163. except socket.error as e:
  164. if e.errno not in (errno.ECONNRESET, errno.ETIMEDOUT):
  165. raise
  166. retry(e)
  167. byte_counter += len(data_block)
  168. # exit loop when download is finished
  169. if len(data_block) == 0:
  170. break
  171. # Open destination file just in time
  172. if ctx.stream is None:
  173. try:
  174. ctx.stream, ctx.tmpfilename = sanitize_open(
  175. ctx.tmpfilename, ctx.open_mode)
  176. assert ctx.stream is not None
  177. ctx.filename = self.undo_temp_name(ctx.tmpfilename)
  178. self.report_destination(ctx.filename)
  179. except (OSError, IOError) as err:
  180. self.report_error('unable to open for writing: %s' % str(err))
  181. return False
  182. if self.params.get('xattr_set_filesize', False) and data_len is not None:
  183. try:
  184. write_xattr(ctx.tmpfilename, 'user.ytdl.filesize', str(data_len).encode('utf-8'))
  185. except (XAttrUnavailableError, XAttrMetadataError) as err:
  186. self.report_error('unable to set filesize xattr: %s' % str(err))
  187. try:
  188. ctx.stream.write(data_block)
  189. except (IOError, OSError) as err:
  190. self.to_stderr('\n')
  191. self.report_error('unable to write data: %s' % str(err))
  192. return False
  193. # Apply rate limit
  194. self.slow_down(start, now, byte_counter - ctx.resume_len)
  195. # end measuring of one loop run
  196. now = time.time()
  197. after = now
  198. # Adjust block size
  199. if not self.params.get('noresizebuffer', False):
  200. block_size = self.best_block_size(after - before, len(data_block))
  201. before = after
  202. # Progress message
  203. speed = self.calc_speed(start, now, byte_counter - ctx.resume_len)
  204. if data_len is None:
  205. eta = None
  206. else:
  207. eta = self.calc_eta(start, time.time(), data_len - ctx.resume_len, byte_counter - ctx.resume_len)
  208. self._hook_progress({
  209. 'status': 'downloading',
  210. 'downloaded_bytes': byte_counter,
  211. 'total_bytes': data_len,
  212. 'tmpfilename': ctx.tmpfilename,
  213. 'filename': ctx.filename,
  214. 'eta': eta,
  215. 'speed': speed,
  216. 'elapsed': now - start,
  217. })
  218. if is_test and byte_counter == data_len:
  219. break
  220. if ctx.stream is None:
  221. self.to_stderr('\n')
  222. self.report_error('Did not get any data blocks')
  223. return False
  224. if ctx.tmpfilename != '-':
  225. ctx.stream.close()
  226. if data_len is not None and byte_counter != data_len:
  227. err = ContentTooShortError(byte_counter, int(data_len))
  228. if count <= retries:
  229. retry(err)
  230. raise err
  231. self.try_rename(ctx.tmpfilename, ctx.filename)
  232. # Update file modification time
  233. if self.params.get('updatetime', True):
  234. info_dict['filetime'] = self.try_utime(ctx.filename, ctx.data.info().get('last-modified', None))
  235. self._hook_progress({
  236. 'downloaded_bytes': byte_counter,
  237. 'total_bytes': byte_counter,
  238. 'filename': ctx.filename,
  239. 'status': 'finished',
  240. 'elapsed': time.time() - start,
  241. })
  242. return True
  243. while count <= retries:
  244. try:
  245. establish_connection()
  246. download()
  247. return True
  248. except RetryDownload as e:
  249. count += 1
  250. if count <= retries:
  251. self.report_retry(e.source_error, count, retries)
  252. continue
  253. except SucceedDownload:
  254. return True
  255. self.report_error('giving up after %s retries' % retries)
  256. return False