2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2021-2023 Vladimir Golovnev <glassez@yandex.ru>
4 * Copyright (C) 2010 Christian Kandeler, 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.
30 #include "torrentfileswatcher.h"
36 #include <QDirIterator>
38 #include <QFileSystemWatcher>
39 #include <QJsonDocument>
40 #include <QJsonObject>
46 #include "base/algorithm.h"
47 #include "base/bittorrent/torrentcontentlayout.h"
48 #include "base/bittorrent/session.h"
49 #include "base/bittorrent/torrent.h"
50 #include "base/exceptions.h"
51 #include "base/global.h"
52 #include "base/logger.h"
53 #include "base/profile.h"
54 #include "base/settingsstorage.h"
55 #include "base/tagset.h"
56 #include "base/utils/fs.h"
57 #include "base/utils/io.h"
58 #include "base/utils/string.h"
60 using namespace std::chrono_literals
;
62 const std::chrono::seconds WATCH_INTERVAL
{10};
63 const int MAX_FAILED_RETRIES
= 5;
64 const QString CONF_FILE_NAME
= u
"watched_folders.json"_s
;
66 const QString OPTION_ADDTORRENTPARAMS
= u
"add_torrent_params"_s
;
67 const QString OPTION_RECURSIVE
= u
"recursive"_s
;
71 TorrentFilesWatcher::WatchedFolderOptions
parseWatchedFolderOptions(const QJsonObject
&jsonObj
)
73 TorrentFilesWatcher::WatchedFolderOptions options
;
74 options
.addTorrentParams
= BitTorrent::parseAddTorrentParams(jsonObj
.value(OPTION_ADDTORRENTPARAMS
).toObject());
75 options
.recursive
= jsonObj
.value(OPTION_RECURSIVE
).toBool();
80 QJsonObject
serializeWatchedFolderOptions(const TorrentFilesWatcher::WatchedFolderOptions
&options
)
82 return {{OPTION_ADDTORRENTPARAMS
, BitTorrent::serializeAddTorrentParams(options
.addTorrentParams
)},
83 {OPTION_RECURSIVE
, options
.recursive
}};
87 class TorrentFilesWatcher::Worker final
: public QObject
90 Q_DISABLE_COPY_MOVE(Worker
)
93 Worker(QFileSystemWatcher
*watcher
);
96 void setWatchedFolder(const Path
&path
, const TorrentFilesWatcher::WatchedFolderOptions
&options
);
97 void removeWatchedFolder(const Path
&path
);
100 void torrentFound(const BitTorrent::TorrentDescriptor
&torrentDescr
, const BitTorrent::AddTorrentParams
&addTorrentParams
);
104 void scheduleWatchedFolderProcessing(const Path
&path
);
105 void processWatchedFolder(const Path
&path
);
106 void processFolder(const Path
&path
, const Path
&watchedFolderPath
, const TorrentFilesWatcher::WatchedFolderOptions
&options
);
107 void processFailedTorrents();
108 void addWatchedFolder(const Path
&path
, const TorrentFilesWatcher::WatchedFolderOptions
&options
);
109 void updateWatchedFolder(const Path
&path
, const TorrentFilesWatcher::WatchedFolderOptions
&options
);
111 QFileSystemWatcher
*m_watcher
= nullptr;
112 QTimer
*m_watchTimer
= nullptr;
113 QHash
<Path
, TorrentFilesWatcher::WatchedFolderOptions
> m_watchedFolders
;
114 QSet
<Path
> m_watchedByTimeoutFolders
;
117 QTimer
*m_retryTorrentTimer
= nullptr;
118 QHash
<Path
, QHash
<Path
, int>> m_failedTorrents
;
121 TorrentFilesWatcher
*TorrentFilesWatcher::m_instance
= nullptr;
123 void TorrentFilesWatcher::initInstance()
126 m_instance
= new TorrentFilesWatcher
;
129 void TorrentFilesWatcher::freeInstance()
132 m_instance
= nullptr;
135 TorrentFilesWatcher
*TorrentFilesWatcher::instance()
140 TorrentFilesWatcher::TorrentFilesWatcher(QObject
*parent
)
142 , m_ioThread
{new QThread
}
143 , m_asyncWorker
{new TorrentFilesWatcher::Worker(new QFileSystemWatcher(this))}
145 connect(m_asyncWorker
, &TorrentFilesWatcher::Worker::torrentFound
, this, &TorrentFilesWatcher::onTorrentFound
);
147 m_asyncWorker
->moveToThread(m_ioThread
.get());
148 connect(m_ioThread
.get(), &QThread::finished
, m_asyncWorker
, &QObject::deleteLater
);
149 m_ioThread
->setObjectName("TorrentFilesWatcher m_ioThread");
155 void TorrentFilesWatcher::load()
157 const int fileMaxSize
= 10 * 1024 * 1024;
158 const Path path
= specialFolderLocation(SpecialFolder::Config
) / Path(CONF_FILE_NAME
);
160 const auto readResult
= Utils::IO::readFile(path
, fileMaxSize
);
163 if (readResult
.error().status
== Utils::IO::ReadError::NotExist
)
169 LogMsg(tr("Failed to load Watched Folders configuration. %1").arg(readResult
.error().message
), Log::WARNING
);
173 QJsonParseError jsonError
;
174 const QJsonDocument jsonDoc
= QJsonDocument::fromJson(readResult
.value(), &jsonError
);
175 if (jsonError
.error
!= QJsonParseError::NoError
)
177 LogMsg(tr("Failed to parse Watched Folders configuration from %1. Error: \"%2\"")
178 .arg(path
.toString(), jsonError
.errorString()), Log::WARNING
);
182 if (!jsonDoc
.isObject())
184 LogMsg(tr("Failed to load Watched Folders configuration from %1. Error: \"Invalid data format.\"")
185 .arg(path
.toString()), Log::WARNING
);
189 const QJsonObject jsonObj
= jsonDoc
.object();
190 for (auto it
= jsonObj
.constBegin(); it
!= jsonObj
.constEnd(); ++it
)
192 const Path watchedFolder
{it
.key()};
193 const WatchedFolderOptions options
= parseWatchedFolderOptions(it
.value().toObject());
196 doSetWatchedFolder(watchedFolder
, options
);
198 catch (const InvalidArgument
&err
)
200 LogMsg(err
.message(), Log::WARNING
);
205 void TorrentFilesWatcher::loadLegacy()
207 const auto dirs
= SettingsStorage::instance()->loadValue
<QVariantHash
>(u
"Preferences/Downloads/ScanDirsV2"_s
);
209 for (auto it
= dirs
.cbegin(); it
!= dirs
.cend(); ++it
)
211 const Path watchedFolder
{it
.key()};
212 BitTorrent::AddTorrentParams params
;
213 if (it
.value().userType() == QMetaType::Int
)
215 if (it
.value().toInt() == 0)
217 params
.savePath
= watchedFolder
;
218 params
.useAutoTMM
= false;
223 const Path customSavePath
{it
.value().toString()};
224 params
.savePath
= customSavePath
;
225 params
.useAutoTMM
= false;
230 doSetWatchedFolder(watchedFolder
, {params
, false});
232 catch (const InvalidArgument
&err
)
234 LogMsg(err
.message(), Log::WARNING
);
239 SettingsStorage::instance()->removeValue(u
"Preferences/Downloads/ScanDirsV2"_s
);
242 void TorrentFilesWatcher::store() const
245 for (auto it
= m_watchedFolders
.cbegin(); it
!= m_watchedFolders
.cend(); ++it
)
247 const Path
&watchedFolder
= it
.key();
248 const WatchedFolderOptions
&options
= it
.value();
249 jsonObj
[watchedFolder
.data()] = serializeWatchedFolderOptions(options
);
252 const Path path
= specialFolderLocation(SpecialFolder::Config
) / Path(CONF_FILE_NAME
);
253 const QByteArray data
= QJsonDocument(jsonObj
).toJson();
254 const nonstd::expected
<void, QString
> result
= Utils::IO::saveToFile(path
, data
);
257 LogMsg(tr("Couldn't store Watched Folders configuration to %1. Error: %2")
258 .arg(path
.toString(), result
.error()), Log::WARNING
);
262 QHash
<Path
, TorrentFilesWatcher::WatchedFolderOptions
> TorrentFilesWatcher::folders() const
264 return m_watchedFolders
;
267 void TorrentFilesWatcher::setWatchedFolder(const Path
&path
, const WatchedFolderOptions
&options
)
269 doSetWatchedFolder(path
, options
);
273 void TorrentFilesWatcher::doSetWatchedFolder(const Path
&path
, const WatchedFolderOptions
&options
)
276 throw InvalidArgument(tr("Watched folder Path cannot be empty."));
278 if (path
.isRelative())
279 throw InvalidArgument(tr("Watched folder Path cannot be relative."));
281 m_watchedFolders
[path
] = options
;
283 QMetaObject::invokeMethod(m_asyncWorker
, [this, path
, options
]
285 m_asyncWorker
->setWatchedFolder(path
, options
);
288 emit
watchedFolderSet(path
, options
);
291 void TorrentFilesWatcher::removeWatchedFolder(const Path
&path
)
293 if (m_watchedFolders
.remove(path
))
297 QMetaObject::invokeMethod(m_asyncWorker
, [this, path
]()
299 m_asyncWorker
->removeWatchedFolder(path
);
303 emit
watchedFolderRemoved(path
);
309 void TorrentFilesWatcher::onTorrentFound(const BitTorrent::TorrentDescriptor
&torrentDescr
310 , const BitTorrent::AddTorrentParams
&addTorrentParams
)
312 BitTorrent::Session::instance()->addTorrent(torrentDescr
, addTorrentParams
);
315 TorrentFilesWatcher::Worker::Worker(QFileSystemWatcher
*watcher
)
316 : m_watcher
{watcher
}
317 , m_watchTimer
{new QTimer(this)}
318 , m_retryTorrentTimer
{new QTimer(this)}
320 connect(m_watcher
, &QFileSystemWatcher::directoryChanged
, this, [this](const QString
&path
)
322 scheduleWatchedFolderProcessing(Path(path
));
324 connect(m_watchTimer
, &QTimer::timeout
, this, &Worker::onTimeout
);
326 connect(m_retryTorrentTimer
, &QTimer::timeout
, this, &Worker::processFailedTorrents
);
329 void TorrentFilesWatcher::Worker::onTimeout()
331 for (const Path
&path
: asConst(m_watchedByTimeoutFolders
))
332 processWatchedFolder(path
);
335 void TorrentFilesWatcher::Worker::setWatchedFolder(const Path
&path
, const TorrentFilesWatcher::WatchedFolderOptions
&options
)
337 if (m_watchedFolders
.contains(path
))
338 updateWatchedFolder(path
, options
);
340 addWatchedFolder(path
, options
);
343 void TorrentFilesWatcher::Worker::removeWatchedFolder(const Path
&path
)
345 m_watchedFolders
.remove(path
);
347 m_watcher
->removePath(path
.data());
348 m_watchedByTimeoutFolders
.remove(path
);
349 if (m_watchedByTimeoutFolders
.isEmpty())
350 m_watchTimer
->stop();
352 m_failedTorrents
.remove(path
);
353 if (m_failedTorrents
.isEmpty())
354 m_retryTorrentTimer
->stop();
357 void TorrentFilesWatcher::Worker::scheduleWatchedFolderProcessing(const Path
&path
)
359 QTimer::singleShot(2s
, Qt::CoarseTimer
, this, [this, path
]
361 processWatchedFolder(path
);
365 void TorrentFilesWatcher::Worker::processWatchedFolder(const Path
&path
)
367 const TorrentFilesWatcher::WatchedFolderOptions options
= m_watchedFolders
.value(path
);
368 processFolder(path
, path
, options
);
370 if (!m_failedTorrents
.empty() && !m_retryTorrentTimer
->isActive())
371 m_retryTorrentTimer
->start(WATCH_INTERVAL
);
374 void TorrentFilesWatcher::Worker::processFolder(const Path
&path
, const Path
&watchedFolderPath
375 , const TorrentFilesWatcher::WatchedFolderOptions
&options
)
377 QDirIterator dirIter
{path
.data(), {u
"*.torrent"_s
, u
"*.magnet"_s
}, QDir::Files
};
378 while (dirIter
.hasNext())
380 const Path filePath
{dirIter
.next()};
381 BitTorrent::AddTorrentParams addTorrentParams
= options
.addTorrentParams
;
382 if (path
!= watchedFolderPath
)
384 const Path subdirPath
= watchedFolderPath
.relativePathOf(path
);
385 const bool useAutoTMM
= addTorrentParams
.useAutoTMM
.value_or(!BitTorrent::Session::instance()->isAutoTMMDisabledByDefault());
388 addTorrentParams
.category
= addTorrentParams
.category
.isEmpty()
389 ? subdirPath
.data() : (addTorrentParams
.category
+ u
'/' + subdirPath
.data());
393 addTorrentParams
.savePath
= addTorrentParams
.savePath
/ subdirPath
;
397 if (filePath
.hasExtension(u
".magnet"_s
))
399 const int fileMaxSize
= 100 * 1024 * 1024;
401 QFile file
{filePath
.data()};
402 if (file
.open(QIODevice::ReadOnly
| QIODevice::Text
))
404 if (file
.size() <= fileMaxSize
)
406 while (!file
.atEnd())
408 const auto line
= QString::fromLatin1(file
.readLine()).trimmed();
409 if (const auto parseResult
= BitTorrent::TorrentDescriptor::parse(line
))
410 emit
torrentFound(parseResult
.value(), addTorrentParams
);
412 LogMsg(tr("Invalid Magnet URI. URI: %1. Reason: %2").arg(line
, parseResult
.error()), Log::WARNING
);
416 Utils::Fs::removeFile(filePath
);
420 LogMsg(tr("Magnet file too big. File: %1").arg(file
.errorString()), Log::WARNING
);
425 LogMsg(tr("Failed to open magnet file: %1").arg(file
.errorString()));
430 if (const auto loadResult
= BitTorrent::TorrentDescriptor::loadFromFile(filePath
))
432 emit
torrentFound(loadResult
.value(), addTorrentParams
);
433 Utils::Fs::removeFile(filePath
);
437 if (!m_failedTorrents
.value(path
).contains(filePath
))
439 m_failedTorrents
[path
][filePath
] = 0;
445 if (options
.recursive
)
447 QDirIterator iter
{path
.data(), (QDir::Dirs
| QDir::NoDotAndDotDot
)};
448 while (iter
.hasNext())
450 const Path folderPath
{iter
.next()};
451 // Skip processing of subdirectory that is explicitly set as watched folder
452 if (!m_watchedFolders
.contains(folderPath
))
453 processFolder(folderPath
, watchedFolderPath
, options
);
458 void TorrentFilesWatcher::Worker::processFailedTorrents()
460 // Check which torrents are still partial
461 Algorithm::removeIf(m_failedTorrents
, [this](const Path
&watchedFolderPath
, QHash
<Path
, int> &partialTorrents
)
463 const TorrentFilesWatcher::WatchedFolderOptions options
= m_watchedFolders
.value(watchedFolderPath
);
464 Algorithm::removeIf(partialTorrents
, [this, &watchedFolderPath
, &options
](const Path
&torrentPath
, int &value
)
466 if (!torrentPath
.exists())
469 if (const auto loadResult
= BitTorrent::TorrentDescriptor::loadFromFile(torrentPath
))
471 BitTorrent::AddTorrentParams addTorrentParams
= options
.addTorrentParams
;
472 if (torrentPath
!= watchedFolderPath
)
474 const Path subdirPath
= watchedFolderPath
.relativePathOf(torrentPath
);
475 const bool useAutoTMM
= addTorrentParams
.useAutoTMM
.value_or(!BitTorrent::Session::instance()->isAutoTMMDisabledByDefault());
478 addTorrentParams
.category
= addTorrentParams
.category
.isEmpty()
479 ? subdirPath
.data() : (addTorrentParams
.category
+ u
'/' + subdirPath
.data());
483 addTorrentParams
.savePath
= addTorrentParams
.savePath
/ subdirPath
;
487 emit
torrentFound(loadResult
.value(), addTorrentParams
);
488 Utils::Fs::removeFile(torrentPath
);
493 if (value
>= MAX_FAILED_RETRIES
)
495 LogMsg(tr("Rejecting failed torrent file: %1").arg(torrentPath
.toString()));
496 Utils::Fs::renameFile(torrentPath
, (torrentPath
+ u
".qbt_rejected"));
504 if (partialTorrents
.isEmpty())
510 // Stop the partial timer if necessary
511 if (m_failedTorrents
.empty())
512 m_retryTorrentTimer
->stop();
514 m_retryTorrentTimer
->start(WATCH_INTERVAL
);
517 void TorrentFilesWatcher::Worker::addWatchedFolder(const Path
&path
, const TorrentFilesWatcher::WatchedFolderOptions
&options
)
519 // Check if the `path` points to a network file system or not
520 if (Utils::Fs::isNetworkFileSystem(path
) || options
.recursive
)
522 m_watchedByTimeoutFolders
.insert(path
);
523 if (!m_watchTimer
->isActive())
524 m_watchTimer
->start(WATCH_INTERVAL
);
528 m_watcher
->addPath(path
.data());
529 scheduleWatchedFolderProcessing(path
);
532 m_watchedFolders
[path
] = options
;
534 LogMsg(tr("Watching folder: \"%1\"").arg(path
.toString()));
537 void TorrentFilesWatcher::Worker::updateWatchedFolder(const Path
&path
, const TorrentFilesWatcher::WatchedFolderOptions
&options
)
539 const bool recursiveModeChanged
= (m_watchedFolders
[path
].recursive
!= options
.recursive
);
540 if (recursiveModeChanged
&& !Utils::Fs::isNetworkFileSystem(path
))
542 if (options
.recursive
)
544 m_watcher
->removePath(path
.data());
546 m_watchedByTimeoutFolders
.insert(path
);
547 if (!m_watchTimer
->isActive())
548 m_watchTimer
->start(WATCH_INTERVAL
);
552 m_watchedByTimeoutFolders
.remove(path
);
553 if (m_watchedByTimeoutFolders
.isEmpty())
554 m_watchTimer
->stop();
556 m_watcher
->addPath(path
.data());
557 scheduleWatchedFolderProcessing(path
);
561 m_watchedFolders
[path
] = options
;
564 #include "torrentfileswatcher.moc"