cmodmanager.cpp 10 KB

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