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
|
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
|
2016-10-28 18:40:55 +02:00
|
|
|
import html
|
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,
|
2016-09-10 17:32:04 +02:00
|
|
|
Qt, QAbstractListModel, QModelIndex, QUrl)
|
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-11-01 16:19:15 +01:00
|
|
|
from qutebrowser.browser import downloads
|
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
|
|
|
|
|
|
|
|
2016-09-11 20:48:19 +02:00
|
|
|
_RetryInfo = collections.namedtuple('_RetryInfo', ['request', 'manager'])
|
2014-12-10 21:56:57 +01:00
|
|
|
|
2014-11-27 21:35:39 +01:00
|
|
|
|
2016-11-01 16:19:15 +01:00
|
|
|
class DownloadItem(downloads.AbstractDownloadItem):
|
2014-11-27 21:35:39 +01:00
|
|
|
|
|
|
|
"""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:
|
2016-09-11 20:48:19 +02: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.
|
2016-11-01 14:48:28 +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.
|
2016-11-01 16:37:56 +01:00
|
|
|
_manager: The DownloadManager which started this download
|
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.
|
2016-09-11 20:48:28 +02:00
|
|
|
_reply: The QNetworkReply associated with this download.
|
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.
|
2016-11-01 14:51:04 +01:00
|
|
|
adopt_download: Emitted when a download is retried and should be adopted
|
|
|
|
by the QNAM if needed..
|
|
|
|
arg 0: The new DownloadItem
|
2016-09-10 22:54:13 +02:00
|
|
|
remove_requested: Emitted when the removal of this download was
|
|
|
|
requested.
|
2014-06-11 17:27:39 +02:00
|
|
|
"""
|
|
|
|
|
2016-09-11 20:48:19 +02:00
|
|
|
_MAX_REDIRECTS = 10
|
2016-11-01 14:51:04 +01:00
|
|
|
adopt_download = pyqtSignal(object) # DownloadItem
|
2014-06-11 21:55:23 +02:00
|
|
|
|
2016-11-01 16:37:56 +01:00
|
|
|
def __init__(self, reply, manager):
|
2014-06-11 21:55:23 +02:00
|
|
|
"""Constructor.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
reply: The QNetworkReply to download.
|
|
|
|
"""
|
2016-11-01 16:37:56 +01:00
|
|
|
super().__init__(parent=manager)
|
2014-11-18 20:10:57 +01:00
|
|
|
self.autoclose = True
|
2016-11-01 16:19:15 +01:00
|
|
|
self.fileobj = None
|
|
|
|
self.raw_headers = {}
|
|
|
|
|
|
|
|
self._filename = None
|
|
|
|
self._dead = False
|
|
|
|
|
2016-11-01 16:37:56 +01:00
|
|
|
self._manager = manager
|
2016-11-01 16:19:15 +01:00
|
|
|
self._retry_info = None
|
2016-09-11 20:48:28 +02: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)
|
2016-09-11 20:56:35 +02:00
|
|
|
self._read_timer.timeout.connect(self._on_read_timer_timeout)
|
2014-11-24 00:12:19 +01:00
|
|
|
self._redirects = 0
|
2016-11-01 14:44:08 +01:00
|
|
|
self._init_reply(reply)
|
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:
|
2016-11-01 16:28:47 +01:00
|
|
|
self._set_fileobj(fileobj)
|
2014-12-26 21:58:45 +01:00
|
|
|
|
2016-10-03 20:57:33 +02:00
|
|
|
def _ask_confirm_question(self, title, msg):
|
2014-12-26 21:58:45 +01:00
|
|
|
"""Create a Question object to be asked."""
|
2016-11-01 16:19:15 +01:00
|
|
|
# FIXME:qtwebengine move this?
|
2016-10-03 20:57:33 +02:00
|
|
|
no_action = functools.partial(self.cancel, remove_data=False)
|
2016-10-27 22:54:51 +02:00
|
|
|
message.confirm_async(title=title, text=msg,
|
2016-11-01 16:19:15 +01:00
|
|
|
yes_action=self._after_set_filename,
|
2016-10-03 20:57:33 +02:00
|
|
|
no_action=no_action, cancel_action=no_action,
|
|
|
|
abort_on=[self.cancelled, self.error])
|
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."""
|
2016-11-01 16:19:15 +01:00
|
|
|
super()._die(msg)
|
2014-11-30 15:25:23 +01:00
|
|
|
self._read_timer.stop()
|
2016-09-11 20:48:28 +02:00
|
|
|
self._reply.downloadProgress.disconnect()
|
|
|
|
self._reply.finished.disconnect()
|
|
|
|
self._reply.error.disconnect()
|
|
|
|
self._reply.readyRead.disconnect()
|
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/
|
2016-09-11 20:48:28 +02:00
|
|
|
self._reply.abort()
|
|
|
|
self._reply.deleteLater()
|
|
|
|
self._reply = None
|
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
|
|
|
|
2016-11-01 14:44:08 +01:00
|
|
|
def _init_reply(self, reply):
|
2014-11-24 00:12:19 +01:00
|
|
|
"""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
|
2016-09-11 20:48:28 +02: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)
|
2016-09-11 20:56:35 +02:00
|
|
|
reply.finished.connect(self._on_reply_finished)
|
|
|
|
reply.error.connect(self._on_reply_error)
|
|
|
|
reply.readyRead.connect(self._on_ready_read)
|
|
|
|
reply.metaDataChanged.connect(self._on_meta_data_changed)
|
2016-11-01 14:48:28 +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
|
|
|
|
2016-11-01 16:19:15 +01:00
|
|
|
def _do_cancel(self):
|
2016-09-11 20:48:28 +02:00
|
|
|
if self._reply is not None:
|
2016-09-11 20:56:35 +02:00
|
|
|
self._reply.finished.disconnect(self._on_reply_finished)
|
2016-09-11 20:48:28 +02:00
|
|
|
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()
|
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
|
2016-11-01 14:48:28 +01:00
|
|
|
new_reply = self._retry_info.manager.get(self._retry_info.request)
|
2016-11-01 16:37:56 +01:00
|
|
|
new_download = self._manager.fetch(new_reply,
|
|
|
|
suggested_filename=self.basename)
|
2016-11-01 14:51:04 +01:00
|
|
|
self.adopt_download.emit(new_download)
|
2015-03-09 07:39:40 +01:00
|
|
|
self.cancel()
|
2014-12-10 21:56:57 +01:00
|
|
|
|
2016-11-01 16:19:15 +01:00
|
|
|
def _get_open_filename(self):
|
2016-07-05 23:01:48 +02:00
|
|
|
filename = self._filename
|
|
|
|
if filename is None:
|
|
|
|
filename = getattr(self.fileobj, 'name', None)
|
2016-11-01 16:19:15 +01:00
|
|
|
return filename
|
2014-06-12 17:50:09 +02:00
|
|
|
|
2016-11-01 16:19:15 +01:00
|
|
|
def _ensure_can_set_filename(self, filename):
|
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))
|
2016-11-01 16:19:15 +01:00
|
|
|
|
|
|
|
def _after_set_filename(self):
|
|
|
|
self._create_fileobj()
|
2015-03-05 23:44:12 +01:00
|
|
|
|
2016-11-01 16:28:47 +01:00
|
|
|
def _set_fileobj(self, fileobj):
|
2014-11-14 08:28:59 +01:00
|
|
|
""""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()
|
2016-09-11 20:48:28 +02: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.
|
2016-09-11 20:56:35 +02: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.
|
2016-09-11 20:56:35 +02:00
|
|
|
self._on_ready_read()
|
2014-06-12 17:50:09 +02:00
|
|
|
except OSError as e:
|
|
|
|
self._die(e.strerror)
|
|
|
|
|
2016-09-11 20:56:35 +02: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...")
|
2016-09-11 20:48:28 +02: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()
|
2016-09-11 20:48:28 +02:00
|
|
|
self.successful = self._reply.error() == QNetworkReply.NoError
|
|
|
|
self._reply.close()
|
|
|
|
self._reply.deleteLater()
|
|
|
|
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()
|
2016-09-11 20:56:35 +02:00
|
|
|
def _on_reply_finished(self):
|
2014-06-12 17:50:09 +02:00
|
|
|
"""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.
|
|
|
|
"""
|
2016-09-11 20:48:28 +02:00
|
|
|
if self._reply is None:
|
2014-11-30 18:38:33 +01:00
|
|
|
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.
|
2016-09-11 20:56:35 +02:00
|
|
|
self._finish_download()
|
2014-06-11 21:55:23 +02:00
|
|
|
|
|
|
|
@pyqtSlot()
|
2016-09-11 20:56:35 +02:00
|
|
|
def _on_ready_read(self):
|
2014-06-11 21:55:23 +02:00
|
|
|
"""Read available data and save file when ready to read."""
|
2016-09-11 20:48:28 +02:00
|
|
|
if self.fileobj is None or self._reply is None:
|
2014-11-30 18:38:33 +01:00
|
|
|
# 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
|
2016-09-11 20:48:28 +02: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:
|
2016-09-11 20:48:28 +02: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')
|
2016-09-11 20:56:35 +02:00
|
|
|
def _on_reply_error(self, code):
|
2014-06-12 17:50:09 +02:00
|
|
|
"""Handle QNetworkReply errors."""
|
|
|
|
if code == QNetworkReply.OperationCanceledError:
|
|
|
|
return
|
|
|
|
else:
|
2016-09-11 20:48:28 +02:00
|
|
|
self._die(self._reply.errorString())
|
2014-06-11 21:55:23 +02:00
|
|
|
|
2014-11-30 15:25:23 +01:00
|
|
|
@pyqtSlot()
|
2016-09-11 20:56:35 +02:00
|
|
|
def _on_read_timer_timeout(self):
|
2014-11-30 15:25:23 +01:00
|
|
|
"""Read some bytes from the QNetworkReply periodically."""
|
2016-09-11 20:48:28 +02:00
|
|
|
if not self._reply.isOpen():
|
2014-12-10 16:48:23 +01:00
|
|
|
raise OSError("Reply is closed!")
|
2016-09-11 20:48:28 +02: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()
|
2016-09-11 20:56:35 +02:00
|
|
|
def _on_meta_data_changed(self):
|
2015-09-20 17:11:28 +02:00
|
|
|
"""Update the download's metadata."""
|
2016-09-11 20:48:28 +02:00
|
|
|
if self._reply is None:
|
2015-09-19 20:06:15 +02:00
|
|
|
return
|
|
|
|
self.raw_headers = {}
|
2016-09-11 20:48:28 +02:00
|
|
|
for key, value in self._reply.rawHeaderPairs():
|
2015-09-19 20:06:15 +02:00
|
|
|
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.
|
|
|
|
"""
|
2016-09-11 20:48:28 +02:00
|
|
|
redirect = self._reply.attribute(
|
2014-11-24 00:12:19 +01:00
|
|
|
QNetworkRequest.RedirectionTargetAttribute)
|
|
|
|
if redirect is None or redirect.isEmpty():
|
|
|
|
return False
|
2016-09-11 20:48:28 +02:00
|
|
|
new_url = self._reply.url().resolved(redirect)
|
2016-11-01 14:44:08 +01:00
|
|
|
new_request = self._reply.request()
|
|
|
|
if new_url == new_request.url():
|
2014-11-24 00:12:19 +01:00
|
|
|
return False
|
|
|
|
|
2016-09-11 20:48:19 +02:00
|
|
|
if self._redirects > self._MAX_REDIRECTS:
|
2014-11-24 00:12:19 +01:00
|
|
|
self._die("Maximum redirection count reached!")
|
2016-09-10 00:11:37 +02:00
|
|
|
self.delete()
|
2014-11-24 00:12:19 +01:00
|
|
|
return True # so on_reply_finished aborts
|
|
|
|
|
|
|
|
log.downloads.debug("{}: Handling redirect".format(self))
|
|
|
|
self._redirects += 1
|
2016-11-01 14:44:08 +01:00
|
|
|
new_request.setUrl(new_url)
|
|
|
|
old_reply = self._reply
|
|
|
|
old_reply.finished.disconnect(self._on_reply_finished)
|
2014-12-08 16:16:03 +01:00
|
|
|
self._read_timer.stop()
|
2016-09-11 20:48:28 +02:00
|
|
|
self._reply = None
|
2014-11-24 21:04:48 +01:00
|
|
|
if self.fileobj is not None:
|
|
|
|
self.fileobj.seek(0)
|
2016-11-01 14:44:08 +01:00
|
|
|
|
|
|
|
log.downloads.debug("redirected: {} -> {}".format(
|
|
|
|
old_reply.url(), new_request.url()))
|
|
|
|
new_reply = old_reply.manager().get(new_request)
|
|
|
|
self._init_reply(new_reply)
|
|
|
|
|
|
|
|
old_reply.deleteLater()
|
2014-11-24 00:12:19 +01:00
|
|
|
return True
|
|
|
|
|
2016-11-01 16:35:22 +01:00
|
|
|
def _uses_nam(self, nam):
|
2016-09-11 21:27:16 +02:00
|
|
|
"""Check if this download uses the given QNetworkAccessManager."""
|
2016-09-11 20:48:28 +02:00
|
|
|
running_nam = self._reply is not None and self._reply.manager() is nam
|
|
|
|
# user could request retry after tab is closed.
|
|
|
|
retry_nam = (self.done and (not self.successful) and
|
2016-11-01 14:48:28 +01:00
|
|
|
self._retry_info.manager is nam)
|
2016-09-11 20:48:28 +02:00
|
|
|
return running_nam or retry_nam
|
|
|
|
|
2016-11-01 16:28:47 +01:00
|
|
|
def set_target(self, target):
|
|
|
|
if isinstance(target, usertypes.FileObjDownloadTarget):
|
|
|
|
self._set_fileobj(target.fileobj)
|
|
|
|
self.autoclose = False
|
|
|
|
elif isinstance(target, usertypes.FileDownloadTarget):
|
|
|
|
self.set_filename(target.filename)
|
|
|
|
elif isinstance(target, usertypes.OpenFileDownloadTarget):
|
|
|
|
tmp_manager = objreg.get('temporary-downloads')
|
|
|
|
try:
|
|
|
|
fobj = tmp_manager.get_tmpfile(self.basename)
|
|
|
|
except OSError as exc:
|
|
|
|
msg = "Download error: {}".format(exc)
|
|
|
|
message.error(msg)
|
|
|
|
self.cancel()
|
|
|
|
return
|
|
|
|
self.finished.connect(
|
|
|
|
functools.partial(self._open_if_successful, target.cmdline))
|
|
|
|
self.autoclose = True
|
|
|
|
self._set_fileobj(fobj)
|
|
|
|
else: # pragma: no cover
|
2016-11-01 16:35:22 +01:00
|
|
|
raise ValueError("Unsupported download target: {}".format(target))
|
2016-11-01 16:28:47 +01:00
|
|
|
|
2014-06-11 17:27:39 +02:00
|
|
|
|
2016-09-10 22:38:34 +02:00
|
|
|
class DownloadManager(QObject):
|
2014-06-10 22:11:17 +02:00
|
|
|
|
2016-09-10 22:38:34 +02:00
|
|
|
"""Manager 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.
|
2016-09-10 22:38:34 +02:00
|
|
|
|
|
|
|
Signals:
|
|
|
|
begin_remove_rows: Emitted before downloads are removed.
|
|
|
|
end_remove_rows: Emitted after downloads are removed.
|
|
|
|
begin_insert_rows: Emitted before downloads are inserted.
|
|
|
|
end_insert_rows: Emitted after downloads are inserted.
|
|
|
|
data_changed: Emitted when the data of the model changed.
|
|
|
|
The arguments are int indices to the downloads.
|
2014-06-12 08:02:44 +02:00
|
|
|
"""
|
|
|
|
|
2016-09-11 16:03:03 +02:00
|
|
|
# parent, first, last
|
|
|
|
begin_remove_rows = pyqtSignal(QModelIndex, int, int)
|
2016-09-10 22:38:34 +02:00
|
|
|
end_remove_rows = pyqtSignal()
|
2016-09-11 16:03:03 +02:00
|
|
|
# parent, first, last
|
|
|
|
begin_insert_rows = pyqtSignal(QModelIndex, int, int)
|
2016-09-10 22:38:34 +02:00
|
|
|
end_insert_rows = pyqtSignal()
|
|
|
|
data_changed = pyqtSignal(int, int) # begin, end
|
|
|
|
|
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)
|
|
|
|
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')
|
2016-09-11 20:56:35 +02:00
|
|
|
self._update_timer.timeout.connect(self._update_gui)
|
2016-09-11 20:48:19 +02:00
|
|
|
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()
|
2016-09-11 20:56:35 +02:00
|
|
|
def _update_gui(self):
|
2015-06-07 22:22:23 +02:00
|
|
|
"""Periodical GUI update of all items."""
|
|
|
|
assert self.downloads
|
|
|
|
for dl in self.downloads:
|
|
|
|
dl.stats.update_speed()
|
2016-09-10 22:38:34 +02:00
|
|
|
self.data_changed.emit(0, -1)
|
2015-06-07 22:22:23 +02:00
|
|
|
|
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():
|
2016-09-14 20:52:32 +02:00
|
|
|
urlutils.invalid_url_error(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.
|
2016-09-11 20:56:35 +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-09-11 20:56:35 +02:00
|
|
|
return self._fetch_request(request,
|
|
|
|
target=target,
|
|
|
|
suggested_filename=suggested_fn,
|
|
|
|
**kwargs)
|
2014-11-30 18:07:44 +01:00
|
|
|
|
2016-09-11 20:56:35 +02:00
|
|
|
def _fetch_request(self, request, *, qnam=None, **kwargs):
|
2014-11-30 18:07:44 +01:00
|
|
|
"""Download a QNetworkRequest to disk.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
request: The QNetworkRequest to download.
|
2016-09-10 23:07:21 +02:00
|
|
|
qnam: The QNetworkAccessManager 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.
|
|
|
|
"""
|
2016-09-10 23:07:21 +02:00
|
|
|
if qnam is None:
|
|
|
|
qnam = self._networkmanager
|
|
|
|
reply = qnam.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))
|
2016-11-01 16:37:56 +01:00
|
|
|
download = DownloadItem(reply, manager=self)
|
2016-09-10 22:54:13 +02:00
|
|
|
download.cancelled.connect(download.remove)
|
|
|
|
download.remove_requested.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(
|
2016-09-10 22:54:13 +02:00
|
|
|
lambda: QTimer.singleShot(delay, download.remove))
|
2015-11-09 22:45:51 +01:00
|
|
|
elif auto_remove:
|
2016-09-10 22:54:13 +02:00
|
|
|
download.finished.connect(download.remove)
|
2015-11-09 22:45:51 +01:00
|
|
|
|
2014-08-26 19:10:14 +02:00
|
|
|
download.data_changed.connect(
|
2016-09-11 20:56:35 +02:00
|
|
|
functools.partial(self._on_data_changed, download))
|
|
|
|
download.error.connect(self._on_error)
|
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
|
2016-09-10 22:38:34 +02:00
|
|
|
self.begin_insert_rows.emit(QModelIndex(), idx, idx)
|
2014-06-12 17:50:09 +02:00
|
|
|
self.downloads.append(download)
|
2016-09-10 22:38:34 +02:00
|
|
|
self.end_insert_rows.emit()
|
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:
|
2016-11-01 16:28:47 +01:00
|
|
|
download.set_target(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(
|
2016-10-28 11:31:39 +02:00
|
|
|
suggested_filename, parent=self,
|
2015-11-11 23:45:53 +01:00
|
|
|
prompt_download_directory=prompt_download_directory,
|
2016-10-28 18:40:55 +02:00
|
|
|
url=reply.url())
|
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-11-01 16:28:47 +01:00
|
|
|
download.set_target(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-11-01 16:28:47 +01:00
|
|
|
q.answered.connect(download.set_target)
|
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-09-10 22:38:34 +02:00
|
|
|
@pyqtSlot(DownloadItem)
|
2016-09-11 20:56:35 +02:00
|
|
|
def _on_data_changed(self, download):
|
2016-09-10 22:38:34 +02:00
|
|
|
"""Emit data_changed signal when download data changed."""
|
|
|
|
try:
|
|
|
|
idx = self.downloads.index(download)
|
|
|
|
except ValueError:
|
|
|
|
# download has been deleted in the meantime
|
|
|
|
return
|
|
|
|
self.data_changed.emit(idx, idx)
|
|
|
|
|
|
|
|
@pyqtSlot(str)
|
2016-09-11 20:56:35 +02:00
|
|
|
def _on_error(self, msg):
|
2016-09-10 22:38:34 +02:00
|
|
|
"""Display error message on download errors."""
|
2016-09-14 20:52:32 +02:00
|
|
|
message.error("Download error: {}".format(msg))
|
2016-09-10 22:38:34 +02: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.
|
|
|
|
"""
|
|
|
|
assert nam.adopted_downloads == 0
|
|
|
|
for download in self.downloads:
|
2016-11-01 16:35:22 +01:00
|
|
|
if download._uses_nam(nam): # pylint: disable=protected-access
|
2016-09-10 22:38:34 +02:00
|
|
|
nam.adopt_download(download)
|
|
|
|
return nam.adopted_downloads
|
|
|
|
|
2016-09-10 22:54:13 +02:00
|
|
|
@pyqtSlot(DownloadItem)
|
|
|
|
def _remove_item(self, download):
|
2016-09-10 22:38:34 +02:00
|
|
|
"""Remove a given download."""
|
|
|
|
if sip.isdeleted(self):
|
|
|
|
# https://github.com/The-Compiler/qutebrowser/issues/1242
|
|
|
|
return
|
|
|
|
try:
|
|
|
|
idx = self.downloads.index(download)
|
|
|
|
except ValueError:
|
|
|
|
# already removed
|
|
|
|
return
|
|
|
|
self.begin_remove_rows.emit(QModelIndex(), idx, idx)
|
|
|
|
del self.downloads[idx]
|
|
|
|
self.end_remove_rows.emit()
|
|
|
|
download.deleteLater()
|
2016-09-11 20:56:35 +02:00
|
|
|
self._update_indexes()
|
2016-09-10 22:38:34 +02:00
|
|
|
if not self.downloads:
|
|
|
|
self._update_timer.stop()
|
|
|
|
log.downloads.debug("Removed download {}".format(download))
|
|
|
|
|
2016-09-11 20:56:35 +02:00
|
|
|
def _update_indexes(self):
|
2016-09-10 22:38:34 +02:00
|
|
|
"""Update indexes of all DownloadItems."""
|
|
|
|
first_idx = None
|
|
|
|
for i, d in enumerate(self.downloads, 1):
|
|
|
|
if first_idx is None and d.index != i:
|
|
|
|
first_idx = i - 1
|
|
|
|
d.index = i
|
|
|
|
if first_idx is not None:
|
|
|
|
self.data_changed.emit(first_idx, -1)
|
|
|
|
|
|
|
|
|
|
|
|
class DownloadModel(QAbstractListModel):
|
|
|
|
|
2016-09-11 16:03:03 +02:00
|
|
|
"""A list model showing downloads."""
|
|
|
|
|
2016-09-10 22:38:34 +02:00
|
|
|
def __init__(self, downloader, parent=None):
|
|
|
|
super().__init__(parent)
|
|
|
|
self._downloader = downloader
|
|
|
|
# FIXME we'll need to translate indices here...
|
|
|
|
downloader.data_changed.connect(self._on_data_changed)
|
|
|
|
downloader.begin_insert_rows.connect(self.beginInsertRows)
|
|
|
|
downloader.end_insert_rows.connect(self.endInsertRows)
|
|
|
|
downloader.begin_remove_rows.connect(self.beginRemoveRows)
|
|
|
|
downloader.end_remove_rows.connect(self.endRemoveRows)
|
|
|
|
|
2016-09-10 22:45:14 +02:00
|
|
|
def _all_downloads(self):
|
|
|
|
"""Combine downloads from both downloaders."""
|
|
|
|
return self._downloader.downloads[:]
|
|
|
|
|
2016-09-10 22:38:34 +02:00
|
|
|
def __len__(self):
|
|
|
|
return len(self._all_downloads())
|
|
|
|
|
2016-09-10 22:45:14 +02:00
|
|
|
def __iter__(self):
|
|
|
|
return iter(self._all_downloads())
|
|
|
|
|
|
|
|
def __getitem__(self, idx):
|
|
|
|
return self._all_downloads()[idx]
|
|
|
|
|
2016-09-10 22:38:34 +02:00
|
|
|
@pyqtSlot(int, int)
|
|
|
|
def _on_data_changed(self, start, end):
|
|
|
|
"""Called when a downloader's data changed.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
start: The first changed index as int.
|
|
|
|
end: The last changed index as int, or -1 for all indices.
|
|
|
|
"""
|
|
|
|
# FIXME we'll need to translate indices here...
|
|
|
|
start_index = self.index(start, 0)
|
|
|
|
qtutils.ensure_valid(start_index)
|
|
|
|
if end == -1:
|
|
|
|
end_index = self.last_index()
|
|
|
|
else:
|
|
|
|
end_index = self.index(end, 0)
|
|
|
|
qtutils.ensure_valid(end_index)
|
|
|
|
self.dataChanged.emit(start_index, end_index)
|
|
|
|
|
|
|
|
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-09-10 22:38:34 +02:00
|
|
|
@cmdutils.register(instance='download-model', scope='window')
|
2016-05-10 19:51:11 +02:00
|
|
|
@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-09-10 22:38:34 +02:00
|
|
|
downloads = self._all_downloads()
|
2016-03-14 19:05:15 +01:00
|
|
|
if all_:
|
2016-09-10 22:38:34 +02:00
|
|
|
for download in downloads:
|
2016-03-14 19:05:15 +01:00
|
|
|
if not download.done:
|
|
|
|
download.cancel()
|
|
|
|
else:
|
|
|
|
try:
|
2016-09-10 22:38:34 +02:00
|
|
|
download = downloads[count - 1]
|
2016-03-14 19:05:15 +01:00
|
|
|
except IndexError:
|
2016-09-10 22:38:34 +02:00
|
|
|
self._raise_no_download(count)
|
2016-03-14 19:05:15 +01:00
|
|
|
if download.done:
|
|
|
|
if not count:
|
2016-09-10 22:45:14 +02:00
|
|
|
count = len(self)
|
2016-03-14 19:05:15 +01:00
|
|
|
raise cmdexc.CommandError("Download {} is already done!"
|
|
|
|
.format(count))
|
|
|
|
download.cancel()
|
2014-11-30 18:07:44 +01:00
|
|
|
|
2016-09-10 22:38:34 +02:00
|
|
|
@cmdutils.register(instance='download-model', scope='window')
|
2016-05-10 19:51:11 +02:00
|
|
|
@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:
|
2016-09-10 22:45:14 +02:00
|
|
|
download = self[count - 1]
|
2015-02-12 22:20:22 +01:00
|
|
|
except IndexError:
|
2016-09-10 22:38:34 +02: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:
|
2016-09-10 22:38:34 +02:00
|
|
|
count = len(self)
|
2015-02-12 22:20:22 +01:00
|
|
|
raise cmdexc.CommandError("Download {} is not done!".format(count))
|
|
|
|
download.delete()
|
2016-09-10 22:54:13 +02:00
|
|
|
download.remove()
|
2016-04-26 22:56:06 +02:00
|
|
|
log.downloads.debug("deleted download {}".format(download))
|
2015-02-12 22:20:22 +01:00
|
|
|
|
2016-09-10 22:38:34 +02:00
|
|
|
@cmdutils.register(instance='download-model', 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:
|
2016-09-10 22:45:14 +02:00
|
|
|
download = self[count - 1]
|
2015-02-08 22:03:29 +01:00
|
|
|
except IndexError:
|
2016-09-10 22:38:34 +02: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:
|
2016-09-10 22:38:34 +02:00
|
|
|
count = len(self)
|
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-09-10 22:38:34 +02:00
|
|
|
@cmdutils.register(instance='download-model', scope='window')
|
2016-05-10 19:51:11 +02:00
|
|
|
@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:
|
2016-09-10 22:45:14 +02:00
|
|
|
download = self[count - 1]
|
2015-11-09 07:17:54 +01:00
|
|
|
except IndexError:
|
2016-09-10 22:38:34 +02:00
|
|
|
self._raise_no_download(count)
|
2015-11-09 07:17:54 +01:00
|
|
|
if download.successful or not download.done:
|
|
|
|
raise cmdexc.CommandError("Download {} did not fail!".format(
|
|
|
|
count))
|
|
|
|
else:
|
2016-09-10 22:45:14 +02:00
|
|
|
to_retry = [d for d in self if d.done and not d.successful]
|
2015-11-09 07:17:54 +01:00
|
|
|
if not to_retry:
|
|
|
|
raise cmdexc.CommandError("No failed downloads!")
|
|
|
|
else:
|
|
|
|
download = to_retry[0]
|
|
|
|
download.retry()
|
|
|
|
|
2014-12-16 14:30:47 +01:00
|
|
|
def can_clear(self):
|
|
|
|
"""Check if there are finished downloads to clear."""
|
2016-09-10 22:45:14 +02:00
|
|
|
return any(download.done for download in self)
|
2014-12-16 14:30:47 +01:00
|
|
|
|
2016-09-10 22:38:34 +02:00
|
|
|
@cmdutils.register(instance='download-model', scope='window')
|
2015-11-03 19:27:02 +01:00
|
|
|
def download_clear(self):
|
|
|
|
"""Remove all finished downloads from the list."""
|
2016-09-10 22:54:13 +02:00
|
|
|
for download in self:
|
|
|
|
if download.done:
|
|
|
|
download.remove()
|
2015-11-03 19:27:02 +01:00
|
|
|
|
2016-09-10 22:38:34 +02:00
|
|
|
@cmdutils.register(instance='download-model', scope='window')
|
2016-05-10 19:51:11 +02:00
|
|
|
@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:
|
2016-09-10 22:45:14 +02:00
|
|
|
download = self[count - 1]
|
2015-02-12 21:05:53 +01:00
|
|
|
except IndexError:
|
2016-09-10 22:38:34 +02: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:
|
2016-09-10 22:38:34 +02:00
|
|
|
count = len(self)
|
2015-02-12 23:29:05 +01:00
|
|
|
raise cmdexc.CommandError("Download {} is not done!"
|
|
|
|
.format(count))
|
2016-09-10 22:54:13 +02:00
|
|
|
download.remove()
|
2014-12-16 14:30:47 +01:00
|
|
|
|
2016-09-10 22:38:34 +02:00
|
|
|
def running_downloads(self):
|
|
|
|
"""Return the amount of still running downloads.
|
|
|
|
|
|
|
|
Return:
|
|
|
|
The number of unfinished downloads.
|
|
|
|
"""
|
2016-09-10 22:45:14 +02:00
|
|
|
return sum(1 for download in self if not download.done)
|
2016-09-10 22:38:34 +02: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
|
|
|
|
|
2016-09-10 00:12:03 +02:00
|
|
|
def headerData(self, section, orientation, role=Qt.DisplayRole):
|
2014-10-08 20:18:44 +02:00
|
|
|
"""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."""
|
2016-09-10 00:12:03 +02:00
|
|
|
if not index.isValid():
|
|
|
|
return None
|
|
|
|
|
2014-10-08 20:18:44 +02:00
|
|
|
if index.parent().isValid() or index.column() != 0:
|
2016-09-10 00:12:03 +02:00
|
|
|
return None
|
2014-10-08 20:18:44 +02:00
|
|
|
|
2016-09-10 22:45:14 +02:00
|
|
|
item = self[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:
|
2016-09-10 00:12:03 +02:00
|
|
|
data = None
|
2014-10-15 21:22:53 +02:00
|
|
|
else:
|
2014-10-20 00:33:52 +02:00
|
|
|
return item.error_msg
|
2014-10-08 20:18:44 +02:00
|
|
|
else:
|
2016-09-10 00:12:03 +02:00
|
|
|
data = None
|
2014-10-08 20:18:44 +02:00
|
|
|
return data
|
|
|
|
|
2016-09-10 00:12:03 +02:00
|
|
|
def flags(self, index):
|
2014-10-08 20:18:44 +02:00
|
|
|
"""Override flags so items aren't selectable.
|
|
|
|
|
2016-04-08 07:35:53 +02:00
|
|
|
The default would be Qt.ItemIsEnabled | Qt.ItemIsSelectable.
|
|
|
|
"""
|
2016-09-10 00:12:03 +02:00
|
|
|
if not index.isValid():
|
2016-09-11 17:10:52 +02:00
|
|
|
return Qt.ItemFlags()
|
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
|
2016-09-10 22:38:34 +02:00
|
|
|
return len(self)
|
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:
|
2016-09-12 11:30:44 +02:00
|
|
|
try:
|
|
|
|
self._tmpdir.cleanup()
|
|
|
|
except OSError:
|
|
|
|
log.misc.exception("Failed to clean up temporary download "
|
|
|
|
"directory")
|
2016-07-06 18:41:08 +02:00
|
|
|
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
|