Debian Codegraph @

src/librssguard/miscellaneous/systemfactory.cpp

raw symbols SCIP
1 // For license of this file, see <project-root-folder>/LICENSE.md.
2
3 #include "miscellaneous/systemfactory.h"
4
5 #include "3rd-party/boolinq/boolinq.h"
6 #include "exceptions/applicationexception.h"
7 #include "gui/dialogs/formmain.h"
8 #include "gui/dialogs/formupdate.h"
9 #include "miscellaneous/application.h"
10 #include "miscellaneous/settings.h"
11 #include "miscellaneous/systemfactory.h"
12
13 #if defined(Q_OS_WIN)
14 #include <QSettings>
15 #endif
16
17 #include <QDesktopServices>
18 #include <QDir>
19 #include <QFile>
20 #include <QFileInfo>
21 #include <QJsonArray>
22 #include <QJsonDocument>
23 #include <QJsonObject>
24 #include <QProcess>
25 #include <QString>
26 #include <QVersionNumber>
27
28 using UpdateCheck = QPair<UpdateInfo, QNetworkReply::NetworkError>;
29
30 SystemFactory::SystemFactory(QObject* parent) : QObject(parent) {}
31
32 SystemFactory::~SystemFactory() = default;
33
34 QRegularExpression SystemFactory::supportedUpdateFiles() {
35 #if defined(Q_OS_WIN)
36 return QRegularExpression(QSL(".+win.+\\.(exe|7z)"));
37 #elif defined(Q_OS_MACOS)
38 return QRegularExpression(QSL(".dmg"));
39 #elif defined(Q_OS_LINUX)
40 return QRegularExpression(QSL(".AppImage"));
41 #else
42 return QRegularExpression(QSL(".*"));
43 #endif
44 }
45
46 SystemFactory::AutoStartStatus SystemFactory::autoStartStatus() const {
47 // User registry way to auto-start the application on Windows.
48 #if defined(Q_OS_WIN)
49 QSettings registry_key(QSL("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"),
50 QSettings::Format::NativeFormat);
51 const bool autostart_enabled = registry_key.contains(QSL(APP_LOW_NAME));
52
53 if (autostart_enabled) {
54 return AutoStartStatus::Enabled;
55 }
56 else {
57 return AutoStartStatus::Disabled;
58 }
59 #elif defined(Q_OS_UNIX) && !defined(Q_OS_MACOS)
60 // Use proper freedesktop.org way to auto-start the application.
61 // INFO: http://standards.freedesktop.org/autostart-spec/latest/
62 const QString desktop_file_location = autostartDesktopFileLocation();
63
64 // No correct path was found.
65 if (desktop_file_location.isEmpty()) {
66 qWarningNN << LOGSEC_GUI << "Searching for auto-start function status failed. HOME variable not found.";
67 return AutoStartStatus::Unavailable;
68 }
69
70 // We found correct path, now check if file exists and return correct status.
71 if (QFile::exists(desktop_file_location)) {
72 // File exists, we must read it and check if "Hidden" attribute is defined and what is its value.
73 QSettings desktop_settings(desktop_file_location, QSettings::IniFormat);
74 bool hidden_value = desktop_settings.value(QSL("Desktop Entry/Hidden"), false).toBool();
75
76 return hidden_value ? AutoStartStatus::Disabled : AutoStartStatus::Enabled;
77 }
78 else {
79 return AutoStartStatus::Disabled;
80 }
81 #else
82 // Disable auto-start functionality on unsupported platforms.
83 return AutoStartStatus::Unavailable;
84 #endif
85 }
86
87 #if defined(Q_OS_UNIX) && !defined(Q_OS_MACOS)
88 QString SystemFactory::autostartDesktopFileLocation() const {
89 const QString xdg_config_path(qgetenv("XDG_CONFIG_HOME"));
90 QString desktop_file_location;
91
92 if (!xdg_config_path.isEmpty()) {
93 // XDG_CONFIG_HOME variable is specified. Look for .desktop file
94 // in 'autostart' subdirectory.
95 desktop_file_location = xdg_config_path + QSL("/autostart/") + APP_REVERSE_NAME + QSL(".desktop");
96 }
97 else {
98 // Desired variable is not set, look for the default 'autostart' subdirectory.
99 const QString home_directory(qgetenv("HOME"));
100
101 if (!home_directory.isEmpty()) {
102 // Home directory exists. Check if target .desktop file exists and
103 // return according status.
104 desktop_file_location = home_directory + QSL("/.config/autostart/") + APP_REVERSE_NAME + QSL(".desktop");
105 }
106 }
107
108 return desktop_file_location;
109 }
110
111 #endif
112
113 bool SystemFactory::setAutoStartStatus(AutoStartStatus new_status) {
114 const SystemFactory::AutoStartStatus current_status = SystemFactory::autoStartStatus();
115
116 // Auto-start feature is not even available, exit.
117 if (current_status == AutoStartStatus::Unavailable) {
118 return false;
119 }
120
121 #if defined(Q_OS_WIN)
122 QSettings registry_key(QSL("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"),
123 QSettings::Format::NativeFormat);
124
125 switch (new_status) {
126 case AutoStartStatus::Enabled: {
127 QStringList args = qApp->rawCliArgs();
128 auto std_args = boolinq::from(args.begin(), args.end())
129 .select([](const QString& arg) {
130 if (arg.contains(QL1S(" ")) && !arg.startsWith(QL1S("\""))) {
131 return QSL("\"%1\"").arg(arg);
132 }
133 else {
134 return arg;
135 }
136 })
137 .toStdList();
138 args = FROM_STD_LIST(QStringList, std_args);
139
140 QString app_run_line = args.join(QL1C(' '));
141 registry_key.setValue(QSL(APP_LOW_NAME), app_run_line);
142 return true;
143 }
144
145 case AutoStartStatus::Disabled:
146 registry_key.remove(QSL(APP_LOW_NAME));
147 return true;
148
149 default:
150 return false;
151 }
152 #elif defined(Q_OS_UNIX) && !defined(Q_OS_MACOS)
153 // Note that we expect here that no other program uses
154 // "rssguard.desktop" desktop file.
155 const QString destination_file = autostartDesktopFileLocation();
156 const QString destination_folder = QFileInfo(destination_file).absolutePath();
157
158 switch (new_status) {
159 case AutoStartStatus::Enabled: {
160 if (QFile::exists(destination_file)) {
161 if (!QFile::remove(destination_file)) {
162 return false;
163 }
164 }
165
166 if (!QDir().mkpath(destination_folder)) {
167 return false;
168 }
169
170 const QString source_autostart_desktop_file =
171 QString(APP_DESKTOP_ENTRY_PATH) + QDir::separator() + APP_DESKTOP_ENTRY_FILE;
172
173 try {
174 QString desktop_file_contents = QString::fromUtf8(IOFactory::readFile(source_autostart_desktop_file));
175
176 QStringList args = qApp->rawCliArgs();
177 auto std_args = boolinq::from(args.begin(), args.end())
178 .select([](const QString& arg) {
179 if (arg.contains(QL1S(" ")) && !arg.startsWith(QL1S("\""))) {
180 return QSL("\"%1\"").arg(arg);
181 }
182 else {
183 return arg;
184 }
185 })
186 .toStdList();
187 args = FROM_STD_LIST(QStringList, std_args);
188
189 #if defined(IS_FLATPAK_BUILD)
190 const QString flatpak_run = QSL("flatpak run %1").arg(APP_REVERSE_NAME);
191
192 args = args.mid(1);
193 args.prepend(flatpak_run);
194 #endif
195
196 desktop_file_contents.replace("Exec=@APP_LOW_NAME@", QSL("Exec=") + args.join(QL1C(' ')));
197 desktop_file_contents.replace("@APPDATA_SUMMARY@", APPDATA_SUMMARY);
198 desktop_file_contents.replace("@APPDATA_NAME@", APPDATA_NAME);
199 desktop_file_contents.replace("@APP_REVERSE_NAME@", APP_REVERSE_NAME);
200 desktop_file_contents.replace("@APP_LOW_NAME@", APP_LOW_NAME);
201
202 IOFactory::writeFile(destination_file, desktop_file_contents.toUtf8());
203 }
204 catch (const ApplicationException& ex) {
205 return false;
206 }
207
208 return true;
209 }
210
211 case AutoStartStatus::Disabled:
212 return QFile::remove(destination_file);
213
214 default:
215 return false;
216 }
217 #else
218 return false;
219 #endif
220 }
221
222 QString SystemFactory::loggedInUser() const {
223 QString name = qEnvironmentVariable("USER");
224
225 if (name.isEmpty()) {
226 name = qEnvironmentVariable("USERNAME");
227 }
228
229 if (name.isEmpty()) {
230 name = tr("anonymous");
231 }
232
233 return name;
234 }
235
236 void SystemFactory::checkForUpdates() const {
237 auto* downloader = new Downloader();
238
239 connect(downloader, &Downloader::completed, this, [this, downloader]() {
240 QPair<QList<UpdateInfo>, QNetworkReply::NetworkError> result;
241 result.second = downloader->lastOutputError();
242
243 if (result.second == QNetworkReply::NoError) {
244 QByteArray obtained_data = downloader->lastOutputData();
245 result.first = parseUpdatesFile(obtained_data);
246 }
247
248 emit updatesChecked(result);
249 downloader->deleteLater();
250 });
251 downloader->downloadFile(QSL(RELEASES_LIST));
252 }
253
254 void SystemFactory::checkForUpdatesOnStartup() {
255 #if !defined(NO_UPDATE_CHECK)
256 if (qApp->settings()->value(GROUP(General), SETTING(General::UpdateOnStartup)).toBool()) {
257 QObject::connect(qApp->system(),
258 &SystemFactory::updatesChecked,
259 this,
260 [&](const QPair<QList<UpdateInfo>, QNetworkReply::NetworkError>& updates) {
261 QObject::disconnect(qApp->system(), &SystemFactory::updatesChecked, this, nullptr);
262
263 if (!updates.first.isEmpty() && updates.second == QNetworkReply::NetworkError::NoError &&
264 SystemFactory::isVersionNewer(updates.first.at(0).m_availableVersion, QSL(APP_VERSION))) {
265 qApp->showGuiMessage(Notification::Event::NewAppVersionAvailable,
266 {QObject::tr("New version available"),
267 QObject::tr("Click the bubble for more information."),
268 QSystemTrayIcon::Information},
269 {},
270 {tr("See new version info"), [] {
271 FormUpdate(qApp->mainForm()).exec();
272 }});
273 }
274 });
275 checkForUpdates();
276 }
277 #endif
278 }
279
280 bool SystemFactory::isVersionNewer(const QString& new_version, const QString& base_version) {
281 QVersionNumber nw = QVersionNumber::fromString(new_version);
282 QVersionNumber bs = QVersionNumber::fromString(base_version);
283
284 return nw > bs;
285 }
286
287 bool SystemFactory::isVersionEqualOrNewer(const QString& new_version, const QString& base_version) {
288 return new_version == base_version || isVersionNewer(new_version, base_version);
289 }
290
291 bool SystemFactory::openFolderFile(const QString& file_path) {
292 #if defined(Q_OS_WIN)
293 return QProcess::startDetached(QSL("explorer.exe"), {"/select,", QDir::toNativeSeparators(file_path)});
294 #else
295 const QString folder = QDir::toNativeSeparators(QFileInfo(file_path).absoluteDir().absolutePath());
296
297 return QDesktopServices::openUrl(QUrl::fromLocalFile(folder));
298 #endif
299 }
300
301 QList<UpdateInfo> SystemFactory::parseUpdatesFile(const QByteArray& updates_file) const {
302 QList<UpdateInfo> updates;
303 QJsonArray document = QJsonDocument::fromJson(updates_file).array();
304
305 for (QJsonValueRef i : document) {
306 QJsonObject release = i.toObject();
307
308 if (release[QSL("tag_name")].toString() == QSL("devbuild")) {
309 continue;
310 }
311
312 UpdateInfo update;
313
314 update.m_availableVersion = release[QSL("tag_name")].toString();
315 update.m_date = QDateTime::fromString(release[QSL("published_at")].toString(), QSL("yyyy-MM-ddTHH:mm:ssZ"));
316 update.m_changes = release[QSL("body")].toString();
317 QJsonArray assets = release[QSL("assets")].toArray();
318
319 for (QJsonValueRef j : assets) {
320 QJsonObject asset = j.toObject();
321 UpdateUrl url;
322
323 url.m_fileUrl = asset[QSL("browser_download_url")].toString();
324 url.m_name = asset[QSL("name")].toString();
325 url.m_size = asset[QSL("size")].toVariant().toString() + tr(" bytes");
326 update.m_urls.append(url);
327 }
328
329 updates.append(update);
330 }
331
332 std::sort(updates.begin(), updates.end(), [](const UpdateInfo& a, const UpdateInfo& b) -> bool {
333 return a.m_date > b.m_date;
334 });
335 return updates;
336 }