summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorSilarn <jrim@rimpo.org>2019-01-27 17:08:42 -0600
committerSilarn <jrim@rimpo.org>2019-02-18 21:28:04 -0600
commit4bea346b26f2e34120a42fdf2f1c5485ab93f5c9 (patch)
tree110d43c989ef068117298aeef929a2500de02075 /src
parent7de78b6697b60ac20add32b5b9140b04da973be8 (diff)
Reworking update checks to use the file update info with a fallback
Diffstat (limited to 'src')
-rw-r--r--src/downloadmanager.cpp3673
-rw-r--r--src/downloadmanager.h1132
-rw-r--r--src/mainwindow.cpp145
-rw-r--r--src/mainwindow.h5
-rw-r--r--src/modinfo.cpp41
-rw-r--r--src/modinfobackup.h1
-rw-r--r--src/modinfodialog.cpp3154
-rw-r--r--src/modinfoforeign.h1
-rw-r--r--src/modinfooverwrite.h1
-rw-r--r--src/modinforegular.cpp14
-rw-r--r--src/modinforegular.h2
-rw-r--r--src/modinfoseparator.h18
-rw-r--r--src/nexusinterface.cpp1444
-rw-r--r--src/nexusinterface.h847
-rw-r--r--src/organizer_en.ts426
15 files changed, 5453 insertions, 5451 deletions
diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp
index c927695e..8f36b9cf 100644
--- a/src/downloadmanager.cpp
+++ b/src/downloadmanager.cpp
@@ -1,1842 +1,1831 @@
-/*
-Copyright (C) 2012 Sebastian Herbord. All rights reserved.
-
-This file is part of Mod Organizer.
-
-Mod Organizer is free software: you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-Mod Organizer is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with Mod Organizer. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#include "downloadmanager.h"
-
-#include "nxmurl.h"
-#include "nexusinterface.h"
-#include "nxmaccessmanager.h"
-#include "iplugingame.h"
-#include "downloadmanager.h"
-#include <nxmurl.h>
-#include <taskprogressmanager.h>
-#include "utility.h"
-#include "selectiondialog.h"
-#include "bbcode.h"
-#include <utility.h>
-#include <report.h>
-
-#include <QTimer>
-#include <QFileInfo>
-#include <QRegExp>
-#include <QDirIterator>
-#include <QDesktopServices>
-#include <QInputDialog>
-#include <QMessageBox>
-#include <QCoreApplication>
-#include <QTextDocument>
-
-#include <boost/bind.hpp>
-#include <regex>
-
-
-using namespace MOBase;
-
-
-// TODO limit number of downloads, also display download during nxm requests, store modid/fileid with downloads
-
-
-static const char UNFINISHED[] = ".unfinished";
-
-unsigned int DownloadManager::DownloadInfo::s_NextDownloadID = 1U;
-int DownloadManager::m_DirWatcherDisabler = 0;
-
-
-DownloadManager::DownloadInfo *DownloadManager::DownloadInfo::createNew(const ModRepositoryFileInfo *fileInfo, const QStringList &URLs)
-{
- DownloadInfo *info = new DownloadInfo;
- info->m_DownloadID = s_NextDownloadID++;
- info->m_StartTime.start();
- info->m_PreResumeSize = 0LL;
- info->m_Progress = std::make_pair<int, QString>(0, "0.0 B/s ");
- info->m_ResumePos = 0;
- info->m_FileInfo = new ModRepositoryFileInfo(*fileInfo);
- info->m_Urls = URLs;
- info->m_CurrentUrl = 0;
- info->m_Tries = AUTOMATIC_RETRIES;
- info->m_State = STATE_STARTED;
- info->m_TaskProgressId = TaskProgressManager::instance().getId();
- info->m_Reply = nullptr;
-
- return info;
-}
-
-DownloadManager::DownloadInfo *DownloadManager::DownloadInfo::createFromMeta(const QString &filePath, bool showHidden, const QString outputDirectory)
-{
- DownloadInfo *info = new DownloadInfo;
-
- QString metaFileName = filePath + ".meta";
- QFileInfo metaFileInfo(metaFileName);
- if (QDir::fromNativeSeparators(metaFileInfo.path()).compare(QDir::fromNativeSeparators(outputDirectory), Qt::CaseInsensitive) != 0) return nullptr;
- QSettings metaFile(metaFileName, QSettings::IniFormat);
- if (!showHidden && metaFile.value("removed", false).toBool()) {
- return nullptr;
- } else {
- info->m_Hidden = metaFile.value("removed", false).toBool();
- }
-
- QString fileName = QFileInfo(filePath).fileName();
-
- if (fileName.endsWith(UNFINISHED)) {
- info->m_FileName = fileName.mid(
- 0, fileName.length() - static_cast<int>(strlen(UNFINISHED)));
- info->m_State = STATE_PAUSED;
- } else {
- info->m_FileName = fileName;
-
- if (metaFile.value("paused", false).toBool()) {
- info->m_State = STATE_PAUSED;
- } else if (metaFile.value("uninstalled", false).toBool()) {
- info->m_State = STATE_UNINSTALLED;
- } else if (metaFile.value("installed", false).toBool()) {
- info->m_State = STATE_INSTALLED;
- } else {
- info->m_State = STATE_READY;
- }
- }
-
- info->m_DownloadID = s_NextDownloadID++;
- info->m_Output.setFileName(filePath);
- info->m_TotalSize = QFileInfo(filePath).size();
- info->m_PreResumeSize = info->m_TotalSize;
- info->m_CurrentUrl = 0;
- info->m_Urls = metaFile.value("url", "").toString().split(";");
- info->m_Tries = 0;
- info->m_TaskProgressId = TaskProgressManager::instance().getId();
- QString gameName = metaFile.value("gameName", "").toString();
- int modID = metaFile.value("modID", 0).toInt();
- int fileID = metaFile.value("fileID", 0).toInt();
- info->m_FileInfo = new ModRepositoryFileInfo(gameName, modID, fileID);
- info->m_FileInfo->name = metaFile.value("name", "").toString();
- if (info->m_FileInfo->name == "0") {
- // bug in earlier version
- info->m_FileInfo->name = "";
- }
- info->m_FileInfo->modName = metaFile.value("modName", "").toString();
- info->m_FileInfo->gameName = gameName;
- info->m_FileInfo->modID = modID;
- info->m_FileInfo->fileID = fileID;
- info->m_FileInfo->description = metaFile.value("description").toString();
- info->m_FileInfo->version.parse(metaFile.value("version", "0").toString());
- info->m_FileInfo->newestVersion.parse(metaFile.value("newestVersion", "0").toString());
- info->m_FileInfo->categoryID = metaFile.value("category", 0).toInt();
- info->m_FileInfo->fileCategory = metaFile.value("fileCategory", 0).toInt();
- info->m_FileInfo->repository = metaFile.value("repository", "Nexus").toString();
- info->m_FileInfo->userData = metaFile.value("userData").toMap();
- info->m_Reply = nullptr;
-
- return info;
-}
-
-void DownloadManager::startDisableDirWatcher()
-{
- DownloadManager::m_DirWatcherDisabler++;
-}
-
-
-void DownloadManager::endDisableDirWatcher()
-{
- if (DownloadManager::m_DirWatcherDisabler > 0)
- {
- if (DownloadManager::m_DirWatcherDisabler == 1)
- QCoreApplication::processEvents();
- DownloadManager::m_DirWatcherDisabler--;
- }
- else {
- DownloadManager::m_DirWatcherDisabler = 0;
- }
-}
-
-void DownloadManager::DownloadInfo::setName(QString newName, bool renameFile)
-{
- QString oldMetaFileName = QString("%1.meta").arg(m_FileName);
- m_FileName = QFileInfo(newName).fileName();
- if ((m_State == DownloadManager::STATE_STARTED) ||
- (m_State == DownloadManager::STATE_DOWNLOADING) ||
- (m_State == DownloadManager::STATE_PAUSED)) {
- newName.append(UNFINISHED);
- oldMetaFileName = QString("%1%2.meta").arg(m_FileName).arg(UNFINISHED);
- }
- if (renameFile) {
- if ((newName != m_Output.fileName()) && !m_Output.rename(newName)) {
- reportError(tr("failed to rename \"%1\" to \"%2\"").arg(m_Output.fileName()).arg(newName));
- return;
- }
-
- QFile metaFile(QFileInfo(newName).path() + "/" + oldMetaFileName);
- if (metaFile.exists())
- metaFile.rename(newName.mid(0).append(".meta"));
- }
- if (!m_Output.isOpen()) {
- // can't set file name if it's open
- m_Output.setFileName(newName);
- }
-}
-
-bool DownloadManager::DownloadInfo::isPausedState()
-{
- return m_State == STATE_PAUSED || m_State == STATE_ERROR;
-}
-
-QString DownloadManager::DownloadInfo::currentURL()
-{
- return m_Urls[m_CurrentUrl];
-}
-
-
-DownloadManager::DownloadManager(NexusInterface *nexusInterface, QObject *parent)
- : IDownloadManager(parent), m_NexusInterface(nexusInterface), m_DirWatcher(), m_ShowHidden(false),
- m_DateExpression("/Date\\((\\d+)\\)/")
-{
- connect(&m_DirWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(directoryChanged(QString)));
- m_TimeoutTimer.setSingleShot(false);
- //connect(&m_TimeoutTimer, SIGNAL(timeout()), this, SLOT(checkDownloadTimeout()));
- m_TimeoutTimer.start(5 * 1000);
-}
-
-
-DownloadManager::~DownloadManager()
-{
- for (QVector<DownloadInfo*>::iterator iter = m_ActiveDownloads.begin(); iter != m_ActiveDownloads.end(); ++iter) {
- delete *iter;
- }
- m_ActiveDownloads.clear();
-}
-
-
-bool DownloadManager::downloadsInProgress()
-{
- for (QVector<DownloadInfo*>::iterator iter = m_ActiveDownloads.begin(); iter != m_ActiveDownloads.end(); ++iter) {
- if ((*iter)->m_State < STATE_READY) {
- return true;
- }
- }
- return false;
-}
-
-bool DownloadManager::downloadsInProgressNoPause()
-{
- for (QVector<DownloadInfo*>::iterator iter = m_ActiveDownloads.begin(); iter != m_ActiveDownloads.end(); ++iter) {
- if ((*iter)->m_State < STATE_READY && (*iter)->m_State != STATE_PAUSED) {
- return true;
- }
- }
- return false;
-}
-
-
-void DownloadManager::pauseAll()
-{
-
- // first loop: pause all downloads
- for (int i = 0; i < m_ActiveDownloads.count(); ++i) {
- if (m_ActiveDownloads[i]->m_State < STATE_READY) {
- pauseDownload(i);
- }
- }
-
- ::Sleep(100);
-
- bool done = false;
- QTime startTime = QTime::currentTime();
- // further loops: busy waiting for all downloads to complete. This could be neater...
- while (!done && (startTime.secsTo(QTime::currentTime()) < 5)) {
- QCoreApplication::processEvents();
- done = true;
- foreach (DownloadInfo *info, m_ActiveDownloads) {
- if ((info->m_State < STATE_CANCELED) ||
- (info->m_State == STATE_FETCHINGFILEINFO) ||
- (info->m_State == STATE_FETCHINGMODINFO)) {
- done = false;
- break;
- }
- }
- if (!done) {
- ::Sleep(100);
- }
- }
-
-}
-
-
-void DownloadManager::setOutputDirectory(const QString &outputDirectory)
-{
- QStringList directories = m_DirWatcher.directories();
- if (directories.length() != 0) {
- m_DirWatcher.removePaths(directories);
- }
- m_OutputDirectory = QDir::fromNativeSeparators(outputDirectory);
- refreshList();
- m_DirWatcher.addPath(m_OutputDirectory);
-}
-
-
-void DownloadManager::setPreferredServers(const std::map<QString, int> &preferredServers)
-{
- m_PreferredServers = preferredServers;
-}
-
-
-void DownloadManager::setSupportedExtensions(const QStringList &extensions)
-{
- m_SupportedExtensions = extensions;
- refreshList();
-}
-
-void DownloadManager::setShowHidden(bool showHidden)
-{
- m_ShowHidden = showHidden;
- refreshList();
-}
-
-void DownloadManager::setPluginContainer(PluginContainer *pluginContainer)
-{
- m_NexusInterface->setPluginContainer(pluginContainer);
-}
-
-
-
-
-
-
-void DownloadManager::refreshList()
-{
- try {
- //avoid triggering other refreshes
- startDisableDirWatcher();
-
- int downloadsBefore = m_ActiveDownloads.size();
-
- // remove finished downloads
- for (QVector<DownloadInfo*>::iterator iter = m_ActiveDownloads.begin(); iter != m_ActiveDownloads.end();) {
- if (((*iter)->m_State == STATE_READY) || ((*iter)->m_State == STATE_INSTALLED) || ((*iter)->m_State == STATE_UNINSTALLED)) {
- delete *iter;
- iter = m_ActiveDownloads.erase(iter);
- } else {
- ++iter;
- }
- }
-
- QStringList nameFilters(m_SupportedExtensions);
- foreach (const QString &extension, m_SupportedExtensions) {
- nameFilters.append("*." + extension);
- }
-
- nameFilters.append(QString("*").append(UNFINISHED));
- QDir dir(QDir::fromNativeSeparators(m_OutputDirectory));
-
- // find orphaned meta files and delete them (sounds cruel but it's better for everyone)
- QStringList orphans;
- QStringList metaFiles = dir.entryList(QStringList() << "*.meta");
- foreach (const QString &metaFile, metaFiles) {
- QString baseFile = metaFile.left(metaFile.length() - 5);
- if (!QFile::exists(dir.absoluteFilePath(baseFile))) {
- orphans.append(dir.absoluteFilePath(metaFile));
- }
- }
- if (orphans.size() > 0) {
- qDebug("%d orphaned meta files will be deleted", orphans.size());
- shellDelete(orphans, true);
- }
-
- // add existing downloads to list
- foreach (QString file, dir.entryList(nameFilters, QDir::Files, QDir::Time)) {
- bool Exists = false;
- for (QVector<DownloadInfo*>::const_iterator Iter = m_ActiveDownloads.begin(); Iter != m_ActiveDownloads.end() && !Exists; ++Iter) {
- if (QString::compare((*Iter)->m_FileName, file, Qt::CaseInsensitive) == 0) {
- Exists = true;
- } else if (QString::compare(QFileInfo((*Iter)->m_Output.fileName()).fileName(), file, Qt::CaseInsensitive) == 0) {
- Exists = true;
- }
- }
- if (Exists) {
- continue;
- }
-
- QString fileName = QDir::fromNativeSeparators(m_OutputDirectory) + "/" + file;
-
- DownloadInfo *info = DownloadInfo::createFromMeta(fileName, m_ShowHidden, m_OutputDirectory);
- if (info != nullptr) {
- m_ActiveDownloads.push_front(info);
- }
- }
-
- //if (m_ActiveDownloads.size() != downloadsBefore) {
- qDebug("Downloads after refresh: %d", m_ActiveDownloads.size());
- //}
- emit update(-1);
-
- //let watcher trigger refreshes again
- endDisableDirWatcher();
-
- } catch (const std::bad_alloc&) {
- reportError(tr("Memory allocation error (in refreshing directory)."));
- }
-}
-
-
-bool DownloadManager::addDownload(const QStringList &URLs, QString gameName,
- int modID, int fileID, const ModRepositoryFileInfo *fileInfo)
-{
- QString fileName = QFileInfo(URLs.first()).fileName();
- if (fileName.isEmpty()) {
- fileName = "unknown";
- }
-
- QUrl preferredUrl = QUrl::fromEncoded(URLs.first().toLocal8Bit());
- qDebug("selected download url: %s", qUtf8Printable(preferredUrl.toString()));
- QNetworkRequest request(preferredUrl);
- request.setHeader(QNetworkRequest::UserAgentHeader, m_NexusInterface->getAccessManager()->userAgent());
- return addDownload(m_NexusInterface->getAccessManager()->get(request), URLs, fileName, gameName, modID, fileID, fileInfo);
-}
-
-
-bool DownloadManager::addDownload(QNetworkReply *reply, const ModRepositoryFileInfo *fileInfo)
-{
- QString fileName = getFileNameFromNetworkReply(reply);
- if (fileName.isEmpty()) {
- fileName = "unknown";
- }
-
- return addDownload(reply, QStringList(reply->url().toString()), fileName, fileInfo->gameName, fileInfo->modID, fileInfo->fileID, fileInfo);
-}
-
-
-bool DownloadManager::addDownload(QNetworkReply *reply, const QStringList &URLs, const QString &fileName,
- QString gameName, int modID, int fileID, const ModRepositoryFileInfo *fileInfo)
-{
- // download invoked from an already open network reply (i.e. download link in the browser)
- DownloadInfo *newDownload = DownloadInfo::createNew(fileInfo, URLs);
-
- QString baseName = fileName;
- if (!fileInfo->fileName.isEmpty()) {
- baseName = fileInfo->fileName;
- } else {
- QString dispoName = getFileNameFromNetworkReply(reply);
-
- if (!dispoName.isEmpty()) {
- baseName = dispoName;
- }
- }
-
- startDisableDirWatcher();
- newDownload->setName(getDownloadFileName(baseName), false);
- endDisableDirWatcher();
-
- startDownload(reply, newDownload, false);
-// emit update(-1);
- return true;
-}
-
-
-void DownloadManager::removePending(QString gameName, int modID, int fileID)
-{
- emit aboutToUpdate();
- for (auto iter : m_PendingDownloads) {
- if (gameName.compare(std::get<0>(iter), Qt::CaseInsensitive) == 0 && (std::get<1>(iter) == modID) && (std::get<2>(iter) == fileID)) {
- m_PendingDownloads.removeAt(m_PendingDownloads.indexOf(iter));
- break;
- }
- }
- emit update(-1);
-}
-
-
-void DownloadManager::startDownload(QNetworkReply *reply, DownloadInfo *newDownload, bool resume)
-{
- reply->setReadBufferSize(1024 * 1024); // don't read more than 1MB at once to avoid memory troubles
- newDownload->m_Reply = reply;
- setState(newDownload, STATE_DOWNLOADING);
- if (newDownload->m_Urls.count() == 0) {
- newDownload->m_Urls = QStringList(reply->url().toString());
- }
-
- QIODevice::OpenMode mode = QIODevice::WriteOnly;
- if (resume) {
- mode |= QIODevice::Append;
- }
-
- newDownload->m_StartTime.start();
- createMetaFile(newDownload);
-
- if (!newDownload->m_Output.open(mode)) {
- reportError(tr("failed to download %1: could not open output file: %2")
- .arg(reply->url().toString()).arg(newDownload->m_Output.fileName()));
- return;
- }
-
- connect(newDownload->m_Reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(downloadProgress(qint64, qint64)));
- connect(newDownload->m_Reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(downloadError(QNetworkReply::NetworkError)));
- connect(newDownload->m_Reply, SIGNAL(readyRead()), this, SLOT(downloadReadyRead()));
- connect(newDownload->m_Reply, SIGNAL(metaDataChanged()), this, SLOT(metaDataChanged()));
-
- if (!resume) {
- newDownload->m_PreResumeSize = newDownload->m_Output.size();
- removePending(newDownload->m_FileInfo->gameName, newDownload->m_FileInfo->modID, newDownload->m_FileInfo->fileID);
-
- emit aboutToUpdate();
- m_ActiveDownloads.append(newDownload);
-
- emit update(-1);
- emit downloadAdded();
-
- if (QFile::exists(m_OutputDirectory + "/" + newDownload->m_FileName)) {
- setState(newDownload, STATE_PAUSING);
- QCoreApplication::processEvents();
- if (QMessageBox::question(nullptr, tr("Download again?"), tr("A file with the same name \"%1\" has already been downloaded. "
- "Do you want to download it again? The new file will receive a different name.").arg(newDownload->m_FileName),
- QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) {
- if (reply->isFinished())
- setState(newDownload, STATE_CANCELED);
- else
- setState(newDownload, STATE_CANCELING);
- } else {
- startDisableDirWatcher();
- newDownload->setName(getDownloadFileName(newDownload->m_FileName, true), true);
- endDisableDirWatcher();
- if (newDownload->m_State == STATE_PAUSED)
- resumeDownload(indexByName(newDownload->m_FileName));
- else
- setState(newDownload, STATE_DOWNLOADING);
- }
- } else
- connect(newDownload->m_Reply, SIGNAL(finished()), this, SLOT(downloadFinished()));
-
-
- QCoreApplication::processEvents();
-
- if (newDownload->m_State != STATE_DOWNLOADING &&
- newDownload->m_State != STATE_READY &&
- newDownload->m_State != STATE_FETCHINGMODINFO &&
- reply->isFinished()) {
- downloadFinished(indexByName(newDownload->m_FileName));
- return;
- }
- } else
- connect(newDownload->m_Reply, SIGNAL(finished()), this, SLOT(downloadFinished()));
-}
-
-
-void DownloadManager::addNXMDownload(const QString &url)
-{
- NXMUrl nxmInfo(url);
-
- QStringList validGames;
- validGames.append(m_ManagedGame->gameShortName());
- validGames.append(m_ManagedGame->validShortNames());
- qDebug("add nxm download: %s", qUtf8Printable(url));
- if (!validGames.contains(nxmInfo.game(), Qt::CaseInsensitive)) {
- qDebug("download requested for wrong game (game: %s, url: %s)", qUtf8Printable(m_ManagedGame->gameShortName()), qUtf8Printable(nxmInfo.game()));
- QMessageBox::information(nullptr, tr("Wrong Game"), tr("The download link is for a mod for \"%1\" but this instance of MO "
- "has been set up for \"%2\".").arg(nxmInfo.game()).arg(m_ManagedGame->gameShortName()), QMessageBox::Ok);
- return;
- }
-
- for (auto tuple : m_PendingDownloads) {
- if (std::get<0>(tuple).compare(nxmInfo.game(), Qt::CaseInsensitive) == 0, std::get<1>(tuple) == nxmInfo.modId() && std::get<2>(tuple) == nxmInfo.fileId()) {
- qDebug("download requested is already started (mod id: %s, file id: %s)", qUtf8Printable(QString(nxmInfo.modId())), qUtf8Printable(QString(nxmInfo.fileId())));
- QMessageBox::information(nullptr, tr("Already Started"), tr("A download for this mod file has already been queued."), QMessageBox::Ok);
- return;
- }
- }
-
- for (DownloadInfo *download : m_ActiveDownloads) {
- if (download->m_FileInfo->modID == nxmInfo.modId() && download->m_FileInfo->fileID == nxmInfo.fileId()) {
- if (download->m_State == STATE_DOWNLOADING || download->m_State == STATE_PAUSED || download->m_State == STATE_STARTED) {
- qDebug("download requested is already started (mod: %s, file: %s)", qUtf8Printable(QString(download->m_FileInfo->modID)),
- qUtf8Printable(download->m_FileInfo->fileName));
-
- QMessageBox::information(nullptr, tr("Already Started"), tr("There is already a download started for this file (mod: %1, file: %2).")
- .arg(download->m_FileInfo->modName).arg(download->m_FileInfo->fileName), QMessageBox::Ok);
- return;
- }
- }
- }
-
- emit aboutToUpdate();
-
- m_PendingDownloads.append(std::make_tuple(nxmInfo.game(), nxmInfo.modId(), nxmInfo.fileId()));
-
- emit update(-1);
- emit downloadAdded();
- m_RequestIDs.insert(m_NexusInterface->requestFileInfo(nxmInfo.game(), nxmInfo.modId(), nxmInfo.fileId(), this, nxmInfo.fileId(), ""));
-}
-
-
-void DownloadManager::removeFile(int index, bool deleteFile)
-{
- //Avoid triggering refreshes from DirWatcher
- startDisableDirWatcher();
-
- if (index >= m_ActiveDownloads.size()) {
- throw MyException(tr("remove: invalid download index %1").arg(index));
- }
-
- DownloadInfo *download = m_ActiveDownloads.at(index);
- QString filePath = m_OutputDirectory + "/" + download->m_FileName;
- if ((download->m_State == STATE_STARTED) ||
- (download->m_State == STATE_DOWNLOADING)) {
- // shouldn't have been possible
- qCritical("tried to remove active download");
- endDisableDirWatcher();
- return;
- }
-
- if ((download->m_State == STATE_PAUSED) || (download->m_State == STATE_ERROR)) {
- filePath = download->m_Output.fileName();
- }
-
- if (deleteFile) {
- if (!shellDelete(QStringList(filePath), true)) {
- reportError(tr("failed to delete %1").arg(filePath));
- endDisableDirWatcher();
- return;
- }
-
- QFile metaFile(filePath.append(".meta"));
- if (metaFile.exists() && !shellDelete(QStringList(filePath), true)) {
- reportError(tr("failed to delete meta file for %1").arg(filePath));
- }
- } else {
- QSettings metaSettings(filePath.append(".meta"), QSettings::IniFormat);
- if(!download->m_Hidden)
- metaSettings.setValue("removed", true);
- }
-
- endDisableDirWatcher();
-}
-
-class LessThanWrapper
-{
-public:
- LessThanWrapper(DownloadManager *manager) : m_Manager(manager) {}
- bool operator()(int LHS, int RHS) {
- return m_Manager->getFileName(LHS).compare(m_Manager->getFileName(RHS), Qt::CaseInsensitive) < 0;
-
- }
-
-private:
- DownloadManager *m_Manager;
-};
-
-
-bool DownloadManager::ByName(int LHS, int RHS)
-{
- return m_ActiveDownloads[LHS]->m_FileName < m_ActiveDownloads[RHS]->m_FileName;
-}
-
-
-void DownloadManager::refreshAlphabeticalTranslation()
-{
- m_AlphabeticalTranslation.clear();
- int pos = 0;
- for (QVector<DownloadInfo*>::iterator iter = m_ActiveDownloads.begin(); iter != m_ActiveDownloads.end(); ++iter, ++pos) {
- m_AlphabeticalTranslation.push_back(pos);
- }
-
- qSort(m_AlphabeticalTranslation.begin(), m_AlphabeticalTranslation.end(), LessThanWrapper(this));
-}
-
-
-void DownloadManager::restoreDownload(int index)
-{
-
- if (index < 0) {
- DownloadState minState = STATE_READY ;
- index = 0;
-
- for (QVector<DownloadInfo*>::const_iterator iter = m_ActiveDownloads.begin(); iter != m_ActiveDownloads.end(); ++iter ) {
-
- if ((*iter)->m_State >= minState) {
- restoreDownload(index);
- }
- index++;
- }
- }
- else {
- if (index >= m_ActiveDownloads.size()) {
- throw MyException(tr("restore: invalid download index: %1").arg(index));
- }
-
- DownloadInfo *download = m_ActiveDownloads.at(index);
- if (download->m_Hidden) {
- download->m_Hidden = false;
-
- QString filePath = m_OutputDirectory + "/" + download->m_FileName;
-
- //avoid dirWatcher triggering refreshes
- startDisableDirWatcher();
- QSettings metaSettings(filePath.append(".meta"), QSettings::IniFormat);
- metaSettings.setValue("removed", false);
-
- endDisableDirWatcher();
- }
- }
-}
-
-
-void DownloadManager::removeDownload(int index, bool deleteFile)
-{
- try {
- //avoid dirWatcher triggering refreshes
- startDisableDirWatcher();
-
- emit aboutToUpdate();
-
- if (index < 0) {
- bool removeAll = (index == -1);
- DownloadState removeState = (index == -2 ? STATE_INSTALLED : STATE_UNINSTALLED);
-
- index = 0;
- for (QVector<DownloadInfo*>::iterator iter = m_ActiveDownloads.begin(); iter != m_ActiveDownloads.end();) {
- DownloadState downloadState = (*iter)->m_State;
- if ((removeAll && (downloadState >= STATE_READY)) ||
- (removeState == downloadState)) {
- removeFile(index, deleteFile);
- delete *iter;
- iter = m_ActiveDownloads.erase(iter);
- } else {
- ++iter;
- ++index;
- }
- }
- } else {
- if (index >= m_ActiveDownloads.size()) {
- reportError(tr("remove: invalid download index %1").arg(index));
- //emit update(-1);
- endDisableDirWatcher();
- return;
- }
-
- removeFile(index, deleteFile);
- delete m_ActiveDownloads.at(index);
- m_ActiveDownloads.erase(m_ActiveDownloads.begin() + index);
- }
- emit update(-1);
- endDisableDirWatcher();
- } catch (const std::exception &e) {
- qCritical("failed to remove download: %s", e.what());
- }
- refreshList();
-}
-
-
-void DownloadManager::cancelDownload(int index)
-{
- if ((index < 0) || (index >= m_ActiveDownloads.size())) {
- reportError(tr("cancel: invalid download index %1").arg(index));
- return;
- }
-
- if (m_ActiveDownloads.at(index)->m_State == STATE_DOWNLOADING) {
- setState(m_ActiveDownloads.at(index), STATE_CANCELING);
- }
-}
-
-
-void DownloadManager::pauseDownload(int index)
-{
- if ((index < 0) || (index >= m_ActiveDownloads.size())) {
- reportError(tr("pause: invalid download index %1").arg(index));
- return;
- }
-
- DownloadInfo *info = m_ActiveDownloads.at(index);
-
- if (info->m_State == STATE_DOWNLOADING) {
- if ((info->m_Reply != nullptr) && (info->m_Reply->isRunning())) {
- setState(info, STATE_PAUSING);
- } else {
- setState(info, STATE_PAUSED);
- }
- } else if ((info->m_State == STATE_FETCHINGMODINFO) || (info->m_State == STATE_FETCHINGFILEINFO)) {
- setState(info, STATE_READY);
- }
-}
-
-void DownloadManager::resumeDownload(int index)
-{
- if ((index < 0) || (index >= m_ActiveDownloads.size())) {
- reportError(tr("resume: invalid download index %1").arg(index));
- return;
- }
- DownloadInfo *info = m_ActiveDownloads[index];
- info->m_Tries = AUTOMATIC_RETRIES;
- resumeDownloadInt(index);
-}
-
-void DownloadManager::resumeDownloadInt(int index)
-{
- if ((index < 0) || (index >= m_ActiveDownloads.size())) {
- reportError(tr("resume (int): invalid download index %1").arg(index));
- return;
- }
- DownloadInfo *info = m_ActiveDownloads[index];
-
- // Check for finished download;
- if (info->m_TotalSize <= info->m_Output.size() && info->m_Reply != nullptr
- && info->m_Reply->isOpen() && info->m_Reply->isFinished() && info->m_State != STATE_ERROR) {
- setState(info, STATE_DOWNLOADING);
- downloadFinished(index);
- return;
- }
-
- if (info->isPausedState() || info->m_State == STATE_PAUSING) {
- if (info->m_State == STATE_PAUSING) {
- if (info->m_Output.isOpen()) {
- writeData(info);
- if (info->m_State == STATE_PAUSING) {
- setState(info, STATE_PAUSED);
- }
- }
- }
- if ((info->m_Urls.size() == 0)
- || ((info->m_Urls.size() == 1) && (info->m_Urls[0].size() == 0))) {
- emit showMessage(tr("No known download urls. Sorry, this download can't be resumed."));
- return;
- }
- if (info->m_State == STATE_ERROR) {
- info->m_CurrentUrl = (info->m_CurrentUrl + 1) % info->m_Urls.count();
- }
- qDebug("request resume from url %s", qUtf8Printable(info->currentURL()));
- QNetworkRequest request(QUrl::fromEncoded(info->currentURL().toLocal8Bit()));
- request.setHeader(QNetworkRequest::UserAgentHeader, m_NexusInterface->getAccessManager()->userAgent());
- if (info->m_State != STATE_ERROR) {
- info->m_ResumePos = info->m_Output.size();
- QByteArray rangeHeader = "bytes=" + QByteArray::number(info->m_ResumePos) + "-";
- request.setRawHeader("Range", rangeHeader);
- }
- std::get<0>(info->m_SpeedDiff) = 0;
- std::get<1>(info->m_SpeedDiff) = 0;
- std::get<2>(info->m_SpeedDiff) = 0;
- std::get<3>(info->m_SpeedDiff) = 0;
- std::get<4>(info->m_SpeedDiff) = 0;
- qDebug("resume at %lld bytes", info->m_ResumePos);
- startDownload(m_NexusInterface->getAccessManager()->get(request), info, true);
- }
- emit update(index);
-}
-
-
-DownloadManager::DownloadInfo *DownloadManager::downloadInfoByID(unsigned int id)
-{
- auto iter = std::find_if(m_ActiveDownloads.begin(), m_ActiveDownloads.end(),
- [id](DownloadInfo *info) { return info->m_DownloadID == id; });
- if (iter != m_ActiveDownloads.end()) {
- return *iter;
- } else {
- return nullptr;
- }
-}
-
-
-void DownloadManager::queryInfo(int index)
-{
- if ((index < 0) || (index >= m_ActiveDownloads.size())) {
- reportError(tr("query: invalid download index %1").arg(index));
- return;
- }
- DownloadInfo *info = m_ActiveDownloads[index];
-
- if (info->m_FileInfo->repository != "Nexus") {
- qWarning("re-querying file info is currently only possible with Nexus");
- return;
- }
-
- if (info->m_State < DownloadManager::STATE_READY) {
- // UI shouldn't allow this
- return;
- }
-
- if (info->m_FileInfo->modID <= 0) {
- QString fileName = getFileName(index);
- QString ignore;
- NexusInterface::interpretNexusFileName(fileName, ignore, info->m_FileInfo->modID, true);
- if (info->m_FileInfo->modID < 0) {
- bool ok = false;
- int modId = QInputDialog::getInt(
- nullptr, tr("Please enter the nexus mod id"), tr("Mod ID:"), 1, 1,
- std::numeric_limits<int>::max(), 1, &ok);
- // careful now: while the dialog was displayed, events were processed.
- // the download list might have changed and our info-ptr invalidated.
- if (ok)
- m_ActiveDownloads[index]->m_FileInfo->modID = modId;
- return;
- }
- }
-
- if (info->m_FileInfo->gameName.size() == 0) {
- SelectionDialog selection(tr("Please select the source game code for %1").arg(getFileName(index)));
-
- std::vector<std::pair<QString, QString>> choices = m_NexusInterface->getGameChoices(m_ManagedGame);
- for (auto choice : choices) {
- selection.addChoice(choice.first, choice.second, choice.first);
- }
- if (selection.exec() == QDialog::Accepted) {
- info->m_FileInfo->gameName = selection.getChoiceData().toString();
- } else {
- info->m_FileInfo->gameName = m_ManagedGame->gameShortName();
- }
- }
- info->m_ReQueried = true;
- setState(info, STATE_FETCHINGMODINFO);
-}
-
-void DownloadManager::visitOnNexus(int index)
-{
- if ((index < 0) || (index >= m_ActiveDownloads.size())) {
- reportError(tr("VisitNexus: invalid download index %1").arg(index));
- return;
- }
- DownloadInfo *info = m_ActiveDownloads[index];
-
- if (info->m_FileInfo->repository != "Nexus") {
- qWarning("Visiting mod page is currently only possible with Nexus");
- return;
- }
-
- if (info->m_State < DownloadManager::STATE_READY) {
- // UI shouldn't allow this
- return;
- }
- int modID = info->m_FileInfo->modID;
-
- QString gameName = info->m_FileInfo->gameName;
- if (modID > 0) {
- QDesktopServices::openUrl(QUrl(m_NexusInterface->getModURL(modID, gameName)));
- }
- else {
- emit showMessage(tr("Nexus ID for this Mod is unknown"));
- }
-}
-
-void DownloadManager::openFile(int index)
-{
- if ((index < 0) || (index >= m_ActiveDownloads.size())) {
- reportError(tr("OpenFile: invalid download index %1").arg(index));
- return;
- }
- QDir path = QDir(m_OutputDirectory);
- if (path.exists(getFileName(index))) {
-
- ::ShellExecuteW(nullptr, L"open", ToWString(QDir::toNativeSeparators(getFilePath(index))).c_str(), nullptr, nullptr, SW_SHOWNORMAL);
- return;
- }
-
- ::ShellExecuteW(nullptr, L"explore", ToWString(QDir::toNativeSeparators(m_OutputDirectory)).c_str(), nullptr, nullptr, SW_SHOWNORMAL);
- return;
-}
-
-void DownloadManager::openInDownloadsFolder(int index)
-{
- if ((index < 0) || (index >= m_ActiveDownloads.size())) {
- reportError(tr("OpenFileInDownloadsFolder: invalid download index %1").arg(index));
- return;
- }
- QString params = "/select,\"";
- QDir path = QDir(m_OutputDirectory);
- if (path.exists(getFileName(index))) {
- params = params + QDir::toNativeSeparators(getFilePath(index)) + "\"";
-
- ::ShellExecuteW(nullptr, nullptr, L"explorer", ToWString(params).c_str(), nullptr, SW_SHOWNORMAL);
- return;
- }
- else if (path.exists(getFileName(index) + ".unfinished")) {
- params = params + QDir::toNativeSeparators(getFilePath(index)+".unfinished") + "\"";
-
- ::ShellExecuteW(nullptr, nullptr, L"explorer", ToWString(params).c_str(), nullptr, SW_SHOWNORMAL);
- return;
- }
-
- ::ShellExecuteW(nullptr, L"explore", ToWString(QDir::toNativeSeparators(m_OutputDirectory)).c_str(), nullptr, nullptr, SW_SHOWNORMAL);
- return;
-}
-
-
-int DownloadManager::numTotalDownloads() const
-{
- return m_ActiveDownloads.size();
-}
-
-int DownloadManager::numPendingDownloads() const
-{
- return m_PendingDownloads.size();
-}
-
-std::tuple<QString, int, int> DownloadManager::getPendingDownload(int index)
-{
- if ((index < 0) || (index >= m_PendingDownloads.size())) {
- throw MyException(tr("get pending: invalid download index %1").arg(index));
- }
-
- return m_PendingDownloads.at(index);
-}
-
-QString DownloadManager::getFilePath(int index) const
-{
- if ((index < 0) || (index >= m_ActiveDownloads.size())) {
- throw MyException(tr("get path: invalid download index %1").arg(index));
- }
-
- return m_OutputDirectory + "/" + m_ActiveDownloads.at(index)->m_FileName;
-}
-
-QString DownloadManager::getFileTypeString(int fileType)
-{
- switch (fileType) {
- case 1: return tr("Main");
- case 2: return tr("Update");
- case 3: return tr("Optional");
- case 4: return tr("Old");
- case 5: return tr("Misc");
- default: return tr("Unknown");
- }
-}
-
-QString DownloadManager::getDisplayName(int index) const
-{
- if ((index < 0) || (index >= m_ActiveDownloads.size())) {
- throw MyException(tr("display name: invalid download index %1").arg(index));
- }
-
- DownloadInfo *info = m_ActiveDownloads.at(index);
-
- QTextDocument doc;
- if (!info->m_FileInfo->name.isEmpty()) {
- doc.setHtml(info->m_FileInfo->name);
- return QString("%1 (%2, v%3)").arg(doc.toPlainText())
- .arg(getFileTypeString(info->m_FileInfo->fileCategory))
- .arg(info->m_FileInfo->version.displayString());
- } else {
- doc.setHtml(info->m_FileName);
- return doc.toPlainText();
- }
-}
-
-QString DownloadManager::getFileName(int index) const
-{
- if ((index < 0) || (index >= m_ActiveDownloads.size())) {
- throw MyException(tr("file name: invalid download index %1").arg(index));
- }
-
- return m_ActiveDownloads.at(index)->m_FileName;
-}
-
-QDateTime DownloadManager::getFileTime(int index) const
-{
- if ((index < 0) || (index >= m_ActiveDownloads.size())) {
- throw MyException(tr("file time: invalid download index %1").arg(index));
- }
-
- DownloadInfo *info = m_ActiveDownloads.at(index);
- if (!info->m_Created.isValid()) {
- info->m_Created = QFileInfo(info->m_Output).created();
- }
-
- return info->m_Created;
-}
-
-qint64 DownloadManager::getFileSize(int index) const
-{
- if ((index < 0) || (index >= m_ActiveDownloads.size())) {
- throw MyException(tr("file size: invalid download index %1").arg(index));
- }
-
- return m_ActiveDownloads.at(index)->m_TotalSize;
-}
-
-
-std::pair<int, QString> DownloadManager::getProgress(int index) const
-{
- if ((index < 0) || (index >= m_ActiveDownloads.size())) {
- throw MyException(tr("progress: invalid download index %1").arg(index));
- }
-
- return m_ActiveDownloads.at(index)->m_Progress;
-}
-
-
-DownloadManager::DownloadState DownloadManager::getState(int index) const
-{
- if ((index < 0) || (index >= m_ActiveDownloads.size())) {
- throw MyException(tr("state: invalid download index %1").arg(index));
- }
-
- return m_ActiveDownloads.at(index)->m_State;
-}
-
-
-bool DownloadManager::isInfoIncomplete(int index) const
-{
- if ((index < 0) || (index >= m_ActiveDownloads.size())) {
- throw MyException(tr("infocomplete: invalid download index %1").arg(index));
- }
-
- DownloadInfo *info = m_ActiveDownloads.at(index);
- if (info->m_FileInfo->repository != "Nexus") {
- // other repositories currently don't support re-querying info anyway
- return false;
- }
- return (info->m_FileInfo->fileID == 0) || (info->m_FileInfo->modID == 0);
-}
-
-
-int DownloadManager::getModID(int index) const
-{
- if ((index < 0) || (index >= m_ActiveDownloads.size())) {
- throw MyException(tr("mod id: invalid download index %1").arg(index));
- }
- return m_ActiveDownloads.at(index)->m_FileInfo->modID;
-}
-
-QString DownloadManager::getGameName(int index) const
-{
- if ((index < 0) || (index >= m_ActiveDownloads.size())) {
- throw MyException(tr("mod id: invalid download index %1").arg(index));
- }
- return m_ActiveDownloads.at(index)->m_FileInfo->gameName;
-}
-
-bool DownloadManager::isHidden(int index) const
-{
- if ((index < 0) || (index >= m_ActiveDownloads.size())) {
- throw MyException(tr("ishidden: invalid download index %1").arg(index));
- }
- return m_ActiveDownloads.at(index)->m_Hidden;
-}
-
-
-const ModRepositoryFileInfo *DownloadManager::getFileInfo(int index) const
-{
- if ((index < 0) || (index >= m_ActiveDownloads.size())) {
- throw MyException(tr("file info: invalid download index %1").arg(index));
- }
-
- return m_ActiveDownloads.at(index)->m_FileInfo;
-}
-
-
-void DownloadManager::markInstalled(int index)
-{
- if ((index < 0) || (index >= m_ActiveDownloads.size())) {
- throw MyException(tr("mark installed: invalid download index %1").arg(index));
- }
-
- //Avoid triggering refreshes from DirWatcher
- startDisableDirWatcher();
-
- DownloadInfo *info = m_ActiveDownloads.at(index);
- QSettings metaFile(info->m_Output.fileName() + ".meta", QSettings::IniFormat);
- metaFile.setValue("installed", true);
- metaFile.setValue("uninstalled", false);
-
- endDisableDirWatcher();
-
- setState(m_ActiveDownloads.at(index), STATE_INSTALLED);
-}
-
-void DownloadManager::markInstalled(QString fileName)
-{
- int index = indexByName(fileName);
- if (index >= 0) {
- markInstalled(index);
- } else {
- DownloadInfo *info = getDownloadInfo(fileName);
- if (info != nullptr) {
- //Avoid triggering refreshes from DirWatcher
- startDisableDirWatcher();
-
- QSettings metaFile(info->m_Output.fileName() + ".meta", QSettings::IniFormat);
- metaFile.setValue("installed", true);
- metaFile.setValue("uninstalled", false);
- delete info;
-
- endDisableDirWatcher();
- }
- }
-}
-
-DownloadManager::DownloadInfo* DownloadManager::getDownloadInfo(QString fileName)
-{
- return DownloadInfo::createFromMeta(fileName, true, m_OutputDirectory);
-}
-
-void DownloadManager::markUninstalled(int index)
-{
- if ((index < 0) || (index >= m_ActiveDownloads.size())) {
- throw MyException(tr("mark uninstalled: invalid download index %1").arg(index));
- }
-
- //Avoid triggering refreshes from DirWatcher
- startDisableDirWatcher();
-
- DownloadInfo *info = m_ActiveDownloads.at(index);
- QSettings metaFile(info->m_Output.fileName() + ".meta", QSettings::IniFormat);
- metaFile.setValue("uninstalled", true);
-
- endDisableDirWatcher();
-
- setState(m_ActiveDownloads.at(index), STATE_UNINSTALLED);
-}
-
-
-void DownloadManager::markUninstalled(QString fileName)
-{
- int index = indexByName(fileName);
- if (index >= 0) {
- markUninstalled(index);
- } else {
- QString filePath = QDir::fromNativeSeparators(m_OutputDirectory) + "/" + fileName;
- DownloadInfo *info = getDownloadInfo(filePath);
- if (info != nullptr) {
-
- //Avoid triggering refreshes from DirWatcher
- startDisableDirWatcher();
-
- QSettings metaFile(info->m_Output.fileName() + ".meta", QSettings::IniFormat);
- metaFile.setValue("uninstalled", true);
- delete info;
-
- endDisableDirWatcher();
- }
- }
-}
-
-
-QString DownloadManager::getDownloadFileName(const QString &baseName, bool rename) const
-{
- QString fullPath = m_OutputDirectory + "/" + baseName;
- if (QFile::exists(fullPath) && rename) {
- int i = 1;
- while (QFile::exists(QString("%1/%2_%3").arg(m_OutputDirectory).arg(i).arg(baseName))) {
- ++i;
- }
-
- fullPath = QString("%1/%2_%3").arg(m_OutputDirectory).arg(i).arg(baseName);
- }
- return fullPath;
-}
-
-
-QString DownloadManager::getFileNameFromNetworkReply(QNetworkReply *reply)
-{
- if (reply->hasRawHeader("Content-Disposition")) {
- std::regex exp("filename=\"(.*)\"");
-
- std::cmatch result;
- if (std::regex_search(reply->rawHeader("Content-Disposition").constData(), result, exp)) {
- return QString::fromUtf8(result.str(1).c_str());
- }
- }
-
- return QString();
-}
-
-
-void DownloadManager::setState(DownloadManager::DownloadInfo *info, DownloadManager::DownloadState state)
-{
- int row = 0;
- for (int i = 0; i < m_ActiveDownloads.size(); ++i) {
- if (m_ActiveDownloads[i] == info) {
- row = i;
- break;
- }
- }
- info->m_State = state;
- switch (state) {
- case STATE_PAUSED:
- case STATE_ERROR: {
- info->m_Reply->abort();
- info->m_Output.close();
- } break;
- case STATE_CANCELED: {
- info->m_Reply->abort();
- } break;
- case STATE_FETCHINGMODINFO: {
- m_RequestIDs.insert(m_NexusInterface->requestDescription(info->m_FileInfo->gameName, info->m_FileInfo->modID, this, info->m_DownloadID, QString()));
- } break;
- case STATE_FETCHINGFILEINFO: {
- m_RequestIDs.insert(m_NexusInterface->requestFiles(info->m_FileInfo->gameName, info->m_FileInfo->modID, this, info->m_DownloadID, QString()));
- } break;
- case STATE_READY: {
- createMetaFile(info);
- emit downloadComplete(row);
- } break;
- default: /* NOP */ break;
- }
- emit stateChanged(row, state);
-}
-
-
-DownloadManager::DownloadInfo *DownloadManager::findDownload(QObject *reply, int *index) const
-{
- // reverse search as newer, thus more relevant, downloads are at the end
- for (int i = m_ActiveDownloads.size() - 1; i >= 0; --i) {
- if (m_ActiveDownloads[i]->m_Reply == reply) {
- if (index != nullptr) {
- *index = i;
- }
- return m_ActiveDownloads[i];
- }
- }
- return nullptr;
-}
-
-
-void DownloadManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
-{
- if (bytesTotal == 0) {
- return;
- }
- int index = 0;
- try {
- DownloadInfo *info = findDownload(this->sender(), &index);
- if (info != nullptr) {
- info->m_HasData = true;
- if (info->m_State == STATE_CANCELING) {
- setState(info, STATE_CANCELED);
- } else if (info->m_State == STATE_PAUSING) {
- setState(info, STATE_PAUSED);
- }
- else {
- if (bytesTotal > info->m_TotalSize) {
- info->m_TotalSize = bytesTotal;
- }
- int oldProgress = info->m_Progress.first;
- info->m_Progress.first = ((info->m_ResumePos + bytesReceived) * 100) / (info->m_ResumePos + bytesTotal);
-
- int elapsed = info->m_StartTime.elapsed();
- std::get<0>(info->m_SpeedDiff) = bytesReceived - std::get<2>(info->m_SpeedDiff);
- std::get<1>(info->m_SpeedDiff) = elapsed - std::get<3>(info->m_SpeedDiff);
- std::get<2>(info->m_SpeedDiff) = bytesReceived;
- std::get<3>(info->m_SpeedDiff) = elapsed;
-
- double calc = ((double)std::get<0>(info->m_SpeedDiff)) / (((double)(std::get<1>(info->m_SpeedDiff)) / 5000.0));
- std::get<4>(info->m_SpeedDiff) = ((calc*0.5) + (std::get<4>(info->m_SpeedDiff)*1.5)) / 2;
-
- // calculate the download speed
- double speed = (std::get<4>(info->m_SpeedDiff) * 1000.0) / (5 * 1000);
-
- QString unit;
- if (speed < 1000) {
- unit = "B/s";
- }
- else if (speed < 1000*1024) {
- speed /= 1024;
- unit = "KB/s";
- }
- else {
- speed /= 1024 * 1024;
- unit = "MB/s";
- }
-
- info->m_Progress.second = QString::fromLatin1("%1% - %2 %3").arg(info->m_Progress.first).arg(QString::number(speed, 'f', 1)).arg(unit);
-
- TaskProgressManager::instance().updateProgress(info->m_TaskProgressId, bytesReceived, bytesTotal);
- emit update(index);
- }
- }
- } catch (const std::bad_alloc&) {
- reportError(tr("Memory allocation error (in processing progress event)."));
- }
-}
-
-
-void DownloadManager::downloadReadyRead()
-{
- try {
- writeData(findDownload(this->sender()));
- } catch (const std::bad_alloc&) {
- reportError(tr("Memory allocation error (in processing downloaded data)."));
- }
-}
-
-
-void DownloadManager::createMetaFile(DownloadInfo *info)
-{
- //Avoid triggering refreshes from DirWatcher
- startDisableDirWatcher();
-
- QSettings metaFile(QString("%1.meta").arg(info->m_Output.fileName()), QSettings::IniFormat);
- metaFile.setValue("gameName", info->m_FileInfo->gameName);
- metaFile.setValue("modID", info->m_FileInfo->modID);
- metaFile.setValue("fileID", info->m_FileInfo->fileID);
- metaFile.setValue("url", info->m_Urls.join(";"));
- metaFile.setValue("name", info->m_FileInfo->name);
- metaFile.setValue("description", info->m_FileInfo->description);
- metaFile.setValue("modName", info->m_FileInfo->modName);
- metaFile.setValue("version", info->m_FileInfo->version.canonicalString());
- metaFile.setValue("newestVersion", info->m_FileInfo->newestVersion.canonicalString());
- metaFile.setValue("fileTime", info->m_FileInfo->fileTime);
- metaFile.setValue("fileCategory", info->m_FileInfo->fileCategory);
- metaFile.setValue("category", info->m_FileInfo->categoryID);
- metaFile.setValue("repository", info->m_FileInfo->repository);
- metaFile.setValue("userData", info->m_FileInfo->userData);
- metaFile.setValue("installed", info->m_State == DownloadManager::STATE_INSTALLED);
- metaFile.setValue("uninstalled", info->m_State == DownloadManager::STATE_UNINSTALLED);
- metaFile.setValue("paused", (info->m_State == DownloadManager::STATE_PAUSED) ||
- (info->m_State == DownloadManager::STATE_ERROR));
- metaFile.setValue("removed", info->m_Hidden);
-
- endDisableDirWatcher();
- // slightly hackish...
- for (int i = 0; i < m_ActiveDownloads.size(); ++i) {
- if (m_ActiveDownloads[i] == info) {
- emit update(i);
- }
- }
-}
-
-
-void DownloadManager::nxmDescriptionAvailable(QString, int, QVariant userData, QVariant resultData, int requestID)
-{
- std::set<int>::iterator idIter = m_RequestIDs.find(requestID);
- if (idIter == m_RequestIDs.end()) {
- return;
- } else {
- m_RequestIDs.erase(idIter);
- }
-
- QVariantMap result = resultData.toMap();
-
- DownloadInfo *info = downloadInfoByID(userData.toInt());
- if (info == nullptr) return;
- info->m_FileInfo->categoryID = result["category_id"].toInt();
- QTextDocument doc;
- doc.setHtml(result["name"].toString().trimmed());
- info->m_FileInfo->modName = doc.toPlainText();
- info->m_FileInfo->newestVersion.parse(result["version"].toString());
- if (info->m_FileInfo->fileID != 0) {
- setState(info, STATE_READY);
- } else {
- setState(info, STATE_FETCHINGFILEINFO);
- }
-}
-
-
-QDateTime DownloadManager::matchDate(const QString &timeString)
-{
- if (m_DateExpression.exactMatch(timeString)) {
- return QDateTime::fromMSecsSinceEpoch(m_DateExpression.cap(1).toLongLong());
- } else {
- qWarning("date not matched: %s", qUtf8Printable(timeString));
- return QDateTime::currentDateTime();
- }
-}
-
-
-void DownloadManager::nxmFilesAvailable(QString, int, QVariant userData, QVariant resultData, int requestID)
-{
- std::set<int>::iterator idIter = m_RequestIDs.find(requestID);
- if (idIter == m_RequestIDs.end()) {
- return;
- } else {
- m_RequestIDs.erase(idIter);
- }
-
- DownloadInfo *info = downloadInfoByID(userData.toInt());
- if (info == nullptr) return;
-
- QVariantList result = resultData.toList();
-
- // MO sometimes prepends <digit>_ to the filename in case of duplicate downloads.
- // this may muck up the file name comparison
- QString alternativeLocalName = info->m_FileName;
-
- QRegExp expression("^\\d_(.*)$");
- if (expression.indexIn(alternativeLocalName) == 0) {
- alternativeLocalName = expression.cap(1);
- }
-
- bool found = false;
-
- for (QVariant file : result) {
- QVariantMap fileInfo = file.toMap();
- QString fileName = fileInfo["uri"].toString();
- QString fileNameVariant = fileName.mid(0).replace(' ', '_');
- if ((fileName == info->m_FileName) || (fileName == alternativeLocalName) ||
- (fileNameVariant == info->m_FileName) || (fileNameVariant == alternativeLocalName)) {
- info->m_FileInfo->name = fileInfo["name"].toString();
- info->m_FileInfo->version.parse(fileInfo["version"].toString());
- if (!info->m_FileInfo->version.isValid()) {
- info->m_FileInfo->version = info->m_FileInfo->newestVersion;
- }
- info->m_FileInfo->fileCategory = fileInfo["category_id"].toInt();
- info->m_FileInfo->fileTime = matchDate(fileInfo["date"].toString());
- info->m_FileInfo->fileID = fileInfo["id"].toInt();
- info->m_FileInfo->fileName = fileInfo["uri"].toString();
- info->m_FileInfo->description = BBCode::convertToHTML(fileInfo["description"].toString());
- found = true;
- break;
- }
- }
-
- if (info->m_ReQueried) {
- if (found) {
- emit showMessage(tr("Information updated"));
- } else if (result.count() == 0) {
- emit showMessage(tr("No matching file found on Nexus! Maybe this file is no longer available or it was renamed?"));
- } else {
- SelectionDialog selection(tr("No file on Nexus matches the selected file by name. Please manually choose the correct one."));
- for (QVariant file : result) {
- QVariantMap fileInfo = file.toMap();
- selection.addChoice(fileInfo["uri"].toString(), "", file);
- }
- if (selection.exec() == QDialog::Accepted) {
- QVariantMap fileInfo = selection.getChoiceData().toMap();
- info->m_FileInfo->name = fileInfo["name"].toString();
- info->m_FileInfo->version.parse(fileInfo["version"].toString());
- info->m_FileInfo->fileCategory = fileInfo["category_id"].toInt();
- info->m_FileInfo->fileID = fileInfo["id"].toInt();
- } else {
- emit showMessage(tr("No matching file found on Nexus! Maybe this file is no longer available or it was renamed?"));
- }
- }
- } else {
- if (info->m_FileInfo->fileID == 0) {
- qWarning("could not determine file id for %s (state %d)",
- qUtf8Printable(info->m_FileName), info->m_State);
- }
- }
-
- setState(info, STATE_READY);
-}
-
-
-void DownloadManager::nxmFileInfoAvailable(QString gameName, int modID, int fileID, QVariant userData, QVariant resultData, int requestID)
-{
- std::set<int>::iterator idIter = m_RequestIDs.find(requestID);
- if (idIter == m_RequestIDs.end()) {
- return;
- } else {
- m_RequestIDs.erase(idIter);
- }
-
- ModRepositoryFileInfo *info = new ModRepositoryFileInfo();
-
- QVariantMap result = resultData.toMap();
- info->name = result["name"].toString();
- info->version.parse(result["version"].toString());
- if (!info->version.isValid()) {
- info->version = info->newestVersion;
- }
- info->fileName = result["file_name"].toString();
- info->fileCategory = result["category_id"].toInt();
- info->fileTime = matchDate(result["uploaded_timestamp"].toString());
- info->description = BBCode::convertToHTML(result["changelog_html"].toString());
-
- info->repository = "Nexus";
- info->gameName = gameName;
- info->modID = modID;
- info->fileID = fileID;
-
- QObject *test = info;
- m_RequestIDs.insert(m_NexusInterface->requestDownloadURL(gameName, modID, fileID, this, qVariantFromValue(test), QString()));
-}
-
-static int evaluateFileInfoMap(const QVariantMap &map, const std::map<QString, int> &preferredServers)
-{
- int result = 0;
-
- auto preference = preferredServers.find(map["name"].toString());
-
- if (preference != preferredServers.end()) {
- result += 100 + preference->second * 20;
- }
-
- return result;
-}
-
-// sort function to sort by best download server
-bool DownloadManager::ServerByPreference(const std::map<QString, int> &preferredServers, const QVariant &LHS, const QVariant &RHS)
-{
- return evaluateFileInfoMap(LHS.toMap(), preferredServers) > evaluateFileInfoMap(RHS.toMap(), preferredServers);
-}
-
-int DownloadManager::startDownloadURLs(const QStringList &urls)
-{
- ModRepositoryFileInfo info;
- addDownload(urls, "", -1, -1, &info);
- return m_ActiveDownloads.size() - 1;
-}
-
-int DownloadManager::startDownloadNexusFile(int modID, int fileID)
-{
- int newID = m_ActiveDownloads.size();
- addNXMDownload(QString("nxm://%1/mods/%2/files/%3").arg(m_ManagedGame->gameShortName()).arg(modID).arg(fileID));
- return newID;
-}
-
-QString DownloadManager::downloadPath(int id)
-{
- return getFilePath(id);
-}
-
-int DownloadManager::indexByName(const QString &fileName) const
-{
- for (int i = 0; i < m_ActiveDownloads.size(); ++i) {
- if (m_ActiveDownloads[i]->m_FileName == fileName) {
- return i;
- }
- }
- return -1;
-}
-
-void DownloadManager::nxmDownloadURLsAvailable(QString gameName, int modID, int fileID, QVariant userData, QVariant resultData, int requestID)
-{
- std::set<int>::iterator idIter = m_RequestIDs.find(requestID);
- if (idIter == m_RequestIDs.end()) {
- return;
- } else {
- m_RequestIDs.erase(idIter);
- }
-
- ModRepositoryFileInfo *info = qobject_cast<ModRepositoryFileInfo*>(qvariant_cast<QObject*>(userData));
- QVariantList resultList = resultData.toList();
- if (resultList.length() == 0) {
- removePending(gameName, modID, fileID);
- emit showMessage(tr("No download server available. Please try again later."));
- return;
- }
-
- std::sort(resultList.begin(), resultList.end(), boost::bind(&DownloadManager::ServerByPreference, m_PreferredServers, _1, _2));
-
- info->userData["downloadMap"] = resultList;
-
- QStringList URLs;
-
- foreach (const QVariant &server, resultList) {
- URLs.append(server.toMap()["URI"].toString());
- }
- addDownload(URLs, gameName, modID, fileID, info);
-}
-
-
-void DownloadManager::nxmRequestFailed(QString gameName, int modID, int fileID, QVariant userData, int requestID, const QString &errorString)
-{
- std::set<int>::iterator idIter = m_RequestIDs.find(requestID);
- if (idIter == m_RequestIDs.end()) {
- return;
- } else {
- m_RequestIDs.erase(idIter);
- }
-
- int index = 0;
-
- for (QVector<DownloadInfo*>::iterator iter = m_ActiveDownloads.begin(); iter != m_ActiveDownloads.end(); ++iter, ++index) {
- DownloadInfo *info = *iter;
- if (info->m_FileInfo->modID == modID) {
- if (info->m_State < STATE_FETCHINGMODINFO) {
- m_ActiveDownloads.erase(iter);
- delete info;
- } else {
- setState(info, STATE_READY);
- }
- emit update(index);
- break;
- }
- }
-
- removePending(gameName, modID, fileID);
- emit showMessage(tr("Failed to request file info from nexus: %1").arg(errorString));
-}
-
-
-void DownloadManager::downloadFinished(int index)
-{
- DownloadInfo *info;
- if (index)
- info = m_ActiveDownloads[index];
- else
- info = findDownload(this->sender(), &index);
-
- if (info != nullptr) {
- QNetworkReply *reply = info->m_Reply;
- QByteArray data;
- if (reply->isOpen() && info->m_HasData) {
- data = reply->readAll();
- info->m_Output.write(data);
- }
- info->m_Output.close();
- TaskProgressManager::instance().forgetMe(info->m_TaskProgressId);
-
- bool error = false;
- if ((info->m_State != STATE_CANCELING) &&
- (info->m_State != STATE_PAUSING)) {
- bool textData = reply->header(QNetworkRequest::ContentTypeHeader).toString().startsWith("text", Qt::CaseInsensitive);
- if (textData)
- emit showMessage(tr("Warning: Content type is: %1").arg(reply->header(QNetworkRequest::ContentTypeHeader).toString()));
- if ((info->m_Output.size() == 0) ||
- ((reply->error() != QNetworkReply::NoError)
- && (reply->error() != QNetworkReply::OperationCanceledError))) {
- if (reply->error() == QNetworkReply::UnknownContentError)
- emit showMessage(tr("Download header content length: %1 downloaded file size: %2").arg(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong()).arg(info->m_Output.size()));
- if (info->m_Tries == 0) {
- emit showMessage(tr("Download failed: %1 (%2)").arg(reply->errorString()).arg(reply->error()));
- }
- error = true;
- setState(info, STATE_ERROR);
- }
- }
-
- if (info->m_State == STATE_CANCELING) {
- setState(info, STATE_CANCELED);
- } else if (info->m_State == STATE_PAUSING) {
- if (info->m_Output.isOpen() && info->m_HasData) {
- info->m_Output.write(info->m_Reply->readAll());
- }
- setState(info, STATE_PAUSED);
- }
-
- if (info->m_State == STATE_CANCELED || (info->m_Tries == 0 && error)) {
- emit aboutToUpdate();
- info->m_Output.remove();
- delete info;
- m_ActiveDownloads.erase(m_ActiveDownloads.begin() + index);
- if (error)
- emit showMessage(tr("We were unable to download the file due to errors after four retries. There may be an issue with the Nexus servers."));
- emit update(-1);
- } else if (info->isPausedState() || info->m_State == STATE_PAUSING) {
- info->m_Output.close();
- createMetaFile(info);
- emit update(index);
- } else {
- QString url = info->m_Urls[info->m_CurrentUrl];
- if (info->m_FileInfo->userData.contains("downloadMap")) {
- foreach (const QVariant &server, info->m_FileInfo->userData["downloadMap"].toList()) {
- QVariantMap serverMap = server.toMap();
- if (serverMap["URI"].toString() == url) {
- int deltaTime = info->m_StartTime.secsTo(QTime::currentTime());
- if (deltaTime > 5) {
- emit downloadSpeed(serverMap["Name"].toString(), (info->m_TotalSize - info->m_PreResumeSize) / deltaTime);
- } // no division by zero please! Also, if the download is shorter than a few seconds, the result is way to inprecise
- break;
- }
- }
- }
-
- bool isNexus = info->m_FileInfo->repository == "Nexus";
- // need to change state before changing the file name, otherwise .unfinished is appended
- if (isNexus) {
- setState(info, STATE_FETCHINGMODINFO);
- } else {
- setState(info, STATE_NOFETCH);
- }
-
- QString newName = getFileNameFromNetworkReply(reply);
- QString oldName = QFileInfo(info->m_Output).fileName();
-
- startDisableDirWatcher();
- if (!newName.isEmpty() && (oldName.isEmpty())) {
- info->setName(getDownloadFileName(newName), true);
- } else {
- info->setName(m_OutputDirectory + "/" + info->m_FileName, true); // don't rename but remove the ".unfinished" extension
- }
- endDisableDirWatcher();
-
- if (!isNexus) {
- setState(info, STATE_READY);
- }
-
- emit update(index);
- }
- reply->close();
- reply->deleteLater();
-
- if ((info->m_Tries > 0) && error) {
- --info->m_Tries;
- resumeDownloadInt(index);
- }
- } else {
- qWarning("no download index %d", index);
- }
-}
-
-
-void DownloadManager::downloadError(QNetworkReply::NetworkError error)
-{
- if (error != QNetworkReply::OperationCanceledError) {
- QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
- qWarning("%s (%d)", reply != nullptr ? qUtf8Printable(reply->errorString())
- : "Download error occured",
- error);
- }
-}
-
-
-void DownloadManager::metaDataChanged()
-{
- int index = 0;
-
- DownloadInfo *info = findDownload(this->sender(), &index);
- if (info != nullptr) {
- QString newName = getFileNameFromNetworkReply(info->m_Reply);
- if (!newName.isEmpty() && (info->m_FileName.isEmpty())) {
- startDisableDirWatcher();
- info->setName(getDownloadFileName(newName), true);
- endDisableDirWatcher();
- refreshAlphabeticalTranslation();
- if (!info->m_Output.isOpen() && !info->m_Output.open(QIODevice::WriteOnly | QIODevice::Append)) {
- reportError(tr("failed to re-open %1").arg(info->m_FileName));
- setState(info, STATE_CANCELING);
- }
- }
- } else {
- qWarning("meta data event for unknown download");
- }
-}
-
-void DownloadManager::directoryChanged(const QString&)
-{
- if(DownloadManager::m_DirWatcherDisabler==0)
- refreshList();
-}
-
-void DownloadManager::managedGameChanged(MOBase::IPluginGame const *managedGame)
-{
- m_ManagedGame = managedGame;
-}
-
-void DownloadManager::checkDownloadTimeout()
-{
- for (int i = 0; i < m_ActiveDownloads.size(); ++i) {
- if (m_ActiveDownloads[i]->m_StartTime.elapsed() - std::get<3>(m_ActiveDownloads[i]->m_SpeedDiff) > 5 * 1000 &&
- m_ActiveDownloads[i]->m_State == STATE_DOWNLOADING && m_ActiveDownloads[i]->m_Reply != nullptr &&
- m_ActiveDownloads[i]->m_Reply->isOpen()) {
- pauseDownload(i);
- downloadFinished(i);
- resumeDownload(i);
- }
- }
-}
-
-void DownloadManager::writeData(DownloadInfo *info)
-{
- if (info != nullptr) {
- qint64 ret = info->m_Output.write(info->m_Reply->readAll());
- if (ret < info->m_Reply->size()) {
- QString fileName = info->m_FileName; // m_FileName may be destroyed after setState
- setState(info, DownloadState::STATE_CANCELED);
- qCritical(QString("Unable to write download \"%2\" to drive (return %1)").arg(ret).arg(info->m_FileName).toLocal8Bit());
- reportError(tr("Unable to write download to drive (return %1).\n"
- "Check the drive's available storage.\n\n"
- "Canceling download \"%2\"...").arg(ret).arg(fileName));
- }
- }
-}
+/*
+Copyright (C) 2012 Sebastian Herbord. All rights reserved.
+
+This file is part of Mod Organizer.
+
+Mod Organizer is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+Mod Organizer is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Mod Organizer. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "downloadmanager.h"
+
+#include "nxmurl.h"
+#include "nexusinterface.h"
+#include "nxmaccessmanager.h"
+#include "iplugingame.h"
+#include "downloadmanager.h"
+#include <nxmurl.h>
+#include <taskprogressmanager.h>
+#include "utility.h"
+#include "selectiondialog.h"
+#include "bbcode.h"
+#include <utility.h>
+#include <report.h>
+
+#include <QTimer>
+#include <QFileInfo>
+#include <QRegExp>
+#include <QDirIterator>
+#include <QDesktopServices>
+#include <QInputDialog>
+#include <QMessageBox>
+#include <QCoreApplication>
+#include <QTextDocument>
+
+#include <boost/bind.hpp>
+#include <regex>
+
+
+using namespace MOBase;
+
+
+// TODO limit number of downloads, also display download during nxm requests, store modid/fileid with downloads
+
+
+static const char UNFINISHED[] = ".unfinished";
+
+unsigned int DownloadManager::DownloadInfo::s_NextDownloadID = 1U;
+int DownloadManager::m_DirWatcherDisabler = 0;
+
+
+DownloadManager::DownloadInfo *DownloadManager::DownloadInfo::createNew(const ModRepositoryFileInfo *fileInfo, const QStringList &URLs)
+{
+ DownloadInfo *info = new DownloadInfo;
+ info->m_DownloadID = s_NextDownloadID++;
+ info->m_StartTime.start();
+ info->m_PreResumeSize = 0LL;
+ info->m_Progress = std::make_pair<int, QString>(0, "0.0 B/s ");
+ info->m_ResumePos = 0;
+ info->m_FileInfo = new ModRepositoryFileInfo(*fileInfo);
+ info->m_Urls = URLs;
+ info->m_CurrentUrl = 0;
+ info->m_Tries = AUTOMATIC_RETRIES;
+ info->m_State = STATE_STARTED;
+ info->m_TaskProgressId = TaskProgressManager::instance().getId();
+ info->m_Reply = nullptr;
+
+ return info;
+}
+
+DownloadManager::DownloadInfo *DownloadManager::DownloadInfo::createFromMeta(const QString &filePath, bool showHidden, const QString outputDirectory)
+{
+ DownloadInfo *info = new DownloadInfo;
+
+ QString metaFileName = filePath + ".meta";
+ QFileInfo metaFileInfo(metaFileName);
+ if (QDir::fromNativeSeparators(metaFileInfo.path()).compare(QDir::fromNativeSeparators(outputDirectory), Qt::CaseInsensitive) != 0) return nullptr;
+ QSettings metaFile(metaFileName, QSettings::IniFormat);
+ if (!showHidden && metaFile.value("removed", false).toBool()) {
+ return nullptr;
+ } else {
+ info->m_Hidden = metaFile.value("removed", false).toBool();
+ }
+
+ QString fileName = QFileInfo(filePath).fileName();
+
+ if (fileName.endsWith(UNFINISHED)) {
+ info->m_FileName = fileName.mid(
+ 0, fileName.length() - static_cast<int>(strlen(UNFINISHED)));
+ info->m_State = STATE_PAUSED;
+ } else {
+ info->m_FileName = fileName;
+
+ if (metaFile.value("paused", false).toBool()) {
+ info->m_State = STATE_PAUSED;
+ } else if (metaFile.value("uninstalled", false).toBool()) {
+ info->m_State = STATE_UNINSTALLED;
+ } else if (metaFile.value("installed", false).toBool()) {
+ info->m_State = STATE_INSTALLED;
+ } else {
+ info->m_State = STATE_READY;
+ }
+ }
+
+ info->m_DownloadID = s_NextDownloadID++;
+ info->m_Output.setFileName(filePath);
+ info->m_TotalSize = QFileInfo(filePath).size();
+ info->m_PreResumeSize = info->m_TotalSize;
+ info->m_CurrentUrl = 0;
+ info->m_Urls = metaFile.value("url", "").toString().split(";");
+ info->m_Tries = 0;
+ info->m_TaskProgressId = TaskProgressManager::instance().getId();
+ QString gameName = metaFile.value("gameName", "").toString();
+ int modID = metaFile.value("modID", 0).toInt();
+ int fileID = metaFile.value("fileID", 0).toInt();
+ info->m_FileInfo = new ModRepositoryFileInfo(gameName, modID, fileID);
+ info->m_FileInfo->name = metaFile.value("name", "").toString();
+ if (info->m_FileInfo->name == "0") {
+ // bug in earlier version
+ info->m_FileInfo->name = "";
+ }
+ info->m_FileInfo->modName = metaFile.value("modName", "").toString();
+ info->m_FileInfo->gameName = gameName;
+ info->m_FileInfo->modID = modID;
+ info->m_FileInfo->fileID = fileID;
+ info->m_FileInfo->description = metaFile.value("description").toString();
+ info->m_FileInfo->version.parse(metaFile.value("version", "0").toString());
+ info->m_FileInfo->newestVersion.parse(metaFile.value("newestVersion", "0").toString());
+ info->m_FileInfo->categoryID = metaFile.value("category", 0).toInt();
+ info->m_FileInfo->fileCategory = metaFile.value("fileCategory", 0).toInt();
+ info->m_FileInfo->repository = metaFile.value("repository", "Nexus").toString();
+ info->m_FileInfo->userData = metaFile.value("userData").toMap();
+ info->m_Reply = nullptr;
+
+ return info;
+}
+
+void DownloadManager::startDisableDirWatcher()
+{
+ DownloadManager::m_DirWatcherDisabler++;
+}
+
+
+void DownloadManager::endDisableDirWatcher()
+{
+ if (DownloadManager::m_DirWatcherDisabler > 0)
+ {
+ if (DownloadManager::m_DirWatcherDisabler == 1)
+ QCoreApplication::processEvents();
+ DownloadManager::m_DirWatcherDisabler--;
+ }
+ else {
+ DownloadManager::m_DirWatcherDisabler = 0;
+ }
+}
+
+void DownloadManager::DownloadInfo::setName(QString newName, bool renameFile)
+{
+ QString oldMetaFileName = QString("%1.meta").arg(m_FileName);
+ m_FileName = QFileInfo(newName).fileName();
+ if ((m_State == DownloadManager::STATE_STARTED) ||
+ (m_State == DownloadManager::STATE_DOWNLOADING) ||
+ (m_State == DownloadManager::STATE_PAUSED)) {
+ newName.append(UNFINISHED);
+ oldMetaFileName = QString("%1%2.meta").arg(m_FileName).arg(UNFINISHED);
+ }
+ if (renameFile) {
+ if ((newName != m_Output.fileName()) && !m_Output.rename(newName)) {
+ reportError(tr("failed to rename \"%1\" to \"%2\"").arg(m_Output.fileName()).arg(newName));
+ return;
+ }
+
+ QFile metaFile(QFileInfo(newName).path() + "/" + oldMetaFileName);
+ if (metaFile.exists())
+ metaFile.rename(newName.mid(0).append(".meta"));
+ }
+ if (!m_Output.isOpen()) {
+ // can't set file name if it's open
+ m_Output.setFileName(newName);
+ }
+}
+
+bool DownloadManager::DownloadInfo::isPausedState()
+{
+ return m_State == STATE_PAUSED || m_State == STATE_ERROR;
+}
+
+QString DownloadManager::DownloadInfo::currentURL()
+{
+ return m_Urls[m_CurrentUrl];
+}
+
+
+DownloadManager::DownloadManager(NexusInterface *nexusInterface, QObject *parent)
+ : IDownloadManager(parent), m_NexusInterface(nexusInterface), m_DirWatcher(), m_ShowHidden(false)
+{
+ connect(&m_DirWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(directoryChanged(QString)));
+ m_TimeoutTimer.setSingleShot(false);
+ //connect(&m_TimeoutTimer, SIGNAL(timeout()), this, SLOT(checkDownloadTimeout()));
+ m_TimeoutTimer.start(5 * 1000);
+}
+
+
+DownloadManager::~DownloadManager()
+{
+ for (QVector<DownloadInfo*>::iterator iter = m_ActiveDownloads.begin(); iter != m_ActiveDownloads.end(); ++iter) {
+ delete *iter;
+ }
+ m_ActiveDownloads.clear();
+}
+
+
+bool DownloadManager::downloadsInProgress()
+{
+ for (QVector<DownloadInfo*>::iterator iter = m_ActiveDownloads.begin(); iter != m_ActiveDownloads.end(); ++iter) {
+ if ((*iter)->m_State < STATE_READY) {
+ return true;
+ }
+ }
+ return false;
+}
+
+bool DownloadManager::downloadsInProgressNoPause()
+{
+ for (QVector<DownloadInfo*>::iterator iter = m_ActiveDownloads.begin(); iter != m_ActiveDownloads.end(); ++iter) {
+ if ((*iter)->m_State < STATE_READY && (*iter)->m_State != STATE_PAUSED) {
+ return true;
+ }
+ }
+ return false;
+}
+
+
+void DownloadManager::pauseAll()
+{
+
+ // first loop: pause all downloads
+ for (int i = 0; i < m_ActiveDownloads.count(); ++i) {
+ if (m_ActiveDownloads[i]->m_State < STATE_READY) {
+ pauseDownload(i);
+ }
+ }
+
+ ::Sleep(100);
+
+ bool done = false;
+ QTime startTime = QTime::currentTime();
+ // further loops: busy waiting for all downloads to complete. This could be neater...
+ while (!done && (startTime.secsTo(QTime::currentTime()) < 5)) {
+ QCoreApplication::processEvents();
+ done = true;
+ foreach (DownloadInfo *info, m_ActiveDownloads) {
+ if ((info->m_State < STATE_CANCELED) ||
+ (info->m_State == STATE_FETCHINGFILEINFO) ||
+ (info->m_State == STATE_FETCHINGMODINFO)) {
+ done = false;
+ break;
+ }
+ }
+ if (!done) {
+ ::Sleep(100);
+ }
+ }
+
+}
+
+
+void DownloadManager::setOutputDirectory(const QString &outputDirectory)
+{
+ QStringList directories = m_DirWatcher.directories();
+ if (directories.length() != 0) {
+ m_DirWatcher.removePaths(directories);
+ }
+ m_OutputDirectory = QDir::fromNativeSeparators(outputDirectory);
+ refreshList();
+ m_DirWatcher.addPath(m_OutputDirectory);
+}
+
+
+void DownloadManager::setPreferredServers(const std::map<QString, int> &preferredServers)
+{
+ m_PreferredServers = preferredServers;
+}
+
+
+void DownloadManager::setSupportedExtensions(const QStringList &extensions)
+{
+ m_SupportedExtensions = extensions;
+ refreshList();
+}
+
+void DownloadManager::setShowHidden(bool showHidden)
+{
+ m_ShowHidden = showHidden;
+ refreshList();
+}
+
+void DownloadManager::setPluginContainer(PluginContainer *pluginContainer)
+{
+ m_NexusInterface->setPluginContainer(pluginContainer);
+}
+
+
+
+
+
+
+void DownloadManager::refreshList()
+{
+ try {
+ //avoid triggering other refreshes
+ startDisableDirWatcher();
+
+ int downloadsBefore = m_ActiveDownloads.size();
+
+ // remove finished downloads
+ for (QVector<DownloadInfo*>::iterator iter = m_ActiveDownloads.begin(); iter != m_ActiveDownloads.end();) {
+ if (((*iter)->m_State == STATE_READY) || ((*iter)->m_State == STATE_INSTALLED) || ((*iter)->m_State == STATE_UNINSTALLED)) {
+ delete *iter;
+ iter = m_ActiveDownloads.erase(iter);
+ } else {
+ ++iter;
+ }
+ }
+
+ QStringList nameFilters(m_SupportedExtensions);
+ foreach (const QString &extension, m_SupportedExtensions) {
+ nameFilters.append("*." + extension);
+ }
+
+ nameFilters.append(QString("*").append(UNFINISHED));
+ QDir dir(QDir::fromNativeSeparators(m_OutputDirectory));
+
+ // find orphaned meta files and delete them (sounds cruel but it's better for everyone)
+ QStringList orphans;
+ QStringList metaFiles = dir.entryList(QStringList() << "*.meta");
+ foreach (const QString &metaFile, metaFiles) {
+ QString baseFile = metaFile.left(metaFile.length() - 5);
+ if (!QFile::exists(dir.absoluteFilePath(baseFile))) {
+ orphans.append(dir.absoluteFilePath(metaFile));
+ }
+ }
+ if (orphans.size() > 0) {
+ qDebug("%d orphaned meta files will be deleted", orphans.size());
+ shellDelete(orphans, true);
+ }
+
+ // add existing downloads to list
+ foreach (QString file, dir.entryList(nameFilters, QDir::Files, QDir::Time)) {
+ bool Exists = false;
+ for (QVector<DownloadInfo*>::const_iterator Iter = m_ActiveDownloads.begin(); Iter != m_ActiveDownloads.end() && !Exists; ++Iter) {
+ if (QString::compare((*Iter)->m_FileName, file, Qt::CaseInsensitive) == 0) {
+ Exists = true;
+ } else if (QString::compare(QFileInfo((*Iter)->m_Output.fileName()).fileName(), file, Qt::CaseInsensitive) == 0) {
+ Exists = true;
+ }
+ }
+ if (Exists) {
+ continue;
+ }
+
+ QString fileName = QDir::fromNativeSeparators(m_OutputDirectory) + "/" + file;
+
+ DownloadInfo *info = DownloadInfo::createFromMeta(fileName, m_ShowHidden, m_OutputDirectory);
+ if (info != nullptr) {
+ m_ActiveDownloads.push_front(info);
+ }
+ }
+
+ //if (m_ActiveDownloads.size() != downloadsBefore) {
+ qDebug("Downloads after refresh: %d", m_ActiveDownloads.size());
+ //}
+ emit update(-1);
+
+ //let watcher trigger refreshes again
+ endDisableDirWatcher();
+
+ } catch (const std::bad_alloc&) {
+ reportError(tr("Memory allocation error (in refreshing directory)."));
+ }
+}
+
+
+bool DownloadManager::addDownload(const QStringList &URLs, QString gameName,
+ int modID, int fileID, const ModRepositoryFileInfo *fileInfo)
+{
+ QString fileName = QFileInfo(URLs.first()).fileName();
+ if (fileName.isEmpty()) {
+ fileName = "unknown";
+ }
+
+ QUrl preferredUrl = QUrl::fromEncoded(URLs.first().toLocal8Bit());
+ qDebug("selected download url: %s", qUtf8Printable(preferredUrl.toString()));
+ QNetworkRequest request(preferredUrl);
+ request.setHeader(QNetworkRequest::UserAgentHeader, m_NexusInterface->getAccessManager()->userAgent());
+ return addDownload(m_NexusInterface->getAccessManager()->get(request), URLs, fileName, gameName, modID, fileID, fileInfo);
+}
+
+
+bool DownloadManager::addDownload(QNetworkReply *reply, const ModRepositoryFileInfo *fileInfo)
+{
+ QString fileName = getFileNameFromNetworkReply(reply);
+ if (fileName.isEmpty()) {
+ fileName = "unknown";
+ }
+
+ return addDownload(reply, QStringList(reply->url().toString()), fileName, fileInfo->gameName, fileInfo->modID, fileInfo->fileID, fileInfo);
+}
+
+
+bool DownloadManager::addDownload(QNetworkReply *reply, const QStringList &URLs, const QString &fileName,
+ QString gameName, int modID, int fileID, const ModRepositoryFileInfo *fileInfo)
+{
+ // download invoked from an already open network reply (i.e. download link in the browser)
+ DownloadInfo *newDownload = DownloadInfo::createNew(fileInfo, URLs);
+
+ QString baseName = fileName;
+ if (!fileInfo->fileName.isEmpty()) {
+ baseName = fileInfo->fileName;
+ } else {
+ QString dispoName = getFileNameFromNetworkReply(reply);
+
+ if (!dispoName.isEmpty()) {
+ baseName = dispoName;
+ }
+ }
+
+ startDisableDirWatcher();
+ newDownload->setName(getDownloadFileName(baseName), false);
+ endDisableDirWatcher();
+
+ startDownload(reply, newDownload, false);
+// emit update(-1);
+ return true;
+}
+
+
+void DownloadManager::removePending(QString gameName, int modID, int fileID)
+{
+ emit aboutToUpdate();
+ for (auto iter : m_PendingDownloads) {
+ if (gameName.compare(std::get<0>(iter), Qt::CaseInsensitive) == 0 && (std::get<1>(iter) == modID) && (std::get<2>(iter) == fileID)) {
+ m_PendingDownloads.removeAt(m_PendingDownloads.indexOf(iter));
+ break;
+ }
+ }
+ emit update(-1);
+}
+
+
+void DownloadManager::startDownload(QNetworkReply *reply, DownloadInfo *newDownload, bool resume)
+{
+ reply->setReadBufferSize(1024 * 1024); // don't read more than 1MB at once to avoid memory troubles
+ newDownload->m_Reply = reply;
+ setState(newDownload, STATE_DOWNLOADING);
+ if (newDownload->m_Urls.count() == 0) {
+ newDownload->m_Urls = QStringList(reply->url().toString());
+ }
+
+ QIODevice::OpenMode mode = QIODevice::WriteOnly;
+ if (resume) {
+ mode |= QIODevice::Append;
+ }
+
+ newDownload->m_StartTime.start();
+ createMetaFile(newDownload);
+
+ if (!newDownload->m_Output.open(mode)) {
+ reportError(tr("failed to download %1: could not open output file: %2")
+ .arg(reply->url().toString()).arg(newDownload->m_Output.fileName()));
+ return;
+ }
+
+ connect(newDownload->m_Reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(downloadProgress(qint64, qint64)));
+ connect(newDownload->m_Reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(downloadError(QNetworkReply::NetworkError)));
+ connect(newDownload->m_Reply, SIGNAL(readyRead()), this, SLOT(downloadReadyRead()));
+ connect(newDownload->m_Reply, SIGNAL(metaDataChanged()), this, SLOT(metaDataChanged()));
+
+ if (!resume) {
+ newDownload->m_PreResumeSize = newDownload->m_Output.size();
+ removePending(newDownload->m_FileInfo->gameName, newDownload->m_FileInfo->modID, newDownload->m_FileInfo->fileID);
+
+ emit aboutToUpdate();
+ m_ActiveDownloads.append(newDownload);
+
+ emit update(-1);
+ emit downloadAdded();
+
+ if (QFile::exists(m_OutputDirectory + "/" + newDownload->m_FileName)) {
+ setState(newDownload, STATE_PAUSING);
+ QCoreApplication::processEvents();
+ if (QMessageBox::question(nullptr, tr("Download again?"), tr("A file with the same name \"%1\" has already been downloaded. "
+ "Do you want to download it again? The new file will receive a different name.").arg(newDownload->m_FileName),
+ QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) {
+ if (reply->isFinished())
+ setState(newDownload, STATE_CANCELED);
+ else
+ setState(newDownload, STATE_CANCELING);
+ } else {
+ startDisableDirWatcher();
+ newDownload->setName(getDownloadFileName(newDownload->m_FileName, true), true);
+ endDisableDirWatcher();
+ if (newDownload->m_State == STATE_PAUSED)
+ resumeDownload(indexByName(newDownload->m_FileName));
+ else
+ setState(newDownload, STATE_DOWNLOADING);
+ }
+ } else
+ connect(newDownload->m_Reply, SIGNAL(finished()), this, SLOT(downloadFinished()));
+
+
+ QCoreApplication::processEvents();
+
+ if (newDownload->m_State != STATE_DOWNLOADING &&
+ newDownload->m_State != STATE_READY &&
+ newDownload->m_State != STATE_FETCHINGMODINFO &&
+ reply->isFinished()) {
+ downloadFinished(indexByName(newDownload->m_FileName));
+ return;
+ }
+ } else
+ connect(newDownload->m_Reply, SIGNAL(finished()), this, SLOT(downloadFinished()));
+}
+
+
+void DownloadManager::addNXMDownload(const QString &url)
+{
+ NXMUrl nxmInfo(url);
+
+ QStringList validGames;
+ validGames.append(m_ManagedGame->gameShortName());
+ validGames.append(m_ManagedGame->validShortNames());
+ qDebug("add nxm download: %s", qUtf8Printable(url));
+ if (!validGames.contains(nxmInfo.game(), Qt::CaseInsensitive)) {
+ qDebug("download requested for wrong game (game: %s, url: %s)", qUtf8Printable(m_ManagedGame->gameShortName()), qUtf8Printable(nxmInfo.game()));
+ QMessageBox::information(nullptr, tr("Wrong Game"), tr("The download link is for a mod for \"%1\" but this instance of MO "
+ "has been set up for \"%2\".").arg(nxmInfo.game()).arg(m_ManagedGame->gameShortName()), QMessageBox::Ok);
+ return;
+ }
+
+ for (auto tuple : m_PendingDownloads) {
+ if (std::get<0>(tuple).compare(nxmInfo.game(), Qt::CaseInsensitive) == 0, std::get<1>(tuple) == nxmInfo.modId() && std::get<2>(tuple) == nxmInfo.fileId()) {
+ qDebug("download requested is already started (mod id: %s, file id: %s)", qUtf8Printable(QString(nxmInfo.modId())), qUtf8Printable(QString(nxmInfo.fileId())));
+ QMessageBox::information(nullptr, tr("Already Started"), tr("A download for this mod file has already been queued."), QMessageBox::Ok);
+ return;
+ }
+ }
+
+ for (DownloadInfo *download : m_ActiveDownloads) {
+ if (download->m_FileInfo->modID == nxmInfo.modId() && download->m_FileInfo->fileID == nxmInfo.fileId()) {
+ if (download->m_State == STATE_DOWNLOADING || download->m_State == STATE_PAUSED || download->m_State == STATE_STARTED) {
+ qDebug("download requested is already started (mod: %s, file: %s)", qUtf8Printable(QString(download->m_FileInfo->modID)),
+ qUtf8Printable(download->m_FileInfo->fileName));
+
+ QMessageBox::information(nullptr, tr("Already Started"), tr("There is already a download started for this file (mod: %1, file: %2).")
+ .arg(download->m_FileInfo->modName).arg(download->m_FileInfo->fileName), QMessageBox::Ok);
+ return;
+ }
+ }
+ }
+
+ emit aboutToUpdate();
+
+ m_PendingDownloads.append(std::make_tuple(nxmInfo.game(), nxmInfo.modId(), nxmInfo.fileId()));
+
+ emit update(-1);
+ emit downloadAdded();
+ m_RequestIDs.insert(m_NexusInterface->requestFileInfo(nxmInfo.game(), nxmInfo.modId(), nxmInfo.fileId(), this, nxmInfo.fileId(), ""));
+}
+
+
+void DownloadManager::removeFile(int index, bool deleteFile)
+{
+ //Avoid triggering refreshes from DirWatcher
+ startDisableDirWatcher();
+
+ if (index >= m_ActiveDownloads.size()) {
+ throw MyException(tr("remove: invalid download index %1").arg(index));
+ }
+
+ DownloadInfo *download = m_ActiveDownloads.at(index);
+ QString filePath = m_OutputDirectory + "/" + download->m_FileName;
+ if ((download->m_State == STATE_STARTED) ||
+ (download->m_State == STATE_DOWNLOADING)) {
+ // shouldn't have been possible
+ qCritical("tried to remove active download");
+ endDisableDirWatcher();
+ return;
+ }
+
+ if ((download->m_State == STATE_PAUSED) || (download->m_State == STATE_ERROR)) {
+ filePath = download->m_Output.fileName();
+ }
+
+ if (deleteFile) {
+ if (!shellDelete(QStringList(filePath), true)) {
+ reportError(tr("failed to delete %1").arg(filePath));
+ endDisableDirWatcher();
+ return;
+ }
+
+ QFile metaFile(filePath.append(".meta"));
+ if (metaFile.exists() && !shellDelete(QStringList(filePath), true)) {
+ reportError(tr("failed to delete meta file for %1").arg(filePath));
+ }
+ } else {
+ QSettings metaSettings(filePath.append(".meta"), QSettings::IniFormat);
+ if(!download->m_Hidden)
+ metaSettings.setValue("removed", true);
+ }
+
+ endDisableDirWatcher();
+}
+
+class LessThanWrapper
+{
+public:
+ LessThanWrapper(DownloadManager *manager) : m_Manager(manager) {}
+ bool operator()(int LHS, int RHS) {
+ return m_Manager->getFileName(LHS).compare(m_Manager->getFileName(RHS), Qt::CaseInsensitive) < 0;
+
+ }
+
+private:
+ DownloadManager *m_Manager;
+};
+
+
+bool DownloadManager::ByName(int LHS, int RHS)
+{
+ return m_ActiveDownloads[LHS]->m_FileName < m_ActiveDownloads[RHS]->m_FileName;
+}
+
+
+void DownloadManager::refreshAlphabeticalTranslation()
+{
+ m_AlphabeticalTranslation.clear();
+ int pos = 0;
+ for (QVector<DownloadInfo*>::iterator iter = m_ActiveDownloads.begin(); iter != m_ActiveDownloads.end(); ++iter, ++pos) {
+ m_AlphabeticalTranslation.push_back(pos);
+ }
+
+ qSort(m_AlphabeticalTranslation.begin(), m_AlphabeticalTranslation.end(), LessThanWrapper(this));
+}
+
+
+void DownloadManager::restoreDownload(int index)
+{
+
+ if (index < 0) {
+ DownloadState minState = STATE_READY ;
+ index = 0;
+
+ for (QVector<DownloadInfo*>::const_iterator iter = m_ActiveDownloads.begin(); iter != m_ActiveDownloads.end(); ++iter ) {
+
+ if ((*iter)->m_State >= minState) {
+ restoreDownload(index);
+ }
+ index++;
+ }
+ }
+ else {
+ if (index >= m_ActiveDownloads.size()) {
+ throw MyException(tr("restore: invalid download index: %1").arg(index));
+ }
+
+ DownloadInfo *download = m_ActiveDownloads.at(index);
+ if (download->m_Hidden) {
+ download->m_Hidden = false;
+
+ QString filePath = m_OutputDirectory + "/" + download->m_FileName;
+
+ //avoid dirWatcher triggering refreshes
+ startDisableDirWatcher();
+ QSettings metaSettings(filePath.append(".meta"), QSettings::IniFormat);
+ metaSettings.setValue("removed", false);
+
+ endDisableDirWatcher();
+ }
+ }
+}
+
+
+void DownloadManager::removeDownload(int index, bool deleteFile)
+{
+ try {
+ //avoid dirWatcher triggering refreshes
+ startDisableDirWatcher();
+
+ emit aboutToUpdate();
+
+ if (index < 0) {
+ bool removeAll = (index == -1);
+ DownloadState removeState = (index == -2 ? STATE_INSTALLED : STATE_UNINSTALLED);
+
+ index = 0;
+ for (QVector<DownloadInfo*>::iterator iter = m_ActiveDownloads.begin(); iter != m_ActiveDownloads.end();) {
+ DownloadState downloadState = (*iter)->m_State;
+ if ((removeAll && (downloadState >= STATE_READY)) ||
+ (removeState == downloadState)) {
+ removeFile(index, deleteFile);
+ delete *iter;
+ iter = m_ActiveDownloads.erase(iter);
+ } else {
+ ++iter;
+ ++index;
+ }
+ }
+ } else {
+ if (index >= m_ActiveDownloads.size()) {
+ reportError(tr("remove: invalid download index %1").arg(index));
+ //emit update(-1);
+ endDisableDirWatcher();
+ return;
+ }
+
+ removeFile(index, deleteFile);
+ delete m_ActiveDownloads.at(index);
+ m_ActiveDownloads.erase(m_ActiveDownloads.begin() + index);
+ }
+ emit update(-1);
+ endDisableDirWatcher();
+ } catch (const std::exception &e) {
+ qCritical("failed to remove download: %s", e.what());
+ }
+ refreshList();
+}
+
+
+void DownloadManager::cancelDownload(int index)
+{
+ if ((index < 0) || (index >= m_ActiveDownloads.size())) {
+ reportError(tr("cancel: invalid download index %1").arg(index));
+ return;
+ }
+
+ if (m_ActiveDownloads.at(index)->m_State == STATE_DOWNLOADING) {
+ setState(m_ActiveDownloads.at(index), STATE_CANCELING);
+ }
+}
+
+
+void DownloadManager::pauseDownload(int index)
+{
+ if ((index < 0) || (index >= m_ActiveDownloads.size())) {
+ reportError(tr("pause: invalid download index %1").arg(index));
+ return;
+ }
+
+ DownloadInfo *info = m_ActiveDownloads.at(index);
+
+ if (info->m_State == STATE_DOWNLOADING) {
+ if ((info->m_Reply != nullptr) && (info->m_Reply->isRunning())) {
+ setState(info, STATE_PAUSING);
+ } else {
+ setState(info, STATE_PAUSED);
+ }
+ } else if ((info->m_State == STATE_FETCHINGMODINFO) || (info->m_State == STATE_FETCHINGFILEINFO)) {
+ setState(info, STATE_READY);
+ }
+}
+
+void DownloadManager::resumeDownload(int index)
+{
+ if ((index < 0) || (index >= m_ActiveDownloads.size())) {
+ reportError(tr("resume: invalid download index %1").arg(index));
+ return;
+ }
+ DownloadInfo *info = m_ActiveDownloads[index];
+ info->m_Tries = AUTOMATIC_RETRIES;
+ resumeDownloadInt(index);
+}
+
+void DownloadManager::resumeDownloadInt(int index)
+{
+ if ((index < 0) || (index >= m_ActiveDownloads.size())) {
+ reportError(tr("resume (int): invalid download index %1").arg(index));
+ return;
+ }
+ DownloadInfo *info = m_ActiveDownloads[index];
+
+ // Check for finished download;
+ if (info->m_TotalSize <= info->m_Output.size() && info->m_Reply != nullptr
+ && info->m_Reply->isOpen() && info->m_Reply->isFinished() && info->m_State != STATE_ERROR) {
+ setState(info, STATE_DOWNLOADING);
+ downloadFinished(index);
+ return;
+ }
+
+ if (info->isPausedState() || info->m_State == STATE_PAUSING) {
+ if (info->m_State == STATE_PAUSING) {
+ if (info->m_Output.isOpen()) {
+ writeData(info);
+ if (info->m_State == STATE_PAUSING) {
+ setState(info, STATE_PAUSED);
+ }
+ }
+ }
+ if ((info->m_Urls.size() == 0)
+ || ((info->m_Urls.size() == 1) && (info->m_Urls[0].size() == 0))) {
+ emit showMessage(tr("No known download urls. Sorry, this download can't be resumed."));
+ return;
+ }
+ if (info->m_State == STATE_ERROR) {
+ info->m_CurrentUrl = (info->m_CurrentUrl + 1) % info->m_Urls.count();
+ }
+ qDebug("request resume from url %s", qUtf8Printable(info->currentURL()));
+ QNetworkRequest request(QUrl::fromEncoded(info->currentURL().toLocal8Bit()));
+ request.setHeader(QNetworkRequest::UserAgentHeader, m_NexusInterface->getAccessManager()->userAgent());
+ if (info->m_State != STATE_ERROR) {
+ info->m_ResumePos = info->m_Output.size();
+ QByteArray rangeHeader = "bytes=" + QByteArray::number(info->m_ResumePos) + "-";
+ request.setRawHeader("Range", rangeHeader);
+ }
+ std::get<0>(info->m_SpeedDiff) = 0;
+ std::get<1>(info->m_SpeedDiff) = 0;
+ std::get<2>(info->m_SpeedDiff) = 0;
+ std::get<3>(info->m_SpeedDiff) = 0;
+ std::get<4>(info->m_SpeedDiff) = 0;
+ qDebug("resume at %lld bytes", info->m_ResumePos);
+ startDownload(m_NexusInterface->getAccessManager()->get(request), info, true);
+ }
+ emit update(index);
+}
+
+
+DownloadManager::DownloadInfo *DownloadManager::downloadInfoByID(unsigned int id)
+{
+ auto iter = std::find_if(m_ActiveDownloads.begin(), m_ActiveDownloads.end(),
+ [id](DownloadInfo *info) { return info->m_DownloadID == id; });
+ if (iter != m_ActiveDownloads.end()) {
+ return *iter;
+ } else {
+ return nullptr;
+ }
+}
+
+
+void DownloadManager::queryInfo(int index)
+{
+ if ((index < 0) || (index >= m_ActiveDownloads.size())) {
+ reportError(tr("query: invalid download index %1").arg(index));
+ return;
+ }
+ DownloadInfo *info = m_ActiveDownloads[index];
+
+ if (info->m_FileInfo->repository != "Nexus") {
+ qWarning("re-querying file info is currently only possible with Nexus");
+ return;
+ }
+
+ if (info->m_State < DownloadManager::STATE_READY) {
+ // UI shouldn't allow this
+ return;
+ }
+
+ if (info->m_FileInfo->modID <= 0) {
+ QString fileName = getFileName(index);
+ QString ignore;
+ NexusInterface::interpretNexusFileName(fileName, ignore, info->m_FileInfo->modID, true);
+ if (info->m_FileInfo->modID < 0) {
+ bool ok = false;
+ int modId = QInputDialog::getInt(
+ nullptr, tr("Please enter the nexus mod id"), tr("Mod ID:"), 1, 1,
+ std::numeric_limits<int>::max(), 1, &ok);
+ // careful now: while the dialog was displayed, events were processed.
+ // the download list might have changed and our info-ptr invalidated.
+ if (ok)
+ m_ActiveDownloads[index]->m_FileInfo->modID = modId;
+ return;
+ }
+ }
+
+ if (info->m_FileInfo->gameName.size() == 0) {
+ SelectionDialog selection(tr("Please select the source game code for %1").arg(getFileName(index)));
+
+ std::vector<std::pair<QString, QString>> choices = m_NexusInterface->getGameChoices(m_ManagedGame);
+ for (auto choice : choices) {
+ selection.addChoice(choice.first, choice.second, choice.first);
+ }
+ if (selection.exec() == QDialog::Accepted) {
+ info->m_FileInfo->gameName = selection.getChoiceData().toString();
+ } else {
+ info->m_FileInfo->gameName = m_ManagedGame->gameShortName();
+ }
+ }
+ info->m_ReQueried = true;
+ setState(info, STATE_FETCHINGMODINFO);
+}
+
+void DownloadManager::visitOnNexus(int index)
+{
+ if ((index < 0) || (index >= m_ActiveDownloads.size())) {
+ reportError(tr("VisitNexus: invalid download index %1").arg(index));
+ return;
+ }
+ DownloadInfo *info = m_ActiveDownloads[index];
+
+ if (info->m_FileInfo->repository != "Nexus") {
+ qWarning("Visiting mod page is currently only possible with Nexus");
+ return;
+ }
+
+ if (info->m_State < DownloadManager::STATE_READY) {
+ // UI shouldn't allow this
+ return;
+ }
+ int modID = info->m_FileInfo->modID;
+
+ QString gameName = info->m_FileInfo->gameName;
+ if (modID > 0) {
+ QDesktopServices::openUrl(QUrl(m_NexusInterface->getModURL(modID, gameName)));
+ }
+ else {
+ emit showMessage(tr("Nexus ID for this Mod is unknown"));
+ }
+}
+
+void DownloadManager::openFile(int index)
+{
+ if ((index < 0) || (index >= m_ActiveDownloads.size())) {
+ reportError(tr("OpenFile: invalid download index %1").arg(index));
+ return;
+ }
+ QDir path = QDir(m_OutputDirectory);
+ if (path.exists(getFileName(index))) {
+
+ ::ShellExecuteW(nullptr, L"open", ToWString(QDir::toNativeSeparators(getFilePath(index))).c_str(), nullptr, nullptr, SW_SHOWNORMAL);
+ return;
+ }
+
+ ::ShellExecuteW(nullptr, L"explore", ToWString(QDir::toNativeSeparators(m_OutputDirectory)).c_str(), nullptr, nullptr, SW_SHOWNORMAL);
+ return;
+}
+
+void DownloadManager::openInDownloadsFolder(int index)
+{
+ if ((index < 0) || (index >= m_ActiveDownloads.size())) {
+ reportError(tr("OpenFileInDownloadsFolder: invalid download index %1").arg(index));
+ return;
+ }
+ QString params = "/select,\"";
+ QDir path = QDir(m_OutputDirectory);
+ if (path.exists(getFileName(index))) {
+ params = params + QDir::toNativeSeparators(getFilePath(index)) + "\"";
+
+ ::ShellExecuteW(nullptr, nullptr, L"explorer", ToWString(params).c_str(), nullptr, SW_SHOWNORMAL);
+ return;
+ }
+ else if (path.exists(getFileName(index) + ".unfinished")) {
+ params = params + QDir::toNativeSeparators(getFilePath(index)+".unfinished") + "\"";
+
+ ::ShellExecuteW(nullptr, nullptr, L"explorer", ToWString(params).c_str(), nullptr, SW_SHOWNORMAL);
+ return;
+ }
+
+ ::ShellExecuteW(nullptr, L"explore", ToWString(QDir::toNativeSeparators(m_OutputDirectory)).c_str(), nullptr, nullptr, SW_SHOWNORMAL);
+ return;
+}
+
+
+int DownloadManager::numTotalDownloads() const
+{
+ return m_ActiveDownloads.size();
+}
+
+int DownloadManager::numPendingDownloads() const
+{
+ return m_PendingDownloads.size();
+}
+
+std::tuple<QString, int, int> DownloadManager::getPendingDownload(int index)
+{
+ if ((index < 0) || (index >= m_PendingDownloads.size())) {
+ throw MyException(tr("get pending: invalid download index %1").arg(index));
+ }
+
+ return m_PendingDownloads.at(index);
+}
+
+QString DownloadManager::getFilePath(int index) const
+{
+ if ((index < 0) || (index >= m_ActiveDownloads.size())) {
+ throw MyException(tr("get path: invalid download index %1").arg(index));
+ }
+
+ return m_OutputDirectory + "/" + m_ActiveDownloads.at(index)->m_FileName;
+}
+
+QString DownloadManager::getFileTypeString(int fileType)
+{
+ switch (fileType) {
+ case 1: return tr("Main");
+ case 2: return tr("Update");
+ case 3: return tr("Optional");
+ case 4: return tr("Old");
+ case 5: return tr("Misc");
+ default: return tr("Unknown");
+ }
+}
+
+QString DownloadManager::getDisplayName(int index) const
+{
+ if ((index < 0) || (index >= m_ActiveDownloads.size())) {
+ throw MyException(tr("display name: invalid download index %1").arg(index));
+ }
+
+ DownloadInfo *info = m_ActiveDownloads.at(index);
+
+ QTextDocument doc;
+ if (!info->m_FileInfo->name.isEmpty()) {
+ doc.setHtml(info->m_FileInfo->name);
+ return QString("%1 (%2, v%3)").arg(doc.toPlainText())
+ .arg(getFileTypeString(info->m_FileInfo->fileCategory))
+ .arg(info->m_FileInfo->version.displayString());
+ } else {
+ doc.setHtml(info->m_FileName);
+ return doc.toPlainText();
+ }
+}
+
+QString DownloadManager::getFileName(int index) const
+{
+ if ((index < 0) || (index >= m_ActiveDownloads.size())) {
+ throw MyException(tr("file name: invalid download index %1").arg(index));
+ }
+
+ return m_ActiveDownloads.at(index)->m_FileName;
+}
+
+QDateTime DownloadManager::getFileTime(int index) const
+{
+ if ((index < 0) || (index >= m_ActiveDownloads.size())) {
+ throw MyException(tr("file time: invalid download index %1").arg(index));
+ }
+
+ DownloadInfo *info = m_ActiveDownloads.at(index);
+ if (!info->m_Created.isValid()) {
+ info->m_Created = QFileInfo(info->m_Output).created();
+ }
+
+ return info->m_Created;
+}
+
+qint64 DownloadManager::getFileSize(int index) const
+{
+ if ((index < 0) || (index >= m_ActiveDownloads.size())) {
+ throw MyException(tr("file size: invalid download index %1").arg(index));
+ }
+
+ return m_ActiveDownloads.at(index)->m_TotalSize;
+}
+
+
+std::pair<int, QString> DownloadManager::getProgress(int index) const
+{
+ if ((index < 0) || (index >= m_ActiveDownloads.size())) {
+ throw MyException(tr("progress: invalid download index %1").arg(index));
+ }
+
+ return m_ActiveDownloads.at(index)->m_Progress;
+}
+
+
+DownloadManager::DownloadState DownloadManager::getState(int index) const
+{
+ if ((index < 0) || (index >= m_ActiveDownloads.size())) {
+ throw MyException(tr("state: invalid download index %1").arg(index));
+ }
+
+ return m_ActiveDownloads.at(index)->m_State;
+}
+
+
+bool DownloadManager::isInfoIncomplete(int index) const
+{
+ if ((index < 0) || (index >= m_ActiveDownloads.size())) {
+ throw MyException(tr("infocomplete: invalid download index %1").arg(index));
+ }
+
+ DownloadInfo *info = m_ActiveDownloads.at(index);
+ if (info->m_FileInfo->repository != "Nexus") {
+ // other repositories currently don't support re-querying info anyway
+ return false;
+ }
+ return (info->m_FileInfo->fileID == 0) || (info->m_FileInfo->modID == 0);
+}
+
+
+int DownloadManager::getModID(int index) const
+{
+ if ((index < 0) || (index >= m_ActiveDownloads.size())) {
+ throw MyException(tr("mod id: invalid download index %1").arg(index));
+ }
+ return m_ActiveDownloads.at(index)->m_FileInfo->modID;
+}
+
+QString DownloadManager::getGameName(int index) const
+{
+ if ((index < 0) || (index >= m_ActiveDownloads.size())) {
+ throw MyException(tr("mod id: invalid download index %1").arg(index));
+ }
+ return m_ActiveDownloads.at(index)->m_FileInfo->gameName;
+}
+
+bool DownloadManager::isHidden(int index) const
+{
+ if ((index < 0) || (index >= m_ActiveDownloads.size())) {
+ throw MyException(tr("ishidden: invalid download index %1").arg(index));
+ }
+ return m_ActiveDownloads.at(index)->m_Hidden;
+}
+
+
+const ModRepositoryFileInfo *DownloadManager::getFileInfo(int index) const
+{
+ if ((index < 0) || (index >= m_ActiveDownloads.size())) {
+ throw MyException(tr("file info: invalid download index %1").arg(index));
+ }
+
+ return m_ActiveDownloads.at(index)->m_FileInfo;
+}
+
+
+void DownloadManager::markInstalled(int index)
+{
+ if ((index < 0) || (index >= m_ActiveDownloads.size())) {
+ throw MyException(tr("mark installed: invalid download index %1").arg(index));
+ }
+
+ //Avoid triggering refreshes from DirWatcher
+ startDisableDirWatcher();
+
+ DownloadInfo *info = m_ActiveDownloads.at(index);
+ QSettings metaFile(info->m_Output.fileName() + ".meta", QSettings::IniFormat);
+ metaFile.setValue("installed", true);
+ metaFile.setValue("uninstalled", false);
+
+ endDisableDirWatcher();
+
+ setState(m_ActiveDownloads.at(index), STATE_INSTALLED);
+}
+
+void DownloadManager::markInstalled(QString fileName)
+{
+ int index = indexByName(fileName);
+ if (index >= 0) {
+ markInstalled(index);
+ } else {
+ DownloadInfo *info = getDownloadInfo(fileName);
+ if (info != nullptr) {
+ //Avoid triggering refreshes from DirWatcher
+ startDisableDirWatcher();
+
+ QSettings metaFile(info->m_Output.fileName() + ".meta", QSettings::IniFormat);
+ metaFile.setValue("installed", true);
+ metaFile.setValue("uninstalled", false);
+ delete info;
+
+ endDisableDirWatcher();
+ }
+ }
+}
+
+DownloadManager::DownloadInfo* DownloadManager::getDownloadInfo(QString fileName)
+{
+ return DownloadInfo::createFromMeta(fileName, true, m_OutputDirectory);
+}
+
+void DownloadManager::markUninstalled(int index)
+{
+ if ((index < 0) || (index >= m_ActiveDownloads.size())) {
+ throw MyException(tr("mark uninstalled: invalid download index %1").arg(index));
+ }
+
+ //Avoid triggering refreshes from DirWatcher
+ startDisableDirWatcher();
+
+ DownloadInfo *info = m_ActiveDownloads.at(index);
+ QSettings metaFile(info->m_Output.fileName() + ".meta", QSettings::IniFormat);
+ metaFile.setValue("uninstalled", true);
+
+ endDisableDirWatcher();
+
+ setState(m_ActiveDownloads.at(index), STATE_UNINSTALLED);
+}
+
+
+void DownloadManager::markUninstalled(QString fileName)
+{
+ int index = indexByName(fileName);
+ if (index >= 0) {
+ markUninstalled(index);
+ } else {
+ QString filePath = QDir::fromNativeSeparators(m_OutputDirectory) + "/" + fileName;
+ DownloadInfo *info = getDownloadInfo(filePath);
+ if (info != nullptr) {
+
+ //Avoid triggering refreshes from DirWatcher
+ startDisableDirWatcher();
+
+ QSettings metaFile(info->m_Output.fileName() + ".meta", QSettings::IniFormat);
+ metaFile.setValue("uninstalled", true);
+ delete info;
+
+ endDisableDirWatcher();
+ }
+ }
+}
+
+
+QString DownloadManager::getDownloadFileName(const QString &baseName, bool rename) const
+{
+ QString fullPath = m_OutputDirectory + "/" + baseName;
+ if (QFile::exists(fullPath) && rename) {
+ int i = 1;
+ while (QFile::exists(QString("%1/%2_%3").arg(m_OutputDirectory).arg(i).arg(baseName))) {
+ ++i;
+ }
+
+ fullPath = QString("%1/%2_%3").arg(m_OutputDirectory).arg(i).arg(baseName);
+ }
+ return fullPath;
+}
+
+
+QString DownloadManager::getFileNameFromNetworkReply(QNetworkReply *reply)
+{
+ if (reply->hasRawHeader("Content-Disposition")) {
+ std::regex exp("filename=\"(.*)\"");
+
+ std::cmatch result;
+ if (std::regex_search(reply->rawHeader("Content-Disposition").constData(), result, exp)) {
+ return QString::fromUtf8(result.str(1).c_str());
+ }
+ }
+
+ return QString();
+}
+
+
+void DownloadManager::setState(DownloadManager::DownloadInfo *info, DownloadManager::DownloadState state)
+{
+ int row = 0;
+ for (int i = 0; i < m_ActiveDownloads.size(); ++i) {
+ if (m_ActiveDownloads[i] == info) {
+ row = i;
+ break;
+ }
+ }
+ info->m_State = state;
+ switch (state) {
+ case STATE_PAUSED:
+ case STATE_ERROR: {
+ info->m_Reply->abort();
+ info->m_Output.close();
+ } break;
+ case STATE_CANCELED: {
+ info->m_Reply->abort();
+ } break;
+ case STATE_FETCHINGMODINFO: {
+ m_RequestIDs.insert(m_NexusInterface->requestDescription(info->m_FileInfo->gameName, info->m_FileInfo->modID, this, info->m_DownloadID, QString()));
+ } break;
+ case STATE_FETCHINGFILEINFO: {
+ m_RequestIDs.insert(m_NexusInterface->requestFiles(info->m_FileInfo->gameName, info->m_FileInfo->modID, this, info->m_DownloadID, QString()));
+ } break;
+ case STATE_READY: {
+ createMetaFile(info);
+ emit downloadComplete(row);
+ } break;
+ default: /* NOP */ break;
+ }
+ emit stateChanged(row, state);
+}
+
+
+DownloadManager::DownloadInfo *DownloadManager::findDownload(QObject *reply, int *index) const
+{
+ // reverse search as newer, thus more relevant, downloads are at the end
+ for (int i = m_ActiveDownloads.size() - 1; i >= 0; --i) {
+ if (m_ActiveDownloads[i]->m_Reply == reply) {
+ if (index != nullptr) {
+ *index = i;
+ }
+ return m_ActiveDownloads[i];
+ }
+ }
+ return nullptr;
+}
+
+
+void DownloadManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
+{
+ if (bytesTotal == 0) {
+ return;
+ }
+ int index = 0;
+ try {
+ DownloadInfo *info = findDownload(this->sender(), &index);
+ if (info != nullptr) {
+ info->m_HasData = true;
+ if (info->m_State == STATE_CANCELING) {
+ setState(info, STATE_CANCELED);
+ } else if (info->m_State == STATE_PAUSING) {
+ setState(info, STATE_PAUSED);
+ }
+ else {
+ if (bytesTotal > info->m_TotalSize) {
+ info->m_TotalSize = bytesTotal;
+ }
+ int oldProgress = info->m_Progress.first;
+ info->m_Progress.first = ((info->m_ResumePos + bytesReceived) * 100) / (info->m_ResumePos + bytesTotal);
+
+ int elapsed = info->m_StartTime.elapsed();
+ std::get<0>(info->m_SpeedDiff) = bytesReceived - std::get<2>(info->m_SpeedDiff);
+ std::get<1>(info->m_SpeedDiff) = elapsed - std::get<3>(info->m_SpeedDiff);
+ std::get<2>(info->m_SpeedDiff) = bytesReceived;
+ std::get<3>(info->m_SpeedDiff) = elapsed;
+
+ double calc = ((double)std::get<0>(info->m_SpeedDiff)) / (((double)(std::get<1>(info->m_SpeedDiff)) / 5000.0));
+ std::get<4>(info->m_SpeedDiff) = ((calc*0.5) + (std::get<4>(info->m_SpeedDiff)*1.5)) / 2;
+
+ // calculate the download speed
+ double speed = (std::get<4>(info->m_SpeedDiff) * 1000.0) / (5 * 1000);
+
+ QString unit;
+ if (speed < 1000) {
+ unit = "B/s";
+ }
+ else if (speed < 1000*1024) {
+ speed /= 1024;
+ unit = "KB/s";
+ }
+ else {
+ speed /= 1024 * 1024;
+ unit = "MB/s";
+ }
+
+ info->m_Progress.second = QString::fromLatin1("%1% - %2 %3").arg(info->m_Progress.first).arg(QString::number(speed, 'f', 1)).arg(unit);
+
+ TaskProgressManager::instance().updateProgress(info->m_TaskProgressId, bytesReceived, bytesTotal);
+ emit update(index);
+ }
+ }
+ } catch (const std::bad_alloc&) {
+ reportError(tr("Memory allocation error (in processing progress event)."));
+ }
+}
+
+
+void DownloadManager::downloadReadyRead()
+{
+ try {
+ writeData(findDownload(this->sender()));
+ } catch (const std::bad_alloc&) {
+ reportError(tr("Memory allocation error (in processing downloaded data)."));
+ }
+}
+
+
+void DownloadManager::createMetaFile(DownloadInfo *info)
+{
+ //Avoid triggering refreshes from DirWatcher
+ startDisableDirWatcher();
+
+ QSettings metaFile(QString("%1.meta").arg(info->m_Output.fileName()), QSettings::IniFormat);
+ metaFile.setValue("gameName", info->m_FileInfo->gameName);
+ metaFile.setValue("modID", info->m_FileInfo->modID);
+ metaFile.setValue("fileID", info->m_FileInfo->fileID);
+ metaFile.setValue("url", info->m_Urls.join(";"));
+ metaFile.setValue("name", info->m_FileInfo->name);
+ metaFile.setValue("description", info->m_FileInfo->description);
+ metaFile.setValue("modName", info->m_FileInfo->modName);
+ metaFile.setValue("version", info->m_FileInfo->version.canonicalString());
+ metaFile.setValue("newestVersion", info->m_FileInfo->newestVersion.canonicalString());
+ metaFile.setValue("fileTime", info->m_FileInfo->fileTime);
+ metaFile.setValue("fileCategory", info->m_FileInfo->fileCategory);
+ metaFile.setValue("category", info->m_FileInfo->categoryID);
+ metaFile.setValue("repository", info->m_FileInfo->repository);
+ metaFile.setValue("userData", info->m_FileInfo->userData);
+ metaFile.setValue("installed", info->m_State == DownloadManager::STATE_INSTALLED);
+ metaFile.setValue("uninstalled", info->m_State == DownloadManager::STATE_UNINSTALLED);
+ metaFile.setValue("paused", (info->m_State == DownloadManager::STATE_PAUSED) ||
+ (info->m_State == DownloadManager::STATE_ERROR));
+ metaFile.setValue("removed", info->m_Hidden);
+
+ endDisableDirWatcher();
+ // slightly hackish...
+ for (int i = 0; i < m_ActiveDownloads.size(); ++i) {
+ if (m_ActiveDownloads[i] == info) {
+ emit update(i);
+ }
+ }
+}
+
+
+void DownloadManager::nxmDescriptionAvailable(QString, int, QVariant userData, QVariant resultData, int requestID)
+{
+ std::set<int>::iterator idIter = m_RequestIDs.find(requestID);
+ if (idIter == m_RequestIDs.end()) {
+ return;
+ } else {
+ m_RequestIDs.erase(idIter);
+ }
+
+ QVariantMap result = resultData.toMap();
+
+ DownloadInfo *info = downloadInfoByID(userData.toInt());
+ if (info == nullptr) return;
+ info->m_FileInfo->categoryID = result["category_id"].toInt();
+ QTextDocument doc;
+ doc.setHtml(result["name"].toString().trimmed());
+ info->m_FileInfo->modName = doc.toPlainText();
+ info->m_FileInfo->newestVersion.parse(result["version"].toString());
+ if (info->m_FileInfo->fileID != 0) {
+ setState(info, STATE_READY);
+ } else {
+ setState(info, STATE_FETCHINGFILEINFO);
+ }
+}
+
+void DownloadManager::nxmFilesAvailable(QString, int, QVariant userData, QVariant resultData, int requestID)
+{
+ std::set<int>::iterator idIter = m_RequestIDs.find(requestID);
+ if (idIter == m_RequestIDs.end()) {
+ return;
+ } else {
+ m_RequestIDs.erase(idIter);
+ }
+
+ DownloadInfo *info = downloadInfoByID(userData.toInt());
+ if (info == nullptr) return;
+
+ QVariantMap result = resultData.toMap();
+ QVariantList files = result["files"].toList();
+
+
+ // MO sometimes prepends <digit>_ to the filename in case of duplicate downloads.
+ // this may muck up the file name comparison
+ QString alternativeLocalName = info->m_FileName;
+
+ QRegExp expression("^\\d_(.*)$");
+ if (expression.indexIn(alternativeLocalName) == 0) {
+ alternativeLocalName = expression.cap(1);
+ }
+
+ bool found = false;
+
+ for (QVariant file : files) {
+ QVariantMap fileInfo = file.toMap();
+ QString fileName = fileInfo["file_name"].toString();
+ QString fileNameVariant = fileName.mid(0).replace(' ', '_');
+ if ((fileName == info->m_FileName) || (fileName == alternativeLocalName) ||
+ (fileNameVariant == info->m_FileName) || (fileNameVariant == alternativeLocalName)) {
+ info->m_FileInfo->name = fileInfo["name"].toString();
+ info->m_FileInfo->version.parse(fileInfo["version"].toString());
+ if (!info->m_FileInfo->version.isValid()) {
+ info->m_FileInfo->version = info->m_FileInfo->newestVersion;
+ }
+ info->m_FileInfo->fileCategory = fileInfo["category_id"].toInt();
+ info->m_FileInfo->fileTime = QDateTime::fromMSecsSinceEpoch(fileInfo["uploaded_timestamp"].toLongLong());
+ info->m_FileInfo->fileID = fileInfo["file_id"].toInt();
+ info->m_FileInfo->fileName = fileInfo["file_name"].toString();
+ info->m_FileInfo->description = BBCode::convertToHTML(fileInfo["changelog_html"].toString());
+ found = true;
+ break;
+ }
+ }
+
+ if (info->m_ReQueried) {
+ if (found) {
+ emit showMessage(tr("Information updated"));
+ } else if (result.count() == 0) {
+ emit showMessage(tr("No matching file found on Nexus! Maybe this file is no longer available or it was renamed?"));
+ } else {
+ SelectionDialog selection(tr("No file on Nexus matches the selected file by name. Please manually choose the correct one."));
+ for (QVariant file : result) {
+ QVariantMap fileInfo = file.toMap();
+ selection.addChoice(fileInfo["file_name"].toString(), "", file);
+ }
+ if (selection.exec() == QDialog::Accepted) {
+ QVariantMap fileInfo = selection.getChoiceData().toMap();
+ info->m_FileInfo->name = fileInfo["name"].toString();
+ info->m_FileInfo->version.parse(fileInfo["version"].toString());
+ info->m_FileInfo->fileCategory = fileInfo["category_id"].toInt();
+ info->m_FileInfo->fileID = fileInfo["file_id"].toInt();
+ } else {
+ emit showMessage(tr("No matching file found on Nexus! Maybe this file is no longer available or it was renamed?"));
+ }
+ }
+ } else {
+ if (info->m_FileInfo->fileID == 0) {
+ qWarning("could not determine file id for %s (state %d)",
+ qUtf8Printable(info->m_FileName), info->m_State);
+ }
+ }
+
+ setState(info, STATE_READY);
+}
+
+
+void DownloadManager::nxmFileInfoAvailable(QString gameName, int modID, int fileID, QVariant userData, QVariant resultData, int requestID)
+{
+ std::set<int>::iterator idIter = m_RequestIDs.find(requestID);
+ if (idIter == m_RequestIDs.end()) {
+ return;
+ } else {
+ m_RequestIDs.erase(idIter);
+ }
+
+ ModRepositoryFileInfo *info = new ModRepositoryFileInfo();
+
+ QVariantMap result = resultData.toMap();
+ info->name = result["name"].toString();
+ info->version.parse(result["version"].toString());
+ if (!info->version.isValid()) {
+ info->version = info->newestVersion;
+ }
+ info->fileName = result["file_name"].toString();
+ info->fileCategory = result["category_id"].toInt();
+ info->fileTime = QDateTime::fromMSecsSinceEpoch(result["uploaded_timestamp"].toLongLong());
+ info->description = BBCode::convertToHTML(result["changelog_html"].toString());
+
+ info->repository = "Nexus";
+ info->gameName = gameName;
+ info->modID = modID;
+ info->fileID = fileID;
+
+ QObject *test = info;
+ m_RequestIDs.insert(m_NexusInterface->requestDownloadURL(gameName, modID, fileID, this, qVariantFromValue(test), QString()));
+}
+
+static int evaluateFileInfoMap(const QVariantMap &map, const std::map<QString, int> &preferredServers)
+{
+ int result = 0;
+
+ auto preference = preferredServers.find(map["name"].toString());
+
+ if (preference != preferredServers.end()) {
+ result += 100 + preference->second * 20;
+ }
+
+ return result;
+}
+
+// sort function to sort by best download server
+bool DownloadManager::ServerByPreference(const std::map<QString, int> &preferredServers, const QVariant &LHS, const QVariant &RHS)
+{
+ return evaluateFileInfoMap(LHS.toMap(), preferredServers) > evaluateFileInfoMap(RHS.toMap(), preferredServers);
+}
+
+int DownloadManager::startDownloadURLs(const QStringList &urls)
+{
+ ModRepositoryFileInfo info;
+ addDownload(urls, "", -1, -1, &info);
+ return m_ActiveDownloads.size() - 1;
+}
+
+int DownloadManager::startDownloadNexusFile(int modID, int fileID)
+{
+ int newID = m_ActiveDownloads.size();
+ addNXMDownload(QString("nxm://%1/mods/%2/files/%3").arg(m_ManagedGame->gameShortName()).arg(modID).arg(fileID));
+ return newID;
+}
+
+QString DownloadManager::downloadPath(int id)
+{
+ return getFilePath(id);
+}
+
+int DownloadManager::indexByName(const QString &fileName) const
+{
+ for (int i = 0; i < m_ActiveDownloads.size(); ++i) {
+ if (m_ActiveDownloads[i]->m_FileName == fileName) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+void DownloadManager::nxmDownloadURLsAvailable(QString gameName, int modID, int fileID, QVariant userData, QVariant resultData, int requestID)
+{
+ std::set<int>::iterator idIter = m_RequestIDs.find(requestID);
+ if (idIter == m_RequestIDs.end()) {
+ return;
+ } else {
+ m_RequestIDs.erase(idIter);
+ }
+
+ ModRepositoryFileInfo *info = qobject_cast<ModRepositoryFileInfo*>(qvariant_cast<QObject*>(userData));
+ QVariantList resultList = resultData.toList();
+ if (resultList.length() == 0) {
+ removePending(gameName, modID, fileID);
+ emit showMessage(tr("No download server available. Please try again later."));
+ return;
+ }
+
+ std::sort(resultList.begin(), resultList.end(), boost::bind(&DownloadManager::ServerByPreference, m_PreferredServers, _1, _2));
+
+ info->userData["downloadMap"] = resultList;
+
+ QStringList URLs;
+
+ foreach (const QVariant &server, resultList) {
+ URLs.append(server.toMap()["URI"].toString());
+ }
+ addDownload(URLs, gameName, modID, fileID, info);
+}
+
+
+void DownloadManager::nxmRequestFailed(QString gameName, int modID, int fileID, QVariant userData, int requestID, QNetworkReply::NetworkError error, const QString &errorString)
+{
+ std::set<int>::iterator idIter = m_RequestIDs.find(requestID);
+ if (idIter == m_RequestIDs.end()) {
+ return;
+ } else {
+ m_RequestIDs.erase(idIter);
+ }
+
+ int index = 0;
+
+ for (QVector<DownloadInfo*>::iterator iter = m_ActiveDownloads.begin(); iter != m_ActiveDownloads.end(); ++iter, ++index) {
+ DownloadInfo *info = *iter;
+ if (info->m_FileInfo->modID == modID) {
+ if (info->m_State < STATE_FETCHINGMODINFO) {
+ m_ActiveDownloads.erase(iter);
+ delete info;
+ } else {
+ setState(info, STATE_READY);
+ }
+ emit update(index);
+ break;
+ }
+ }
+
+ removePending(gameName, modID, fileID);
+ emit showMessage(tr("Failed to request file info from nexus: %1").arg(errorString));
+}
+
+
+void DownloadManager::downloadFinished(int index)
+{
+ DownloadInfo *info;
+ if (index)
+ info = m_ActiveDownloads[index];
+ else
+ info = findDownload(this->sender(), &index);
+
+ if (info != nullptr) {
+ QNetworkReply *reply = info->m_Reply;
+ QByteArray data;
+ if (reply->isOpen() && info->m_HasData) {
+ data = reply->readAll();
+ info->m_Output.write(data);
+ }
+ info->m_Output.close();
+ TaskProgressManager::instance().forgetMe(info->m_TaskProgressId);
+
+ bool error = false;
+ if ((info->m_State != STATE_CANCELING) &&
+ (info->m_State != STATE_PAUSING)) {
+ bool textData = reply->header(QNetworkRequest::ContentTypeHeader).toString().startsWith("text", Qt::CaseInsensitive);
+ if (textData)
+ emit showMessage(tr("Warning: Content type is: %1").arg(reply->header(QNetworkRequest::ContentTypeHeader).toString()));
+ if ((info->m_Output.size() == 0) ||
+ ((reply->error() != QNetworkReply::NoError)
+ && (reply->error() != QNetworkReply::OperationCanceledError))) {
+ if (reply->error() == QNetworkReply::UnknownContentError)
+ emit showMessage(tr("Download header content length: %1 downloaded file size: %2").arg(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong()).arg(info->m_Output.size()));
+ if (info->m_Tries == 0) {
+ emit showMessage(tr("Download failed: %1 (%2)").arg(reply->errorString()).arg(reply->error()));
+ }
+ error = true;
+ setState(info, STATE_ERROR);
+ }
+ }
+
+ if (info->m_State == STATE_CANCELING) {
+ setState(info, STATE_CANCELED);
+ } else if (info->m_State == STATE_PAUSING) {
+ if (info->m_Output.isOpen() && info->m_HasData) {
+ info->m_Output.write(info->m_Reply->readAll());
+ }
+ setState(info, STATE_PAUSED);
+ }
+
+ if (info->m_State == STATE_CANCELED || (info->m_Tries == 0 && error)) {
+ emit aboutToUpdate();
+ info->m_Output.remove();
+ delete info;
+ m_ActiveDownloads.erase(m_ActiveDownloads.begin() + index);
+ if (error)
+ emit showMessage(tr("We were unable to download the file due to errors after four retries. There may be an issue with the Nexus servers."));
+ emit update(-1);
+ } else if (info->isPausedState() || info->m_State == STATE_PAUSING) {
+ info->m_Output.close();
+ createMetaFile(info);
+ emit update(index);
+ } else {
+ QString url = info->m_Urls[info->m_CurrentUrl];
+ if (info->m_FileInfo->userData.contains("downloadMap")) {
+ foreach (const QVariant &server, info->m_FileInfo->userData["downloadMap"].toList()) {
+ QVariantMap serverMap = server.toMap();
+ if (serverMap["URI"].toString() == url) {
+ int deltaTime = info->m_StartTime.secsTo(QTime::currentTime());
+ if (deltaTime > 5) {
+ emit downloadSpeed(serverMap["Name"].toString(), (info->m_TotalSize - info->m_PreResumeSize) / deltaTime);
+ } // no division by zero please! Also, if the download is shorter than a few seconds, the result is way to inprecise
+ break;
+ }
+ }
+ }
+
+ bool isNexus = info->m_FileInfo->repository == "Nexus";
+ // need to change state before changing the file name, otherwise .unfinished is appended
+ if (isNexus) {
+ setState(info, STATE_FETCHINGMODINFO);
+ } else {
+ setState(info, STATE_NOFETCH);
+ }
+
+ QString newName = getFileNameFromNetworkReply(reply);
+ QString oldName = QFileInfo(info->m_Output).fileName();
+
+ startDisableDirWatcher();
+ if (!newName.isEmpty() && (oldName.isEmpty())) {
+ info->setName(getDownloadFileName(newName), true);
+ } else {
+ info->setName(m_OutputDirectory + "/" + info->m_FileName, true); // don't rename but remove the ".unfinished" extension
+ }
+ endDisableDirWatcher();
+
+ if (!isNexus) {
+ setState(info, STATE_READY);
+ }
+
+ emit update(index);
+ }
+ reply->close();
+ reply->deleteLater();
+
+ if ((info->m_Tries > 0) && error) {
+ --info->m_Tries;
+ resumeDownloadInt(index);
+ }
+ } else {
+ qWarning("no download index %d", index);
+ }
+}
+
+
+void DownloadManager::downloadError(QNetworkReply::NetworkError error)
+{
+ if (error != QNetworkReply::OperationCanceledError) {
+ QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
+ qWarning("%s (%d)", reply != nullptr ? qUtf8Printable(reply->errorString())
+ : "Download error occured",
+ error);
+ }
+}
+
+
+void DownloadManager::metaDataChanged()
+{
+ int index = 0;
+
+ DownloadInfo *info = findDownload(this->sender(), &index);
+ if (info != nullptr) {
+ QString newName = getFileNameFromNetworkReply(info->m_Reply);
+ if (!newName.isEmpty() && (info->m_FileName.isEmpty())) {
+ startDisableDirWatcher();
+ info->setName(getDownloadFileName(newName), true);
+ endDisableDirWatcher();
+ refreshAlphabeticalTranslation();
+ if (!info->m_Output.isOpen() && !info->m_Output.open(QIODevice::WriteOnly | QIODevice::Append)) {
+ reportError(tr("failed to re-open %1").arg(info->m_FileName));
+ setState(info, STATE_CANCELING);
+ }
+ }
+ } else {
+ qWarning("meta data event for unknown download");
+ }
+}
+
+void DownloadManager::directoryChanged(const QString&)
+{
+ if(DownloadManager::m_DirWatcherDisabler==0)
+ refreshList();
+}
+
+void DownloadManager::managedGameChanged(MOBase::IPluginGame const *managedGame)
+{
+ m_ManagedGame = managedGame;
+}
+
+void DownloadManager::checkDownloadTimeout()
+{
+ for (int i = 0; i < m_ActiveDownloads.size(); ++i) {
+ if (m_ActiveDownloads[i]->m_StartTime.elapsed() - std::get<3>(m_ActiveDownloads[i]->m_SpeedDiff) > 5 * 1000 &&
+ m_ActiveDownloads[i]->m_State == STATE_DOWNLOADING && m_ActiveDownloads[i]->m_Reply != nullptr &&
+ m_ActiveDownloads[i]->m_Reply->isOpen()) {
+ pauseDownload(i);
+ downloadFinished(i);
+ resumeDownload(i);
+ }
+ }
+}
+
+void DownloadManager::writeData(DownloadInfo *info)
+{
+ if (info != nullptr) {
+ qint64 ret = info->m_Output.write(info->m_Reply->readAll());
+ if (ret < info->m_Reply->size()) {
+ QString fileName = info->m_FileName; // m_FileName may be destroyed after setState
+ setState(info, DownloadState::STATE_CANCELED);
+ qCritical(QString("Unable to write download \"%2\" to drive (return %1)").arg(ret).arg(info->m_FileName).toLocal8Bit());
+ reportError(tr("Unable to write download to drive (return %1).\n"
+ "Check the drive's available storage.\n\n"
+ "Canceling download \"%2\"...").arg(ret).arg(fileName));
+ }
+ }
+}
diff --git a/src/downloadmanager.h b/src/downloadmanager.h
index 4cbe31b7..3c36143e 100644
--- a/src/downloadmanager.h
+++ b/src/downloadmanager.h
@@ -1,568 +1,564 @@
-/*
-Copyright (C) 2012 Sebastian Herbord. All rights reserved.
-
-This file is part of Mod Organizer.
-
-Mod Organizer is free software: you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-Mod Organizer is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with Mod Organizer. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#ifndef DOWNLOADMANAGER_H
-#define DOWNLOADMANAGER_H
-
-#include <idownloadmanager.h>
-#include <modrepositoryfileinfo.h>
-#include <set>
-#include <QObject>
-#include <QUrl>
-#include <QQueue>
-#include <QFile>
-#include <QNetworkReply>
-#include <QTime>
-#include <QTimer>
-#include <QVector>
-#include <QMap>
-#include <QStringList>
-#include <QFileSystemWatcher>
-#include <QSettings>
-
-namespace MOBase { class IPluginGame; }
-
-class NexusInterface;
-class PluginContainer;
-
-/*!
- * \brief manages downloading of files and provides progress information for gui elements
- **/
-class DownloadManager : public MOBase::IDownloadManager
-{
- Q_OBJECT
-
-public:
-
- enum DownloadState {
- STATE_STARTED = 0,
- STATE_DOWNLOADING,
- STATE_CANCELING,
- STATE_PAUSING,
- STATE_CANCELED,
- STATE_PAUSED,
- STATE_ERROR,
- STATE_FETCHINGMODINFO,
- STATE_FETCHINGFILEINFO,
- STATE_NOFETCH,
- STATE_READY,
- STATE_INSTALLED,
- STATE_UNINSTALLED
- };
-
-private:
-
- struct DownloadInfo {
- ~DownloadInfo() { delete m_FileInfo; }
- unsigned int m_DownloadID;
- QString m_FileName;
- QFile m_Output;
- QNetworkReply *m_Reply;
- QTime m_StartTime;
- qint64 m_PreResumeSize;
- std::pair<int, QString> m_Progress;
- std::tuple<int, int, int, int, int> m_SpeedDiff;
- bool m_HasData;
- DownloadState m_State;
- int m_CurrentUrl;
- QStringList m_Urls;
- qint64 m_ResumePos;
- qint64 m_TotalSize;
- QDateTime m_Created; // used as a cache in DownloadManager::getFileTime, may not be valid elsewhere
-
- int m_Tries;
- bool m_ReQueried;
-
- quint32 m_TaskProgressId;
-
- MOBase::ModRepositoryFileInfo *m_FileInfo { nullptr };
-
- bool m_Hidden;
-
- static DownloadInfo *createNew(const MOBase::ModRepositoryFileInfo *fileInfo, const QStringList &URLs);
- static DownloadInfo *createFromMeta(const QString &filePath, bool showHidden, const QString outputDirectory);
-
- /**
- * @brief rename the file
- * this will change the file name as well as the display name. It will automatically
- * append .unfinished to the name if this file is still being downloaded
- * @param newName the new name to setName
- * @param renameFile if true, the file is assumed to exist and renamed. If the file does not
- * yet exist, set this to false
- **/
- void setName(QString newName, bool renameFile);
-
- unsigned int downloadID() { return m_DownloadID; }
-
- bool isPausedState();
-
- QString currentURL();
- private:
- static unsigned int s_NextDownloadID;
- private:
- DownloadInfo() : m_TotalSize(0), m_ReQueried(false), m_Hidden(false), m_SpeedDiff(std::tuple<int,int,int,int,int>(0,0,0,0,0)), m_HasData(false) {}
- };
-
-public:
-
- /**
- * @brief constructor
- *
- * @param nexusInterface interface to use to retrieve information from the relevant nexus page
- * @param parent parent object
- **/
- explicit DownloadManager(NexusInterface *nexusInterface, QObject *parent);
-
- ~DownloadManager();
-
- /**
- * @brief determine if a download is currently in progress
- *
- * @return true if there is currently a download in progress
- **/
- bool downloadsInProgress();
-
- /**
- * @brief determine if a download is currently in progress, does not count paused ones.
- *
- * @return true if there is currently a download in progress (that is not paused already).
- **/
- bool downloadsInProgressNoPause();
-
- /**
- * @brief set the output directory to write to
- *
- * @param outputDirectory the new output directory
- **/
- void setOutputDirectory(const QString &outputDirectory);
-
- /**
- * @brief disables feedback from the downlods fileSystemWhatcher untill disableDownloadsWatcherEnd() is called
- *
- **/
- static void startDisableDirWatcher();
-
- /**
- * @brief re-enables feedback from the downlods fileSystemWhatcher after disableDownloadsWatcherStart() was called
- **/
- static void endDisableDirWatcher();
-
- /**
- * @return current download directory
- **/
- QString getOutputDirectory() const { return m_OutputDirectory; }
-
- /**
- * @brief setPreferredServers set the list of preferred servers
- */
- void setPreferredServers(const std::map<QString, int> &preferredServers);
-
- /**
- * @brief set the list of supported extensions
- * @param extensions list of supported extensions
- */
- void setSupportedExtensions(const QStringList &extensions);
-
- /**
- * @brief sets whether hidden files are to be shown after all
- */
- void setShowHidden(bool showHidden);
-
- void setPluginContainer(PluginContainer *pluginContainer);
-
- /**
- * @brief download from an already open network connection
- *
- * @param reply the network reply to download from
- * @param fileInfo information about the file, like mod id, file id, version, ...
- * @return true if the download was started, false if it wasn't. The latter currently only happens if there is a duplicate and the user decides not to download again
- **/
- bool addDownload(QNetworkReply *reply, const MOBase::ModRepositoryFileInfo *fileInfo);
-
- /**
- * @brief download from an already open network connection
- *
- * @param reply the network reply to download from
- * @param fileName the name to use for the file. This may be overridden by the name in the fileInfo-structure or if the http stream specifies a name
- * @param fileInfo information previously retrieved from the nexus network
- * @return true if the download was started, false if it wasn't. The latter currently only happens if there is a duplicate and the user decides not to download again
- **/
- bool addDownload(QNetworkReply *reply, const QStringList &URLs, const QString &fileName, QString gameName, int modID, int fileID = 0, const MOBase::ModRepositoryFileInfo *fileInfo = new MOBase::ModRepositoryFileInfo());
-
- /**
- * @brief start a download using a nxm-link
- *
- * starts a download using a nxm-link. The download manager will first query the nexus
- * page for file information.
- * @param url a nxm link looking like this: nxm://skyrim/mods/1234/files/4711
- * @todo the game name encoded into the link is currently ignored, all downloads are incorrectly assumed to be for the identified game
- **/
- void addNXMDownload(const QString &url);
-
- /**
- * @brief retrieve the total number of downloads, both finished and unfinished including downloads from previous sessions
- *
- * @return total number of downloads
- **/
- int numTotalDownloads() const;
-
- /**
- * @brief retrieve number of pending downloads (nexus downloads for which we don't know the name and url yet)
- * @return number of pending downloads
- */
- int numPendingDownloads() const;
-
- /**
- * @brief retrieve the info of a pending download
- * @param index index of the pending download (index in the range [0, numPendingDownloads()[)
- * @return pair of modid, fileid
- */
- std::tuple<QString, int, int> getPendingDownload(int index);
-
- /**
- * @brief retrieve the full path to the download specified by index
- *
- * @param index the index to look up
- * @return absolute path of the file
- **/
- QString getFilePath(int index) const;
-
- /**
- * @brief retrieve a descriptive name of the download specified by index
- *
- * @param index index of the file to look up
- * @return display name of the file
- **/
- QString getDisplayName(int index) const;
-
- /**
- * @brief retrieve the filename of the download specified by index
- *
- * @param index index of the file to look up
- * @return name of the file
- **/
- QString getFileName(int index) const;
-
- /**
- * @brief retrieve the file size of the download specified by index
- *
- * @param index index of the file to look up
- * @return size of the file (total size during download)
- */
- qint64 getFileSize(int index) const;
-
- /**
- * @brief retrieve the creation time of the download specified by index
- * @param index index of the file to look up
- * @return size of the file (total size during download)
- */
- QDateTime getFileTime(int index) const;
-
- /**
- * @brief retrieve the current progress of the download specified by index
- *
- * @param index index of the file to look up
- * @return progress of the download in percent (integer)
- **/
- std::pair<int, QString> getProgress(int index) const;
-
- /**
- * @brief retrieve the current state of the download
- *
- * retrieve the current state of the download. A download usually goes through
- * the following states:
- * started -> downloading -> fetching mod info -> fetching file info -> done
- * in case of downloads started via nxm-link, file information is fetched first
- *
- * @param index index of the file to look up
- * @return the download state
- **/
- DownloadState getState(int index) const;
-
- /**
- * @param index index of the file to look up
- * @return true if the nexus information for this download is not complete
- **/
- bool isInfoIncomplete(int index) const;
-
- /**
- * @brief retrieve the nexus mod id of the download specified by index
- *
- * @param index index of the file to look up
- * @return the nexus mod id
- **/
- int getModID(int index) const;
-
- /**
- * @brief retrieve the game name of the downlaod specified by the index
- *
- * @param index index of the file to look up
- * @return the game name
- **/
- QString getGameName(int index) const;
-
- /**
- * @brief determine if the specified file is supposed to be hidden
- * @param index index of the file to look up
- * @return true if the specified file is supposed to be hidden
- */
- bool isHidden(int index) const;
-
- /**
- * @brief retrieve all nexus info of the download specified by index
- *
- * @param index index of the file to look up
- * @return the nexus mod information
- **/
- const MOBase::ModRepositoryFileInfo *getFileInfo(int index) const;
-
- /**
- * @brief mark a download as installed
- *
- * @param index index of the file to mark installed
- */
- void markInstalled(int index);
-
- void markInstalled(QString download);
-
- /**
- * @brief mark a download as uninstalled
- *
- * @param index index of the file to mark uninstalled
- */
- void markUninstalled(int index);
-
- void markUninstalled(QString download);
-
- /**
- * @brief refreshes the list of downloads
- */
- void refreshList();
-
- /**
- * @brief Sort function for download servers
- * @param LHS
- * @param RHS
- * @return
- */
- static bool ServerByPreference(const std::map<QString, int> &preferredServers, const QVariant &LHS, const QVariant &RHS);
-
-
- virtual int startDownloadURLs(const QStringList &urls);
-
- virtual int startDownloadNexusFile(int modID, int fileID);
-
- virtual QString downloadPath(int id);
-
- /**
- * @brief retrieve a download index from the filename
- * @param fileName file to look up
- * @return index of that download or -1 if it wasn't found
- */
- int indexByName(const QString &fileName) const;
-
- void pauseAll();
-
-signals:
-
- void aboutToUpdate();
-
- /**
- * @brief signals that the specified download has changed
- *
- * @param row the row that changed. This corresponds to the download index
- **/
- void update(int row);
-
- /**
- * @brief signals the ui that a message should be displayed
- *
- * @param message the message to display
- **/
- void showMessage(const QString &message);
-
- /**
- * @brief emitted whenever the state of a download changes
- * @param row the row that changed
- * @param state the new state
- */
- void stateChanged(int row, DownloadManager::DownloadState state);
-
- /**
- * @brief emitted whenever a download completes successfully, reporting the download speed for the server used
- */
- void downloadSpeed(const QString &serverName, int bytesPerSecond);
-
- /**
- * @brief emitted whenever a new download is added to the list
- */
- void downloadAdded();
-
-public slots:
-
- /**
- * @brief removes the specified download
- *
- * @param index index of the download to remove
- * @param deleteFile if true, the file will also be deleted from disc, otherwise it is only marked as hidden.
- **/
- void removeDownload(int index, bool deleteFile);
-
- /**
- * @brief restores the specified download to view (which was previously hidden
- * @param index index of the download to restore
- */
- void restoreDownload(int index);
-
- /**
- * @brief cancel the specified download. This will lead to the corresponding file to be deleted
- *
- * @param index index of the download to cancel
- **/
- void cancelDownload(int index);
-
- void pauseDownload(int index);
-
- void resumeDownload(int index);
-
- void queryInfo(int index);
-
- void visitOnNexus(int index);
-
- void openFile(int index);
-
- void openInDownloadsFolder(int index);
-
- void nxmDescriptionAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID);
-
- void nxmFilesAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID);
-
- void nxmFileInfoAvailable(QString gameName, int modID, int fileID, QVariant userData, QVariant resultData, int requestID);
-
- void nxmDownloadURLsAvailable(QString gameName, int modID, int fileID, QVariant userData, QVariant resultData, int requestID);
-
- void nxmRequestFailed(QString gameName, int modID, int fileID, QVariant userData, int requestID, const QString &errorString);
-
- void managedGameChanged(MOBase::IPluginGame const *gamePlugin);
-
-private slots:
-
- void downloadProgress(qint64 bytesReceived, qint64 bytesTotal);
- void downloadReadyRead();
- void downloadFinished(int index = 0);
- void downloadError(QNetworkReply::NetworkError error);
- void metaDataChanged();
- void directoryChanged(const QString &dirctory);
- void checkDownloadTimeout();
-
-private:
-
- void createMetaFile(DownloadInfo *info);
- DownloadManager::DownloadInfo* getDownloadInfo(QString fileName);
-
-public:
-
- /** Get a unique filename for a download.
- *
- * This allows you multiple versions of download files, useful if the file
- * comes from a web site with no version control
- *
- * @param basename: Name of the file
- *
- * @return Unique(ish) name
- */
- QString getDownloadFileName(const QString &baseName, bool rename = false) const;
-
-private:
-
- void startDownload(QNetworkReply *reply, DownloadInfo *newDownload, bool resume);
- void resumeDownloadInt(int index);
-
- /**
- * @brief start a download from a url
- *
- * @param url the url to download from
- * @param fileInfo information previously retrieved from the mod page
- * @return true if the download was started, false if it wasn't. The latter currently only happens if there is a duplicate and the user decides not to download again
- **/
- bool addDownload(const QStringList &URLs, QString gameName, int modID, int fileID, const MOBase::ModRepositoryFileInfo *fileInfo);
-
- // important: the caller has to lock the list-mutex, otherwise the DownloadInfo-pointer might get invalidated at any time
- DownloadInfo *findDownload(QObject *reply, int *index = nullptr) const;
-
- void removeFile(int index, bool deleteFile);
-
- void refreshAlphabeticalTranslation();
-
- bool ByName(int LHS, int RHS);
-
- QString getFileNameFromNetworkReply(QNetworkReply *reply);
-
- void setState(DownloadInfo *info, DownloadManager::DownloadState state);
-
- DownloadInfo *downloadInfoByID(unsigned int id);
-
- QDateTime matchDate(const QString &timeString);
-
- void removePending(QString gameName, int modID, int fileID);
-
- static QString getFileTypeString(int fileType);
-
- void writeData(DownloadInfo *info);
-
-private:
-
- static const int AUTOMATIC_RETRIES = 3;
-
-private:
-
- NexusInterface *m_NexusInterface;
-
- QVector<std::tuple<QString, int, int>> m_PendingDownloads;
-
- QVector<DownloadInfo*> m_ActiveDownloads;
-
- QString m_OutputDirectory;
- std::map<QString, int> m_PreferredServers;
- QStringList m_SupportedExtensions;
- std::set<int> m_RequestIDs;
- QVector<int> m_AlphabeticalTranslation;
-
- QFileSystemWatcher m_DirWatcher;
-
- //The dirWatcher is actually triggering off normal Mo operations such as deleting downloads or editing .meta files
- //so it needs to be disabled during operations that are known to cause the creation or deletion of files in the Downloads folder.
- //Notably using QSettings to edit a file creates a temporarily .lock file that causes the Watcher to trigger multiple listRefreshes freezing the ui.
- static int m_DirWatcherDisabler;
-
-
- std::map<QString, int> m_DownloadFails;
-
- bool m_ShowHidden;
-
- QRegExp m_DateExpression;
-
- MOBase::IPluginGame const *m_ManagedGame;
-
- QTimer m_TimeoutTimer;
-};
-
-
-
-#endif // DOWNLOADMANAGER_H
+/*
+Copyright (C) 2012 Sebastian Herbord. All rights reserved.
+
+This file is part of Mod Organizer.
+
+Mod Organizer is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+Mod Organizer is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Mod Organizer. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef DOWNLOADMANAGER_H
+#define DOWNLOADMANAGER_H
+
+#include <idownloadmanager.h>
+#include <modrepositoryfileinfo.h>
+#include <set>
+#include <QObject>
+#include <QUrl>
+#include <QQueue>
+#include <QFile>
+#include <QNetworkReply>
+#include <QTime>
+#include <QTimer>
+#include <QVector>
+#include <QMap>
+#include <QStringList>
+#include <QFileSystemWatcher>
+#include <QSettings>
+
+namespace MOBase { class IPluginGame; }
+
+class NexusInterface;
+class PluginContainer;
+
+/*!
+ * \brief manages downloading of files and provides progress information for gui elements
+ **/
+class DownloadManager : public MOBase::IDownloadManager
+{
+ Q_OBJECT
+
+public:
+
+ enum DownloadState {
+ STATE_STARTED = 0,
+ STATE_DOWNLOADING,
+ STATE_CANCELING,
+ STATE_PAUSING,
+ STATE_CANCELED,
+ STATE_PAUSED,
+ STATE_ERROR,
+ STATE_FETCHINGMODINFO,
+ STATE_FETCHINGFILEINFO,
+ STATE_NOFETCH,
+ STATE_READY,
+ STATE_INSTALLED,
+ STATE_UNINSTALLED
+ };
+
+private:
+
+ struct DownloadInfo {
+ ~DownloadInfo() { delete m_FileInfo; }
+ unsigned int m_DownloadID;
+ QString m_FileName;
+ QFile m_Output;
+ QNetworkReply *m_Reply;
+ QTime m_StartTime;
+ qint64 m_PreResumeSize;
+ std::pair<int, QString> m_Progress;
+ std::tuple<int, int, int, int, int> m_SpeedDiff;
+ bool m_HasData;
+ DownloadState m_State;
+ int m_CurrentUrl;
+ QStringList m_Urls;
+ qint64 m_ResumePos;
+ qint64 m_TotalSize;
+ QDateTime m_Created; // used as a cache in DownloadManager::getFileTime, may not be valid elsewhere
+
+ int m_Tries;
+ bool m_ReQueried;
+
+ quint32 m_TaskProgressId;
+
+ MOBase::ModRepositoryFileInfo *m_FileInfo { nullptr };
+
+ bool m_Hidden;
+
+ static DownloadInfo *createNew(const MOBase::ModRepositoryFileInfo *fileInfo, const QStringList &URLs);
+ static DownloadInfo *createFromMeta(const QString &filePath, bool showHidden, const QString outputDirectory);
+
+ /**
+ * @brief rename the file
+ * this will change the file name as well as the display name. It will automatically
+ * append .unfinished to the name if this file is still being downloaded
+ * @param newName the new name to setName
+ * @param renameFile if true, the file is assumed to exist and renamed. If the file does not
+ * yet exist, set this to false
+ **/
+ void setName(QString newName, bool renameFile);
+
+ unsigned int downloadID() { return m_DownloadID; }
+
+ bool isPausedState();
+
+ QString currentURL();
+ private:
+ static unsigned int s_NextDownloadID;
+ private:
+ DownloadInfo() : m_TotalSize(0), m_ReQueried(false), m_Hidden(false), m_SpeedDiff(std::tuple<int,int,int,int,int>(0,0,0,0,0)), m_HasData(false) {}
+ };
+
+public:
+
+ /**
+ * @brief constructor
+ *
+ * @param nexusInterface interface to use to retrieve information from the relevant nexus page
+ * @param parent parent object
+ **/
+ explicit DownloadManager(NexusInterface *nexusInterface, QObject *parent);
+
+ ~DownloadManager();
+
+ /**
+ * @brief determine if a download is currently in progress
+ *
+ * @return true if there is currently a download in progress
+ **/
+ bool downloadsInProgress();
+
+ /**
+ * @brief determine if a download is currently in progress, does not count paused ones.
+ *
+ * @return true if there is currently a download in progress (that is not paused already).
+ **/
+ bool downloadsInProgressNoPause();
+
+ /**
+ * @brief set the output directory to write to
+ *
+ * @param outputDirectory the new output directory
+ **/
+ void setOutputDirectory(const QString &outputDirectory);
+
+ /**
+ * @brief disables feedback from the downlods fileSystemWhatcher untill disableDownloadsWatcherEnd() is called
+ *
+ **/
+ static void startDisableDirWatcher();
+
+ /**
+ * @brief re-enables feedback from the downlods fileSystemWhatcher after disableDownloadsWatcherStart() was called
+ **/
+ static void endDisableDirWatcher();
+
+ /**
+ * @return current download directory
+ **/
+ QString getOutputDirectory() const { return m_OutputDirectory; }
+
+ /**
+ * @brief setPreferredServers set the list of preferred servers
+ */
+ void setPreferredServers(const std::map<QString, int> &preferredServers);
+
+ /**
+ * @brief set the list of supported extensions
+ * @param extensions list of supported extensions
+ */
+ void setSupportedExtensions(const QStringList &extensions);
+
+ /**
+ * @brief sets whether hidden files are to be shown after all
+ */
+ void setShowHidden(bool showHidden);
+
+ void setPluginContainer(PluginContainer *pluginContainer);
+
+ /**
+ * @brief download from an already open network connection
+ *
+ * @param reply the network reply to download from
+ * @param fileInfo information about the file, like mod id, file id, version, ...
+ * @return true if the download was started, false if it wasn't. The latter currently only happens if there is a duplicate and the user decides not to download again
+ **/
+ bool addDownload(QNetworkReply *reply, const MOBase::ModRepositoryFileInfo *fileInfo);
+
+ /**
+ * @brief download from an already open network connection
+ *
+ * @param reply the network reply to download from
+ * @param fileName the name to use for the file. This may be overridden by the name in the fileInfo-structure or if the http stream specifies a name
+ * @param fileInfo information previously retrieved from the nexus network
+ * @return true if the download was started, false if it wasn't. The latter currently only happens if there is a duplicate and the user decides not to download again
+ **/
+ bool addDownload(QNetworkReply *reply, const QStringList &URLs, const QString &fileName, QString gameName, int modID, int fileID = 0, const MOBase::ModRepositoryFileInfo *fileInfo = new MOBase::ModRepositoryFileInfo());
+
+ /**
+ * @brief start a download using a nxm-link
+ *
+ * starts a download using a nxm-link. The download manager will first query the nexus
+ * page for file information.
+ * @param url a nxm link looking like this: nxm://skyrim/mods/1234/files/4711
+ * @todo the game name encoded into the link is currently ignored, all downloads are incorrectly assumed to be for the identified game
+ **/
+ void addNXMDownload(const QString &url);
+
+ /**
+ * @brief retrieve the total number of downloads, both finished and unfinished including downloads from previous sessions
+ *
+ * @return total number of downloads
+ **/
+ int numTotalDownloads() const;
+
+ /**
+ * @brief retrieve number of pending downloads (nexus downloads for which we don't know the name and url yet)
+ * @return number of pending downloads
+ */
+ int numPendingDownloads() const;
+
+ /**
+ * @brief retrieve the info of a pending download
+ * @param index index of the pending download (index in the range [0, numPendingDownloads()[)
+ * @return pair of modid, fileid
+ */
+ std::tuple<QString, int, int> getPendingDownload(int index);
+
+ /**
+ * @brief retrieve the full path to the download specified by index
+ *
+ * @param index the index to look up
+ * @return absolute path of the file
+ **/
+ QString getFilePath(int index) const;
+
+ /**
+ * @brief retrieve a descriptive name of the download specified by index
+ *
+ * @param index index of the file to look up
+ * @return display name of the file
+ **/
+ QString getDisplayName(int index) const;
+
+ /**
+ * @brief retrieve the filename of the download specified by index
+ *
+ * @param index index of the file to look up
+ * @return name of the file
+ **/
+ QString getFileName(int index) const;
+
+ /**
+ * @brief retrieve the file size of the download specified by index
+ *
+ * @param index index of the file to look up
+ * @return size of the file (total size during download)
+ */
+ qint64 getFileSize(int index) const;
+
+ /**
+ * @brief retrieve the creation time of the download specified by index
+ * @param index index of the file to look up
+ * @return size of the file (total size during download)
+ */
+ QDateTime getFileTime(int index) const;
+
+ /**
+ * @brief retrieve the current progress of the download specified by index
+ *
+ * @param index index of the file to look up
+ * @return progress of the download in percent (integer)
+ **/
+ std::pair<int, QString> getProgress(int index) const;
+
+ /**
+ * @brief retrieve the current state of the download
+ *
+ * retrieve the current state of the download. A download usually goes through
+ * the following states:
+ * started -> downloading -> fetching mod info -> fetching file info -> done
+ * in case of downloads started via nxm-link, file information is fetched first
+ *
+ * @param index index of the file to look up
+ * @return the download state
+ **/
+ DownloadState getState(int index) const;
+
+ /**
+ * @param index index of the file to look up
+ * @return true if the nexus information for this download is not complete
+ **/
+ bool isInfoIncomplete(int index) const;
+
+ /**
+ * @brief retrieve the nexus mod id of the download specified by index
+ *
+ * @param index index of the file to look up
+ * @return the nexus mod id
+ **/
+ int getModID(int index) const;
+
+ /**
+ * @brief retrieve the game name of the downlaod specified by the index
+ *
+ * @param index index of the file to look up
+ * @return the game name
+ **/
+ QString getGameName(int index) const;
+
+ /**
+ * @brief determine if the specified file is supposed to be hidden
+ * @param index index of the file to look up
+ * @return true if the specified file is supposed to be hidden
+ */
+ bool isHidden(int index) const;
+
+ /**
+ * @brief retrieve all nexus info of the download specified by index
+ *
+ * @param index index of the file to look up
+ * @return the nexus mod information
+ **/
+ const MOBase::ModRepositoryFileInfo *getFileInfo(int index) const;
+
+ /**
+ * @brief mark a download as installed
+ *
+ * @param index index of the file to mark installed
+ */
+ void markInstalled(int index);
+
+ void markInstalled(QString download);
+
+ /**
+ * @brief mark a download as uninstalled
+ *
+ * @param index index of the file to mark uninstalled
+ */
+ void markUninstalled(int index);
+
+ void markUninstalled(QString download);
+
+ /**
+ * @brief refreshes the list of downloads
+ */
+ void refreshList();
+
+ /**
+ * @brief Sort function for download servers
+ * @param LHS
+ * @param RHS
+ * @return
+ */
+ static bool ServerByPreference(const std::map<QString, int> &preferredServers, const QVariant &LHS, const QVariant &RHS);
+
+
+ virtual int startDownloadURLs(const QStringList &urls);
+
+ virtual int startDownloadNexusFile(int modID, int fileID);
+
+ virtual QString downloadPath(int id);
+
+ /**
+ * @brief retrieve a download index from the filename
+ * @param fileName file to look up
+ * @return index of that download or -1 if it wasn't found
+ */
+ int indexByName(const QString &fileName) const;
+
+ void pauseAll();
+
+signals:
+
+ void aboutToUpdate();
+
+ /**
+ * @brief signals that the specified download has changed
+ *
+ * @param row the row that changed. This corresponds to the download index
+ **/
+ void update(int row);
+
+ /**
+ * @brief signals the ui that a message should be displayed
+ *
+ * @param message the message to display
+ **/
+ void showMessage(const QString &message);
+
+ /**
+ * @brief emitted whenever the state of a download changes
+ * @param row the row that changed
+ * @param state the new state
+ */
+ void stateChanged(int row, DownloadManager::DownloadState state);
+
+ /**
+ * @brief emitted whenever a download completes successfully, reporting the download speed for the server used
+ */
+ void downloadSpeed(const QString &serverName, int bytesPerSecond);
+
+ /**
+ * @brief emitted whenever a new download is added to the list
+ */
+ void downloadAdded();
+
+public slots:
+
+ /**
+ * @brief removes the specified download
+ *
+ * @param index index of the download to remove
+ * @param deleteFile if true, the file will also be deleted from disc, otherwise it is only marked as hidden.
+ **/
+ void removeDownload(int index, bool deleteFile);
+
+ /**
+ * @brief restores the specified download to view (which was previously hidden
+ * @param index index of the download to restore
+ */
+ void restoreDownload(int index);
+
+ /**
+ * @brief cancel the specified download. This will lead to the corresponding file to be deleted
+ *
+ * @param index index of the download to cancel
+ **/
+ void cancelDownload(int index);
+
+ void pauseDownload(int index);
+
+ void resumeDownload(int index);
+
+ void queryInfo(int index);
+
+ void visitOnNexus(int index);
+
+ void openFile(int index);
+
+ void openInDownloadsFolder(int index);
+
+ void nxmDescriptionAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID);
+
+ void nxmFilesAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID);
+
+ void nxmFileInfoAvailable(QString gameName, int modID, int fileID, QVariant userData, QVariant resultData, int requestID);
+
+ void nxmDownloadURLsAvailable(QString gameName, int modID, int fileID, QVariant userData, QVariant resultData, int requestID);
+
+ void nxmRequestFailed(QString gameName, int modID, int fileID, QVariant userData, int requestID, QNetworkReply::NetworkError error, const QString &errorString);
+
+ void managedGameChanged(MOBase::IPluginGame const *gamePlugin);
+
+private slots:
+
+ void downloadProgress(qint64 bytesReceived, qint64 bytesTotal);
+ void downloadReadyRead();
+ void downloadFinished(int index = 0);
+ void downloadError(QNetworkReply::NetworkError error);
+ void metaDataChanged();
+ void directoryChanged(const QString &dirctory);
+ void checkDownloadTimeout();
+
+private:
+
+ void createMetaFile(DownloadInfo *info);
+ DownloadManager::DownloadInfo* getDownloadInfo(QString fileName);
+
+public:
+
+ /** Get a unique filename for a download.
+ *
+ * This allows you multiple versions of download files, useful if the file
+ * comes from a web site with no version control
+ *
+ * @param basename: Name of the file
+ *
+ * @return Unique(ish) name
+ */
+ QString getDownloadFileName(const QString &baseName, bool rename = false) const;
+
+private:
+
+ void startDownload(QNetworkReply *reply, DownloadInfo *newDownload, bool resume);
+ void resumeDownloadInt(int index);
+
+ /**
+ * @brief start a download from a url
+ *
+ * @param url the url to download from
+ * @param fileInfo information previously retrieved from the mod page
+ * @return true if the download was started, false if it wasn't. The latter currently only happens if there is a duplicate and the user decides not to download again
+ **/
+ bool addDownload(const QStringList &URLs, QString gameName, int modID, int fileID, const MOBase::ModRepositoryFileInfo *fileInfo);
+
+ // important: the caller has to lock the list-mutex, otherwise the DownloadInfo-pointer might get invalidated at any time
+ DownloadInfo *findDownload(QObject *reply, int *index = nullptr) const;
+
+ void removeFile(int index, bool deleteFile);
+
+ void refreshAlphabeticalTranslation();
+
+ bool ByName(int LHS, int RHS);
+
+ QString getFileNameFromNetworkReply(QNetworkReply *reply);
+
+ void setState(DownloadInfo *info, DownloadManager::DownloadState state);
+
+ DownloadInfo *downloadInfoByID(unsigned int id);
+
+ void removePending(QString gameName, int modID, int fileID);
+
+ static QString getFileTypeString(int fileType);
+
+ void writeData(DownloadInfo *info);
+
+private:
+
+ static const int AUTOMATIC_RETRIES = 3;
+
+private:
+
+ NexusInterface *m_NexusInterface;
+
+ QVector<std::tuple<QString, int, int>> m_PendingDownloads;
+
+ QVector<DownloadInfo*> m_ActiveDownloads;
+
+ QString m_OutputDirectory;
+ std::map<QString, int> m_PreferredServers;
+ QStringList m_SupportedExtensions;
+ std::set<int> m_RequestIDs;
+ QVector<int> m_AlphabeticalTranslation;
+
+ QFileSystemWatcher m_DirWatcher;
+
+ //The dirWatcher is actually triggering off normal Mo operations such as deleting downloads or editing .meta files
+ //so it needs to be disabled during operations that are known to cause the creation or deletion of files in the Downloads folder.
+ //Notably using QSettings to edit a file creates a temporarily .lock file that causes the Watcher to trigger multiple listRefreshes freezing the ui.
+ static int m_DirWatcherDisabler;
+
+
+ std::map<QString, int> m_DownloadFails;
+
+ bool m_ShowHidden;
+
+ MOBase::IPluginGame const *m_ManagedGame;
+
+ QTimer m_TimeoutTimer;
+};
+
+
+
+#endif // DOWNLOADMANAGER_H
diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp
index 9003d6b2..9dbb8a86 100644
--- a/src/mainwindow.cpp
+++ b/src/mainwindow.cpp
@@ -5433,52 +5433,78 @@ void MainWindow::modDetailsUpdated(bool)
}
}
-void MainWindow::nxmUpdatesAvailable(const std::vector<int> &modIDs, QVariant userData, QVariant resultData, int)
+void MainWindow::nxmUpdatesAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID)
{
- m_ModsToUpdate -= static_cast<int>(modIDs.size());
- QVariantList resultList = resultData.toList();
- for (auto iter = resultList.begin(); iter != resultList.end(); ++iter) {
- QVariantMap result = iter->toMap();
- // Normally this would be the managed game but MO2 is only uploaded to the Skyrim SE site right now
- IPluginGame * game = m_OrganizerCore.getGame("skyrimse");
- if (game
- && result["id"].toInt() == game->nexusModOrganizerID()
- && result["game_id"].toInt() == game->nexusGameID()) {
- if (!result["voted_by_user"].toBool() &&
- Settings::instance().endorsementIntegration() &&
- !Settings::instance().directInterface().value("wont_endorse_MO", false).toBool()) {
- ui->actionEndorseMO->setVisible(true);
- }
- } else {
- QString gameName = m_OrganizerCore.managedGame()->gameShortName();
- bool sameNexus = false;
- for (IPluginGame *game : m_PluginContainer.plugins<IPluginGame>()) {
- if (game->nexusGameID() == result["game_id"].toInt()) {
- gameName = game->gameShortName();
- if (game->nexusGameID() == m_OrganizerCore.managedGame()->nexusGameID())
- sameNexus = true;
- break;
+ QVariantMap resultInfo = resultData.toMap();
+ QList files = resultInfo["files"].toList();
+ QList fileUpdates = resultInfo["file_updates"].toList();
+ bool foundUpdate = false;
+ m_ModsToUpdate--;
+ bool sameNexus = false;
+ for (IPluginGame *game : m_PluginContainer.plugins<IPluginGame>()) {
+ if (game->gameShortName() == gameName) {
+ if (game->nexusGameID() == m_OrganizerCore.managedGame()->nexusGameID())
+ sameNexus = true;
+ break;
+ }
+ }
+ std::vector<ModInfo::Ptr> modsList = ModInfo::getByModID(gameName, modID);
+ // Not clear to me what this is accomplishing?
+ //if (sameNexus) {
+ // std::vector<ModInfo::Ptr> mainInfo = ModInfo::getByModID(m_OrganizerCore.managedGame()->gameShortName(), modID);
+ // info.reserve(info.size() + mainInfo.size());
+ // info.insert(info.end(), mainInfo.begin(), mainInfo.end());
+ //}
+ for (auto mod : modsList) {
+ QString installedFile = mod->getInstallationFile();
+ for (auto update : fileUpdates) {
+ QVariantMap updateData = update.toMap();
+ if (installedFile == updateData["old_file_name"].toString()) {
+ int currentUpdate = updateData["new_file_id"].toInt();
+ bool finalUpdate = false;
+ while (!finalUpdate) {
+ finalUpdate = true;
+ for (auto updateScan : fileUpdates) {
+ QVariantMap updateScanData = updateScan.toMap();
+ if (currentUpdate == updateScanData["old_file_id"].toInt()) {
+ currentUpdate = updateScanData["new_file_id"].toInt();
+ finalUpdate = false;
+ break;
+ }
+ }
}
- }
- std::vector<ModInfo::Ptr> info = ModInfo::getByModID(gameName, result["id"].toInt());
- if (sameNexus) {
- std::vector<ModInfo::Ptr> mainInfo = ModInfo::getByModID(m_OrganizerCore.managedGame()->gameShortName(), result["id"].toInt());
- info.reserve(info.size() + mainInfo.size());
- info.insert(info.end(), mainInfo.begin(), mainInfo.end());
- }
- for (auto iter = info.begin(); iter != info.end(); ++iter) {
- (*iter)->setNewestVersion(result["version"].toString());
- (*iter)->setNexusDescription(result["description"].toString());
- if (NexusInterface::instance(&m_PluginContainer)->getAccessManager()->validated() &&
- result.contains("voted_by_user") &&
- Settings::instance().endorsementIntegration()) {
- // don't use endorsement info if we're not logged in or if the response doesn't contain it
- (*iter)->setIsEndorsed(result["voted_by_user"].toBool());
+ for (auto file : files) {
+ QVariantMap fileData = file.toMap();
+ if (fileData["file_id"].toInt() == currentUpdate) {
+ mod->setNewestVersion(fileData["version"].toString());
+ foundUpdate = true;
+ }
}
+
+ break;
}
}
+
+ if (foundUpdate) {
+ mod->updateNXMInfo();
+ }
+ else {
+ NexusInterface::instance(&m_PluginContainer)->requestDescription(gameName, modID, this, QVariant(), QString());
+ }
}
+ // Old endorsement and mod info updater
+ //for
+ // if (updateData["old_file_id"].toInt() == mod->readMeta())
+ // (*iter)->setNewestVersion(result["version"].toString());
+ //(*iter)->setNexusDescription(result["description"].toString());
+ //if (NexusInterface::instance(&m_PluginContainer)->getAccessManager()->validated() &&
+ // result.contains("voted_by_user") &&
+ // Settings::instance().endorsementIntegration()) {
+ // // don't use endorsement info if we're not logged in or if the response doesn't contain it
+ // (*iter)->setIsEndorsed(result["voted_by_user"].toBool());
+ //}
+
if (m_ModsToUpdate <= 0) {
statusBar()->hide();
m_ModListSortProxy->setCategoryFilter(boost::assign::list_of(CategoryFactory::CATEGORY_SPECIAL_UPDATEAVAILABLE));
@@ -5488,18 +5514,41 @@ void MainWindow::nxmUpdatesAvailable(const std::vector<int> &modIDs, QVariant us
break;
}
}
- } else {
+ }
+ else {
m_RefreshProgress->setValue(m_RefreshProgress->maximum() - m_ModsToUpdate);
}
}
+void MainWindow::nxmDescriptionAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID)
+{
+ QVariantMap result = resultData.toMap();
+ std::vector<ModInfo::Ptr> modsList = ModInfo::getByModID(gameName, modID);
+ for (auto mod : modsList) {
+ mod->setNexusDescription(result["description"].toString());
+
+ if ((mod->endorsedState() != ModInfo::ENDORSED_NEVER) && (result.contains("endorsement"))) {
+ QVariantMap endorsement = result["endorsement"].toMap();
+ QString endorsementStatus = endorsement["endorse_status"].toString();
+ if (endorsementStatus.compare("Endorsed") == 00)
+ mod->setIsEndorsed(true);
+ else if (endorsementStatus.compare("Abstained") == 00)
+ mod->setNeverEndorse();
+ else
+ mod->setIsEndorsed(false);
+ }
+ }
+ disconnect(sender(), SIGNAL(nxmDescriptionAvailable(QString, int, QVariant, QVariant, int)),
+ this, SLOT(nxmDescriptionAvailable(QString, int, QVariant, QVariant, int)));
+}
+
void MainWindow::nxmEndorsementToggled(QString, int, QVariant, QVariant resultData, int)
{
QMap results = resultData.toMap();
- if (results["code"].toInt() == 200) {
+ if (results["code"].toInt() == 200 || results["code"].toInt() == 201) {
if (results["status"].toString().compare("Endorsed") == 0) {
QMessageBox::information(this, tr("Thank you!"), tr("Thank you for your endorsement!"));
- } else {
+ } else if (results["status"].toString().compare("Abstained") == 0) {
QMessageBox::information(this, tr("Okay."), tr("This mod will not be endorsed and will no longer ask you to endorse."));
}
ui->actionEndorseMO->setVisible(false);
@@ -5529,14 +5578,22 @@ void MainWindow::nxmDownloadURLs(QString, int, int, QVariant, QVariant resultDat
}
-void MainWindow::nxmRequestFailed(QString, int modID, int, QVariant, int, const QString &errorString)
+void MainWindow::nxmRequestFailed(QString gameName, int modID, int, QVariant, int, QNetworkReply::NetworkError error, const QString &errorString)
{
if (modID == -1) {
// must be the update-check that failed
m_ModsToUpdate = 0;
statusBar()->hide();
}
- MessageDialog::showMessage(tr("Request to Nexus failed: %1").arg(errorString), this);
+ if (error == QNetworkReply::ContentAccessDenied || error == QNetworkReply::ContentNotFoundError) {
+ std::vector<ModInfo::Ptr> modsList = ModInfo::getByModID(gameName, modID);
+ for (auto mod : modsList) {
+ mod->setNexusID(-1);
+ }
+ MessageDialog::showMessage(tr("Mod ID %1 no longer seems to be available on Nexus.").arg(modID), this);
+ } else {
+ MessageDialog::showMessage(tr("Request to Nexus failed: %1").arg(errorString), this);
+ }
}
diff --git a/src/mainwindow.h b/src/mainwindow.h
index caf94c0e..077022db 100644
--- a/src/mainwindow.h
+++ b/src/mainwindow.h
@@ -508,10 +508,11 @@ private slots:
void modInstalled(const QString &modName);
- void nxmUpdatesAvailable(const std::vector<int> &modIDs, QVariant userData, QVariant resultData, int requestID);
+ void nxmUpdatesAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID);
+ void nxmDescriptionAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID);
void nxmEndorsementToggled(QString, int, QVariant, QVariant resultData, int);
void nxmDownloadURLs(QString, int modID, int fileID, QVariant userData, QVariant resultData, int requestID);
- void nxmRequestFailed(QString, int modID, int fileID, QVariant userData, int requestID, const QString &errorString);
+ void nxmRequestFailed(QString gameName, int modID, int fileID, QVariant userData, int requestID, QNetworkReply::NetworkError error, const QString &errorString);
void editCategories();
void deselectFilters();
diff --git a/src/modinfo.cpp b/src/modinfo.cpp
index 905341b0..e7b7657b 100644
--- a/src/modinfo.cpp
+++ b/src/modinfo.cpp
@@ -285,30 +285,15 @@ ModInfo::ModInfo(PluginContainer *pluginContainer)
}
-void ModInfo::checkChunkForUpdate(PluginContainer *pluginContainer, const std::vector<int> &modIDs, QObject *receiver, QString gameName)
-{
- if (modIDs.size() != 0) {
- NexusInterface::instance(pluginContainer)->requestUpdates(modIDs, receiver, QVariant(), gameName, QString());
- }
-}
-
-
int ModInfo::checkAllForUpdate(PluginContainer *pluginContainer, QObject *receiver)
{
- // technically this should be 255 but those requests can take nexus fairly long, produce
- // large output and may have been the cause of issue #1166
- static const int chunkSize = 64;
-
int result = 0;
- std::vector<int> modIDs;
- // Normally this would be the managed game but MO2 is only uploaded to the Skyrim SE site right now
- IPluginGame const *game = pluginContainer->managedGame("Skyrim Special Edition");
- if (game && game->nexusModOrganizerID()) {
- modIDs.push_back(game->nexusModOrganizerID());
- checkChunkForUpdate(pluginContainer, modIDs, receiver, game->gameShortName());
- modIDs.clear();
- }
+ // MO2 endorsement status is no longer available via this method - an alternative must be found
+ //IPluginGame const *game = pluginContainer->managedGame("Skyrim Special Edition");
+ //if (game && game->nexusModOrganizerID()) {
+ // NexusInterface::instance(pluginContainer)->requestUpdates(game->nexusModOrganizerID(), receiver, QVariant(), game->gameShortName(), QString());
+ //}
std::multimap<QString, QSharedPointer<ModInfo>> organizedGames;
for (auto mod : s_Collection) {
@@ -317,24 +302,10 @@ int ModInfo::checkAllForUpdate(PluginContainer *pluginContainer, QObject *receiv
}
}
- QString currentGame = "";
for (auto game : organizedGames) {
- if (currentGame != game.first) {
- if (currentGame != "") {
- checkChunkForUpdate(pluginContainer, modIDs, receiver, currentGame);
- modIDs.clear();
- }
- currentGame = game.first;
- }
- modIDs.push_back(game.second->getNexusID());
- if (modIDs.size() >= chunkSize) {
- checkChunkForUpdate(pluginContainer, modIDs, receiver, currentGame);
- modIDs.clear();
- }
+ NexusInterface::instance(pluginContainer)->requestUpdates(game.second->getNexusID(), receiver, QVariant(), game.first, QString());
}
- checkChunkForUpdate(pluginContainer, modIDs, receiver, currentGame);
-
return result;
}
diff --git a/src/modinfobackup.h b/src/modinfobackup.h
index da1fcd4a..f74cd111 100644
--- a/src/modinfobackup.h
+++ b/src/modinfobackup.h
@@ -17,6 +17,7 @@ public:
virtual void setGameName(QString) {}
virtual void setNexusID(int) {}
virtual void endorse(bool) {}
+ virtual void parseNexusInfo() {}
virtual int getFixedPriority() const { return -1; }
virtual void ignoreUpdate(bool) {}
virtual bool canBeUpdated() const { return false; }
diff --git a/src/modinfodialog.cpp b/src/modinfodialog.cpp
index c2ded812..d086de08 100644
--- a/src/modinfodialog.cpp
+++ b/src/modinfodialog.cpp
@@ -1,1577 +1,1577 @@
-/*
-Copyright (C) 2012 Sebastian Herbord. All rights reserved.
-
-This file is part of Mod Organizer.
-
-Mod Organizer is free software: you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-Mod Organizer is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with Mod Organizer. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#include "modinfodialog.h"
-#include "ui_modinfodialog.h"
-#include "descriptionpage.h"
-#include "mainwindow.h"
-
-#include "modidlineedit.h"
-#include "iplugingame.h"
-#include "nexusinterface.h"
-#include "report.h"
-#include "utility.h"
-#include "messagedialog.h"
-#include "bbcode.h"
-#include "questionboxmemory.h"
-#include "settings.h"
-#include "categories.h"
-#include "organizercore.h"
-#include "pluginlistsortproxy.h"
-#include "previewgenerator.h"
-#include "previewdialog.h"
-
-#include <QDir>
-#include <QDirIterator>
-#include <QPushButton>
-#include <QInputDialog>
-#include <QMessageBox>
-#include <QMenu>
-#include <QFileSystemModel>
-#include <QInputDialog>
-#include <QPointer>
-#include <QFileDialog>
-#include <QShortcut>
-
-#include <Shlwapi.h>
-
-#include <sstream>
-
-
-using namespace MOBase;
-using namespace MOShared;
-
-
-class ModFileListWidget : public QListWidgetItem {
- friend bool operator<(const ModFileListWidget &LHS, const ModFileListWidget &RHS);
-public:
- ModFileListWidget(const QString &text, int sortValue, QListWidget *parent = 0)
- : QListWidgetItem(text, parent, QListWidgetItem::UserType + 1), m_SortValue(sortValue) {}
-private:
- int m_SortValue;
-};
-
-
-static bool operator<(const ModFileListWidget &LHS, const ModFileListWidget &RHS)
-{
- return LHS.m_SortValue < RHS.m_SortValue;
-}
-
-
-ModInfoDialog::ModInfoDialog(ModInfo::Ptr modInfo, const DirectoryEntry *directory, bool unmanaged, OrganizerCore *organizerCore, PluginContainer *pluginContainer, QWidget *parent)
- : TutorableDialog("ModInfoDialog", parent), ui(new Ui::ModInfoDialog), m_ModInfo(modInfo),
- m_ThumbnailMapper(this), m_RequestStarted(false),
- m_DeleteAction(nullptr), m_RenameAction(nullptr), m_OpenAction(nullptr),
- m_Directory(directory), m_Origin(nullptr),
- m_OrganizerCore(organizerCore), m_PluginContainer(pluginContainer)
-{
- ui->setupUi(this);
- this->setWindowTitle(modInfo->name());
- this->setWindowModality(Qt::WindowModal);
-
- m_RootPath = modInfo->absolutePath();
-
- QString metaFileName = m_RootPath.mid(0).append("/meta.ini");
- m_Settings = new QSettings(metaFileName, QSettings::IniFormat);
-
- QLineEdit *modIDEdit = findChild<QLineEdit*>("modIDEdit");
- ui->modIDEdit->setValidator(new QIntValidator(modIDEdit));
- ui->modIDEdit->setText(QString("%1").arg(modInfo->getNexusID()));
-
- connect(ui->modIDEdit, SIGNAL(linkClicked(QString)), this, SLOT(linkClicked(QString)));
-
- QString gameName = modInfo->getGameName();
- ui->sourceGameEdit->addItem(organizerCore->managedGame()->gameName(), organizerCore->managedGame()->gameShortName());
- if (organizerCore->managedGame()->validShortNames().size() == 0) {
- ui->sourceGameEdit->setDisabled(true);
- } else {
- for (auto game : pluginContainer->plugins<IPluginGame>()) {
- for (QString gameName : organizerCore->managedGame()->validShortNames()) {
- if (game->gameShortName().compare(gameName, Qt::CaseInsensitive) == 0) {
- ui->sourceGameEdit->addItem(game->gameName(), game->gameShortName());
- break;
- }
- }
- }
- }
- ui->sourceGameEdit->setCurrentIndex(ui->sourceGameEdit->findData(gameName));
-
- ui->commentsEdit->setText(modInfo->comments());
- ui->notesEdit->setText(modInfo->notes());
-
- ui->descriptionView->setPage(new DescriptionPage());
-
- connect(&m_ThumbnailMapper, SIGNAL(mapped(const QString&)), this, SIGNAL(thumbnailClickedSignal(const QString&)));
- connect(this, SIGNAL(thumbnailClickedSignal(const QString&)), this, SLOT(thumbnailClicked(const QString&)));
- connect(m_ModInfo.data(), SIGNAL(modDetailsUpdated(bool)), this, SLOT(modDetailsUpdated(bool)));
- connect(ui->descriptionView->page(), SIGNAL(linkClicked(QUrl)), this, SLOT(linkClicked(QUrl)));
- //TODO: No easy way to delegate links
- //ui->descriptionView->page()->acceptNavigationRequest(QWebEnginePage::DelegateAllLinks);
-
- new QShortcut(QKeySequence::Delete, this, SLOT(delete_activated()));
-
- if (directory->originExists(ToWString(modInfo->name()))) {
- m_Origin = &directory->getOriginByName(ToWString(modInfo->name()));
- if (m_Origin->isDisabled()) {
- m_Origin = nullptr;
- }
- }
-
- refreshLists();
-
- if (modInfo->hasFlag(ModInfo::FLAG_SEPARATOR))
- {
- ui->tabWidget->setTabEnabled(TAB_TEXTFILES, false);
- ui->tabWidget->setTabEnabled(TAB_INIFILES, false);
- ui->tabWidget->setTabEnabled(TAB_IMAGES, false);
- ui->tabWidget->setTabEnabled(TAB_ESPS, false);
- ui->tabWidget->setTabEnabled(TAB_CONFLICTS, false);
- //ui->tabWidget->setTabEnabled(TAB_CATEGORIES, false);
- addCategories(CategoryFactory::instance(), modInfo->getCategories(), ui->categoriesTree->invisibleRootItem(), 0);
- refreshPrimaryCategoriesBox();
- ui->tabWidget->setTabEnabled(TAB_NEXUS, false);
- //ui->tabWidget->setTabEnabled(TAB_NOTES, false);
- ui->tabWidget->setTabEnabled(TAB_FILETREE, false);
- }
- else if (unmanaged)
- {
- ui->tabWidget->setTabEnabled(TAB_INIFILES, false);
- ui->tabWidget->setTabEnabled(TAB_CATEGORIES, false);
- ui->tabWidget->setTabEnabled(TAB_NEXUS, false);
- ui->tabWidget->setTabEnabled(TAB_FILETREE, false);
- ui->tabWidget->setTabEnabled(TAB_NOTES, false);
- ui->tabWidget->setTabEnabled(TAB_ESPS, false);
- ui->tabWidget->setTabEnabled(TAB_TEXTFILES, false);
- ui->tabWidget->setTabEnabled(TAB_IMAGES, false);
- } else {
- initFiletree(modInfo);
- addCategories(CategoryFactory::instance(), modInfo->getCategories(), ui->categoriesTree->invisibleRootItem(), 0);
- refreshPrimaryCategoriesBox();
- ui->tabWidget->setTabEnabled(TAB_TEXTFILES, ui->textFileList->count() != 0);
- ui->tabWidget->setTabEnabled(TAB_IMAGES, ui->thumbnailArea->count() != 0);
- ui->tabWidget->setTabEnabled(TAB_ESPS, (ui->inactiveESPList->count() != 0) || (ui->activeESPList->count() != 0));
- }
- initINITweaks();
-
- ui->tabWidget->setTabEnabled(TAB_CONFLICTS, m_Origin != nullptr);
-
-
- ui->endorseBtn->setVisible(Settings::instance().endorsementIntegration());
- ui->endorseBtn->setEnabled((m_ModInfo->endorsedState() == ModInfo::ENDORSED_FALSE) ||
- (m_ModInfo->endorsedState() == ModInfo::ENDORSED_NEVER));
-
- // activate first enabled tab
- for (int i = 0; i < ui->tabWidget->count(); ++i) {
- if (ui->tabWidget->isTabEnabled(i)) {
- ui->tabWidget->setCurrentIndex(i);
- break;
- }
- }
-
- if (ui->tabWidget->currentIndex() == TAB_NEXUS) {
- activateNexusTab();
- }
-}
-
-
-ModInfoDialog::~ModInfoDialog()
-{
- m_ModInfo->setComments(ui->commentsEdit->text());
- //Avoid saving html stump if notes field is empty.
- if (ui->notesEdit->toPlainText().isEmpty())
- m_ModInfo->setNotes(ui->notesEdit->toPlainText());
- else
- m_ModInfo->setNotes(ui->notesEdit->toHtml());
- saveCategories(ui->categoriesTree->invisibleRootItem());
- saveIniTweaks(); // ini tweaks are written to the ini file directly. This is the only information not managed by ModInfo
- delete ui->descriptionView->page();
- delete ui->descriptionView;
- delete ui;
- delete m_Settings;
-}
-
-
-void ModInfoDialog::initINITweaks()
-{
- int numTweaks = m_Settings->beginReadArray("INI Tweaks");
- for (int i = 0; i < numTweaks; ++i) {
- m_Settings->setArrayIndex(i);
- QList<QListWidgetItem*> items = ui->iniTweaksList->findItems(m_Settings->value("name").toString(), Qt::MatchFixedString);
- if (items.size() != 0) {
- items.at(0)->setCheckState(Qt::Checked);
- }
- }
- m_Settings->endArray();
-}
-
-void ModInfoDialog::initFiletree(ModInfo::Ptr modInfo)
-{
- ui->fileTree = findChild<QTreeView*>("fileTree");
-
- m_FileSystemModel = new QFileSystemModel(this);
- m_FileSystemModel->setReadOnly(false);
- m_FileSystemModel->setRootPath(m_RootPath);
- ui->fileTree->setModel(m_FileSystemModel);
- ui->fileTree->setRootIndex(m_FileSystemModel->index(m_RootPath));
- ui->fileTree->setColumnWidth(0, 300);
-
- m_DeleteAction = new QAction(tr("&Delete"), ui->fileTree);
- m_RenameAction = new QAction(tr("&Rename"), ui->fileTree);
- m_HideAction = new QAction(tr("&Hide"), ui->fileTree);
- m_UnhideAction = new QAction(tr("&Unhide"), ui->fileTree);
- m_OpenAction = new QAction(tr("&Open"), ui->fileTree);
- m_NewFolderAction = new QAction(tr("&New Folder"), ui->fileTree);
- QObject::connect(m_DeleteAction, SIGNAL(triggered()), this, SLOT(deleteTriggered()));
- QObject::connect(m_RenameAction, SIGNAL(triggered()), this, SLOT(renameTriggered()));
- QObject::connect(m_OpenAction, SIGNAL(triggered()), this, SLOT(openTriggered()));
- QObject::connect(m_NewFolderAction, SIGNAL(triggered()), this, SLOT(createDirectoryTriggered()));
- QObject::connect(m_HideAction, SIGNAL(triggered()), this, SLOT(hideTriggered()));
- connect(m_UnhideAction, SIGNAL(triggered()), this, SLOT(unhideTriggered()));
-}
-
-
-int ModInfoDialog::tabIndex(const QString &tabId)
-{
- for (int i = 0; i < ui->tabWidget->count(); ++i) {
- if (ui->tabWidget->widget(i)->objectName() == tabId) {
- return i;
- }
- }
- return -1;
-}
-
-
-void ModInfoDialog::restoreTabState(const QByteArray &state)
-{
- QDataStream stream(state);
- int count = 0;
- stream >> count;
-
- QStringList tabIds;
-
- // first, only determine the new mapping
- for (int newPos = 0; newPos < count; ++newPos) {
- QString tabId;
- stream >> tabId;
- tabIds.append(tabId);
- int oldPos = tabIndex(tabId);
- if (oldPos != -1) {
- m_RealTabPos[newPos] = oldPos;
- } else {
- m_RealTabPos[newPos] = newPos;
- }
- }
- // then actually move the tabs
- QTabBar *tabBar = ui->tabWidget->findChild<QTabBar*>("qt_tabwidget_tabbar"); // magic name = bad
- ui->tabWidget->blockSignals(true);
- for (int newPos = 0; newPos < count; ++newPos) {
- QString tabId = tabIds.at(newPos);
- int oldPos = tabIndex(tabId);
- tabBar->moveTab(oldPos, newPos);
- }
- ui->tabWidget->blockSignals(false);
-}
-
-
-QByteArray ModInfoDialog::saveTabState() const
-{
- QByteArray result;
- QDataStream stream(&result, QIODevice::WriteOnly);
- stream << ui->tabWidget->count();
- for (int i = 0; i < ui->tabWidget->count(); ++i) {
- stream << ui->tabWidget->widget(i)->objectName();
- }
-
- return result;
-}
-
-
-void ModInfoDialog::refreshLists()
-{
- int numNonConflicting = 0;
- int numOverwrite = 0;
- int numOverwritten = 0;
-
- ui->overwriteTree->clear();
- ui->overwrittenTree->clear();
-
- if (m_Origin != nullptr) {
- std::vector<FileEntry::Ptr> files = m_Origin->getFiles();
- for (auto iter = files.begin(); iter != files.end(); ++iter) {
- QString relativeName = QDir::fromNativeSeparators(ToQString((*iter)->getRelativePath()));
- QString fileName = relativeName.mid(0).prepend(m_RootPath);
- bool archive;
- if ((*iter)->getOrigin(archive) == m_Origin->getID()) {
- std::vector<std::pair<int, std::pair<std::wstring, int>>> alternatives = (*iter)->getAlternatives();
- if (!alternatives.empty()) {
- std::wostringstream altString;
- for (std::vector<std::pair<int, std::pair<std::wstring, int>>>::iterator altIter = alternatives.begin();
- altIter != alternatives.end(); ++altIter) {
- if (altIter != alternatives.begin()) {
- altString << ", ";
- }
- altString << m_Directory->getOriginByID(altIter->first).getName();
- }
- QStringList fields(relativeName.prepend("..."));
- fields.append(ToQString(altString.str()));
-
- QTreeWidgetItem *item = new QTreeWidgetItem(fields);
- item->setData(0, Qt::UserRole, fileName);
- item->setData(1, Qt::UserRole, ToQString(m_Directory->getOriginByID(alternatives.back().first).getName()));
- item->setData(1, Qt::UserRole + 1, alternatives.back().first);
- item->setData(1, Qt::UserRole + 2, archive);
- if (archive) {
- QFont font = item->font(0);
- font.setItalic(true);
- item->setFont(0, font);
- item->setFont(1, font);
- }
- ui->overwriteTree->addTopLevelItem(item);
- ++numOverwrite;
- } else {// otherwise don't display the file
- ++numNonConflicting;
- }
- } else {
- FilesOrigin &realOrigin = m_Directory->getOriginByID((*iter)->getOrigin(archive));
- QStringList fields(relativeName);
- fields.append(ToQString(realOrigin.getName()));
- QTreeWidgetItem *item = new QTreeWidgetItem(fields);
- item->setData(0, Qt::UserRole, fileName);
- item->setData(1, Qt::UserRole, ToQString(realOrigin.getName()));
- item->setData(1, Qt::UserRole + 2, archive);
- if (archive) {
- QFont font = item->font(0);
- font.setItalic(true);
- item->setFont(0, font);
- item->setFont(1, font);
- }
- ui->overwrittenTree->addTopLevelItem(item);
- ++numOverwritten;
- }
- }
- }
-
- if (m_RootPath.length() > 0) {
- QDirIterator dirIterator(m_RootPath, QDir::Files, QDirIterator::Subdirectories);
- while (dirIterator.hasNext()) {
- QString fileName = dirIterator.next();
-
- if (fileName.endsWith(".txt", Qt::CaseInsensitive)) {
- ui->textFileList->addItem(fileName.mid(m_RootPath.length() + 1));
- } else if ((fileName.endsWith(".ini", Qt::CaseInsensitive) || fileName.endsWith(".cfg", Qt::CaseInsensitive)) &&
- !fileName.endsWith("meta.ini")) {
- QString namePart = fileName.mid(m_RootPath.length() + 1);
- if (namePart.startsWith("INI Tweaks", Qt::CaseInsensitive)) {
- QListWidgetItem *newItem = new QListWidgetItem(namePart.mid(11), ui->iniTweaksList);
- newItem->setData(Qt::UserRole, namePart);
- newItem->setFlags(newItem->flags() | Qt::ItemIsUserCheckable);
- newItem->setCheckState(Qt::Unchecked);
- ui->iniTweaksList->addItem(newItem);
- } else {
- ui->iniFileList->addItem(namePart);
- }
- } else if (fileName.endsWith(".esp", Qt::CaseInsensitive) ||
- fileName.endsWith(".esm", Qt::CaseInsensitive) ||
- fileName.endsWith(".esl", Qt::CaseInsensitive)) {
- QString relativePath = fileName.mid(m_RootPath.length() + 1);
- if (relativePath.contains('/')) {
- QFileInfo fileInfo(fileName);
- QListWidgetItem *newItem = new QListWidgetItem(fileInfo.fileName());
- newItem->setData(Qt::UserRole, relativePath);
- ui->inactiveESPList->addItem(newItem);
- } else {
- ui->activeESPList->addItem(relativePath);
- }
- } else if ((fileName.endsWith(".png", Qt::CaseInsensitive)) ||
- (fileName.endsWith(".jpg", Qt::CaseInsensitive))) {
- QImage image = QImage(fileName);
- if (!image.isNull()) {
- if (static_cast<float>(image.width()) / static_cast<float>(image.height()) > 1.34) {
- image = image.scaledToWidth(128);
- } else {
- image = image.scaledToHeight(96);
- }
-
- QPushButton *thumbnailButton = new QPushButton(QPixmap::fromImage(image), "");
- thumbnailButton->setIconSize(QSize(image.width(), image.height()));
- connect(thumbnailButton, SIGNAL(clicked()), &m_ThumbnailMapper, SLOT(map()));
- m_ThumbnailMapper.setMapping(thumbnailButton, fileName);
- ui->thumbnailArea->addWidget(thumbnailButton);
- }
- }
- }
- }
-
- ui->overwriteCount->display(numOverwrite);
- ui->overwrittenCount->display(numOverwritten);
- ui->noConflictCount->display(numNonConflicting);
-}
-
-
-void ModInfoDialog::addCategories(const CategoryFactory &factory, const std::set<int> &enabledCategories, QTreeWidgetItem *root, int rootLevel)
-{
- for (int i = 0; i < static_cast<int>(factory.numCategories()); ++i) {
- if (factory.getParentID(i) != rootLevel) {
- continue;
- }
- int categoryID = factory.getCategoryID(i);
- QTreeWidgetItem *newItem
- = new QTreeWidgetItem(QStringList(factory.getCategoryName(i)));
- newItem->setFlags(newItem->flags() | Qt::ItemIsUserCheckable);
- newItem->setCheckState(0, enabledCategories.find(categoryID)
- != enabledCategories.end()
- ? Qt::Checked
- : Qt::Unchecked);
- newItem->setData(0, Qt::UserRole, categoryID);
- if (factory.hasChildren(i)) {
- addCategories(factory, enabledCategories, newItem, categoryID);
- }
- root->addChild(newItem);
- }
-}
-
-
-void ModInfoDialog::saveCategories(QTreeWidgetItem *currentNode)
-{
- for (int i = 0; i < currentNode->childCount(); ++i) {
- QTreeWidgetItem *childNode = currentNode->child(i);
- m_ModInfo->setCategory(childNode->data(0, Qt::UserRole).toInt(), childNode->checkState(0));
- saveCategories(childNode);
- }
-}
-
-
-void ModInfoDialog::on_closeButton_clicked()
-{
- if (allowNavigateFromTXT() && allowNavigateFromINI()) {
- this->close();
- }
-}
-
-
-
-QString ModInfoDialog::getModVersion() const
-{
- return m_Settings->value("version", "").toString();
-}
-
-
-const int ModInfoDialog::getModID() const
-{
- return m_Settings->value("modid", 0).toInt();
-}
-
-void ModInfoDialog::openTab(int tab)
-{
- QTabWidget *tabWidget = findChild<QTabWidget*>("tabWidget");
- if (tabWidget->isTabEnabled(tab)) {
- tabWidget->setCurrentIndex(tab);
- }
-}
-
-void ModInfoDialog::thumbnailClicked(const QString &fileName)
-{
- QLabel *imageLabel = findChild<QLabel*>("imageLabel");
- imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
- QImage image(fileName);
- if (static_cast<float>(image.width()) / static_cast<float>(image.height()) > 1.34) {
- image = image.scaledToWidth(imageLabel->geometry().width());
- } else {
- image = image.scaledToHeight(imageLabel->geometry().height());
- }
- imageLabel->setPixmap(QPixmap::fromImage(image));
-}
-
-bool ModInfoDialog::allowNavigateFromTXT()
-{
- if (ui->saveTXTButton->isEnabled()) {
- int res = QMessageBox::question(this, tr("Save changes?"), tr("Save changes to \"%1\"?").arg(ui->textFileView->property("currentFile").toString()),
- QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
- if (res == QMessageBox::Cancel) {
- return false;
- } else if (res == QMessageBox::Yes) {
- saveCurrentTextFile();
- }
- }
- return true;
-}
-
-
-bool ModInfoDialog::allowNavigateFromINI()
-{
- if (ui->saveButton->isEnabled()) {
- int res = QMessageBox::question(this, tr("Save changes?"), tr("Save changes to \"%1\"?").arg(ui->iniFileView->property("currentFile").toString()),
- QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
- if (res == QMessageBox::Cancel) {
- return false;
- } else if (res == QMessageBox::Yes) {
- saveCurrentIniFile();
- }
- }
- return true;
-}
-
-
-void ModInfoDialog::on_textFileList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
-{
- QString fullPath = m_RootPath + "/" + current->text();
-
- QVariant currentFile = ui->textFileView->property("currentFile");
- if (currentFile.isValid() && (currentFile.toString() == fullPath)) {
- // the new file is the same as the currently displayed file. May be the result of a cancelation
- return;
- }
-
- if (allowNavigateFromTXT()) {
- openTextFile(fullPath);
- } else {
- ui->textFileList->setCurrentItem(previous, QItemSelectionModel::Current);
- }
-}
-
-
-void ModInfoDialog::openTextFile(const QString &fileName)
-{
- QString encoding;
- ui->textFileView->setText(MOBase::readFileText(fileName, &encoding));
- ui->textFileView->setProperty("currentFile", fileName);
- ui->textFileView->setProperty("encoding", encoding);
- ui->saveTXTButton->setEnabled(false);
-}
-
-
-void ModInfoDialog::openIniFile(const QString &fileName)
-{
- QFile iniFile(fileName);
- iniFile.open(QIODevice::ReadOnly);
- QByteArray buffer = iniFile.readAll();
-
- QTextCodec *codec = QTextCodec::codecForUtfText(buffer, QTextCodec::codecForName("utf-8"));
- QTextEdit *iniFileView = findChild<QTextEdit*>("iniFileView");
- iniFileView->setText(codec->toUnicode(buffer));
- iniFileView->setProperty("currentFile", fileName);
- iniFileView->setProperty("encoding", codec->name());
- iniFile.close();
-
- ui->saveButton->setEnabled(false);
-}
-
-
-void ModInfoDialog::saveIniTweaks()
-{
- m_Settings->remove("INI Tweaks");
- m_Settings->beginWriteArray("INI Tweaks");
-
- int countEnabled = 0;
- for (int i = 0; i < ui->iniTweaksList->count(); ++i) {
- if (ui->iniTweaksList->item(i)->checkState() == Qt::Checked) {
- m_Settings->setArrayIndex(countEnabled++);
- m_Settings->setValue("name", ui->iniTweaksList->item(i)->text());
- }
- }
- m_Settings->endArray();
-}
-
-
-void ModInfoDialog::on_iniFileList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
-{
- QString fullPath = m_RootPath + "/" + current->text();
-
- QVariant currentFile = ui->iniFileView->property("currentFile");
- if (currentFile.isValid() && (currentFile.toString() == fullPath)) {
- // the new file is the same as the currently displayed file. May be the result of a cancelation
- return;
- }
-
- if (allowNavigateFromINI()) {
- openIniFile(fullPath);
- } else {
- ui->iniFileList->setCurrentItem(previous, QItemSelectionModel::Current);
- }
-}
-
-
-void ModInfoDialog::on_iniTweaksList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
-{
- QString fullPath = m_RootPath + "/" + current->data(Qt::UserRole).toString();
-
- QVariant currentFile = ui->iniFileView->property("currentFile");
- if (currentFile.isValid() && (currentFile.toString() == fullPath)) {
- // the new file is the same as the currently displayed file. May be the result of a cancelation
- return;
- }
-
- if (allowNavigateFromINI()) {
- openIniFile(fullPath);
- } else {
- ui->iniFileList->setCurrentItem(previous, QItemSelectionModel::Current);
- }
-
-}
-
-
-void ModInfoDialog::on_saveButton_clicked()
-{
- saveCurrentIniFile();
-}
-
-
-void ModInfoDialog::on_saveTXTButton_clicked()
-{
- saveCurrentTextFile();
-}
-
-
-void ModInfoDialog::saveCurrentTextFile()
-{
- QVariant fileNameVar = ui->textFileView->property("currentFile");
- QVariant encodingVar = ui->textFileView->property("encoding");
- if (fileNameVar.isValid() && encodingVar.isValid()) {
- QString fileName = fileNameVar.toString();
- QFile txtFile(fileName);
- txtFile.open(QIODevice::WriteOnly);
- txtFile.resize(0);
- QTextCodec *codec = QTextCodec::codecForName(encodingVar.toString().toUtf8());
- QString data = ui->textFileView->toPlainText().replace("\n", "\r\n");
- txtFile.write(codec->fromUnicode(data));
- } else {
- reportError("no file selected");
- }
- ui->saveTXTButton->setEnabled(false);
-}
-
-
-void ModInfoDialog::saveCurrentIniFile()
-{
- QVariant fileNameVar = ui->iniFileView->property("currentFile");
- QVariant encodingVar = ui->iniFileView->property("encoding");
- if (fileNameVar.isValid() && !fileNameVar.toString().isEmpty()) {
- QString fileName = fileNameVar.toString();
- QDir().mkpath(QFileInfo(fileName).absolutePath());
- QFile txtFile(fileName);
- txtFile.open(QIODevice::WriteOnly);
- txtFile.resize(0);
- QTextCodec *codec = QTextCodec::codecForName(encodingVar.toString().toUtf8());
- QString data = ui->iniFileView->toPlainText().replace("\n", "\r\n");
- txtFile.write(codec->fromUnicode(data));
- } else {
- reportError("no file selected");
- }
- ui->saveButton->setEnabled(false);
-}
-
-
-void ModInfoDialog::on_iniFileView_textChanged()
-{
- QPushButton* saveButton = findChild<QPushButton*>("saveButton");
- saveButton->setEnabled(true);
-}
-
-
-void ModInfoDialog::on_textFileView_textChanged()
-{
- ui->saveTXTButton->setEnabled(true);
-}
-
-
-void ModInfoDialog::on_activateESP_clicked()
-{
- QListWidget *activeESPList = findChild<QListWidget*>("activeESPList");
- QListWidget *inactiveESPList = findChild<QListWidget*>("inactiveESPList");
-
- int selectedRow = inactiveESPList->currentRow();
- if (selectedRow < 0) {
- return;
- }
-
- QListWidgetItem *selectedItem = inactiveESPList->takeItem(selectedRow);
-
- QDir root(m_RootPath);
- bool renamed = false;
-
- while (root.exists(selectedItem->text())) {
- bool okClicked = false;
- QString newName = QInputDialog::getText(this, tr("File Exists"), tr("A file with that name exists, please enter a new one"), QLineEdit::Normal, selectedItem->text(), &okClicked);
- if (!okClicked) {
- inactiveESPList->insertItem(selectedRow, selectedItem);
- return;
- } else if (newName.size() > 0) {
- selectedItem->setText(newName);
- renamed = true;
- }
- }
-
- if (root.rename(selectedItem->data(Qt::UserRole).toString(), selectedItem->text())) {
- activeESPList->addItem(selectedItem);
- if (renamed) {
- selectedItem->setData(Qt::UserRole, QVariant());
- }
- } else {
- inactiveESPList->insertItem(selectedRow, selectedItem);
- reportError(tr("failed to move file"));
- }
-}
-
-
-void ModInfoDialog::on_deactivateESP_clicked()
-{
- QListWidget *activeESPList = findChild<QListWidget*>("activeESPList");
- QListWidget *inactiveESPList = findChild<QListWidget*>("inactiveESPList");
-
- int selectedRow = activeESPList->currentRow();
- if (selectedRow < 0) {
- return;
- }
-
- QDir root(m_RootPath);
-
- QListWidgetItem *selectedItem = activeESPList->takeItem(selectedRow);
-
- // if we moved the file from optional to active in this session, we move the file back to
- // where it came from. Otherwise, it is moved to the new folder "optional"
- if (selectedItem->data(Qt::UserRole).isNull()) {
- selectedItem->setData(Qt::UserRole, QString("optional/") + selectedItem->text());
- if (!root.exists("optional")) {
- if (!root.mkdir("optional")) {
- reportError(tr("failed to create directory \"optional\""));
- activeESPList->insertItem(selectedRow, selectedItem);
- return;
- }
- }
- }
-
- if (root.rename(selectedItem->text(), selectedItem->data(Qt::UserRole).toString())) {
- inactiveESPList->addItem(selectedItem);
- } else {
- activeESPList->insertItem(selectedRow, selectedItem);
- }
-}
-
-void ModInfoDialog::on_visitNexusLabel_linkActivated(const QString &link)
-{
- emit linkActivated(link);
-}
-
-void ModInfoDialog::linkClicked(const QUrl &url)
-{
- //Ideally we'd ask the mod for the game and the web service then pass the game
- //and URL to the web service
- if (NexusInterface::instance(m_PluginContainer)->isURLGameRelated(url)) {
-
- emit linkActivated(url.toString());
- } else {
- ::ShellExecuteW(nullptr, L"open", ToWString(url.toString()).c_str(), nullptr, nullptr, SW_SHOWNORMAL);
- }
-}
-
-void ModInfoDialog::linkClicked(QString url)
-{
- emit linkActivated(url);
-}
-
-
-void ModInfoDialog::refreshNexusData(int modID)
-{
- if ((!m_RequestStarted) && (modID > 0)) {
- m_RequestStarted = true;
-
- m_ModInfo->updateNXMInfo();
-
- MessageDialog::showMessage(tr("Info requested, please wait"), this);
- }
-}
-
-
-/*void ModInfoDialog::nxmDescriptionAvailable(int, QVariant, QVariant resultData, int requestID)
-{
- std::set<int>::iterator idIter = m_RequestIDs.find(requestID);
- if (idIter == m_RequestIDs.end()) {
- return;
- } else {
- m_RequestIDs.erase(idIter);
- }
-
- QVariantMap result = resultData.toMap();
-
- if (!result["description"].isNull()) {
- QString descriptionAsHTML =
- QString("<html>"
- "<head><style>body {background: #707070; } a { color: #5EA2E5; }</style></head>"
- "<body>%1</body>"
- "</html>").arg(BBCode::convertToHTML(result["description"].toString()));
-
-// QString descriptionAsHTML = BBCode::convertToHTML(result["description"].toString());
- ui->descriptionView->setHtml(descriptionAsHTML);
- } else {
- ui->descriptionView->setHtml(result["summary"].toString().append(QString("\r\n") + tr("(description incomplete, please visit nexus)")));
- }
-
- QLineEdit *versionEdit = findChild<QLineEdit*>("versionEdit");
- QString version = result["version"].toString();
-
- if (!version.isEmpty()) {
- m_ModInfo->setNewestVersion(version);
-
- VersionInfo currentVersion(versionEdit->text());
- VersionInfo newestVersion(version);
-
- QPalette versionColor;
- if (currentVersion < newestVersion) {
- versionColor.setColor(QPalette::Text, Qt::red);
- versionEdit->setToolTip(tr("Current Version: %1").arg(version));
- } else {
- versionColor.setColor(QPalette::Text, Qt::green);
- versionEdit->setToolTip(tr("No update available"));
- }
- versionEdit->setPalette(versionColor);
- }
-}*/
-
-
-QString ModInfoDialog::getFileCategory(int categoryID)
-{
- switch (categoryID) {
- case 1: return tr("Main");
- case 2: return tr("Update");
- case 3: return tr("Optional");
- case 4: return tr("Old");
- case 5: return tr("Misc");
- default: return tr("Unknown");
- }
-}
-
-
-void ModInfoDialog::updateVersionColor()
-{
-// QPalette versionColor;
- if (m_ModInfo->getVersion() != m_ModInfo->getNewestVersion()) {
- ui->versionEdit->setStyleSheet("color: red");
-// versionColor.setColor(QPalette::Text, Qt::red);
- ui->versionEdit->setToolTip(tr("Current Version: %1").arg(m_ModInfo->getNewestVersion().canonicalString()));
- } else {
- ui->versionEdit->setStyleSheet("color: green");
-// versionColor.setColor(QPalette::Text, Qt::green);
- ui->versionEdit->setToolTip(tr("No update available"));
- }
-// ui->versionEdit->setPalette(versionColor);
-}
-
-
-void ModInfoDialog::modDetailsUpdated(bool success)
-{
- if (success) {
- QString nexusDescription = m_ModInfo->getNexusDescription();
- if (!nexusDescription.isEmpty()) {
- /* QString input =
- "[size=20]sizetest[/size]\r\n"
- "[COLOR=yellow]colortest[/COLOR]\r\n"
- "[center]centertest[/center]\r\n"
- "[quote]quotetest 1[/quote]\r\n"
- "[quote=bla]quotetest 2[/quote]\r\n"
- "[url]www.skyrimnexus.com[/url]\r\n"
- "[url=www.skyrimnexus.com]urltest 2[/url]\r\n"
- "[ol]\r\n"
- "[li]item 2[/li]"
- "[*]item 1\r\n"
- "[/ol]\r\n"
- "[img]http://www.bbcode.org/images/bbcode_logo.png[/img]\r\n"
- "[table][tr][th]headertest1[/th]"
- "[th]headertest2[/th][/tr]"
- "[tr][td]rowtest11[/td][td]rowtest12[/td][/tr]"
- "[tr][td]rowtest21[/td][td]rowtest22[/td][/tr][/table]"
- "[email=\"sherb@gmx.net\"]mail me[/email]";
- ui->descriptionView->setHtml(BBCode::convertToHTML(input));*/
-
- QString descriptionAsHTML =
- QString("<html>"
- "<head><style>body {background: #707070; } a { color: #5EA2E5; }</style></head>"
- "<body>%1</body>"
- "</html>").arg(BBCode::convertToHTML(nexusDescription));
-
- ui->descriptionView->page()->setHtml(descriptionAsHTML);
-
- // QString descriptionAsHTML = BBCode::convertToHTML(result["description"].toString());
- // ui->descriptionView->setHtml(descriptionAsHTML);
- } else {
- // ui->descriptionView->setHtml(result["summary"].toString().append(QString("\r\n") + tr("(description incomplete, please visit nexus)")));
- ui->descriptionView->page()->setHtml(tr("(description incomplete, please visit nexus)"));
- }
-
- updateVersionColor();
- }
-}
-
-
-void ModInfoDialog::activateNexusTab()
-{
- QLineEdit *modIDEdit = findChild<QLineEdit*>("modIDEdit");
- int modID = modIDEdit->text().toInt();
- if (modID != 0) {
- QString nexusLink = NexusInterface::instance(m_PluginContainer)->getModURL(modID, m_ModInfo->getGameName());
- QLabel *visitNexusLabel = findChild<QLabel*>("visitNexusLabel");
- visitNexusLabel->setText(tr("<a href=\"%1\">Visit on Nexus</a>").arg(nexusLink));
- visitNexusLabel->setToolTip(nexusLink);
-
- if (m_ModInfo->getNexusDescription().isEmpty() ||
- QDateTime::currentDateTime() > m_ModInfo->getLastNexusQuery().addDays(1)) {
- refreshNexusData(modID);
- } else {
- this->modDetailsUpdated(true);
- }
- }
- QLineEdit *versionEdit = findChild<QLineEdit*>("versionEdit");
- QString currentVersion = m_Settings->value("version", "0.0").toString();
- versionEdit->setText(currentVersion);
- ui->customUrlLineEdit->setText(m_ModInfo->getURL());
-}
-
-
-void ModInfoDialog::on_tabWidget_currentChanged(int index)
-{
- if (index == TAB_NEXUS || m_RealTabPos[index] == TAB_NEXUS) {
- activateNexusTab();
- }
-}
-
-
-void ModInfoDialog::on_modIDEdit_editingFinished()
-{
- int oldID = m_Settings->value("modid", 0).toInt();
- int modID = ui->modIDEdit->text().toInt();
- if (oldID != modID){
- m_ModInfo->setNexusID(modID);
-
- ui->descriptionView->page()->setHtml("");
- if (modID != 0) {
- m_RequestStarted = false;
- refreshNexusData(modID);
- }
- }
-}
-
-void ModInfoDialog::on_sourceGameEdit_currentIndexChanged(int)
-{
- for (auto game : m_PluginContainer->plugins<IPluginGame>()) {
- if (game->gameName() == ui->sourceGameEdit->currentText()) {
- m_ModInfo->setGameName(game->gameShortName());
- return;
- }
- }
-}
-
-void ModInfoDialog::on_versionEdit_editingFinished()
-{
- VersionInfo version(ui->versionEdit->text());
- m_ModInfo->setVersion(version);
- updateVersionColor();
-}
-
-void ModInfoDialog::on_customUrlLineEdit_editingFinished()
-{
- m_ModInfo->setURL(ui->customUrlLineEdit->text());
-}
-
-bool ModInfoDialog::recursiveDelete(const QModelIndex &index)
-{
- for (int childRow = 0; childRow < m_FileSystemModel->rowCount(index); ++childRow) {
- QModelIndex childIndex = m_FileSystemModel->index(childRow, 0, index);
- if (m_FileSystemModel->isDir(childIndex)) {
- if (!recursiveDelete(childIndex)) {
- qCritical("failed to delete %s", m_FileSystemModel->fileName(childIndex).toUtf8().constData());
- return false;
- }
- } else {
- if (!m_FileSystemModel->remove(childIndex)) {
- qCritical("failed to delete %s", m_FileSystemModel->fileName(childIndex).toUtf8().constData());
- return false;
- }
- }
- }
- if (!m_FileSystemModel->remove(index)) {
- qCritical("failed to delete %s", m_FileSystemModel->fileName(index).toUtf8().constData());
- return false;
- }
- return true;
-}
-
-
-void ModInfoDialog::on_openInExplorerButton_clicked()
-{
- ::ShellExecuteW(nullptr, L"explore", ToWString(m_ModInfo->absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL);
-}
-
-void ModInfoDialog::deleteFile(const QModelIndex &index)
-{
-
- bool res = m_FileSystemModel->isDir(index) ? recursiveDelete(index)
- : m_FileSystemModel->remove(index);
- if (!res) {
- QString fileName = m_FileSystemModel->fileName(index);
- reportError(tr("Failed to delete %1").arg(fileName));
- }
-}
-
-void ModInfoDialog::delete_activated()
-{
- if (ui->fileTree->hasFocus()) {
- QItemSelectionModel *selection = ui->fileTree->selectionModel();
-
- if (selection->hasSelection() && selection->selectedRows().count() >= 1) {
-
- if (selection->selectedRows().count() == 0) {
- return;
- }
- else if (selection->selectedRows().count() == 1) {
- QString fileName = m_FileSystemModel->fileName(selection->selectedRows().at(0));
- if (QMessageBox::question(this, tr("Confirm"), tr("Are sure you want to delete \"%1\"?").arg(fileName),
- QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
- return;
- }
- }
- else {
- if (QMessageBox::question(this, tr("Confirm"), tr("Are sure you want to delete the selected files?"),
- QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
- return;
- }
- }
-
- foreach(QModelIndex index, selection->selectedRows()) {
- deleteFile(index);
- }
- }
- }
-}
-
-void ModInfoDialog::deleteTriggered()
-{
- if (m_FileSelection.count() == 0) {
- return;
- } else if (m_FileSelection.count() == 1) {
- QString fileName = m_FileSystemModel->fileName(m_FileSelection.at(0));
- if (QMessageBox::question(this, tr("Confirm"), tr("Are sure you want to delete \"%1\"?").arg(fileName),
- QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
- return;
- }
- } else {
- if (QMessageBox::question(this, tr("Confirm"), tr("Are sure you want to delete the selected files?"),
- QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
- return;
- }
- }
-
- foreach(QModelIndex index, m_FileSelection) {
- deleteFile(index);
- }
-}
-
-
-void ModInfoDialog::renameTriggered()
-{
- QModelIndex selection = m_FileSelection.at(0);
- QModelIndex index = selection.sibling(selection.row(), 0);
- if (!index.isValid() || m_FileSystemModel->isReadOnly()) {
- return;
- }
-
- ui->fileTree->edit(index);
-}
-
-
-void ModInfoDialog::hideTriggered()
-{
- for (QModelIndexList::const_iterator iter = m_FileSelection.constBegin();
- iter != m_FileSelection.constEnd(); ++iter) {
- QString path = m_FileSystemModel->filePath(*iter);
- if (!path.endsWith(ModInfo::s_HiddenExt)) {
- hideFile(path);
- }
- }
-}
-
-
-void ModInfoDialog::unhideTriggered()
-{
- for (QModelIndexList::const_iterator iter = m_FileSelection.constBegin();
- iter != m_FileSelection.constEnd(); ++iter) {
- QString path = m_FileSystemModel->filePath(*iter);
- if (path.endsWith(ModInfo::s_HiddenExt)) {
- unhideFile(path);
- }
- }
-}
-
-
-void ModInfoDialog::openFile(const QModelIndex &index)
-{
- QString fileName = m_FileSystemModel->filePath(index);
-
- HINSTANCE res = ::ShellExecuteW(nullptr, L"open", ToWString(fileName).c_str(), nullptr, nullptr, SW_SHOW);
- if ((unsigned long long)res <= 32) {
- qCritical("failed to invoke %s: %d", qUtf8Printable(fileName), res);
- }
-}
-
-
-void ModInfoDialog::openTriggered()
-{
- foreach(QModelIndex idx, m_FileSelection) {
- openFile(idx);
- }
-}
-
-void ModInfoDialog::createDirectoryTriggered()
-{
- QModelIndex selection = m_FileSelection.at(0);
-
- QModelIndex index = m_FileSystemModel->isDir(selection) ? selection
- : selection.parent();
- index = index.sibling(index.row(), 0);
-
- QString name = tr("New Folder");
- QString path = m_FileSystemModel->filePath(index).append("/");
-
- QModelIndex existingIndex = m_FileSystemModel->index(path + name);
- int suffix = 1;
- while (existingIndex.isValid()) {
- name = tr("New Folder") + QString::number(suffix++);
- existingIndex = m_FileSystemModel->index(path + name);
- }
-
- QModelIndex newIndex = m_FileSystemModel->mkdir(index, name);
- if (!newIndex.isValid()) {
- reportError(tr("Failed to create \"%1\"").arg(name));
- return;
- }
-
- ui->fileTree->setCurrentIndex(newIndex);
- ui->fileTree->edit(newIndex);
-}
-
-
-void ModInfoDialog::on_fileTree_customContextMenuRequested(const QPoint &pos)
-{
- QItemSelectionModel *selectionModel = ui->fileTree->selectionModel();
- m_FileSelection = selectionModel->selectedRows(0);
-
-// m_FileSelection = ui->fileTree->indexAt(pos);
- QMenu menu(ui->fileTree);
-
- menu.addAction(m_NewFolderAction);
-
- bool hasFiles = false;
-
- foreach(QModelIndex idx, m_FileSelection) {
- if (m_FileSystemModel->fileInfo(idx).isFile()) {
- hasFiles = true;
- break;
- }
- }
-
- if (selectionModel->hasSelection()) {
- if (hasFiles) {
- menu.addAction(m_OpenAction);
- }
- menu.addAction(m_RenameAction);
- menu.addAction(m_DeleteAction);
- if (m_FileSystemModel->fileName(m_FileSelection.at(0)).endsWith(ModInfo::s_HiddenExt)) {
- menu.addAction(m_UnhideAction);
- } else {
- menu.addAction(m_HideAction);
- }
- } else {
- m_FileSelection.clear();
- m_FileSelection.append(m_FileSystemModel->index(m_FileSystemModel->rootPath(), 0));
- }
- menu.exec(ui->fileTree->mapToGlobal(pos));
-}
-
-
-void ModInfoDialog::on_categoriesTree_itemChanged(QTreeWidgetItem *item, int)
-{
- QTreeWidgetItem *parent = item->parent();
- while ((parent != nullptr) && ((parent->flags() & Qt::ItemIsUserCheckable) != 0) && (parent->checkState(0) == Qt::Unchecked)) {
- parent->setCheckState(0, Qt::Checked);
- parent = parent->parent();
- }
- refreshPrimaryCategoriesBox();
-}
-
-
-void ModInfoDialog::addCheckedCategories(QTreeWidgetItem *tree)
-{
- for (int i = 0; i < tree->childCount(); ++i) {
- QTreeWidgetItem *child = tree->child(i);
- if (child->checkState(0) == Qt::Checked) {
- ui->primaryCategoryBox->addItem(child->text(0), child->data(0, Qt::UserRole));
- addCheckedCategories(child);
- }
- }
-}
-
-
-void ModInfoDialog::refreshPrimaryCategoriesBox()
-{
- ui->primaryCategoryBox->clear();
- int primaryCategory = m_ModInfo->getPrimaryCategory();
- addCheckedCategories(ui->categoriesTree->invisibleRootItem());
- for (int i = 0; i < ui->primaryCategoryBox->count(); ++i) {
- if (ui->primaryCategoryBox->itemData(i).toInt() == primaryCategory) {
- ui->primaryCategoryBox->setCurrentIndex(i);
- break;
- }
- }
-}
-
-
-void ModInfoDialog::on_primaryCategoryBox_currentIndexChanged(int index)
-{
- if (index != -1) {
- m_ModInfo->setPrimaryCategory(ui->primaryCategoryBox->itemData(index).toInt());
- }
-}
-
-
-void ModInfoDialog::on_overwriteTree_itemDoubleClicked(QTreeWidgetItem *item, int)
-{
- this->close();
- emit modOpen(item->data(1, Qt::UserRole).toString(), TAB_CONFLICTS);
-}
-
-
-bool ModInfoDialog::hideFile(const QString &oldName)
-{
- QString newName = oldName + ModInfo::s_HiddenExt;
-
- if (QFileInfo(newName).exists()) {
- if (QMessageBox::question(this, tr("Replace file?"), tr("There already is a hidden version of this file. Replace it?"),
- QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
- if (!QFile(newName).remove()) {
- QMessageBox::critical(this, tr("File operation failed"), tr("Failed to remove \"%1\". Maybe you lack the required file permissions?").arg(newName));
- return false;
- }
- } else {
- return false;
- }
- }
-
- if (QFile::rename(oldName, newName)) {
- return true;
- } else {
- reportError(tr("failed to rename %1 to %2").arg(oldName).arg(QDir::toNativeSeparators(newName)));
- return false;
- }
-}
-
-
-bool ModInfoDialog::unhideFile(const QString &oldName)
-{
- QString newName = oldName.left(oldName.length() - ModInfo::s_HiddenExt.length());
- if (QFileInfo(newName).exists()) {
- if (QMessageBox::question(this, tr("Replace file?"), tr("There already is a visible version of this file. Replace it?"),
- QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
- if (!QFile(newName).remove()) {
- QMessageBox::critical(this, tr("File operation failed"), tr("Failed to remove \"%1\". Maybe you lack the required file permissions?").arg(newName));
- return false;
- }
- } else {
- return false;
- }
- }
- if (QFile::rename(oldName, newName)) {
- return true;
- } else {
- reportError(tr("failed to rename %1 to %2").arg(QDir::toNativeSeparators(oldName)).arg(QDir::toNativeSeparators(newName)));
- return false;
- }
-}
-
-
-void ModInfoDialog::hideConflictFile()
-{
- if (hideFile(m_ConflictsContextItem->data(0, Qt::UserRole).toString())) {
- emit originModified(m_Origin->getID());
- refreshLists();
- }
-}
-
-
-void ModInfoDialog::unhideConflictFile()
-{
- if (unhideFile(m_ConflictsContextItem->data(0, Qt::UserRole).toString())) {
- emit originModified(m_Origin->getID());
- refreshLists();
- }
-}
-
-int ModInfoDialog::getBinaryExecuteInfo(const QFileInfo &targetInfo, QFileInfo &binaryInfo, QString &arguments)
-{
- QString extension = targetInfo.suffix();
- if ((extension.compare("cmd", Qt::CaseInsensitive) == 0) ||
- (extension.compare("com", Qt::CaseInsensitive) == 0) ||
- (extension.compare("bat", Qt::CaseInsensitive) == 0)) {
- binaryInfo = QFileInfo("C:\\Windows\\System32\\cmd.exe");
- arguments = QString("/C \"%1\"").arg(QDir::toNativeSeparators(targetInfo.absoluteFilePath()));
- return 1;
- }
- else if (extension.compare("exe", Qt::CaseInsensitive) == 0) {
- binaryInfo = targetInfo;
- return 1;
- }
- else if (extension.compare("jar", Qt::CaseInsensitive) == 0) {
- // types that need to be injected into
- std::wstring targetPathW = ToWString(targetInfo.absoluteFilePath());
- QString binaryPath;
-
- { // try to find java automatically
- WCHAR buffer[MAX_PATH];
- if (::FindExecutableW(targetPathW.c_str(), nullptr, buffer) > (HINSTANCE)32) {
- DWORD binaryType = 0UL;
- if (!::GetBinaryTypeW(buffer, &binaryType)) {
- qDebug("failed to determine binary type of \"%ls\": %lu", buffer, ::GetLastError());
- }
- else if (binaryType == SCS_32BIT_BINARY) {
- binaryPath = ToQString(buffer);
- }
- }
- }
- if (binaryPath.isEmpty() && (extension == "jar")) {
- // second attempt: look to the registry
- QSettings javaReg("HKEY_LOCAL_MACHINE\\Software\\JavaSoft\\Java Runtime Environment", QSettings::NativeFormat);
- if (javaReg.contains("CurrentVersion")) {
- QString currentVersion = javaReg.value("CurrentVersion").toString();
- binaryPath = javaReg.value(QString("%1/JavaHome").arg(currentVersion)).toString().append("\\bin\\javaw.exe");
- }
- }
- if (binaryPath.isEmpty()) {
- binaryPath = QFileDialog::getOpenFileName(this, tr("Select binary"), QString(), tr("Binary") + " (*.exe)");
- }
- if (binaryPath.isEmpty()) {
- return 0;
- }
- binaryInfo = QFileInfo(binaryPath);
- if (extension == "jar") {
- arguments = QString("-jar \"%1\"").arg(QDir::toNativeSeparators(targetInfo.absoluteFilePath()));
- }
- else {
- arguments = QString("\"%1\"").arg(QDir::toNativeSeparators(targetInfo.absoluteFilePath()));
- }
- return 1;
- }
- else {
- return 2;
- }
-}
-
-void ModInfoDialog::openDataFile()
-{
- if (m_ConflictsContextItem != nullptr) {
- QFileInfo targetInfo(m_ConflictsContextItem->data(0, Qt::UserRole).toString());
- QFileInfo binaryInfo;
- QString arguments;
- switch (getBinaryExecuteInfo(targetInfo, binaryInfo, arguments)) {
- case 1: {
- m_OrganizerCore->spawnBinaryDirect(
- binaryInfo, arguments, m_OrganizerCore->currentProfile()->name(),
- targetInfo.absolutePath(), "", "");
- } break;
- case 2: {
- ::ShellExecuteW(nullptr, L"open",
- ToWString(targetInfo.absoluteFilePath()).c_str(),
- nullptr, nullptr, SW_SHOWNORMAL);
- } break;
- default: {
- // nop
- } break;
- }
- }
-}
-
-void ModInfoDialog::previewDataFile()
-{
- QString fileName = QDir::fromNativeSeparators(m_ConflictsContextItem->data(0, Qt::UserRole).toString());
-
- // what we have is an absolute path to the file in its actual location (for the primary origin)
- // what we want is the path relative to the virtual data directory
-
- // we need to look in the virtual directory for the file to make sure the info is up to date.
-
- // check if the file comes from the actual data folder instead of a mod
- QDir gameDirectory = m_OrganizerCore->managedGame()->dataDirectory().absolutePath();
- QString relativePath = gameDirectory.relativeFilePath(fileName);
- QDir direRelativePath = gameDirectory.relativeFilePath(fileName);
- // if the file is on a different drive the dirRelativePath will actually be an absolute path so we make sure that is not the case
- if (!direRelativePath.isAbsolute() && !relativePath.startsWith("..")) {
- fileName = relativePath;
- }
- else {
- // crude: we search for the next slash after the base mod directory to skip everything up to the data-relative directory
- int offset = m_OrganizerCore->settings().getModDirectory().size() + 1;
- offset = fileName.indexOf("/", offset);
- fileName = fileName.mid(offset + 1);
- }
-
-
-
- const FileEntry::Ptr file = m_OrganizerCore->directoryStructure()->searchFile(ToWString(fileName), nullptr);
-
- if (file.get() == nullptr) {
- reportError(tr("file not found: %1").arg(qUtf8Printable(fileName)));
- return;
- }
-
- // set up preview dialog
- PreviewDialog preview(fileName);
- auto addFunc = [&](int originId) {
- FilesOrigin &origin = m_OrganizerCore->directoryStructure()->getOriginByID(originId);
- QString filePath = QDir::fromNativeSeparators(ToQString(origin.getPath())) + "/" + fileName;
- if (QFile::exists(filePath)) {
- // it's very possible the file doesn't exist, because it's inside an archive. we don't support that
- QWidget *wid = m_PluginContainer->previewGenerator().genPreview(filePath);
- if (wid == nullptr) {
- reportError(tr("failed to generate preview for %1").arg(filePath));
- }
- else {
- preview.addVariant(ToQString(origin.getName()), wid);
- }
- }
- };
-
- addFunc(file->getOrigin());
- for (auto alt : file->getAlternatives()) {
- addFunc(alt.first);
- }
- if (preview.numVariants() > 0) {
- preview.exec();
- }
- else {
- QMessageBox::information(this, tr("Sorry"), tr("Sorry, can't preview anything. This function currently does not support extracting from bsas."));
- }
-}
-
-
-void ModInfoDialog::on_overwriteTree_customContextMenuRequested(const QPoint &pos)
-{
- m_ConflictsContextItem = ui->overwriteTree->itemAt(pos.x(), pos.y());
-
- if (m_ConflictsContextItem != nullptr) {
- // offer to hide/unhide file, but not for files from archives
- if (!m_ConflictsContextItem->data(1, Qt::UserRole + 2).toBool()) {
- QMenu menu;
- if (m_ConflictsContextItem->text(0).endsWith(ModInfo::s_HiddenExt)) {
- menu.addAction(tr("Un-Hide"), this, SLOT(unhideConflictFile()));
- } else {
- menu.addAction(tr("Hide"), this, SLOT(hideConflictFile()));
- }
-
- menu.addAction(tr("Open/Execute"), this, SLOT(openDataFile()));
-
- QString fileName = m_ConflictsContextItem->data(0, Qt::UserRole).toString();
- if (m_PluginContainer->previewGenerator().previewSupported(QFileInfo(fileName).suffix())) {
- menu.addAction(tr("Preview"), this, SLOT(previewDataFile()));
- }
-
- menu.exec(ui->overwriteTree->mapToGlobal(pos));
- }
- }
-}
-
-void ModInfoDialog::on_overwrittenTree_customContextMenuRequested(const QPoint &pos)
-{
- m_ConflictsContextItem = ui->overwrittenTree->itemAt(pos.x(), pos.y());
-
- if (m_ConflictsContextItem != nullptr) {
- if (!m_ConflictsContextItem->data(1, Qt::UserRole + 2).toBool()) {
- QMenu menu;
-
- menu.addAction(tr("Open/Execute"), this, SLOT(openDataFile()));
-
- QString fileName = m_ConflictsContextItem->data(0, Qt::UserRole).toString();
- if (m_PluginContainer->previewGenerator().previewSupported(QFileInfo(fileName).suffix())) {
- menu.addAction(tr("Preview"), this, SLOT(previewDataFile()));
- }
-
- menu.exec(ui->overwrittenTree->mapToGlobal(pos));
- }
- }
-}
-
-
-void ModInfoDialog::on_overwrittenTree_itemDoubleClicked(QTreeWidgetItem *item, int)
-{
- emit modOpen(item->data(1, Qt::UserRole).toString(), TAB_CONFLICTS);
- this->accept();
-}
-
-void ModInfoDialog::on_refreshButton_clicked()
-{
- m_ModInfo->updateNXMInfo();
-
- MessageDialog::showMessage(tr("Info requested, please wait"), this);
-}
-
-void ModInfoDialog::on_endorseBtn_clicked()
-{
- emit endorseMod(m_ModInfo);
-}
-
-void ModInfoDialog::on_nextButton_clicked()
-{
- int currentTab = ui->tabWidget->currentIndex();
- int tab = m_RealTabPos[currentTab];
-
- emit modOpenNext(tab);
- this->accept();
-}
-
-void ModInfoDialog::on_prevButton_clicked()
-{
- int currentTab = ui->tabWidget->currentIndex();
- int tab = m_RealTabPos[currentTab];
-
- emit modOpenPrev(tab);
- this->accept();
-}
-
-
-void ModInfoDialog::createTweak()
-{
- QString name = QInputDialog::getText(this, tr("Name"), tr("Please enter a name"));
- if (name.isNull()) {
- return;
- } else if (!fixDirectoryName(name)) {
- QMessageBox::critical(this, tr("Error"), tr("Invalid name. Must be a valid file name"));
- return;
- } else if (ui->iniTweaksList->findItems(name, Qt::MatchFixedString).count() != 0) {
- QMessageBox::critical(this, tr("Error"), tr("A tweak by that name exists"));
- return;
- }
-
- QListWidgetItem *newTweak = new QListWidgetItem(name + ".ini");
- newTweak->setData(Qt::UserRole, "INI Tweaks/" + name + ".ini");
- newTweak->setFlags(newTweak->flags() | Qt::ItemIsUserCheckable);
- newTweak->setCheckState(Qt::Unchecked);
- ui->iniTweaksList->addItem(newTweak);
-}
-
-void ModInfoDialog::on_iniTweaksList_customContextMenuRequested(const QPoint &pos)
-{
- QMenu menu;
- menu.addAction(tr("Create Tweak"), this, SLOT(createTweak()));
- menu.exec(ui->iniTweaksList->mapToGlobal(pos));
-}
+/*
+Copyright (C) 2012 Sebastian Herbord. All rights reserved.
+
+This file is part of Mod Organizer.
+
+Mod Organizer is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+Mod Organizer is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Mod Organizer. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "modinfodialog.h"
+#include "ui_modinfodialog.h"
+#include "descriptionpage.h"
+#include "mainwindow.h"
+
+#include "modidlineedit.h"
+#include "iplugingame.h"
+#include "nexusinterface.h"
+#include "report.h"
+#include "utility.h"
+#include "messagedialog.h"
+#include "bbcode.h"
+#include "questionboxmemory.h"
+#include "settings.h"
+#include "categories.h"
+#include "organizercore.h"
+#include "pluginlistsortproxy.h"
+#include "previewgenerator.h"
+#include "previewdialog.h"
+
+#include <QDir>
+#include <QDirIterator>
+#include <QPushButton>
+#include <QInputDialog>
+#include <QMessageBox>
+#include <QMenu>
+#include <QFileSystemModel>
+#include <QInputDialog>
+#include <QPointer>
+#include <QFileDialog>
+#include <QShortcut>
+
+#include <Shlwapi.h>
+
+#include <sstream>
+
+
+using namespace MOBase;
+using namespace MOShared;
+
+
+class ModFileListWidget : public QListWidgetItem {
+ friend bool operator<(const ModFileListWidget &LHS, const ModFileListWidget &RHS);
+public:
+ ModFileListWidget(const QString &text, int sortValue, QListWidget *parent = 0)
+ : QListWidgetItem(text, parent, QListWidgetItem::UserType + 1), m_SortValue(sortValue) {}
+private:
+ int m_SortValue;
+};
+
+
+static bool operator<(const ModFileListWidget &LHS, const ModFileListWidget &RHS)
+{
+ return LHS.m_SortValue < RHS.m_SortValue;
+}
+
+
+ModInfoDialog::ModInfoDialog(ModInfo::Ptr modInfo, const DirectoryEntry *directory, bool unmanaged, OrganizerCore *organizerCore, PluginContainer *pluginContainer, QWidget *parent)
+ : TutorableDialog("ModInfoDialog", parent), ui(new Ui::ModInfoDialog), m_ModInfo(modInfo),
+ m_ThumbnailMapper(this), m_RequestStarted(false),
+ m_DeleteAction(nullptr), m_RenameAction(nullptr), m_OpenAction(nullptr),
+ m_Directory(directory), m_Origin(nullptr),
+ m_OrganizerCore(organizerCore), m_PluginContainer(pluginContainer)
+{
+ ui->setupUi(this);
+ this->setWindowTitle(modInfo->name());
+ this->setWindowModality(Qt::WindowModal);
+
+ m_RootPath = modInfo->absolutePath();
+
+ QString metaFileName = m_RootPath.mid(0).append("/meta.ini");
+ m_Settings = new QSettings(metaFileName, QSettings::IniFormat);
+
+ QLineEdit *modIDEdit = findChild<QLineEdit*>("modIDEdit");
+ ui->modIDEdit->setValidator(new QIntValidator(modIDEdit));
+ ui->modIDEdit->setText(QString("%1").arg(modInfo->getNexusID()));
+
+ connect(ui->modIDEdit, SIGNAL(linkClicked(QString)), this, SLOT(linkClicked(QString)));
+
+ QString gameName = modInfo->getGameName();
+ ui->sourceGameEdit->addItem(organizerCore->managedGame()->gameName(), organizerCore->managedGame()->gameShortName());
+ if (organizerCore->managedGame()->validShortNames().size() == 0) {
+ ui->sourceGameEdit->setDisabled(true);
+ } else {
+ for (auto game : pluginContainer->plugins<IPluginGame>()) {
+ for (QString gameName : organizerCore->managedGame()->validShortNames()) {
+ if (game->gameShortName().compare(gameName, Qt::CaseInsensitive) == 0) {
+ ui->sourceGameEdit->addItem(game->gameName(), game->gameShortName());
+ break;
+ }
+ }
+ }
+ }
+ ui->sourceGameEdit->setCurrentIndex(ui->sourceGameEdit->findData(gameName));
+
+ ui->commentsEdit->setText(modInfo->comments());
+ ui->notesEdit->setText(modInfo->notes());
+
+ ui->descriptionView->setPage(new DescriptionPage());
+
+ connect(&m_ThumbnailMapper, SIGNAL(mapped(const QString&)), this, SIGNAL(thumbnailClickedSignal(const QString&)));
+ connect(this, SIGNAL(thumbnailClickedSignal(const QString&)), this, SLOT(thumbnailClicked(const QString&)));
+ connect(m_ModInfo.data(), SIGNAL(modDetailsUpdated(bool)), this, SLOT(modDetailsUpdated(bool)));
+ connect(ui->descriptionView->page(), SIGNAL(linkClicked(QUrl)), this, SLOT(linkClicked(QUrl)));
+ //TODO: No easy way to delegate links
+ //ui->descriptionView->page()->acceptNavigationRequest(QWebEnginePage::DelegateAllLinks);
+
+ new QShortcut(QKeySequence::Delete, this, SLOT(delete_activated()));
+
+ if (directory->originExists(ToWString(modInfo->name()))) {
+ m_Origin = &directory->getOriginByName(ToWString(modInfo->name()));
+ if (m_Origin->isDisabled()) {
+ m_Origin = nullptr;
+ }
+ }
+
+ refreshLists();
+
+ if (modInfo->hasFlag(ModInfo::FLAG_SEPARATOR))
+ {
+ ui->tabWidget->setTabEnabled(TAB_TEXTFILES, false);
+ ui->tabWidget->setTabEnabled(TAB_INIFILES, false);
+ ui->tabWidget->setTabEnabled(TAB_IMAGES, false);
+ ui->tabWidget->setTabEnabled(TAB_ESPS, false);
+ ui->tabWidget->setTabEnabled(TAB_CONFLICTS, false);
+ //ui->tabWidget->setTabEnabled(TAB_CATEGORIES, false);
+ addCategories(CategoryFactory::instance(), modInfo->getCategories(), ui->categoriesTree->invisibleRootItem(), 0);
+ refreshPrimaryCategoriesBox();
+ ui->tabWidget->setTabEnabled(TAB_NEXUS, false);
+ //ui->tabWidget->setTabEnabled(TAB_NOTES, false);
+ ui->tabWidget->setTabEnabled(TAB_FILETREE, false);
+ }
+ else if (unmanaged)
+ {
+ ui->tabWidget->setTabEnabled(TAB_INIFILES, false);
+ ui->tabWidget->setTabEnabled(TAB_CATEGORIES, false);
+ ui->tabWidget->setTabEnabled(TAB_NEXUS, false);
+ ui->tabWidget->setTabEnabled(TAB_FILETREE, false);
+ ui->tabWidget->setTabEnabled(TAB_NOTES, false);
+ ui->tabWidget->setTabEnabled(TAB_ESPS, false);
+ ui->tabWidget->setTabEnabled(TAB_TEXTFILES, false);
+ ui->tabWidget->setTabEnabled(TAB_IMAGES, false);
+ } else {
+ initFiletree(modInfo);
+ addCategories(CategoryFactory::instance(), modInfo->getCategories(), ui->categoriesTree->invisibleRootItem(), 0);
+ refreshPrimaryCategoriesBox();
+ ui->tabWidget->setTabEnabled(TAB_TEXTFILES, ui->textFileList->count() != 0);
+ ui->tabWidget->setTabEnabled(TAB_IMAGES, ui->thumbnailArea->count() != 0);
+ ui->tabWidget->setTabEnabled(TAB_ESPS, (ui->inactiveESPList->count() != 0) || (ui->activeESPList->count() != 0));
+ }
+ initINITweaks();
+
+ ui->tabWidget->setTabEnabled(TAB_CONFLICTS, m_Origin != nullptr);
+
+
+ ui->endorseBtn->setVisible(Settings::instance().endorsementIntegration());
+ ui->endorseBtn->setEnabled((m_ModInfo->endorsedState() == ModInfo::ENDORSED_FALSE) ||
+ (m_ModInfo->endorsedState() == ModInfo::ENDORSED_NEVER));
+
+ // activate first enabled tab
+ for (int i = 0; i < ui->tabWidget->count(); ++i) {
+ if (ui->tabWidget->isTabEnabled(i)) {
+ ui->tabWidget->setCurrentIndex(i);
+ break;
+ }
+ }
+
+ if (ui->tabWidget->currentIndex() == TAB_NEXUS) {
+ activateNexusTab();
+ }
+}
+
+
+ModInfoDialog::~ModInfoDialog()
+{
+ m_ModInfo->setComments(ui->commentsEdit->text());
+ //Avoid saving html stump if notes field is empty.
+ if (ui->notesEdit->toPlainText().isEmpty())
+ m_ModInfo->setNotes(ui->notesEdit->toPlainText());
+ else
+ m_ModInfo->setNotes(ui->notesEdit->toHtml());
+ saveCategories(ui->categoriesTree->invisibleRootItem());
+ saveIniTweaks(); // ini tweaks are written to the ini file directly. This is the only information not managed by ModInfo
+ delete ui->descriptionView->page();
+ delete ui->descriptionView;
+ delete ui;
+ delete m_Settings;
+}
+
+
+void ModInfoDialog::initINITweaks()
+{
+ int numTweaks = m_Settings->beginReadArray("INI Tweaks");
+ for (int i = 0; i < numTweaks; ++i) {
+ m_Settings->setArrayIndex(i);
+ QList<QListWidgetItem*> items = ui->iniTweaksList->findItems(m_Settings->value("name").toString(), Qt::MatchFixedString);
+ if (items.size() != 0) {
+ items.at(0)->setCheckState(Qt::Checked);
+ }
+ }
+ m_Settings->endArray();
+}
+
+void ModInfoDialog::initFiletree(ModInfo::Ptr modInfo)
+{
+ ui->fileTree = findChild<QTreeView*>("fileTree");
+
+ m_FileSystemModel = new QFileSystemModel(this);
+ m_FileSystemModel->setReadOnly(false);
+ m_FileSystemModel->setRootPath(m_RootPath);
+ ui->fileTree->setModel(m_FileSystemModel);
+ ui->fileTree->setRootIndex(m_FileSystemModel->index(m_RootPath));
+ ui->fileTree->setColumnWidth(0, 300);
+
+ m_DeleteAction = new QAction(tr("&Delete"), ui->fileTree);
+ m_RenameAction = new QAction(tr("&Rename"), ui->fileTree);
+ m_HideAction = new QAction(tr("&Hide"), ui->fileTree);
+ m_UnhideAction = new QAction(tr("&Unhide"), ui->fileTree);
+ m_OpenAction = new QAction(tr("&Open"), ui->fileTree);
+ m_NewFolderAction = new QAction(tr("&New Folder"), ui->fileTree);
+ QObject::connect(m_DeleteAction, SIGNAL(triggered()), this, SLOT(deleteTriggered()));
+ QObject::connect(m_RenameAction, SIGNAL(triggered()), this, SLOT(renameTriggered()));
+ QObject::connect(m_OpenAction, SIGNAL(triggered()), this, SLOT(openTriggered()));
+ QObject::connect(m_NewFolderAction, SIGNAL(triggered()), this, SLOT(createDirectoryTriggered()));
+ QObject::connect(m_HideAction, SIGNAL(triggered()), this, SLOT(hideTriggered()));
+ connect(m_UnhideAction, SIGNAL(triggered()), this, SLOT(unhideTriggered()));
+}
+
+
+int ModInfoDialog::tabIndex(const QString &tabId)
+{
+ for (int i = 0; i < ui->tabWidget->count(); ++i) {
+ if (ui->tabWidget->widget(i)->objectName() == tabId) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+
+void ModInfoDialog::restoreTabState(const QByteArray &state)
+{
+ QDataStream stream(state);
+ int count = 0;
+ stream >> count;
+
+ QStringList tabIds;
+
+ // first, only determine the new mapping
+ for (int newPos = 0; newPos < count; ++newPos) {
+ QString tabId;
+ stream >> tabId;
+ tabIds.append(tabId);
+ int oldPos = tabIndex(tabId);
+ if (oldPos != -1) {
+ m_RealTabPos[newPos] = oldPos;
+ } else {
+ m_RealTabPos[newPos] = newPos;
+ }
+ }
+ // then actually move the tabs
+ QTabBar *tabBar = ui->tabWidget->findChild<QTabBar*>("qt_tabwidget_tabbar"); // magic name = bad
+ ui->tabWidget->blockSignals(true);
+ for (int newPos = 0; newPos < count; ++newPos) {
+ QString tabId = tabIds.at(newPos);
+ int oldPos = tabIndex(tabId);
+ tabBar->moveTab(oldPos, newPos);
+ }
+ ui->tabWidget->blockSignals(false);
+}
+
+
+QByteArray ModInfoDialog::saveTabState() const
+{
+ QByteArray result;
+ QDataStream stream(&result, QIODevice::WriteOnly);
+ stream << ui->tabWidget->count();
+ for (int i = 0; i < ui->tabWidget->count(); ++i) {
+ stream << ui->tabWidget->widget(i)->objectName();
+ }
+
+ return result;
+}
+
+
+void ModInfoDialog::refreshLists()
+{
+ int numNonConflicting = 0;
+ int numOverwrite = 0;
+ int numOverwritten = 0;
+
+ ui->overwriteTree->clear();
+ ui->overwrittenTree->clear();
+
+ if (m_Origin != nullptr) {
+ std::vector<FileEntry::Ptr> files = m_Origin->getFiles();
+ for (auto iter = files.begin(); iter != files.end(); ++iter) {
+ QString relativeName = QDir::fromNativeSeparators(ToQString((*iter)->getRelativePath()));
+ QString fileName = relativeName.mid(0).prepend(m_RootPath);
+ bool archive;
+ if ((*iter)->getOrigin(archive) == m_Origin->getID()) {
+ std::vector<std::pair<int, std::pair<std::wstring, int>>> alternatives = (*iter)->getAlternatives();
+ if (!alternatives.empty()) {
+ std::wostringstream altString;
+ for (std::vector<std::pair<int, std::pair<std::wstring, int>>>::iterator altIter = alternatives.begin();
+ altIter != alternatives.end(); ++altIter) {
+ if (altIter != alternatives.begin()) {
+ altString << ", ";
+ }
+ altString << m_Directory->getOriginByID(altIter->first).getName();
+ }
+ QStringList fields(relativeName.prepend("..."));
+ fields.append(ToQString(altString.str()));
+
+ QTreeWidgetItem *item = new QTreeWidgetItem(fields);
+ item->setData(0, Qt::UserRole, fileName);
+ item->setData(1, Qt::UserRole, ToQString(m_Directory->getOriginByID(alternatives.back().first).getName()));
+ item->setData(1, Qt::UserRole + 1, alternatives.back().first);
+ item->setData(1, Qt::UserRole + 2, archive);
+ if (archive) {
+ QFont font = item->font(0);
+ font.setItalic(true);
+ item->setFont(0, font);
+ item->setFont(1, font);
+ }
+ ui->overwriteTree->addTopLevelItem(item);
+ ++numOverwrite;
+ } else {// otherwise don't display the file
+ ++numNonConflicting;
+ }
+ } else {
+ FilesOrigin &realOrigin = m_Directory->getOriginByID((*iter)->getOrigin(archive));
+ QStringList fields(relativeName);
+ fields.append(ToQString(realOrigin.getName()));
+ QTreeWidgetItem *item = new QTreeWidgetItem(fields);
+ item->setData(0, Qt::UserRole, fileName);
+ item->setData(1, Qt::UserRole, ToQString(realOrigin.getName()));
+ item->setData(1, Qt::UserRole + 2, archive);
+ if (archive) {
+ QFont font = item->font(0);
+ font.setItalic(true);
+ item->setFont(0, font);
+ item->setFont(1, font);
+ }
+ ui->overwrittenTree->addTopLevelItem(item);
+ ++numOverwritten;
+ }
+ }
+ }
+
+ if (m_RootPath.length() > 0) {
+ QDirIterator dirIterator(m_RootPath, QDir::Files, QDirIterator::Subdirectories);
+ while (dirIterator.hasNext()) {
+ QString fileName = dirIterator.next();
+
+ if (fileName.endsWith(".txt", Qt::CaseInsensitive)) {
+ ui->textFileList->addItem(fileName.mid(m_RootPath.length() + 1));
+ } else if ((fileName.endsWith(".ini", Qt::CaseInsensitive) || fileName.endsWith(".cfg", Qt::CaseInsensitive)) &&
+ !fileName.endsWith("meta.ini")) {
+ QString namePart = fileName.mid(m_RootPath.length() + 1);
+ if (namePart.startsWith("INI Tweaks", Qt::CaseInsensitive)) {
+ QListWidgetItem *newItem = new QListWidgetItem(namePart.mid(11), ui->iniTweaksList);
+ newItem->setData(Qt::UserRole, namePart);
+ newItem->setFlags(newItem->flags() | Qt::ItemIsUserCheckable);
+ newItem->setCheckState(Qt::Unchecked);
+ ui->iniTweaksList->addItem(newItem);
+ } else {
+ ui->iniFileList->addItem(namePart);
+ }
+ } else if (fileName.endsWith(".esp", Qt::CaseInsensitive) ||
+ fileName.endsWith(".esm", Qt::CaseInsensitive) ||
+ fileName.endsWith(".esl", Qt::CaseInsensitive)) {
+ QString relativePath = fileName.mid(m_RootPath.length() + 1);
+ if (relativePath.contains('/')) {
+ QFileInfo fileInfo(fileName);
+ QListWidgetItem *newItem = new QListWidgetItem(fileInfo.fileName());
+ newItem->setData(Qt::UserRole, relativePath);
+ ui->inactiveESPList->addItem(newItem);
+ } else {
+ ui->activeESPList->addItem(relativePath);
+ }
+ } else if ((fileName.endsWith(".png", Qt::CaseInsensitive)) ||
+ (fileName.endsWith(".jpg", Qt::CaseInsensitive))) {
+ QImage image = QImage(fileName);
+ if (!image.isNull()) {
+ if (static_cast<float>(image.width()) / static_cast<float>(image.height()) > 1.34) {
+ image = image.scaledToWidth(128);
+ } else {
+ image = image.scaledToHeight(96);
+ }
+
+ QPushButton *thumbnailButton = new QPushButton(QPixmap::fromImage(image), "");
+ thumbnailButton->setIconSize(QSize(image.width(), image.height()));
+ connect(thumbnailButton, SIGNAL(clicked()), &m_ThumbnailMapper, SLOT(map()));
+ m_ThumbnailMapper.setMapping(thumbnailButton, fileName);
+ ui->thumbnailArea->addWidget(thumbnailButton);
+ }
+ }
+ }
+ }
+
+ ui->overwriteCount->display(numOverwrite);
+ ui->overwrittenCount->display(numOverwritten);
+ ui->noConflictCount->display(numNonConflicting);
+}
+
+
+void ModInfoDialog::addCategories(const CategoryFactory &factory, const std::set<int> &enabledCategories, QTreeWidgetItem *root, int rootLevel)
+{
+ for (int i = 0; i < static_cast<int>(factory.numCategories()); ++i) {
+ if (factory.getParentID(i) != rootLevel) {
+ continue;
+ }
+ int categoryID = factory.getCategoryID(i);
+ QTreeWidgetItem *newItem
+ = new QTreeWidgetItem(QStringList(factory.getCategoryName(i)));
+ newItem->setFlags(newItem->flags() | Qt::ItemIsUserCheckable);
+ newItem->setCheckState(0, enabledCategories.find(categoryID)
+ != enabledCategories.end()
+ ? Qt::Checked
+ : Qt::Unchecked);
+ newItem->setData(0, Qt::UserRole, categoryID);
+ if (factory.hasChildren(i)) {
+ addCategories(factory, enabledCategories, newItem, categoryID);
+ }
+ root->addChild(newItem);
+ }
+}
+
+
+void ModInfoDialog::saveCategories(QTreeWidgetItem *currentNode)
+{
+ for (int i = 0; i < currentNode->childCount(); ++i) {
+ QTreeWidgetItem *childNode = currentNode->child(i);
+ m_ModInfo->setCategory(childNode->data(0, Qt::UserRole).toInt(), childNode->checkState(0));
+ saveCategories(childNode);
+ }
+}
+
+
+void ModInfoDialog::on_closeButton_clicked()
+{
+ if (allowNavigateFromTXT() && allowNavigateFromINI()) {
+ this->close();
+ }
+}
+
+
+
+QString ModInfoDialog::getModVersion() const
+{
+ return m_Settings->value("version", "").toString();
+}
+
+
+const int ModInfoDialog::getModID() const
+{
+ return m_Settings->value("modid", 0).toInt();
+}
+
+void ModInfoDialog::openTab(int tab)
+{
+ QTabWidget *tabWidget = findChild<QTabWidget*>("tabWidget");
+ if (tabWidget->isTabEnabled(tab)) {
+ tabWidget->setCurrentIndex(tab);
+ }
+}
+
+void ModInfoDialog::thumbnailClicked(const QString &fileName)
+{
+ QLabel *imageLabel = findChild<QLabel*>("imageLabel");
+ imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
+ QImage image(fileName);
+ if (static_cast<float>(image.width()) / static_cast<float>(image.height()) > 1.34) {
+ image = image.scaledToWidth(imageLabel->geometry().width());
+ } else {
+ image = image.scaledToHeight(imageLabel->geometry().height());
+ }
+ imageLabel->setPixmap(QPixmap::fromImage(image));
+}
+
+bool ModInfoDialog::allowNavigateFromTXT()
+{
+ if (ui->saveTXTButton->isEnabled()) {
+ int res = QMessageBox::question(this, tr("Save changes?"), tr("Save changes to \"%1\"?").arg(ui->textFileView->property("currentFile").toString()),
+ QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
+ if (res == QMessageBox::Cancel) {
+ return false;
+ } else if (res == QMessageBox::Yes) {
+ saveCurrentTextFile();
+ }
+ }
+ return true;
+}
+
+
+bool ModInfoDialog::allowNavigateFromINI()
+{
+ if (ui->saveButton->isEnabled()) {
+ int res = QMessageBox::question(this, tr("Save changes?"), tr("Save changes to \"%1\"?").arg(ui->iniFileView->property("currentFile").toString()),
+ QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
+ if (res == QMessageBox::Cancel) {
+ return false;
+ } else if (res == QMessageBox::Yes) {
+ saveCurrentIniFile();
+ }
+ }
+ return true;
+}
+
+
+void ModInfoDialog::on_textFileList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
+{
+ QString fullPath = m_RootPath + "/" + current->text();
+
+ QVariant currentFile = ui->textFileView->property("currentFile");
+ if (currentFile.isValid() && (currentFile.toString() == fullPath)) {
+ // the new file is the same as the currently displayed file. May be the result of a cancelation
+ return;
+ }
+
+ if (allowNavigateFromTXT()) {
+ openTextFile(fullPath);
+ } else {
+ ui->textFileList->setCurrentItem(previous, QItemSelectionModel::Current);
+ }
+}
+
+
+void ModInfoDialog::openTextFile(const QString &fileName)
+{
+ QString encoding;
+ ui->textFileView->setText(MOBase::readFileText(fileName, &encoding));
+ ui->textFileView->setProperty("currentFile", fileName);
+ ui->textFileView->setProperty("encoding", encoding);
+ ui->saveTXTButton->setEnabled(false);
+}
+
+
+void ModInfoDialog::openIniFile(const QString &fileName)
+{
+ QFile iniFile(fileName);
+ iniFile.open(QIODevice::ReadOnly);
+ QByteArray buffer = iniFile.readAll();
+
+ QTextCodec *codec = QTextCodec::codecForUtfText(buffer, QTextCodec::codecForName("utf-8"));
+ QTextEdit *iniFileView = findChild<QTextEdit*>("iniFileView");
+ iniFileView->setText(codec->toUnicode(buffer));
+ iniFileView->setProperty("currentFile", fileName);
+ iniFileView->setProperty("encoding", codec->name());
+ iniFile.close();
+
+ ui->saveButton->setEnabled(false);
+}
+
+
+void ModInfoDialog::saveIniTweaks()
+{
+ m_Settings->remove("INI Tweaks");
+ m_Settings->beginWriteArray("INI Tweaks");
+
+ int countEnabled = 0;
+ for (int i = 0; i < ui->iniTweaksList->count(); ++i) {
+ if (ui->iniTweaksList->item(i)->checkState() == Qt::Checked) {
+ m_Settings->setArrayIndex(countEnabled++);
+ m_Settings->setValue("name", ui->iniTweaksList->item(i)->text());
+ }
+ }
+ m_Settings->endArray();
+}
+
+
+void ModInfoDialog::on_iniFileList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
+{
+ QString fullPath = m_RootPath + "/" + current->text();
+
+ QVariant currentFile = ui->iniFileView->property("currentFile");
+ if (currentFile.isValid() && (currentFile.toString() == fullPath)) {
+ // the new file is the same as the currently displayed file. May be the result of a cancelation
+ return;
+ }
+
+ if (allowNavigateFromINI()) {
+ openIniFile(fullPath);
+ } else {
+ ui->iniFileList->setCurrentItem(previous, QItemSelectionModel::Current);
+ }
+}
+
+
+void ModInfoDialog::on_iniTweaksList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
+{
+ QString fullPath = m_RootPath + "/" + current->data(Qt::UserRole).toString();
+
+ QVariant currentFile = ui->iniFileView->property("currentFile");
+ if (currentFile.isValid() && (currentFile.toString() == fullPath)) {
+ // the new file is the same as the currently displayed file. May be the result of a cancelation
+ return;
+ }
+
+ if (allowNavigateFromINI()) {
+ openIniFile(fullPath);
+ } else {
+ ui->iniFileList->setCurrentItem(previous, QItemSelectionModel::Current);
+ }
+
+}
+
+
+void ModInfoDialog::on_saveButton_clicked()
+{
+ saveCurrentIniFile();
+}
+
+
+void ModInfoDialog::on_saveTXTButton_clicked()
+{
+ saveCurrentTextFile();
+}
+
+
+void ModInfoDialog::saveCurrentTextFile()
+{
+ QVariant fileNameVar = ui->textFileView->property("currentFile");
+ QVariant encodingVar = ui->textFileView->property("encoding");
+ if (fileNameVar.isValid() && encodingVar.isValid()) {
+ QString fileName = fileNameVar.toString();
+ QFile txtFile(fileName);
+ txtFile.open(QIODevice::WriteOnly);
+ txtFile.resize(0);
+ QTextCodec *codec = QTextCodec::codecForName(encodingVar.toString().toUtf8());
+ QString data = ui->textFileView->toPlainText().replace("\n", "\r\n");
+ txtFile.write(codec->fromUnicode(data));
+ } else {
+ reportError("no file selected");
+ }
+ ui->saveTXTButton->setEnabled(false);
+}
+
+
+void ModInfoDialog::saveCurrentIniFile()
+{
+ QVariant fileNameVar = ui->iniFileView->property("currentFile");
+ QVariant encodingVar = ui->iniFileView->property("encoding");
+ if (fileNameVar.isValid() && !fileNameVar.toString().isEmpty()) {
+ QString fileName = fileNameVar.toString();
+ QDir().mkpath(QFileInfo(fileName).absolutePath());
+ QFile txtFile(fileName);
+ txtFile.open(QIODevice::WriteOnly);
+ txtFile.resize(0);
+ QTextCodec *codec = QTextCodec::codecForName(encodingVar.toString().toUtf8());
+ QString data = ui->iniFileView->toPlainText().replace("\n", "\r\n");
+ txtFile.write(codec->fromUnicode(data));
+ } else {
+ reportError("no file selected");
+ }
+ ui->saveButton->setEnabled(false);
+}
+
+
+void ModInfoDialog::on_iniFileView_textChanged()
+{
+ QPushButton* saveButton = findChild<QPushButton*>("saveButton");
+ saveButton->setEnabled(true);
+}
+
+
+void ModInfoDialog::on_textFileView_textChanged()
+{
+ ui->saveTXTButton->setEnabled(true);
+}
+
+
+void ModInfoDialog::on_activateESP_clicked()
+{
+ QListWidget *activeESPList = findChild<QListWidget*>("activeESPList");
+ QListWidget *inactiveESPList = findChild<QListWidget*>("inactiveESPList");
+
+ int selectedRow = inactiveESPList->currentRow();
+ if (selectedRow < 0) {
+ return;
+ }
+
+ QListWidgetItem *selectedItem = inactiveESPList->takeItem(selectedRow);
+
+ QDir root(m_RootPath);
+ bool renamed = false;
+
+ while (root.exists(selectedItem->text())) {
+ bool okClicked = false;
+ QString newName = QInputDialog::getText(this, tr("File Exists"), tr("A file with that name exists, please enter a new one"), QLineEdit::Normal, selectedItem->text(), &okClicked);
+ if (!okClicked) {
+ inactiveESPList->insertItem(selectedRow, selectedItem);
+ return;
+ } else if (newName.size() > 0) {
+ selectedItem->setText(newName);
+ renamed = true;
+ }
+ }
+
+ if (root.rename(selectedItem->data(Qt::UserRole).toString(), selectedItem->text())) {
+ activeESPList->addItem(selectedItem);
+ if (renamed) {
+ selectedItem->setData(Qt::UserRole, QVariant());
+ }
+ } else {
+ inactiveESPList->insertItem(selectedRow, selectedItem);
+ reportError(tr("failed to move file"));
+ }
+}
+
+
+void ModInfoDialog::on_deactivateESP_clicked()
+{
+ QListWidget *activeESPList = findChild<QListWidget*>("activeESPList");
+ QListWidget *inactiveESPList = findChild<QListWidget*>("inactiveESPList");
+
+ int selectedRow = activeESPList->currentRow();
+ if (selectedRow < 0) {
+ return;
+ }
+
+ QDir root(m_RootPath);
+
+ QListWidgetItem *selectedItem = activeESPList->takeItem(selectedRow);
+
+ // if we moved the file from optional to active in this session, we move the file back to
+ // where it came from. Otherwise, it is moved to the new folder "optional"
+ if (selectedItem->data(Qt::UserRole).isNull()) {
+ selectedItem->setData(Qt::UserRole, QString("optional/") + selectedItem->text());
+ if (!root.exists("optional")) {
+ if (!root.mkdir("optional")) {
+ reportError(tr("failed to create directory \"optional\""));
+ activeESPList->insertItem(selectedRow, selectedItem);
+ return;
+ }
+ }
+ }
+
+ if (root.rename(selectedItem->text(), selectedItem->data(Qt::UserRole).toString())) {
+ inactiveESPList->addItem(selectedItem);
+ } else {
+ activeESPList->insertItem(selectedRow, selectedItem);
+ }
+}
+
+void ModInfoDialog::on_visitNexusLabel_linkActivated(const QString &link)
+{
+ emit linkActivated(link);
+}
+
+void ModInfoDialog::linkClicked(const QUrl &url)
+{
+ //Ideally we'd ask the mod for the game and the web service then pass the game
+ //and URL to the web service
+ if (NexusInterface::instance(m_PluginContainer)->isURLGameRelated(url)) {
+
+ emit linkActivated(url.toString());
+ } else {
+ ::ShellExecuteW(nullptr, L"open", ToWString(url.toString()).c_str(), nullptr, nullptr, SW_SHOWNORMAL);
+ }
+}
+
+void ModInfoDialog::linkClicked(QString url)
+{
+ emit linkActivated(url);
+}
+
+
+void ModInfoDialog::refreshNexusData(int modID)
+{
+ if ((!m_RequestStarted) && (modID > 0)) {
+ m_RequestStarted = true;
+
+ m_ModInfo->updateNXMInfo();
+
+ MessageDialog::showMessage(tr("Info requested, please wait"), this);
+ }
+}
+
+
+/*void ModInfoDialog::nxmDescriptionAvailable(int, QVariant, QVariant resultData, int requestID)
+{
+ std::set<int>::iterator idIter = m_RequestIDs.find(requestID);
+ if (idIter == m_RequestIDs.end()) {
+ return;
+ } else {
+ m_RequestIDs.erase(idIter);
+ }
+
+ QVariantMap result = resultData.toMap();
+
+ if (!result["description"].isNull()) {
+ QString descriptionAsHTML =
+ QString("<html>"
+ "<head><style>body {background: #707070; } a { color: #5EA2E5; }</style></head>"
+ "<body>%1</body>"
+ "</html>").arg(BBCode::convertToHTML(result["description"].toString()));
+
+// QString descriptionAsHTML = BBCode::convertToHTML(result["description"].toString());
+ ui->descriptionView->setHtml(descriptionAsHTML);
+ } else {
+ ui->descriptionView->setHtml(result["summary"].toString().append(QString("\r\n") + tr("(description incomplete, please visit nexus)")));
+ }
+
+ QLineEdit *versionEdit = findChild<QLineEdit*>("versionEdit");
+ QString version = result["version"].toString();
+
+ if (!version.isEmpty()) {
+ m_ModInfo->setNewestVersion(version);
+
+ VersionInfo currentVersion(versionEdit->text());
+ VersionInfo newestVersion(version);
+
+ QPalette versionColor;
+ if (currentVersion < newestVersion) {
+ versionColor.setColor(QPalette::Text, Qt::red);
+ versionEdit->setToolTip(tr("Current Version: %1").arg(version));
+ } else {
+ versionColor.setColor(QPalette::Text, Qt::green);
+ versionEdit->setToolTip(tr("No update available"));
+ }
+ versionEdit->setPalette(versionColor);
+ }
+}*/
+
+
+QString ModInfoDialog::getFileCategory(int categoryID)
+{
+ switch (categoryID) {
+ case 1: return tr("Main");
+ case 2: return tr("Update");
+ case 3: return tr("Optional");
+ case 4: return tr("Old");
+ case 6: return tr("Deleted");
+ default: return tr("Unknown");
+ }
+}
+
+
+void ModInfoDialog::updateVersionColor()
+{
+// QPalette versionColor;
+ if (m_ModInfo->getVersion() != m_ModInfo->getNewestVersion()) {
+ ui->versionEdit->setStyleSheet("color: red");
+// versionColor.setColor(QPalette::Text, Qt::red);
+ ui->versionEdit->setToolTip(tr("Current Version: %1").arg(m_ModInfo->getNewestVersion().canonicalString()));
+ } else {
+ ui->versionEdit->setStyleSheet("color: green");
+// versionColor.setColor(QPalette::Text, Qt::green);
+ ui->versionEdit->setToolTip(tr("No update available"));
+ }
+// ui->versionEdit->setPalette(versionColor);
+}
+
+
+void ModInfoDialog::modDetailsUpdated(bool success)
+{
+ if (success) {
+ QString nexusDescription = m_ModInfo->getNexusDescription();
+ if (!nexusDescription.isEmpty()) {
+ /* QString input =
+ "[size=20]sizetest[/size]\r\n"
+ "[COLOR=yellow]colortest[/COLOR]\r\n"
+ "[center]centertest[/center]\r\n"
+ "[quote]quotetest 1[/quote]\r\n"
+ "[quote=bla]quotetest 2[/quote]\r\n"
+ "[url]www.skyrimnexus.com[/url]\r\n"
+ "[url=www.skyrimnexus.com]urltest 2[/url]\r\n"
+ "[ol]\r\n"
+ "[li]item 2[/li]"
+ "[*]item 1\r\n"
+ "[/ol]\r\n"
+ "[img]http://www.bbcode.org/images/bbcode_logo.png[/img]\r\n"
+ "[table][tr][th]headertest1[/th]"
+ "[th]headertest2[/th][/tr]"
+ "[tr][td]rowtest11[/td][td]rowtest12[/td][/tr]"
+ "[tr][td]rowtest21[/td][td]rowtest22[/td][/tr][/table]"
+ "[email=\"sherb@gmx.net\"]mail me[/email]";
+ ui->descriptionView->setHtml(BBCode::convertToHTML(input));*/
+
+ QString descriptionAsHTML =
+ QString("<html>"
+ "<head><style>body {background: #707070; } a { color: #5EA2E5; }</style></head>"
+ "<body>%1</body>"
+ "</html>").arg(BBCode::convertToHTML(nexusDescription));
+
+ ui->descriptionView->page()->setHtml(descriptionAsHTML);
+
+ // QString descriptionAsHTML = BBCode::convertToHTML(result["description"].toString());
+ // ui->descriptionView->setHtml(descriptionAsHTML);
+ } else {
+ // ui->descriptionView->setHtml(result["summary"].toString().append(QString("\r\n") + tr("(description incomplete, please visit nexus)")));
+ ui->descriptionView->page()->setHtml(tr("(description incomplete, please visit nexus)"));
+ }
+
+ updateVersionColor();
+ }
+}
+
+
+void ModInfoDialog::activateNexusTab()
+{
+ QLineEdit *modIDEdit = findChild<QLineEdit*>("modIDEdit");
+ int modID = modIDEdit->text().toInt();
+ if (modID != 0) {
+ QString nexusLink = NexusInterface::instance(m_PluginContainer)->getModURL(modID, m_ModInfo->getGameName());
+ QLabel *visitNexusLabel = findChild<QLabel*>("visitNexusLabel");
+ visitNexusLabel->setText(tr("<a href=\"%1\">Visit on Nexus</a>").arg(nexusLink));
+ visitNexusLabel->setToolTip(nexusLink);
+
+ if (m_ModInfo->getNexusDescription().isEmpty() ||
+ QDateTime::currentDateTime() > m_ModInfo->getLastNexusQuery().addDays(1)) {
+ refreshNexusData(modID);
+ } else {
+ this->modDetailsUpdated(true);
+ }
+ }
+ QLineEdit *versionEdit = findChild<QLineEdit*>("versionEdit");
+ QString currentVersion = m_Settings->value("version", "0.0").toString();
+ versionEdit->setText(currentVersion);
+ ui->customUrlLineEdit->setText(m_ModInfo->getURL());
+}
+
+
+void ModInfoDialog::on_tabWidget_currentChanged(int index)
+{
+ if (index == TAB_NEXUS || m_RealTabPos[index] == TAB_NEXUS) {
+ activateNexusTab();
+ }
+}
+
+
+void ModInfoDialog::on_modIDEdit_editingFinished()
+{
+ int oldID = m_Settings->value("modid", 0).toInt();
+ int modID = ui->modIDEdit->text().toInt();
+ if (oldID != modID){
+ m_ModInfo->setNexusID(modID);
+
+ ui->descriptionView->page()->setHtml("");
+ if (modID != 0) {
+ m_RequestStarted = false;
+ refreshNexusData(modID);
+ }
+ }
+}
+
+void ModInfoDialog::on_sourceGameEdit_currentIndexChanged(int)
+{
+ for (auto game : m_PluginContainer->plugins<IPluginGame>()) {
+ if (game->gameName() == ui->sourceGameEdit->currentText()) {
+ m_ModInfo->setGameName(game->gameShortName());
+ return;
+ }
+ }
+}
+
+void ModInfoDialog::on_versionEdit_editingFinished()
+{
+ VersionInfo version(ui->versionEdit->text());
+ m_ModInfo->setVersion(version);
+ updateVersionColor();
+}
+
+void ModInfoDialog::on_customUrlLineEdit_editingFinished()
+{
+ m_ModInfo->setURL(ui->customUrlLineEdit->text());
+}
+
+bool ModInfoDialog::recursiveDelete(const QModelIndex &index)
+{
+ for (int childRow = 0; childRow < m_FileSystemModel->rowCount(index); ++childRow) {
+ QModelIndex childIndex = m_FileSystemModel->index(childRow, 0, index);
+ if (m_FileSystemModel->isDir(childIndex)) {
+ if (!recursiveDelete(childIndex)) {
+ qCritical("failed to delete %s", m_FileSystemModel->fileName(childIndex).toUtf8().constData());
+ return false;
+ }
+ } else {
+ if (!m_FileSystemModel->remove(childIndex)) {
+ qCritical("failed to delete %s", m_FileSystemModel->fileName(childIndex).toUtf8().constData());
+ return false;
+ }
+ }
+ }
+ if (!m_FileSystemModel->remove(index)) {
+ qCritical("failed to delete %s", m_FileSystemModel->fileName(index).toUtf8().constData());
+ return false;
+ }
+ return true;
+}
+
+
+void ModInfoDialog::on_openInExplorerButton_clicked()
+{
+ ::ShellExecuteW(nullptr, L"explore", ToWString(m_ModInfo->absolutePath()).c_str(), nullptr, nullptr, SW_SHOWNORMAL);
+}
+
+void ModInfoDialog::deleteFile(const QModelIndex &index)
+{
+
+ bool res = m_FileSystemModel->isDir(index) ? recursiveDelete(index)
+ : m_FileSystemModel->remove(index);
+ if (!res) {
+ QString fileName = m_FileSystemModel->fileName(index);
+ reportError(tr("Failed to delete %1").arg(fileName));
+ }
+}
+
+void ModInfoDialog::delete_activated()
+{
+ if (ui->fileTree->hasFocus()) {
+ QItemSelectionModel *selection = ui->fileTree->selectionModel();
+
+ if (selection->hasSelection() && selection->selectedRows().count() >= 1) {
+
+ if (selection->selectedRows().count() == 0) {
+ return;
+ }
+ else if (selection->selectedRows().count() == 1) {
+ QString fileName = m_FileSystemModel->fileName(selection->selectedRows().at(0));
+ if (QMessageBox::question(this, tr("Confirm"), tr("Are sure you want to delete \"%1\"?").arg(fileName),
+ QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
+ return;
+ }
+ }
+ else {
+ if (QMessageBox::question(this, tr("Confirm"), tr("Are sure you want to delete the selected files?"),
+ QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
+ return;
+ }
+ }
+
+ foreach(QModelIndex index, selection->selectedRows()) {
+ deleteFile(index);
+ }
+ }
+ }
+}
+
+void ModInfoDialog::deleteTriggered()
+{
+ if (m_FileSelection.count() == 0) {
+ return;
+ } else if (m_FileSelection.count() == 1) {
+ QString fileName = m_FileSystemModel->fileName(m_FileSelection.at(0));
+ if (QMessageBox::question(this, tr("Confirm"), tr("Are sure you want to delete \"%1\"?").arg(fileName),
+ QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
+ return;
+ }
+ } else {
+ if (QMessageBox::question(this, tr("Confirm"), tr("Are sure you want to delete the selected files?"),
+ QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
+ return;
+ }
+ }
+
+ foreach(QModelIndex index, m_FileSelection) {
+ deleteFile(index);
+ }
+}
+
+
+void ModInfoDialog::renameTriggered()
+{
+ QModelIndex selection = m_FileSelection.at(0);
+ QModelIndex index = selection.sibling(selection.row(), 0);
+ if (!index.isValid() || m_FileSystemModel->isReadOnly()) {
+ return;
+ }
+
+ ui->fileTree->edit(index);
+}
+
+
+void ModInfoDialog::hideTriggered()
+{
+ for (QModelIndexList::const_iterator iter = m_FileSelection.constBegin();
+ iter != m_FileSelection.constEnd(); ++iter) {
+ QString path = m_FileSystemModel->filePath(*iter);
+ if (!path.endsWith(ModInfo::s_HiddenExt)) {
+ hideFile(path);
+ }
+ }
+}
+
+
+void ModInfoDialog::unhideTriggered()
+{
+ for (QModelIndexList::const_iterator iter = m_FileSelection.constBegin();
+ iter != m_FileSelection.constEnd(); ++iter) {
+ QString path = m_FileSystemModel->filePath(*iter);
+ if (path.endsWith(ModInfo::s_HiddenExt)) {
+ unhideFile(path);
+ }
+ }
+}
+
+
+void ModInfoDialog::openFile(const QModelIndex &index)
+{
+ QString fileName = m_FileSystemModel->filePath(index);
+
+ HINSTANCE res = ::ShellExecuteW(nullptr, L"open", ToWString(fileName).c_str(), nullptr, nullptr, SW_SHOW);
+ if ((unsigned long long)res <= 32) {
+ qCritical("failed to invoke %s: %d", qUtf8Printable(fileName), res);
+ }
+}
+
+
+void ModInfoDialog::openTriggered()
+{
+ foreach(QModelIndex idx, m_FileSelection) {
+ openFile(idx);
+ }
+}
+
+void ModInfoDialog::createDirectoryTriggered()
+{
+ QModelIndex selection = m_FileSelection.at(0);
+
+ QModelIndex index = m_FileSystemModel->isDir(selection) ? selection
+ : selection.parent();
+ index = index.sibling(index.row(), 0);
+
+ QString name = tr("New Folder");
+ QString path = m_FileSystemModel->filePath(index).append("/");
+
+ QModelIndex existingIndex = m_FileSystemModel->index(path + name);
+ int suffix = 1;
+ while (existingIndex.isValid()) {
+ name = tr("New Folder") + QString::number(suffix++);
+ existingIndex = m_FileSystemModel->index(path + name);
+ }
+
+ QModelIndex newIndex = m_FileSystemModel->mkdir(index, name);
+ if (!newIndex.isValid()) {
+ reportError(tr("Failed to create \"%1\"").arg(name));
+ return;
+ }
+
+ ui->fileTree->setCurrentIndex(newIndex);
+ ui->fileTree->edit(newIndex);
+}
+
+
+void ModInfoDialog::on_fileTree_customContextMenuRequested(const QPoint &pos)
+{
+ QItemSelectionModel *selectionModel = ui->fileTree->selectionModel();
+ m_FileSelection = selectionModel->selectedRows(0);
+
+// m_FileSelection = ui->fileTree->indexAt(pos);
+ QMenu menu(ui->fileTree);
+
+ menu.addAction(m_NewFolderAction);
+
+ bool hasFiles = false;
+
+ foreach(QModelIndex idx, m_FileSelection) {
+ if (m_FileSystemModel->fileInfo(idx).isFile()) {
+ hasFiles = true;
+ break;
+ }
+ }
+
+ if (selectionModel->hasSelection()) {
+ if (hasFiles) {
+ menu.addAction(m_OpenAction);
+ }
+ menu.addAction(m_RenameAction);
+ menu.addAction(m_DeleteAction);
+ if (m_FileSystemModel->fileName(m_FileSelection.at(0)).endsWith(ModInfo::s_HiddenExt)) {
+ menu.addAction(m_UnhideAction);
+ } else {
+ menu.addAction(m_HideAction);
+ }
+ } else {
+ m_FileSelection.clear();
+ m_FileSelection.append(m_FileSystemModel->index(m_FileSystemModel->rootPath(), 0));
+ }
+ menu.exec(ui->fileTree->mapToGlobal(pos));
+}
+
+
+void ModInfoDialog::on_categoriesTree_itemChanged(QTreeWidgetItem *item, int)
+{
+ QTreeWidgetItem *parent = item->parent();
+ while ((parent != nullptr) && ((parent->flags() & Qt::ItemIsUserCheckable) != 0) && (parent->checkState(0) == Qt::Unchecked)) {
+ parent->setCheckState(0, Qt::Checked);
+ parent = parent->parent();
+ }
+ refreshPrimaryCategoriesBox();
+}
+
+
+void ModInfoDialog::addCheckedCategories(QTreeWidgetItem *tree)
+{
+ for (int i = 0; i < tree->childCount(); ++i) {
+ QTreeWidgetItem *child = tree->child(i);
+ if (child->checkState(0) == Qt::Checked) {
+ ui->primaryCategoryBox->addItem(child->text(0), child->data(0, Qt::UserRole));
+ addCheckedCategories(child);
+ }
+ }
+}
+
+
+void ModInfoDialog::refreshPrimaryCategoriesBox()
+{
+ ui->primaryCategoryBox->clear();
+ int primaryCategory = m_ModInfo->getPrimaryCategory();
+ addCheckedCategories(ui->categoriesTree->invisibleRootItem());
+ for (int i = 0; i < ui->primaryCategoryBox->count(); ++i) {
+ if (ui->primaryCategoryBox->itemData(i).toInt() == primaryCategory) {
+ ui->primaryCategoryBox->setCurrentIndex(i);
+ break;
+ }
+ }
+}
+
+
+void ModInfoDialog::on_primaryCategoryBox_currentIndexChanged(int index)
+{
+ if (index != -1) {
+ m_ModInfo->setPrimaryCategory(ui->primaryCategoryBox->itemData(index).toInt());
+ }
+}
+
+
+void ModInfoDialog::on_overwriteTree_itemDoubleClicked(QTreeWidgetItem *item, int)
+{
+ this->close();
+ emit modOpen(item->data(1, Qt::UserRole).toString(), TAB_CONFLICTS);
+}
+
+
+bool ModInfoDialog::hideFile(const QString &oldName)
+{
+ QString newName = oldName + ModInfo::s_HiddenExt;
+
+ if (QFileInfo(newName).exists()) {
+ if (QMessageBox::question(this, tr("Replace file?"), tr("There already is a hidden version of this file. Replace it?"),
+ QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
+ if (!QFile(newName).remove()) {
+ QMessageBox::critical(this, tr("File operation failed"), tr("Failed to remove \"%1\". Maybe you lack the required file permissions?").arg(newName));
+ return false;
+ }
+ } else {
+ return false;
+ }
+ }
+
+ if (QFile::rename(oldName, newName)) {
+ return true;
+ } else {
+ reportError(tr("failed to rename %1 to %2").arg(oldName).arg(QDir::toNativeSeparators(newName)));
+ return false;
+ }
+}
+
+
+bool ModInfoDialog::unhideFile(const QString &oldName)
+{
+ QString newName = oldName.left(oldName.length() - ModInfo::s_HiddenExt.length());
+ if (QFileInfo(newName).exists()) {
+ if (QMessageBox::question(this, tr("Replace file?"), tr("There already is a visible version of this file. Replace it?"),
+ QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
+ if (!QFile(newName).remove()) {
+ QMessageBox::critical(this, tr("File operation failed"), tr("Failed to remove \"%1\". Maybe you lack the required file permissions?").arg(newName));
+ return false;
+ }
+ } else {
+ return false;
+ }
+ }
+ if (QFile::rename(oldName, newName)) {
+ return true;
+ } else {
+ reportError(tr("failed to rename %1 to %2").arg(QDir::toNativeSeparators(oldName)).arg(QDir::toNativeSeparators(newName)));
+ return false;
+ }
+}
+
+
+void ModInfoDialog::hideConflictFile()
+{
+ if (hideFile(m_ConflictsContextItem->data(0, Qt::UserRole).toString())) {
+ emit originModified(m_Origin->getID());
+ refreshLists();
+ }
+}
+
+
+void ModInfoDialog::unhideConflictFile()
+{
+ if (unhideFile(m_ConflictsContextItem->data(0, Qt::UserRole).toString())) {
+ emit originModified(m_Origin->getID());
+ refreshLists();
+ }
+}
+
+int ModInfoDialog::getBinaryExecuteInfo(const QFileInfo &targetInfo, QFileInfo &binaryInfo, QString &arguments)
+{
+ QString extension = targetInfo.suffix();
+ if ((extension.compare("cmd", Qt::CaseInsensitive) == 0) ||
+ (extension.compare("com", Qt::CaseInsensitive) == 0) ||
+ (extension.compare("bat", Qt::CaseInsensitive) == 0)) {
+ binaryInfo = QFileInfo("C:\\Windows\\System32\\cmd.exe");
+ arguments = QString("/C \"%1\"").arg(QDir::toNativeSeparators(targetInfo.absoluteFilePath()));
+ return 1;
+ }
+ else if (extension.compare("exe", Qt::CaseInsensitive) == 0) {
+ binaryInfo = targetInfo;
+ return 1;
+ }
+ else if (extension.compare("jar", Qt::CaseInsensitive) == 0) {
+ // types that need to be injected into
+ std::wstring targetPathW = ToWString(targetInfo.absoluteFilePath());
+ QString binaryPath;
+
+ { // try to find java automatically
+ WCHAR buffer[MAX_PATH];
+ if (::FindExecutableW(targetPathW.c_str(), nullptr, buffer) > (HINSTANCE)32) {
+ DWORD binaryType = 0UL;
+ if (!::GetBinaryTypeW(buffer, &binaryType)) {
+ qDebug("failed to determine binary type of \"%ls\": %lu", buffer, ::GetLastError());
+ }
+ else if (binaryType == SCS_32BIT_BINARY) {
+ binaryPath = ToQString(buffer);
+ }
+ }
+ }
+ if (binaryPath.isEmpty() && (extension == "jar")) {
+ // second attempt: look to the registry
+ QSettings javaReg("HKEY_LOCAL_MACHINE\\Software\\JavaSoft\\Java Runtime Environment", QSettings::NativeFormat);
+ if (javaReg.contains("CurrentVersion")) {
+ QString currentVersion = javaReg.value("CurrentVersion").toString();
+ binaryPath = javaReg.value(QString("%1/JavaHome").arg(currentVersion)).toString().append("\\bin\\javaw.exe");
+ }
+ }
+ if (binaryPath.isEmpty()) {
+ binaryPath = QFileDialog::getOpenFileName(this, tr("Select binary"), QString(), tr("Binary") + " (*.exe)");
+ }
+ if (binaryPath.isEmpty()) {
+ return 0;
+ }
+ binaryInfo = QFileInfo(binaryPath);
+ if (extension == "jar") {
+ arguments = QString("-jar \"%1\"").arg(QDir::toNativeSeparators(targetInfo.absoluteFilePath()));
+ }
+ else {
+ arguments = QString("\"%1\"").arg(QDir::toNativeSeparators(targetInfo.absoluteFilePath()));
+ }
+ return 1;
+ }
+ else {
+ return 2;
+ }
+}
+
+void ModInfoDialog::openDataFile()
+{
+ if (m_ConflictsContextItem != nullptr) {
+ QFileInfo targetInfo(m_ConflictsContextItem->data(0, Qt::UserRole).toString());
+ QFileInfo binaryInfo;
+ QString arguments;
+ switch (getBinaryExecuteInfo(targetInfo, binaryInfo, arguments)) {
+ case 1: {
+ m_OrganizerCore->spawnBinaryDirect(
+ binaryInfo, arguments, m_OrganizerCore->currentProfile()->name(),
+ targetInfo.absolutePath(), "", "");
+ } break;
+ case 2: {
+ ::ShellExecuteW(nullptr, L"open",
+ ToWString(targetInfo.absoluteFilePath()).c_str(),
+ nullptr, nullptr, SW_SHOWNORMAL);
+ } break;
+ default: {
+ // nop
+ } break;
+ }
+ }
+}
+
+void ModInfoDialog::previewDataFile()
+{
+ QString fileName = QDir::fromNativeSeparators(m_ConflictsContextItem->data(0, Qt::UserRole).toString());
+
+ // what we have is an absolute path to the file in its actual location (for the primary origin)
+ // what we want is the path relative to the virtual data directory
+
+ // we need to look in the virtual directory for the file to make sure the info is up to date.
+
+ // check if the file comes from the actual data folder instead of a mod
+ QDir gameDirectory = m_OrganizerCore->managedGame()->dataDirectory().absolutePath();
+ QString relativePath = gameDirectory.relativeFilePath(fileName);
+ QDir direRelativePath = gameDirectory.relativeFilePath(fileName);
+ // if the file is on a different drive the dirRelativePath will actually be an absolute path so we make sure that is not the case
+ if (!direRelativePath.isAbsolute() && !relativePath.startsWith("..")) {
+ fileName = relativePath;
+ }
+ else {
+ // crude: we search for the next slash after the base mod directory to skip everything up to the data-relative directory
+ int offset = m_OrganizerCore->settings().getModDirectory().size() + 1;
+ offset = fileName.indexOf("/", offset);
+ fileName = fileName.mid(offset + 1);
+ }
+
+
+
+ const FileEntry::Ptr file = m_OrganizerCore->directoryStructure()->searchFile(ToWString(fileName), nullptr);
+
+ if (file.get() == nullptr) {
+ reportError(tr("file not found: %1").arg(qUtf8Printable(fileName)));
+ return;
+ }
+
+ // set up preview dialog
+ PreviewDialog preview(fileName);
+ auto addFunc = [&](int originId) {
+ FilesOrigin &origin = m_OrganizerCore->directoryStructure()->getOriginByID(originId);
+ QString filePath = QDir::fromNativeSeparators(ToQString(origin.getPath())) + "/" + fileName;
+ if (QFile::exists(filePath)) {
+ // it's very possible the file doesn't exist, because it's inside an archive. we don't support that
+ QWidget *wid = m_PluginContainer->previewGenerator().genPreview(filePath);
+ if (wid == nullptr) {
+ reportError(tr("failed to generate preview for %1").arg(filePath));
+ }
+ else {
+ preview.addVariant(ToQString(origin.getName()), wid);
+ }
+ }
+ };
+
+ addFunc(file->getOrigin());
+ for (auto alt : file->getAlternatives()) {
+ addFunc(alt.first);
+ }
+ if (preview.numVariants() > 0) {
+ preview.exec();
+ }
+ else {
+ QMessageBox::information(this, tr("Sorry"), tr("Sorry, can't preview anything. This function currently does not support extracting from bsas."));
+ }
+}
+
+
+void ModInfoDialog::on_overwriteTree_customContextMenuRequested(const QPoint &pos)
+{
+ m_ConflictsContextItem = ui->overwriteTree->itemAt(pos.x(), pos.y());
+
+ if (m_ConflictsContextItem != nullptr) {
+ // offer to hide/unhide file, but not for files from archives
+ if (!m_ConflictsContextItem->data(1, Qt::UserRole + 2).toBool()) {
+ QMenu menu;
+ if (m_ConflictsContextItem->text(0).endsWith(ModInfo::s_HiddenExt)) {
+ menu.addAction(tr("Un-Hide"), this, SLOT(unhideConflictFile()));
+ } else {
+ menu.addAction(tr("Hide"), this, SLOT(hideConflictFile()));
+ }
+
+ menu.addAction(tr("Open/Execute"), this, SLOT(openDataFile()));
+
+ QString fileName = m_ConflictsContextItem->data(0, Qt::UserRole).toString();
+ if (m_PluginContainer->previewGenerator().previewSupported(QFileInfo(fileName).suffix())) {
+ menu.addAction(tr("Preview"), this, SLOT(previewDataFile()));
+ }
+
+ menu.exec(ui->overwriteTree->mapToGlobal(pos));
+ }
+ }
+}
+
+void ModInfoDialog::on_overwrittenTree_customContextMenuRequested(const QPoint &pos)
+{
+ m_ConflictsContextItem = ui->overwrittenTree->itemAt(pos.x(), pos.y());
+
+ if (m_ConflictsContextItem != nullptr) {
+ if (!m_ConflictsContextItem->data(1, Qt::UserRole + 2).toBool()) {
+ QMenu menu;
+
+ menu.addAction(tr("Open/Execute"), this, SLOT(openDataFile()));
+
+ QString fileName = m_ConflictsContextItem->data(0, Qt::UserRole).toString();
+ if (m_PluginContainer->previewGenerator().previewSupported(QFileInfo(fileName).suffix())) {
+ menu.addAction(tr("Preview"), this, SLOT(previewDataFile()));
+ }
+
+ menu.exec(ui->overwrittenTree->mapToGlobal(pos));
+ }
+ }
+}
+
+
+void ModInfoDialog::on_overwrittenTree_itemDoubleClicked(QTreeWidgetItem *item, int)
+{
+ emit modOpen(item->data(1, Qt::UserRole).toString(), TAB_CONFLICTS);
+ this->accept();
+}
+
+void ModInfoDialog::on_refreshButton_clicked()
+{
+ m_ModInfo->updateNXMInfo();
+
+ MessageDialog::showMessage(tr("Info requested, please wait"), this);
+}
+
+void ModInfoDialog::on_endorseBtn_clicked()
+{
+ emit endorseMod(m_ModInfo);
+}
+
+void ModInfoDialog::on_nextButton_clicked()
+{
+ int currentTab = ui->tabWidget->currentIndex();
+ int tab = m_RealTabPos[currentTab];
+
+ emit modOpenNext(tab);
+ this->accept();
+}
+
+void ModInfoDialog::on_prevButton_clicked()
+{
+ int currentTab = ui->tabWidget->currentIndex();
+ int tab = m_RealTabPos[currentTab];
+
+ emit modOpenPrev(tab);
+ this->accept();
+}
+
+
+void ModInfoDialog::createTweak()
+{
+ QString name = QInputDialog::getText(this, tr("Name"), tr("Please enter a name"));
+ if (name.isNull()) {
+ return;
+ } else if (!fixDirectoryName(name)) {
+ QMessageBox::critical(this, tr("Error"), tr("Invalid name. Must be a valid file name"));
+ return;
+ } else if (ui->iniTweaksList->findItems(name, Qt::MatchFixedString).count() != 0) {
+ QMessageBox::critical(this, tr("Error"), tr("A tweak by that name exists"));
+ return;
+ }
+
+ QListWidgetItem *newTweak = new QListWidgetItem(name + ".ini");
+ newTweak->setData(Qt::UserRole, "INI Tweaks/" + name + ".ini");
+ newTweak->setFlags(newTweak->flags() | Qt::ItemIsUserCheckable);
+ newTweak->setCheckState(Qt::Unchecked);
+ ui->iniTweaksList->addItem(newTweak);
+}
+
+void ModInfoDialog::on_iniTweaksList_customContextMenuRequested(const QPoint &pos)
+{
+ QMenu menu;
+ menu.addAction(tr("Create Tweak"), this, SLOT(createTweak()));
+ menu.exec(ui->iniTweaksList->mapToGlobal(pos));
+}
diff --git a/src/modinfoforeign.h b/src/modinfoforeign.h
index 45fe7689..20bfab2a 100644
--- a/src/modinfoforeign.h
+++ b/src/modinfoforeign.h
@@ -31,6 +31,7 @@ public:
virtual void setNeverEndorse() {}
virtual bool remove() { return false; }
virtual void endorse(bool) {}
+ virtual void parseNexusInfo() {}
virtual bool isEmpty() const { return false; }
virtual QString name() const;
virtual QString internalName() const { return name(); }
diff --git a/src/modinfooverwrite.h b/src/modinfooverwrite.h
index cfd662af..b68fb15b 100644
--- a/src/modinfooverwrite.h
+++ b/src/modinfooverwrite.h
@@ -33,6 +33,7 @@ public:
virtual void setNeverEndorse() {}
virtual bool remove() { return false; }
virtual void endorse(bool) {}
+ virtual void parseNexusInfo() {}
virtual bool alwaysEnabled() const { return true; }
virtual bool isEmpty() const;
virtual QString name() const { return "Overwrite"; }
diff --git a/src/modinforegular.cpp b/src/modinforegular.cpp
index 3523feae..71b99e10 100644
--- a/src/modinforegular.cpp
+++ b/src/modinforegular.cpp
@@ -56,7 +56,7 @@ ModInfoRegular::ModInfoRegular(PluginContainer *pluginContainer, const IPluginGa
connect(&m_NexusBridge, SIGNAL(endorsementToggled(QString,int,QVariant,QVariant))
, this, SLOT(nxmEndorsementToggled(QString,int,QVariant,QVariant)));
connect(&m_NexusBridge, SIGNAL(requestFailed(QString,int,int,QVariant,QString))
- , this, SLOT(nxmRequestFailed(QString,int,int,QVariant,QString)));
+ , this, SLOT(nxmRequestFailed(QString,int,int,QVariant, QNetworkReply::NetworkError,QString)));
}
@@ -213,13 +213,17 @@ bool ModInfoRegular::downgradeAvailable() const
void ModInfoRegular::nxmDescriptionAvailable(QString, int, QVariant, QVariant resultData)
{
QVariantMap result = resultData.toMap();
- setNewestVersion(VersionInfo(result["version"].toString()));
setNexusDescription(result["description"].toString());
if ((m_EndorsedState != ENDORSED_NEVER) && (result.contains("endorsement"))) {
QVariantMap endorsement = result["endorsement"].toMap();
QString endorsementStatus = endorsement["endorse_status"].toString();
- setEndorsedState(endorsementStatus.compare("Endorsed") == 0 ? ENDORSED_TRUE : ENDORSED_FALSE);
+ if (endorsementStatus.compare("Endorsed") == 00)
+ setEndorsedState(ENDORSED_TRUE);
+ else if (endorsementStatus.compare("Abstained") == 00)
+ setEndorsedState(ENDORSED_NEVER);
+ else
+ setEndorsedState(ENDORSED_FALSE);
}
m_LastNexusQuery = QDateTime::currentDateTime();
//m_MetaInfoChanged = true;
@@ -234,6 +238,8 @@ void ModInfoRegular::nxmEndorsementToggled(QString, int, QVariant, QVariant resu
if (results["code"].toInt() == 200 || results["code"].toInt() == 201) {
if (results["status"].toString().compare("Endorsed") == 0) {
m_EndorsedState = ENDORSED_TRUE;
+ } else if (results["status"].toString().compare("Abstained") == 0) {
+ m_EndorsedState = ENDORSED_NEVER;
} else {
m_EndorsedState = ENDORSED_FALSE;
}
@@ -244,7 +250,7 @@ void ModInfoRegular::nxmEndorsementToggled(QString, int, QVariant, QVariant resu
}
-void ModInfoRegular::nxmRequestFailed(QString, int, int, QVariant userData, const QString &errorMessage)
+void ModInfoRegular::nxmRequestFailed(QString, int, int, QVariant userData, QNetworkReply::NetworkError error, const QString &errorMessage)
{
QString fullMessage = errorMessage;
if (userData.canConvert<int>() && (userData.toInt() == 1)) {
diff --git a/src/modinforegular.h b/src/modinforegular.h
index 093b4e5b..fdb0e672 100644
--- a/src/modinforegular.h
+++ b/src/modinforegular.h
@@ -353,7 +353,7 @@ private slots:
void nxmDescriptionAvailable(QString, int modID, QVariant userData, QVariant resultData);
void nxmEndorsementToggled(QString, int, QVariant userData, QVariant resultData);
- void nxmRequestFailed(QString, int modID, int fileID, QVariant userData, const QString &errorMessage);
+ void nxmRequestFailed(QString, int modID, int fileID, QVariant userData, QNetworkReply::NetworkError error, const QString &errorMessage);
protected:
diff --git a/src/modinfoseparator.h b/src/modinfoseparator.h
index f215fb17..c5e0f0e5 100644
--- a/src/modinfoseparator.h
+++ b/src/modinfoseparator.h
@@ -20,21 +20,15 @@ public:
virtual int getNexusID() const { return -1; }
- virtual void setGameName(QString /*gameName*/)
- {
- }
+ virtual void setGameName(QString /*gameName*/) {}
- virtual void setNexusID(int /*modID*/)
- {
- }
+ virtual void setNexusID(int /*modID*/) {}
- virtual void endorse(bool /*doEndorse*/)
- {
- }
+ virtual void endorse(bool /*doEndorse*/) {}
- virtual void ignoreUpdate(bool /*ignore*/)
- {
- }
+ virtual void parseNexusInfo() {}
+
+ virtual void ignoreUpdate(bool /*ignore*/) {}
virtual bool canBeUpdated() const { return false; }
virtual bool canBeEnabled() const { return false; }
diff --git a/src/nexusinterface.cpp b/src/nexusinterface.cpp
index 4fe86136..789d30d2 100644
--- a/src/nexusinterface.cpp
+++ b/src/nexusinterface.cpp
@@ -1,734 +1,710 @@
-/*
-Copyright (C) 2012 Sebastian Herbord. All rights reserved.
-
-This file is part of Mod Organizer.
-
-Mod Organizer is free software: you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-Mod Organizer is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with Mod Organizer. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#include "nexusinterface.h"
-
-#include "iplugingame.h"
-#include "nxmaccessmanager.h"
-#include "json.h"
-#include "selectiondialog.h"
-#include <utility.h>
-#include <util.h>
-
-#include <QApplication>
-#include <QNetworkCookieJar>
-#include <QJsonDocument>
-
-#include <regex>
-
-
-using namespace MOBase;
-using namespace MOShared;
-
-
-NexusBridge::NexusBridge(PluginContainer *pluginContainer, const QString &subModule)
- : m_Interface(NexusInterface::instance(pluginContainer))
- , m_SubModule(subModule)
-{
-}
-
-void NexusBridge::requestDescription(QString gameName, int modID, QVariant userData)
-{
- m_RequestIDs.insert(m_Interface->requestDescription(gameName, modID, this, userData, m_SubModule));
-}
-
-void NexusBridge::requestFiles(QString gameName, int modID, QVariant userData)
-{
- m_RequestIDs.insert(m_Interface->requestFiles(gameName, modID, this, userData, m_SubModule));
-}
-
-void NexusBridge::requestFileInfo(QString gameName, int modID, int fileID, QVariant userData)
-{
- m_RequestIDs.insert(m_Interface->requestFileInfo(gameName, modID, fileID, this, userData, m_SubModule));
-}
-
-void NexusBridge::requestDownloadURL(QString gameName, int modID, int fileID, QVariant userData)
-{
- m_RequestIDs.insert(m_Interface->requestDownloadURL(gameName, modID, fileID, this, userData, m_SubModule));
-}
-
-void NexusBridge::requestToggleEndorsement(QString gameName, int modID, QString modVersion, bool endorse, QVariant userData)
-{
- m_RequestIDs.insert(m_Interface->requestToggleEndorsement(gameName, modID, modVersion, endorse, this, userData, m_SubModule));
-}
-
-void NexusBridge::nxmDescriptionAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID)
-{
- std::set<int>::iterator iter = m_RequestIDs.find(requestID);
- if (iter != m_RequestIDs.end()) {
- m_RequestIDs.erase(iter);
-
- emit descriptionAvailable(gameName, modID, userData, resultData);
- }
-}
-
-void NexusBridge::nxmFilesAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID)
-{
- std::set<int>::iterator iter = m_RequestIDs.find(requestID);
- if (iter != m_RequestIDs.end()) {
- m_RequestIDs.erase(iter);
-
- QList<ModRepositoryFileInfo> fileInfoList;
-
- QVariantMap resultInfo = resultData.toMap();
- QList resultList = resultInfo["files"].toList();
-
- for (const QVariant &file : resultList) {
- ModRepositoryFileInfo temp;
- QVariantMap fileInfo = file.toMap();
- temp.uri = fileInfo["file_name"].toString();
- temp.name = fileInfo["name"].toString();
- temp.description = fileInfo["changelog_html"].toString();
- temp.version = VersionInfo(fileInfo["version"].toString());
- temp.categoryID = fileInfo["category_id"].toInt();
- temp.fileID = fileInfo["file_id"].toInt();
- temp.fileSize = fileInfo["size"].toInt();
- fileInfoList.append(temp);
- }
-
- emit filesAvailable(gameName, modID, userData, fileInfoList);
- }
-}
-
-void NexusBridge::nxmFileInfoAvailable(QString gameName, int modID, int fileID, QVariant userData, QVariant resultData, int requestID)
-{
- std::set<int>::iterator iter = m_RequestIDs.find(requestID);
- if (iter != m_RequestIDs.end()) {
- m_RequestIDs.erase(iter);
- emit fileInfoAvailable(gameName, modID, fileID, userData, resultData);
- }
-}
-
-void NexusBridge::nxmDownloadURLsAvailable(QString gameName, int modID, int fileID, QVariant userData, QVariant resultData, int requestID)
-{
- std::set<int>::iterator iter = m_RequestIDs.find(requestID);
- if (iter != m_RequestIDs.end()) {
- m_RequestIDs.erase(iter);
- emit downloadURLsAvailable(gameName, modID, fileID, userData, resultData);
- }
-}
-
-void NexusBridge::nxmEndorsementToggled(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID)
-{
- std::set<int>::iterator iter = m_RequestIDs.find(requestID);
- if (iter != m_RequestIDs.end()) {
- m_RequestIDs.erase(iter);
- emit endorsementToggled(gameName, modID, userData, resultData);
- }
-}
-
-void NexusBridge::nxmRequestFailed(QString gameName, int modID, int fileID, QVariant userData, int requestID, const QString &errorMessage)
-{
- std::set<int>::iterator iter = m_RequestIDs.find(requestID);
- if (iter != m_RequestIDs.end()) {
- m_RequestIDs.erase(iter);
- emit requestFailed(gameName, modID, fileID, userData, errorMessage);
- }
-}
-
-
-QAtomicInt NexusInterface::NXMRequestInfo::s_NextID(0);
-
-
-NexusInterface::NexusInterface(PluginContainer *pluginContainer)
- : m_NMMVersion(), m_PluginContainer(pluginContainer)
-{
- m_MOVersion = createVersionInfo();
-
- m_AccessManager = new NXMAccessManager(this, m_MOVersion.displayString(3));
- m_DiskCache = new QNetworkDiskCache(this);
- connect(m_AccessManager, SIGNAL(requestNXMDownload(QString)), this, SLOT(downloadRequestedNXM(QString)));
-}
-
-NXMAccessManager *NexusInterface::getAccessManager()
-{
- return m_AccessManager;
-}
-
-NexusInterface::~NexusInterface()
-{
- cleanup();
-}
-
-NexusInterface *NexusInterface::instance(PluginContainer *pluginContainer)
-{
- static NexusInterface s_Instance(pluginContainer);
- return &s_Instance;
-}
-
-void NexusInterface::setCacheDirectory(const QString &directory)
-{
- m_DiskCache->setCacheDirectory(directory);
- m_AccessManager->setCache(m_DiskCache);
-}
-
-void NexusInterface::setNMMVersion(const QString &nmmVersion)
-{
- m_NMMVersion = nmmVersion;
- m_AccessManager->setNMMVersion(nmmVersion);
-}
-
-void NexusInterface::loginCompleted()
-{
- nextRequest();
-}
-
-
-void NexusInterface::interpretNexusFileName(const QString &fileName, QString &modName, int &modID, bool query)
-{
- //Look for something along the lines of modulename-Vn-m + any old rubbish.
- static std::regex exp(R"exp(^([a-zA-Z0-9_'"\-.() ]*?)([-_ ][VvRr]?[0-9_]+)?-([1-9][0-9]*).*\.(zip|rar|7z))exp");
- static std::regex simpleexp("^([a-zA-Z0-9_]+)");
-
- QByteArray fileNameUTF8 = fileName.toUtf8();
- std::cmatch result;
- if (std::regex_search(fileNameUTF8.constData(), result, exp)) {
- modName = QString::fromUtf8(result[1].str().c_str());
- modName = modName.replace('_', ' ').trimmed();
-
- std::string candidate = result[3].str();
- std::string candidate2 = result[2].str();
- if (candidate2.length() != 0 && (candidate2.find_last_of("VvRr") == std::string::npos)) {
- // well, that second match might be an id too...
- size_t offset = strspn(candidate2.c_str(), "-_ ");
- if (offset < candidate2.length() && query) {
- SelectionDialog selection(tr("Failed to guess mod id for \"%1\", please pick the correct one").arg(fileName));
- QString r2Highlight(fileName);
- r2Highlight.insert(result.position(2) + result.length(2), "* ")
- .insert(result.position(2) + static_cast<int>(offset), " *");
- QString r3Highlight(fileName);
- r3Highlight.insert(result.position(3) + result.length(3), "* ").insert(result.position(3), " *");
-
- selection.addChoice(candidate.c_str(), r3Highlight, static_cast<int>(strtol(candidate.c_str(), nullptr, 10)));
- selection.addChoice(candidate2.c_str() + offset, r2Highlight, static_cast<int>(abs(strtol(candidate2.c_str() + offset, nullptr, 10))));
- if (selection.exec() == QDialog::Accepted) {
- modID = selection.getChoiceData().toInt();
- } else {
- modID = -1;
- }
- } else {
- modID = -1;
- }
- } else {
- modID = strtol(candidate.c_str(), nullptr, 10);
- }
- qDebug("mod id guessed: %s -> %d", qUtf8Printable(fileName), modID);
- } else if (std::regex_search(fileNameUTF8.constData(), result, simpleexp)) {
- qDebug("simple expression matched, using name only");
- modName = QString::fromUtf8(result[1].str().c_str());
- modName = modName.replace('_', ' ').trimmed();
-
- modID = -1;
- } else {
- qDebug("no expression matched!");
- modName.clear();
- modID = -1;
- }
-}
-
-bool NexusInterface::isURLGameRelated(const QUrl &url) const
-{
- QString const name(url.toString());
- return name.startsWith(getGameURL("") + "/") ||
- name.startsWith(getOldModsURL("") + "/");
-}
-
-QString NexusInterface::getGameURL(QString gameName) const
-{
- IPluginGame *game = getGame(gameName);
- return "https://www.nexusmods.com/" + game->gameNexusName().toLower();
-}
-
-QString NexusInterface::getOldModsURL(QString gameName) const
-{
- IPluginGame *game = getGame(gameName);
- return "https://" + game->gameNexusName().toLower() + ".nexusmods.com/mods";
-}
-
-
-QString NexusInterface::getModURL(int modID, QString gameName = "") const
-{
- return QString("%1/mods/%2").arg(getGameURL(gameName)).arg(modID);
-}
-
-std::vector<std::pair<QString, QString>> NexusInterface::getGameChoices(const MOBase::IPluginGame *game)
-{
- std::vector<std::pair<QString, QString>> choices;
- choices.push_back(std::pair<QString, QString>(game->gameShortName(), game->gameName()));
- for (QString gameName : game->validShortNames()) {
- for (auto gamePlugin : m_PluginContainer->plugins<IPluginGame>()) {
- if (gamePlugin->gameShortName().compare(gameName, Qt::CaseInsensitive) == 0) {
- choices.push_back(std::pair<QString, QString>(gamePlugin->gameShortName(), gamePlugin->gameName()));
- break;
- }
- }
- }
- return choices;
-}
-
-bool NexusInterface::isModURL(int modID, const QString &url) const
-{
- if (QUrl(url) == QUrl(getModURL(modID))) {
- return true;
- }
- //Try the alternate (old style) mod name
- QString alt = QString("%1/%2").arg(getOldModsURL("")).arg(modID);
- return QUrl(alt) == QUrl(url);
-}
-
-void NexusInterface::setPluginContainer(PluginContainer *pluginContainer)
-{
- m_PluginContainer = pluginContainer;
-}
-
-int NexusInterface::requestDescription(QString gameName, int modID, QObject *receiver, QVariant userData,
- const QString &subModule, MOBase::IPluginGame const *game)
-{
- NXMRequestInfo requestInfo(modID, NXMRequestInfo::TYPE_DESCRIPTION, userData, subModule, game);
- m_RequestQueue.enqueue(requestInfo);
-
- connect(this, SIGNAL(nxmDescriptionAvailable(QString, int, QVariant, QVariant, int)),
- receiver, SLOT(nxmDescriptionAvailable(QString, int, QVariant, QVariant, int)), Qt::UniqueConnection);
-
- connect(this, SIGNAL(nxmRequestFailed(QString, int, int, QVariant, int, QString)),
- receiver, SLOT(nxmRequestFailed(QString, int, int, QVariant, int, QString)), Qt::UniqueConnection);
-
- nextRequest();
- return requestInfo.m_ID;
-}
-
-
-int NexusInterface::requestUpdates(const std::vector<int> &modIDs, QObject *receiver, QVariant userData,
- QString gameName, const QString &subModule)
-{
- IPluginGame *game = getGame(gameName);
- NXMRequestInfo requestInfo(modIDs, NXMRequestInfo::TYPE_GETUPDATES, userData, subModule, game);
- m_RequestQueue.enqueue(requestInfo);
-
- connect(this, SIGNAL(nxmUpdatesAvailable(std::vector<int>, QVariant, QVariant, int)),
- receiver, SLOT(nxmUpdatesAvailable(std::vector<int>, QVariant, QVariant, int)), Qt::UniqueConnection);
-
- connect(this, SIGNAL(nxmRequestFailed(QString, int, int, QVariant, int, QString)),
- receiver, SLOT(nxmRequestFailed(QString, int, int, QVariant, int, QString)), Qt::UniqueConnection);
-
- nextRequest();
- return requestInfo.m_ID;
-}
-
-
-void NexusInterface::fakeFiles()
-{
- static int id = 42;
-
- QVariantList result;
- QVariantMap fileMap;
- fileMap["uri"] = "fakeURI";
- fileMap["name"] = "fakeName";
- fileMap["description"] = "fakeDescription";
- fileMap["version"] = "1.0.0";
- fileMap["category_id"] = "1";
- fileMap["id"] = "1";
- fileMap["size"] = "512";
- result.append(fileMap);
-
- emit nxmFilesAvailable("fakeGame", 1234, "fake", result, id++);
-}
-
-
-int NexusInterface::requestFiles(QString gameName, int modID, QObject *receiver, QVariant userData,
- const QString &subModule, MOBase::IPluginGame const *game)
-{
- NXMRequestInfo requestInfo(modID, NXMRequestInfo::TYPE_FILES, userData, subModule, game);
- m_RequestQueue.enqueue(requestInfo);
- connect(this, SIGNAL(nxmFilesAvailable(QString, int, QVariant, QVariant, int)),
- receiver, SLOT(nxmFilesAvailable(QString, int, QVariant, QVariant, int)), Qt::UniqueConnection);
-
- connect(this, SIGNAL(nxmRequestFailed(QString, int, int, QVariant, int, QString)),
- receiver, SLOT(nxmRequestFailed(QString, int, int, QVariant, int, QString)), Qt::UniqueConnection);
-
- nextRequest();
- return requestInfo.m_ID;
-}
-
-
-int NexusInterface::requestFileInfo(QString gameName, int modID, int fileID, QObject *receiver, QVariant userData, const QString &subModule)
-{
- IPluginGame *gamePlugin = getGame(gameName);
- NXMRequestInfo requestInfo(modID, fileID, NXMRequestInfo::TYPE_FILEINFO, userData, subModule, gamePlugin);
- m_RequestQueue.enqueue(requestInfo);
-
- connect(this, SIGNAL(nxmFileInfoAvailable(QString, int, int, QVariant, QVariant, int)),
- receiver, SLOT(nxmFileInfoAvailable(QString, int, int, QVariant, QVariant, int)), Qt::UniqueConnection);
-
- connect(this, SIGNAL(nxmRequestFailed(QString, int, int, QVariant, int, QString)),
- receiver, SLOT(nxmRequestFailed(QString, int, int, QVariant, int, QString)), Qt::UniqueConnection);
-
- nextRequest();
- return requestInfo.m_ID;
-}
-
-
-int NexusInterface::requestDownloadURL(QString gameName, int modID, int fileID, QObject *receiver, QVariant userData,
- const QString &subModule, MOBase::IPluginGame const *game)
-{
- NXMRequestInfo requestInfo(modID, fileID, NXMRequestInfo::TYPE_DOWNLOADURL, userData, subModule, game);
- m_RequestQueue.enqueue(requestInfo);
-
- connect(this, SIGNAL(nxmDownloadURLsAvailable(QString,int,int,QVariant,QVariant,int)),
- receiver, SLOT(nxmDownloadURLsAvailable(QString,int,int,QVariant,QVariant,int)), Qt::UniqueConnection);
-
- connect(this, SIGNAL(nxmRequestFailed(QString,int,int,QVariant,int,QString)),
- receiver, SLOT(nxmRequestFailed(QString,int,int,QVariant,int,QString)), Qt::UniqueConnection);
-
- nextRequest();
- return requestInfo.m_ID;
-}
-
-
-int NexusInterface::requestToggleEndorsement(QString gameName, int modID, QString modVersion, bool endorse, QObject *receiver, QVariant userData,
- const QString &subModule, MOBase::IPluginGame const *game)
-{
- NXMRequestInfo requestInfo(modID, modVersion, NXMRequestInfo::TYPE_TOGGLEENDORSEMENT, userData, subModule, game);
- requestInfo.m_Endorse = endorse;
- m_RequestQueue.enqueue(requestInfo);
-
- connect(this, SIGNAL(nxmEndorsementToggled(QString, int, QVariant, QVariant, int)),
- receiver, SLOT(nxmEndorsementToggled(QString, int, QVariant, QVariant, int)), Qt::UniqueConnection);
-
- connect(this, SIGNAL(nxmRequestFailed(QString, int, int, QVariant, int, QString)),
- receiver, SLOT(nxmRequestFailed(QString, int, int, QVariant, int, QString)), Qt::UniqueConnection);
-
- nextRequest();
- return requestInfo.m_ID;
-}
-
-bool NexusInterface::requiresLogin(const NXMRequestInfo &info)
-{
- return (info.m_Type == NXMRequestInfo::TYPE_TOGGLEENDORSEMENT)
- || (info.m_Type == NXMRequestInfo::TYPE_DOWNLOADURL);
-}
-
-IPluginGame* NexusInterface::getGame(QString gameName) const
-{
- auto gamePlugins = m_PluginContainer->plugins<IPluginGame>();
- IPluginGame *gamePlugin = qApp->property("managed_game").value<IPluginGame*>();
- for (auto plugin : gamePlugins) {
- if (plugin->gameShortName().compare(gameName, Qt::CaseInsensitive) == 0) {
- gamePlugin = plugin;
- break;
- }
- }
- return gamePlugin;
-}
-
-void NexusInterface::cleanup()
-{
-// delete m_AccessManager;
-// delete m_DiskCache;
- m_AccessManager = nullptr;
- m_DiskCache = nullptr;
-}
-
-void NexusInterface::clearCache()
-{
- m_DiskCache->clear();
- m_AccessManager->clearCookies();
-}
-
-void NexusInterface::nextRequest()
-{
- if ((m_ActiveRequest.size() >= MAX_ACTIVE_DOWNLOADS)
- || m_RequestQueue.isEmpty()) {
- return;
- }
-
- if (requiresLogin(m_RequestQueue.head()) && !getAccessManager()->validated()) {
- if (!getAccessManager()->validateAttempted()) {
- emit needLogin();
- return;
- } else if (getAccessManager()->validateWaiting()) {
- return;
- }
- }
-
- NXMRequestInfo info = m_RequestQueue.dequeue();
- info.m_Timeout = new QTimer(this);
- info.m_Timeout->setInterval(60000);
-
- QJsonObject postObject;
- QJsonDocument postData(postObject);
-
- QString url;
- if (!info.m_Reroute) {
- bool hasParams = false;
- switch (info.m_Type) {
- case NXMRequestInfo::TYPE_DESCRIPTION: {
- url = QString("%1/games/%2/mods/%3").arg(info.m_URL).arg(info.m_GameName).arg(info.m_ModID);
- } break;
- case NXMRequestInfo::TYPE_FILES: {
- url = QString("%1/games/%2/mods/%3/files").arg(info.m_URL).arg(info.m_GameName).arg(info.m_ModID);
- } break;
- case NXMRequestInfo::TYPE_FILEINFO: {
- url = QString("%1/games/%2/mods/%3/files/%4").arg(info.m_URL).arg(info.m_GameName).arg(info.m_ModID).arg(info.m_FileID);
- } break;
- case NXMRequestInfo::TYPE_DOWNLOADURL: {
- url = QString("%1/games/%2/mods/%3/files/%4/download_link").arg(info.m_URL).arg(info.m_GameName).arg(info.m_ModID).arg(info.m_FileID);
- } break;
- case NXMRequestInfo::TYPE_TOGGLEENDORSEMENT: {
- QString endorse = info.m_Endorse ? "endorse" : "abstain";
- url = QString("%1/games/%2/mods/%3/%4").arg(info.m_URL).arg(info.m_GameName).arg(info.m_ModID).arg(endorse);
- postObject.insert("Version", info.m_ModVersion);
- postData.setObject(postObject);
- } break;
- case NXMRequestInfo::TYPE_GETUPDATES: {
- QString modIDList = VectorJoin<int>(info.m_ModIDList, ",");
- modIDList = "[" + modIDList + "]";
- url = QString("%1/Mods/GetUpdates?ModList=%2").arg(info.m_URL).arg(modIDList);
- } break;
- }
- } else {
- url = info.m_URL;
- }
- QNetworkRequest request(url);
- request.setRawHeader("apikey", m_AccessManager->apiKey().toUtf8());
- request.setHeader(QNetworkRequest::KnownHeaders::UserAgentHeader, m_AccessManager->userAgent(info.m_SubModule));
- request.setHeader(QNetworkRequest::KnownHeaders::ContentTypeHeader, "application/json");
- request.setRawHeader("Protocol-Version", "0.5.5");
- request.setRawHeader("Application-Version", QApplication::applicationVersion().toUtf8());
-
- if (postData.object().isEmpty())
- info.m_Reply = m_AccessManager->get(request);
- else
- info.m_Reply = m_AccessManager->post(request, postData.toJson());
-
- connect(info.m_Reply, SIGNAL(finished()), this, SLOT(requestFinished()));
- connect(info.m_Reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(requestError(QNetworkReply::NetworkError)));
- connect(info.m_Timeout, SIGNAL(timeout()), this, SLOT(requestTimeout()));
- info.m_Timeout->start();
- m_ActiveRequest.push_back(info);
-}
-
-
-void NexusInterface::downloadRequestedNXM(const QString &url)
-{
- emit requestNXMDownload(url);
-}
-
-void NexusInterface::requestFinished(std::list<NXMRequestInfo>::iterator iter)
-{
- QNetworkReply *reply = iter->m_Reply;
-
- if (reply->error() != QNetworkReply::NoError) {
- qWarning("request failed: %s", reply->errorString().toUtf8().constData());
- emit nxmRequestFailed(iter->m_GameName, iter->m_ModID, iter->m_FileID, iter->m_UserData, iter->m_ID, reply->errorString());
- } else {
- int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
- if (statusCode == 301) {
- // redirect request, return request to queue
- iter->m_URL = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString();
- iter->m_Reroute = true;
- m_RequestQueue.enqueue(*iter);
- //nextRequest();
- return;
- }
- QByteArray data = reply->readAll();
- if (data.isNull() || data.isEmpty() || (strcmp(data.constData(), "null") == 0)) {
- QString nexusError(reply->rawHeader("NexusErrorInfo"));
- if (nexusError.length() == 0) {
- nexusError = tr("empty response");
- }
- qDebug("nexus error: %s", qUtf8Printable(nexusError));
- emit nxmRequestFailed(iter->m_GameName, iter->m_ModID, iter->m_FileID, iter->m_UserData, iter->m_ID, nexusError);
- } else {
- bool ok;
- QVariant result = QtJson::parse(data, ok);
- if (result.isValid() && ok) {
- switch (iter->m_Type) {
- case NXMRequestInfo::TYPE_DESCRIPTION: {
- emit nxmDescriptionAvailable(iter->m_GameName, iter->m_ModID, iter->m_UserData, result, iter->m_ID);
- } break;
- case NXMRequestInfo::TYPE_FILES: {
- emit nxmFilesAvailable(iter->m_GameName, iter->m_ModID, iter->m_UserData, result, iter->m_ID);
- } break;
- case NXMRequestInfo::TYPE_FILEINFO: {
- emit nxmFileInfoAvailable(iter->m_GameName, iter->m_ModID, iter->m_FileID, iter->m_UserData, result, iter->m_ID);
- } break;
- case NXMRequestInfo::TYPE_DOWNLOADURL: {
- emit nxmDownloadURLsAvailable(iter->m_GameName, iter->m_ModID, iter->m_FileID, iter->m_UserData, result, iter->m_ID);
- } break;
- case NXMRequestInfo::TYPE_GETUPDATES: {
- emit nxmUpdatesAvailable(iter->m_ModIDList, iter->m_UserData, result, iter->m_ID);
- } break;
- case NXMRequestInfo::TYPE_TOGGLEENDORSEMENT: {
- emit nxmEndorsementToggled(iter->m_GameName, iter->m_ModID, iter->m_UserData, result, iter->m_ID);
- } break;
- }
- } else {
- emit nxmRequestFailed(iter->m_GameName, iter->m_ModID, iter->m_FileID, iter->m_UserData, iter->m_ID, tr("invalid response"));
- }
- }
- }
-}
-
-
-void NexusInterface::requestFinished()
-{
- QNetworkReply *reply = static_cast<QNetworkReply*>(sender());
- for (std::list<NXMRequestInfo>::iterator iter = m_ActiveRequest.begin(); iter != m_ActiveRequest.end(); ++iter) {
- if (iter->m_Reply == reply) {
- iter->m_Timeout->stop();
- iter->m_Timeout->deleteLater();
- requestFinished(iter);
- iter->m_Reply->deleteLater();
- m_ActiveRequest.erase(iter);
- nextRequest();
- return;
- }
- }
-}
-
-
-void NexusInterface::requestError(QNetworkReply::NetworkError)
-{
- QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
- if (reply == nullptr) {
- qWarning("invalid sender type");
- return;
- }
-
- qCritical("request (%s) error: %s (%d)",
- qUtf8Printable(reply->url().toString()),
- qUtf8Printable(reply->errorString()),
- reply->error());
-}
-
-
-void NexusInterface::requestTimeout()
-{
- QTimer *timer = qobject_cast<QTimer*>(sender());
- if (timer == nullptr) {
- qWarning("invalid sender type");
- return;
- }
- for (std::list<NXMRequestInfo>::iterator iter = m_ActiveRequest.begin(); iter != m_ActiveRequest.end(); ++iter) {
- if (iter->m_Timeout == timer) {
- // this abort causes a "request failed" which cleans up the rest
- iter->m_Reply->abort();
- return;
- }
- }
-}
-
-namespace {
- QString get_management_url(MOBase::IPluginGame const *game)
- {
- return "https://api.nexusmods.com/v1";
- }
-}
-
-NexusInterface::NXMRequestInfo::NXMRequestInfo(int modID
- , NexusInterface::NXMRequestInfo::Type type
- , QVariant userData
- , const QString &subModule
- , MOBase::IPluginGame const *game
- )
- : m_ModID(modID)
- , m_ModVersion("0")
- , m_FileID(0)
- , m_Reply(nullptr)
- , m_Type(type)
- , m_UserData(userData)
- , m_Timeout(nullptr)
- , m_Reroute(false)
- , m_ID(s_NextID.fetchAndAddAcquire(1))
- , m_URL(get_management_url(game))
- , m_SubModule(subModule)
- , m_NexusGameID(game->nexusGameID())
- , m_GameName(game->gameNexusName())
- , m_Endorse(false)
-{}
-
-NexusInterface::NXMRequestInfo::NXMRequestInfo(int modID
- , QString modVersion
- , NexusInterface::NXMRequestInfo::Type type
- , QVariant userData
- , const QString &subModule
- , MOBase::IPluginGame const *game
-)
- : m_ModID(modID)
- , m_ModVersion(modVersion)
- , m_FileID(0)
- , m_Reply(nullptr)
- , m_Type(type)
- , m_UserData(userData)
- , m_Timeout(nullptr)
- , m_Reroute(false)
- , m_ID(s_NextID.fetchAndAddAcquire(1))
- , m_URL(get_management_url(game))
- , m_SubModule(subModule)
- , m_NexusGameID(game->nexusGameID())
- , m_GameName(game->gameNexusName())
- , m_Endorse(false)
-{}
-
-NexusInterface::NXMRequestInfo::NXMRequestInfo(std::vector<int> modIDList
- , NexusInterface::NXMRequestInfo::Type type
- , QVariant userData
- , const QString &subModule
- , MOBase::IPluginGame const *game
- )
- : m_ModID(-1)
- , m_ModVersion("0")
- , m_ModIDList(modIDList)
- , m_FileID(0)
- , m_Reply(nullptr)
- , m_Type(type)
- , m_UserData(userData)
- , m_Timeout(nullptr)
- , m_Reroute(false)
- , m_ID(s_NextID.fetchAndAddAcquire(1))
- , m_URL(get_management_url(game))
- , m_SubModule(subModule)
- , m_NexusGameID(game->nexusGameID())
- , m_GameName(game->gameNexusName())
- , m_Endorse(false)
-{}
-
-NexusInterface::NXMRequestInfo::NXMRequestInfo(int modID
- , int fileID
- , NexusInterface::NXMRequestInfo::Type type
- , QVariant userData
- , const QString &subModule
- , MOBase::IPluginGame const *game
-)
- : m_ModID(modID)
- , m_ModVersion("0")
- , m_FileID(fileID)
- , m_Reply(nullptr)
- , m_Type(type)
- , m_UserData(userData)
- , m_Timeout(nullptr)
- , m_Reroute(false)
- , m_ID(s_NextID.fetchAndAddAcquire(1))
- , m_URL(get_management_url(game))
- , m_SubModule(subModule)
- , m_NexusGameID(game->nexusGameID())
- , m_GameName(game->gameNexusName())
- , m_Endorse(false)
-{}
+/*
+Copyright (C) 2012 Sebastian Herbord. All rights reserved.
+
+This file is part of Mod Organizer.
+
+Mod Organizer is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+Mod Organizer is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Mod Organizer. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "nexusinterface.h"
+
+#include "iplugingame.h"
+#include "nxmaccessmanager.h"
+#include "json.h"
+#include "selectiondialog.h"
+#include "bbcode.h"
+#include <utility.h>
+#include <util.h>
+
+#include <QApplication>
+#include <QNetworkCookieJar>
+#include <QJsonDocument>
+
+#include <regex>
+
+
+using namespace MOBase;
+using namespace MOShared;
+
+
+NexusBridge::NexusBridge(PluginContainer *pluginContainer, const QString &subModule)
+ : m_Interface(NexusInterface::instance(pluginContainer))
+ , m_SubModule(subModule)
+{
+}
+
+void NexusBridge::requestDescription(QString gameName, int modID, QVariant userData)
+{
+ m_RequestIDs.insert(m_Interface->requestDescription(gameName, modID, this, userData, m_SubModule));
+}
+
+void NexusBridge::requestFiles(QString gameName, int modID, QVariant userData)
+{
+ m_RequestIDs.insert(m_Interface->requestFiles(gameName, modID, this, userData, m_SubModule));
+}
+
+void NexusBridge::requestFileInfo(QString gameName, int modID, int fileID, QVariant userData)
+{
+ m_RequestIDs.insert(m_Interface->requestFileInfo(gameName, modID, fileID, this, userData, m_SubModule));
+}
+
+void NexusBridge::requestDownloadURL(QString gameName, int modID, int fileID, QVariant userData)
+{
+ m_RequestIDs.insert(m_Interface->requestDownloadURL(gameName, modID, fileID, this, userData, m_SubModule));
+}
+
+void NexusBridge::requestToggleEndorsement(QString gameName, int modID, QString modVersion, bool endorse, QVariant userData)
+{
+ m_RequestIDs.insert(m_Interface->requestToggleEndorsement(gameName, modID, modVersion, endorse, this, userData, m_SubModule));
+}
+
+void NexusBridge::nxmDescriptionAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID)
+{
+ std::set<int>::iterator iter = m_RequestIDs.find(requestID);
+ if (iter != m_RequestIDs.end()) {
+ m_RequestIDs.erase(iter);
+
+ emit descriptionAvailable(gameName, modID, userData, resultData);
+ }
+}
+
+void NexusBridge::nxmFilesAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID)
+{
+ std::set<int>::iterator iter = m_RequestIDs.find(requestID);
+ if (iter != m_RequestIDs.end()) {
+ m_RequestIDs.erase(iter);
+
+ QList<ModRepositoryFileInfo> fileInfoList;
+
+ QVariantMap resultInfo = resultData.toMap();
+ QList resultList = resultInfo["files"].toList();
+
+ for (const QVariant &file : resultList) {
+ ModRepositoryFileInfo temp;
+ QVariantMap fileInfo = file.toMap();
+ temp.uri = fileInfo["file_name"].toString();
+ temp.name = fileInfo["name"].toString();
+ temp.description = BBCode::convertToHTML(fileInfo["changelog_html"].toString());
+ temp.version = VersionInfo(fileInfo["version"].toString());
+ temp.categoryID = fileInfo["category_id"].toInt();
+ temp.fileID = fileInfo["file_id"].toInt();
+ temp.fileSize = fileInfo["size"].toInt();
+ fileInfoList.append(temp);
+ }
+
+ emit filesAvailable(gameName, modID, userData, fileInfoList);
+ }
+}
+
+void NexusBridge::nxmFileInfoAvailable(QString gameName, int modID, int fileID, QVariant userData, QVariant resultData, int requestID)
+{
+ std::set<int>::iterator iter = m_RequestIDs.find(requestID);
+ if (iter != m_RequestIDs.end()) {
+ m_RequestIDs.erase(iter);
+ emit fileInfoAvailable(gameName, modID, fileID, userData, resultData);
+ }
+}
+
+void NexusBridge::nxmDownloadURLsAvailable(QString gameName, int modID, int fileID, QVariant userData, QVariant resultData, int requestID)
+{
+ std::set<int>::iterator iter = m_RequestIDs.find(requestID);
+ if (iter != m_RequestIDs.end()) {
+ m_RequestIDs.erase(iter);
+ emit downloadURLsAvailable(gameName, modID, fileID, userData, resultData);
+ }
+}
+
+void NexusBridge::nxmEndorsementToggled(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID)
+{
+ std::set<int>::iterator iter = m_RequestIDs.find(requestID);
+ if (iter != m_RequestIDs.end()) {
+ m_RequestIDs.erase(iter);
+ emit endorsementToggled(gameName, modID, userData, resultData);
+ }
+}
+
+void NexusBridge::nxmRequestFailed(QString gameName, int modID, int fileID, QVariant userData, int requestID, QNetworkReply::NetworkError error, const QString &errorMessage)
+{
+ std::set<int>::iterator iter = m_RequestIDs.find(requestID);
+ if (iter != m_RequestIDs.end()) {
+ m_RequestIDs.erase(iter);
+ emit requestFailed(gameName, modID, fileID, userData, errorMessage);
+ }
+}
+
+
+QAtomicInt NexusInterface::NXMRequestInfo::s_NextID(0);
+
+
+NexusInterface::NexusInterface(PluginContainer *pluginContainer)
+ : m_NMMVersion(), m_PluginContainer(pluginContainer)
+{
+ m_MOVersion = createVersionInfo();
+
+ m_AccessManager = new NXMAccessManager(this, m_MOVersion.displayString(3));
+ m_DiskCache = new QNetworkDiskCache(this);
+ connect(m_AccessManager, SIGNAL(requestNXMDownload(QString)), this, SLOT(downloadRequestedNXM(QString)));
+}
+
+NXMAccessManager *NexusInterface::getAccessManager()
+{
+ return m_AccessManager;
+}
+
+NexusInterface::~NexusInterface()
+{
+ cleanup();
+}
+
+NexusInterface *NexusInterface::instance(PluginContainer *pluginContainer)
+{
+ static NexusInterface s_Instance(pluginContainer);
+ return &s_Instance;
+}
+
+void NexusInterface::setCacheDirectory(const QString &directory)
+{
+ m_DiskCache->setCacheDirectory(directory);
+ m_AccessManager->setCache(m_DiskCache);
+}
+
+void NexusInterface::setNMMVersion(const QString &nmmVersion)
+{
+ m_NMMVersion = nmmVersion;
+ m_AccessManager->setNMMVersion(nmmVersion);
+}
+
+void NexusInterface::loginCompleted()
+{
+ nextRequest();
+}
+
+
+void NexusInterface::interpretNexusFileName(const QString &fileName, QString &modName, int &modID, bool query)
+{
+ //Look for something along the lines of modulename-Vn-m + any old rubbish.
+ static std::regex exp(R"exp(^([a-zA-Z0-9_'"\-.() ]*?)([-_ ][VvRr]?[0-9_]+)?-([1-9][0-9]*).*\.(zip|rar|7z))exp");
+ static std::regex simpleexp("^([a-zA-Z0-9_]+)");
+
+ QByteArray fileNameUTF8 = fileName.toUtf8();
+ std::cmatch result;
+ if (std::regex_search(fileNameUTF8.constData(), result, exp)) {
+ modName = QString::fromUtf8(result[1].str().c_str());
+ modName = modName.replace('_', ' ').trimmed();
+
+ std::string candidate = result[3].str();
+ std::string candidate2 = result[2].str();
+ if (candidate2.length() != 0 && (candidate2.find_last_of("VvRr") == std::string::npos)) {
+ // well, that second match might be an id too...
+ size_t offset = strspn(candidate2.c_str(), "-_ ");
+ if (offset < candidate2.length() && query) {
+ SelectionDialog selection(tr("Failed to guess mod id for \"%1\", please pick the correct one").arg(fileName));
+ QString r2Highlight(fileName);
+ r2Highlight.insert(result.position(2) + result.length(2), "* ")
+ .insert(result.position(2) + static_cast<int>(offset), " *");
+ QString r3Highlight(fileName);
+ r3Highlight.insert(result.position(3) + result.length(3), "* ").insert(result.position(3), " *");
+
+ selection.addChoice(candidate.c_str(), r3Highlight, static_cast<int>(strtol(candidate.c_str(), nullptr, 10)));
+ selection.addChoice(candidate2.c_str() + offset, r2Highlight, static_cast<int>(abs(strtol(candidate2.c_str() + offset, nullptr, 10))));
+ if (selection.exec() == QDialog::Accepted) {
+ modID = selection.getChoiceData().toInt();
+ } else {
+ modID = -1;
+ }
+ } else {
+ modID = -1;
+ }
+ } else {
+ modID = strtol(candidate.c_str(), nullptr, 10);
+ }
+ qDebug("mod id guessed: %s -> %d", qUtf8Printable(fileName), modID);
+ } else if (std::regex_search(fileNameUTF8.constData(), result, simpleexp)) {
+ qDebug("simple expression matched, using name only");
+ modName = QString::fromUtf8(result[1].str().c_str());
+ modName = modName.replace('_', ' ').trimmed();
+
+ modID = -1;
+ } else {
+ qDebug("no expression matched!");
+ modName.clear();
+ modID = -1;
+ }
+}
+
+bool NexusInterface::isURLGameRelated(const QUrl &url) const
+{
+ QString const name(url.toString());
+ return name.startsWith(getGameURL("") + "/") ||
+ name.startsWith(getOldModsURL("") + "/");
+}
+
+QString NexusInterface::getGameURL(QString gameName) const
+{
+ IPluginGame *game = getGame(gameName);
+ return "https://www.nexusmods.com/" + game->gameNexusName().toLower();
+}
+
+QString NexusInterface::getOldModsURL(QString gameName) const
+{
+ IPluginGame *game = getGame(gameName);
+ return "https://" + game->gameNexusName().toLower() + ".nexusmods.com/mods";
+}
+
+
+QString NexusInterface::getModURL(int modID, QString gameName = "") const
+{
+ return QString("%1/mods/%2").arg(getGameURL(gameName)).arg(modID);
+}
+
+std::vector<std::pair<QString, QString>> NexusInterface::getGameChoices(const MOBase::IPluginGame *game)
+{
+ std::vector<std::pair<QString, QString>> choices;
+ choices.push_back(std::pair<QString, QString>(game->gameShortName(), game->gameName()));
+ for (QString gameName : game->validShortNames()) {
+ for (auto gamePlugin : m_PluginContainer->plugins<IPluginGame>()) {
+ if (gamePlugin->gameShortName().compare(gameName, Qt::CaseInsensitive) == 0) {
+ choices.push_back(std::pair<QString, QString>(gamePlugin->gameShortName(), gamePlugin->gameName()));
+ break;
+ }
+ }
+ }
+ return choices;
+}
+
+bool NexusInterface::isModURL(int modID, const QString &url) const
+{
+ if (QUrl(url) == QUrl(getModURL(modID))) {
+ return true;
+ }
+ //Try the alternate (old style) mod name
+ QString alt = QString("%1/%2").arg(getOldModsURL("")).arg(modID);
+ return QUrl(alt) == QUrl(url);
+}
+
+void NexusInterface::setPluginContainer(PluginContainer *pluginContainer)
+{
+ m_PluginContainer = pluginContainer;
+}
+
+int NexusInterface::requestDescription(QString gameName, int modID, QObject *receiver, QVariant userData,
+ const QString &subModule, MOBase::IPluginGame const *game)
+{
+ NXMRequestInfo requestInfo(modID, NXMRequestInfo::TYPE_DESCRIPTION, userData, subModule, game);
+ m_RequestQueue.enqueue(requestInfo);
+
+ connect(this, SIGNAL(nxmDescriptionAvailable(QString, int, QVariant, QVariant, int)),
+ receiver, SLOT(nxmDescriptionAvailable(QString, int, QVariant, QVariant, int)), Qt::UniqueConnection);
+
+ connect(this, SIGNAL(nxmRequestFailed(QString, int, int, QVariant, int, QNetworkReply::NetworkError, QString)),
+ receiver, SLOT(nxmRequestFailed(QString, int, int, QVariant, int, QNetworkReply::NetworkError, QString)), Qt::UniqueConnection);
+
+ nextRequest();
+ return requestInfo.m_ID;
+}
+
+
+int NexusInterface::requestUpdates(const int &modID, QObject *receiver, QVariant userData,
+ QString gameName, const QString &subModule)
+{
+ IPluginGame *game = getGame(gameName);
+ NXMRequestInfo requestInfo(modID, NXMRequestInfo::TYPE_GETUPDATES, userData, subModule, game);
+ m_RequestQueue.enqueue(requestInfo);
+
+ connect(this, SIGNAL(nxmUpdatesAvailable(QString, int, QVariant, QVariant, int)),
+ receiver, SLOT(nxmUpdatesAvailable(QString, int, QVariant, QVariant, int)), Qt::UniqueConnection);
+
+ connect(this, SIGNAL(nxmRequestFailed(QString, int, int, QVariant, int, QNetworkReply::NetworkError, QString)),
+ receiver, SLOT(nxmRequestFailed(QString, int, int, QVariant, int, QNetworkReply::NetworkError, QString)), Qt::UniqueConnection);
+
+ nextRequest();
+ return requestInfo.m_ID;
+}
+
+
+void NexusInterface::fakeFiles()
+{
+ static int id = 42;
+
+ QVariantList result;
+ QVariantMap fileMap;
+ fileMap["uri"] = "fakeURI";
+ fileMap["name"] = "fakeName";
+ fileMap["description"] = "fakeDescription";
+ fileMap["version"] = "1.0.0";
+ fileMap["category_id"] = "1";
+ fileMap["id"] = "1";
+ fileMap["size"] = "512";
+ result.append(fileMap);
+
+ emit nxmFilesAvailable("fakeGame", 1234, "fake", result, id++);
+}
+
+
+int NexusInterface::requestFiles(QString gameName, int modID, QObject *receiver, QVariant userData,
+ const QString &subModule, MOBase::IPluginGame const *game)
+{
+ NXMRequestInfo requestInfo(modID, NXMRequestInfo::TYPE_FILES, userData, subModule, game);
+ m_RequestQueue.enqueue(requestInfo);
+ connect(this, SIGNAL(nxmFilesAvailable(QString, int, QVariant, QVariant, int)),
+ receiver, SLOT(nxmFilesAvailable(QString, int, QVariant, QVariant, int)), Qt::UniqueConnection);
+
+ connect(this, SIGNAL(nxmRequestFailed(QString, int, int, QVariant, int, QNetworkReply::NetworkError, QString)),
+ receiver, SLOT(nxmRequestFailed(QString, int, int, QVariant, int, QNetworkReply::NetworkError, QString)), Qt::UniqueConnection);
+
+ nextRequest();
+ return requestInfo.m_ID;
+}
+
+
+int NexusInterface::requestFileInfo(QString gameName, int modID, int fileID, QObject *receiver, QVariant userData, const QString &subModule)
+{
+ IPluginGame *gamePlugin = getGame(gameName);
+ NXMRequestInfo requestInfo(modID, fileID, NXMRequestInfo::TYPE_FILEINFO, userData, subModule, gamePlugin);
+ m_RequestQueue.enqueue(requestInfo);
+
+ connect(this, SIGNAL(nxmFileInfoAvailable(QString, int, int, QVariant, QVariant, int)),
+ receiver, SLOT(nxmFileInfoAvailable(QString, int, int, QVariant, QVariant, int)), Qt::UniqueConnection);
+
+ connect(this, SIGNAL(nxmRequestFailed(QString, int, int, QVariant, int, QNetworkReply::NetworkError, QString)),
+ receiver, SLOT(nxmRequestFailed(QString, int, int, QVariant, int, QNetworkReply::NetworkError, QString)), Qt::UniqueConnection);
+
+ nextRequest();
+ return requestInfo.m_ID;
+}
+
+
+int NexusInterface::requestDownloadURL(QString gameName, int modID, int fileID, QObject *receiver, QVariant userData,
+ const QString &subModule, MOBase::IPluginGame const *game)
+{
+ NXMRequestInfo requestInfo(modID, fileID, NXMRequestInfo::TYPE_DOWNLOADURL, userData, subModule, game);
+ m_RequestQueue.enqueue(requestInfo);
+
+ connect(this, SIGNAL(nxmDownloadURLsAvailable(QString,int,int,QVariant,QVariant,int)),
+ receiver, SLOT(nxmDownloadURLsAvailable(QString,int,int,QVariant,QVariant,int)), Qt::UniqueConnection);
+
+ connect(this, SIGNAL(nxmRequestFailed(QString,int,int,QVariant,int,QNetworkReply::NetworkError,QString)),
+ receiver, SLOT(nxmRequestFailed(QString,int,int,QVariant,int,QNetworkReply::NetworkError,QString)), Qt::UniqueConnection);
+
+ nextRequest();
+ return requestInfo.m_ID;
+}
+
+
+int NexusInterface::requestToggleEndorsement(QString gameName, int modID, QString modVersion, bool endorse, QObject *receiver, QVariant userData,
+ const QString &subModule, MOBase::IPluginGame const *game)
+{
+ NXMRequestInfo requestInfo(modID, modVersion, NXMRequestInfo::TYPE_TOGGLEENDORSEMENT, userData, subModule, game);
+ requestInfo.m_Endorse = endorse;
+ m_RequestQueue.enqueue(requestInfo);
+
+ connect(this, SIGNAL(nxmEndorsementToggled(QString, int, QVariant, QVariant, int)),
+ receiver, SLOT(nxmEndorsementToggled(QString, int, QVariant, QVariant, int)), Qt::UniqueConnection);
+
+ connect(this, SIGNAL(nxmRequestFailed(QString, int, int, QVariant, int, QNetworkReply::NetworkError, QString)),
+ receiver, SLOT(nxmRequestFailed(QString, int, int, QVariant, int, QNetworkReply::NetworkError, QString)), Qt::UniqueConnection);
+
+ nextRequest();
+ return requestInfo.m_ID;
+}
+
+bool NexusInterface::requiresLogin(const NXMRequestInfo &info)
+{
+ return (info.m_Type == NXMRequestInfo::TYPE_TOGGLEENDORSEMENT)
+ || (info.m_Type == NXMRequestInfo::TYPE_DOWNLOADURL);
+}
+
+IPluginGame* NexusInterface::getGame(QString gameName) const
+{
+ auto gamePlugins = m_PluginContainer->plugins<IPluginGame>();
+ IPluginGame *gamePlugin = qApp->property("managed_game").value<IPluginGame*>();
+ for (auto plugin : gamePlugins) {
+ if (plugin->gameShortName().compare(gameName, Qt::CaseInsensitive) == 0) {
+ gamePlugin = plugin;
+ break;
+ }
+ }
+ return gamePlugin;
+}
+
+void NexusInterface::cleanup()
+{
+// delete m_AccessManager;
+// delete m_DiskCache;
+ m_AccessManager = nullptr;
+ m_DiskCache = nullptr;
+}
+
+void NexusInterface::clearCache()
+{
+ m_DiskCache->clear();
+ m_AccessManager->clearCookies();
+}
+
+void NexusInterface::nextRequest()
+{
+ if ((m_ActiveRequest.size() >= MAX_ACTIVE_DOWNLOADS)
+ || m_RequestQueue.isEmpty()) {
+ return;
+ }
+
+ if (requiresLogin(m_RequestQueue.head()) && !getAccessManager()->validated()) {
+ if (!getAccessManager()->validateAttempted()) {
+ emit needLogin();
+ return;
+ } else if (getAccessManager()->validateWaiting()) {
+ return;
+ }
+ }
+
+ NXMRequestInfo info = m_RequestQueue.dequeue();
+ info.m_Timeout = new QTimer(this);
+ info.m_Timeout->setInterval(60000);
+
+ QJsonObject postObject;
+ QJsonDocument postData(postObject);
+
+ QString url;
+ if (!info.m_Reroute) {
+ bool hasParams = false;
+ switch (info.m_Type) {
+ case NXMRequestInfo::TYPE_DESCRIPTION: {
+ url = QString("%1/games/%2/mods/%3").arg(info.m_URL).arg(info.m_GameName).arg(info.m_ModID);
+ } break;
+ case NXMRequestInfo::TYPE_FILES: {
+ url = QString("%1/games/%2/mods/%3/files").arg(info.m_URL).arg(info.m_GameName).arg(info.m_ModID);
+ } break;
+ case NXMRequestInfo::TYPE_GETUPDATES: {
+ url = QString("%1/games/%2/mods/%3/files").arg(info.m_URL).arg(info.m_GameName).arg(info.m_ModID);
+ } break;
+ case NXMRequestInfo::TYPE_FILEINFO: {
+ url = QString("%1/games/%2/mods/%3/files/%4").arg(info.m_URL).arg(info.m_GameName).arg(info.m_ModID).arg(info.m_FileID);
+ } break;
+ case NXMRequestInfo::TYPE_DOWNLOADURL: {
+ url = QString("%1/games/%2/mods/%3/files/%4/download_link").arg(info.m_URL).arg(info.m_GameName).arg(info.m_ModID).arg(info.m_FileID);
+ } break;
+ case NXMRequestInfo::TYPE_TOGGLEENDORSEMENT: {
+ QString endorse = info.m_Endorse ? "endorse" : "abstain";
+ url = QString("%1/games/%2/mods/%3/%4").arg(info.m_URL).arg(info.m_GameName).arg(info.m_ModID).arg(endorse);
+ postObject.insert("Version", info.m_ModVersion);
+ postData.setObject(postObject);
+ } break;
+ }
+ } else {
+ url = info.m_URL;
+ }
+ QNetworkRequest request(url);
+ request.setRawHeader("apikey", m_AccessManager->apiKey().toUtf8());
+ request.setHeader(QNetworkRequest::KnownHeaders::UserAgentHeader, m_AccessManager->userAgent(info.m_SubModule));
+ request.setHeader(QNetworkRequest::KnownHeaders::ContentTypeHeader, "application/json");
+ request.setRawHeader("Protocol-Version", "0.5.5");
+ request.setRawHeader("Application-Version", QApplication::applicationVersion().toUtf8());
+
+ if (postData.object().isEmpty())
+ info.m_Reply = m_AccessManager->get(request);
+ else
+ info.m_Reply = m_AccessManager->post(request, postData.toJson());
+
+ connect(info.m_Reply, SIGNAL(finished()), this, SLOT(requestFinished()));
+ connect(info.m_Reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(requestError(QNetworkReply::NetworkError)));
+ connect(info.m_Timeout, SIGNAL(timeout()), this, SLOT(requestTimeout()));
+ info.m_Timeout->start();
+ m_ActiveRequest.push_back(info);
+}
+
+
+void NexusInterface::downloadRequestedNXM(const QString &url)
+{
+ emit requestNXMDownload(url);
+}
+
+void NexusInterface::requestFinished(std::list<NXMRequestInfo>::iterator iter)
+{
+ QNetworkReply *reply = iter->m_Reply;
+
+ if (reply->error() != QNetworkReply::NoError) {
+ qWarning("request failed: %s", reply->errorString().toUtf8().constData());
+ emit nxmRequestFailed(iter->m_GameName, iter->m_ModID, iter->m_FileID, iter->m_UserData, iter->m_ID, reply->error(), reply->errorString());
+ } else {
+ int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+ if (statusCode == 301) {
+ // redirect request, return request to queue
+ iter->m_URL = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString();
+ iter->m_Reroute = true;
+ m_RequestQueue.enqueue(*iter);
+ //nextRequest();
+ return;
+ }
+ QByteArray data = reply->readAll();
+ if (data.isNull() || data.isEmpty() || (strcmp(data.constData(), "null") == 0)) {
+ QString nexusError(reply->rawHeader("NexusErrorInfo"));
+ if (nexusError.length() == 0) {
+ nexusError = tr("empty response");
+ }
+ qDebug("nexus error: %s", qUtf8Printable(nexusError));
+ emit nxmRequestFailed(iter->m_GameName, iter->m_ModID, iter->m_FileID, iter->m_UserData, iter->m_ID, reply->error(), nexusError);
+ } else {
+ bool ok;
+ QVariant result = QtJson::parse(data, ok);
+ if (result.isValid() && ok) {
+ switch (iter->m_Type) {
+ case NXMRequestInfo::TYPE_DESCRIPTION: {
+ emit nxmDescriptionAvailable(iter->m_GameName, iter->m_ModID, iter->m_UserData, result, iter->m_ID);
+ } break;
+ case NXMRequestInfo::TYPE_FILES: {
+ emit nxmFilesAvailable(iter->m_GameName, iter->m_ModID, iter->m_UserData, result, iter->m_ID);
+ } break;
+ case NXMRequestInfo::TYPE_FILEINFO: {
+ emit nxmFileInfoAvailable(iter->m_GameName, iter->m_ModID, iter->m_FileID, iter->m_UserData, result, iter->m_ID);
+ } break;
+ case NXMRequestInfo::TYPE_DOWNLOADURL: {
+ emit nxmDownloadURLsAvailable(iter->m_GameName, iter->m_ModID, iter->m_FileID, iter->m_UserData, result, iter->m_ID);
+ } break;
+ case NXMRequestInfo::TYPE_GETUPDATES: {
+ emit nxmUpdatesAvailable(iter->m_GameName, iter->m_ModID, iter->m_UserData, result, iter->m_ID);
+ } break;
+ case NXMRequestInfo::TYPE_TOGGLEENDORSEMENT: {
+ emit nxmEndorsementToggled(iter->m_GameName, iter->m_ModID, iter->m_UserData, result, iter->m_ID);
+ } break;
+ }
+ } else {
+ emit nxmRequestFailed(iter->m_GameName, iter->m_ModID, iter->m_FileID, iter->m_UserData, iter->m_ID, reply->error(), tr("invalid response"));
+ }
+ }
+ }
+}
+
+
+void NexusInterface::requestFinished()
+{
+ QNetworkReply *reply = static_cast<QNetworkReply*>(sender());
+ for (std::list<NXMRequestInfo>::iterator iter = m_ActiveRequest.begin(); iter != m_ActiveRequest.end(); ++iter) {
+ if (iter->m_Reply == reply) {
+ iter->m_Timeout->stop();
+ iter->m_Timeout->deleteLater();
+ requestFinished(iter);
+ iter->m_Reply->deleteLater();
+ m_ActiveRequest.erase(iter);
+ nextRequest();
+ return;
+ }
+ }
+}
+
+
+void NexusInterface::requestError(QNetworkReply::NetworkError)
+{
+ QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
+ if (reply == nullptr) {
+ qWarning("invalid sender type");
+ return;
+ }
+
+ qCritical("request (%s) error: %s (%d)",
+ qUtf8Printable(reply->url().toString()),
+ qUtf8Printable(reply->errorString()),
+ reply->error());
+}
+
+
+void NexusInterface::requestTimeout()
+{
+ QTimer *timer = qobject_cast<QTimer*>(sender());
+ if (timer == nullptr) {
+ qWarning("invalid sender type");
+ return;
+ }
+ for (std::list<NXMRequestInfo>::iterator iter = m_ActiveRequest.begin(); iter != m_ActiveRequest.end(); ++iter) {
+ if (iter->m_Timeout == timer) {
+ // this abort causes a "request failed" which cleans up the rest
+ iter->m_Reply->abort();
+ return;
+ }
+ }
+}
+
+namespace {
+ QString get_management_url(MOBase::IPluginGame const *game)
+ {
+ return "https://api.nexusmods.com/v1";
+ }
+}
+
+NexusInterface::NXMRequestInfo::NXMRequestInfo(int modID
+ , NexusInterface::NXMRequestInfo::Type type
+ , QVariant userData
+ , const QString &subModule
+ , MOBase::IPluginGame const *game
+ )
+ : m_ModID(modID)
+ , m_ModVersion("0")
+ , m_FileID(0)
+ , m_Reply(nullptr)
+ , m_Type(type)
+ , m_UserData(userData)
+ , m_Timeout(nullptr)
+ , m_Reroute(false)
+ , m_ID(s_NextID.fetchAndAddAcquire(1))
+ , m_URL(get_management_url(game))
+ , m_SubModule(subModule)
+ , m_NexusGameID(game->nexusGameID())
+ , m_GameName(game->gameNexusName())
+ , m_Endorse(false)
+{}
+
+NexusInterface::NXMRequestInfo::NXMRequestInfo(int modID
+ , QString modVersion
+ , NexusInterface::NXMRequestInfo::Type type
+ , QVariant userData
+ , const QString &subModule
+ , MOBase::IPluginGame const *game
+)
+ : m_ModID(modID)
+ , m_ModVersion(modVersion)
+ , m_FileID(0)
+ , m_Reply(nullptr)
+ , m_Type(type)
+ , m_UserData(userData)
+ , m_Timeout(nullptr)
+ , m_Reroute(false)
+ , m_ID(s_NextID.fetchAndAddAcquire(1))
+ , m_URL(get_management_url(game))
+ , m_SubModule(subModule)
+ , m_NexusGameID(game->nexusGameID())
+ , m_GameName(game->gameNexusName())
+ , m_Endorse(false)
+{}
+
+NexusInterface::NXMRequestInfo::NXMRequestInfo(int modID
+ , int fileID
+ , NexusInterface::NXMRequestInfo::Type type
+ , QVariant userData
+ , const QString &subModule
+ , MOBase::IPluginGame const *game
+)
+ : m_ModID(modID)
+ , m_ModVersion("0")
+ , m_FileID(fileID)
+ , m_Reply(nullptr)
+ , m_Type(type)
+ , m_UserData(userData)
+ , m_Timeout(nullptr)
+ , m_Reroute(false)
+ , m_ID(s_NextID.fetchAndAddAcquire(1))
+ , m_URL(get_management_url(game))
+ , m_SubModule(subModule)
+ , m_NexusGameID(game->nexusGameID())
+ , m_GameName(game->gameNexusName())
+ , m_Endorse(false)
+{}
diff --git a/src/nexusinterface.h b/src/nexusinterface.h
index 7b707711..56cdef47 100644
--- a/src/nexusinterface.h
+++ b/src/nexusinterface.h
@@ -1,424 +1,423 @@
-/*
-Copyright (C) 2012 Sebastian Herbord. All rights reserved.
-
-This file is part of Mod Organizer.
-
-Mod Organizer is free software: you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-Mod Organizer is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with Mod Organizer. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#ifndef NEXUSINTERFACE_H
-#define NEXUSINTERFACE_H
-
-#include <utility.h>
-#include <versioninfo.h>
-#include <imodrepositorybridge.h>
-#include <plugincontainer.h>
-
-#include <QNetworkReply>
-#include <QNetworkDiskCache>
-#include <QQueue>
-#include <QVariant>
-#include <QTimer>
-
-#include <list>
-#include <set>
-
-namespace MOBase { class IPluginGame; }
-
-class NexusInterface;
-class NXMAccessManager;
-
-/**
- * @brief convenience class to make nxm requests easier
- * usually, all objects that started a nxm request will be signaled if one finished.
- * Therefore, the objects need to store the id of the requests they started and then filter
- * the result.
- * NexusBridge does this automatically. Users connect to the signals of NexusBridge they intend
- * to handle and only receive the signals the caused
- **/
-class NexusBridge : public MOBase::IModRepositoryBridge
-{
-
- Q_OBJECT
-
-public:
-
- NexusBridge(PluginContainer *pluginContainer, const QString &subModule = "");
-
- /**
- * @brief request description for a mod
- *
- * @param modID id of the mod caller is interested in
- * @param userData user data to be returned with the result
- * @param url the url to request from
- **/
- virtual void requestDescription(QString gameName, int modID, QVariant userData);
-
- /**
- * @brief request a list of the files belonging to a mod
- *
- * @param modID id of the mod caller is interested in
- * @param userData user data to be returned with the result
- **/
- virtual void requestFiles(QString gameName, int modID, QVariant userData);
-
- /**
- * @brief request info about a single file of a mod
- *
- * @param modID id of the mod caller is interested in
- * @param fileID id of the file the caller is interested in
- * @param userData user data to be returned with the result
- **/
- virtual void requestFileInfo(QString gameName, int modID, int fileID, QVariant userData);
-
- /**
- * @brief request the download url of a file
- *
- * @param modID id of the mod caller is interested in
- * @param fileID id of the file the caller is interested in
- * @param userData user data to be returned with the result
- **/
- virtual void requestDownloadURL(QString gameName, int modID, int fileID, QVariant userData);
-
- /**
- * @brief requestToggleEndorsement
- * @param modID id of the mod caller is interested in
- * @param userData user data to be returned with the result
- */
- virtual void requestToggleEndorsement(QString gameName, int modID, QString modVersion, bool endorse, QVariant userData);
-
-public slots:
-
- void nxmDescriptionAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID);
- void nxmFilesAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID);
- void nxmFileInfoAvailable(QString gameName, int modID, int fileID, QVariant userData, QVariant resultData, int requestID);
- void nxmDownloadURLsAvailable(QString gameName, int modID, int fileID, QVariant userData, QVariant resultData, int requestID);
- void nxmEndorsementToggled(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID);
- void nxmRequestFailed(QString gameName, int modID, int fileID, QVariant userData, int requestID, const QString &errorMessage);
-
-private:
-
- NexusInterface *m_Interface;
- QString m_SubModule;
- std::set<int> m_RequestIDs;
-
-};
-
-
-/**
- * @brief Makes asynchronous requests to the nexus API
- *
- * This class can be used to make asynchronous requests to the Nexus API.
- * Currently, responses are sent to all receivers that have sent a request of the relevant type, so the
- * recipient has to filter the response by the id returned when making the request
- **/
-class NexusInterface : public QObject
-{
- Q_OBJECT
-
-public:
-
- ~NexusInterface();
-
- static NexusInterface *instance(PluginContainer *pluginContainer);
-
- /**
- * @return the access manager object used to connect to nexus
- **/
- NXMAccessManager *getAccessManager();
-
- /**
- * @brief cleanup this interface. this is destructive, afterwards it can't be used again
- */
- void cleanup();
-
- /**
- * @brief clear webcache and cookies associated with this access manager
- */
- void clearCache();
-
- /**
- * @brief request description for a mod
- *
- * @param modID id of the mod caller is interested in (assumed to be for the current game)
- * @param receiver the object to receive the result asynchronously via a signal (nxmDescriptionAvailable)
- * @param userData user data to be returned with the result
- * @return int an id to identify the request
- **/
- int requestDescription(QString gameName, int modID, QObject *receiver, QVariant userData, const QString &subModule)
- {
- return requestDescription(gameName, modID, receiver, userData, subModule, getGame(gameName));
- }
-
- /**
- * @brief request description for a mod
- *
- * @param modID id of the mod caller is interested in
- * @param receiver the object to receive the result asynchronously via a signal (nxmDescriptionAvailable)
- * @param userData user data to be returned with the result
- * @param game Game with which the mod is associated
- * @return int an id to identify the request
- **/
- int requestDescription(QString gameName, int modID, QObject *receiver, QVariant userData, const QString &subModule,
- MOBase::IPluginGame const *game);
-
- /**
- * @brief request nexus descriptions for multiple mods at once
- * @param modIDs a list of ids of mods the caller is interested in
- * @param receiver the object to receive the result asynchronously via a signal (nxmDescriptionAvailable)
- * @param userData user data to be returned with the result
- * @param game the game with which the mods are associated
- * @return int an id to identify the request
- */
- int requestUpdates(const std::vector<int> &modIDs, QObject *receiver, QVariant userData, QString gameName, const QString &subModule);
-
- /**
- * @brief request a list of the files belonging to a mod
- *
- * @param modID id of the mod caller is interested in (assumed to be for the current game)
- * @param receiver the object to receive the result asynchronously via a signal (nxmFilesAvailable)
- * @param userData user data to be returned with the result
- * @return int an id to identify the request
- **/
- int requestFiles(QString gameName, int modID, QObject *receiver, QVariant userData, const QString &subModule)
- {
- return requestFiles(gameName, modID, receiver, userData, subModule, getGame(gameName));
- }
-
-
- /**
- * @brief request a list of the files belonging to a mod
- *
- * @param modID id of the mod caller is interested in
- * @param receiver the object to receive the result asynchronously via a signal (nxmFilesAvailable)
- * @param userData user data to be returned with the result
- * @param game the game with which the mods are associated
- * @return int an id to identify the request
- **/
- int requestFiles(QString gameName, int modID, QObject *receiver, QVariant userData, const QString &subModule,
- MOBase::IPluginGame const *game);
-
- /**
- * @brief request info about a single file of a mod
- *
- * @param game name of the game short name to request the download from
- * @param modID id of the mod caller is interested in (assumed to be for the current game)
- * @param fileID id of the file the caller is interested in
- * @param receiver the object to receive the result asynchronously via a signal (nxmFilesAvailable)
- * @param userData user data to be returned with the result
- * @return int an id to identify the request
- **/
- int requestFileInfo(QString gameName, int modID, int fileID, QObject *receiver, QVariant userData, const QString &subModule);
-
- /**
- * @brief request the download url of a file
- *
- * @param modID id of the mod caller is interested in (assumed to be for the current game)
- * @param fileID id of the file the caller is interested in
- * @param receiver the object to receive the result asynchronously via a signal (nxmFilesAvailable)
- * @param userData user data to be returned with the result
- * @return int an id to identify the request
- **/
- int requestDownloadURL(QString gameName, int modID, int fileID, QObject *receiver, QVariant userData, const QString &subModule)
- {
- return requestDownloadURL(gameName, modID, fileID, receiver, userData, subModule, getGame(gameName));
- }
-
- /**
- * @brief request the download url of a file
- *
- * @param modID id of the mod caller is interested in
- * @param fileID id of the file the caller is interested in
- * @param receiver the object to receive the result asynchronously via a signal (nxmFilesAvailable)
- * @param userData user data to be returned with the result
- * @param game the game with which the mods are associated
- * @return int an id to identify the request
- **/
- int requestDownloadURL(QString gameName, int modID, int fileID, QObject *receiver, QVariant userData, const QString &subModule, MOBase::IPluginGame const *game);
-
- /**
- * @brief toggle endorsement state of the mod
- * @param modID id of the mod (assumed to be for the current game)
- * @param endorse true if the mod should be endorsed, false for un-endorse
- * @param receiver the object to receive the result asynchronously via a signal (nxmFilesAvailable)
- * @param userData user data to be returned with the result
- * @return int an id to identify the request
- */
- int requestToggleEndorsement(QString gameName, int modID, QString modVersion, bool endorse, QObject *receiver, QVariant userData, const QString &subModule)
- {
- return requestToggleEndorsement(gameName, modID, modVersion, endorse, receiver, userData, subModule, getGame(gameName));
- }
-
- /**
- * @brief toggle endorsement state of the mod
- * @param modID id of the mod
- * @param endorse true if the mod should be endorsed, false for un-endorse
- * @param receiver the object to receive the result asynchronously via a signal (nxmFilesAvailable)
- * @param userData user data to be returned with the result
- * @param game the game with which the mods are associated
- * @return int an id to identify the request
- */
- int requestToggleEndorsement(QString gameName, int modID, QString modVersion, bool endorse, QObject *receiver, QVariant userData, const QString &subModule,
- MOBase::IPluginGame const *game);
-
- /**
- * @param directory the directory to store cache files
- **/
- void setCacheDirectory(const QString &directory);
-
- /**
- * MO has to send a "Nexus Client Vx.y.z" as part of the user agent to be allowed to use the API
- * @param nmmVersion the version of nmm to impersonate
- **/
- void setNMMVersion(const QString &nmmVersion);
-
- /**
- * @brief called when the log-in completes. This was, requests waiting for the log-in can be run
- */
- void loginCompleted();
-
- std::vector<std::pair<QString, QString>> getGameChoices(const MOBase::IPluginGame *game);
-
-public:
-
- /**
- * @brief guess the mod id from a filename as delivered by Nexus
- * @param fileName name of the file
- * @return the guessed mod id
- * @note this currently doesn't fit well with the remaining interface but this is the best place for the function
- */
- static void interpretNexusFileName(const QString &fileName, QString &modName, int &modID, bool query);
-
- /**
- * @brief get the currently managed game
- */
- MOBase::IPluginGame const *managedGame() const;
-
- /**
- * @brief see if the passed URL is related to the current game
- *
- * Arguably, this should optionally take a gameplugin pointer
- */
- bool isURLGameRelated(QUrl const &url) const;
-
- /**
- * @brief Get the nexus page for the current game
- *
- * Arguably, this should optionally take a gameplugin pointer
- */
- QString getGameURL(QString gameName) const;
-
- /**
- * @brief Get the URL for the mod web page
- * @param modID
- */
- QString getModURL(int modID, QString gameName) const;
-
- /**
- * @brief Checks if the specified URL might correspond to a nexus mod
- * @param modID
- * @param url
- * @return
- */
- bool isModURL(int modID, QString const &url) const;
-
- void setPluginContainer(PluginContainer *pluginContainer);
-
-signals:
-
- void requestNXMDownload(const QString &url);
-
- void needLogin();
-
- void nxmDescriptionAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID);
- void nxmUpdatesAvailable(const std::vector<int> &modIDs, QVariant userData, QVariant resultData, int requestID);
- void nxmFilesAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID);
- void nxmFileInfoAvailable(QString gameName, int modID, int fileID, QVariant userData, QVariant resultData, int requestID);
- void nxmDownloadURLsAvailable(QString gameName, int modID, int fileID, QVariant userData, QVariant resultData, int requestID);
- void nxmEndorsementToggled(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID);
- void nxmRequestFailed(QString gameName, int modID, int fileID, QVariant userData, int requestID, const QString &errorString);
-
-private slots:
-
- void requestFinished();
- void requestError(QNetworkReply::NetworkError error);
- void requestTimeout();
-
- void downloadRequestedNXM(const QString &url);
-
- void fakeFiles();
-
-private:
-
- struct NXMRequestInfo {
- int m_ModID;
- QString m_ModVersion;
- std::vector<int> m_ModIDList;
- int m_FileID;
- QNetworkReply *m_Reply;
- enum Type {
- TYPE_DESCRIPTION,
- TYPE_FILES,
- TYPE_FILEINFO,
- TYPE_DOWNLOADURL,
- TYPE_TOGGLEENDORSEMENT,
- TYPE_GETUPDATES
- } m_Type;
- QVariant m_UserData;
- QTimer *m_Timeout;
- QString m_URL;
- QString m_SubModule;
- QString m_GameName;
- int m_NexusGameID;
- bool m_Reroute;
- int m_ID;
- int m_Endorse;
-
- NXMRequestInfo(int modID, Type type, QVariant userData, const QString &subModule, MOBase::IPluginGame const *game);
- NXMRequestInfo(int modID, QString modVersion, Type type, QVariant userData, const QString &subModule, MOBase::IPluginGame const *game);
- NXMRequestInfo(std::vector<int> modIDList, Type type, QVariant userData, const QString &subModule, MOBase::IPluginGame const *game);
- NXMRequestInfo(int modID, int fileID, Type type, QVariant userData, const QString &subModule, MOBase::IPluginGame const *game);
-
- private:
- static QAtomicInt s_NextID;
- };
-
- static const int MAX_ACTIVE_DOWNLOADS = 2;
-
-private:
-
- NexusInterface(PluginContainer *pluginContainer);
- void nextRequest();
- void requestFinished(std::list<NXMRequestInfo>::iterator iter);
- bool requiresLogin(const NXMRequestInfo &info);
- MOBase::IPluginGame *getGame(QString gameName) const;
- QString getOldModsURL(QString gameName) const;
-
-private:
-
- QNetworkDiskCache *m_DiskCache;
-
- NXMAccessManager *m_AccessManager;
-
- std::list<NXMRequestInfo> m_ActiveRequest;
- QQueue<NXMRequestInfo> m_RequestQueue;
-
- MOBase::VersionInfo m_MOVersion;
- QString m_NMMVersion;
-
- PluginContainer *m_PluginContainer;
-
-};
-
-#endif // NEXUSINTERFACE_H
+/*
+Copyright (C) 2012 Sebastian Herbord. All rights reserved.
+
+This file is part of Mod Organizer.
+
+Mod Organizer is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+Mod Organizer is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Mod Organizer. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef NEXUSINTERFACE_H
+#define NEXUSINTERFACE_H
+
+#include <utility.h>
+#include <versioninfo.h>
+#include <imodrepositorybridge.h>
+#include <plugincontainer.h>
+
+#include <QNetworkReply>
+#include <QNetworkDiskCache>
+#include <QQueue>
+#include <QVariant>
+#include <QTimer>
+
+#include <list>
+#include <set>
+
+namespace MOBase { class IPluginGame; }
+
+class NexusInterface;
+class NXMAccessManager;
+
+/**
+ * @brief convenience class to make nxm requests easier
+ * usually, all objects that started a nxm request will be signaled if one finished.
+ * Therefore, the objects need to store the id of the requests they started and then filter
+ * the result.
+ * NexusBridge does this automatically. Users connect to the signals of NexusBridge they intend
+ * to handle and only receive the signals the caused
+ **/
+class NexusBridge : public MOBase::IModRepositoryBridge
+{
+
+ Q_OBJECT
+
+public:
+
+ NexusBridge(PluginContainer *pluginContainer, const QString &subModule = "");
+
+ /**
+ * @brief request description for a mod
+ *
+ * @param modID id of the mod caller is interested in
+ * @param userData user data to be returned with the result
+ * @param url the url to request from
+ **/
+ virtual void requestDescription(QString gameName, int modID, QVariant userData);
+
+ /**
+ * @brief request a list of the files belonging to a mod
+ *
+ * @param modID id of the mod caller is interested in
+ * @param userData user data to be returned with the result
+ **/
+ virtual void requestFiles(QString gameName, int modID, QVariant userData);
+
+ /**
+ * @brief request info about a single file of a mod
+ *
+ * @param modID id of the mod caller is interested in
+ * @param fileID id of the file the caller is interested in
+ * @param userData user data to be returned with the result
+ **/
+ virtual void requestFileInfo(QString gameName, int modID, int fileID, QVariant userData);
+
+ /**
+ * @brief request the download url of a file
+ *
+ * @param modID id of the mod caller is interested in
+ * @param fileID id of the file the caller is interested in
+ * @param userData user data to be returned with the result
+ **/
+ virtual void requestDownloadURL(QString gameName, int modID, int fileID, QVariant userData);
+
+ /**
+ * @brief requestToggleEndorsement
+ * @param modID id of the mod caller is interested in
+ * @param userData user data to be returned with the result
+ */
+ virtual void requestToggleEndorsement(QString gameName, int modID, QString modVersion, bool endorse, QVariant userData);
+
+public slots:
+
+ void nxmDescriptionAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID);
+ void nxmFilesAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID);
+ void nxmFileInfoAvailable(QString gameName, int modID, int fileID, QVariant userData, QVariant resultData, int requestID);
+ void nxmDownloadURLsAvailable(QString gameName, int modID, int fileID, QVariant userData, QVariant resultData, int requestID);
+ void nxmEndorsementToggled(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID);
+ void nxmRequestFailed(QString gameName, int modID, int fileID, QVariant userData, int requestID, QNetworkReply::NetworkError error, const QString &errorMessage);
+
+private:
+
+ NexusInterface *m_Interface;
+ QString m_SubModule;
+ std::set<int> m_RequestIDs;
+
+};
+
+
+/**
+ * @brief Makes asynchronous requests to the nexus API
+ *
+ * This class can be used to make asynchronous requests to the Nexus API.
+ * Currently, responses are sent to all receivers that have sent a request of the relevant type, so the
+ * recipient has to filter the response by the id returned when making the request
+ **/
+class NexusInterface : public QObject
+{
+ Q_OBJECT
+
+public:
+
+ ~NexusInterface();
+
+ static NexusInterface *instance(PluginContainer *pluginContainer);
+
+ /**
+ * @return the access manager object used to connect to nexus
+ **/
+ NXMAccessManager *getAccessManager();
+
+ /**
+ * @brief cleanup this interface. this is destructive, afterwards it can't be used again
+ */
+ void cleanup();
+
+ /**
+ * @brief clear webcache and cookies associated with this access manager
+ */
+ void clearCache();
+
+ /**
+ * @brief request description for a mod
+ *
+ * @param modID id of the mod caller is interested in (assumed to be for the current game)
+ * @param receiver the object to receive the result asynchronously via a signal (nxmDescriptionAvailable)
+ * @param userData user data to be returned with the result
+ * @return int an id to identify the request
+ **/
+ int requestDescription(QString gameName, int modID, QObject *receiver, QVariant userData, const QString &subModule)
+ {
+ return requestDescription(gameName, modID, receiver, userData, subModule, getGame(gameName));
+ }
+
+ /**
+ * @brief request description for a mod
+ *
+ * @param modID id of the mod caller is interested in
+ * @param receiver the object to receive the result asynchronously via a signal (nxmDescriptionAvailable)
+ * @param userData user data to be returned with the result
+ * @param game Game with which the mod is associated
+ * @return int an id to identify the request
+ **/
+ int requestDescription(QString gameName, int modID, QObject *receiver, QVariant userData, const QString &subModule,
+ MOBase::IPluginGame const *game);
+
+ /**
+ * @brief request nexus descriptions for multiple mods at once
+ * @param modIDs a list of ids of mods the caller is interested in
+ * @param receiver the object to receive the result asynchronously via a signal (nxmDescriptionAvailable)
+ * @param userData user data to be returned with the result
+ * @param game the game with which the mods are associated
+ * @return int an id to identify the request
+ */
+ int requestUpdates(const int &modID, QObject *receiver, QVariant userData, QString gameName, const QString &subModule);
+
+ /**
+ * @brief request a list of the files belonging to a mod
+ *
+ * @param modID id of the mod caller is interested in (assumed to be for the current game)
+ * @param receiver the object to receive the result asynchronously via a signal (nxmFilesAvailable)
+ * @param userData user data to be returned with the result
+ * @return int an id to identify the request
+ **/
+ int requestFiles(QString gameName, int modID, QObject *receiver, QVariant userData, const QString &subModule)
+ {
+ return requestFiles(gameName, modID, receiver, userData, subModule, getGame(gameName));
+ }
+
+
+ /**
+ * @brief request a list of the files belonging to a mod
+ *
+ * @param modID id of the mod caller is interested in
+ * @param receiver the object to receive the result asynchronously via a signal (nxmFilesAvailable)
+ * @param userData user data to be returned with the result
+ * @param game the game with which the mods are associated
+ * @return int an id to identify the request
+ **/
+ int requestFiles(QString gameName, int modID, QObject *receiver, QVariant userData, const QString &subModule,
+ MOBase::IPluginGame const *game);
+
+ /**
+ * @brief request info about a single file of a mod
+ *
+ * @param game name of the game short name to request the download from
+ * @param modID id of the mod caller is interested in (assumed to be for the current game)
+ * @param fileID id of the file the caller is interested in
+ * @param receiver the object to receive the result asynchronously via a signal (nxmFilesAvailable)
+ * @param userData user data to be returned with the result
+ * @return int an id to identify the request
+ **/
+ int requestFileInfo(QString gameName, int modID, int fileID, QObject *receiver, QVariant userData, const QString &subModule);
+
+ /**
+ * @brief request the download url of a file
+ *
+ * @param modID id of the mod caller is interested in (assumed to be for the current game)
+ * @param fileID id of the file the caller is interested in
+ * @param receiver the object to receive the result asynchronously via a signal (nxmFilesAvailable)
+ * @param userData user data to be returned with the result
+ * @return int an id to identify the request
+ **/
+ int requestDownloadURL(QString gameName, int modID, int fileID, QObject *receiver, QVariant userData, const QString &subModule)
+ {
+ return requestDownloadURL(gameName, modID, fileID, receiver, userData, subModule, getGame(gameName));
+ }
+
+ /**
+ * @brief request the download url of a file
+ *
+ * @param modID id of the mod caller is interested in
+ * @param fileID id of the file the caller is interested in
+ * @param receiver the object to receive the result asynchronously via a signal (nxmFilesAvailable)
+ * @param userData user data to be returned with the result
+ * @param game the game with which the mods are associated
+ * @return int an id to identify the request
+ **/
+ int requestDownloadURL(QString gameName, int modID, int fileID, QObject *receiver, QVariant userData, const QString &subModule, MOBase::IPluginGame const *game);
+
+ /**
+ * @brief toggle endorsement state of the mod
+ * @param modID id of the mod (assumed to be for the current game)
+ * @param endorse true if the mod should be endorsed, false for un-endorse
+ * @param receiver the object to receive the result asynchronously via a signal (nxmFilesAvailable)
+ * @param userData user data to be returned with the result
+ * @return int an id to identify the request
+ */
+ int requestToggleEndorsement(QString gameName, int modID, QString modVersion, bool endorse, QObject *receiver, QVariant userData, const QString &subModule)
+ {
+ return requestToggleEndorsement(gameName, modID, modVersion, endorse, receiver, userData, subModule, getGame(gameName));
+ }
+
+ /**
+ * @brief toggle endorsement state of the mod
+ * @param modID id of the mod
+ * @param endorse true if the mod should be endorsed, false for un-endorse
+ * @param receiver the object to receive the result asynchronously via a signal (nxmFilesAvailable)
+ * @param userData user data to be returned with the result
+ * @param game the game with which the mods are associated
+ * @return int an id to identify the request
+ */
+ int requestToggleEndorsement(QString gameName, int modID, QString modVersion, bool endorse, QObject *receiver, QVariant userData, const QString &subModule,
+ MOBase::IPluginGame const *game);
+
+ /**
+ * @param directory the directory to store cache files
+ **/
+ void setCacheDirectory(const QString &directory);
+
+ /**
+ * MO has to send a "Nexus Client Vx.y.z" as part of the user agent to be allowed to use the API
+ * @param nmmVersion the version of nmm to impersonate
+ **/
+ void setNMMVersion(const QString &nmmVersion);
+
+ /**
+ * @brief called when the log-in completes. This was, requests waiting for the log-in can be run
+ */
+ void loginCompleted();
+
+ std::vector<std::pair<QString, QString>> getGameChoices(const MOBase::IPluginGame *game);
+
+public:
+
+ /**
+ * @brief guess the mod id from a filename as delivered by Nexus
+ * @param fileName name of the file
+ * @return the guessed mod id
+ * @note this currently doesn't fit well with the remaining interface but this is the best place for the function
+ */
+ static void interpretNexusFileName(const QString &fileName, QString &modName, int &modID, bool query);
+
+ /**
+ * @brief get the currently managed game
+ */
+ MOBase::IPluginGame const *managedGame() const;
+
+ /**
+ * @brief see if the passed URL is related to the current game
+ *
+ * Arguably, this should optionally take a gameplugin pointer
+ */
+ bool isURLGameRelated(QUrl const &url) const;
+
+ /**
+ * @brief Get the nexus page for the current game
+ *
+ * Arguably, this should optionally take a gameplugin pointer
+ */
+ QString getGameURL(QString gameName) const;
+
+ /**
+ * @brief Get the URL for the mod web page
+ * @param modID
+ */
+ QString getModURL(int modID, QString gameName) const;
+
+ /**
+ * @brief Checks if the specified URL might correspond to a nexus mod
+ * @param modID
+ * @param url
+ * @return
+ */
+ bool isModURL(int modID, QString const &url) const;
+
+ void setPluginContainer(PluginContainer *pluginContainer);
+
+signals:
+
+ void requestNXMDownload(const QString &url);
+
+ void needLogin();
+
+ void nxmDescriptionAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID);
+ void nxmUpdatesAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID);
+ void nxmFilesAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID);
+ void nxmFileInfoAvailable(QString gameName, int modID, int fileID, QVariant userData, QVariant resultData, int requestID);
+ void nxmDownloadURLsAvailable(QString gameName, int modID, int fileID, QVariant userData, QVariant resultData, int requestID);
+ void nxmEndorsementToggled(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID);
+ void nxmRequestFailed(QString gameName, int modID, int fileID, QVariant userData, int requestID, QNetworkReply::NetworkError error, const QString &errorString);
+
+private slots:
+
+ void requestFinished();
+ void requestError(QNetworkReply::NetworkError error);
+ void requestTimeout();
+
+ void downloadRequestedNXM(const QString &url);
+
+ void fakeFiles();
+
+private:
+
+ struct NXMRequestInfo {
+ int m_ModID;
+ QString m_ModVersion;
+ std::vector<int> m_ModIDList;
+ int m_FileID;
+ QNetworkReply *m_Reply;
+ enum Type {
+ TYPE_DESCRIPTION,
+ TYPE_FILES,
+ TYPE_FILEINFO,
+ TYPE_DOWNLOADURL,
+ TYPE_TOGGLEENDORSEMENT,
+ TYPE_GETUPDATES
+ } m_Type;
+ QVariant m_UserData;
+ QTimer *m_Timeout;
+ QString m_URL;
+ QString m_SubModule;
+ QString m_GameName;
+ int m_NexusGameID;
+ bool m_Reroute;
+ int m_ID;
+ int m_Endorse;
+
+ NXMRequestInfo(int modID, Type type, QVariant userData, const QString &subModule, MOBase::IPluginGame const *game);
+ NXMRequestInfo(int modID, QString modVersion, Type type, QVariant userData, const QString &subModule, MOBase::IPluginGame const *game);
+ NXMRequestInfo(int modID, int fileID, Type type, QVariant userData, const QString &subModule, MOBase::IPluginGame const *game);
+
+ private:
+ static QAtomicInt s_NextID;
+ };
+
+ static const int MAX_ACTIVE_DOWNLOADS = 2;
+
+private:
+
+ NexusInterface(PluginContainer *pluginContainer);
+ void nextRequest();
+ void requestFinished(std::list<NXMRequestInfo>::iterator iter);
+ bool requiresLogin(const NXMRequestInfo &info);
+ MOBase::IPluginGame *getGame(QString gameName) const;
+ QString getOldModsURL(QString gameName) const;
+
+private:
+
+ QNetworkDiskCache *m_DiskCache;
+
+ NXMAccessManager *m_AccessManager;
+
+ std::list<NXMRequestInfo> m_ActiveRequest;
+ QQueue<NXMRequestInfo> m_RequestQueue;
+
+ MOBase::VersionInfo m_MOVersion;
+ QString m_NMMVersion;
+
+ PluginContainer *m_PluginContainer;
+
+};
+
+#endif // NEXUSINTERFACE_H
diff --git a/src/organizer_en.ts b/src/organizer_en.ts
index bcdbd069..0d63c34c 100644
--- a/src/organizer_en.ts
+++ b/src/organizer_en.ts
@@ -571,301 +571,301 @@ p, li { white-space: pre-wrap; }
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="389"/>
+ <location filename="downloadmanager.cpp" line="388"/>
<source>Memory allocation error (in refreshing directory).</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="479"/>
+ <location filename="downloadmanager.cpp" line="478"/>
<source>failed to download %1: could not open output file: %2</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="502"/>
+ <location filename="downloadmanager.cpp" line="501"/>
<source>Download again?</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="502"/>
+ <location filename="downloadmanager.cpp" line="501"/>
<source>A file with the same name &quot;%1&quot; has already been downloaded. Do you want to download it again? The new file will receive a different name.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="546"/>
+ <location filename="downloadmanager.cpp" line="545"/>
<source>Wrong Game</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="546"/>
+ <location filename="downloadmanager.cpp" line="545"/>
<source>The download link is for a mod for &quot;%1&quot; but this instance of MO has been set up for &quot;%2&quot;.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="554"/>
- <location filename="downloadmanager.cpp" line="565"/>
+ <location filename="downloadmanager.cpp" line="553"/>
+ <location filename="downloadmanager.cpp" line="564"/>
<source>Already Started</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="554"/>
+ <location filename="downloadmanager.cpp" line="553"/>
<source>A download for this mod file has already been queued.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="565"/>
+ <location filename="downloadmanager.cpp" line="564"/>
<source>There is already a download started for this file (mod: %1, file: %2).</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="588"/>
- <location filename="downloadmanager.cpp" line="721"/>
+ <location filename="downloadmanager.cpp" line="587"/>
+ <location filename="downloadmanager.cpp" line="720"/>
<source>remove: invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="607"/>
+ <location filename="downloadmanager.cpp" line="606"/>
<source>failed to delete %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="614"/>
+ <location filename="downloadmanager.cpp" line="613"/>
<source>failed to delete meta file for %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="674"/>
+ <location filename="downloadmanager.cpp" line="673"/>
<source>restore: invalid download index: %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="743"/>
+ <location filename="downloadmanager.cpp" line="742"/>
<source>cancel: invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="756"/>
+ <location filename="downloadmanager.cpp" line="755"/>
<source>pause: invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="776"/>
+ <location filename="downloadmanager.cpp" line="775"/>
<source>resume: invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="787"/>
+ <location filename="downloadmanager.cpp" line="786"/>
<source>resume (int): invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="811"/>
+ <location filename="downloadmanager.cpp" line="810"/>
<source>No known download urls. Sorry, this download can&apos;t be resumed.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="852"/>
+ <location filename="downloadmanager.cpp" line="851"/>
<source>query: invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="874"/>
+ <location filename="downloadmanager.cpp" line="873"/>
<source>Please enter the nexus mod id</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="874"/>
+ <location filename="downloadmanager.cpp" line="873"/>
<source>Mod ID:</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="884"/>
+ <location filename="downloadmanager.cpp" line="883"/>
<source>Please select the source game code for %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="903"/>
+ <location filename="downloadmanager.cpp" line="902"/>
<source>VisitNexus: invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="924"/>
+ <location filename="downloadmanager.cpp" line="923"/>
<source>Nexus ID for this Mod is unknown</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="931"/>
+ <location filename="downloadmanager.cpp" line="930"/>
<source>OpenFile: invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="948"/>
+ <location filename="downloadmanager.cpp" line="947"/>
<source>OpenFileInDownloadsFolder: invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="984"/>
+ <location filename="downloadmanager.cpp" line="983"/>
<source>get pending: invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="993"/>
+ <location filename="downloadmanager.cpp" line="992"/>
<source>get path: invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1002"/>
+ <location filename="downloadmanager.cpp" line="1001"/>
<source>Main</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1003"/>
+ <location filename="downloadmanager.cpp" line="1002"/>
<source>Update</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1004"/>
+ <location filename="downloadmanager.cpp" line="1003"/>
<source>Optional</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1005"/>
+ <location filename="downloadmanager.cpp" line="1004"/>
<source>Old</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1006"/>
+ <location filename="downloadmanager.cpp" line="1005"/>
<source>Misc</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1007"/>
+ <location filename="downloadmanager.cpp" line="1006"/>
<source>Unknown</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1014"/>
+ <location filename="downloadmanager.cpp" line="1013"/>
<source>display name: invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1034"/>
+ <location filename="downloadmanager.cpp" line="1033"/>
<source>file name: invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1043"/>
+ <location filename="downloadmanager.cpp" line="1042"/>
<source>file time: invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1057"/>
+ <location filename="downloadmanager.cpp" line="1056"/>
<source>file size: invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1067"/>
+ <location filename="downloadmanager.cpp" line="1066"/>
<source>progress: invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1077"/>
+ <location filename="downloadmanager.cpp" line="1076"/>
<source>state: invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1087"/>
+ <location filename="downloadmanager.cpp" line="1086"/>
<source>infocomplete: invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1102"/>
- <location filename="downloadmanager.cpp" line="1110"/>
+ <location filename="downloadmanager.cpp" line="1101"/>
+ <location filename="downloadmanager.cpp" line="1109"/>
<source>mod id: invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1118"/>
+ <location filename="downloadmanager.cpp" line="1117"/>
<source>ishidden: invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1127"/>
+ <location filename="downloadmanager.cpp" line="1126"/>
<source>file info: invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1137"/>
+ <location filename="downloadmanager.cpp" line="1136"/>
<source>mark installed: invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1182"/>
+ <location filename="downloadmanager.cpp" line="1181"/>
<source>mark uninstalled: invalid download index %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1355"/>
+ <location filename="downloadmanager.cpp" line="1354"/>
<source>Memory allocation error (in processing progress event).</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1365"/>
+ <location filename="downloadmanager.cpp" line="1364"/>
<source>Memory allocation error (in processing downloaded data).</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1491"/>
+ <location filename="downloadmanager.cpp" line="1480"/>
<source>Information updated</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1493"/>
- <location filename="downloadmanager.cpp" line="1507"/>
+ <location filename="downloadmanager.cpp" line="1482"/>
+ <location filename="downloadmanager.cpp" line="1496"/>
<source>No matching file found on Nexus! Maybe this file is no longer available or it was renamed?</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1495"/>
+ <location filename="downloadmanager.cpp" line="1484"/>
<source>No file on Nexus matches the selected file by name. Please manually choose the correct one.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1613"/>
+ <location filename="downloadmanager.cpp" line="1602"/>
<source>No download server available. Please try again later.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1656"/>
+ <location filename="downloadmanager.cpp" line="1645"/>
<source>Failed to request file info from nexus: %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1683"/>
+ <location filename="downloadmanager.cpp" line="1672"/>
<source>Warning: Content type is: %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1688"/>
+ <location filename="downloadmanager.cpp" line="1677"/>
<source>Download header content length: %1 downloaded file size: %2</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1690"/>
+ <location filename="downloadmanager.cpp" line="1679"/>
<source>Download failed: %1 (%2)</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1712"/>
+ <location filename="downloadmanager.cpp" line="1701"/>
<source>We were unable to download the file due to errors after four retries. There may be an issue with the Nexus servers.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1795"/>
+ <location filename="downloadmanager.cpp" line="1784"/>
<source>failed to re-open %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="downloadmanager.cpp" line="1836"/>
+ <location filename="downloadmanager.cpp" line="1825"/>
<source>Unable to write download to drive (return %1).
Check the drive&apos;s available storage.
@@ -2431,7 +2431,7 @@ Please enter a name:</source>
</message>
<message>
<location filename="mainwindow.cpp" line="3617"/>
- <location filename="mainwindow.cpp" line="5682"/>
+ <location filename="mainwindow.cpp" line="5731"/>
<source>Are you sure?</source>
<translation type="unfinished"></translation>
</message>
@@ -2768,13 +2768,13 @@ You can also use online editors and converters instead.</source>
</message>
<message>
<location filename="mainwindow.cpp" line="4505"/>
- <location filename="mainwindow.cpp" line="5793"/>
+ <location filename="mainwindow.cpp" line="5842"/>
<source>Enable selected</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="mainwindow.cpp" line="4506"/>
- <location filename="mainwindow.cpp" line="5794"/>
+ <location filename="mainwindow.cpp" line="5843"/>
<source>Disable selected</source>
<translation type="unfinished"></translation>
</message>
@@ -2835,13 +2835,13 @@ You can also use online editors and converters instead.</source>
</message>
<message>
<location filename="mainwindow.cpp" line="4567"/>
- <location filename="mainwindow.cpp" line="5841"/>
+ <location filename="mainwindow.cpp" line="5890"/>
<source>Exception: </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="mainwindow.cpp" line="4569"/>
- <location filename="mainwindow.cpp" line="5843"/>
+ <location filename="mainwindow.cpp" line="5892"/>
<source>Unknown exception</source>
<translation type="unfinished"></translation>
</message>
@@ -2979,7 +2979,7 @@ Click OK to restart MO now.</source>
</message>
<message>
<location filename="mainwindow.cpp" line="5135"/>
- <location filename="mainwindow.cpp" line="6455"/>
+ <location filename="mainwindow.cpp" line="6504"/>
<source>Set Priority</source>
<translation type="unfinished"></translation>
</message>
@@ -3044,206 +3044,206 @@ Click OK to restart MO now.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5488"/>
+ <location filename="mainwindow.cpp" line="5537"/>
<source>Thank you!</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5488"/>
+ <location filename="mainwindow.cpp" line="5537"/>
<source>Thank you for your endorsement!</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5490"/>
+ <location filename="mainwindow.cpp" line="5539"/>
<source>Okay.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5490"/>
+ <location filename="mainwindow.cpp" line="5539"/>
<source>This mod will not be endorsed and will no longer ask you to endorse.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5526"/>
+ <location filename="mainwindow.cpp" line="5575"/>
<source>Request to Nexus failed: %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5541"/>
- <location filename="mainwindow.cpp" line="5603"/>
+ <location filename="mainwindow.cpp" line="5590"/>
+ <location filename="mainwindow.cpp" line="5652"/>
<source>failed to read %1: %2</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5553"/>
- <location filename="mainwindow.cpp" line="6031"/>
+ <location filename="mainwindow.cpp" line="5602"/>
+ <location filename="mainwindow.cpp" line="6080"/>
<source>Error</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5553"/>
+ <location filename="mainwindow.cpp" line="5602"/>
<source>failed to extract %1 (errorcode %2)</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5585"/>
+ <location filename="mainwindow.cpp" line="5634"/>
<source>Extract BSA</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5614"/>
+ <location filename="mainwindow.cpp" line="5663"/>
<source>This archive contains invalid hashes. Some files may be broken.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5660"/>
+ <location filename="mainwindow.cpp" line="5709"/>
<source>Extract...</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5683"/>
+ <location filename="mainwindow.cpp" line="5732"/>
<source>This will restart MO, continue?</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5730"/>
+ <location filename="mainwindow.cpp" line="5779"/>
<source>Edit Categories...</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5731"/>
+ <location filename="mainwindow.cpp" line="5780"/>
<source>Deselect filter</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5782"/>
+ <location filename="mainwindow.cpp" line="5831"/>
<source>Remove</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5798"/>
+ <location filename="mainwindow.cpp" line="5847"/>
<source>Enable all</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5799"/>
+ <location filename="mainwindow.cpp" line="5848"/>
<source>Disable all</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5820"/>
+ <location filename="mainwindow.cpp" line="5869"/>
<source>Unlock load order</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5823"/>
+ <location filename="mainwindow.cpp" line="5872"/>
<source>Lock load order</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5827"/>
+ <location filename="mainwindow.cpp" line="5876"/>
<source>Open Origin in Explorer</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5834"/>
+ <location filename="mainwindow.cpp" line="5883"/>
<source>Open Origin Info...</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5977"/>
+ <location filename="mainwindow.cpp" line="6026"/>
<source>depends on missing &quot;%1&quot;</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="5981"/>
+ <location filename="mainwindow.cpp" line="6030"/>
<source>incompatible with &quot;%1&quot;</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="6007"/>
+ <location filename="mainwindow.cpp" line="6056"/>
<source>Please wait while LOOT is running</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="6104"/>
+ <location filename="mainwindow.cpp" line="6153"/>
<source>loot failed. Exit code was: %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="6126"/>
+ <location filename="mainwindow.cpp" line="6175"/>
<source>failed to start loot</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="6129"/>
+ <location filename="mainwindow.cpp" line="6178"/>
<source>failed to run loot: %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="6133"/>
+ <location filename="mainwindow.cpp" line="6182"/>
<source>Errors occured</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="6180"/>
+ <location filename="mainwindow.cpp" line="6229"/>
<source>Backup of load order created</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="6190"/>
+ <location filename="mainwindow.cpp" line="6239"/>
<source>Choose backup to restore</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="6203"/>
+ <location filename="mainwindow.cpp" line="6252"/>
<source>No Backups</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="6203"/>
+ <location filename="mainwindow.cpp" line="6252"/>
<source>There are no backups to restore</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="6224"/>
- <location filename="mainwindow.cpp" line="6246"/>
+ <location filename="mainwindow.cpp" line="6273"/>
+ <location filename="mainwindow.cpp" line="6295"/>
<source>Restore failed</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="6225"/>
- <location filename="mainwindow.cpp" line="6247"/>
+ <location filename="mainwindow.cpp" line="6274"/>
+ <location filename="mainwindow.cpp" line="6296"/>
<source>Failed to restore the backup. Errorcode: %1</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="6236"/>
+ <location filename="mainwindow.cpp" line="6285"/>
<source>Backup of modlist created</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="6342"/>
+ <location filename="mainwindow.cpp" line="6391"/>
<source>A file with the same name has already been downloaded. What would you like to do?</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="6344"/>
+ <location filename="mainwindow.cpp" line="6393"/>
<source>Overwrite</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="6345"/>
+ <location filename="mainwindow.cpp" line="6394"/>
<source>Rename new file</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="6346"/>
+ <location filename="mainwindow.cpp" line="6395"/>
<source>Ignore file</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="mainwindow.cpp" line="6455"/>
+ <location filename="mainwindow.cpp" line="6504"/>
<source>Set the priority of the selected mods</source>
<translation type="unfinished"></translation>
</message>
@@ -3768,7 +3768,7 @@ p, li { white-space: pre-wrap; }
</message>
<message>
<location filename="modinfodialog.cpp" line="854"/>
- <source>Misc</source>
+ <source>Deleted</source>
<translation type="unfinished"></translation>
</message>
<message>
@@ -3990,12 +3990,12 @@ p, li { white-space: pre-wrap; }
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="modinforegular.cpp" line="577"/>
+ <location filename="modinforegular.cpp" line="583"/>
<source>%1 contains no esp/esm/esl and no asset (textures, meshes, interface, ...) directory</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="modinforegular.cpp" line="581"/>
+ <location filename="modinforegular.cpp" line="587"/>
<source>Categories: &lt;br&gt;</source>
<translation type="unfinished"></translation>
</message>
@@ -4350,7 +4350,7 @@ p, li { white-space: pre-wrap; }
</message>
<message>
<location filename="nxmaccessmanager.cpp" line="218"/>
- <source>timeout</source>
+ <source>There was a timeout during the request</source>
<translation type="unfinished"></translation>
</message>
<message>
@@ -4370,17 +4370,17 @@ p, li { white-space: pre-wrap; }
<context>
<name>NexusInterface</name>
<message>
- <location filename="nexusinterface.cpp" line="211"/>
+ <location filename="nexusinterface.cpp" line="212"/>
<source>Failed to guess mod id for &quot;%1&quot;, please pick the correct one</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="nexusinterface.cpp" line="554"/>
+ <location filename="nexusinterface.cpp" line="553"/>
<source>empty response</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="nexusinterface.cpp" line="583"/>
+ <location filename="nexusinterface.cpp" line="582"/>
<source>invalid response</source>
<translation type="unfinished"></translation>
</message>
@@ -5617,7 +5617,7 @@ If the folder was still in use, restart MO and try again.</source>
</message>
<message>
<location filename="main.cpp" line="685"/>
- <location filename="settings.cpp" line="1135"/>
+ <location filename="settings.cpp" line="1143"/>
<source>Mod Organizer</source>
<translation type="unfinished"></translation>
</message>
@@ -5694,12 +5694,12 @@ If the folder was still in use, restart MO and try again.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settings.cpp" line="1142"/>
+ <location filename="settings.cpp" line="1150"/>
<source>Script Extender</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settings.cpp" line="1149"/>
+ <location filename="settings.cpp" line="1157"/>
<source>Proxy DLL</source>
<translation type="unfinished"></translation>
</message>
@@ -5921,28 +5921,28 @@ Select Show Details option to see the full change-log.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settings.cpp" line="679"/>
- <location filename="settings.cpp" line="914"/>
+ <location filename="settings.cpp" line="686"/>
+ <location filename="settings.cpp" line="922"/>
<source>Error</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settings.cpp" line="680"/>
+ <location filename="settings.cpp" line="687"/>
<source>Failed to retrieve a Nexus API key! Please try again.A browser window should open asking you to authorize.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settings.cpp" line="915"/>
+ <location filename="settings.cpp" line="923"/>
<source>Failed to create &quot;%1&quot;, you may not have the necessary permission. path remains unchanged.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settings.cpp" line="1188"/>
+ <location filename="settings.cpp" line="1196"/>
<source>Restart Mod Organizer?</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settings.cpp" line="1189"/>
+ <location filename="settings.cpp" line="1197"/>
<source>In order to reset the window geometries, MO must be restarted.
Restart it now?</source>
<translation type="unfinished"></translation>
@@ -6215,137 +6215,147 @@ p, li { white-space: pre-wrap; }
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="487"/>
- <source>Remove cache and cookies. Forces a new login.</source>
+ <location filename="settingsdialog.ui" line="500"/>
+ <source>Clear the stored Nexus API key and force reauthorization.</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="settingsdialog.ui" line="503"/>
+ <source>Revoke Nexus Authorization</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="490"/>
+ <location filename="settingsdialog.ui" line="514"/>
+ <source>Remove cache and cookies.</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="settingsdialog.ui" line="517"/>
<source>Clear Cache</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="521"/>
+ <location filename="settingsdialog.ui" line="548"/>
<source>Disable automatic internet features</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="524"/>
+ <location filename="settingsdialog.ui" line="551"/>
<source>Disable automatic internet features. This does not affect features that are explicitly invoked by the user (like checking mods for updates, endorsing, opening the web browser)</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="527"/>
+ <location filename="settingsdialog.ui" line="554"/>
<source>Offline Mode</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="534"/>
+ <location filename="settingsdialog.ui" line="561"/>
<source>Use a proxy for network connections.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="537"/>
+ <location filename="settingsdialog.ui" line="564"/>
<source>Use a proxy for network connections. This uses the system-wide settings which can be configured in Internet Explorer. Please note that MO will start up a few seconds slower on some systems when using a proxy.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="540"/>
+ <location filename="settingsdialog.ui" line="567"/>
<source>Use HTTP Proxy (Uses System Settings)</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="547"/>
+ <location filename="settingsdialog.ui" line="574"/>
<source>Endorsement Integration</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="561"/>
+ <location filename="settingsdialog.ui" line="588"/>
<source>Associate with &quot;Download with manager&quot; links</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="590"/>
+ <location filename="settingsdialog.ui" line="617"/>
<source>Known Servers (updated on download)</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="611"/>
+ <location filename="settingsdialog.ui" line="638"/>
<source>Preferred Servers (Drag &amp; Drop)</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="646"/>
+ <location filename="settingsdialog.ui" line="673"/>
<source>Steam</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="652"/>
+ <location filename="settingsdialog.ui" line="679"/>
<source>Username</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="662"/>
+ <location filename="settingsdialog.ui" line="689"/>
<source>Password</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="692"/>
+ <location filename="settingsdialog.ui" line="719"/>
<source>If you save your steam user ID and password here, they will be used when logging into steam. Note, however, your password will be stored unencrypted, so make sure your computer is secure.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="719"/>
+ <location filename="settingsdialog.ui" line="746"/>
<source>Plugins</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="744"/>
+ <location filename="settingsdialog.ui" line="771"/>
<source>Author:</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="758"/>
+ <location filename="settingsdialog.ui" line="785"/>
<source>Version:</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="772"/>
+ <location filename="settingsdialog.ui" line="799"/>
<source>Description:</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="810"/>
+ <location filename="settingsdialog.ui" line="837"/>
<source>Key</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="815"/>
+ <location filename="settingsdialog.ui" line="842"/>
<source>Value</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="827"/>
+ <location filename="settingsdialog.ui" line="854"/>
<source>Blacklisted Plugins (use &lt;del&gt; to remove):</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="838"/>
+ <location filename="settingsdialog.ui" line="865"/>
<source>Workarounds</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="846"/>
+ <location filename="settingsdialog.ui" line="873"/>
<source>Steam App ID</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="866"/>
+ <location filename="settingsdialog.ui" line="893"/>
<source>The Steam AppID for your game</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="869"/>
+ <location filename="settingsdialog.ui" line="896"/>
<source>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
@@ -6361,17 +6371,17 @@ p, li { white-space: pre-wrap; }
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="900"/>
+ <location filename="settingsdialog.ui" line="927"/>
<source>Load Mechanism</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="920"/>
+ <location filename="settingsdialog.ui" line="947"/>
<source>Select loading mechanism. See help for details.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="923"/>
+ <location filename="settingsdialog.ui" line="950"/>
<source>Mod Organizer needs a dll to be injected into the game so all mods are visible to it.
There are several means to do this:
*Mod Organizer* (default) In this mode the Mod Organizer itself injects the dll. The disadvantage is that you always have to start the game through MO or a link created by it.
@@ -6382,17 +6392,17 @@ If you use the Steam version of Oblivion the default will NOT work. In this case
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="940"/>
+ <location filename="settingsdialog.ui" line="967"/>
<source>NMM Version</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="960"/>
+ <location filename="settingsdialog.ui" line="987"/>
<source>The Version of Nexus Mod Manager to impersonate.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="963"/>
+ <location filename="settingsdialog.ui" line="990"/>
<source>Mod Organizer uses an API provided by the Nexus to provide features like checking for updates and downloading files. Unfortunately this API has not been made available officially to third party tools like MO so we have to impersonate the Nexus Mod Manager to be allowed in.
On top of this Nexus has used the client identification to lock out outdated versions of NMM to force users to update. This means that MO also needs to impersonate the new version of NMM even if MO doesn&apos;t need an update. Therefore you can configure the version to identify as here.
Please note that MO does identify itself as MO to the webserver, it&apos;s not lying about what it is. It is merely adding a &quot;compatible&quot; NMM version to the user agent.
@@ -6401,28 +6411,28 @@ tl;dr-version: If Nexus-features don&apos;t work, insert the current version num
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="990"/>
+ <location filename="settingsdialog.ui" line="1017"/>
<source>Enforces that inactive ESPs and ESMs are never loaded.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="993"/>
+ <location filename="settingsdialog.ui" line="1020"/>
<source>It seems that the Games occasionally load ESP or ESM files even if they haven&apos;t been activated as plugins.
I don&apos;t yet know what the circumstances are, but user reports imply it is in some cases unwanted. If this is checked, ESPs and ESMs not checked in the List are invisible to the game and can not be loaded.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="997"/>
+ <location filename="settingsdialog.ui" line="1024"/>
<source>Hide inactive ESPs/ESMs</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1004"/>
+ <location filename="settingsdialog.ui" line="1031"/>
<source>Disable this to no longer display mods installed outside MO in the mod list (left pane). Assets from those mods will then be treated as having lowest mod priority together with the original game content.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1007"/>
+ <location filename="settingsdialog.ui" line="1034"/>
<source>By default Mod Organizer will display esp+bsa bundles installed with foreign tools as mods (left pane). This allows you to control their priority in relation to other mods. This is particularly useful if you also use Steam Workshop to install mods.
However, if you installed loose file mods outside MO which conflict with BSAs also installed outside MO those conflicts can&apos;t be resolved correctly.
@@ -6430,66 +6440,66 @@ If you disable this feature, MO will only display official DLCs this way. Please
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1013"/>
+ <location filename="settingsdialog.ui" line="1040"/>
<source>Display mods installed outside MO</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1023"/>
+ <location filename="settingsdialog.ui" line="1050"/>
<source>If checked, files (i.e. esps, esms and bsas) belonging to the core game can not be disabled in the UI. (default: on)</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1026"/>
+ <location filename="settingsdialog.ui" line="1053"/>
<source>If checked, files (i.e. esps, esms and bsas) belonging to the core game can not be disabled in the UI. (default: on)
Uncheck this if you want to use Mod Organizer with total conversions (like Nehrim) but be aware that the game will crash if required files are not enabled.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1030"/>
+ <location filename="settingsdialog.ui" line="1057"/>
<source>Force-enable game files</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1040"/>
- <location filename="settingsdialog.ui" line="1043"/>
+ <location filename="settingsdialog.ui" line="1067"/>
+ <location filename="settingsdialog.ui" line="1070"/>
<source>Disable this to prevent the GUI from being locked when running an executable. This may result in abnormal behavior.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1046"/>
+ <location filename="settingsdialog.ui" line="1073"/>
<source>Lock GUI when running executable</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1056"/>
+ <location filename="settingsdialog.ui" line="1083"/>
<source>Enable parsing of Archives. Has negative effects on performance.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1059"/>
+ <location filename="settingsdialog.ui" line="1086"/>
<source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;By default, MO will parse archive files (BSA, BA2) to calculate conflicts between the contents of the archive files and other loose files. This process has a noticeable cost in performance.&lt;/p&gt;&lt;p&gt;This feature should not be confused with the archive management feature offered by MO1. MO2 will only show conflicts with archives and will NOT load them into the game or program.&lt;/p&gt;&lt;p&gt;If you disable this feature, MO will only display conflicts between loose files.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1062"/>
+ <location filename="settingsdialog.ui" line="1089"/>
<source>Enable parsing of Archives</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1074"/>
- <location filename="settingsdialog.ui" line="1078"/>
+ <location filename="settingsdialog.ui" line="1101"/>
+ <location filename="settingsdialog.ui" line="1105"/>
<source>For Skyrim, this can be used instead of Archive Invalidation. It should make AI redundant for all Profiles.
For the other games this is not a sufficient replacement for AI!</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1082"/>
+ <location filename="settingsdialog.ui" line="1109"/>
<source>Back-date BSAs</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1093"/>
+ <location filename="settingsdialog.ui" line="1120"/>
<source>Add executables to the blacklist to prevent them from
accessing the virtual file system. This is useful to prevent
unintended programs from being hooked. Hooking unintended
@@ -6498,48 +6508,48 @@ programs you are intentionally running.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1100"/>
+ <location filename="settingsdialog.ui" line="1127"/>
<source>Add executables to the blacklist to prevent them from accessing the virtual file system. This is useful to prevent unintended programs from being hooked. Hooking unintended programs may affect the execution of these programs or the programs you are intentionally running.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1103"/>
+ <location filename="settingsdialog.ui" line="1130"/>
<source>Configure Executables Blacklist</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1113"/>
- <location filename="settingsdialog.ui" line="1116"/>
+ <location filename="settingsdialog.ui" line="1140"/>
+ <location filename="settingsdialog.ui" line="1143"/>
<source>Resets the window geometries for all windows. This can be useful if a window becomes too small or too large, if a column becomes too thin or too wide, and in similar situations.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1119"/>
+ <location filename="settingsdialog.ui" line="1146"/>
<source>Reset Window Geometries</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1142"/>
+ <location filename="settingsdialog.ui" line="1169"/>
<source>These are workarounds for problems with Mod Organizer. Please make sure you read the help text before changing anything here.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1153"/>
+ <location filename="settingsdialog.ui" line="1180"/>
<source>Diagnostics</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1161"/>
+ <location filename="settingsdialog.ui" line="1188"/>
<source>Max Dumps To Keep</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1181"/>
+ <location filename="settingsdialog.ui" line="1208"/>
<source>Maximum number of crash dumps to keep on disk. Use 0 for unlimited.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1184"/>
+ <location filename="settingsdialog.ui" line="1211"/>
<source>
Maximum number of crash dumps to keep on disk. Use 0 for unlimited.
Set &quot;Crash Dumps&quot; above to None to disable crash dump collection.
@@ -6547,12 +6557,12 @@ programs you are intentionally running.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1196"/>
+ <location filename="settingsdialog.ui" line="1223"/>
<source>Hint: right click link and copy link location</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1199"/>
+ <location filename="settingsdialog.ui" line="1226"/>
<source>
Logs and crash dumps are stored under your current instance in the &lt;a href=&quot;LOGS_FULL_PATH&quot;&gt;LOGS_DIR&lt;/a&gt;
and &lt;a href=&quot;DUMPS_FULL_PATH&quot;&gt;DUMPS_DIR&lt;/a&gt; folders.
@@ -6562,17 +6572,17 @@ programs you are intentionally running.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1216"/>
+ <location filename="settingsdialog.ui" line="1243"/>
<source>Crash Dumps</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1223"/>
+ <location filename="settingsdialog.ui" line="1250"/>
<source>Decides which type of crash dumps are collected when injected processes crash.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1226"/>
+ <location filename="settingsdialog.ui" line="1253"/>
<source>
Decides which type of crash dumps are collected when injected processes crash.
&quot;None&quot; Disables the generation of crash dumps by MO.
@@ -6583,37 +6593,37 @@ programs you are intentionally running.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1236"/>
+ <location filename="settingsdialog.ui" line="1263"/>
<source>None</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1241"/>
+ <location filename="settingsdialog.ui" line="1268"/>
<source>Mini (recommended)</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1246"/>
+ <location filename="settingsdialog.ui" line="1273"/>
<source>Data</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1251"/>
+ <location filename="settingsdialog.ui" line="1278"/>
<source>Full</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1279"/>
+ <location filename="settingsdialog.ui" line="1306"/>
<source>Log Level</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1286"/>
+ <location filename="settingsdialog.ui" line="1313"/>
<source>Decides the amount of data printed to &quot;ModOrganizer.log&quot;</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1289"/>
+ <location filename="settingsdialog.ui" line="1316"/>
<source>
Decides the amount of data printed to &quot;ModOrganizer.log&quot;.
&quot;Debug&quot; produces very useful information for finding problems. There is usually no noteworthy performance impact but the file may become rather large. If this is a problem you may prefer the &quot;Info&quot; level for regluar use. On the &quot;Error&quot; level the log file usually remains empty.
@@ -6621,22 +6631,22 @@ programs you are intentionally running.</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1296"/>
+ <location filename="settingsdialog.ui" line="1323"/>
<source>Debug</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1301"/>
+ <location filename="settingsdialog.ui" line="1328"/>
<source>Info (recommended)</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1306"/>
+ <location filename="settingsdialog.ui" line="1333"/>
<source>Warning</source>
<translation type="unfinished"></translation>
</message>
<message>
- <location filename="settingsdialog.ui" line="1311"/>
+ <location filename="settingsdialog.ui" line="1338"/>
<source>Error</source>
<translation type="unfinished"></translation>
</message>