cmodmanager.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. /*
  2. * cmodmanager.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "cmodmanager.h"
  12. #include "../../lib/VCMIDirs.h"
  13. #include "../../lib/filesystem/Filesystem.h"
  14. #include "../../lib/filesystem/CZipLoader.h"
  15. #include "../../lib/modding/CModHandler.h"
  16. #include "../../lib/modding/CModInfo.h"
  17. #include "../../lib/modding/IdentifierStorage.h"
  18. #include "../jsonutils.h"
  19. #include "../launcherdirs.h"
  20. #include <future>
  21. namespace
  22. {
  23. QString detectModArchive(QString path, QString modName, std::vector<std::string> & filesToExtract)
  24. {
  25. ZipArchive archive(qstringToPath(path));
  26. filesToExtract = archive.listFiles();
  27. QString modDirName;
  28. for(int folderLevel : {0, 1}) //search in subfolder if there is no mod.json in the root
  29. {
  30. for(auto file : filesToExtract)
  31. {
  32. QString filename = QString::fromUtf8(file.c_str());
  33. modDirName = filename.section('/', 0, folderLevel);
  34. if(filename == modDirName + "/mod.json")
  35. {
  36. return modDirName;
  37. }
  38. }
  39. }
  40. logGlobal->error("Failed to detect mod path in archive!");
  41. logGlobal->debug("List of file in archive:");
  42. for(auto file : filesToExtract)
  43. logGlobal->debug("%s", file.c_str());
  44. return "";
  45. }
  46. }
  47. CModManager::CModManager(CModList * modList)
  48. : modList(modList)
  49. {
  50. loadMods();
  51. loadModSettings();
  52. }
  53. QString CModManager::settingsPath()
  54. {
  55. return pathToQString(VCMIDirs::get().userConfigPath() / "modSettings.json");
  56. }
  57. void CModManager::loadModSettings()
  58. {
  59. modSettings = JsonUtils::JsonFromFile(settingsPath()).toMap();
  60. modList->setModSettings(modSettings["activeMods"]);
  61. }
  62. void CModManager::resetRepositories()
  63. {
  64. modList->resetRepositories();
  65. }
  66. void CModManager::loadRepositories(QVector<QVariantMap> repomap)
  67. {
  68. for (auto const & entry : repomap)
  69. modList->addRepository(entry);
  70. modList->reloadRepositories();
  71. }
  72. void CModManager::loadMods()
  73. {
  74. CModHandler handler;
  75. handler.loadMods();
  76. auto installedMods = handler.getAllMods();
  77. localMods.clear();
  78. for(auto modname : installedMods)
  79. {
  80. auto resID = CModInfo::getModFile(modname);
  81. if(CResourceHandler::get()->existsResource(resID))
  82. {
  83. //calculate mod size
  84. qint64 total = 0;
  85. ResourcePath resDir(CModInfo::getModDir(modname), EResType::DIRECTORY);
  86. if(CResourceHandler::get()->existsResource(resDir))
  87. {
  88. for(QDirIterator iter(QString::fromStdString(CResourceHandler::get()->getResourceName(resDir)->string()), QDirIterator::Subdirectories); iter.hasNext(); iter.next())
  89. total += iter.fileInfo().size();
  90. }
  91. boost::filesystem::path name = *CResourceHandler::get()->getResourceName(resID);
  92. auto mod = JsonUtils::JsonFromFile(pathToQString(name));
  93. auto json = JsonUtils::toJson(mod);
  94. json["localSizeBytes"].Float() = total;
  95. if(!name.is_absolute())
  96. json["storedLocaly"].Bool() = true;
  97. mod = JsonUtils::toVariant(json);
  98. localMods.insert(QString::fromUtf8(modname.c_str()).toLower(), mod);
  99. }
  100. }
  101. modList->setLocalModList(localMods);
  102. }
  103. bool CModManager::addError(QString modname, QString message)
  104. {
  105. recentErrors.push_back(QString("%1: %2").arg(modname).arg(message));
  106. return false;
  107. }
  108. QStringList CModManager::getErrors()
  109. {
  110. QStringList ret = recentErrors;
  111. recentErrors.clear();
  112. return ret;
  113. }
  114. bool CModManager::installMod(QString modname, QString archivePath)
  115. {
  116. return canInstallMod(modname) && doInstallMod(modname, archivePath);
  117. }
  118. bool CModManager::uninstallMod(QString modname)
  119. {
  120. return canUninstallMod(modname) && doUninstallMod(modname);
  121. }
  122. bool CModManager::enableMod(QString modname)
  123. {
  124. return canEnableMod(modname) && doEnableMod(modname, true);
  125. }
  126. bool CModManager::disableMod(QString modname)
  127. {
  128. return canDisableMod(modname) && doEnableMod(modname, false);
  129. }
  130. bool CModManager::canInstallMod(QString modname)
  131. {
  132. auto mod = modList->getMod(modname);
  133. if(mod.isSubmod())
  134. return addError(modname, tr("Can not install submod"));
  135. if(mod.isInstalled())
  136. return addError(modname, tr("Mod is already installed"));
  137. return true;
  138. }
  139. bool CModManager::canUninstallMod(QString modname)
  140. {
  141. auto mod = modList->getMod(modname);
  142. if(mod.isSubmod())
  143. return addError(modname, tr("Can not uninstall submod"));
  144. if(!mod.isInstalled())
  145. return addError(modname, tr("Mod is not installed"));
  146. return true;
  147. }
  148. bool CModManager::canEnableMod(QString modname)
  149. {
  150. auto mod = modList->getMod(modname);
  151. if(mod.isEnabled())
  152. return addError(modname, tr("Mod is already enabled"));
  153. if(!mod.isInstalled())
  154. return addError(modname, tr("Mod must be installed first"));
  155. //check for compatibility
  156. if(!mod.isCompatible())
  157. return addError(modname, tr("Mod is not compatible, please update VCMI and checkout latest mod revisions"));
  158. for(auto modEntry : mod.getDependencies())
  159. {
  160. if(!modList->hasMod(modEntry)) // required mod is not available
  161. return addError(modname, tr("Required mod %1 is missing").arg(modEntry));
  162. CModEntry modData = modList->getMod(modEntry);
  163. if(!modData.isCompatibilityPatch() && !modData.isEnabled())
  164. return addError(modname, tr("Required mod %1 is not enabled").arg(modEntry));
  165. }
  166. for(QString modEntry : modList->getModList())
  167. {
  168. auto mod = modList->getMod(modEntry);
  169. // "reverse conflict" - enabled mod has this one as conflict
  170. if(mod.isEnabled() && mod.getConflicts().contains(modname))
  171. return addError(modname, tr("This mod conflicts with %1").arg(modEntry));
  172. }
  173. for(auto modEntry : mod.getConflicts())
  174. {
  175. // check if conflicting mod installed and enabled
  176. if(modList->hasMod(modEntry) && modList->getMod(modEntry).isEnabled())
  177. return addError(modname, tr("This mod conflicts with %1").arg(modEntry));
  178. }
  179. return true;
  180. }
  181. bool CModManager::canDisableMod(QString modname)
  182. {
  183. auto mod = modList->getMod(modname);
  184. if(mod.isDisabled())
  185. return addError(modname, tr("Mod is already disabled"));
  186. if(!mod.isInstalled())
  187. return addError(modname, tr("Mod must be installed first"));
  188. for(QString modEntry : modList->getModList())
  189. {
  190. auto current = modList->getMod(modEntry);
  191. if(current.getDependencies().contains(modname) && current.isEnabled())
  192. return addError(modname, tr("This mod is needed to run %1").arg(modEntry));
  193. }
  194. return true;
  195. }
  196. static QVariant writeValue(QString path, QVariantMap input, QVariant value)
  197. {
  198. if(path.size() > 1)
  199. {
  200. QString entryName = path.section('/', 0, 1);
  201. QString remainder = "/" + path.section('/', 2, -1);
  202. entryName.remove(0, 1);
  203. input.insert(entryName, writeValue(remainder, input.value(entryName).toMap(), value));
  204. return input;
  205. }
  206. else
  207. {
  208. return value;
  209. }
  210. }
  211. bool CModManager::doEnableMod(QString mod, bool on)
  212. {
  213. QString path = mod;
  214. path = "/activeMods/" + path.replace(".", "/mods/") + "/active";
  215. modSettings = writeValue(path, modSettings, QVariant(on)).toMap();
  216. modList->setModSettings(modSettings["activeMods"]);
  217. modList->modChanged(mod);
  218. JsonUtils::JsonToFile(settingsPath(), modSettings);
  219. return true;
  220. }
  221. bool CModManager::doInstallMod(QString modname, QString archivePath)
  222. {
  223. const auto destDir = CLauncherDirs::modsPath() + QChar{'/'};
  224. if(!QFile(archivePath).exists())
  225. return addError(modname, tr("Mod archive is missing"));
  226. if(localMods.contains(modname))
  227. return addError(modname, tr("Mod with such name is already installed"));
  228. std::vector<std::string> filesToExtract;
  229. QString modDirName = ::detectModArchive(archivePath, modname, filesToExtract);
  230. if(!modDirName.size())
  231. return addError(modname, tr("Mod archive is invalid or corrupted"));
  232. std::atomic<int> filesCounter = 0;
  233. auto futureExtract = std::async(std::launch::async, [&archivePath, &destDir, &filesCounter, &filesToExtract]()
  234. {
  235. const auto destDirFsPath = qstringToPath(destDir);
  236. ZipArchive archive(qstringToPath(archivePath));
  237. for (auto const & file : filesToExtract)
  238. {
  239. if (!archive.extract(destDirFsPath, file))
  240. return false;
  241. ++filesCounter;
  242. }
  243. return true;
  244. });
  245. while(futureExtract.wait_for(std::chrono::milliseconds(10)) != std::future_status::ready)
  246. {
  247. emit extractionProgress(filesCounter, filesToExtract.size());
  248. qApp->processEvents();
  249. }
  250. if(!futureExtract.get())
  251. {
  252. removeModDir(destDir + modDirName);
  253. return addError(modname, tr("Failed to extract mod data"));
  254. }
  255. //rename folder and fix the path
  256. QDir extractedDir(destDir + modDirName);
  257. auto rc = QFile::rename(destDir + modDirName, destDir + modname);
  258. if (rc)
  259. extractedDir.setPath(destDir + modname);
  260. //there are possible excessive files - remove them
  261. QString upperLevel = modDirName.section('/', 0, 0);
  262. if(upperLevel != modDirName)
  263. removeModDir(destDir + upperLevel);
  264. CResourceHandler::get("initial")->updateFilteredFiles([](const std::string &) { return true; });
  265. loadMods();
  266. modList->reloadRepositories();
  267. return true;
  268. }
  269. bool CModManager::doUninstallMod(QString modname)
  270. {
  271. ResourcePath resID(std::string("Mods/") + modname.toStdString(), EResType::DIRECTORY);
  272. // Get location of the mod, in case-insensitive way
  273. QString modDir = pathToQString(*CResourceHandler::get()->getResourceName(resID));
  274. if(!QDir(modDir).exists())
  275. return addError(modname, tr("Data with this mod was not found"));
  276. QDir modFullDir(modDir);
  277. if(!removeModDir(modDir))
  278. return addError(modname, tr("Mod is located in protected directory, please remove it manually:\n") + modFullDir.absolutePath());
  279. CResourceHandler::get("initial")->updateFilteredFiles([](const std::string &){ return true; });
  280. loadMods();
  281. modList->reloadRepositories();
  282. return true;
  283. }
  284. bool CModManager::removeModDir(QString path)
  285. {
  286. // issues 2673 and 2680 its why you do not recursively remove without sanity check
  287. QDir checkDir(path);
  288. QDir dir(path);
  289. if(!checkDir.cdUp() || QString::compare("Mods", checkDir.dirName(), Qt::CaseInsensitive))
  290. return false;
  291. #ifndef VCMI_MOBILE // ios and android applications are stored in the isolated container
  292. if(!checkDir.cdUp() || QString::compare("vcmi", checkDir.dirName(), Qt::CaseInsensitive))
  293. return false;
  294. if(!dir.absolutePath().contains("vcmi", Qt::CaseInsensitive))
  295. return false;
  296. #endif
  297. if(!dir.absolutePath().contains("Mods", Qt::CaseInsensitive))
  298. return false;
  299. return dir.removeRecursively();
  300. }