cmodmanager.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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, tr("Can not install submod"));
  134. if(mod.isInstalled())
  135. return addError(modname, tr("Mod is already installed"));
  136. return true;
  137. }
  138. bool CModManager::canUninstallMod(QString modname)
  139. {
  140. auto mod = modList->getMod(modname);
  141. if(mod.isSubmod())
  142. return addError(modname, tr("Can not uninstall submod"));
  143. if(!mod.isInstalled())
  144. return addError(modname, tr("Mod is not installed"));
  145. return true;
  146. }
  147. bool CModManager::canEnableMod(QString modname)
  148. {
  149. auto mod = modList->getMod(modname);
  150. if(mod.isEnabled())
  151. return addError(modname, tr("Mod is already enabled"));
  152. if(!mod.isInstalled())
  153. return addError(modname, tr("Mod must be installed first"));
  154. //check for compatibility
  155. if(!mod.isCompatible())
  156. return addError(modname, tr("Mod is not compatible, please update VCMI and checkout latest mod revisions"));
  157. for(auto modEntry : mod.getDependencies())
  158. {
  159. if(!modList->hasMod(modEntry)) // required mod is not available
  160. return addError(modname, tr("Required mod %1 is missing").arg(modEntry));
  161. CModEntry modData = modList->getMod(modEntry);
  162. if(!modData.isCompatibilityPatch() && !modData.isEnabled())
  163. return addError(modname, tr("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.getConflicts().contains(modname))
  170. return addError(modname, tr("This mod conflicts with %1").arg(modEntry));
  171. }
  172. for(auto modEntry : mod.getConflicts())
  173. {
  174. // check if conflicting mod installed and enabled
  175. if(modList->hasMod(modEntry) && modList->getMod(modEntry).isEnabled())
  176. return addError(modname, tr("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, tr("Mod is already disabled"));
  185. if(!mod.isInstalled())
  186. return addError(modname, tr("Mod must be installed first"));
  187. for(QString modEntry : modList->getModList())
  188. {
  189. auto current = modList->getMod(modEntry);
  190. if(current.getDependencies().contains(modname) && current.isEnabled())
  191. return addError(modname, tr("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. const auto destDir = CLauncherDirs::modsPath() + QChar{'/'};
  223. if(!QFile(archivePath).exists())
  224. return addError(modname, tr("Mod archive is missing"));
  225. if(localMods.contains(modname))
  226. return addError(modname, tr("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, tr("Mod archive is invalid or corrupted"));
  231. std::atomic<int> filesCounter = 0;
  232. auto futureExtract = std::async(std::launch::async, [&archivePath, &destDir, &filesCounter, &filesToExtract]()
  233. {
  234. const auto destDirFsPath = qstringToPath(destDir);
  235. ZipArchive archive(qstringToPath(archivePath));
  236. for (auto const & file : filesToExtract)
  237. {
  238. if (!archive.extract(destDirFsPath, 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, tr("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, tr("Data with this mod was not found"));
  275. QDir modFullDir(modDir);
  276. if(!removeModDir(modDir))
  277. return addError(modname, tr("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. }