WebBrowser/Download/DownloadItem.py

branch
QtWebEngine
changeset 4769
2b6f7e026cdc
parent 4768
57da9217196b
child 4772
db71b47b663e
equal deleted inserted replaced
4768:57da9217196b 4769:2b6f7e026cdc
6 """ 6 """
7 Module implementing a widget controlling a download. 7 Module implementing a widget controlling a download.
8 """ 8 """
9 9
10 from __future__ import unicode_literals 10 from __future__ import unicode_literals
11 try: 11
12 str = unicode 12 from PyQt5.QtCore import pyqtSlot, pyqtSignal, Qt, QTime, QFileInfo, QUrl, \
13 except NameError: 13 PYQT_VERSION_STR
14 pass
15
16 from PyQt5.QtCore import pyqtSlot, pyqtSignal, Qt, QTime, QFile, QFileInfo, \
17 QUrl, QIODevice, QCryptographicHash, PYQT_VERSION_STR
18 from PyQt5.QtGui import QPalette, QDesktopServices 14 from PyQt5.QtGui import QPalette, QDesktopServices
19 from PyQt5.QtWidgets import QWidget, QStyle, QDialog 15 from PyQt5.QtWidgets import QWidget, QStyle, QDialog
20 from PyQt5.QtNetwork import QNetworkRequest, QNetworkReply 16 from PyQt5.QtWebEngineWidgets import QWebEngineDownloadItem
21 17
22 from E5Gui import E5FileDialog 18 from E5Gui import E5FileDialog
23 19
24 from .Ui_DownloadItem import Ui_DownloadItem 20 from .Ui_DownloadItem import Ui_DownloadItem
25 21
26 from .DownloadUtilities import timeString, dataString 22 from .DownloadUtilities import timeString, dataString
27 ##from ..HelpUtilities import parseContentDisposition 23 from WebBrowser.WebBrowserWindow import WebBrowserWindow
28 24
29 import UI.PixmapCache 25 import UI.PixmapCache
30 import Preferences 26 import Utilities.MimeTypes
31 27
32 28
33 class DownloadItem(QWidget, Ui_DownloadItem): 29 class DownloadItem(QWidget, Ui_DownloadItem):
34 """ 30 """
35 Class implementing a widget controlling a download. 31 Class implementing a widget controlling a download.
44 40
45 Downloading = 0 41 Downloading = 0
46 DownloadSuccessful = 1 42 DownloadSuccessful = 1
47 DownloadCancelled = 2 43 DownloadCancelled = 2
48 44
49 def __init__(self, reply=None, requestFilename=False, webPage=None, 45 def __init__(self, downloadItem, parent=None):
50 download=False, parent=None, mainWindow=None):
51 """ 46 """
52 Constructor 47 Constructor
53 48
54 @keyparam reply reference to the network reply object (QNetworkReply) 49 @param downloadItem reference to the download object containing the
55 @keyparam requestFilename flag indicating to ask the user for a 50 download data.
56 filename (boolean)
57 @keyparam webPage reference to the web page object the download
58 originated from (QWebPage)
59 @keyparam download flag indicating a download operation (boolean)
60 @keyparam parent reference to the parent widget (QWidget) 51 @keyparam parent reference to the parent widget (QWidget)
61 @keyparam mainWindow reference to the main window (HelpWindow) 52 @type QWebEngineDownloadItem
62 """ 53 """
63 super(DownloadItem, self).__init__(parent) 54 super(DownloadItem, self).__init__(parent)
64 self.setupUi(self) 55 self.setupUi(self)
65 56
66 p = self.infoLabel.palette() 57 p = self.infoLabel.palette()
67 p.setColor(QPalette.Text, Qt.darkGray) 58 p.setColor(QPalette.Text, Qt.darkGray)
68 self.infoLabel.setPalette(p) 59 self.infoLabel.setPalette(p)
69 60
70 self.progressBar.setMaximum(0) 61 self.progressBar.setMaximum(0)
71 62
72 self.__isFtpDownload = reply is not None and \
73 reply.url().scheme() == "ftp"
74
75 self.tryAgainButton.setIcon(UI.PixmapCache.getIcon("restart.png"))
76 self.tryAgainButton.setEnabled(False)
77 self.tryAgainButton.setVisible(False)
78 self.stopButton.setIcon(UI.PixmapCache.getIcon("stopLoading.png")) 63 self.stopButton.setIcon(UI.PixmapCache.getIcon("stopLoading.png"))
79 self.pauseButton.setIcon(UI.PixmapCache.getIcon("pause.png"))
80 self.openButton.setIcon(UI.PixmapCache.getIcon("open.png")) 64 self.openButton.setIcon(UI.PixmapCache.getIcon("open.png"))
81 self.openButton.setEnabled(False) 65 self.openButton.setEnabled(False)
82 self.openButton.setVisible(False) 66 self.openButton.setVisible(False)
83 if self.__isFtpDownload:
84 self.stopButton.setEnabled(False)
85 self.stopButton.setVisible(False)
86 self.pauseButton.setEnabled(False)
87 self.pauseButton.setVisible(False)
88 67
89 self.__state = DownloadItem.Downloading 68 self.__state = DownloadItem.Downloading
90 69
91 icon = self.style().standardIcon(QStyle.SP_FileIcon) 70 icon = self.style().standardIcon(QStyle.SP_FileIcon)
92 self.fileIcon.setPixmap(icon.pixmap(48, 48)) 71 self.fileIcon.setPixmap(icon.pixmap(48, 48))
93 72
94 self.__mainWindow = mainWindow 73 self.__downloadItem = downloadItem
95 self.__reply = reply 74 self.__pageUrl = \
96 self.__requestFilename = requestFilename 75 WebBrowserWindow.mainWindow().getWindow().currentBrowser().url() \
97 self.__page = webPage 76 or QUrl()
98 self.__pageUrl = webPage and webPage.mainFrame().url() or QUrl()
99 self.__toDownload = download
100 self.__bytesReceived = 0 77 self.__bytesReceived = 0
101 self.__bytesTotal = -1 78 self.__bytesTotal = -1
102 self.__downloadTime = QTime() 79 self.__downloadTime = QTime()
103 self.__output = QFile()
104 self.__fileName = "" 80 self.__fileName = ""
105 self.__originalFileName = "" 81 self.__originalFileName = ""
106 self.__startedSaving = False
107 self.__finishedDownloading = False 82 self.__finishedDownloading = False
108 self.__gettingFileName = False 83 self.__gettingFileName = False
109 self.__canceledFileSelect = False 84 self.__canceledFileSelect = False
110 self.__autoOpen = False 85 self.__autoOpen = False
111 86
112 self.__sha1Hash = QCryptographicHash(QCryptographicHash.Sha1)
113 self.__md5Hash = QCryptographicHash(QCryptographicHash.Md5)
114
115 if not requestFilename:
116 self.__requestFilename = \
117 Preferences.getUI("RequestDownloadFilename")
118
119 self.__initialize() 87 self.__initialize()
120 88
121 def __initialize(self, tryAgain=False): 89 def __initialize(self):
122 """ 90 """
123 Private method to (re)initialize the widget. 91 Private method to initialize the widget.
124 92 """
125 @param tryAgain flag indicating a retry (boolean) 93 if self.__downloadItem is None:
126 """
127 if self.__reply is None:
128 return 94 return
129 95
130 self.__startedSaving = False
131 self.__finishedDownloading = False 96 self.__finishedDownloading = False
132 self.__bytesReceived = 0 97 self.__bytesReceived = 0
133 self.__bytesTotal = -1 98 self.__bytesTotal = -1
134 99
135 self.__sha1Hash.reset()
136 self.__md5Hash.reset()
137
138 # start timer for the download estimation 100 # start timer for the download estimation
139 self.__downloadTime.start() 101 self.__downloadTime.start()
140 102
141 # attach to the reply object 103 # attach to the download item object
142 self.__url = self.__reply.url() 104 self.__url = self.__downloadItem.url()
143 self.__reply.setParent(self) 105 self.__downloadItem.downloadProgress.connect(self.__downloadProgress)
144 self.__reply.setReadBufferSize(16 * 1024 * 1024) 106 self.__downloadItem.finished.connect(self.__finished)
145 self.__reply.readyRead.connect(self.__readyRead)
146 self.__reply.error.connect(self.__networkError)
147 self.__reply.downloadProgress.connect(self.__downloadProgress)
148 self.__reply.metaDataChanged.connect(self.__metaDataChanged)
149 self.__reply.finished.connect(self.__finished)
150 107
151 # reset info 108 # reset info
152 self.infoLabel.clear() 109 self.infoLabel.clear()
153 self.progressBar.setValue(0) 110 self.progressBar.setValue(0)
154 self.__getFileName() 111 self.__getFileName()
155 112 if not self.__fileName:
156 if self.__reply.error() != QNetworkReply.NoError: 113 self.__downloadItem.cancel()
157 self.__networkError() 114 else:
158 self.__finished() 115 self.__downloadItem.setPath(self.__fileName)
116 self.__downloadItem.accept()
159 117
160 def __getFileName(self): 118 def __getFileName(self):
161 """ 119 """
162 Private method to get the file name to save to from the user. 120 Private method to get the file name to save to from the user.
163 """ 121 """
164 if self.__gettingFileName: 122 if self.__gettingFileName:
165 return 123 return
166 124
167 from WebBrowser.WebBrowserWindow import WebBrowserWindow
168 downloadDirectory = WebBrowserWindow\ 125 downloadDirectory = WebBrowserWindow\
169 .downloadManager().downloadDirectory() 126 .downloadManager().downloadDirectory()
170 127
171 if self.__fileName: 128 if self.__fileName:
172 fileName = self.__fileName 129 fileName = self.__fileName
178 self.__saveFileName(downloadDirectory) 135 self.__saveFileName(downloadDirectory)
179 fileName = defaultFileName 136 fileName = defaultFileName
180 self.__originalFileName = originalFileName 137 self.__originalFileName = originalFileName
181 ask = True 138 ask = True
182 self.__autoOpen = False 139 self.__autoOpen = False
183 if not self.__toDownload: 140 from .DownloadAskActionDialog import DownloadAskActionDialog
184 from .DownloadAskActionDialog import DownloadAskActionDialog 141 url = self.__downloadItem.url()
185 url = self.__reply.url() 142 mimetype = Utilities.MimeTypes.mimeType(originalFileName)
186 dlg = DownloadAskActionDialog( 143 dlg = DownloadAskActionDialog(
187 QFileInfo(originalFileName).fileName(), 144 QFileInfo(originalFileName).fileName(),
188 self.__reply.header(QNetworkRequest.ContentTypeHeader), 145 mimetype,
189 "{0}://{1}".format(url.scheme(), url.authority()), 146 "{0}://{1}".format(url.scheme(), url.authority()),
190 self) 147 self)
191 if dlg.exec_() == QDialog.Rejected or dlg.getAction() == "cancel": 148 if dlg.exec_() == QDialog.Rejected or dlg.getAction() == "cancel":
192 self.progressBar.setVisible(False) 149 self.progressBar.setVisible(False)
193 self.__reply.close() 150 self.on_stopButton_clicked()
194 self.on_stopButton_clicked() 151 self.filenameLabel.setText(
195 self.filenameLabel.setText( 152 self.tr("Download canceled: {0}").format(
196 self.tr("Download canceled: {0}").format( 153 QFileInfo(defaultFileName).fileName()))
197 QFileInfo(defaultFileName).fileName())) 154 self.__canceledFileSelect = True
198 self.__canceledFileSelect = True 155 return
199 return 156
157 if dlg.getAction() == "scan":
158 self.__mainWindow.requestVirusTotalScan(url)
200 159
201 if dlg.getAction() == "scan": 160 self.progressBar.setVisible(False)
202 self.__mainWindow.requestVirusTotalScan(url) 161 self.on_stopButton_clicked()
203 162 self.filenameLabel.setText(
204 self.progressBar.setVisible(False) 163 self.tr("VirusTotal scan scheduled: {0}").format(
205 self.__reply.close() 164 QFileInfo(defaultFileName).fileName()))
206 self.on_stopButton_clicked() 165 self.__canceledFileSelect = True
207 self.filenameLabel.setText( 166 return
208 self.tr("VirusTotal scan scheduled: {0}").format( 167
209 QFileInfo(defaultFileName).fileName())) 168 self.__autoOpen = dlg.getAction() == "open"
210 self.__canceledFileSelect = True 169 if PYQT_VERSION_STR >= "5.0.0":
211 return 170 from PyQt5.QtCore import QStandardPaths
212 171 tempLocation = QStandardPaths.standardLocations(
213 self.__autoOpen = dlg.getAction() == "open" 172 QStandardPaths.TempLocation)[0]
214 if PYQT_VERSION_STR >= "5.0.0": 173 else:
215 from PyQt5.QtCore import QStandardPaths 174 from PyQt5.QtGui import QDesktopServices
216 tempLocation = QStandardPaths.storageLocation( 175 tempLocation = QDesktopServices.storageLocation(
217 QStandardPaths.TempLocation) 176 QDesktopServices.TempLocation)
218 else: 177 fileName = tempLocation + '/' + \
219 from PyQt5.QtGui import QDesktopServices 178 QFileInfo(fileName).completeBaseName()
220 tempLocation = QDesktopServices.storageLocation( 179
221 QDesktopServices.TempLocation) 180 if ask and not self.__autoOpen:
222 fileName = tempLocation + '/' + \
223 QFileInfo(fileName).completeBaseName()
224
225 if ask and not self.__autoOpen and self.__requestFilename:
226 self.__gettingFileName = True 181 self.__gettingFileName = True
227 fileName = E5FileDialog.getSaveFileName( 182 fileName = E5FileDialog.getSaveFileName(
228 None, 183 None,
229 self.tr("Save File"), 184 self.tr("Save File"),
230 defaultFileName, 185 defaultFileName,
231 "") 186 "")
232 self.__gettingFileName = False 187 self.__gettingFileName = False
233 if not fileName: 188 if not fileName:
234 self.progressBar.setVisible(False) 189 self.progressBar.setVisible(False)
235 self.__reply.close()
236 self.on_stopButton_clicked() 190 self.on_stopButton_clicked()
237 self.filenameLabel.setText( 191 self.filenameLabel.setText(
238 self.tr("Download canceled: {0}") 192 self.tr("Download canceled: {0}")
239 .format(QFileInfo(defaultFileName).fileName())) 193 .format(QFileInfo(defaultFileName).fileName()))
240 self.__canceledFileSelect = True 194 self.__canceledFileSelect = True
243 fileInfo = QFileInfo(fileName) 197 fileInfo = QFileInfo(fileName)
244 WebBrowserWindow.downloadManager()\ 198 WebBrowserWindow.downloadManager()\
245 .setDownloadDirectory(fileInfo.absoluteDir().absolutePath()) 199 .setDownloadDirectory(fileInfo.absoluteDir().absolutePath())
246 self.filenameLabel.setText(fileInfo.fileName()) 200 self.filenameLabel.setText(fileInfo.fileName())
247 201
248 self.__output.setFileName(fileName + ".part")
249 self.__fileName = fileName 202 self.__fileName = fileName
250 203
251 # check file path for saving 204 # check file path for saving
252 saveDirPath = QFileInfo(self.__fileName).dir() 205 saveDirPath = QFileInfo(self.__fileName).dir()
253 if not saveDirPath.exists(): 206 if not saveDirPath.exists():
258 "Download directory ({0}) couldn't be created.") 211 "Download directory ({0}) couldn't be created.")
259 .format(saveDirPath.absolutePath())) 212 .format(saveDirPath.absolutePath()))
260 return 213 return
261 214
262 self.filenameLabel.setText(QFileInfo(self.__fileName).fileName()) 215 self.filenameLabel.setText(QFileInfo(self.__fileName).fileName())
263 if self.__requestFilename:
264 self.__readyRead()
265 216
266 def __saveFileName(self, directory): 217 def __saveFileName(self, directory):
267 """ 218 """
268 Private method to calculate a name for the file to download. 219 Private method to calculate a name for the file to download.
269 220
270 @param directory name of the directory to store the file into (string) 221 @param directory name of the directory to store the file into (string)
271 @return proposed filename and original filename (string, string) 222 @return proposed filename and original filename (string, string)
272 """ 223 """
273 path = parseContentDisposition(self.__reply) 224 path = self.__downloadItem.path()
274 info = QFileInfo(path) 225 info = QFileInfo(path)
275 baseName = info.completeBaseName() 226 baseName = info.completeBaseName()
276 endName = info.suffix() 227 endName = info.suffix()
277 228
278 origName = baseName 229 origName = baseName
280 origName += '.' + endName 231 origName += '.' + endName
281 232
282 name = directory + baseName 233 name = directory + baseName
283 if endName: 234 if endName:
284 name += '.' + endName 235 name += '.' + endName
285 if not self.__requestFilename:
286 # do not overwrite, if the user is not being asked
287 i = 1
288 while QFile.exists(name):
289 # file exists already, don't overwrite
290 name = directory + baseName + ('-{0:d}'.format(i))
291 if endName:
292 name += '.' + endName
293 i += 1
294 return name, origName 236 return name, origName
295 237
296 def __open(self): 238 def __open(self):
297 """ 239 """
298 Private slot to open the downloaded file. 240 Private slot to open the downloaded file.
299 """ 241 """
300 info = QFileInfo(self.__output) 242 info = QFileInfo(self.__fileName)
301 url = QUrl.fromLocalFile(info.absoluteFilePath()) 243 url = QUrl.fromLocalFile(info.absoluteFilePath())
302 QDesktopServices.openUrl(url) 244 QDesktopServices.openUrl(url)
303 245
304 @pyqtSlot() 246 @pyqtSlot()
305 def on_tryAgainButton_clicked(self):
306 """
307 Private slot to retry the download.
308 """
309 self.retry()
310
311 def retry(self):
312 """
313 Public slot to retry the download.
314 """
315 if not self.tryAgainButton.isEnabled():
316 return
317
318 self.tryAgainButton.setEnabled(False)
319 self.tryAgainButton.setVisible(False)
320 self.openButton.setEnabled(False)
321 self.openButton.setVisible(False)
322 if not self.__isFtpDownload:
323 self.stopButton.setEnabled(True)
324 self.stopButton.setVisible(True)
325 self.pauseButton.setEnabled(True)
326 self.pauseButton.setVisible(True)
327 self.progressBar.setVisible(True)
328
329 if self.__page:
330 nam = self.__page.networkAccessManager()
331 else:
332 from WebBrowser.WebBrowserWindow import WebBrowserWindow
333 nam = WebBrowserWindow.networkAccessManager()
334 reply = nam.get(QNetworkRequest(self.__url))
335 if self.__output.exists():
336 self.__output.remove()
337 self.__output = QFile()
338 self.__reply = reply
339 self.__initialize(tryAgain=True)
340 self.__state = DownloadItem.Downloading
341 self.statusChanged.emit()
342
343 @pyqtSlot(bool)
344 def on_pauseButton_clicked(self, checked):
345 """
346 Private slot to pause the download.
347
348 @param checked flag indicating the state of the button (boolean)
349 """
350 if checked:
351 self.__reply.readyRead.disconnect(self.__readyRead)
352 self.__reply.setReadBufferSize(16 * 1024)
353 else:
354 self.__reply.readyRead.connect(self.__readyRead)
355 self.__reply.setReadBufferSize(16 * 1024 * 1024)
356 self.__readyRead()
357
358 @pyqtSlot()
359 def on_stopButton_clicked(self): 247 def on_stopButton_clicked(self):
360 """ 248 """
361 Private slot to stop the download. 249 Private slot to stop the download.
362 """ 250 """
363 self.cancelDownload() 251 self.cancelDownload()
365 def cancelDownload(self): 253 def cancelDownload(self):
366 """ 254 """
367 Public slot to stop the download. 255 Public slot to stop the download.
368 """ 256 """
369 self.setUpdatesEnabled(False) 257 self.setUpdatesEnabled(False)
370 if not self.__isFtpDownload: 258 self.stopButton.setEnabled(False)
371 self.stopButton.setEnabled(False) 259 self.stopButton.setVisible(False)
372 self.stopButton.setVisible(False)
373 self.pauseButton.setEnabled(False)
374 self.pauseButton.setVisible(False)
375 self.tryAgainButton.setEnabled(True)
376 self.tryAgainButton.setVisible(True)
377 self.openButton.setEnabled(False) 260 self.openButton.setEnabled(False)
378 self.openButton.setVisible(False) 261 self.openButton.setVisible(False)
379 self.setUpdatesEnabled(True) 262 self.setUpdatesEnabled(True)
380 self.__state = DownloadItem.DownloadCancelled 263 self.__state = DownloadItem.DownloadCancelled
381 self.__reply.abort() 264 self.__downloadItem.cancel()
382 self.downloadFinished.emit() 265 self.downloadFinished.emit()
383 266
384 @pyqtSlot() 267 @pyqtSlot()
385 def on_openButton_clicked(self): 268 def on_openButton_clicked(self):
386 """ 269 """
401 Public slot to open the folder containing the downloaded file. 284 Public slot to open the folder containing the downloaded file.
402 """ 285 """
403 info = QFileInfo(self.__fileName) 286 info = QFileInfo(self.__fileName)
404 url = QUrl.fromLocalFile(info.absolutePath()) 287 url = QUrl.fromLocalFile(info.absolutePath())
405 QDesktopServices.openUrl(url) 288 QDesktopServices.openUrl(url)
406
407 def __readyRead(self):
408 """
409 Private slot to read the available data.
410 """
411 if self.__requestFilename and not self.__output.fileName():
412 return
413
414 if not self.__output.isOpen():
415 # in case someone else has already put a file there
416 if not self.__requestFilename:
417 self.__getFileName()
418 if not self.__output.open(QIODevice.WriteOnly):
419 self.infoLabel.setText(
420 self.tr("Error opening save file: {0}")
421 .format(self.__output.errorString()))
422 self.on_stopButton_clicked()
423 self.statusChanged.emit()
424 return
425 self.statusChanged.emit()
426
427 buffer = self.__reply.readAll()
428 self.__sha1Hash.addData(buffer)
429 self.__md5Hash.addData(buffer)
430 bytesWritten = self.__output.write(buffer)
431 if bytesWritten == -1:
432 self.infoLabel.setText(
433 self.tr("Error saving: {0}")
434 .format(self.__output.errorString()))
435 self.on_stopButton_clicked()
436 else:
437 self.__startedSaving = True
438 if self.__finishedDownloading:
439 self.__finished()
440
441 def __networkError(self):
442 """
443 Private slot to handle a network error.
444 """
445 self.infoLabel.setText(
446 self.tr("Network Error: {0}")
447 .format(self.__reply.errorString()))
448 self.tryAgainButton.setEnabled(True)
449 self.tryAgainButton.setVisible(True)
450 self.downloadFinished.emit()
451
452 def __metaDataChanged(self):
453 """
454 Private slot to handle a change of the meta data.
455 """
456 locationHeader = self.__reply.header(QNetworkRequest.LocationHeader)
457 if locationHeader and locationHeader.isValid():
458 self.__url = QUrl(locationHeader)
459 from WebBrowser.WebBrowserWindow import WebBrowserWindow
460 self.__reply = WebBrowserWindow\
461 .networkAccessManager().get(QNetworkRequest(self.__url))
462 self.__initialize()
463 289
464 def __downloadProgress(self, bytesReceived, bytesTotal): 290 def __downloadProgress(self, bytesReceived, bytesTotal):
465 """ 291 """
466 Private method to show the download progress. 292 Private method to show the download progress.
467 293
486 Public method to get the total number of bytes of the download. 312 Public method to get the total number of bytes of the download.
487 313
488 @return total number of bytes (integer) 314 @return total number of bytes (integer)
489 """ 315 """
490 if self.__bytesTotal == -1: 316 if self.__bytesTotal == -1:
491 self.__bytesTotal = self.__reply.header( 317 self.__bytesTotal = self.__downloadItem.totalBytes()
492 QNetworkRequest.ContentLengthHeader)
493 if self.__bytesTotal is None:
494 self.__bytesTotal = -1
495 return self.__bytesTotal 318 return self.__bytesTotal
496 319
497 def bytesReceived(self): 320 def bytesReceived(self):
498 """ 321 """
499 Public method to get the number of bytes received. 322 Public method to get the number of bytes received.
539 362
540 def __updateInfoLabel(self): 363 def __updateInfoLabel(self):
541 """ 364 """
542 Private method to update the info label. 365 Private method to update the info label.
543 """ 366 """
544 if self.__reply.error() != QNetworkReply.NoError:
545 return
546
547 bytesTotal = self.bytesTotal() 367 bytesTotal = self.bytesTotal()
548 running = not self.downloadedSuccessfully() 368 running = not self.downloadedSuccessfully()
549 369
550 speed = self.currentSpeed() 370 speed = self.currentSpeed()
551 timeRemaining = self.remainingTime() 371 timeRemaining = self.remainingTime()
564 or dataString(bytesTotal), 384 or dataString(bytesTotal),
565 dataString(int(speed)), 385 dataString(int(speed)),
566 remaining) 386 remaining)
567 else: 387 else:
568 if self.__bytesReceived == bytesTotal or bytesTotal == -1: 388 if self.__bytesReceived == bytesTotal or bytesTotal == -1:
569 info = self.tr("{0} downloaded\nSHA1: {1}\nMD5: {2}")\ 389 info = self.tr("{0} downloaded")\
570 .format(dataString(self.__output.size()), 390 .format(dataString(self.__output.size()))
571 str(self.__sha1Hash.result().toHex(),
572 encoding="ascii"),
573 str(self.__md5Hash.result().toHex(),
574 encoding="ascii")
575 )
576 else: 391 else:
577 info = self.tr("{0} of {1} - Stopped")\ 392 info = self.tr("{0} of {1} - Stopped")\
578 .format(dataString(self.__bytesReceived), 393 .format(dataString(self.__bytesReceived),
579 dataString(bytesTotal)) 394 dataString(bytesTotal))
580 self.infoLabel.setText(info) 395 self.infoLabel.setText(info)
606 def __finished(self): 421 def __finished(self):
607 """ 422 """
608 Private slot to handle the download finished. 423 Private slot to handle the download finished.
609 """ 424 """
610 self.__finishedDownloading = True 425 self.__finishedDownloading = True
611 if not self.__startedSaving: 426
612 return 427 noError = (self.__downloadItem.state() ==
613 428 QWebEngineDownloadItem.DownloadCompleted)
614 noError = self.__reply.error() == QNetworkReply.NoError
615 429
616 self.progressBar.setVisible(False) 430 self.progressBar.setVisible(False)
617 if not self.__isFtpDownload: 431 self.stopButton.setEnabled(False)
618 self.stopButton.setEnabled(False) 432 self.stopButton.setVisible(False)
619 self.stopButton.setVisible(False)
620 self.pauseButton.setEnabled(False)
621 self.pauseButton.setVisible(False)
622 self.openButton.setEnabled(noError) 433 self.openButton.setEnabled(noError)
623 self.openButton.setVisible(noError) 434 self.openButton.setVisible(noError)
624 self.__output.close()
625 if QFile.exists(self.__fileName):
626 QFile.remove(self.__fileName)
627 self.__output.rename(self.__fileName)
628 self.__updateInfoLabel() 435 self.__updateInfoLabel()
629 self.__state = DownloadItem.DownloadSuccessful 436 self.__state = DownloadItem.DownloadSuccessful
630 self.statusChanged.emit() 437 self.statusChanged.emit()
631 self.downloadFinished.emit() 438 self.downloadFinished.emit()
632 439
683 URL of the related web page (QUrl, string, boolean, QUrl) 490 URL of the related web page (QUrl, string, boolean, QUrl)
684 """ 491 """
685 self.__url = data[0] 492 self.__url = data[0]
686 self.__fileName = data[1] 493 self.__fileName = data[1]
687 self.__pageUrl = data[3] 494 self.__pageUrl = data[3]
688 self.__isFtpDownload = self.__url.scheme() == "ftp"
689 495
690 self.filenameLabel.setText(QFileInfo(self.__fileName).fileName()) 496 self.filenameLabel.setText(QFileInfo(self.__fileName).fileName())
691 self.infoLabel.setText(self.__fileName) 497 self.infoLabel.setText(self.__fileName)
692 498
693 self.stopButton.setEnabled(False) 499 self.stopButton.setEnabled(False)
694 self.stopButton.setVisible(False) 500 self.stopButton.setVisible(False)
695 self.pauseButton.setEnabled(False)
696 self.pauseButton.setVisible(False)
697 self.openButton.setEnabled(data[2]) 501 self.openButton.setEnabled(data[2])
698 self.openButton.setVisible(data[2]) 502 self.openButton.setVisible(data[2])
699 self.tryAgainButton.setEnabled(not data[2])
700 self.tryAgainButton.setVisible(not data[2])
701 if data[2]: 503 if data[2]:
702 self.__state = DownloadItem.DownloadSuccessful 504 self.__state = DownloadItem.DownloadSuccessful
703 else: 505 else:
704 self.__state = DownloadItem.DownloadCancelled 506 self.__state = DownloadItem.DownloadCancelled
705 self.progressBar.setVisible(False) 507 self.progressBar.setVisible(False)

eric ide

mercurial