cmodmanager.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. namespace
  21. {
  22. QString detectModArchive(QString path, QString modName, std::vector<std::string> & filesToExtract)
  23. {
  24. ZipArchive archive(qstringToPath(path));
  25. filesToExtract = archive.listFiles();
  26. QString modDirName;
  27. for(int folderLevel : {0, 1}) //search in subfolder if there is no mod.json in the root
  28. {
  29. for(auto file : filesToExtract)
  30. {
  31. QString filename = QString::fromUtf8(file.c_str());
  32. modDirName = filename.section('/', 0, folderLevel);
  33. if(filename == modDirName + "/mod.json")
  34. {
  35. return modDirName;
  36. }
  37. }
  38. }
  39. logGlobal->error("Failed to detect mod path in archive!");
  40. logGlobal->debug("List of file in archive:");
  41. for(auto file : filesToExtract)
  42. logGlobal->debug("%s", file.c_str());
  43. return "";
  44. }
  45. }
  46. CModManager::CModManager(CModList * modList)
  47. : modList(modList)
  48. {
  49. loadMods();
  50. loadModSettings();
  51. }
  52. QString CModManager::settingsPath()
  53. {
  54. return pathToQString(VCMIDirs::get().userConfigPath() / "modSettings.json");
  55. }
  56. void CModManager::loadModSettings()
  57. {
  58. modSettings = JsonUtils::JsonFromFile(settingsPath()).toMap();
  59. modList->setModSettings(modSettings["activeMods"]);
  60. }
  61. void CModManager::resetRepositories()
  62. {
  63. modList->resetRepositories();
  64. }
  65. void CModManager::loadRepositories(QVector<QVariantMap> repomap)
  66. {
  67. for (auto const & entry : repomap)
  68. modList->addRepository(entry);
  69. modList->reloadRepositories();
  70. }
  71. void CModManager::loadMods()
  72. {
  73. CModHandler handler;
  74. handler.loadMods();
  75. auto installedMods = handler.getAllMods();
  76. localMods.clear();
  77. for(auto modname : installedMods)
  78. {
  79. auto resID = CModInfo::getModFile(modname);
  80. if(CResourceHandler::get()->existsResource(resID))
  81. {
  82. //calculate mod size
  83. qint64 total = 0;
  84. ResourcePath resDir(CModInfo::getModDir(modname), EResType::DIRECTORY);
  85. if(CResourceHandler::get()->existsResource(resDir))
  86. {
  87. for(QDirIterator iter(QString::fromStdString(CResourceHandler::get()->getResourceName(resDir)->string()), QDirIterator::Subdirectories); iter.hasNext(); iter.next())
  88. total += iter.fileInfo().size();
  89. }
  90. boost::filesystem::path name = *CResourceHandler::get()->getResourceName(resID);
  91. auto mod = JsonUtils::JsonFromFile(pathToQString(name));
  92. auto json = JsonUtils::toJson(mod);
  93. json["localSizeBytes"].Float() = total;
  94. if(!name.is_absolute())
  95. json["storedLocaly"].Bool() = true;
  96. mod = JsonUtils::toVariant(json);
  97. localMods.insert(QString::fromUtf8(modname.c_str()).toLower(), mod);
  98. }
  99. }
  100. modList->setLocalModList(localMods);
  101. }
  102. bool CModManager::addError(QString modname, QString message)
  103. {
  104. recentErrors.push_back(QString("%1: %2").arg(modname).arg(message));
  105. return false;
  106. }
  107. QStringList CModManager::getErrors()
  108. {
  109. QStringList ret = recentErrors;
  110. recentErrors.clear();
  111. return ret;
  112. }
  113. bool CModManager::installMod(QString modname, QString archivePath)
  114. {
  115. return canInstallMod(modname) && doInstallMod(modname, archivePath);
  116. }
  117. bool CModManager::uninstallMod(QString modname)
  118. {
  119. return canUninstallMod(modname) && doUninstallMod(modname);
  120. }
  121. bool CModManager::enableMod(QString modname)
  122. {
  123. return canEnableMod(modname) && doEnableMod(modname, true);
  124. }
  125. bool CModManager::disableMod(QString modname)
  126. {
  127. return canDisableMod(modname) && doEnableMod(modname, false);
  128. }
  129. bool CModManager::canInstallMod(QString modname)
  130. {
  131. auto mod = modList->getMod(modname);
  132. if(mod.isSubmod())
  133. return addError(modname, "Can not install submod");
  134. if(mod.isInstalled())
  135. return addError(modname, "Mod is already installed");
  136. if(!mod.isAvailable())
  137. return addError(modname, "Mod is not available");
  138. return true;
  139. }
  140. bool CModManager::canUninstallMod(QString modname)
  141. {
  142. auto mod = modList->getMod(modname);
  143. if(mod.isSubmod())
  144. return addError(modname, "Can not uninstall submod");
  145. if(!mod.isInstalled())
  146. return addError(modname, "Mod is not installed");
  147. return true;
  148. }
  149. bool CModManager::canEnableMod(QString modname)
  150. {
  151. auto mod = modList->getMod(modname);
  152. if(mod.isEnabled())
  153. return addError(modname, "Mod is already enabled");
  154. if(!mod.isInstalled())
  155. return addError(modname, "Mod must be installed first");
  156. //check for compatibility
  157. if(!mod.isCompatible())
  158. return addError(modname, "Mod is not compatible, please update VCMI and checkout latest mod revisions");
  159. for(auto modEntry : mod.getDependencies())
  160. {
  161. if(!modList->hasMod(modEntry)) // required mod is not available
  162. return addError(modname, QString("Required mod %1 is missing").arg(modEntry));
  163. if(!modList->getMod(modEntry).isEnabled())
  164. return addError(modname, QString("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, QString("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, QString("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, "Mod is already disabled");
  186. if(!mod.isInstalled())
  187. return addError(modname, "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, QString("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. QString destDir = CLauncherDirs::get().modsPath() + "/";
  224. if(!QFile(archivePath).exists())
  225. return addError(modname, "Mod archive is missing");
  226. if(localMods.contains(modname))
  227. return addError(modname, "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, "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. ZipArchive archive(qstringToPath(archivePath));
  236. for (auto const & file : filesToExtract)
  237. {
  238. if (!archive.extract(qstringToPath(destDir), file))
  239. return false;
  240. ++filesCounter;
  241. }
  242. return true;
  243. });
  244. while(futureExtract.wait_for(std::chrono::milliseconds(10)) != std::future_status::ready)
  245. {
  246. emit extractionProgress(filesCounter, filesToExtract.size());
  247. qApp->processEvents();
  248. }
  249. if(!futureExtract.get())
  250. {
  251. removeModDir(destDir + modDirName);
  252. return addError(modname, "Failed to extract mod data");
  253. }
  254. //rename folder and fix the path
  255. QDir extractedDir(destDir + modDirName);
  256. auto rc = QFile::rename(destDir + modDirName, destDir + modname);
  257. if (rc)
  258. extractedDir.setPath(destDir + modname);
  259. //there are possible excessive files - remove them
  260. QString upperLevel = modDirName.section('/', 0, 0);
  261. if(upperLevel != modDirName)
  262. removeModDir(destDir + upperLevel);
  263. CResourceHandler::get("initial")->updateFilteredFiles([](const std::string &) { return true; });
  264. loadMods();
  265. modList->reloadRepositories();
  266. return true;
  267. }
  268. bool CModManager::doUninstallMod(QString modname)
  269. {
  270. ResourcePath resID(std::string("Mods/") + modname.toStdString(), EResType::DIRECTORY);
  271. // Get location of the mod, in case-insensitive way
  272. QString modDir = pathToQString(*CResourceHandler::get()->getResourceName(resID));
  273. if(!QDir(modDir).exists())
  274. return addError(modname, "Data with this mod was not found");
  275. QDir modFullDir(modDir);
  276. if(!removeModDir(modDir))
  277. return addError(modname, "Mod is located in protected directory, please remove it manually:\n" + modFullDir.absolutePath());
  278. CResourceHandler::get("initial")->updateFilteredFiles([](const std::string &){ return true; });
  279. loadMods();
  280. modList->reloadRepositories();
  281. return true;
  282. }
  283. bool CModManager::removeModDir(QString path)
  284. {
  285. // issues 2673 and 2680 its why you do not recursively remove without sanity check
  286. QDir checkDir(path);
  287. QDir dir(path);
  288. if(!checkDir.cdUp() || QString::compare("Mods", checkDir.dirName(), Qt::CaseInsensitive))
  289. return false;
  290. #ifndef VCMI_IOS //ios applications are stored in the isolated container
  291. if(!checkDir.cdUp() || QString::compare("vcmi", checkDir.dirName(), Qt::CaseInsensitive))
  292. return false;
  293. if(!dir.absolutePath().contains("vcmi", Qt::CaseInsensitive))
  294. return false;
  295. #endif
  296. if(!dir.absolutePath().contains("Mods", Qt::CaseInsensitive))
  297. return false;
  298. return dir.removeRecursively();
  299. }