2014-06-19 09:04:37 +02:00
|
|
|
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
|
|
|
|
|
2016-01-04 07:12:39 +01:00
|
|
|
# Copyright 2014-2016 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
|
2014-06-10 22:11:17 +02:00
|
|
|
#
|
|
|
|
# This file is part of qutebrowser.
|
|
|
|
#
|
|
|
|
# qutebrowser is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# qutebrowser is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with qutebrowser. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
|
|
|
"""Download manager."""
|
|
|
|
|
2014-11-30 15:25:23 +01:00
|
|
|
import io
|
2014-06-13 12:19:30 +02:00
|
|
|
import os
|
2015-01-03 17:50:59 +01:00
|
|
|
import sys
|
2016-08-02 19:40:57 +02:00
|
|
|
import shlex
|
2014-06-10 22:11:17 +02:00
|
|
|
import os.path
|
2014-11-30 15:25:23 +01:00
|
|
|
import shutil
|
2014-08-26 19:10:14 +02:00
|
|
|
import functools
|
2016-07-05 23:01:48 +02:00
|
|
|
import tempfile
|
2014-08-26 19:10:14 +02:00
|
|
|
import collections
|
2014-06-10 22:11:17 +02:00
|
|
|
|
2016-03-31 19:09:43 +02:00
|
|
|
import sip
|
2014-10-08 20:18:44 +02:00
|
|
|
from PyQt5.QtCore import (pyqtSlot, pyqtSignal, QObject, QTimer,
|
2015-02-22 19:13:51 +01:00
|
|
|
Qt, QVariant, QAbstractListModel, QModelIndex, QUrl)
|
2014-12-10 20:48:19 +01:00
|
|
|
from PyQt5.QtGui import QDesktopServices
|
2014-06-19 17:58:46 +02:00
|
|
|
from PyQt5.QtNetwork import QNetworkRequest, QNetworkReply
|
2014-06-10 22:11:17 +02:00
|
|
|
|
2014-08-26 19:10:14 +02:00
|
|
|
from qutebrowser.config import config
|
2014-08-26 20:48:39 +02:00
|
|
|
from qutebrowser.commands import cmdexc, cmdutils
|
2014-12-13 17:28:50 +01:00
|
|
|
from qutebrowser.utils import (message, usertypes, log, utils, urlutils,
|
2014-10-08 20:18:44 +02:00
|
|
|
objreg, standarddir, qtutils)
|
2016-08-02 19:40:57 +02:00
|
|
|
from qutebrowser.misc import guiprocess
|
2016-06-13 10:49:58 +02:00
|
|
|
from qutebrowser.browser.webkit import http
|
|
|
|
from qutebrowser.browser.webkit.network import networkmanager
|
2014-10-08 20:18:44 +02:00
|
|
|
|
|
|
|
|
|
|
|
ModelRole = usertypes.enum('ModelRole', ['item'], start=Qt.UserRole,
|
|
|
|
is_int=True)
|
2014-06-10 22:11:17 +02:00
|
|
|
|
|
|
|
|
2014-12-10 21:56:57 +01:00
|
|
|
RetryInfo = collections.namedtuple('RetryInfo', ['request', 'manager'])
|
|
|
|
|
2016-04-27 18:30:54 +02:00
|
|
|
DownloadPath = collections.namedtuple('DownloadPath', ['filename', 'question'])
|
2015-11-11 23:45:53 +01:00
|
|
|
|
2015-08-01 14:19:06 +02:00
|
|
|
# Remember the last used directory
|
2015-10-19 20:08:37 +02:00
|
|
|
last_used_directory = None
|
2015-08-01 14:19:06 +02:00
|
|
|
|
2014-12-10 21:56:57 +01:00
|
|
|
|
2015-06-07 22:22:23 +02:00
|
|
|
# All REFRESH_INTERVAL milliseconds, speeds will be recalculated and downloads
|
|
|
|
# redrawn.
|
|
|
|
REFRESH_INTERVAL = 500
|
|
|
|
|
|
|
|
|
2015-10-19 20:08:37 +02:00
|
|
|
def download_dir():
|
2015-03-03 23:36:12 +01:00
|
|
|
"""Get the download directory to use."""
|
|
|
|
directory = config.get('storage', 'download-directory')
|
2015-08-01 14:19:06 +02:00
|
|
|
remember_dir = config.get('storage', 'remember-download-directory')
|
|
|
|
|
2015-10-19 20:08:37 +02:00
|
|
|
if remember_dir and last_used_directory is not None:
|
|
|
|
return last_used_directory
|
2015-08-01 14:19:06 +02:00
|
|
|
elif directory is None:
|
|
|
|
return standarddir.download()
|
|
|
|
else:
|
|
|
|
return directory
|
2015-03-03 23:36:12 +01:00
|
|
|
|
|
|
|
|
2015-09-24 12:38:52 +02:00
|
|
|
def path_suggestion(filename):
|
2015-03-26 07:08:13 +01:00
|
|
|
"""Get the suggested file path.
|
2015-03-04 23:05:23 +01:00
|
|
|
|
|
|
|
Args:
|
|
|
|
filename: The filename to use if included in the suggestion.
|
|
|
|
"""
|
2015-03-03 23:36:12 +01:00
|
|
|
suggestion = config.get('completion', 'download-path-suggestion')
|
|
|
|
if suggestion == 'path':
|
2015-03-05 20:33:02 +01:00
|
|
|
# add trailing '/' if not present
|
2015-10-19 20:08:37 +02:00
|
|
|
return os.path.join(download_dir(), '')
|
2015-03-03 23:36:12 +01:00
|
|
|
elif suggestion == 'filename':
|
|
|
|
return filename
|
|
|
|
elif suggestion == 'both':
|
2015-10-19 20:08:37 +02:00
|
|
|
return os.path.join(download_dir(), filename)
|
2016-04-05 11:43:01 +02:00
|
|
|
else: # pragma: no cover
|
2015-03-03 23:36:12 +01:00
|
|
|
raise ValueError("Invalid suggestion value {}!".format(suggestion))
|
|
|
|
|
|
|
|
|
2015-10-19 20:08:37 +02:00
|
|
|
def create_full_filename(basename, filename):
|
|
|
|
"""Create a full filename based on the given basename and filename.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
basename: The basename to use if filename is a directory.
|
|
|
|
filename: The path to a folder or file where you want to save.
|
|
|
|
|
|
|
|
Return:
|
|
|
|
The full absolute path, or None if filename creation was not possible.
|
|
|
|
"""
|
2016-04-10 20:16:10 +02:00
|
|
|
# Remove chars which can't be encoded in the filename encoding.
|
|
|
|
# See https://github.com/The-Compiler/qutebrowser/issues/427
|
|
|
|
encoding = sys.getfilesystemencoding()
|
|
|
|
filename = utils.force_encoding(filename, encoding)
|
|
|
|
basename = utils.force_encoding(basename, encoding)
|
2015-10-19 20:08:37 +02:00
|
|
|
if os.path.isabs(filename) and os.path.isdir(filename):
|
|
|
|
# We got an absolute directory from the user, so we save it under
|
|
|
|
# the default filename in that directory.
|
|
|
|
return os.path.join(filename, basename)
|
|
|
|
elif os.path.isabs(filename):
|
|
|
|
# We got an absolute filename from the user, so we save it under
|
|
|
|
# that filename.
|
|
|
|
return filename
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
2015-11-11 23:45:53 +01:00
|
|
|
def ask_for_filename(suggested_filename, win_id, *, parent=None,
|
|
|
|
prompt_download_directory=None):
|
|
|
|
"""Prepare a question for a download-path.
|
|
|
|
|
|
|
|
If a filename can be determined directly, it is returned instead.
|
|
|
|
|
|
|
|
Returns a (filename, question)-namedtuple, in which one component is
|
|
|
|
None. filename is a string, question is a usertypes.Question. The
|
|
|
|
question has a special .ask() method that takes no arguments for
|
|
|
|
convenience, as this function does not yet ask the question, it
|
|
|
|
only prepares it.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
suggested_filename: The "default"-name that is pre-entered as path.
|
|
|
|
win_id: The window where the question will be asked.
|
|
|
|
parent: The parent of the question (a QObject).
|
|
|
|
prompt_download_directory: If this is something else than None, it
|
|
|
|
will overwrite the
|
|
|
|
storage->prompt-download-directory setting.
|
|
|
|
"""
|
|
|
|
if prompt_download_directory is None:
|
|
|
|
prompt_download_directory = config.get('storage',
|
|
|
|
'prompt-download-directory')
|
|
|
|
|
|
|
|
if not prompt_download_directory:
|
2015-11-21 00:10:49 +01:00
|
|
|
return DownloadPath(filename=download_dir(), question=None)
|
2015-11-11 23:45:53 +01:00
|
|
|
|
|
|
|
encoding = sys.getfilesystemencoding()
|
2016-04-27 18:30:54 +02:00
|
|
|
suggested_filename = utils.force_encoding(suggested_filename, encoding)
|
2015-11-11 23:45:53 +01:00
|
|
|
|
|
|
|
q = usertypes.Question(parent)
|
|
|
|
q.text = "Save file to:"
|
|
|
|
q.mode = usertypes.PromptMode.text
|
|
|
|
q.completed.connect(q.deleteLater)
|
|
|
|
q.default = path_suggestion(suggested_filename)
|
|
|
|
|
|
|
|
message_bridge = objreg.get('message-bridge', scope='window',
|
|
|
|
window=win_id)
|
|
|
|
q.ask = lambda: message_bridge.ask(q, blocking=False)
|
2015-11-21 00:10:49 +01:00
|
|
|
return DownloadPath(filename=None, question=q)
|
2015-11-11 23:45:53 +01:00
|
|
|
|
|
|
|
|
2014-11-27 21:35:39 +01:00
|
|
|
class DownloadItemStats(QObject):
|
2014-06-11 17:27:39 +02:00
|
|
|
|
2014-11-27 21:35:39 +01:00
|
|
|
"""Statistics (bytes done, total bytes, time, etc.) about a download.
|
2014-06-11 17:27:39 +02:00
|
|
|
|
2014-06-11 21:55:23 +02:00
|
|
|
Class attributes:
|
2014-06-13 21:53:06 +02:00
|
|
|
SPEED_AVG_WINDOW: How many seconds of speed data to average to
|
|
|
|
estimate the remaining time.
|
2014-11-27 21:35:39 +01:00
|
|
|
|
|
|
|
Attributes:
|
|
|
|
done: How many bytes there are already downloaded.
|
|
|
|
total: The total count of bytes. None if the total is unknown.
|
|
|
|
speed: The current download speed, in bytes per second.
|
|
|
|
_speed_avg: A rolling average of speeds.
|
|
|
|
_last_done: The count of bytes which where downloaded when calculating
|
|
|
|
the speed the last time.
|
|
|
|
"""
|
|
|
|
|
|
|
|
SPEED_AVG_WINDOW = 30
|
|
|
|
|
|
|
|
def __init__(self, parent=None):
|
|
|
|
super().__init__(parent)
|
|
|
|
self.total = None
|
|
|
|
self.done = 0
|
|
|
|
self.speed = 0
|
|
|
|
self._last_done = 0
|
2015-06-07 22:22:23 +02:00
|
|
|
samples = int(self.SPEED_AVG_WINDOW * (1000 / REFRESH_INTERVAL))
|
2014-11-27 21:35:39 +01:00
|
|
|
self._speed_avg = collections.deque(maxlen=samples)
|
|
|
|
|
2015-06-07 22:22:23 +02:00
|
|
|
def update_speed(self):
|
|
|
|
"""Recalculate the current download speed.
|
|
|
|
|
|
|
|
The caller needs to guarantee this is called all REFRESH_INTERVAL ms.
|
|
|
|
"""
|
2015-08-06 20:57:40 +02:00
|
|
|
if self.done is None:
|
|
|
|
# this can happen for very fast downloads, e.g. when actually
|
|
|
|
# opening a file
|
|
|
|
return
|
2014-11-27 21:35:39 +01:00
|
|
|
delta = self.done - self._last_done
|
2015-06-07 22:22:23 +02:00
|
|
|
self.speed = delta * 1000 / REFRESH_INTERVAL
|
2014-11-27 21:35:39 +01:00
|
|
|
self._speed_avg.append(self.speed)
|
|
|
|
self._last_done = self.done
|
|
|
|
|
|
|
|
def finish(self):
|
|
|
|
"""Set the download stats as finished."""
|
|
|
|
self.done = self.total
|
|
|
|
|
|
|
|
def percentage(self):
|
|
|
|
"""The current download percentage, or None if unknown."""
|
2015-08-06 20:57:40 +02:00
|
|
|
if self.done == self.total:
|
|
|
|
return 100
|
|
|
|
elif self.total == 0 or self.total is None:
|
2014-11-27 21:35:39 +01:00
|
|
|
return None
|
|
|
|
else:
|
|
|
|
return 100 * self.done / self.total
|
|
|
|
|
|
|
|
def remaining_time(self):
|
|
|
|
"""The remaining download time in seconds, or None."""
|
|
|
|
if self.total is None or not self._speed_avg:
|
|
|
|
# No average yet or we don't know the total size.
|
|
|
|
return None
|
|
|
|
remaining_bytes = self.total - self.done
|
|
|
|
avg = sum(self._speed_avg) / len(self._speed_avg)
|
|
|
|
if avg == 0:
|
|
|
|
# Download stalled
|
|
|
|
return None
|
|
|
|
else:
|
|
|
|
return remaining_bytes / avg
|
|
|
|
|
2016-04-26 20:20:29 +02:00
|
|
|
@pyqtSlot('qint64', 'qint64')
|
2014-11-27 21:35:39 +01:00
|
|
|
def on_download_progress(self, bytes_done, bytes_total):
|
2015-06-07 16:37:25 +02:00
|
|
|
"""Update local variables when the download progress changed.
|
2014-11-27 21:35:39 +01:00
|
|
|
|
|
|
|
Args:
|
|
|
|
bytes_done: How many bytes are downloaded.
|
|
|
|
bytes_total: How many bytes there are to download in total.
|
|
|
|
"""
|
|
|
|
if bytes_total == -1:
|
|
|
|
bytes_total = None
|
|
|
|
self.done = bytes_done
|
|
|
|
self.total = bytes_total
|
|
|
|
|
|
|
|
|
|
|
|
class DownloadItem(QObject):
|
|
|
|
|
|
|
|
"""A single download currently running.
|
|
|
|
|
2014-11-30 15:25:23 +01:00
|
|
|
There are multiple ways the data can flow from the QNetworkReply to the
|
|
|
|
disk.
|
|
|
|
|
|
|
|
If the filename/file object is known immediately when starting the
|
|
|
|
download, QNetworkReply's readyRead writes to the target file directly.
|
|
|
|
|
|
|
|
If not, readyRead is ignored and with self._read_timer we periodically read
|
|
|
|
into the self._buffer BytesIO slowly, so some broken servers don't close
|
|
|
|
our connection.
|
|
|
|
|
|
|
|
As soon as we know the file object, we copy self._buffer over and the next
|
|
|
|
readyRead will write to the real file object.
|
|
|
|
|
2014-11-27 21:35:39 +01:00
|
|
|
Class attributes:
|
2014-11-24 00:12:19 +01:00
|
|
|
MAX_REDIRECTS: The maximum redirection count.
|
2014-06-11 21:55:23 +02:00
|
|
|
|
2014-06-11 17:27:39 +02:00
|
|
|
Attributes:
|
2014-12-10 20:48:19 +01:00
|
|
|
done: Whether the download is finished.
|
2014-11-27 21:35:39 +01:00
|
|
|
stats: A DownloadItemStats object.
|
2015-02-12 20:43:13 +01:00
|
|
|
index: The index of the download in the view.
|
2015-03-31 20:49:29 +02:00
|
|
|
successful: Whether the download has completed successfully.
|
2014-10-20 00:33:52 +02:00
|
|
|
error_msg: The current error message, or None
|
2014-11-14 08:26:43 +01:00
|
|
|
autoclose: Whether to close the associated file if the download is
|
|
|
|
done.
|
2014-11-14 08:27:35 +01:00
|
|
|
fileobj: The file object to download the file to.
|
2014-11-30 18:14:48 +01:00
|
|
|
reply: The QNetworkReply associated with this download.
|
2015-01-25 23:53:23 +01:00
|
|
|
retry_info: A RetryInfo instance.
|
2015-09-19 20:06:15 +02:00
|
|
|
raw_headers: The headers sent by the server.
|
2014-09-24 22:17:53 +02:00
|
|
|
_filename: The filename of the download.
|
2014-11-24 00:12:19 +01:00
|
|
|
_redirects: How many time we were redirected already.
|
2014-11-30 15:25:23 +01:00
|
|
|
_buffer: A BytesIO object to buffer incoming data until we know the
|
|
|
|
target file.
|
2015-02-05 07:17:58 +01:00
|
|
|
_read_timer: A Timer which reads the QNetworkReply into self._buffer
|
2014-11-30 15:25:23 +01:00
|
|
|
periodically.
|
2014-12-26 21:58:45 +01:00
|
|
|
_win_id: The window ID the DownloadItem runs in.
|
tests: fix tests for downloads bdd test
The test was failing because of two reasons:
First, the old code had filename questions in DownloadManager.get and
DownloadManager.fetch which were almost identical, thus the part in
DownloadManager.get was removed in an earlier commit. All filename
asking is now done by DownloadManager.fetch. The good part is code
deduplication, the bad part is slightly modified behavior: The new code
doesn't wait for a filename to start the download, instead it tries to
fill the buffer immediately. This made the test fail because qute:// has
no registered handler, so in order for the test to pass now, the "no
crash" part is not enough, we also need to expect the "No handler"
error.
Secondly, and a rather rare (race) condition was the handling of errors
in the DownloadItem. If an error occured after the registration of
self.on_reply_error as error handler and before the check
reply.error() != QNetworkReply.NoError
at the end of the function, the error signal would be emitted twice:
Once by _die() (called by on_reply_error), and once by the init_reply
function directly (in the last if block). This lead to duplicated error
messages. This is also explained in a comment in the file (with small
"stack traces").
2016-07-07 00:08:13 +02:00
|
|
|
_dead: Whether the Download has _die()'d.
|
2014-06-11 22:33:40 +02:00
|
|
|
|
|
|
|
Signals:
|
2014-06-12 23:29:34 +02:00
|
|
|
data_changed: The downloads metadata changed.
|
2014-06-12 08:02:44 +02:00
|
|
|
finished: The download was finished.
|
2014-06-13 18:17:27 +02:00
|
|
|
cancelled: The download was cancelled.
|
2015-03-31 20:49:29 +02:00
|
|
|
error: An error with the download occurred.
|
2014-06-12 17:50:09 +02:00
|
|
|
arg: The error message as string.
|
2014-11-24 00:12:19 +01:00
|
|
|
redirected: Signal emitted when a download was redirected.
|
|
|
|
arg 0: The new QNetworkRequest.
|
|
|
|
arg 1: The old QNetworkReply.
|
2015-03-09 07:39:40 +01:00
|
|
|
do_retry: Emitted when a download is retried.
|
|
|
|
arg 0: The new DownloadItem
|
2014-06-11 17:27:39 +02:00
|
|
|
"""
|
|
|
|
|
2014-12-01 06:55:15 +01:00
|
|
|
MAX_REDIRECTS = 10
|
2014-06-12 23:29:34 +02:00
|
|
|
data_changed = pyqtSignal()
|
2014-06-12 08:02:44 +02:00
|
|
|
finished = pyqtSignal()
|
2014-06-12 17:50:09 +02:00
|
|
|
error = pyqtSignal(str)
|
2014-06-13 18:17:27 +02:00
|
|
|
cancelled = pyqtSignal()
|
2014-11-24 00:12:19 +01:00
|
|
|
redirected = pyqtSignal(QNetworkRequest, QNetworkReply)
|
2015-03-09 07:39:40 +01:00
|
|
|
do_retry = pyqtSignal(object) # DownloadItem
|
2014-06-11 21:55:23 +02:00
|
|
|
|
2014-12-28 02:00:31 +01:00
|
|
|
def __init__(self, reply, win_id, parent=None):
|
2014-06-11 21:55:23 +02:00
|
|
|
"""Constructor.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
reply: The QNetworkReply to download.
|
|
|
|
"""
|
2014-06-11 17:27:39 +02:00
|
|
|
super().__init__(parent)
|
2015-01-25 23:53:23 +01:00
|
|
|
self.retry_info = None
|
2014-12-10 20:48:19 +01:00
|
|
|
self.done = False
|
2014-11-27 21:35:39 +01:00
|
|
|
self.stats = DownloadItemStats(self)
|
2015-02-12 20:43:13 +01:00
|
|
|
self.index = 0
|
2014-11-18 20:10:57 +01:00
|
|
|
self.autoclose = True
|
2014-11-30 18:14:48 +01:00
|
|
|
self.reply = None
|
2014-11-30 15:25:23 +01:00
|
|
|
self._buffer = io.BytesIO()
|
2015-02-05 07:17:58 +01:00
|
|
|
self._read_timer = usertypes.Timer(self, name='download-read-timer')
|
2014-11-30 15:25:23 +01:00
|
|
|
self._read_timer.setInterval(500)
|
|
|
|
self._read_timer.timeout.connect(self.on_read_timer_timeout)
|
2014-11-24 00:12:19 +01:00
|
|
|
self._redirects = 0
|
2014-10-20 00:33:52 +02:00
|
|
|
self.error_msg = None
|
2014-06-12 23:29:34 +02:00
|
|
|
self.basename = '???'
|
2014-11-14 08:25:54 +01:00
|
|
|
self.successful = False
|
2014-11-14 08:27:35 +01:00
|
|
|
self.fileobj = None
|
2014-09-24 22:17:53 +02:00
|
|
|
self._filename = None
|
2014-11-24 00:12:19 +01:00
|
|
|
self.init_reply(reply)
|
2014-12-28 02:00:31 +01:00
|
|
|
self._win_id = win_id
|
2015-09-19 20:06:15 +02:00
|
|
|
self.raw_headers = {}
|
tests: fix tests for downloads bdd test
The test was failing because of two reasons:
First, the old code had filename questions in DownloadManager.get and
DownloadManager.fetch which were almost identical, thus the part in
DownloadManager.get was removed in an earlier commit. All filename
asking is now done by DownloadManager.fetch. The good part is code
deduplication, the bad part is slightly modified behavior: The new code
doesn't wait for a filename to start the download, instead it tries to
fill the buffer immediately. This made the test fail because qute:// has
no registered handler, so in order for the test to pass now, the "no
crash" part is not enough, we also need to expect the "No handler"
error.
Secondly, and a rather rare (race) condition was the handling of errors
in the DownloadItem. If an error occured after the registration of
self.on_reply_error as error handler and before the check
reply.error() != QNetworkReply.NoError
at the end of the function, the error signal would be emitted twice:
Once by _die() (called by on_reply_error), and once by the init_reply
function directly (in the last if block). This lead to duplicated error
messages. This is also explained in a comment in the file (with small
"stack traces").
2016-07-07 00:08:13 +02:00
|
|
|
self._dead = False
|
2014-06-11 21:55:23 +02:00
|
|
|
|
2014-06-17 11:03:42 +02:00
|
|
|
def __repr__(self):
|
2014-09-26 15:48:24 +02:00
|
|
|
return utils.get_repr(self, basename=self.basename)
|
2014-06-17 11:03:42 +02:00
|
|
|
|
2014-06-12 23:29:34 +02:00
|
|
|
def __str__(self):
|
|
|
|
"""Get the download as a string.
|
|
|
|
|
2014-06-13 07:49:21 +02:00
|
|
|
Example: foo.pdf [699.2kB/s|0.34|16%|4.253/25.124]
|
2014-06-12 23:29:34 +02:00
|
|
|
"""
|
2014-11-27 21:35:39 +01:00
|
|
|
speed = utils.format_size(self.stats.speed, suffix='B/s')
|
|
|
|
down = utils.format_size(self.stats.done, suffix='B')
|
|
|
|
perc = self.stats.percentage()
|
|
|
|
remaining = self.stats.remaining_time()
|
2014-10-20 00:33:52 +02:00
|
|
|
if self.error_msg is None:
|
2014-10-15 21:22:53 +02:00
|
|
|
errmsg = ""
|
|
|
|
else:
|
2014-10-20 00:33:52 +02:00
|
|
|
errmsg = " - {}".format(self.error_msg)
|
2016-07-12 22:05:32 +02:00
|
|
|
if all(e is None for e in [perc, remaining, self.stats.total]):
|
2015-02-12 20:43:13 +01:00
|
|
|
return ('{index}: {name} [{speed:>10}|{down}]{errmsg}'.format(
|
|
|
|
index=self.index, name=self.basename, speed=speed,
|
|
|
|
down=down, errmsg=errmsg))
|
2016-09-09 17:00:13 +02:00
|
|
|
perc = round(perc)
|
2014-09-02 21:54:07 +02:00
|
|
|
if remaining is None:
|
|
|
|
remaining = '?'
|
|
|
|
else:
|
|
|
|
remaining = utils.format_seconds(remaining)
|
2014-11-27 21:35:39 +01:00
|
|
|
total = utils.format_size(self.stats.total, suffix='B')
|
2014-12-10 20:48:19 +01:00
|
|
|
if self.done:
|
2015-02-12 20:43:13 +01:00
|
|
|
return ('{index}: {name} [{perc:>2}%|{total}]{errmsg}'.format(
|
|
|
|
index=self.index, name=self.basename, perc=perc,
|
|
|
|
total=total, errmsg=errmsg))
|
2014-12-10 20:48:19 +01:00
|
|
|
else:
|
2015-02-12 20:43:13 +01:00
|
|
|
return ('{index}: {name} [{speed:>10}|{remaining:>5}|{perc:>2}%|'
|
2014-12-10 20:48:19 +01:00
|
|
|
'{down}/{total}]{errmsg}'.format(
|
2015-02-12 20:43:13 +01:00
|
|
|
index=self.index, name=self.basename, speed=speed,
|
|
|
|
remaining=remaining, perc=perc, down=down,
|
|
|
|
total=total, errmsg=errmsg))
|
2014-06-12 23:29:34 +02:00
|
|
|
|
2014-12-26 21:58:45 +01:00
|
|
|
def _create_fileobj(self):
|
2015-03-26 07:08:13 +01:00
|
|
|
"""Create a file object using the internal filename."""
|
2014-12-26 21:58:45 +01:00
|
|
|
try:
|
|
|
|
fileobj = open(self._filename, 'wb')
|
|
|
|
except OSError as e:
|
|
|
|
self._die(e.strerror)
|
|
|
|
else:
|
|
|
|
self.set_fileobj(fileobj)
|
|
|
|
|
2015-06-30 13:22:20 +02:00
|
|
|
def _ask_confirm_question(self, msg):
|
2014-12-26 21:58:45 +01:00
|
|
|
"""Create a Question object to be asked."""
|
|
|
|
q = usertypes.Question(self)
|
2015-07-02 20:57:23 +02:00
|
|
|
q.text = msg
|
2014-12-26 21:58:45 +01:00
|
|
|
q.mode = usertypes.PromptMode.yesno
|
|
|
|
q.answered_yes.connect(self._create_fileobj)
|
|
|
|
q.answered_no.connect(functools.partial(self.cancel, False))
|
|
|
|
q.cancelled.connect(functools.partial(self.cancel, False))
|
2015-02-02 06:53:55 +01:00
|
|
|
self.cancelled.connect(q.abort)
|
|
|
|
self.error.connect(q.abort)
|
2014-12-27 00:50:52 +01:00
|
|
|
message_bridge = objreg.get('message-bridge', scope='window',
|
|
|
|
window=self._win_id)
|
|
|
|
message_bridge.ask(q, blocking=False)
|
2014-12-26 21:58:45 +01:00
|
|
|
|
2014-06-12 17:50:09 +02:00
|
|
|
def _die(self, msg):
|
|
|
|
"""Abort the download and emit an error."""
|
2014-11-18 19:56:57 +01:00
|
|
|
assert not self.successful
|
tests: fix tests for downloads bdd test
The test was failing because of two reasons:
First, the old code had filename questions in DownloadManager.get and
DownloadManager.fetch which were almost identical, thus the part in
DownloadManager.get was removed in an earlier commit. All filename
asking is now done by DownloadManager.fetch. The good part is code
deduplication, the bad part is slightly modified behavior: The new code
doesn't wait for a filename to start the download, instead it tries to
fill the buffer immediately. This made the test fail because qute:// has
no registered handler, so in order for the test to pass now, the "no
crash" part is not enough, we also need to expect the "No handler"
error.
Secondly, and a rather rare (race) condition was the handling of errors
in the DownloadItem. If an error occured after the registration of
self.on_reply_error as error handler and before the check
reply.error() != QNetworkReply.NoError
at the end of the function, the error signal would be emitted twice:
Once by _die() (called by on_reply_error), and once by the init_reply
function directly (in the last if block). This lead to duplicated error
messages. This is also explained in a comment in the file (with small
"stack traces").
2016-07-07 00:08:13 +02:00
|
|
|
# Prevent actions if calling _die() twice. This might happen if the
|
|
|
|
# error handler correctly connects, and the error occurs in init_reply
|
|
|
|
# between reply.error.connect and the reply.error() check. In this
|
|
|
|
# case, the connected error handlers will be called twice, once via the
|
|
|
|
# direct error.emit() and once here in _die(). The stacks look like
|
|
|
|
# this then:
|
|
|
|
# <networkmanager error.emit> -> on_reply_error -> _die ->
|
|
|
|
# self.error.emit()
|
|
|
|
# and
|
|
|
|
# [init_reply -> <single shot timer> ->] <lambda in init_reply> ->
|
|
|
|
# self.error.emit()
|
|
|
|
# which may lead to duplicate error messages (and failing tests)
|
|
|
|
if self._dead:
|
|
|
|
return
|
|
|
|
self._dead = True
|
2014-11-30 15:25:23 +01:00
|
|
|
self._read_timer.stop()
|
2014-11-30 18:14:48 +01:00
|
|
|
self.reply.downloadProgress.disconnect()
|
|
|
|
self.reply.finished.disconnect()
|
|
|
|
self.reply.error.disconnect()
|
|
|
|
self.reply.readyRead.disconnect()
|
2014-10-20 00:33:52 +02:00
|
|
|
self.error_msg = msg
|
2014-11-27 21:35:39 +01:00
|
|
|
self.stats.finish()
|
2014-06-12 17:50:09 +02:00
|
|
|
self.error.emit(msg)
|
2015-03-09 07:49:02 +01:00
|
|
|
with log.hide_qt_warning('QNetworkReplyImplPrivate::error: Internal '
|
|
|
|
'problem, this method must only be called '
|
|
|
|
'once.'):
|
|
|
|
# See https://codereview.qt-project.org/#/c/107863/
|
|
|
|
self.reply.abort()
|
2014-11-30 18:14:48 +01:00
|
|
|
self.reply.deleteLater()
|
|
|
|
self.reply = None
|
2014-12-10 20:48:19 +01:00
|
|
|
self.done = True
|
2014-10-15 21:22:53 +02:00
|
|
|
self.data_changed.emit()
|
2016-05-06 18:01:45 +02:00
|
|
|
if self.fileobj is not None:
|
2016-07-03 18:26:01 +02:00
|
|
|
try:
|
|
|
|
self.fileobj.close()
|
|
|
|
except OSError:
|
|
|
|
log.downloads.exception("Error while closing file object")
|
2014-06-12 17:50:09 +02:00
|
|
|
|
2014-11-24 00:12:19 +01:00
|
|
|
def init_reply(self, reply):
|
|
|
|
"""Set a new reply and connect its signals.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
reply: The QNetworkReply to handle.
|
|
|
|
"""
|
2014-12-10 21:56:57 +01:00
|
|
|
self.done = False
|
|
|
|
self.successful = False
|
2014-11-30 18:14:48 +01:00
|
|
|
self.reply = reply
|
2014-11-30 15:25:23 +01:00
|
|
|
reply.setReadBufferSize(16 * 1024 * 1024) # 16 MB
|
2014-11-27 21:35:39 +01:00
|
|
|
reply.downloadProgress.connect(self.stats.on_download_progress)
|
2014-11-24 00:12:19 +01:00
|
|
|
reply.finished.connect(self.on_reply_finished)
|
|
|
|
reply.error.connect(self.on_reply_error)
|
|
|
|
reply.readyRead.connect(self.on_ready_read)
|
2015-09-24 12:40:40 +02:00
|
|
|
reply.metaDataChanged.connect(self.on_meta_data_changed)
|
2015-01-25 23:53:23 +01:00
|
|
|
self.retry_info = RetryInfo(request=reply.request(),
|
|
|
|
manager=reply.manager())
|
2014-12-01 07:40:36 +01:00
|
|
|
if not self.fileobj:
|
|
|
|
self._read_timer.start()
|
2014-11-24 00:12:19 +01:00
|
|
|
# We could have got signals before we connected slots to them.
|
|
|
|
# Here no signals are connected to the DownloadItem yet, so we use a
|
|
|
|
# singleShot QTimer to emit them after they are connected.
|
|
|
|
if reply.error() != QNetworkReply.NoError:
|
tests: fix tests for downloads bdd test
The test was failing because of two reasons:
First, the old code had filename questions in DownloadManager.get and
DownloadManager.fetch which were almost identical, thus the part in
DownloadManager.get was removed in an earlier commit. All filename
asking is now done by DownloadManager.fetch. The good part is code
deduplication, the bad part is slightly modified behavior: The new code
doesn't wait for a filename to start the download, instead it tries to
fill the buffer immediately. This made the test fail because qute:// has
no registered handler, so in order for the test to pass now, the "no
crash" part is not enough, we also need to expect the "No handler"
error.
Secondly, and a rather rare (race) condition was the handling of errors
in the DownloadItem. If an error occured after the registration of
self.on_reply_error as error handler and before the check
reply.error() != QNetworkReply.NoError
at the end of the function, the error signal would be emitted twice:
Once by _die() (called by on_reply_error), and once by the init_reply
function directly (in the last if block). This lead to duplicated error
messages. This is also explained in a comment in the file (with small
"stack traces").
2016-07-07 00:08:13 +02:00
|
|
|
QTimer.singleShot(0, lambda: self._die(reply.errorString()))
|
2014-11-24 00:12:19 +01:00
|
|
|
|
2015-05-26 02:47:16 +02:00
|
|
|
def get_status_color(self, position):
|
|
|
|
"""Choose an appropriate color for presenting the download's status.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
position: The color type requested, can be 'fg' or 'bg'.
|
|
|
|
"""
|
2015-06-03 14:42:13 +02:00
|
|
|
# pylint: disable=bad-config-call
|
|
|
|
# WORKAROUND for https://bitbucket.org/logilab/astroid/issue/104/
|
2016-07-12 22:05:32 +02:00
|
|
|
assert position in ["fg", "bg"]
|
2015-05-26 02:47:16 +02:00
|
|
|
start = config.get('colors', 'downloads.{}.start'.format(position))
|
|
|
|
stop = config.get('colors', 'downloads.{}.stop'.format(position))
|
|
|
|
system = config.get('colors', 'downloads.{}.system'.format(position))
|
|
|
|
error = config.get('colors', 'downloads.{}.error'.format(position))
|
2014-10-20 00:33:52 +02:00
|
|
|
if self.error_msg is not None:
|
2014-11-18 19:56:57 +01:00
|
|
|
assert not self.successful
|
2014-10-15 21:22:53 +02:00
|
|
|
return error
|
2014-11-27 21:35:39 +01:00
|
|
|
elif self.stats.percentage() is None:
|
2014-06-12 21:43:30 +02:00
|
|
|
return start
|
|
|
|
else:
|
2016-04-27 18:30:54 +02:00
|
|
|
return utils.interpolate_color(start, stop,
|
|
|
|
self.stats.percentage(), system)
|
2014-06-12 21:43:30 +02:00
|
|
|
|
2015-02-23 10:01:37 +01:00
|
|
|
@pyqtSlot()
|
2016-09-09 18:03:01 +02:00
|
|
|
def cancel(self):
|
|
|
|
"""Cancel the download."""
|
2014-08-26 20:15:41 +02:00
|
|
|
log.downloads.debug("cancelled")
|
2014-12-08 16:16:03 +01:00
|
|
|
self._read_timer.stop()
|
2014-06-13 18:17:27 +02:00
|
|
|
self.cancelled.emit()
|
2014-11-30 18:14:48 +01:00
|
|
|
if self.reply is not None:
|
|
|
|
self.reply.finished.disconnect(self.on_reply_finished)
|
|
|
|
self.reply.abort()
|
|
|
|
self.reply.deleteLater()
|
|
|
|
self.reply = None
|
2014-11-14 08:27:35 +01:00
|
|
|
if self.fileobj is not None:
|
|
|
|
self.fileobj.close()
|
2016-09-09 18:03:01 +02:00
|
|
|
self.delete()
|
2015-02-12 22:20:22 +01:00
|
|
|
self.done = True
|
|
|
|
self.finished.emit()
|
|
|
|
self.data_changed.emit()
|
|
|
|
|
|
|
|
def delete(self):
|
2015-03-26 07:08:13 +01:00
|
|
|
"""Delete the downloaded file."""
|
2014-12-10 18:00:49 +01:00
|
|
|
try:
|
2015-02-12 23:29:05 +01:00
|
|
|
if self._filename is not None and os.path.exists(self._filename):
|
2014-12-10 18:00:49 +01:00
|
|
|
os.remove(self._filename)
|
|
|
|
except OSError:
|
|
|
|
log.downloads.exception("Failed to remove partial file")
|
2014-12-10 20:48:19 +01:00
|
|
|
|
2015-03-04 23:05:23 +01:00
|
|
|
@pyqtSlot()
|
2014-12-10 21:56:57 +01:00
|
|
|
def retry(self):
|
|
|
|
"""Retry a failed download."""
|
2015-11-09 07:34:49 +01:00
|
|
|
assert self.done
|
|
|
|
assert not self.successful
|
2015-03-09 07:39:40 +01:00
|
|
|
download_manager = objreg.get('download-manager', scope='window',
|
|
|
|
window=self._win_id)
|
2015-01-25 23:53:23 +01:00
|
|
|
new_reply = self.retry_info.manager.get(self.retry_info.request)
|
2015-03-09 07:39:40 +01:00
|
|
|
new_download = download_manager.fetch(
|
|
|
|
new_reply, suggested_filename=self.basename)
|
|
|
|
self.do_retry.emit(new_download)
|
|
|
|
self.cancel()
|
2014-12-10 21:56:57 +01:00
|
|
|
|
2015-02-23 10:01:37 +01:00
|
|
|
@pyqtSlot()
|
2016-08-02 19:57:45 +02:00
|
|
|
def open_file(self, cmdline=None):
|
|
|
|
"""Open the downloaded file.
|
|
|
|
|
|
|
|
Args:
|
2016-08-04 11:54:27 +02:00
|
|
|
cmdline: The command to use as string. A `{}` is expanded to the
|
|
|
|
filename. None means to use the system's default
|
|
|
|
application. If no `{}` is found, the filename is appended
|
|
|
|
to the cmdline.
|
2016-08-02 19:57:45 +02:00
|
|
|
"""
|
2014-12-10 20:48:19 +01:00
|
|
|
assert self.successful
|
2016-07-05 23:01:48 +02:00
|
|
|
filename = self._filename
|
|
|
|
if filename is None:
|
|
|
|
filename = getattr(self.fileobj, 'name', None)
|
2016-09-09 18:40:37 +02:00
|
|
|
if filename is None: # pragma: no cover
|
2016-07-05 23:01:48 +02:00
|
|
|
log.downloads.error("No filename to open the download!")
|
|
|
|
return
|
2016-08-02 19:57:45 +02:00
|
|
|
|
|
|
|
if cmdline is None:
|
|
|
|
log.downloads.debug("Opening {} with the system application"
|
|
|
|
.format(filename))
|
|
|
|
url = QUrl.fromLocalFile(filename)
|
|
|
|
QDesktopServices.openUrl(url)
|
|
|
|
return
|
|
|
|
|
|
|
|
cmd, *args = shlex.split(cmdline)
|
2016-08-03 10:25:14 +02:00
|
|
|
args = [arg.replace('{}', filename) for arg in args]
|
2016-08-04 11:50:35 +02:00
|
|
|
if '{}' not in cmdline:
|
|
|
|
args.append(filename)
|
2016-08-02 19:57:45 +02:00
|
|
|
log.downloads.debug("Opening {} with {}"
|
|
|
|
.format(filename, [cmd] + args))
|
|
|
|
proc = guiprocess.GUIProcess(self._win_id, what='download')
|
|
|
|
proc.start_detached(cmd, args)
|
2014-06-12 17:50:09 +02:00
|
|
|
|
|
|
|
def set_filename(self, filename):
|
|
|
|
"""Set the filename to save the download to.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
filename: The full filename to save the download to.
|
|
|
|
None: special value to stop the download.
|
|
|
|
"""
|
2015-10-19 20:08:37 +02:00
|
|
|
global last_used_directory
|
2016-04-05 11:43:01 +02:00
|
|
|
if self.fileobj is not None: # pragma: no cover
|
2014-11-14 08:28:59 +01:00
|
|
|
raise ValueError("fileobj was already set! filename: {}, "
|
|
|
|
"existing: {}, fileobj {}".format(
|
|
|
|
filename, self._filename, self.fileobj))
|
2014-09-01 17:51:49 +02:00
|
|
|
filename = os.path.expanduser(filename)
|
2015-10-19 20:08:37 +02:00
|
|
|
self._filename = create_full_filename(self.basename, filename)
|
|
|
|
if self._filename is None:
|
2015-03-05 23:44:12 +01:00
|
|
|
# We only got a filename (without directory) or a relative path
|
|
|
|
# from the user, so we append that to the default directory and
|
|
|
|
# try again.
|
2015-10-19 20:08:37 +02:00
|
|
|
self._filename = create_full_filename(
|
|
|
|
self.basename, os.path.join(download_dir(), filename))
|
2015-03-05 23:44:12 +01:00
|
|
|
|
2016-05-27 12:07:00 +02:00
|
|
|
# At this point, we have a misconfigured XDG_DOWNLOAD_DIR, as
|
2016-02-22 23:38:18 +01:00
|
|
|
# download_dir() + filename is still no absolute path.
|
|
|
|
# The config value is checked for "absoluteness", but
|
|
|
|
# ~/.config/user-dirs.dirs may be misconfigured and a non-absolute path
|
|
|
|
# may be set for XDG_DOWNLOAD_DIR
|
|
|
|
if self._filename is None:
|
|
|
|
message.error(
|
|
|
|
self._win_id,
|
|
|
|
"XDG_DOWNLOAD_DIR points to a relative path - please check"
|
2016-02-23 14:33:10 +01:00
|
|
|
" your ~/.config/user-dirs.dirs. The download is saved in"
|
|
|
|
" your home directory.",
|
2016-02-22 23:38:18 +01:00
|
|
|
)
|
|
|
|
# fall back to $HOME as download_dir
|
|
|
|
self._filename = create_full_filename(
|
|
|
|
self.basename, os.path.expanduser(os.path.join('~', filename)))
|
|
|
|
|
2015-10-19 20:08:37 +02:00
|
|
|
self.basename = os.path.basename(self._filename)
|
|
|
|
last_used_directory = os.path.dirname(self._filename)
|
2015-08-01 14:19:06 +02:00
|
|
|
|
2015-03-05 23:44:12 +01:00
|
|
|
log.downloads.debug("Setting filename to {}".format(filename))
|
|
|
|
if os.path.isfile(self._filename):
|
|
|
|
# The file already exists, so ask the user if it should be
|
|
|
|
# overwritten.
|
2015-07-02 20:51:51 +02:00
|
|
|
txt = self._filename + " already exists. Overwrite?"
|
|
|
|
self._ask_confirm_question(txt)
|
2015-06-27 22:28:06 +02:00
|
|
|
# FIFO, device node, etc. Make sure we want to do this
|
2016-04-27 18:30:54 +02:00
|
|
|
elif (os.path.exists(self._filename) and
|
|
|
|
not os.path.isdir(self._filename)):
|
2015-07-02 20:51:51 +02:00
|
|
|
txt = (self._filename + " already exists and is a special file. "
|
|
|
|
"Write to this?")
|
|
|
|
self._ask_confirm_question(txt)
|
2015-03-05 23:44:12 +01:00
|
|
|
else:
|
|
|
|
self._create_fileobj()
|
|
|
|
|
2014-11-14 08:28:59 +01:00
|
|
|
def set_fileobj(self, fileobj):
|
|
|
|
""""Set the file object to write the download to.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
fileobj: A file-like object.
|
|
|
|
"""
|
2016-04-05 11:43:01 +02:00
|
|
|
if self.fileobj is not None: # pragma: no cover
|
2014-11-14 08:28:59 +01:00
|
|
|
raise ValueError("fileobj was already set! Old: {}, new: "
|
|
|
|
"{}".format(self.fileobj, fileobj))
|
|
|
|
self.fileobj = fileobj
|
|
|
|
try:
|
2014-11-30 15:25:23 +01:00
|
|
|
self._read_timer.stop()
|
|
|
|
log.downloads.debug("buffer: {} bytes".format(self._buffer.tell()))
|
|
|
|
self._buffer.seek(0)
|
|
|
|
shutil.copyfileobj(self._buffer, fileobj)
|
|
|
|
self._buffer.close()
|
2014-11-30 18:14:48 +01:00
|
|
|
if self.reply.isFinished():
|
2014-06-12 17:50:09 +02:00
|
|
|
# Downloading to the buffer in RAM has already finished so we
|
|
|
|
# write out the data and clean up now.
|
2014-12-01 07:40:36 +01:00
|
|
|
self.on_reply_finished()
|
2014-06-12 17:50:09 +02:00
|
|
|
else:
|
|
|
|
# Since the buffer already might be full, on_ready_read might
|
|
|
|
# not be called at all anymore, so we force it here to flush
|
|
|
|
# the buffer and continue receiving new data.
|
|
|
|
self.on_ready_read()
|
|
|
|
except OSError as e:
|
|
|
|
self._die(e.strerror)
|
|
|
|
|
2014-11-27 21:35:39 +01:00
|
|
|
def finish_download(self):
|
2014-06-12 17:50:09 +02:00
|
|
|
"""Write buffered data to disk and finish the QNetworkReply."""
|
2014-11-27 21:35:39 +01:00
|
|
|
log.downloads.debug("Finishing download...")
|
2014-11-30 18:14:48 +01:00
|
|
|
if self.reply.isOpen():
|
|
|
|
self.fileobj.write(self.reply.readAll())
|
2014-11-14 08:26:43 +01:00
|
|
|
if self.autoclose:
|
2014-11-14 08:27:35 +01:00
|
|
|
self.fileobj.close()
|
2014-11-30 18:14:48 +01:00
|
|
|
self.successful = self.reply.error() == QNetworkReply.NoError
|
|
|
|
self.reply.close()
|
|
|
|
self.reply.deleteLater()
|
2014-11-30 18:38:33 +01:00
|
|
|
self.reply = None
|
2014-06-12 17:50:09 +02:00
|
|
|
self.finished.emit()
|
2014-12-10 20:48:19 +01:00
|
|
|
self.done = True
|
2016-09-09 15:15:10 +02:00
|
|
|
log.downloads.debug("Download {} finished".format(self.basename))
|
2014-12-10 20:48:19 +01:00
|
|
|
self.data_changed.emit()
|
2014-06-12 17:50:09 +02:00
|
|
|
|
2014-06-11 21:55:23 +02:00
|
|
|
@pyqtSlot()
|
2014-06-12 17:50:09 +02:00
|
|
|
def on_reply_finished(self):
|
|
|
|
"""Clean up when the download was finished.
|
|
|
|
|
|
|
|
Note when this gets called, only the QNetworkReply has finished. This
|
|
|
|
doesn't mean the download (i.e. writing data to the disk) is finished
|
|
|
|
as well. Therefore, we can't close() the QNetworkReply in here yet.
|
|
|
|
"""
|
2014-11-30 18:38:33 +01:00
|
|
|
if self.reply is None:
|
|
|
|
return
|
2014-12-18 23:08:19 +01:00
|
|
|
self._read_timer.stop()
|
2014-11-27 21:35:39 +01:00
|
|
|
self.stats.finish()
|
2014-11-24 00:12:19 +01:00
|
|
|
is_redirected = self._handle_redirect()
|
|
|
|
if is_redirected:
|
|
|
|
return
|
2014-11-14 08:27:35 +01:00
|
|
|
log.downloads.debug("Reply finished, fileobj {}".format(self.fileobj))
|
2014-11-27 21:35:39 +01:00
|
|
|
if self.fileobj is not None:
|
2014-06-12 17:50:09 +02:00
|
|
|
# We can do a "delayed" write immediately to empty the buffer and
|
|
|
|
# clean up.
|
2014-11-27 21:35:39 +01:00
|
|
|
self.finish_download()
|
2014-06-11 21:55:23 +02:00
|
|
|
|
|
|
|
@pyqtSlot()
|
|
|
|
def on_ready_read(self):
|
|
|
|
"""Read available data and save file when ready to read."""
|
2014-11-30 18:38:33 +01:00
|
|
|
if self.fileobj is None or self.reply is None:
|
|
|
|
# No filename has been set yet (so we don't empty the buffer) or we
|
|
|
|
# got a readyRead after the reply was finished (which happens on
|
|
|
|
# qute:log for example).
|
2014-06-12 17:50:09 +02:00
|
|
|
return
|
2014-12-01 07:35:57 +01:00
|
|
|
if not self.reply.isOpen():
|
2014-12-10 16:48:23 +01:00
|
|
|
raise OSError("Reply is closed!")
|
2014-06-12 17:50:09 +02:00
|
|
|
try:
|
2014-11-30 18:14:48 +01:00
|
|
|
self.fileobj.write(self.reply.readAll())
|
2014-06-12 17:50:09 +02:00
|
|
|
except OSError as e:
|
|
|
|
self._die(e.strerror)
|
|
|
|
|
2016-04-26 20:20:29 +02:00
|
|
|
@pyqtSlot('QNetworkReply::NetworkError')
|
2014-06-12 17:50:09 +02:00
|
|
|
def on_reply_error(self, code):
|
|
|
|
"""Handle QNetworkReply errors."""
|
|
|
|
if code == QNetworkReply.OperationCanceledError:
|
|
|
|
return
|
|
|
|
else:
|
2014-11-30 18:14:48 +01:00
|
|
|
self._die(self.reply.errorString())
|
2014-06-11 21:55:23 +02:00
|
|
|
|
2014-11-30 15:25:23 +01:00
|
|
|
@pyqtSlot()
|
|
|
|
def on_read_timer_timeout(self):
|
|
|
|
"""Read some bytes from the QNetworkReply periodically."""
|
2014-12-01 07:35:57 +01:00
|
|
|
if not self.reply.isOpen():
|
2014-12-10 16:48:23 +01:00
|
|
|
raise OSError("Reply is closed!")
|
2014-12-08 16:07:50 +01:00
|
|
|
data = self.reply.read(1024)
|
2014-12-18 23:09:33 +01:00
|
|
|
if data is not None:
|
|
|
|
self._buffer.write(data)
|
2014-11-30 15:25:23 +01:00
|
|
|
|
2015-09-19 20:06:15 +02:00
|
|
|
@pyqtSlot()
|
2015-09-24 12:40:40 +02:00
|
|
|
def on_meta_data_changed(self):
|
2015-09-20 17:11:28 +02:00
|
|
|
"""Update the download's metadata."""
|
2015-09-19 20:06:15 +02:00
|
|
|
if self.reply is None:
|
|
|
|
return
|
|
|
|
self.raw_headers = {}
|
|
|
|
for key, value in self.reply.rawHeaderPairs():
|
|
|
|
self.raw_headers[bytes(key)] = bytes(value)
|
|
|
|
|
2014-11-24 00:12:19 +01:00
|
|
|
def _handle_redirect(self):
|
2016-07-05 08:34:03 +02:00
|
|
|
"""Handle an HTTP redirect.
|
2014-11-24 00:12:19 +01:00
|
|
|
|
|
|
|
Return:
|
|
|
|
True if the download was redirected, False otherwise.
|
|
|
|
"""
|
2014-11-30 18:14:48 +01:00
|
|
|
redirect = self.reply.attribute(
|
2014-11-24 00:12:19 +01:00
|
|
|
QNetworkRequest.RedirectionTargetAttribute)
|
|
|
|
if redirect is None or redirect.isEmpty():
|
|
|
|
return False
|
2014-11-30 18:14:48 +01:00
|
|
|
new_url = self.reply.url().resolved(redirect)
|
|
|
|
request = self.reply.request()
|
2014-11-24 00:12:19 +01:00
|
|
|
if new_url == request.url():
|
|
|
|
return False
|
|
|
|
|
|
|
|
if self._redirects > self.MAX_REDIRECTS:
|
|
|
|
self._die("Maximum redirection count reached!")
|
|
|
|
return True # so on_reply_finished aborts
|
|
|
|
|
|
|
|
log.downloads.debug("{}: Handling redirect".format(self))
|
|
|
|
self._redirects += 1
|
|
|
|
request.setUrl(new_url)
|
2014-11-30 18:14:48 +01:00
|
|
|
reply = self.reply
|
2014-11-24 00:12:19 +01:00
|
|
|
reply.finished.disconnect(self.on_reply_finished)
|
2014-12-08 16:16:03 +01:00
|
|
|
self._read_timer.stop()
|
2014-11-30 18:14:48 +01:00
|
|
|
self.reply = None
|
2014-11-24 21:04:48 +01:00
|
|
|
if self.fileobj is not None:
|
|
|
|
self.fileobj.seek(0)
|
2014-11-30 18:14:48 +01:00
|
|
|
self.redirected.emit(request, reply) # this will change self.reply!
|
2014-11-24 00:12:19 +01:00
|
|
|
reply.deleteLater() # the old one
|
|
|
|
return True
|
|
|
|
|
2014-06-11 17:27:39 +02:00
|
|
|
|
2014-10-08 20:18:44 +02:00
|
|
|
class DownloadManager(QAbstractListModel):
|
2014-06-10 22:11:17 +02:00
|
|
|
|
2014-10-08 20:18:44 +02:00
|
|
|
"""Manager and model for currently running downloads.
|
2014-06-12 08:02:44 +02:00
|
|
|
|
2014-06-13 20:18:16 +02:00
|
|
|
Attributes:
|
|
|
|
downloads: A list of active DownloadItems.
|
|
|
|
questions: A list of Question objects to not GC them.
|
2014-11-14 08:30:59 +01:00
|
|
|
_networkmanager: A NetworkManager for generic downloads.
|
2014-11-14 08:29:32 +01:00
|
|
|
_win_id: The window ID the DownloadManager runs in.
|
2014-06-12 08:02:44 +02:00
|
|
|
"""
|
|
|
|
|
2014-11-11 21:36:47 +01:00
|
|
|
def __init__(self, win_id, parent=None):
|
2014-06-10 22:11:17 +02:00
|
|
|
super().__init__(parent)
|
2014-11-11 21:36:47 +01:00
|
|
|
self._win_id = win_id
|
2014-06-10 22:11:17 +02:00
|
|
|
self.downloads = []
|
2014-06-13 20:18:16 +02:00
|
|
|
self.questions = []
|
2015-01-03 22:21:47 +01:00
|
|
|
self._networkmanager = networkmanager.NetworkManager(
|
|
|
|
win_id, None, self)
|
2015-06-07 22:22:23 +02:00
|
|
|
self._update_timer = usertypes.Timer(self, 'download-update')
|
|
|
|
self._update_timer.timeout.connect(self.update_gui)
|
|
|
|
self._update_timer.setInterval(REFRESH_INTERVAL)
|
2014-06-10 22:11:17 +02:00
|
|
|
|
2014-06-17 11:03:42 +02:00
|
|
|
def __repr__(self):
|
2014-09-26 15:48:24 +02:00
|
|
|
return utils.get_repr(self, downloads=len(self.downloads))
|
2014-06-17 11:03:42 +02:00
|
|
|
|
2015-11-11 23:45:53 +01:00
|
|
|
def _postprocess_question(self, q):
|
|
|
|
"""Postprocess a Question object that is asked."""
|
2014-11-30 18:07:44 +01:00
|
|
|
q.destroyed.connect(functools.partial(self.questions.remove, q))
|
2016-07-05 23:01:48 +02:00
|
|
|
# We set the mode here so that other code that uses ask_for_filename
|
|
|
|
# doesn't need to handle the special download mode.
|
|
|
|
q.mode = usertypes.PromptMode.download
|
2014-11-30 18:07:44 +01:00
|
|
|
self.questions.append(q)
|
|
|
|
|
2015-06-07 22:22:23 +02:00
|
|
|
@pyqtSlot()
|
|
|
|
def update_gui(self):
|
|
|
|
"""Periodical GUI update of all items."""
|
|
|
|
assert self.downloads
|
|
|
|
for dl in self.downloads:
|
|
|
|
dl.stats.update_speed()
|
|
|
|
self.dataChanged.emit(self.index(0), self.last_index())
|
|
|
|
|
2016-09-05 18:14:50 +02:00
|
|
|
@pyqtSlot('QUrl')
|
2015-08-06 20:41:57 +02:00
|
|
|
def get(self, url, **kwargs):
|
2014-06-19 17:58:46 +02:00
|
|
|
"""Start a download with a link URL.
|
|
|
|
|
|
|
|
Args:
|
2014-06-20 16:33:01 +02:00
|
|
|
url: The URL to get, as QUrl
|
2015-08-06 20:41:57 +02:00
|
|
|
**kwargs: passed to get_request().
|
2014-11-14 08:31:22 +01:00
|
|
|
|
|
|
|
Return:
|
2016-07-13 22:25:23 +02:00
|
|
|
The created DownloadItem.
|
2014-06-19 17:58:46 +02:00
|
|
|
"""
|
2014-10-03 16:58:30 +02:00
|
|
|
if not url.isValid():
|
2014-11-11 21:36:47 +01:00
|
|
|
urlutils.invalid_url_error(self._win_id, url, "start download")
|
2014-10-03 16:58:30 +02:00
|
|
|
return
|
2014-06-20 16:33:01 +02:00
|
|
|
req = QNetworkRequest(url)
|
2015-08-06 20:41:57 +02:00
|
|
|
return self.get_request(req, **kwargs)
|
2014-11-30 18:07:44 +01:00
|
|
|
|
2016-07-07 13:18:38 +02:00
|
|
|
def get_request(self, request, *, target=None, **kwargs):
|
2014-11-30 18:07:44 +01:00
|
|
|
"""Start a download with a QNetworkRequest.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
request: The QNetworkRequest to download.
|
2016-07-07 13:18:38 +02:00
|
|
|
target: Where to save the download as usertypes.DownloadTarget.
|
2015-08-06 20:41:57 +02:00
|
|
|
**kwargs: Passed to fetch_request.
|
2014-11-30 18:07:44 +01:00
|
|
|
|
|
|
|
Return:
|
2016-07-13 22:25:23 +02:00
|
|
|
The created DownloadItem.
|
2014-11-30 18:07:44 +01:00
|
|
|
"""
|
2014-11-19 19:43:07 +01:00
|
|
|
# WORKAROUND for Qt corrupting data loaded from cache:
|
2015-06-12 16:59:33 +02:00
|
|
|
# https://bugreports.qt.io/browse/QTBUG-42757
|
2014-11-30 18:07:44 +01:00
|
|
|
request.setAttribute(QNetworkRequest.CacheLoadControlAttribute,
|
|
|
|
QNetworkRequest.AlwaysNetwork)
|
2016-01-26 22:37:46 +01:00
|
|
|
|
2016-02-18 16:17:35 +01:00
|
|
|
if request.url().scheme().lower() != 'data':
|
|
|
|
suggested_fn = urlutils.filename_from_url(request.url())
|
|
|
|
else:
|
|
|
|
# We might be downloading a binary blob embedded on a page or even
|
|
|
|
# generated dynamically via javascript. We try to figure out a more
|
|
|
|
# sensible name than the base64 content of the data.
|
|
|
|
origin = request.originatingObject()
|
|
|
|
try:
|
|
|
|
origin_url = origin.url()
|
|
|
|
except AttributeError:
|
|
|
|
# Raised either if origin is None or some object that doesn't
|
|
|
|
# have its own url. We're probably fine with a default fallback
|
|
|
|
# then.
|
|
|
|
suggested_fn = 'binary blob'
|
|
|
|
else:
|
|
|
|
# Use the originating URL as a base for the filename (works
|
|
|
|
# e.g. for pdf.js).
|
|
|
|
suggested_fn = urlutils.filename_from_url(origin_url)
|
|
|
|
|
2016-01-26 22:37:46 +01:00
|
|
|
if suggested_fn is None:
|
|
|
|
suggested_fn = 'qutebrowser-download'
|
2015-08-04 16:30:55 +02:00
|
|
|
|
2016-07-05 23:01:48 +02:00
|
|
|
return self.fetch_request(request,
|
2016-07-07 13:18:38 +02:00
|
|
|
target=target,
|
2016-07-05 23:01:48 +02:00
|
|
|
suggested_filename=suggested_fn,
|
|
|
|
**kwargs)
|
2014-11-30 18:07:44 +01:00
|
|
|
|
2015-08-06 20:41:57 +02:00
|
|
|
def fetch_request(self, request, *, page=None, **kwargs):
|
2014-11-30 18:07:44 +01:00
|
|
|
"""Download a QNetworkRequest to disk.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
request: The QNetworkRequest to download.
|
|
|
|
page: The QWebPage to use.
|
2015-08-06 20:41:57 +02:00
|
|
|
**kwargs: passed to fetch().
|
2014-11-30 18:07:44 +01:00
|
|
|
|
|
|
|
Return:
|
|
|
|
The created DownloadItem.
|
|
|
|
"""
|
2014-11-14 08:30:59 +01:00
|
|
|
if page is None:
|
|
|
|
nam = self._networkmanager
|
|
|
|
else:
|
|
|
|
nam = page.networkAccessManager()
|
2014-11-30 18:07:44 +01:00
|
|
|
reply = nam.get(request)
|
2015-08-06 20:41:57 +02:00
|
|
|
return self.fetch(reply, **kwargs)
|
2014-06-19 17:58:46 +02:00
|
|
|
|
2014-06-10 22:11:17 +02:00
|
|
|
@pyqtSlot('QNetworkReply')
|
2016-07-07 13:18:38 +02:00
|
|
|
def fetch(self, reply, *, target=None, auto_remove=False,
|
2015-08-06 19:09:21 +02:00
|
|
|
suggested_filename=None, prompt_download_directory=None):
|
2014-06-10 22:11:17 +02:00
|
|
|
"""Download a QNetworkReply to disk.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
reply: The QNetworkReply to download.
|
2016-07-07 13:18:38 +02:00
|
|
|
target: Where to save the download as usertypes.DownloadTarget.
|
2014-12-16 13:44:09 +01:00
|
|
|
auto_remove: Whether to remove the download even if
|
2015-10-29 18:40:14 +01:00
|
|
|
ui -> remove-finished-downloads is set to -1.
|
2014-11-14 08:31:22 +01:00
|
|
|
|
|
|
|
Return:
|
|
|
|
The created DownloadItem.
|
2014-06-10 22:11:17 +02:00
|
|
|
"""
|
2015-03-04 12:24:26 +01:00
|
|
|
if not suggested_filename:
|
2016-07-12 16:46:03 +02:00
|
|
|
if isinstance(target, usertypes.FileDownloadTarget):
|
2016-07-07 13:18:38 +02:00
|
|
|
suggested_filename = os.path.basename(target.filename)
|
2016-07-12 16:46:03 +02:00
|
|
|
elif (isinstance(target, usertypes.FileObjDownloadTarget) and
|
2016-07-07 13:18:38 +02:00
|
|
|
getattr(target.fileobj, 'name', None)):
|
|
|
|
suggested_filename = target.fileobj.name
|
2015-03-05 20:17:48 +01:00
|
|
|
else:
|
|
|
|
_, suggested_filename = http.parse_content_disposition(reply)
|
2014-08-26 20:15:41 +02:00
|
|
|
log.downloads.debug("fetch: {} -> {}".format(reply.url(),
|
|
|
|
suggested_filename))
|
2014-12-28 02:00:31 +01:00
|
|
|
download = DownloadItem(reply, self._win_id, self)
|
2014-12-10 20:48:19 +01:00
|
|
|
download.cancelled.connect(
|
|
|
|
functools.partial(self.remove_item, download))
|
2015-11-09 22:45:51 +01:00
|
|
|
|
2015-10-29 18:40:14 +01:00
|
|
|
delay = config.get('ui', 'remove-finished-downloads')
|
2015-11-09 22:45:51 +01:00
|
|
|
if delay > -1:
|
2014-12-10 20:48:19 +01:00
|
|
|
download.finished.connect(
|
2015-10-29 18:40:14 +01:00
|
|
|
functools.partial(self.remove_item_delayed, download, delay))
|
2015-11-09 22:45:51 +01:00
|
|
|
elif auto_remove:
|
|
|
|
download.finished.connect(
|
|
|
|
functools.partial(self.remove_item, download))
|
|
|
|
|
2014-08-26 19:10:14 +02:00
|
|
|
download.data_changed.connect(
|
|
|
|
functools.partial(self.on_data_changed, download))
|
2014-10-20 00:33:52 +02:00
|
|
|
download.error.connect(self.on_error)
|
2014-11-24 00:12:19 +01:00
|
|
|
download.redirected.connect(
|
|
|
|
functools.partial(self.on_redirect, download))
|
2014-06-12 23:29:34 +02:00
|
|
|
download.basename = suggested_filename
|
2016-05-08 23:28:01 +02:00
|
|
|
idx = len(self.downloads)
|
|
|
|
download.index = idx + 1 # "Human readable" index
|
2014-10-08 20:18:44 +02:00
|
|
|
self.beginInsertRows(QModelIndex(), idx, idx)
|
2014-06-12 17:50:09 +02:00
|
|
|
self.downloads.append(download)
|
2014-10-08 20:18:44 +02:00
|
|
|
self.endInsertRows()
|
2014-06-13 18:17:27 +02:00
|
|
|
|
2015-06-07 22:22:23 +02:00
|
|
|
if not self._update_timer.isActive():
|
|
|
|
self._update_timer.start()
|
|
|
|
|
2016-07-07 13:18:38 +02:00
|
|
|
if target is not None:
|
|
|
|
self._set_download_target(download, suggested_filename, target)
|
2015-11-23 12:32:58 +01:00
|
|
|
return download
|
|
|
|
|
|
|
|
# Neither filename nor fileobj were given, prepare a question
|
2015-11-11 23:45:53 +01:00
|
|
|
filename, q = ask_for_filename(
|
|
|
|
suggested_filename, self._win_id, parent=self,
|
|
|
|
prompt_download_directory=prompt_download_directory,
|
|
|
|
)
|
2015-11-23 12:32:58 +01:00
|
|
|
|
|
|
|
# User doesn't want to be asked, so just use the download_dir
|
2014-11-20 06:24:15 +01:00
|
|
|
if filename is not None:
|
2016-07-12 16:46:03 +02:00
|
|
|
target = usertypes.FileDownloadTarget(filename)
|
2016-07-07 13:18:38 +02:00
|
|
|
self._set_download_target(download, suggested_filename, target)
|
2015-11-11 23:45:53 +01:00
|
|
|
return download
|
|
|
|
|
2015-11-23 12:32:58 +01:00
|
|
|
# Ask the user for a filename
|
2015-11-11 23:45:53 +01:00
|
|
|
self._postprocess_question(q)
|
2016-07-05 23:01:48 +02:00
|
|
|
q.answered.connect(
|
2016-07-07 13:18:38 +02:00
|
|
|
functools.partial(self._set_download_target, download,
|
2016-07-05 23:01:48 +02:00
|
|
|
suggested_filename))
|
2015-11-11 23:45:53 +01:00
|
|
|
q.cancelled.connect(download.cancel)
|
|
|
|
download.cancelled.connect(q.abort)
|
|
|
|
download.error.connect(q.abort)
|
|
|
|
q.ask()
|
2014-11-14 08:28:59 +01:00
|
|
|
|
|
|
|
return download
|
2014-06-12 08:02:44 +02:00
|
|
|
|
2016-07-07 13:18:38 +02:00
|
|
|
def _set_download_target(self, download, suggested_filename, target):
|
|
|
|
"""Set the target for a given download.
|
2016-07-05 23:01:48 +02:00
|
|
|
|
|
|
|
Args:
|
|
|
|
download: The download to set the filename for.
|
|
|
|
suggested_filename: The suggested filename.
|
2016-07-07 13:18:38 +02:00
|
|
|
target: The usertypes.DownloadTarget for this download.
|
2016-07-05 23:01:48 +02:00
|
|
|
"""
|
2016-07-12 16:46:03 +02:00
|
|
|
if isinstance(target, usertypes.FileObjDownloadTarget):
|
2016-07-07 13:18:38 +02:00
|
|
|
download.set_fileobj(target.fileobj)
|
|
|
|
download.autoclose = False
|
2016-07-12 16:46:03 +02:00
|
|
|
elif isinstance(target, usertypes.FileDownloadTarget):
|
2016-07-07 13:18:38 +02:00
|
|
|
download.set_filename(target.filename)
|
2016-07-12 16:46:03 +02:00
|
|
|
elif isinstance(target, usertypes.OpenFileDownloadTarget):
|
2016-07-07 13:18:38 +02:00
|
|
|
tmp_manager = objreg.get('temporary-downloads')
|
2016-08-02 00:46:59 +02:00
|
|
|
try:
|
|
|
|
fobj = tmp_manager.get_tmpfile(suggested_filename)
|
|
|
|
except OSError as exc:
|
|
|
|
msg = "Download error: {}".format(exc)
|
|
|
|
message.error(self._win_id, msg)
|
|
|
|
download.cancel()
|
|
|
|
return
|
2016-08-02 01:10:40 +02:00
|
|
|
download.finished.connect(
|
2016-08-02 19:40:57 +02:00
|
|
|
functools.partial(self._open_download, download,
|
|
|
|
target.cmdline))
|
2016-07-07 13:18:38 +02:00
|
|
|
download.autoclose = True
|
|
|
|
download.set_fileobj(fobj)
|
|
|
|
else:
|
|
|
|
log.downloads.error("Unknown download target: {}".format(target))
|
2016-07-05 23:01:48 +02:00
|
|
|
|
2016-08-02 19:40:57 +02:00
|
|
|
def _open_download(self, download, cmdline):
|
|
|
|
"""Open the given download but only if it was successful.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
download: The DownloadItem to use.
|
2016-08-04 11:54:27 +02:00
|
|
|
cmdline: Passed to DownloadItem.open_file().
|
2016-08-02 19:40:57 +02:00
|
|
|
"""
|
|
|
|
if not download.successful:
|
2016-08-02 01:10:40 +02:00
|
|
|
log.downloads.debug("{} finished but not successful, not opening!"
|
|
|
|
.format(download))
|
2016-08-02 19:40:57 +02:00
|
|
|
return
|
2016-08-02 19:57:45 +02:00
|
|
|
download.open_file(cmdline)
|
2016-08-02 19:40:57 +02:00
|
|
|
|
2015-02-14 14:11:38 +01:00
|
|
|
def raise_no_download(self, count):
|
2015-03-26 07:08:13 +01:00
|
|
|
"""Raise an exception that the download doesn't exist.
|
2015-02-13 12:40:37 +01:00
|
|
|
|
|
|
|
Args:
|
2015-02-14 14:11:38 +01:00
|
|
|
count: The index of the download
|
2015-02-13 12:40:37 +01:00
|
|
|
"""
|
2015-02-14 14:11:38 +01:00
|
|
|
if not count:
|
2015-02-13 12:40:37 +01:00
|
|
|
raise cmdexc.CommandError("There's no download!")
|
2015-02-14 14:11:38 +01:00
|
|
|
raise cmdexc.CommandError("There's no download {}!".format(count))
|
2015-02-13 12:40:37 +01:00
|
|
|
|
2016-05-10 19:51:11 +02:00
|
|
|
@cmdutils.register(instance='download-manager', scope='window')
|
|
|
|
@cmdutils.argument('count', count=True)
|
2016-03-14 19:05:15 +01:00
|
|
|
def download_cancel(self, all_=False, count=0):
|
2015-02-08 22:03:29 +01:00
|
|
|
"""Cancel the last/[count]th download.
|
2014-11-30 18:07:44 +01:00
|
|
|
|
|
|
|
Args:
|
2016-03-14 19:05:15 +01:00
|
|
|
all_: Cancel all running downloads
|
2014-11-30 18:07:44 +01:00
|
|
|
count: The index of the download to cancel.
|
|
|
|
"""
|
2016-03-14 19:05:15 +01:00
|
|
|
if all_:
|
|
|
|
# We need to make a copy as we're indirectly mutating
|
|
|
|
# self.downloads here
|
|
|
|
for download in self.downloads[:]:
|
|
|
|
if not download.done:
|
|
|
|
download.cancel()
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
download = self.downloads[count - 1]
|
|
|
|
except IndexError:
|
|
|
|
self.raise_no_download(count)
|
|
|
|
if download.done:
|
|
|
|
if not count:
|
|
|
|
count = len(self.downloads)
|
|
|
|
raise cmdexc.CommandError("Download {} is already done!"
|
|
|
|
.format(count))
|
|
|
|
download.cancel()
|
2014-11-30 18:07:44 +01:00
|
|
|
|
2016-05-10 19:51:11 +02:00
|
|
|
@cmdutils.register(instance='download-manager', scope='window')
|
|
|
|
@cmdutils.argument('count', count=True)
|
2015-04-20 19:29:29 +02:00
|
|
|
def download_delete(self, count=0):
|
2015-02-12 22:20:22 +01:00
|
|
|
"""Delete the last/[count]th download from disk.
|
|
|
|
|
|
|
|
Args:
|
2016-03-14 19:05:36 +01:00
|
|
|
count: The index of the download to delete.
|
2015-02-12 22:20:22 +01:00
|
|
|
"""
|
|
|
|
try:
|
|
|
|
download = self.downloads[count - 1]
|
|
|
|
except IndexError:
|
2015-02-13 12:40:37 +01:00
|
|
|
self.raise_no_download(count)
|
2015-02-12 22:20:22 +01:00
|
|
|
if not download.successful:
|
2015-02-13 12:40:37 +01:00
|
|
|
if not count:
|
|
|
|
count = len(self.downloads)
|
2015-02-12 22:20:22 +01:00
|
|
|
raise cmdexc.CommandError("Download {} is not done!".format(count))
|
|
|
|
download.delete()
|
|
|
|
self.remove_item(download)
|
2016-04-26 22:56:06 +02:00
|
|
|
log.downloads.debug("deleted download {}".format(download))
|
2015-02-12 22:20:22 +01:00
|
|
|
|
2016-08-02 19:57:45 +02:00
|
|
|
@cmdutils.register(instance='download-manager', scope='window', maxsplit=0)
|
2016-05-10 19:51:11 +02:00
|
|
|
@cmdutils.argument('count', count=True)
|
2016-08-02 19:57:45 +02:00
|
|
|
def download_open(self, cmdline: str=None, count=0):
|
2015-02-12 22:21:30 +01:00
|
|
|
"""Open the last/[count]th download.
|
2015-02-08 22:03:29 +01:00
|
|
|
|
2016-08-03 18:06:28 +02:00
|
|
|
If no specific command is given, this will use the system's default
|
|
|
|
application to open the file.
|
|
|
|
|
2015-02-08 22:03:29 +01:00
|
|
|
Args:
|
2016-08-03 18:06:28 +02:00
|
|
|
cmdline: The command which should be used to open the file. A `{}`
|
2016-08-04 11:54:27 +02:00
|
|
|
is expanded to the temporary file name. If no `{}` is
|
|
|
|
present, the filename is automatically appended to the
|
|
|
|
cmdline.
|
2016-03-14 19:05:36 +01:00
|
|
|
count: The index of the download to open.
|
2015-02-08 22:03:29 +01:00
|
|
|
"""
|
|
|
|
try:
|
2015-02-12 21:05:53 +01:00
|
|
|
download = self.downloads[count - 1]
|
2015-02-08 22:03:29 +01:00
|
|
|
except IndexError:
|
2015-02-13 12:40:37 +01:00
|
|
|
self.raise_no_download(count)
|
2015-02-12 22:21:30 +01:00
|
|
|
if not download.successful:
|
2015-02-13 12:40:37 +01:00
|
|
|
if not count:
|
|
|
|
count = len(self.downloads)
|
2015-02-12 21:05:53 +01:00
|
|
|
raise cmdexc.CommandError("Download {} is not done!".format(count))
|
2016-08-02 19:57:45 +02:00
|
|
|
download.open_file(cmdline)
|
2015-02-08 22:03:29 +01:00
|
|
|
|
2016-05-10 19:51:11 +02:00
|
|
|
@cmdutils.register(instance='download-manager', scope='window')
|
|
|
|
@cmdutils.argument('count', count=True)
|
2015-11-09 07:17:54 +01:00
|
|
|
def download_retry(self, count=0):
|
|
|
|
"""Retry the first failed/[count]th download.
|
|
|
|
|
|
|
|
Args:
|
2016-03-14 19:05:36 +01:00
|
|
|
count: The index of the download to retry.
|
2015-11-09 07:17:54 +01:00
|
|
|
"""
|
|
|
|
if count:
|
|
|
|
try:
|
|
|
|
download = self.downloads[count - 1]
|
|
|
|
except IndexError:
|
|
|
|
self.raise_no_download(count)
|
|
|
|
if download.successful or not download.done:
|
|
|
|
raise cmdexc.CommandError("Download {} did not fail!".format(
|
|
|
|
count))
|
|
|
|
else:
|
|
|
|
to_retry = [d for d in self.downloads
|
|
|
|
if d.done and not d.successful]
|
|
|
|
if not to_retry:
|
|
|
|
raise cmdexc.CommandError("No failed downloads!")
|
|
|
|
else:
|
|
|
|
download = to_retry[0]
|
|
|
|
download.retry()
|
|
|
|
|
2014-11-24 00:12:19 +01:00
|
|
|
@pyqtSlot(QNetworkRequest, QNetworkReply)
|
|
|
|
def on_redirect(self, download, request, reply):
|
2016-07-05 08:34:03 +02:00
|
|
|
"""Handle an HTTP redirect of a download.
|
2014-11-24 00:12:19 +01:00
|
|
|
|
|
|
|
Args:
|
|
|
|
download: The old DownloadItem.
|
|
|
|
request: The new QNetworkRequest.
|
|
|
|
reply: The old QNetworkReply.
|
|
|
|
"""
|
|
|
|
log.downloads.debug("redirected: {} -> {}".format(
|
|
|
|
reply.url(), request.url()))
|
|
|
|
new_reply = reply.manager().get(request)
|
|
|
|
download.init_reply(new_reply)
|
|
|
|
|
2014-06-16 22:49:22 +02:00
|
|
|
@pyqtSlot(DownloadItem)
|
|
|
|
def on_data_changed(self, download):
|
2014-06-12 17:56:28 +02:00
|
|
|
"""Emit data_changed signal when download data changed."""
|
2014-12-10 20:48:19 +01:00
|
|
|
try:
|
|
|
|
idx = self.downloads.index(download)
|
|
|
|
except ValueError:
|
|
|
|
# download has been deleted in the meantime
|
|
|
|
return
|
2014-10-08 20:18:44 +02:00
|
|
|
model_idx = self.index(idx, 0)
|
|
|
|
qtutils.ensure_valid(model_idx)
|
|
|
|
self.dataChanged.emit(model_idx, model_idx)
|
2014-06-12 17:50:09 +02:00
|
|
|
|
2014-10-20 00:33:52 +02:00
|
|
|
@pyqtSlot(str)
|
|
|
|
def on_error(self, msg):
|
2014-06-12 17:56:28 +02:00
|
|
|
"""Display error message on download errors."""
|
2014-11-11 21:36:47 +01:00
|
|
|
message.error(self._win_id, "Download error: {}".format(msg))
|
2014-10-08 20:18:44 +02:00
|
|
|
|
2014-11-30 18:14:48 +01:00
|
|
|
def has_downloads_with_nam(self, nam):
|
|
|
|
"""Check if the DownloadManager has any downloads with the given QNAM.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
nam: The QNetworkAccessManager to check.
|
|
|
|
|
|
|
|
Return:
|
|
|
|
A boolean.
|
|
|
|
"""
|
2015-01-28 22:52:24 +01:00
|
|
|
assert nam.adopted_downloads == 0
|
2014-11-30 18:14:48 +01:00
|
|
|
for download in self.downloads:
|
2015-01-28 22:52:24 +01:00
|
|
|
running_download = (download.reply is not None and
|
|
|
|
download.reply.manager() is nam)
|
|
|
|
# user could request retry after tab is closed.
|
|
|
|
failed_download = (download.done and (not download.successful) and
|
|
|
|
download.retry_info.manager is nam)
|
|
|
|
if running_download or failed_download:
|
2015-03-09 07:39:40 +01:00
|
|
|
nam.adopt_download(download)
|
2015-01-28 22:52:24 +01:00
|
|
|
return nam.adopted_downloads
|
2014-11-30 18:14:48 +01:00
|
|
|
|
2014-12-16 14:30:47 +01:00
|
|
|
def can_clear(self):
|
|
|
|
"""Check if there are finished downloads to clear."""
|
2015-02-09 17:17:34 +01:00
|
|
|
return any(download.done for download in self.downloads)
|
2014-12-16 14:30:47 +01:00
|
|
|
|
2015-11-03 19:27:02 +01:00
|
|
|
@cmdutils.register(instance='download-manager', scope='window')
|
|
|
|
def download_clear(self):
|
|
|
|
"""Remove all finished downloads from the list."""
|
|
|
|
finished_items = [d for d in self.downloads if d.done]
|
|
|
|
self.remove_items(finished_items)
|
|
|
|
|
2016-05-10 19:51:11 +02:00
|
|
|
@cmdutils.register(instance='download-manager', scope='window')
|
|
|
|
@cmdutils.argument('count', count=True)
|
2015-04-20 22:25:27 +02:00
|
|
|
def download_remove(self, all_=False, count=0):
|
2015-02-12 22:21:30 +01:00
|
|
|
"""Remove the last/[count]th download from the list.
|
2015-02-09 17:17:34 +01:00
|
|
|
|
|
|
|
Args:
|
2016-03-14 19:11:41 +01:00
|
|
|
all_: Remove all finished downloads.
|
2016-03-14 19:05:36 +01:00
|
|
|
count: The index of the download to remove.
|
2015-02-09 17:17:34 +01:00
|
|
|
"""
|
|
|
|
if all_:
|
2015-11-03 19:27:02 +01:00
|
|
|
self.download_clear()
|
2015-02-09 17:17:34 +01:00
|
|
|
else:
|
2015-02-12 21:05:53 +01:00
|
|
|
try:
|
|
|
|
download = self.downloads[count - 1]
|
|
|
|
except IndexError:
|
2015-02-13 12:40:37 +01:00
|
|
|
self.raise_no_download(count)
|
2015-02-12 21:05:53 +01:00
|
|
|
if not download.done:
|
2015-02-13 12:40:37 +01:00
|
|
|
if not count:
|
|
|
|
count = len(self.downloads)
|
2015-02-12 23:29:05 +01:00
|
|
|
raise cmdexc.CommandError("Download {} is not done!"
|
|
|
|
.format(count))
|
2015-02-12 21:05:53 +01:00
|
|
|
self.remove_item(download)
|
2014-12-16 14:30:47 +01:00
|
|
|
|
2014-10-08 20:18:44 +02:00
|
|
|
def last_index(self):
|
|
|
|
"""Get the last index in the model.
|
|
|
|
|
|
|
|
Return:
|
|
|
|
A (possibly invalid) QModelIndex.
|
|
|
|
"""
|
|
|
|
idx = self.index(self.rowCount() - 1)
|
|
|
|
return idx
|
|
|
|
|
2014-12-10 20:48:19 +01:00
|
|
|
def remove_item(self, download):
|
|
|
|
"""Remove a given download."""
|
2016-03-31 19:09:43 +02:00
|
|
|
if sip.isdeleted(self):
|
|
|
|
# https://github.com/The-Compiler/qutebrowser/issues/1242
|
|
|
|
return
|
2014-12-10 21:56:57 +01:00
|
|
|
try:
|
|
|
|
idx = self.downloads.index(download)
|
|
|
|
except ValueError:
|
|
|
|
# already removed
|
|
|
|
return
|
2014-12-10 20:48:19 +01:00
|
|
|
self.beginRemoveRows(QModelIndex(), idx, idx)
|
|
|
|
del self.downloads[idx]
|
|
|
|
self.endRemoveRows()
|
|
|
|
download.deleteLater()
|
2015-02-12 20:43:13 +01:00
|
|
|
self.update_indexes()
|
2015-06-07 22:22:23 +02:00
|
|
|
if not self.downloads:
|
|
|
|
self._update_timer.stop()
|
2014-12-10 20:48:19 +01:00
|
|
|
|
2015-10-29 18:40:14 +01:00
|
|
|
def remove_item_delayed(self, download, delay):
|
|
|
|
"""Remove a given download after a short delay."""
|
|
|
|
QTimer.singleShot(delay, functools.partial(self.remove_item, download))
|
|
|
|
|
2014-12-16 14:30:47 +01:00
|
|
|
def remove_items(self, downloads):
|
|
|
|
"""Remove an iterable of downloads."""
|
|
|
|
# On the first pass, we only generate the indices so we get the
|
|
|
|
# first/last one for beginRemoveRows.
|
|
|
|
indices = []
|
|
|
|
# We need to iterate over downloads twice, which won't work if it's a
|
|
|
|
# generator.
|
|
|
|
downloads = list(downloads)
|
|
|
|
for download in downloads:
|
|
|
|
try:
|
|
|
|
indices.append(self.downloads.index(download))
|
|
|
|
except ValueError:
|
|
|
|
# already removed
|
|
|
|
pass
|
|
|
|
if not indices:
|
|
|
|
return
|
|
|
|
indices.sort()
|
|
|
|
self.beginRemoveRows(QModelIndex(), indices[0], indices[-1])
|
|
|
|
for download in downloads:
|
|
|
|
try:
|
|
|
|
self.downloads.remove(download)
|
|
|
|
except ValueError:
|
|
|
|
# already removed
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
download.deleteLater()
|
|
|
|
self.endRemoveRows()
|
2015-06-07 22:22:23 +02:00
|
|
|
if not self.downloads:
|
|
|
|
self._update_timer.stop()
|
2014-12-16 14:30:47 +01:00
|
|
|
|
2015-02-12 20:43:13 +01:00
|
|
|
def update_indexes(self):
|
2015-03-26 07:08:13 +01:00
|
|
|
"""Update indexes of all DownloadItems."""
|
2015-02-12 23:29:05 +01:00
|
|
|
first_idx = None
|
2015-02-12 20:43:13 +01:00
|
|
|
for i, d in enumerate(self.downloads, 1):
|
2015-02-14 14:11:38 +01:00
|
|
|
if first_idx is None and d.index != i:
|
2015-02-12 23:29:05 +01:00
|
|
|
first_idx = i - 1
|
|
|
|
d.index = i
|
2015-02-14 14:11:38 +01:00
|
|
|
if first_idx is not None:
|
2015-02-12 23:29:05 +01:00
|
|
|
model_idx = self.index(first_idx, 0)
|
|
|
|
qtutils.ensure_valid(model_idx)
|
|
|
|
self.dataChanged.emit(model_idx, self.last_index())
|
2015-02-12 20:43:13 +01:00
|
|
|
|
2014-10-08 20:18:44 +02:00
|
|
|
def headerData(self, section, orientation, role):
|
|
|
|
"""Simple constant header."""
|
|
|
|
if (section == 0 and orientation == Qt.Horizontal and
|
|
|
|
role == Qt.DisplayRole):
|
|
|
|
return "Downloads"
|
|
|
|
else:
|
|
|
|
return ""
|
|
|
|
|
|
|
|
def data(self, index, role):
|
|
|
|
"""Download data from DownloadManager."""
|
|
|
|
qtutils.ensure_valid(index)
|
|
|
|
if index.parent().isValid() or index.column() != 0:
|
|
|
|
return QVariant()
|
|
|
|
|
2014-11-11 21:36:47 +01:00
|
|
|
item = self.downloads[index.row()]
|
2014-10-08 20:18:44 +02:00
|
|
|
if role == Qt.DisplayRole:
|
|
|
|
data = str(item)
|
|
|
|
elif role == Qt.ForegroundRole:
|
2015-05-26 02:47:16 +02:00
|
|
|
data = item.get_status_color('fg')
|
2014-10-08 20:18:44 +02:00
|
|
|
elif role == Qt.BackgroundRole:
|
2015-05-26 02:47:16 +02:00
|
|
|
data = item.get_status_color('bg')
|
2014-10-08 20:18:44 +02:00
|
|
|
elif role == ModelRole.item:
|
|
|
|
data = item
|
2014-10-15 21:22:53 +02:00
|
|
|
elif role == Qt.ToolTipRole:
|
2014-10-20 00:33:52 +02:00
|
|
|
if item.error_msg is None:
|
2014-10-15 21:22:53 +02:00
|
|
|
data = QVariant()
|
|
|
|
else:
|
2014-10-20 00:33:52 +02:00
|
|
|
return item.error_msg
|
2014-10-08 20:18:44 +02:00
|
|
|
else:
|
|
|
|
data = QVariant()
|
|
|
|
return data
|
|
|
|
|
|
|
|
def flags(self, _index):
|
|
|
|
"""Override flags so items aren't selectable.
|
|
|
|
|
2016-04-08 07:35:53 +02:00
|
|
|
The default would be Qt.ItemIsEnabled | Qt.ItemIsSelectable.
|
|
|
|
"""
|
2015-05-18 21:35:14 +02:00
|
|
|
return Qt.ItemIsEnabled | Qt.ItemNeverHasChildren
|
2014-10-08 20:18:44 +02:00
|
|
|
|
|
|
|
def rowCount(self, parent=QModelIndex()):
|
|
|
|
"""Get count of active downloads."""
|
|
|
|
if parent.isValid():
|
|
|
|
# We don't have children
|
|
|
|
return 0
|
2014-11-11 21:36:47 +01:00
|
|
|
return len(self.downloads)
|
2016-05-08 03:17:30 +02:00
|
|
|
|
|
|
|
def running_downloads(self):
|
|
|
|
"""Return the amount of still running downloads.
|
|
|
|
|
|
|
|
Return:
|
|
|
|
The number of unfinished downloads.
|
|
|
|
"""
|
2016-05-08 23:24:50 +02:00
|
|
|
return sum(1 for download in self.downloads if not download.done)
|
2016-07-06 18:41:08 +02:00
|
|
|
|
|
|
|
|
|
|
|
class TempDownloadManager(QObject):
|
|
|
|
|
|
|
|
"""Manager to handle temporary download files.
|
|
|
|
|
|
|
|
The downloads are downloaded to a temporary location and then openened with
|
|
|
|
the system standard application. The temporary files are deleted when
|
|
|
|
qutebrowser is shutdown.
|
|
|
|
|
|
|
|
Attributes:
|
|
|
|
files: A list of NamedTemporaryFiles of downloaded items.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, parent=None):
|
|
|
|
super().__init__(parent)
|
|
|
|
self.files = []
|
|
|
|
self._tmpdir = None
|
|
|
|
|
|
|
|
def cleanup(self):
|
|
|
|
"""Clean up any temporary files."""
|
|
|
|
if self._tmpdir is not None:
|
|
|
|
self._tmpdir.cleanup()
|
|
|
|
self._tmpdir = None
|
|
|
|
|
2016-07-12 16:26:35 +02:00
|
|
|
def _get_tmpdir(self):
|
2016-07-06 18:41:08 +02:00
|
|
|
"""Return the temporary directory that is used for downloads.
|
|
|
|
|
|
|
|
The directory is created lazily on first access.
|
|
|
|
|
|
|
|
Return:
|
|
|
|
The tempfile.TemporaryDirectory that is used.
|
|
|
|
"""
|
|
|
|
if self._tmpdir is None:
|
|
|
|
self._tmpdir = tempfile.TemporaryDirectory(
|
|
|
|
prefix='qutebrowser-downloads-')
|
|
|
|
return self._tmpdir
|
|
|
|
|
|
|
|
def get_tmpfile(self, suggested_name):
|
|
|
|
"""Return a temporary file in the temporary downloads directory.
|
|
|
|
|
|
|
|
The files are kept as long as qutebrowser is running and automatically
|
|
|
|
cleaned up at program exit.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
suggested_name: str of the "suggested"/original filename. Used as a
|
|
|
|
suffix, so any file extenions are preserved.
|
|
|
|
|
|
|
|
Return:
|
|
|
|
A tempfile.NamedTemporaryFile that should be used to save the file.
|
|
|
|
"""
|
2016-07-12 16:26:35 +02:00
|
|
|
tmpdir = self._get_tmpdir()
|
2016-08-02 01:00:57 +02:00
|
|
|
encoding = sys.getfilesystemencoding()
|
|
|
|
suggested_name = utils.force_encoding(suggested_name, encoding)
|
2016-08-02 00:57:22 +02:00
|
|
|
# Make sure that the filename is not too long
|
2016-08-02 13:29:03 +02:00
|
|
|
suggested_name = utils.elide_filename(suggested_name, 50)
|
2016-07-06 18:41:08 +02:00
|
|
|
fobj = tempfile.NamedTemporaryFile(dir=tmpdir.name, delete=False,
|
|
|
|
suffix=suggested_name)
|
|
|
|
self.files.append(fobj)
|
|
|
|
return fobj
|