Bump to 4.5.0alpha1
[qBittorrent.git] / src / base / search / searchhandler.cpp
blob7aec0d84d8ec2c0ad6d03b369ff00543b1fd63d5
1 /*
2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2015, 2018 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.
30 #include "searchhandler.h"
32 #include <QProcess>
33 #include <QTimer>
34 #include <QVector>
36 #include "base/global.h"
37 #include "base/utils/foreignapps.h"
38 #include "base/utils/fs.h"
39 #include "searchpluginmanager.h"
41 namespace
43 enum SearchResultColumn
45 PL_DL_LINK,
46 PL_NAME,
47 PL_SIZE,
48 PL_SEEDS,
49 PL_LEECHS,
50 PL_ENGINE_URL,
51 PL_DESC_LINK,
52 NB_PLUGIN_COLUMNS
56 SearchHandler::SearchHandler(const QString &pattern, const QString &category, const QStringList &usedPlugins, SearchPluginManager *manager)
57 : QObject {manager}
58 , m_pattern {pattern}
59 , m_category {category}
60 , m_usedPlugins {usedPlugins}
61 , m_manager {manager}
62 , m_searchProcess {new QProcess {this}}
63 , m_searchTimeout {new QTimer {this}}
65 // Load environment variables (proxy)
66 m_searchProcess->setEnvironment(QProcess::systemEnvironment());
68 const QStringList params
70 Utils::Fs::toNativePath(m_manager->engineLocation() + "/nova2.py"),
71 m_usedPlugins.join(','),
72 m_category
75 // Launch search
76 m_searchProcess->setProgram(Utils::ForeignApps::pythonInfo().executableName);
77 m_searchProcess->setArguments(params + m_pattern.split(' '));
79 connect(m_searchProcess, &QProcess::errorOccurred, this, &SearchHandler::processFailed);
80 connect(m_searchProcess, &QProcess::readyReadStandardOutput, this, &SearchHandler::readSearchOutput);
81 connect(m_searchProcess, qOverload<int, QProcess::ExitStatus>(&QProcess::finished)
82 , this, &SearchHandler::processFinished);
84 m_searchTimeout->setSingleShot(true);
85 connect(m_searchTimeout, &QTimer::timeout, this, &SearchHandler::cancelSearch);
86 m_searchTimeout->start(180000); // 3 min
88 // deferred start allows clients to handle starting-related signals
89 QTimer::singleShot(0, this, [this]() { m_searchProcess->start(QIODevice::ReadOnly); });
92 bool SearchHandler::isActive() const
94 return (m_searchProcess->state() != QProcess::NotRunning);
97 void SearchHandler::cancelSearch()
99 if ((m_searchProcess->state() == QProcess::NotRunning) || m_searchCancelled)
100 return;
102 #ifdef Q_OS_WIN
103 m_searchProcess->kill();
104 #else
105 m_searchProcess->terminate();
106 #endif
107 m_searchCancelled = true;
108 m_searchTimeout->stop();
111 // Slot called when QProcess is Finished
112 // QProcess can be finished for 3 reasons:
113 // Error | Stopped by user | Finished normally
114 void SearchHandler::processFinished(const int exitcode)
116 m_searchTimeout->stop();
118 if (m_searchCancelled)
119 emit searchFinished(true);
120 else if ((m_searchProcess->exitStatus() == QProcess::NormalExit) && (exitcode == 0))
121 emit searchFinished(false);
122 else
123 emit searchFailed();
126 // search QProcess return output as soon as it gets new
127 // stuff to read. We split it into lines and parse each
128 // line to SearchResult calling parseSearchResult().
129 void SearchHandler::readSearchOutput()
131 QByteArray output = m_searchProcess->readAllStandardOutput();
132 output.replace('\r', "");
134 QList<QByteArray> lines = output.split('\n');
135 if (!m_searchResultLineTruncated.isEmpty())
136 lines.prepend(m_searchResultLineTruncated + lines.takeFirst());
137 m_searchResultLineTruncated = lines.takeLast().trimmed();
139 QVector<SearchResult> searchResultList;
140 searchResultList.reserve(lines.size());
142 for (const QByteArray &line : asConst(lines))
144 SearchResult searchResult;
145 if (parseSearchResult(QString::fromUtf8(line), searchResult))
146 searchResultList << searchResult;
149 if (!searchResultList.isEmpty())
151 for (const SearchResult &result : searchResultList)
152 m_results.append(result);
153 emit newSearchResults(searchResultList);
157 void SearchHandler::processFailed()
159 if (!m_searchCancelled)
160 emit searchFailed();
163 // Parse one line of search results list
164 // Line is in the following form:
165 // file url | file name | file size | nb seeds | nb leechers | Search engine url
166 bool SearchHandler::parseSearchResult(const QStringView line, SearchResult &searchResult)
168 const QList<QStringView> parts = line.split(u'|');
169 const int nbFields = parts.size();
171 if (nbFields < (NB_PLUGIN_COLUMNS - 1)) return false; // -1 because desc_link is optional
173 searchResult = SearchResult();
174 searchResult.fileUrl = parts.at(PL_DL_LINK).trimmed().toString(); // download URL
175 searchResult.fileName = parts.at(PL_NAME).trimmed().toString(); // Name
176 searchResult.fileSize = parts.at(PL_SIZE).trimmed().toLongLong(); // Size
178 bool ok = false;
180 searchResult.nbSeeders = parts.at(PL_SEEDS).trimmed().toLongLong(&ok); // Seeders
181 if (!ok || (searchResult.nbSeeders < 0))
182 searchResult.nbSeeders = -1;
184 searchResult.nbLeechers = parts.at(PL_LEECHS).trimmed().toLongLong(&ok); // Leechers
185 if (!ok || (searchResult.nbLeechers < 0))
186 searchResult.nbLeechers = -1;
188 searchResult.siteUrl = parts.at(PL_ENGINE_URL).trimmed().toString(); // Search site URL
189 if (nbFields == NB_PLUGIN_COLUMNS)
190 searchResult.descrLink = parts.at(PL_DESC_LINK).trimmed().toString(); // Description Link
192 return true;
195 SearchPluginManager *SearchHandler::manager() const
197 return m_manager;
200 QList<SearchResult> SearchHandler::results() const
202 return m_results;
205 QString SearchHandler::pattern() const
207 return m_pattern;