qutebrowser/qutebrowser/browser/downloads.py

501 lines
18 KiB
Python
Raw Normal View History

2014-06-19 09:04:37 +02:00
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# 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."""
import os
import os.path
2014-08-26 19:10:14 +02:00
import functools
import collections
from PyQt5.QtCore import (pyqtSlot, pyqtSignal, QObject, QTimer,
QStandardPaths, Qt, QVariant, QAbstractListModel,
QModelIndex)
2014-06-19 17:58:46 +02:00
from PyQt5.QtNetwork import QNetworkRequest, QNetworkReply
2014-09-28 22:38:11 +02:00
# We need this import so PyQt can use it inside pyqtSlot
from PyQt5.QtWebKitWidgets import QWebPage # pylint: disable=unused-import
2014-08-26 19:10:14 +02:00
from qutebrowser.config import config
from qutebrowser.commands import cmdexc, cmdutils
from qutebrowser.utils import (message, http, usertypes, log, utils, urlutils,
objreg, standarddir, qtutils)
ModelRole = usertypes.enum('ModelRole', ['item'], start=Qt.UserRole,
is_int=True)
2014-06-11 17:27:39 +02:00
class DownloadItem(QObject):
"""A single download currently running.
2014-06-11 21:55:23 +02:00
Class attributes:
SPEED_REFRESH_INTERVAL: How often to refresh the speed, in msec.
SPEED_AVG_WINDOW: How many seconds of speed data to average to
estimate the remaining time.
2014-06-11 21:55:23 +02:00
2014-06-11 17:27:39 +02:00
Attributes:
2014-10-20 00:33:52 +02:00
error_msg: The current error message, or None
_bytes_done: How many bytes there are already downloaded.
_bytes_total: The total count of bytes.
None if the total is unknown.
_speed: The current download speed, in bytes per second.
_fileobj: The file object to download the file to.
_filename: The filename of the download.
_is_cancelled: Whether the download was cancelled.
_speed_avg: A rolling average of speeds.
_reply: The QNetworkReply associated with this download.
2014-06-11 21:55:23 +02:00
_last_done: The count of bytes which where downloaded when calculating
the speed the last time.
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.
cancelled: The download was cancelled.
error: An error with the download occured.
arg: The error message as string.
2014-06-11 17:27:39 +02:00
"""
SPEED_REFRESH_INTERVAL = 500
SPEED_AVG_WINDOW = 30
2014-06-12 23:29:34 +02:00
data_changed = pyqtSignal()
2014-06-12 08:02:44 +02:00
finished = pyqtSignal()
error = pyqtSignal(str)
cancelled = pyqtSignal()
2014-06-11 21:55:23 +02:00
def __init__(self, reply, 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)
self._reply = reply
self._bytes_total = None
self._speed = 0
2014-10-20 00:33:52 +02:00
self.error_msg = None
2014-06-12 23:29:34 +02:00
self.basename = '???'
samples = int(self.SPEED_AVG_WINDOW *
(1000 / self.SPEED_REFRESH_INTERVAL))
self._speed_avg = collections.deque(maxlen=samples)
self._fileobj = None
self._filename = None
self._is_cancelled = False
self._do_delayed_write = False
self._bytes_done = 0
2014-06-13 22:51:16 +02:00
self._last_done = 0
reply.setReadBufferSize(16 * 1024 * 1024)
2014-06-11 21:55:23 +02:00
reply.downloadProgress.connect(self.on_download_progress)
reply.finished.connect(self.on_reply_finished)
reply.error.connect(self.on_reply_error)
2014-06-12 10:18:02 +02:00
reply.readyRead.connect(self.on_ready_read)
2014-06-19 21:36:40 +02: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:
QTimer.singleShot(0, lambda: self.error.emit(reply.errorString()))
if reply.isFinished():
QTimer.singleShot(0, self.finished.emit)
2014-08-26 19:10:14 +02:00
self.timer = usertypes.Timer(self, 'speed_refresh')
2014-06-11 21:55:23 +02:00
self.timer.timeout.connect(self.update_speed)
self.timer.setInterval(self.SPEED_REFRESH_INTERVAL)
2014-06-11 21:55:23 +02:00
self.timer.start()
def __repr__(self):
2014-09-26 15:48:24 +02:00
return utils.get_repr(self, basename=self.basename)
2014-06-12 23:29:34 +02:00
def __str__(self):
"""Get the download as a string.
Example: foo.pdf [699.2kB/s|0.34|16%|4.253/25.124]
2014-06-12 23:29:34 +02:00
"""
speed = utils.format_size(self._speed, suffix='B/s')
down = utils.format_size(self._bytes_done, suffix='B')
perc = self._percentage()
remaining = self._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)
if all(e is None for e in (perc, remaining, self._bytes_total)):
2014-10-15 21:22:53 +02:00
return ('{name} [{speed:>10}|{down}]{errmsg}'.format(
name=self.basename, speed=speed, down=down, errmsg=errmsg))
if perc is None:
perc = '??'
else:
perc = round(perc)
if remaining is None:
remaining = '?'
else:
remaining = utils.format_seconds(remaining)
total = utils.format_size(self._bytes_total, suffix='B')
return ('{name} [{speed:>10}|{remaining:>5}|{perc:>2}%|'
2014-10-15 21:22:53 +02:00
'{down}/{total}]{errmsg}'.format(
name=self.basename, speed=speed, remaining=remaining,
perc=perc, down=down, total=total, errmsg=errmsg))
2014-06-12 23:29:34 +02:00
def _die(self, msg):
"""Abort the download and emit an error."""
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
self._bytes_done = self._bytes_total
2014-09-22 17:56:23 +02:00
self.timer.stop()
self.error.emit(msg)
self._reply.abort()
self._reply.deleteLater()
2014-10-15 21:22:53 +02:00
self._reply = None
if self._fileobj is not None:
try:
self._fileobj.close()
except OSError as e:
self.error.emit(e.strerror)
2014-10-15 21:22:53 +02:00
self.data_changed.emit()
def _percentage(self):
"""The current download percentage, or None if unknown."""
if self._bytes_total == 0 or self._bytes_total is None:
2014-06-11 21:55:23 +02:00
return None
else:
return 100 * self._bytes_done / self._bytes_total
2014-06-11 17:27:39 +02:00
def _remaining_time(self):
"""The remaining download time in seconds, or None."""
if self._bytes_total is None or not self._speed_avg:
2014-06-13 22:51:16 +02:00
# No average yet or we don't know the total size.
2014-06-12 23:29:34 +02:00
return None
remaining_bytes = self._bytes_total - self._bytes_done
avg = sum(self._speed_avg) / len(self._speed_avg)
2014-06-13 22:51:16 +02:00
if avg == 0:
# Download stalled
return None
else:
return remaining_bytes / avg
2014-06-12 23:29:34 +02:00
2014-06-12 21:43:30 +02:00
def bg_color(self):
"""Background color to be shown."""
2014-06-13 07:41:51 +02:00
start = config.get('colors', 'downloads.bg.start')
stop = config.get('colors', 'downloads.bg.stop')
system = config.get('colors', 'downloads.bg.system')
2014-10-15 21:22:53 +02:00
error = config.get('colors', 'downloads.bg.error')
2014-10-20 00:33:52 +02:00
if self.error_msg is not None:
2014-10-15 21:22:53 +02:00
return error
elif self._percentage() is None:
2014-06-12 21:43:30 +02:00
return start
else:
return utils.interpolate_color(start, stop, self._percentage(),
2014-06-23 12:17:13 +02:00
system)
2014-06-12 21:43:30 +02:00
def cancel(self):
"""Cancel the download."""
2014-08-26 20:15:41 +02:00
log.downloads.debug("cancelled")
self.cancelled.emit()
self._is_cancelled = True
2014-10-15 21:22:53 +02:00
if self._reply is not None:
self._reply.abort()
self._reply.deleteLater()
if self._fileobj is not None:
self._fileobj.close()
if self._filename is not None and os.path.exists(self._filename):
os.remove(self._filename)
self.finished.emit()
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.
"""
if self._filename is not None:
raise ValueError("Filename was already set! filename: {}, "
"existing: {}".format(filename, self._filename))
filename = os.path.expanduser(filename)
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.
self._filename = os.path.join(filename, self.basename)
elif os.path.isabs(filename):
# We got an absolute filename from the user, so we save it under
# that filename.
self._filename = filename
self.basename = os.path.basename(self._filename)
else:
# We only got a filename (without directory) from the user, so we
# save it under that filename in the default directory.
download_dir = config.get('storage', 'download-directory')
if download_dir is None:
download_dir = standarddir.get(
QStandardPaths.DownloadLocation)
self._filename = os.path.join(download_dir, filename)
self.basename = filename
2014-08-26 20:15:41 +02:00
log.downloads.debug("Setting filename to {}".format(filename))
try:
self._fileobj = open(self._filename, 'wb')
if self._do_delayed_write:
# Downloading to the buffer in RAM has already finished so we
# write out the data and clean up now.
self.delayed_write()
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)
def delayed_write(self):
"""Write buffered data to disk and finish the QNetworkReply."""
2014-08-26 20:15:41 +02:00
log.downloads.debug("Doing delayed write...")
self._do_delayed_write = False
self._fileobj.write(self._reply.readAll())
self._fileobj.close()
self._reply.close()
self._reply.deleteLater()
self.finished.emit()
2014-08-26 20:15:41 +02:00
log.downloads.debug("Download finished")
2014-06-11 17:27:39 +02:00
@pyqtSlot(int, int)
2014-06-11 21:55:23 +02:00
def on_download_progress(self, bytes_done, bytes_total):
2014-06-11 21:58:06 +02:00
"""Upload local variables when the download progress changed.
Args:
bytes_done: How many bytes are downloaded.
bytes_total: How many bytes there are to download in total.
"""
2014-06-13 22:51:16 +02:00
if bytes_total == -1:
bytes_total = None
self._bytes_done = bytes_done
self._bytes_total = bytes_total
2014-06-12 23:29:34 +02:00
self.data_changed.emit()
2014-06-11 21:55:23 +02:00
@pyqtSlot()
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.
"""
self._bytes_done = self._bytes_total
2014-06-11 21:55:23 +02:00
self.timer.stop()
if self._is_cancelled:
return
log.downloads.debug("Reply finished, fileobj {}".format(self._fileobj))
if self._fileobj is None:
# We'll handle emptying the buffer and cleaning up as soon as the
# filename is set.
self._do_delayed_write = True
else:
# We can do a "delayed" write immediately to empty the buffer and
# clean up.
self.delayed_write()
2014-06-11 21:55:23 +02:00
@pyqtSlot()
def on_ready_read(self):
"""Read available data and save file when ready to read."""
if self._fileobj is None:
# No filename has been set yet, so we don't empty the buffer.
return
try:
self._fileobj.write(self._reply.readAll())
except OSError as e:
self._die(e.strerror)
@pyqtSlot(int)
def on_reply_error(self, code):
"""Handle QNetworkReply errors."""
if code == QNetworkReply.OperationCanceledError:
return
else:
self.error.emit(self._reply.errorString())
2014-06-11 21:55:23 +02:00
@pyqtSlot()
def update_speed(self):
"""Recalculate the current download speed."""
delta = self._bytes_done - self._last_done
self._speed = delta * 1000 / self.SPEED_REFRESH_INTERVAL
self._speed_avg.append(self._speed)
self._last_done = self._bytes_done
2014-06-12 23:29:34 +02:00
self.data_changed.emit()
2014-06-11 17:27:39 +02:00
class DownloadManager(QAbstractListModel):
"""Manager and model for currently running downloads.
2014-06-12 08:02:44 +02:00
Attributes:
downloads: A list of active DownloadItems.
questions: A list of Question objects to not GC them.
2014-06-12 08:02:44 +02:00
"""
def __init__(self, parent=None):
super().__init__(parent)
self.downloads = []
self.questions = []
def __repr__(self):
2014-09-26 15:48:24 +02:00
return utils.get_repr(self, downloads=len(self.downloads))
@pyqtSlot('QUrl', 'QWebPage')
def get(self, url, page):
2014-06-19 17:58:46 +02:00
"""Start a download with a link URL.
Args:
url: The URL to get, as QUrl
page: The QWebPage to get the download from.
2014-06-19 17:58:46 +02:00
"""
if not url.isValid():
urlutils.invalid_url_error('last-focused', url, "start download")
return
req = QNetworkRequest(url)
reply = page.networkAccessManager().get(req)
2014-06-19 17:58:46 +02:00
self.fetch(reply)
2014-09-23 23:05:55 +02:00
@cmdutils.register(instance='download-manager')
def cancel_download(self, count: {'special': 'count'}=1):
2014-09-13 00:33:15 +02:00
"""Cancel the first/[count]th download.
Args:
count: The index of the download to cancel.
"""
2014-06-19 17:58:46 +02:00
if count == 0:
return
try:
download = self.downloads[count - 1]
except IndexError:
2014-08-26 19:10:14 +02:00
raise cmdexc.CommandError("There's no download {}!".format(count))
2014-06-19 17:58:46 +02:00
download.cancel()
@pyqtSlot('QNetworkReply')
def fetch(self, reply):
"""Download a QNetworkReply to disk.
Args:
reply: The QNetworkReply to download.
"""
2014-08-26 19:10:14 +02:00
_inline, 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-06-17 07:17:21 +02:00
download = DownloadItem(reply, self)
2014-08-26 19:10:14 +02:00
download.finished.connect(
functools.partial(self.on_finished, download))
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-06-12 23:29:34 +02:00
download.basename = suggested_filename
idx = len(self.downloads) + 1
self.beginInsertRows(QModelIndex(), idx, idx)
self.downloads.append(download)
self.endInsertRows()
2014-08-26 19:10:14 +02:00
q = usertypes.Question(self)
q.text = "Save file to:"
2014-08-26 19:10:14 +02:00
q.mode = usertypes.PromptMode.text
q.default = suggested_filename
q.answered.connect(download.set_filename)
q.cancelled.connect(download.cancel)
2014-06-27 07:56:16 +02:00
q.completed.connect(q.deleteLater)
2014-08-26 19:10:14 +02:00
q.destroyed.connect(functools.partial(self.questions.remove, q))
self.questions.append(q)
download.cancelled.connect(q.abort)
message_bridge = objreg.get('message-bridge', scope='window',
window='last-focused')
message_bridge.ask(q, blocking=False)
2014-06-12 08:02:44 +02:00
@pyqtSlot(DownloadItem)
def on_finished(self, download):
2014-06-12 17:56:28 +02:00
"""Remove finished download."""
2014-08-26 20:15:41 +02:00
log.downloads.debug("on_finished: {}".format(download))
idx = self.downloads.index(download)
self.beginRemoveRows(QModelIndex(), idx, idx)
2014-06-12 08:02:44 +02:00
del self.downloads[idx]
self.endRemoveRows()
2014-06-17 11:06:59 +02:00
download.deleteLater()
@pyqtSlot(DownloadItem)
def on_data_changed(self, download):
2014-06-12 17:56:28 +02:00
"""Emit data_changed signal when download data changed."""
idx = self.downloads.index(download)
model_idx = self.index(idx, 0)
qtutils.ensure_valid(model_idx)
self.dataChanged.emit(model_idx, model_idx)
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."""
message.error('last-focused', "Download error: {}".format(msg))
def last_index(self):
"""Get the last index in the model.
Return:
A (possibly invalid) QModelIndex.
"""
idx = self.index(self.rowCount() - 1)
return idx
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()
item = objreg.get('download-manager').downloads[index.row()]
if role == Qt.DisplayRole:
data = str(item)
elif role == Qt.ForegroundRole:
data = config.get('colors', 'downloads.fg')
elif role == Qt.BackgroundRole:
data = item.bg_color()
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
else:
data = QVariant()
return data
def flags(self, _index):
"""Override flags so items aren't selectable.
The default would be Qt.ItemIsEnabled | Qt.ItemIsSelectable."""
return Qt.ItemIsEnabled
def rowCount(self, parent=QModelIndex()):
"""Get count of active downloads."""
if parent.isValid():
# We don't have children
return 0
return len(objreg.get('download-manager').downloads)