cmodmanager.cpp 9.3 KB

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