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
);
154 void TorrentFilesWatcher::load()
156 const int fileMaxSize
= 10 * 1024 * 1024;
157 const Path path
= specialFolderLocation(SpecialFolder::Config
) / Path(CONF_FILE_NAME
);
159 const auto readResult
= Utils::IO::readFile(path
, fileMaxSize
);
162 if (readResult
.error().status
== Utils::IO::ReadError::NotExist
)
168 LogMsg(tr("Failed to load Watched Folders configuration. %1").arg(readResult
.error().message
), Log::WARNING
);
172 QJsonParseError jsonError
;
173 const QJsonDocument jsonDoc
= QJsonDocument::fromJson(readResult
.value(), &jsonError
);
174 if (jsonError
.error
!= QJsonParseError::NoError
)
176 LogMsg(tr("Failed to parse Watched Folders configuration from %1. Error: \"%2\"")
177 .arg(path
.toString(), jsonError
.errorString()), Log::WARNING
);
181 if (!jsonDoc
.isObject())
183 LogMsg(tr("Failed to load Watched Folders configuration from %1. Error: \"Invalid data format.\"")
184 .arg(path
.toString()), Log::WARNING
);
188 const QJsonObject jsonObj
= jsonDoc
.object();
189 for (auto it
= jsonObj
.constBegin(); it
!= jsonObj
.constEnd(); ++it
)
191 const Path watchedFolder
{it
.key()};
192 const WatchedFolderOptions options
= parseWatchedFolderOptions(it
.value().toObject());
195 doSetWatchedFolder(watchedFolder
, options
);
197 catch (const InvalidArgument
&err
)
199 LogMsg(err
.message(), Log::WARNING
);
204 void TorrentFilesWatcher::loadLegacy()
206 const auto dirs
= SettingsStorage::instance()->loadValue
<QVariantHash
>(u
"Preferences/Downloads/ScanDirsV2"_s
);
208 for (auto it
= dirs
.cbegin(); it
!= dirs
.cend(); ++it
)
210 const Path watchedFolder
{it
.key()};
211 BitTorrent::AddTorrentParams params
;
212 if (it
.value().userType() == QMetaType::Int
)
214 if (it
.value().toInt() == 0)
216 params
.savePath
= watchedFolder
;
217 params
.useAutoTMM
= false;
222 const Path customSavePath
{it
.value().toString()};
223 params
.savePath
= customSavePath
;
224 params
.useAutoTMM
= false;
229 doSetWatchedFolder(watchedFolder
, {params
, false});
231 catch (const InvalidArgument
&err
)
233 LogMsg(err
.message(), Log::WARNING
);
238 SettingsStorage::instance()->removeValue(u
"Preferences/Downloads/ScanDirsV2"_s
);
241 void TorrentFilesWatcher::store() const
244 for (auto it
= m_watchedFolders
.cbegin(); it
!= m_watchedFolders
.cend(); ++it
)
246 const Path
&watchedFolder
= it
.key();
247 const WatchedFolderOptions
&options
= it
.value();
248 jsonObj
[watchedFolder
.data()] = serializeWatchedFolderOptions(options
);
251 const Path path
= specialFolderLocation(SpecialFolder::Config
) / Path(CONF_FILE_NAME
);
252 const QByteArray data
= QJsonDocument(jsonObj
).toJson();
253 const nonstd::expected
<void, QString
> result
= Utils::IO::saveToFile(path
, data
);
256 LogMsg(tr("Couldn't store Watched Folders configuration to %1. Error: %2")
257 .arg(path
.toString(), result
.error()), Log::WARNING
);
261 QHash
<Path
, TorrentFilesWatcher::WatchedFolderOptions
> TorrentFilesWatcher::folders() const
263 return m_watchedFolders
;
266 void TorrentFilesWatcher::setWatchedFolder(const Path
&path
, const WatchedFolderOptions
&options
)
268 doSetWatchedFolder(path
, options
);
272 void TorrentFilesWatcher::doSetWatchedFolder(const Path
&path
, const WatchedFolderOptions
&options
)
275 throw InvalidArgument(tr("Watched folder Path cannot be empty."));
277 if (path
.isRelative())
278 throw InvalidArgument(tr("Watched folder Path cannot be relative."));
280 m_watchedFolders
[path
] = options
;
282 QMetaObject::invokeMethod(m_asyncWorker
, [this, path
, options
]
284 m_asyncWorker
->setWatchedFolder(path
, options
);
287 emit
watchedFolderSet(path
, options
);
290 void TorrentFilesWatcher::removeWatchedFolder(const Path
&path
)
292 if (m_watchedFolders
.remove(path
))
296 QMetaObject::invokeMethod(m_asyncWorker
, [this, path
]()
298 m_asyncWorker
->removeWatchedFolder(path
);
302 emit
watchedFolderRemoved(path
);
308 void TorrentFilesWatcher::onTorrentFound(const BitTorrent::TorrentDescriptor
&torrentDescr
309 , const BitTorrent::AddTorrentParams
&addTorrentParams
)
311 BitTorrent::Session::instance()->addTorrent(torrentDescr
, addTorrentParams
);
314 TorrentFilesWatcher::Worker::Worker(QFileSystemWatcher
*watcher
)
315 : m_watcher
{watcher
}
316 , m_watchTimer
{new QTimer(this)}
317 , m_retryTorrentTimer
{new QTimer(this)}
319 connect(m_watcher
, &QFileSystemWatcher::directoryChanged
, this, [this](const QString
&path
)
321 scheduleWatchedFolderProcessing(Path(path
));
323 connect(m_watchTimer
, &QTimer::timeout
, this, &Worker::onTimeout
);
325 connect(m_retryTorrentTimer
, &QTimer::timeout
, this, &Worker::processFailedTorrents
);
328 void TorrentFilesWatcher::Worker::onTimeout()
330 for (const Path
&path
: asConst(m_watchedByTimeoutFolders
))
331 processWatchedFolder(path
);
334 void TorrentFilesWatcher::Worker::setWatchedFolder(const Path
&path
, const TorrentFilesWatcher::WatchedFolderOptions
&options
)
336 if (m_watchedFolders
.contains(path
))
337 updateWatchedFolder(path
, options
);
339 addWatchedFolder(path
, options
);
342 void TorrentFilesWatcher::Worker::removeWatchedFolder(const Path
&path
)
344 m_watchedFolders
.remove(path
);
346 m_watcher
->removePath(path
.data());
347 m_watchedByTimeoutFolders
.remove(path
);
348 if (m_watchedByTimeoutFolders
.isEmpty())
349 m_watchTimer
->stop();
351 m_failedTorrents
.remove(path
);
352 if (m_failedTorrents
.isEmpty())
353 m_retryTorrentTimer
->stop();
356 void TorrentFilesWatcher::Worker::scheduleWatchedFolderProcessing(const Path
&path
)
358 QTimer::singleShot(2s
, Qt::CoarseTimer
, this, [this, path
]
360 processWatchedFolder(path
);
364 void TorrentFilesWatcher::Worker::processWatchedFolder(const Path
&path
)
366 const TorrentFilesWatcher::WatchedFolderOptions options
= m_watchedFolders
.value(path
);
367 processFolder(path
, path
, options
);
369 if (!m_failedTorrents
.empty() && !m_retryTorrentTimer
->isActive())
370 m_retryTorrentTimer
->start(WATCH_INTERVAL
);
373 void TorrentFilesWatcher::Worker::processFolder(const Path
&path
, const Path
&watchedFolderPath
374 , const TorrentFilesWatcher::WatchedFolderOptions
&options
)
376 QDirIterator dirIter
{path
.data(), {u
"*.torrent"_s
, u
"*.magnet"_s
}, QDir::Files
};
377 while (dirIter
.hasNext())
379 const Path filePath
{dirIter
.next()};
380 BitTorrent::AddTorrentParams addTorrentParams
= options
.addTorrentParams
;
381 if (path
!= watchedFolderPath
)
383 const Path subdirPath
= watchedFolderPath
.relativePathOf(path
);
384 const bool useAutoTMM
= addTorrentParams
.useAutoTMM
.value_or(!BitTorrent::Session::instance()->isAutoTMMDisabledByDefault());
387 addTorrentParams
.category
= addTorrentParams
.category
.isEmpty()
388 ? subdirPath
.data() : (addTorrentParams
.category
+ u
'/' + subdirPath
.data());
392 addTorrentParams
.savePath
= addTorrentParams
.savePath
/ subdirPath
;
396 if (filePath
.hasExtension(u
".magnet"_s
))
398 const int fileMaxSize
= 100 * 1024 * 1024;
400 QFile file
{filePath
.data()};
401 if (file
.open(QIODevice::ReadOnly
| QIODevice::Text
))
403 if (file
.size() <= fileMaxSize
)
405 while (!file
.atEnd())
407 const auto line
= QString::fromLatin1(file
.readLine()).trimmed();
408 if (const auto parseResult
= BitTorrent::TorrentDescriptor::parse(line
))
409 emit
torrentFound(parseResult
.value(), addTorrentParams
);
411 LogMsg(tr("Invalid Magnet URI. URI: %1. Reason: %2").arg(line
, parseResult
.error()), Log::WARNING
);
415 Utils::Fs::removeFile(filePath
);
419 LogMsg(tr("Magnet file too big. File: %1").arg(file
.errorString()), Log::WARNING
);
424 LogMsg(tr("Failed to open magnet file: %1").arg(file
.errorString()));
429 if (const auto loadResult
= BitTorrent::TorrentDescriptor::loadFromFile(filePath
))
431 emit
torrentFound(loadResult
.value(), addTorrentParams
);
432 Utils::Fs::removeFile(filePath
);
436 if (!m_failedTorrents
.value(path
).contains(filePath
))
438 m_failedTorrents
[path
][filePath
] = 0;
444 if (options
.recursive
)
446 QDirIterator iter
{path
.data(), (QDir::Dirs
| QDir::NoDotAndDotDot
)};
447 while (iter
.hasNext())
449 const Path folderPath
{iter
.next()};
450 // Skip processing of subdirectory that is explicitly set as watched folder
451 if (!m_watchedFolders
.contains(folderPath
))
452 processFolder(folderPath
, watchedFolderPath
, options
);
457 void TorrentFilesWatcher::Worker::processFailedTorrents()
459 // Check which torrents are still partial
460 Algorithm::removeIf(m_failedTorrents
, [this](const Path
&watchedFolderPath
, QHash
<Path
, int> &partialTorrents
)
462 const TorrentFilesWatcher::WatchedFolderOptions options
= m_watchedFolders
.value(watchedFolderPath
);
463 Algorithm::removeIf(partialTorrents
, [this, &watchedFolderPath
, &options
](const Path
&torrentPath
, int &value
)
465 if (!torrentPath
.exists())
468 if (const auto loadResult
= BitTorrent::TorrentDescriptor::loadFromFile(torrentPath
))
470 BitTorrent::AddTorrentParams addTorrentParams
= options
.addTorrentParams
;
471 if (torrentPath
!= watchedFolderPath
)
473 const Path subdirPath
= watchedFolderPath
.relativePathOf(torrentPath
);
474 const bool useAutoTMM
= addTorrentParams
.useAutoTMM
.value_or(!BitTorrent::Session::instance()->isAutoTMMDisabledByDefault());
477 addTorrentParams
.category
= addTorrentParams
.category
.isEmpty()
478 ? subdirPath
.data() : (addTorrentParams
.category
+ u
'/' + subdirPath
.data());
482 addTorrentParams
.savePath
= addTorrentParams
.savePath
/ subdirPath
;
486 emit
torrentFound(loadResult
.value(), addTorrentParams
);
487 Utils::Fs::removeFile(torrentPath
);
492 if (value
>= MAX_FAILED_RETRIES
)
494 LogMsg(tr("Rejecting failed torrent file: %1").arg(torrentPath
.toString()));
495 Utils::Fs::renameFile(torrentPath
, (torrentPath
+ u
".qbt_rejected"));
503 if (partialTorrents
.isEmpty())
509 // Stop the partial timer if necessary
510 if (m_failedTorrents
.empty())
511 m_retryTorrentTimer
->stop();
513 m_retryTorrentTimer
->start(WATCH_INTERVAL
);
516 void TorrentFilesWatcher::Worker::addWatchedFolder(const Path
&path
, const TorrentFilesWatcher::WatchedFolderOptions
&options
)
518 // Check if the `path` points to a network file system or not
519 if (Utils::Fs::isNetworkFileSystem(path
) || options
.recursive
)
521 m_watchedByTimeoutFolders
.insert(path
);
522 if (!m_watchTimer
->isActive())
523 m_watchTimer
->start(WATCH_INTERVAL
);
527 m_watcher
->addPath(path
.data());
528 scheduleWatchedFolderProcessing(path
);
531 m_watchedFolders
[path
] = options
;
533 LogMsg(tr("Watching folder: \"%1\"").arg(path
.toString()));
536 void TorrentFilesWatcher::Worker::updateWatchedFolder(const Path
&path
, const TorrentFilesWatcher::WatchedFolderOptions
&options
)
538 const bool recursiveModeChanged
= (m_watchedFolders
[path
].recursive
!= options
.recursive
);
539 if (recursiveModeChanged
&& !Utils::Fs::isNetworkFileSystem(path
))
541 if (options
.recursive
)
543 m_watcher
->removePath(path
.data());
545 m_watchedByTimeoutFolders
.insert(path
);
546 if (!m_watchTimer
->isActive())
547 m_watchTimer
->start(WATCH_INTERVAL
);
551 m_watchedByTimeoutFolders
.remove(path
);
552 if (m_watchedByTimeoutFolders
.isEmpty())
553 m_watchTimer
->stop();
555 m_watcher
->addPath(path
.data());
556 scheduleWatchedFolderProcessing(path
);
560 m_watchedFolders
[path
] = options
;
563 #include "torrentfileswatcher.moc"