cmodmanager.cpp 9.8 KB

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