2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2015-2023 Vladimir Golovnev <glassez@yandex.ru>
4 * Copyright (C) 2006 Christophe Dumez <chris@qbittorrent.org>
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * In addition, as a special exception, the copyright holders give permission to
21 * link this program with the OpenSSL project's "OpenSSL" library (or with
22 * modified versions of it that use the same license as the "OpenSSL" library),
23 * and distribute the linked executables. You must obey the GNU General Public
24 * License in all respects for all of the code used other than "OpenSSL". If you
25 * modify file(s), you may extend this exception to your version of the file(s),
26 * but you are not obligated to do so. If you do not wish to do so, delete this
27 * exception statement from your version.
35 #include <libtorrent/add_torrent_params.hpp>
36 #include <libtorrent/fwd.hpp>
37 #include <libtorrent/torrent_handle.hpp>
38 #include <libtorrent/torrent_info.hpp>
39 #include <libtorrent/torrent_status.hpp>
50 #include "base/path.h"
51 #include "base/tagset.h"
53 #include "speedmonitor.h"
54 #include "sslparameters.h"
56 #include "torrentcontentlayout.h"
57 #include "torrentinfo.h"
58 #include "trackerentrystatus.h"
63 struct LoadTorrentParams
;
65 enum class MoveStorageMode
72 enum class MoveStorageContext
74 AdjustCurrentLocation
,
79 enum class MaintenanceJob
88 lt::operation_t operation
= lt::operation_t::unknown
;
91 class TorrentImpl final
: public Torrent
94 Q_DISABLE_COPY_MOVE(TorrentImpl
)
97 TorrentImpl(SessionImpl
*session
, lt::session
*nativeSession
98 , const lt::torrent_handle
&nativeHandle
, const LoadTorrentParams
¶ms
);
99 ~TorrentImpl() override
;
101 bool isValid() const;
103 Session
*session() const override
;
105 InfoHash
infoHash() const override
;
106 QString
name() const override
;
107 QDateTime
creationDate() const override
;
108 QString
creator() const override
;
109 QString
comment() const override
;
110 bool isPrivate() const override
;
111 qlonglong
totalSize() const override
;
112 qlonglong
wantedSize() const override
;
113 qlonglong
completedSize() const override
;
114 qlonglong
pieceLength() const override
;
115 qlonglong
wastedSize() const override
;
116 QString
currentTracker() const override
;
118 bool isAutoTMMEnabled() const override
;
119 void setAutoTMMEnabled(bool enabled
) override
;
120 Path
savePath() const override
;
121 void setSavePath(const Path
&path
) override
;
122 Path
downloadPath() const override
;
123 void setDownloadPath(const Path
&path
) override
;
124 Path
actualStorageLocation() const override
;
125 Path
rootPath() const override
;
126 Path
contentPath() const override
;
127 QString
category() const override
;
128 bool belongsToCategory(const QString
&category
) const override
;
129 bool setCategory(const QString
&category
) override
;
131 TagSet
tags() const override
;
132 bool hasTag(const Tag
&tag
) const override
;
133 bool addTag(const Tag
&tag
) override
;
134 bool removeTag(const Tag
&tag
) override
;
135 void removeAllTags() override
;
137 int filesCount() const override
;
138 int piecesCount() const override
;
139 int piecesHave() const override
;
140 qreal
progress() const override
;
141 QDateTime
addedTime() const override
;
143 qreal
ratioLimit() const override
;
144 void setRatioLimit(qreal limit
) override
;
145 int seedingTimeLimit() const override
;
146 void setSeedingTimeLimit(int limit
) override
;
147 int inactiveSeedingTimeLimit() const override
;
148 void setInactiveSeedingTimeLimit(int limit
) override
;
149 ShareLimitAction
shareLimitAction() const override
;
150 void setShareLimitAction(ShareLimitAction action
) override
;
152 Path
filePath(int index
) const override
;
153 Path
actualFilePath(int index
) const override
;
154 qlonglong
fileSize(int index
) const override
;
155 PathList
filePaths() const override
;
156 PathList
actualFilePaths() const override
;
157 QList
<DownloadPriority
> filePriorities() const override
;
159 TorrentInfo
info() const override
;
160 bool isFinished() const override
;
161 bool isStopped() const override
;
162 bool isQueued() const override
;
163 bool isForced() const override
;
164 bool isChecking() const override
;
165 bool isDownloading() const override
;
166 bool isMoving() const override
;
167 bool isUploading() const override
;
168 bool isCompleted() const override
;
169 bool isActive() const override
;
170 bool isInactive() const override
;
171 bool isErrored() const override
;
172 bool isSequentialDownload() const override
;
173 bool hasFirstLastPiecePriority() const override
;
174 TorrentState
state() const override
;
175 bool hasMetadata() const override
;
176 bool hasMissingFiles() const override
;
177 bool hasError() const override
;
178 int queuePosition() const override
;
179 QList
<TrackerEntryStatus
> trackers() const override
;
180 QList
<QUrl
> urlSeeds() const override
;
181 QString
error() const override
;
182 qlonglong
totalDownload() const override
;
183 qlonglong
totalUpload() const override
;
184 qlonglong
activeTime() const override
;
185 qlonglong
finishedTime() const override
;
186 qlonglong
eta() const override
;
187 QList
<qreal
> filesProgress() const override
;
188 int seedsCount() const override
;
189 int peersCount() const override
;
190 int leechsCount() const override
;
191 int totalSeedsCount() const override
;
192 int totalPeersCount() const override
;
193 int totalLeechersCount() const override
;
194 QDateTime
lastSeenComplete() const override
;
195 QDateTime
completedTime() const override
;
196 qlonglong
timeSinceUpload() const override
;
197 qlonglong
timeSinceDownload() const override
;
198 qlonglong
timeSinceActivity() const override
;
199 int downloadLimit() const override
;
200 int uploadLimit() const override
;
201 bool superSeeding() const override
;
202 bool isDHTDisabled() const override
;
203 bool isPEXDisabled() const override
;
204 bool isLSDDisabled() const override
;
205 QList
<PeerInfo
> peers() const override
;
206 QBitArray
pieces() const override
;
207 QBitArray
downloadingPieces() const override
;
208 QList
<int> pieceAvailability() const override
;
209 qreal
distributedCopies() const override
;
210 qreal
maxRatio() const override
;
211 int maxSeedingTime() const override
;
212 int maxInactiveSeedingTime() const override
;
213 qreal
realRatio() const override
;
214 qreal
popularity() const override
;
215 int uploadPayloadRate() const override
;
216 int downloadPayloadRate() const override
;
217 qlonglong
totalPayloadUpload() const override
;
218 qlonglong
totalPayloadDownload() const override
;
219 int connectionsCount() const override
;
220 int connectionsLimit() const override
;
221 qlonglong
nextAnnounce() const override
;
222 QList
<qreal
> availableFileFractions() const override
;
224 void setName(const QString
&name
) override
;
225 void setSequentialDownload(bool enable
) override
;
226 void setFirstLastPiecePriority(bool enabled
) override
;
227 void stop() override
;
228 void start(TorrentOperatingMode mode
= TorrentOperatingMode::AutoManaged
) override
;
229 void forceReannounce(int index
= -1) override
;
230 void forceDHTAnnounce() override
;
231 void forceRecheck() override
;
232 void renameFile(int index
, const Path
&path
) override
;
233 void prioritizeFiles(const QList
<DownloadPriority
> &priorities
) override
;
234 void setUploadLimit(int limit
) override
;
235 void setDownloadLimit(int limit
) override
;
236 void setSuperSeeding(bool enable
) override
;
237 void setDHTDisabled(bool disable
) override
;
238 void setPEXDisabled(bool disable
) override
;
239 void setLSDDisabled(bool disable
) override
;
240 void flushCache() const override
;
241 void addTrackers(QList
<TrackerEntry
> trackers
) override
;
242 void removeTrackers(const QStringList
&trackers
) override
;
243 void replaceTrackers(QList
<TrackerEntry
> trackers
) override
;
244 void addUrlSeeds(const QList
<QUrl
> &urlSeeds
) override
;
245 void removeUrlSeeds(const QList
<QUrl
> &urlSeeds
) override
;
246 bool connectPeer(const PeerAddress
&peerAddress
) override
;
247 void clearPeers() override
;
248 void setMetadata(const TorrentInfo
&torrentInfo
) override
;
250 StopCondition
stopCondition() const override
;
251 void setStopCondition(StopCondition stopCondition
) override
;
252 SSLParameters
getSSLParameters() const override
;
253 void setSSLParameters(const SSLParameters
&sslParams
) override
;
254 bool applySSLParameters();
256 QString
createMagnetURI() const override
;
257 nonstd::expected
<QByteArray
, QString
> exportToBuffer() const override
;
258 nonstd::expected
<void, QString
> exportToFile(const Path
&path
) const override
;
260 void fetchPeerInfo(std::function
<void (QList
<PeerInfo
>)> resultHandler
) const override
;
261 void fetchURLSeeds(std::function
<void (QList
<QUrl
>)> resultHandler
) const override
;
262 void fetchPieceAvailability(std::function
<void (QList
<int>)> resultHandler
) const override
;
263 void fetchDownloadingPieces(std::function
<void (QBitArray
)> resultHandler
) const override
;
264 void fetchAvailableFileFractions(std::function
<void (QList
<qreal
>)> resultHandler
) const override
;
266 bool needSaveResumeData() const;
269 lt::torrent_handle
nativeHandle() const;
271 void handleAlert(const lt::alert
*a
);
272 void handleStateUpdate(const lt::torrent_status
&nativeStatus
);
273 void handleQueueingModeChanged();
274 void handleCategoryOptionsChanged();
275 void handleAppendExtensionToggled();
276 void handleUnwantedFolderToggled();
277 void requestResumeData(lt::resume_data_flags_t flags
= {});
278 void deferredRequestResumeData();
279 void handleMoveStorageJobFinished(const Path
&path
, MoveStorageContext context
, bool hasOutstandingJob
);
280 void fileSearchFinished(const Path
&savePath
, const PathList
&fileNames
);
281 TrackerEntryStatus
updateTrackerEntryStatus(const lt::announce_entry
&announceEntry
, const QHash
<lt::tcp::endpoint
, QMap
<int, int>> &updateInfo
);
282 void resetTrackerEntryStatuses();
285 using EventTrigger
= std::function
<void ()>;
287 std::shared_ptr
<const lt::torrent_info
> nativeTorrentInfo() const;
289 void updateStatus(const lt::torrent_status
&nativeStatus
);
290 void updateProgress();
293 void handleFastResumeRejectedAlert(const lt::fastresume_rejected_alert
*p
);
294 void handleFileCompletedAlert(const lt::file_completed_alert
*p
);
295 void handleFileErrorAlert(const lt::file_error_alert
*p
);
296 #ifdef QBT_USES_LIBTORRENT2
297 void handleFilePrioAlert(const lt::file_prio_alert
*p
);
299 void handleFileRenamedAlert(const lt::file_renamed_alert
*p
);
300 void handleFileRenameFailedAlert(const lt::file_rename_failed_alert
*p
);
301 void handleMetadataReceivedAlert(const lt::metadata_received_alert
*p
);
302 void handlePerformanceAlert(const lt::performance_alert
*p
) const;
303 void handleSaveResumeDataAlert(const lt::save_resume_data_alert
*p
);
304 void handleSaveResumeDataFailedAlert(const lt::save_resume_data_failed_alert
*p
);
305 void handleTorrentCheckedAlert(const lt::torrent_checked_alert
*p
);
306 void handleTorrentFinishedAlert(const lt::torrent_finished_alert
*p
);
307 void handleTorrentPausedAlert(const lt::torrent_paused_alert
*p
);
308 void handleTorrentResumedAlert(const lt::torrent_resumed_alert
*p
);
310 bool isMoveInProgress() const;
312 void setAutoManaged(bool enable
);
314 Path
makeActualPath(int index
, const Path
&path
) const;
315 Path
makeUserPath(const Path
&path
) const;
316 void adjustStorageLocation();
317 void doRenameFile(int index
, const Path
&path
);
318 void moveStorage(const Path
&newPath
, MoveStorageContext context
);
319 void manageActualFilePaths();
320 void applyFirstLastPiecePriority(bool enabled
);
322 void prepareResumeData(const lt::add_torrent_params
¶ms
);
323 void endReceivedMetadataHandling(const Path
&savePath
, const PathList
&fileNames
);
326 nonstd::expected
<lt::entry
, QString
> exportTorrent() const;
328 template <typename Func
, typename Callback
>
329 void invokeAsync(Func func
, Callback resultHandler
) const;
331 SessionImpl
*const m_session
= nullptr;
332 lt::session
*m_nativeSession
= nullptr;
333 lt::torrent_handle m_nativeHandle
;
334 mutable lt::torrent_status m_nativeStatus
;
335 TorrentState m_state
= TorrentState::Unknown
;
336 TorrentInfo m_torrentInfo
;
337 PathList m_filePaths
;
338 QHash
<lt::file_index_t
, int> m_indexMap
;
339 QList
<DownloadPriority
> m_filePriorities
;
340 QBitArray m_completedFiles
;
341 SpeedMonitor m_payloadRateMonitor
;
345 // m_moveFinishedTriggers is activated only when the following conditions are met:
346 // all file rename jobs complete, all file move jobs complete
347 QQueue
<EventTrigger
> m_moveFinishedTriggers
;
348 int m_renameCount
= 0;
349 bool m_storageIsMoving
= false;
351 QQueue
<EventTrigger
> m_statusUpdatedTriggers
;
353 MaintenanceJob m_maintenanceJob
= MaintenanceJob::None
;
355 QList
<TrackerEntryStatus
> m_trackerEntryStatuses
;
356 QList
<QUrl
> m_urlSeeds
;
357 FileErrorInfo m_lastFileError
;
365 qreal m_ratioLimit
= 0;
366 int m_seedingTimeLimit
= 0;
367 int m_inactiveSeedingTimeLimit
= 0;
368 ShareLimitAction m_shareLimitAction
= ShareLimitAction::Default
;
369 TorrentOperatingMode m_operatingMode
= TorrentOperatingMode::AutoManaged
;
370 TorrentContentLayout m_contentLayout
= TorrentContentLayout::Original
;
371 bool m_hasFinishedStatus
= false;
372 bool m_hasMissingFiles
= false;
373 bool m_hasFirstLastPiecePriority
= false;
374 bool m_useAutoTMM
= false;
375 bool m_isStopped
= false;
376 StopCondition m_stopCondition
= StopCondition::None
;
377 SSLParameters m_sslParams
;
379 bool m_unchecked
= false;
381 lt::add_torrent_params m_ltAddTorrentParams
;
383 int m_downloadLimit
= 0;
384 int m_uploadLimit
= 0;
387 QList
<std::int64_t> m_filesProgress
;
389 bool m_deferredRequestResumeDataInvoked
= false;