summaryrefslogtreecommitdiff
path: root/qutebrowser/browser/downloads.py
blob: 4f7897c9db7a426675f8b7865d4d6185ad36c211 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:

# Copyright 2014-2021 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 <https://www.gnu.org/licenses/>.

"""Shared QtWebKit/QtWebEngine code for downloads."""

import re
import sys
import html
import os.path
import collections
import functools
import pathlib
import tempfile
import enum
from typing import Any, Dict, IO, List, MutableSequence, Optional, Union

from PyQt5.QtCore import (pyqtSlot, pyqtSignal, Qt, QObject, QModelIndex,
                          QTimer, QAbstractListModel, QUrl)

from qutebrowser.browser import pdfjs
from qutebrowser.api import cmdutils
from qutebrowser.config import config
from qutebrowser.utils import (usertypes, standarddir, utils, message, log,
                               qtutils, objreg)
from qutebrowser.qt import sip


class ModelRole(enum.IntEnum):

    """Custom download model roles."""

    item = Qt.UserRole


# Remember the last used directory
last_used_directory: Optional[str] = None

# All REFRESH_INTERVAL milliseconds, speeds will be recalculated and downloads
# redrawn.
_REFRESH_INTERVAL = 500


class UnsupportedAttribute:

    """Class which is used to create attributes which are not supported.

    This is used for attributes like "fileobj" for downloads which are not
    supported with QtWebengine.
    """


class UnsupportedOperationError(Exception):

    """Raised when an operation is not supported with the given backend."""


def init():
    """Set the application wide downloads variables."""
    global last_used_directory
    last_used_directory = None

    config.instance.changed.connect(_clear_last_used)


@pyqtSlot()
def shutdown():
    temp_download_manager.cleanup()


@config.change_filter('downloads.location.directory', function=True)
def _clear_last_used():
    global last_used_directory
    last_used_directory = None


def download_dir():
    """Get the download directory to use."""
    directory = config.val.downloads.location.directory
    remember_dir = config.val.downloads.location.remember

    if remember_dir and last_used_directory is not None:
        ddir = last_used_directory
    elif directory is None:
        ddir = standarddir.download()
    else:
        ddir = directory

    try:
        os.makedirs(ddir, exist_ok=True)
    except OSError as e:
        message.error("Failed to create download directory: {}".format(e))

    return ddir


def immediate_download_path(prompt_download_directory=None):
    """Try to get an immediate download path without asking the user.

    If that's possible, we return a path immediately. If not, None is returned.

    Args:
        prompt_download_directory: If this is something else than None, it
                                   will overwrite the
                                   downloads.location.prompt setting.
    """
    if prompt_download_directory is None:
        prompt_download_directory = config.val.downloads.location.prompt

    if not prompt_download_directory:
        return download_dir()

    return None


def _path_suggestion(filename):
    """Get the suggested file path.

    Args:
        filename: The filename to use if included in the suggestion.
    """
    suggestion = config.val.downloads.location.suggestion
    if suggestion == 'path':
        # add trailing '/' if not present
        return os.path.join(download_dir(), '')
    elif suggestion == 'filename':
        return filename
    elif suggestion == 'both':
        return os.path.join(download_dir(), filename)
    else:  # pragma: no cover
        raise ValueError("Invalid suggestion value {}!".format(suggestion))


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.
    """
    basename = utils.sanitize_filename(basename)
    # Filename can be a full path so don't use sanitize_filename on it.
    # Remove chars which can't be encoded in the filename encoding.
    # See https://github.com/qutebrowser/qutebrowser/issues/427
    encoding = sys.getfilesystemencoding()
    filename = utils.force_encoding(filename, encoding)
    if os.path.isabs(filename) and (os.path.isdir(filename) or
                                    filename.endswith(os.sep)):
        # 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


def get_filename_question(*, suggested_filename, url, parent=None):
    """Get a Question object for a download-path.

    Args:
        suggested_filename: The "default"-name that is pre-entered as path.
        url: The URL the download originated from.
        parent: The parent of the question (a QObject).
    """
    suggested_filename = utils.sanitize_filename(suggested_filename)

    q = usertypes.Question(parent)
    q.title = "Save file to:"
    q.text = "Please enter a location for <b>{}</b>".format(
        html.escape(url.toDisplayString()))
    q.url = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
    q.mode = usertypes.PromptMode.download
    q.completed.connect(q.deleteLater)
    q.default = _path_suggestion(suggested_filename)
    return q


def transform_path(path):
    r"""Do platform-specific transformations, like changing E: to E:\.

    Returns None if the path is invalid on the current platform.
    """
    if not utils.is_windows:
        return path
    path = utils.expand_windows_drive(path)
    # Drive dependent working directories are not supported, e.g.
    # E:filename is invalid
    if re.search(r'^[A-Z]:[^\\]', path, re.IGNORECASE):
        return None
    # Paths like COM1, ...
    # See https://github.com/qutebrowser/qutebrowser/issues/82
    if pathlib.Path(path).is_reserved():
        return None
    return path


def suggested_fn_from_title(url_path, title=None):
    """Suggest a filename depending on the URL extension and page title.

    Args:
        url_path: a string with the URL path
        title: the page title string

    Return:
        The download filename based on the title, or None if the extension is
        not found in the whitelist (or if there is no page title).
    """
    ext_whitelist = [".html", ".htm", ".php", ""]
    _, ext = os.path.splitext(url_path)

    suggested_fn: Optional[str] = None
    if ext.lower() in ext_whitelist and title:
        suggested_fn = utils.sanitize_filename(title, shorten=True)
        if not suggested_fn.lower().endswith((".html", ".htm")):
            suggested_fn += ".html"
            suggested_fn = utils.sanitize_filename(suggested_fn, shorten=True)

    return suggested_fn


class NoFilenameError(Exception):

    """Raised when we can't find out a filename in DownloadTarget."""


# Where a download should be saved
class _DownloadTarget:

    """Abstract base class for different download targets."""

    def suggested_filename(self):
        """Get the suggested filename for this download target."""
        raise NotImplementedError


class FileDownloadTarget(_DownloadTarget):

    """Save the download to the given file.

    Attributes:
        filename: Filename where the download should be saved.
        force_overwrite: Whether to overwrite the target without
                         prompting the user.
    """

    def __init__(self, filename, force_overwrite=False):
        self.filename = filename
        self.force_overwrite = force_overwrite

    def suggested_filename(self):
        return os.path.basename(self.filename)

    def __str__(self):
        return self.filename


class FileObjDownloadTarget(_DownloadTarget):

    """Save the download to the given file-like object.

    Attributes:
        fileobj: File-like object where the download should be written to.
    """

    def __init__(self, fileobj):
        self.fileobj = fileobj

    def suggested_filename(self):
        try:
            return self.fileobj.name
        except AttributeError:
            raise NoFilenameError

    def __str__(self):
        try:
            return 'file object at {}'.format(self.fileobj.name)
        except AttributeError:
            return 'anonymous file object'


class OpenFileDownloadTarget(_DownloadTarget):

    """Save the download in a temp dir and directly open it.

    Attributes:
        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.
    """

    def __init__(self, cmdline=None):
        self.cmdline = cmdline

    def suggested_filename(self):
        raise NoFilenameError

    def __str__(self):
        return 'temporary file'


class PDFJSDownloadTarget(_DownloadTarget):

    """Open the download via PDF.js."""

    def suggested_filename(self):
        raise NoFilenameError

    def __str__(self):
        return 'temporary PDF.js file'


class DownloadItemStats(QObject):

    """Statistics (bytes done, total bytes, time, etc.) about a download.

    Class attributes:
        SPEED_AVG_WINDOW: How many seconds of speed data to average to
                          estimate the remaining time.

    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 = None
        self.speed = 0
        self._last_done = 0
        samples = int(self.SPEED_AVG_WINDOW * (1000 / _REFRESH_INTERVAL))
        self._speed_avg: MutableSequence[float] = collections.deque(maxlen=samples)

    def update_speed(self):
        """Recalculate the current download speed.

        The caller needs to guarantee this is called all _REFRESH_INTERVAL ms.
        """
        if self.done is None:
            # this can happen for very fast downloads, e.g. when actually
            # opening a file
            return
        delta = self.done - self._last_done
        self.speed = delta * 1000 / _REFRESH_INTERVAL
        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."""
        if self.done == self.total:
            return 100
        elif self.total is None:
            return None
        else:
            assert self.done is not None
            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

    @pyqtSlot('qint64', 'qint64')
    def on_download_progress(self, bytes_done, bytes_total):
        """Update 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.
        """
        if bytes_total in [0, -1]:  # QtWebEngine, QtWebKit
            bytes_total = None
        self.done = bytes_done
        self.total = bytes_total


class AbstractDownloadItem(QObject):

    """Shared QtNetwork/QtWebEngine part of a download item.

    Attributes:
        done: Whether the download is finished.
        stats: A DownloadItemStats object.
        index: The index of the download in the view.
        successful: Whether the download has completed successfully.
        error_msg: The current error message, or None
        fileobj: The file object to download the file to.
        raw_headers: The headers sent by the server.
        _filename: The filename of the download.
        _dead: Whether the Download has _die()'d.
        _manager: The DownloadManager which started this download.

    Signals:
        data_changed: The downloads metadata changed.
        finished: The download was finished.
        cancelled: The download was cancelled.
        error: An error with the download occurred.
               arg: The error message as string.
        remove_requested: Emitted when the removal of this download was
                          requested.
        pdfjs_requested: Emitted when PDF.js should be opened.
                         arg 1: The filename of the PDF download.
                         arg 2: The original download URL.
    """

    data_changed = pyqtSignal()
    finished = pyqtSignal()
    error = pyqtSignal(str)
    cancelled = pyqtSignal()
    remove_requested = pyqtSignal()
    pdfjs_requested = pyqtSignal(str, QUrl)

    def __init__(self, manager, parent=None):
        super().__init__(parent)
        self._manager = manager
        self.done = False
        self.stats = DownloadItemStats(self)
        self.index = 0
        self.error_msg = None
        self.basename = '???'
        self.successful = False

        self.fileobj: Union[
            UnsupportedAttribute, IO[bytes], None
        ] = UnsupportedAttribute()
        self.raw_headers: Union[
            UnsupportedAttribute, Dict[bytes, bytes]
        ] = UnsupportedAttribute()

        self._filename: Optional[str] = None
        self._dead = False

    def __repr__(self):
        return utils.get_repr(self, basename=self.basename)

    def __str__(self):
        """Get the download as a string.

        Example: foo.pdf [699.2kB/s|0.34|16%|4.253/25.124]
        """
        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()
        if self.error_msg is None:
            errmsg = ""
        else:
            errmsg = " - {}".format(self.error_msg)

        if all(e is None for e in [perc, remaining, self.stats.total]):
            return ('{index}: {name} [{speed:>10}|{down}]{errmsg}'.format(
                index=self.index, name=self.basename, speed=speed,
                down=down, errmsg=errmsg))

        perc = round(perc)
        if remaining is None:
            remaining = '?'
        else:
            remaining = utils.format_seconds(remaining)
        total = utils.format_size(self.stats.total, suffix='B')
        if self.done:
            return ('{index}: {name} [{perc:>2}%|{total}]{errmsg}'.format(
                index=self.index, name=self.basename, perc=perc,
                total=total, errmsg=errmsg))
        else:
            return ('{index}: {name} [{speed:>10}|{remaining:>5}|{perc:>2}%|'
                    '{down}/{total}]{errmsg}'.format(
                        index=self.index, name=self.basename, speed=speed,
                        remaining=remaining, perc=perc, down=down,
                        total=total, errmsg=errmsg))

    def _do_die(self):
        """Do cleanup steps after a download has died."""
        raise NotImplementedError

    def _die(self, msg):
        """Abort the download and emit an error."""
        assert not self.successful
        # Prevent actions if calling _die() twice.
        #
        # For QtWebKit, 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
        self._do_die()
        self.error_msg = msg
        self.stats.finish()
        self.error.emit(msg)
        self.done = True
        self.data_changed.emit()

    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'.
        """
        assert position in ["fg", "bg"]
        start = getattr(config.val.colors.downloads.start, position)
        stop = getattr(config.val.colors.downloads.stop, position)
        system = getattr(config.val.colors.downloads.system, position)
        error = getattr(config.val.colors.downloads.error, position)
        if self.error_msg is not None:
            assert not self.successful
            return error
        elif self.stats.percentage() is None:
            return start
        else:
            return qtutils.interpolate_color(
                start, stop, self.stats.percentage(), system)

    def _do_cancel(self):
        """Actual cancel implementation."""
        raise NotImplementedError

    @pyqtSlot()
    def cancel(self, *, remove_data=True):
        """Cancel the download.

        Args:
            remove_data: Whether to remove the downloaded data.
        """
        assert not self.done
        self._do_cancel()
        log.downloads.debug("cancelled")
        if remove_data:
            self.delete()
        self.done = True
        self.finished.emit()
        self.data_changed.emit()

    @pyqtSlot()
    def remove(self):
        """Remove the download from the model."""
        self.remove_requested.emit()

    def delete(self):
        """Delete the downloaded file."""
        try:
            if self._filename is not None and os.path.exists(self._filename):
                os.remove(self._filename)
                log.downloads.debug("Deleted {}".format(self._filename))
            else:
                log.downloads.debug("Not deleting {}".format(self._filename))
        except OSError:
            log.downloads.exception("Failed to remove partial file")

    @pyqtSlot()
    def retry(self):
        """Retry a failed download."""
        raise NotImplementedError

    @pyqtSlot()
    def try_retry(self):
        """Try to retry a download and show an error if it's unsupported."""
        try:
            self.retry()
        except UnsupportedOperationError as e:
            message.error(str(e))

    def url(self) -> QUrl:
        """Get the download's URL (i.e. where the file is downloaded from)."""
        raise NotImplementedError

    def origin(self) -> QUrl:
        """Get the download's origin URL (i.e. the page starting the download)."""
        raise NotImplementedError

    def _get_open_filename(self):
        """Get the filename to open a download.

        Returns None if no suitable filename was found.
        """
        raise NotImplementedError

    @pyqtSlot()
    def open_file(self, cmdline=None, open_dir=False):
        """Open the downloaded file.

        Args:
            cmdline: The command to use as string. A `{}` is expanded to the
                     filename. None means to use the system's default
                     application or `downloads.open_dispatcher` if set. If no
                     `{}` is found, the filename is appended to the cmdline.
            open_dir: Specify whether to open the file's directory instead.
        """
        assert self.successful
        filename = self._get_open_filename()
        if filename is None:  # pragma: no cover
            log.downloads.error("No filename to open the download!")
            return
        if open_dir:
            filename = os.path.dirname(filename)
        # By using a singleshot timer, we ensure that we return fast. This
        # is important on systems where process creation takes long, as
        # otherwise the prompt might hang around and cause bugs
        # (see issue #2296)
        QTimer.singleShot(0, lambda: utils.open_file(filename, cmdline))

    def _ensure_can_set_filename(self, filename):
        """Make sure we can still set a filename."""
        raise NotImplementedError

    def _after_set_filename(self):
        """Finish initialization based on self._filename."""
        raise NotImplementedError

    def _ask_confirm_question(self, title, msg, *, custom_yes_action=None):
        """Ask a confirmation question for the download."""
        raise NotImplementedError

    def _ask_create_parent_question(self, title, msg,
                                    force_overwrite, remember_directory):
        """Ask a confirmation question for the parent directory."""
        raise NotImplementedError

    def _set_fileobj(self, fileobj, *, autoclose=True):
        """Set a file object to save the download to.

        Not supported by QtWebEngine.

        Args:
            fileobj: The file object to download to.
            autoclose: Close the file object automatically when it's done.
        """
        raise NotImplementedError

    def _set_tempfile(self, fileobj):
        """Set a temporary file when opening the download."""
        raise NotImplementedError

    def _set_filename(self, filename, *, force_overwrite=False,
                      remember_directory=True):
        """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.
            force_overwrite: Force overwriting existing files.
            remember_directory: If True, remember the directory for future
                                downloads.
        """
        filename = os.path.expanduser(filename)
        self._ensure_can_set_filename(filename)

        self._filename = create_full_filename(self.basename, filename)
        if self._filename is None:
            # 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.
            self._filename = create_full_filename(
                self.basename, os.path.join(download_dir(), filename))

        # At this point, we have a misconfigured XDG_DOWNLOAD_DIR, as
        # 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(
                "XDG_DOWNLOAD_DIR points to a relative path - please check"
                " your ~/.config/user-dirs.dirs. The download is saved in"
                " your home directory.",
            )
            # fall back to $HOME as download_dir
            self._filename = create_full_filename(self.basename,
                                                  os.path.expanduser('~'))

        dirname = os.path.dirname(self._filename)
        if not os.path.exists(dirname):
            txt = ("<b>{}</b> does not exist. Create it?".
                   format(html.escape(
                       os.path.join(dirname, ""))))
            self._ask_create_parent_question("Create directory?", txt,
                                             force_overwrite,
                                             remember_directory)
        else:
            self._after_create_parent_question(force_overwrite,
                                               remember_directory)

    def _after_create_parent_question(self,
                                      force_overwrite, remember_directory):
        """After asking about parent directory.

        Args:
            force_overwrite: Force overwriting existing files.
            remember_directory: If True, remember the directory for future
                                downloads.
        """
        assert self._filename is not None
        global last_used_directory

        try:
            os.makedirs(os.path.dirname(self._filename), exist_ok=True)
        except OSError as e:
            self._die(e.strerror)

        self.basename = os.path.basename(self._filename)
        if remember_directory:
            last_used_directory = os.path.dirname(self._filename)

        log.downloads.debug("Setting filename to {}".format(self._filename))
        if self._get_conflicting_download():
            txt = ("<b>{}</b> is already downloading. Cancel and "
                   "re-download?".format(html.escape(self._filename)))
            self._ask_confirm_question(
                "Cancel other download?", txt,
                custom_yes_action=self._cancel_conflicting_download)
        elif force_overwrite:
            self._after_set_filename()
        elif os.path.isfile(self._filename):
            # The file already exists, so ask the user if it should be
            # overwritten.
            txt = "<b>{}</b> already exists. Overwrite?".format(
                html.escape(self._filename))
            self._ask_confirm_question("Overwrite existing file?", txt)
        # FIFO, device node, etc. Make sure we want to do this
        elif (os.path.exists(self._filename) and
              not os.path.isdir(self._filename)):
            txt = ("<b>{}</b> already exists and is a special file. Write to "
                   "it anyways?".format(html.escape(self._filename)))
            self._ask_confirm_question("Overwrite special file?", txt)
        else:
            self._after_set_filename()

    def _conflicts_with(self, other: 'AbstractDownloadItem') -> bool:
        """Check if this download conflicts with the other given one."""
        return (
            other is not self and
            other._filename == self._filename and  # pylint: disable=protected-access
            not other.done
        )

    def _get_conflicting_download(self):
        """Return another potential active download with the same name."""
        for download in self._manager.downloads:
            if self._conflicts_with(download):
                return download
        return None

    def _cancel_conflicting_download(self):
        """Cancel any conflicting download and call _after_set_filename."""
        conflicting_download = self._get_conflicting_download()
        if conflicting_download:
            conflicting_download.cancel(remove_data=False)
        self._after_set_filename()

    def _open_if_successful(self, cmdline):
        """Open the downloaded file, but only if it was successful.

        Args:
            cmdline: Passed to DownloadItem.open_file().
        """
        if not self.successful:
            log.downloads.debug("{} finished but not successful, not opening!"
                                .format(self))
            return
        self.open_file(cmdline)

    def _pdfjs_if_successful(self):
        """Open the file via PDF.js if downloading was successful."""
        if not self.successful:
            log.downloads.debug("{} finished but not successful, not opening!"
                                .format(self))
            return

        filename = self._get_open_filename()
        if filename is None:  # pragma: no cover
            log.downloads.error("No filename to open the download!")
            return
        self.pdfjs_requested.emit(os.path.basename(filename),
                                  self.url())

    def cancel_for_origin(self) -> bool:
        """Cancel the download based on URL/origin.

        For some special cases, we want to cancel downloads immediately, before
        downloading:

        - file:// downloads from file:// URLs (open the file instead)
        - http:// downloads from https:// URLs (mixed content)
        """
        origin = self.origin()
        url = self.url()
        if not origin.isValid():
            return False

        if url.scheme() == "file" and origin.scheme() == "file":
            utils.open_file(url.toLocalFile())
            self.cancel()
            return True

        if (url.scheme() == "http" and
                origin.isValid() and origin.scheme() == "https" and
                config.instance.get("downloads.prevent_mixed_content", url=origin)):
            self._die("Aborting insecure download from secure page "
                      "(see downloads.prevent_mixed_content).")
            return True

        return False

    def set_target(self, target):
        """Set the target for a given download.

        Args:
            target: The DownloadTarget for this download.
        """
        if isinstance(target, FileObjDownloadTarget):
            self._set_fileobj(target.fileobj, autoclose=False)
        elif isinstance(target, FileDownloadTarget):
            self._set_filename(
                target.filename, force_overwrite=target.force_overwrite)
        elif isinstance(target, (OpenFileDownloadTarget, PDFJSDownloadTarget)):
            try:
                fobj = temp_download_manager.get_tmpfile(self.basename)
            except OSError as exc:
                msg = "Download error: {}".format(exc)
                message.error(msg)
                self.cancel()
                return

            if isinstance(target, OpenFileDownloadTarget):
                self.finished.connect(functools.partial(
                    self._open_if_successful, target.cmdline))
            elif isinstance(target, PDFJSDownloadTarget):
                self.finished.connect(self._pdfjs_if_successful)
            else:
                raise utils.Unreachable

            self._set_tempfile(fobj)
        else:  # pragma: no cover
            raise ValueError("Unsupported download target: {}".format(target))


class AbstractDownloadManager(QObject):

    """Backend-independent download manager code.

    Attributes:
        downloads: A list of active DownloadItems.
        _networkmanager: A NetworkManager for generic downloads.

    Signals:
        begin_remove_row: Emitted before downloads are removed.
        end_remove_row: Emitted after downloads are removed.
        begin_insert_row: Emitted before downloads are inserted.
        end_insert_row: Emitted after downloads are inserted.
        data_changed: Emitted when the data of the model changed.
                      The argument is the index of the changed download
    """

    begin_remove_row = pyqtSignal(int)
    end_remove_row = pyqtSignal()
    begin_insert_row = pyqtSignal(int)
    end_insert_row = pyqtSignal()
    data_changed = pyqtSignal(int)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.downloads: List[AbstractDownloadItem] = []
        self._update_timer = usertypes.Timer(self, 'download-update')
        self._update_timer.timeout.connect(self._update_gui)
        self._update_timer.setInterval(_REFRESH_INTERVAL)

    def __repr__(self):
        return utils.get_repr(self, downloads=len(self.downloads))

    @pyqtSlot()
    def _update_gui(self):
        """Periodical GUI update of all items."""
        assert self.downloads
        for dl in self.downloads:
            dl.stats.update_speed()
        self.data_changed.emit(-1)

    @pyqtSlot(str, QUrl)
    def _on_pdfjs_requested(self, filename: str, original_url: QUrl) -> None:
        """Open PDF.js when a download requests it."""
        tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                    window='last-focused')
        tabbed_browser.tabopen(pdfjs.get_main_url(filename, original_url),
                               background=False)

    def _init_item(self, download, auto_remove, suggested_filename):
        """Initialize a newly created DownloadItem."""
        download.cancelled.connect(download.remove)
        download.remove_requested.connect(functools.partial(
            self._remove_item, download))

        delay = config.val.downloads.remove_finished
        if delay > -1:
            download.finished.connect(
                lambda: QTimer.singleShot(delay, download.remove))
        elif auto_remove:
            download.finished.connect(download.remove)

        download.data_changed.connect(
            functools.partial(self._on_data_changed, download))
        download.error.connect(self._on_error)
        download.pdfjs_requested.connect(self._on_pdfjs_requested)

        download.basename = suggested_filename
        idx = len(self.downloads)
        download.index = idx + 1  # "Human readable" index
        self.begin_insert_row.emit(idx)
        self.downloads.append(download)
        self.end_insert_row.emit()

        if not self._update_timer.isActive():
            self._update_timer.start()

    @pyqtSlot(AbstractDownloadItem)
    def _on_data_changed(self, download):
        """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)

    @pyqtSlot(str)
    def _on_error(self, msg):
        """Display error message on download errors."""
        message.error("Download error: {}".format(msg))

    @pyqtSlot(AbstractDownloadItem)
    def _remove_item(self, download):
        """Remove a given download."""
        if sip.isdeleted(self):
            # https://github.com/qutebrowser/qutebrowser/issues/1242
            return
        try:
            idx = self.downloads.index(download)
        except ValueError:
            # already removed
            return
        self.begin_remove_row.emit(idx)
        del self.downloads[idx]
        self.end_remove_row.emit()
        download.deleteLater()
        self._update_indexes()
        if not self.downloads:
            self._update_timer.stop()
        log.downloads.debug("Removed download {}".format(download))

    def _update_indexes(self):
        """Update indexes of all DownloadItems."""
        for i, d in enumerate(self.downloads, 1):
            d.index = i
        self.data_changed.emit(-1)

    def _init_filename_question(self, question, download):
        """Set up an existing filename question with a download."""
        question.answered.connect(download.set_target)
        question.cancelled.connect(download.cancel)
        download.cancelled.connect(question.abort)
        download.error.connect(question.abort)

    @pyqtSlot()
    def shutdown(self):
        """Cancel all downloads when shutting down."""
        for download in self.downloads:
            if not download.done:
                download.cancel(remove_data=False)


class DownloadModel(QAbstractListModel):

    """A list model showing downloads."""

    def __init__(self, qtnetwork_manager, webengine_manager=None, parent=None):
        super().__init__(parent)
        self._qtnetwork_manager = qtnetwork_manager
        self._webengine_manager = webengine_manager

        qtnetwork_manager.data_changed.connect(
            functools.partial(self._on_data_changed, webengine=False))
        qtnetwork_manager.begin_insert_row.connect(
            functools.partial(self._on_begin_insert_row, webengine=False))
        qtnetwork_manager.begin_remove_row.connect(
            functools.partial(self._on_begin_remove_row, webengine=False))
        qtnetwork_manager.end_insert_row.connect(self.endInsertRows)
        qtnetwork_manager.end_remove_row.connect(self.endRemoveRows)

        if webengine_manager is not None:
            webengine_manager.data_changed.connect(
                functools.partial(self._on_data_changed, webengine=True))
            webengine_manager.begin_insert_row.connect(
                functools.partial(self._on_begin_insert_row, webengine=True))
            webengine_manager.begin_remove_row.connect(
                functools.partial(self._on_begin_remove_row, webengine=True))
            webengine_manager.end_insert_row.connect(self.endInsertRows)
            webengine_manager.end_remove_row.connect(self.endRemoveRows)

    def _all_downloads(self):
        """Combine downloads from both downloaders."""
        if self._webengine_manager is None:
            return self._qtnetwork_manager.downloads[:]
        else:
            return (self._qtnetwork_manager.downloads +
                    self._webengine_manager.downloads)

    def __len__(self):
        return len(self._all_downloads())

    def __iter__(self):
        return iter(self._all_downloads())

    def __getitem__(self, idx):
        return self._all_downloads()[idx]

    def _on_begin_insert_row(self, idx, webengine=False):
        log.downloads.debug("_on_begin_insert_row with idx {}, "
                            "webengine {}".format(idx, webengine))
        if idx == -1:
            self.beginInsertRows(QModelIndex(), 0, -1)
            return

        assert idx >= 0, idx
        if webengine:
            idx += len(self._qtnetwork_manager.downloads)
        self.beginInsertRows(QModelIndex(), idx, idx)

    def _on_begin_remove_row(self, idx, webengine=False):
        log.downloads.debug("_on_begin_remove_row with idx {}, "
                            "webengine {}".format(idx, webengine))
        if idx == -1:
            self.beginRemoveRows(QModelIndex(), 0, -1)
            return

        assert idx >= 0, idx
        if webengine:
            idx += len(self._qtnetwork_manager.downloads)
        self.beginRemoveRows(QModelIndex(), idx, idx)

    def _on_data_changed(self, idx, *, webengine):
        """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.
            webengine: If given, the QtNetwork download length is added to the
                      index.
        """
        if idx == -1:
            start_index = self.index(0, 0)
            end_index = self.last_index()
        else:
            if webengine:
                idx += len(self._qtnetwork_manager.downloads)
            start_index = self.index(idx, 0)
            end_index = self.index(idx, 0)
            qtutils.ensure_valid(start_index)
            qtutils.ensure_valid(end_index)
        self.dataChanged.emit(start_index, end_index)

    def _raise_no_download(self, count):
        """Raise an exception that the download doesn't exist.

        Args:
            count: The index of the download
        """
        if not count:
            raise cmdutils.CommandError("There's no download!")
        raise cmdutils.CommandError("There's no download {}!".format(count))

    @cmdutils.register(instance='download-model', scope='window')
    @cmdutils.argument('count', value=cmdutils.Value.count)
    def download_cancel(self, all_=False, count=0):
        """Cancel the last/[count]th download.

        Args:
            all_: Cancel all running downloads
            count: The index of the download to cancel.
        """
        downloads = self._all_downloads()
        if all_:
            for download in downloads:
                if not download.done:
                    download.cancel()
        else:
            try:
                download = downloads[count - 1]
            except IndexError:
                self._raise_no_download(count)
            if download.done:
                if not count:
                    count = len(self)
                raise cmdutils.CommandError("Download {} is already done!"
                                            .format(count))
            download.cancel()

    @cmdutils.register(instance='download-model', scope='window')
    @cmdutils.argument('count', value=cmdutils.Value.count)
    def download_delete(self, count=0):
        """Delete the last/[count]th download from disk.

        Args:
            count: The index of the download to delete.
        """
        try:
            download = self[count - 1]
        except IndexError:
            self._raise_no_download(count)
        if not download.successful:
            if not count:
                count = len(self)
            raise cmdutils.CommandError("Download {} is not done!"
                                        .format(count))
        download.delete()
        download.remove()
        log.downloads.debug("deleted download {}".format(download))

    @cmdutils.register(instance='download-model', scope='window', maxsplit=0)
    @cmdutils.argument('count', value=cmdutils.Value.count)
    def download_open(self, cmdline: str = None, count: int = 0,
                      dir_: bool = False) -> None:
        """Open the last/[count]th download.

        If no specific command is given, this will use the system's default
        application to open the file.

        Args:
            cmdline: The command which should be used to open the file. A `{}`
                     is expanded to the temporary file name. If no `{}` is
                     present, the filename is automatically appended to the
                     cmdline.
            count: The index of the download to open.
            dir_: Whether to open the file's directory instead.
        """
        try:
            download = self[count - 1]
        except IndexError:
            self._raise_no_download(count)
        if not download.successful:
            if not count:
                count = len(self)
            raise cmdutils.CommandError("Download {} is not done!"
                                        .format(count))
        download.open_file(cmdline, open_dir=dir_)

    @cmdutils.register(instance='download-model', scope='window')
    @cmdutils.argument('count', value=cmdutils.Value.count)
    def download_retry(self, count=0):
        """Retry the first failed/[count]th download.

        Args:
            count: The index of the download to retry.
        """
        if count:
            try:
                download = self[count - 1]
            except IndexError:
                self._raise_no_download(count)
            if download.successful or not download.done:
                raise cmdutils.CommandError("Download {} did not fail!"
                                            .format(count))
        else:
            to_retry = [d for d in self if d.done and not d.successful]
            if not to_retry:
                raise cmdutils.CommandError("No failed downloads!")
            download = to_retry[0]
        download.try_retry()

    def can_clear(self):
        """Check if there are finished downloads to clear."""
        return any(download.done for download in self)

    @cmdutils.register(instance='download-model', scope='window')
    def download_clear(self):
        """Remove all finished downloads from the list."""
        for download in self:
            if download.done:
                download.remove()

    @cmdutils.register(instance='download-model', scope='window')
    @cmdutils.argument('count', value=cmdutils.Value.count)
    def download_remove(self, all_=False, count=0):
        """Remove the last/[count]th download from the list.

        Args:
            all_: Remove all finished downloads.
            count: The index of the download to remove.
        """
        if all_:
            self.download_clear()
        else:
            try:
                download = self[count - 1]
            except IndexError:
                self._raise_no_download(count)
            if not download.done:
                if not count:
                    count = len(self)
                raise cmdutils.CommandError("Download {} is not done!"
                                            .format(count))
            download.remove()

    def running_downloads(self):
        """Return the amount of still running downloads.

        Return:
            The number of unfinished downloads.
        """
        return sum(1 for download in self if not download.done)

    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=Qt.DisplayRole):
        """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."""
        if not index.isValid():
            return None

        if index.parent().isValid() or index.column() != 0:
            return None

        item = self[index.row()]
        if role == Qt.DisplayRole:
            data: Any = str(item)
        elif role == Qt.ForegroundRole:
            data = item.get_status_color('fg')
        elif role == Qt.BackgroundRole:
            data = item.get_status_color('bg')
        elif role == ModelRole.item:
            data = item
        elif role == Qt.ToolTipRole:
            if item.error_msg is None:
                data = None
            else:
                return item.error_msg
        else:
            data = None
        return data

    def flags(self, index):
        """Override flags so items aren't selectable.

        The default would be Qt.ItemIsEnabled | Qt.ItemIsSelectable.
        """
        if not index.isValid():
            return Qt.ItemFlags()
        return Qt.ItemIsEnabled | Qt.ItemNeverHasChildren

    def rowCount(self, parent=QModelIndex()):
        """Get count of active downloads."""
        if parent.isValid():
            # We don't have children
            return 0
        return len(self)


class TempDownloadManager:

    """Manager to handle temporary download files.

    The downloads are downloaded to a temporary location and then opened 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):
        self.files: MutableSequence[IO[bytes]] = []
        self._tmpdir = None

    def cleanup(self):
        """Clean up any temporary files."""
        if self._tmpdir is not None:
            try:
                self._tmpdir.cleanup()
            except OSError:
                log.misc.exception("Failed to clean up temporary download "
                                   "directory")
            self._tmpdir = None

    def get_tmpdir(self):
        """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 extensions are preserved.

        Return:
            A tempfile.NamedTemporaryFile that should be used to save the file.
        """
        tmpdir = self.get_tmpdir()
        suggested_name = utils.sanitize_filename(suggested_name)
        # Make sure that the filename is not too long
        suggested_name = utils.elide_filename(suggested_name, 50)
        fobj = tempfile.NamedTemporaryFile(dir=tmpdir.name, delete=False,
                                           suffix='_' + suggested_name)
        self.files.append(fobj)
        return fobj


temp_download_manager = TempDownloadManager()