Don't add duplicate episodes to previously matched
[qBittorrent.git] / src / base / settingsstorage.cpp
blob9f19f089162724752bb5b952523a16c2b38cab47
1 /*
2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2016 Vladimir Golovnev <glassez@yandex.ru>
4 * Copyright (C) 2014 sledgehammer999 <hammered999@gmail.com>
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 "settingsstorage.h"
32 #include <chrono>
33 #include <memory>
35 #include <QFile>
36 #include <QHash>
38 #include "global.h"
39 #include "logger.h"
40 #include "path.h"
41 #include "profile.h"
42 #include "utils/fs.h"
44 using namespace std::chrono_literals;
46 SettingsStorage *SettingsStorage::m_instance = nullptr;
48 SettingsStorage::SettingsStorage()
49 : m_nativeSettingsName {u"qBittorrent"_s}
51 readNativeSettings();
53 m_timer.setSingleShot(true);
54 m_timer.setInterval(5s);
55 connect(&m_timer, &QTimer::timeout, this, &SettingsStorage::save);
58 SettingsStorage::~SettingsStorage()
60 save();
63 void SettingsStorage::initInstance()
65 if (!m_instance)
66 m_instance = new SettingsStorage;
69 void SettingsStorage::freeInstance()
71 delete m_instance;
72 m_instance = nullptr;
75 SettingsStorage *SettingsStorage::instance()
77 return m_instance;
80 bool SettingsStorage::save()
82 // return `true` only when settings is different AND is saved successfully
84 const QWriteLocker locker(&m_lock); // guard for `m_dirty` too
85 if (!m_dirty) return false;
87 if (!writeNativeSettings())
89 m_timer.start();
90 return false;
93 m_dirty = false;
94 return true;
97 QVariant SettingsStorage::loadValueImpl(const QString &key, const QVariant &defaultValue) const
99 const QReadLocker locker(&m_lock);
100 return m_data.value(key, defaultValue);
103 void SettingsStorage::storeValueImpl(const QString &key, const QVariant &value)
105 const QWriteLocker locker(&m_lock);
106 QVariant &currentValue = m_data[key];
107 if (currentValue != value)
109 m_dirty = true;
110 currentValue = value;
111 m_timer.start();
115 void SettingsStorage::readNativeSettings()
117 // We return actual file names used by QSettings because
118 // there is no other way to get that name except actually create a QSettings object.
119 // If serialization operation was not successful we return empty string.
120 const auto deserialize = [](QVariantHash &data, const QString &nativeSettingsName) -> Path
122 std::unique_ptr<QSettings> nativeSettings = Profile::instance()->applicationSettings(nativeSettingsName);
123 if (nativeSettings->allKeys().isEmpty())
124 return {};
126 // Copy everything into memory. This means even keys inserted in the file manually
127 // or that we don't touch directly in this code (eg disabled by ifdef). This ensures
128 // that they will be copied over when save our settings to disk.
129 for (const QString &key : asConst(nativeSettings->allKeys()))
131 const QVariant value = nativeSettings->value(key);
132 if (value.isValid())
133 data[key] = value;
136 return Path(nativeSettings->fileName());
139 const Path newPath = deserialize(m_data, (m_nativeSettingsName + u"_new"));
140 if (!newPath.isEmpty())
142 // "_new" file is NOT empty
143 // This means that the PC closed either due to power outage
144 // or because the disk was full. In any case the settings weren't transferred
145 // in their final position. So assume that qbittorrent_new.ini/qbittorrent_new.conf
146 // contains the most recent settings.
147 LogMsg(tr("Detected unclean program exit. Using fallback file to restore settings: %1")
148 .arg(newPath.toString()), Log::WARNING);
150 QString finalPathStr = newPath.data();
151 const int index = finalPathStr.lastIndexOf(u"_new", -1, Qt::CaseInsensitive);
152 finalPathStr.remove(index, 4);
154 const Path finalPath {finalPathStr};
155 Utils::Fs::removeFile(finalPath);
156 Utils::Fs::renameFile(newPath, finalPath);
158 else
160 deserialize(m_data, m_nativeSettingsName);
164 bool SettingsStorage::writeNativeSettings() const
166 std::unique_ptr<QSettings> nativeSettings = Profile::instance()->applicationSettings(m_nativeSettingsName + u"_new");
168 // QSettings deletes the file before writing it out. This can result in problems
169 // if the disk is full or a power outage occurs. Those events might occur
170 // between deleting the file and recreating it. This is a safety measure.
171 // Write everything to qBittorrent_new.ini/qBittorrent_new.conf and if it succeeds
172 // replace qBittorrent.ini/qBittorrent.conf with it.
173 for (auto i = m_data.begin(); i != m_data.end(); ++i)
174 nativeSettings->setValue(i.key(), i.value());
176 nativeSettings->sync(); // Important to get error status
177 const QSettings::Status status = nativeSettings->status();
178 const Path newPath {nativeSettings->fileName()};
180 nativeSettings.reset(); // close QSettings
182 switch (status)
184 case QSettings::NoError:
185 break;
186 case QSettings::AccessError:
187 LogMsg(tr("An access error occurred while trying to write the configuration file."), Log::CRITICAL);
188 break;
189 case QSettings::FormatError:
190 LogMsg(tr("A format error occurred while trying to write the configuration file."), Log::CRITICAL);
191 break;
192 default:
193 LogMsg(tr("An unknown error occurred while trying to write the configuration file."), Log::CRITICAL);
194 break;
197 if (status != QSettings::NoError)
199 Utils::Fs::removeFile(newPath);
200 return false;
203 QString finalPathStr = newPath.data();
204 const int index = finalPathStr.lastIndexOf(u"_new", -1, Qt::CaseInsensitive);
205 finalPathStr.remove(index, 4);
207 const Path finalPath {finalPathStr};
208 Utils::Fs::removeFile(finalPath);
209 return Utils::Fs::renameFile(newPath, finalPath);
212 void SettingsStorage::removeValue(const QString &key)
214 const QWriteLocker locker(&m_lock);
215 if (m_data.remove(key))
217 m_dirty = true;
218 m_timer.start();
222 bool SettingsStorage::hasKey(const QString &key) const
224 const QReadLocker locker {&m_lock};
225 return m_data.contains(key);
228 bool SettingsStorage::isEmpty() const
230 const QReadLocker locker {&m_lock};
231 return m_data.isEmpty();