Line data Source code
1 : #ifndef BATCHDOWNLOADCORE_H
2 : #define BATCHDOWNLOADCORE_H
3 :
4 : #include <QObject>
5 : #include <QUrl>
6 : #include <QByteArray>
7 : #include <QMap>
8 : #include <QList>
9 :
10 : #include "../FangObject.h"
11 : #include "NetworkDownloadCore.h"
12 :
13 : class QNetworkAccessManager;
14 :
15 : /*!
16 : \brief Result of a single download in a batch.
17 : */
18 : struct BatchDownloadResult {
19 : QByteArray data; // Downloaded content
20 : QUrl finalUrl; // Final URL after redirects
21 : bool success = false; // Whether download succeeded
22 : QString errorString; // Error message if failed
23 : };
24 :
25 : /*!
26 : \brief BatchDownloadCore downloads multiple URLs in parallel by wrapping NetworkDownloadCore.
27 :
28 : Use case: You need to download multiple things and wait for all the results before proeeding.
29 : */
30 : class BatchDownloadCore : public FangObject
31 : {
32 : Q_OBJECT
33 : public:
34 : /*!
35 : \param timeoutMs
36 : \param maxRedirects
37 : \param parent
38 : \param networkManager If specified, caller is responsible for its lifecycle.
39 : */
40 : explicit BatchDownloadCore(int timeoutMs = 30000,
41 : int maxRedirects = 10,
42 : QObject* parent = nullptr,
43 : QNetworkAccessManager* networkManager = nullptr);
44 : virtual ~BatchDownloadCore();
45 :
46 : /*!
47 : Start downloading a list of URLs, emits finished() when done.
48 : */
49 : void download(const QList<QUrl>& urls);
50 :
51 : /*!
52 : Abort all pending downloads.
53 : */
54 : void abort();
55 :
56 : /*!
57 : Get the results (after finished() is emitted.)
58 : */
59 35 : inline QMap<QUrl, BatchDownloadResult> results() const { return _results; }
60 :
61 : signals:
62 : /*!
63 : \brief Emitted when all downloads complete (success or failure).
64 : */
65 : void finished();
66 :
67 : /*!
68 : \brief Emitted as downloads complete to show progress.
69 :
70 : \param completed Number of completed downloads
71 : \param total Total number of downloads
72 : */
73 : void progress(int completed, int total);
74 :
75 : private slots:
76 : void onDownloadFinished(const QUrl& url, const QByteArray& data);
77 : void onDownloadError(const QUrl& url, const QString& errorString);
78 :
79 : private:
80 : void checkCompletion();
81 :
82 : QNetworkAccessManager* manager;
83 : NetworkDownloadConfig config;
84 :
85 : int totalCount;
86 : QMap<QUrl, BatchDownloadResult> _results;
87 : QMap<NetworkDownloadCore*, QUrl> downloaders;
88 : };
89 :
90 : #endif // BATCHDOWNLOADCORE_H
|