/* * ---------- * Essentials * ---------- */ public List <QueueItem> GetQueue() { // Get all mods with valid Github URLs. List <ModConfig> allMods = ModUtilities.GetAllMods(); allMods = GetConfigsWithValidGithubUrl(allMods); // Get mappings from all mods. List <QueueItem> mappings = FromModList(allMods); // Get mappings already stored on disk. List <QueueItem> fileMappings = new List <QueueItem>(); try { fileMappings = JsonConvert.DeserializeObject <List <QueueItem> >(File.ReadAllText(SavePath)); } catch { } // Assign each mapping's proper last checked date. for (int x = 0; x < mappings.Count; x++) { foreach (var fileMapping in fileMappings) { if (mappings[x].ModId == fileMapping.ModId) { var updateMapping = mappings[x]; updateMapping.LastChecked = fileMapping.LastChecked; mappings[x] = updateMapping; break; } } } // Sort mappings. return(SortQueue(mappings)); }
/// <summary> /// Retrieves a list of all mod configurations for each game and adds the ones with GameBananaUpdater.json /// to the list. /// </summary> /// <param name="gbModEntries"></param> /// <returns></returns> public List <GBModEntry> GetEntriesFromExistingMods(List <GBModEntry> gbModEntries) { // Get all of the individual mods, and then if a manual config file exists, try parsing // it and adding a new GBModEntry. List <ModConfig> allExistingMods = ModUtilities.GetAllMods(); foreach (ModConfig existingMod in allExistingMods) { string potentialFileLocation = $"{existingMod.GetModDirectory()}\\{ModManualEntryFileName}"; if (File.Exists(potentialFileLocation)) { try { var simpleModEntry = JsonConvert.DeserializeObject <GBSimpleModEntry>(File.ReadAllText(potentialFileLocation)); simpleModEntry.ModConfig = existingMod; gbModEntries.Add(GBModEntry.FromSimpleModEntry(simpleModEntry)); } catch (Exception ex) { // Write correct template. string templateFileName = potentialFileLocation.Replace(".json", "Example.json"); string json = JsonConvert.SerializeObject(new GBSimpleModEntry("Example", 123456, null), Formatting.Indented); json += $"\r\n\r\n/*You did something wrong in your GameBanana.json, so here's a template to help you.\r\nHere's a tip about what you did wrong {ex.Message}*/"; File.WriteAllText(templateFileName, json); } } } return(gbModEntries); }
public bool Checksum() { #if DEBUG Stopwatch sw = new Stopwatch(); ModEntry.ModLogger.Log("[Checksum] Timer started."); sw.Start(); #endif if (!FilesChanged) { foreach (string path in WatchedPaths) { string absolutePath = Path.Combine(ModHelper.DirectoryPath, path); if (Directory.Exists(absolutePath)) { Dictionary <string, string> currentFilesChecksum = ModUtilities.GetFolderFilesHash(absolutePath, SearchOption.AllDirectories, FileExtensionsFilter); if (!EqualDictionaries(FilesChecksums, currentFilesChecksum)) { FilesChecksums = currentFilesChecksum; FilesChanged = true; } } } } #if DEBUG sw.Stop(); ModEntry.ModLogger.Log("[Checksum] Timer stoped.", $"Elapsed Time: {sw.Elapsed}"); #endif return(FilesChanged); }
public override bool Execute(IEnumerable <string> arguments) { GetScale(); var clone = CreatePrefabFromCode(); clone.transform.position = GetPosition(); clone.AddComponent <ObjectInfo>().ComponentType = ComponentType.Delayer; clone.transform.position = new Vector3(clone.transform.position.x + 10, clone.transform.position.y, clone.transform.position.z + 10); ModUtilities.ExecuteStaticMethod(typeof(StuffPlacer), "SetStateOfAllBoxCollidersFromThingBeingPlaced", true); StuffPlacer.OutlinesOfThingBeingPlaced = null; ModUtilities.SetStaticFieldValue(typeof(StuffPlacer), "BoxCollidersOfThingBeingPlaced", null); FloatingPointRounder.RoundIn(clone, true); MegaMeshManager.AddComponentsIn(clone); foreach (VisualUpdaterWithMeshCombining visualUpdaterWithMeshCombining in clone.GetComponentsInChildren <VisualUpdaterWithMeshCombining>()) { visualUpdaterWithMeshCombining.AllowedToCombineOnStable = true; } SnappingPeg.TryToSnapIn(clone); return(true); }
private void Paste() { if (ClipboardBoard != null) { BoardPlacer.BoardBeingPlaced = Object.Instantiate(ClipboardBoard, new Vector3(0f, -2000f, 0f), Quaternion.identity); foreach (WireCluster wireCluster in BoardPlacer.BoardBeingPlaced.GetComponentsInChildren <WireCluster>()) { Object.Destroy(wireCluster.gameObject); } foreach (CircuitBoard circuitBoard in BoardPlacer.BoardBeingPlaced.GetComponentsInChildren <CircuitBoard>()) { circuitBoard.Renderer.enabled = true; } BoardPlacer.Instance.RecalculateClustersOfCurrentBoard(); ModUtilities.ExecuteMethod(BoardPlacer.Instance, "NewBoardBeingPlaced"); ModUtilities.DummyComponent.StartCoroutine(BoardBeingPlaced()); } IEnumerator BoardBeingPlaced() { yield return(new WaitForSeconds(0.1f)); ModUtilities.ExecuteMethod(BoardPlacer.Instance, "NewBoardBeingPlaced"); } }
static void Awake(BehaviorManager __instance) { MyMod.SetUpdateRate = rate => { CustomFixedUpdate updateDelegate = ModUtilities.GetFieldValue <CustomFixedUpdate>(__instance, "CircuitLogicUpdate"); updateDelegate.updateRate = MyMod.CurrentUpdateRate = rate; }; }
public static void ConnectionFinal() { if (WirePlacer.CurrentWirePlacementIsValid()) { var wireBeingPlaced = ModUtilities.GetStaticFieldValue <GameObject>(typeof(WirePlacer), "WireBeingPlaced"); var wire = wireBeingPlaced.GetComponent <Wire>(); Network.SendPacket(PlaceWirePacket.BuildFromLocalWire(wire)); } }
private static void DoButton(Button button, bool state) { if (state) { ModUtilities.ExecuteMethod(button, "ButtonDown"); PushedDownButtons.Add(button); } else { ModUtilities.ExecuteMethod(button, "ButtonUp"); PushedDownButtons.Remove(button); } }
public void InitData(Texture2D texture) { Width = texture.Width; Height = texture.Height; Data = new Color[Width * Height]; texture.GetData(Data); using (MemoryStream stream = new MemoryStream()) { texture.SaveAsPng(stream, Width, Height); stream.Seek(0, SeekOrigin.Begin); Hash = ModUtilities.GetHash(stream); } }
public void Init() { reff = this; //This is called when the game starts. // ModUtilities.ClearConfig (c,m); //Remove comments this then build to clear the config(Then remove or comment this line), or manually clear it. ModUtilities.CreateConfig(c, m); SetUpConfig(); Debug.Log("Loading model..."); ModUtilities.toInvokeOn.StartCoroutine(ModUtilities.LoadModelFromSource(m, bundleName, modelName, OnModelLoaded)); Debug.Log(m + " has finished setting up..."); }
/// <summary> /// Gets the installation status for a mod. /// </summary> /// <param name="meta">Mod to get status for</param> /// <returns></returns> public ModStatus GetModStatus(ModMetadata meta) { ModMetadata installed = this.Mods.FindOne(x => x.GetModIdentifier() == meta.GetModIdentifier()); if (installed == null) { return(ModStatus.NotInstalled); } ModVersion installedVersion = GetMod(meta); // If we have a request in meta, but no requested version, error. // Delete the meta information and let the user know to re-request the mod. // TODO: Make new exception for this if (installedVersion == null) { this.Mods.Delete(x => x.GetModIdentifier() == installed.GetModIdentifier()); throw new Exception("Mod metadata was in requests, but no matching version was found with it."); } // Check filename exists - if not, mod is requested and not yet downloaded string filename = installedVersion.Filename; if (filename == null) { return(ModStatus.Requested); } // Filename exists- check if properly downloaded string path = Path.Combine(Settings.ModPath, filename); if (File.Exists(path)) { // If our checksum matches, the mod is installed if (ModUtilities.ChecksumMatches(path, installedVersion.Checksum)) { return(ModStatus.Installed); } else { // TODO: Should we remove the mod metadata if the checksum failed here? throw new Exception("Checksum does not match version information."); } } return(ModStatus.Requested); }
static Highlighter() { Materials = new Material[Colors.Length]; Shader outlineShader = ModUtilities.GetFieldValue <Shader>(OutlineEffect.Instance, "outlineShader"); for (int i = 0; i < Colors.Length; i++) { Material mat = new Material(outlineShader); Texture2D tex = new Texture2D(1, 1, TextureFormat.ARGB32, false); tex.SetPixel(0, 0, Colors[i]); tex.Apply(); mat.SetTexture("_MainTex", tex); mat.renderQueue = 5000; Materials[i] = mat; } }
//public PlayerMessage(Farmer sourcePlayer, LocalizedContentManager.LanguageCode language, string message) { // Player = sourcePlayer; // Language = language; // Message = message; // MatchCollection matchCollection = Regex.Matches(message, @"\[(-?[0-9]+)\]"); // int lastIndex = 0; // int horizontalPosition = 0; // foreach(Match match in matchCollection) { // if(int.TryParse(match.Value.Trim('[', ']'), out int index)) { // string messageSubstring = message.Substring(lastIndex, match.Index - lastIndex); // ModEntry.ModLogger.Log($"Message: {message}", $"Substring Message: {messageSubstring}", $"Current Index: {lastIndex}", $"message.Length: {message.Length}", $"match.Index: {match.Index}", $"match.Length: {match.Length}"); // horizontalPosition += MeasureString(language, messageSubstring); // MessageEmojis.Add(new MessageEmoji(index, horizontalPosition, true)); // horizontalPosition += 40; // We add the emoji width // lastIndex = match.Index + match.Length; // } // } //} public PlayerMessage(Farmer sourcePlayer, LocalizedContentManager.LanguageCode language, string message, int messageHash) { Player = sourcePlayer; Language = language; Message = message; MessageHash = messageHash; MatchCollection matchCollection = Regex.Matches(Message, @"\[(-?[0-9]+)\]"); int lastIndex = 0; int horizontalPosition = 0; int verticalPosition = 0; foreach (Match match in matchCollection) { if (int.TryParse(match.Value.Trim('[', ']'), out int index)) { string messageSubstring = Message.Substring(lastIndex, match.Index - lastIndex); string[] breakedLines = ModUtilities.BreakLines(messageSubstring); #if DEBUG ModEntry.ModLogger.LogToMonitor = false; ModEntry.ModLogger.Log($"Message: \"{Message}\"", $"Substring Message: {messageSubstring}", $"Current Index: {lastIndex}", $"message.Length: {message.Length}", $"match.Index: {match.Index}", $"match.Length: {match.Length}"); ModEntry.ModLogger.LogToMonitor = true; #endif int stringMeasure = (int)MeasureString(Language, breakedLines.Last()).X; if (breakedLines.Count() > 1) { horizontalPosition = 0; verticalPosition += (int)MeasureString(Language, "(").Y; } horizontalPosition += stringMeasure; MessageEmojis.Add(new MessageEmoji(index, horizontalPosition, verticalPosition, MessageHash, true)); horizontalPosition += 40; // We add the emoji width lastIndex = match.Index + match.Length; } } }
public static void Place(StackBoardMenu __instance) { if (!ModUtilities.GetFieldValue <bool>(__instance, "CurrentPlacementIsValid")) { return; } var allBoards = ModUtilities.GetFieldValue <List <GameObject> >(__instance, "AllSubBoardsInvolvedWithStacking"); var parentBoard = ModUtilities.GetFieldValue <GameObject>(__instance, "BoardBeingStacked"); var firstBoard = allBoards.First(o => o != parentBoard); foreach (var item in firstBoard.GetComponentsInChildren <ObjectInfo>()) { var netObj = item.GetComponent <NetObject>() ?? item.gameObject.AddComponent <NetObject>(); netObj.NetID = NetObject.GetNewID(); } var packet = PlaceBoardPacket.BuildFromBoard(firstBoard.GetComponent <CircuitBoard>(), parentBoard.transform); Network.SendPacket(packet); }
public void OnEnemySpawn(Enemy enemy, Crab crab) { if (enemy != null) { if (spawnChance < r) { return; } WeaponChance weapon = ModUtilities.GetWeaponFromList(thisWeapon); if (weapon == null) { return; } enemy.rightFist.GetComponent <GrabHand> ().LetGo(); enemy.leftFist.GetComponent <GrabHand> ().LetGo(); GameObject w = UnityEngine.Object.Instantiate(weapon.weapon, enemy.rightFist.GetComponent <GrabHand> ().anchorPoint.position, enemy.rightFist.GetComponent <GrabHand> ().anchorPoint.rotation); w.AddComponent <MyWeaponSetUp> ().SetUp(weapon); enemy.rightFist.GetComponent <TestGrabJoint> ().rigidbodyToGrab = w.GetComponent <WeaponBase> ().grabbable; enemy.rightFist.GetComponent <TestGrabJoint> ().grab = true; ArmorPiece[] componentsInChildren = enemy.GetComponentsInChildren <ArmorPiece> (); for (int i = 0; i < componentsInChildren.Length; i++) { foreach (Collider collider in componentsInChildren[i].GetComponentsInChildren <Collider> ()) { foreach (Collider collider2 in w.GetComponentsInChildren <Collider> ()) { Physics.IgnoreCollision(collider, collider2, true); } } } } }
public void SaveAnotherSelection(bool advance = true) { GameObject a = ModUtilities.GetStaticFieldValue <GameObject>(typeof(WirePlacer), "SelectedPeg"); GameObject b = ModUtilities.GetStaticFieldValue <GameObject>(typeof(WirePlacer), "PegBeingLookedAt"); Vector3 point1, point2; point1 = a.transform.GetChild(0).position; point2 = b.transform.GetChild(0).position; var l = Selections[CurrentSelectionIndex]; if (!IsSelected(a)) { l.Add(a); Highlighter.Highlight(a, CurrentSelectionIndex); } foreach (var item in Physics.RaycastAll(point1, point2 - point1, Vector3.Distance(point1, point2))) { if (item.collider.tag == "Input" || item.collider.tag == "Output") { if (IsSelected(item.collider.gameObject)) { continue; } l.Add(item.collider.gameObject); Highlighter.Highlight(item.collider.gameObject, CurrentSelectionIndex); } } if (advance) { NextSelection(); } }
private void SetUpConfig() { try { ModUtilities.AddKeyToConfig(c, m, "[REQUIRED]", "WeaponObjectName = Name goes here"); ModUtilities.AddKeyToConfig(c, m, "[REQUIRED]", "AssetBundleName = " + a); ModUtilities.AddKeyToConfig(c, m, "[SPACE]", ""); #region ints ModUtilities.AddKeyToConfig(c, m, "[OPTION]", "DamageType = 1"); ModUtilities.AddKeyToConfig(c, m, "[OPTION]", "WeaponType = 1"); ModUtilities.AddKeyToConfig(c, m, "[SPACE]", ""); #endregion #region floats ModUtilities.AddKeyToConfig(c, m, "[OPTION]", "SpawnChance = 25"); ModUtilities.AddKeyToConfig(c, m, "[OPTION]", "ScaleDamage = 1.2"); ModUtilities.AddKeyToConfig(c, m, "[OPTION]", "BonusVelocity = 0.7"); ModUtilities.AddKeyToConfig(c, m, "[OPTION]", "ImpaleDepth = 1"); ModUtilities.AddKeyToConfig(c, m, "[OPTION]", "ImpaleZDamper = 25"); ModUtilities.AddKeyToConfig(c, m, "[OPTION]", "ImpaledConnectedBodyMassScale = 10"); ModUtilities.AddKeyToConfig(c, m, "[OPTION]", "ImpaledBreakForce = 5000"); ModUtilities.AddKeyToConfig(c, m, "[OPTION]", "AddForceToRigidbodyFactor = 0.6"); #endregion #region bools ModUtilities.AddKeyToConfig(c, m, "[OPTION]", "CanPary = true"); ModUtilities.AddKeyToConfig(c, m, "[OPTION]", "CanBeParried = true"); ModUtilities.AddKeyToConfig(c, m, "[OPTION]", "StickOnDamage = false"); ModUtilities.AddKeyToConfig(c, m, "[OPTION]", "HideHandOnGrab = true"); ModUtilities.AddKeyToConfig(c, m, "[OPTION]", "IsCurrentlyGrabbable = true"); ModUtilities.AddKeyToConfig(c, m, "[OPTION]", "SetPositionOnGrab = true"); ModUtilities.AddKeyToConfig(c, m, "[OPTION]", "SetRotationOnGrab = true"); ModUtilities.AddKeyToConfig(c, m, "[OPTION]", "CanAlsoCut = true"); ModUtilities.AddKeyToConfig(c, m, "[OPTION]", "IsDamaging = true"); #endregion modelName = (string)ModUtilities.GetKeyFromConfig(c, m, "WeaponObjectName"); bundleName = (string)ModUtilities.GetKeyFromConfig(c, m, "AssetBundleName"); canPary = (bool)ModUtilities.GetKeyFromConfig(c, m, "CanPary"); canBeParried = (bool)ModUtilities.GetKeyFromConfig(c, m, "CanBeParried"); stickOnDamage = (bool)ModUtilities.GetKeyFromConfig(c, m, "StickOnDamage"); hideHandOnGrab = (bool)ModUtilities.GetKeyFromConfig(c, m, "HideHandOnGrab"); isCurrentlyGrabbable = (bool)ModUtilities.GetKeyFromConfig(c, m, "IsCurrentlyGrabbable"); setPositionOnGrab = (bool)ModUtilities.GetKeyFromConfig(c, m, "SetPositionOnGrab"); setRotationOnGrab = (bool)ModUtilities.GetKeyFromConfig(c, m, "SetRotationOnGrab"); canAlsoCut = (bool)ModUtilities.GetKeyFromConfig(c, m, "CanAlsoCut"); isDamaging = (bool)ModUtilities.GetKeyFromConfig(c, m, "IsDamaging"); spawnChance = (float)ModUtilities.GetKeyFromConfig(c, m, "SpawnChance"); scaleDamage = (float)ModUtilities.GetKeyFromConfig(c, m, "ScaleDamage"); bonusVelocity = (float)ModUtilities.GetKeyFromConfig(c, m, "BonusVelocity"); impaleDepth = (float)ModUtilities.GetKeyFromConfig(c, m, "ImpaleDepth"); impaleZDamper = (float)ModUtilities.GetKeyFromConfig(c, m, "ImpaleZDamper"); connectedBMass = (float)ModUtilities.GetKeyFromConfig(c, m, "ImpaledConnectedBodyMassScale"); impaleBreakForce = (float)ModUtilities.GetKeyFromConfig(c, m, "ImpaledBreakForce"); addForceToRigidbodyFactor = (float)ModUtilities.GetKeyFromConfig(c, m, "AddForceToRigidbodyFactor"); damageType = (float)ModUtilities.GetKeyFromConfig(c, m, "DamageType"); weaponType = (float)ModUtilities.GetKeyFromConfig(c, m, "WeaponType"); } catch (Exception e) { Debug.LogError("UNABLE TO PARSE VALUE, ONE OR MORE MAY HAVE FAILED!\n" + e); } }
public async void Save() { bool modified = false; bool modifiedMv = false; if (Settings.PathToSkyrim != Model.SkyrimPath) { Settings.PathToSkyrim = Model.SkyrimPath; modified = true; } if (Settings.Locale != GetLocaleById(Model.SelectedLocale)) { Settings.Locale = GetLocaleById(Model.SelectedLocale); modified = true; } if (Settings.ExperimentalFunctions != Model.ExpFunctions) { Settings.ExperimentalFunctions = Model.ExpFunctions; modified = true; } if (ModVersion.ModsDisabled != Model.DisabledMods) { ModVersion.ModsDisabled = Model.DisabledMods; if (ModVersion.ModsDisabled) { await Mods.DisableAll(); await Mods.DisableMod("RuFixConsole"); await Mods.DisableMod("SkyMPCore"); } else { if (Mods.ExistMod("RuFixConsole")) { await Mods.EnableMod("RuFixConsole"); } if (Mods.ExistMod("SkyMPCore")) { await Mods.EnableMod("SkyMPCore"); } } modifiedMv = true; } if (Model.CanDisabledSKSE && ModVersion.SKSEDisabled != Model.DisabledSKSE) { ModVersion.SKSEDisabled = Model.DisabledSKSE; if (ModVersion.SKSEDisabled) { await Mods.DisableAll(true); } else { if (ModVersion.ModsDisabled && Mods.ExistMod("SKSE")) { await Mods.EnableMod("SKSE"); } else { await ModUtilities.ActivateCoreMod(); } } modifiedMv = true; } if (modified) { Settings.Save(); } if (modifiedMv) { ModVersion.Save(); } }
private void PingColor(string command, string[] args) { if (mapOverlay != null) { if (args.Length > 0) { int index = 0; bool playerFound = false; Farmer targetPlayer = null; if (args.Length == 2 || args.Length == 4) { if (Game1.IsMasterGame) { string playerName = args[index]; foreach (Farmer farmer in Game1.getAllFarmers()) { if (farmer.Name.Equals(playerName, StringComparison.CurrentCultureIgnoreCase)) { targetPlayer = farmer; playerFound = true; } } index++; if (!playerFound) { this.Monitor.Log($"Player '{playerName}' not found."); } } else { this.Monitor.Log($"You must be the host player to change other players color."); } } else { targetPlayer = Game1.player; playerFound = true; } if (playerFound) { Color?color = null; if (args.Length >= 3) { bool containsR = int.TryParse(args[index], out int r); index++; bool containsG = int.TryParse(args[index], out int g); index++; bool containsB = int.TryParse(args[index], out int b); if (containsR && containsG && containsB) { bool validValues = true; if (r < 0 || r > 255) { validValues = false; Monitor.Log("The R value must be between 0 and 255."); } if (g < 0 || g > 255) { validValues = false; Monitor.Log("The G value must be between 0 and 255."); } if (b < 0 && b < 256) { validValues = false; Monitor.Log("The B value must be between 0 and 255."); } if (validValues) { color = new Color(r, g, b); } } } else { color = ModUtilities.GetColorFromName(args[index]); } if (color.HasValue) { mapOverlay.MapPings[targetPlayer].SetPlayerPingColor(color.Value); } } } } else { this.Monitor.Log($"Missing parameters.\n\n" + "Usage: ping_color [player] <color>|<RGB>\n\n" + "- player:\n\tOptional. The player name. If omitted the target player will be you.\n\n" + "- value:\n\tThe color for the ping. Can be use a color name, the command 'color-list' shows all the available colors." + "\n\tThe color can be also specified in RGB." + "\n\te.g.: ping_color \"Player Name\" 153 50 204 "); //TODO Make more clear and implement feature } }
/// <summary> /// Download a specific version of a mod. /// </summary> /// <exception cref="ModDownloadException"></exception> /// <exception cref="IOException"></exception> /// <returns></returns> public async Task <ModDownloadResult> DownloadMod(ModVersion version, string directory) { CurseforgeModVersion versionInfo; if (version is CurseforgeModVersion) { versionInfo = version as CurseforgeModVersion; } else { throw new ArgumentException("Version provided is not a curseforge mod version, cannot continue."); } // If we get here, the installed version was not found or corrupted if (versionInfo.FileId == null) { throw new ModDownloadException("Error during download: Mod metadata has not been fetched from Curseforge yet."); } if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } #region Perform Mod Download try { HttpWebRequest webRequest = WebRequest.CreateHttp(new Uri(versionInfo.DownloadURL + "/file")); using (WebResponse r = await webRequest.GetResponseAsync()) { Uri downloadUri = r.ResponseUri; if (!FILENAME_MATCH.IsMatch(downloadUri.AbsoluteUri)) { throw new ModDownloadException("The provided download URL does not appear to be valid."); } Match m = FILENAME_MATCH.Match(downloadUri.AbsoluteUri); string filename = m.Groups[1].Value; if (filename.ToLowerInvariant() == "download") { throw new ModDownloadException("Bad filename for a mod from Curseforge; got 'download' instead of filename."); } string finalFilename = Path.Combine(directory, filename); if (File.Exists(finalFilename)) { File.Delete(finalFilename); } FileStream fs = File.OpenWrite(finalFilename); byte[] buffer = new byte[1024]; using (Stream s = r.GetResponseStream()) { int size = s.Read(buffer, 0, buffer.Length); while (size > 0) { fs.Write(buffer, 0, size); size = s.Read(buffer, 0, buffer.Length); } fs.Flush(); fs.Close(); ModDownloadResult result = new ModDownloadResult(); result.Filename = filename; result.Checksum = ModUtilities.GetFileChecksum(finalFilename); return(result); } } } catch (Exception) { throw; } #endregion }
public static void HandleModRemove(IDomain domain, string modIdentifier) { IDomainHandler handler = domain.GetDomainHandler(); ModStorage storage = new ModStorage(Modifi.DefaultPack.Installed, domain); ModMetadata meta = storage.GetMetadata(modIdentifier); if (meta == null) { Modifi.DefaultLogger.Error("Cannot uninstall {0}; it is not installed.", modIdentifier); return; } ModVersion installed = storage.GetMod(meta); ModStatus status = storage.GetModStatus(meta); switch (status) { case ModStatus.NotInstalled: Modifi.DefaultLogger.Error("Cannot uninstall {0}; it is not installed.", meta.GetName()); return; case ModStatus.Requested: Modifi.DefaultLogger.Information("Removing {0}...", meta.GetName()); storage.Delete(meta); Modifi.DefaultLogger.Information("Done."); return; case ModStatus.Installed: Modifi.DefaultLogger.Information("Removing {0} and deleting files...", meta.GetName()); storage.Delete(meta); string filePath = Path.Combine(Settings.ModPath, installed.Filename); bool correctChecksum = ModUtilities.ChecksumMatches(filePath, installed.Checksum); if (correctChecksum) { try { File.Delete(filePath); } catch (Exception e) { Modifi.DefaultLogger.Error("Error deleting {0}, please delete it manually.", filePath); Modifi.DefaultLogger.Error(e.Message); } } else { Modifi.DefaultLogger.Information("File for {0} found at {1}, but the checksum did not match. Delete?", meta.GetName(), filePath); Menu <string> delete = new Menu <string>(); delete.AddItem("Delete"); delete.AddItem("Leave"); delete.DrawMenu(); switch (delete.SelectedOption.ToLower()) { case "delete": File.Delete(filePath); Modifi.DefaultLogger.Information("File deleted."); break; case "leave": Modifi.DefaultLogger.Information("File left in place."); break; } } break; } storage.Dispose(); }