Techblox Mod Manager / Launcher
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

215 рядки
9.2KB

  1. using GCMM.Properties;
  2. using Newtonsoft.Json.Linq;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Drawing;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Reflection;
  11. using System.Runtime.CompilerServices;
  12. using System.Text;
  13. using System.Threading.Tasks;
  14. using System.Windows.Forms;
  15. namespace GCMM
  16. {
  17. partial class MainForm
  18. {
  19. public HashSet<string> GetInstalledMods()
  20. {
  21. bool disabled = false;
  22. if (!Directory.Exists(GamePath("\\Plugins")))
  23. if (Directory.Exists(GamePath("\\Plugins_Disabled")))
  24. disabled = true;
  25. else return new HashSet<string>();
  26. var installed = new HashSet<string>();
  27. foreach (var modPath in Directory.GetFiles(GamePath(disabled ? @"\Plugins_Disabled" : @"\Plugins"), "*.dll"))
  28. {
  29. try
  30. {
  31. var an = AssemblyName.GetAssemblyName(modPath);
  32. if (an.Name == "0Harmony") continue;
  33. //Use filename to avoid differences between repository & assembly name casing
  34. var mod = new ModInfo { Name = Path.GetFileNameWithoutExtension(modPath), Version = an.Version };
  35. AddUpdateModInList(mod);
  36. installed.Add(mod.Name);
  37. }
  38. catch (BadImageFormatException)
  39. { //Not a .NET assembly
  40. }
  41. }
  42. try
  43. {
  44. string ipath = GamePath("\\IPA.exe"); //Heh
  45. if (File.Exists(ipath))
  46. {
  47. var an = AssemblyName.GetAssemblyName(ipath);
  48. gcipa.Version = an.Version;
  49. }
  50. }
  51. catch (BadImageFormatException)
  52. { //Not a .NET assembly
  53. }
  54. try
  55. {
  56. string mmpath = "GCMM.exe";
  57. if (File.Exists(mmpath))
  58. {
  59. var an = AssemblyName.GetAssemblyName(mmpath);
  60. gcmm.Version = an.Version;
  61. }
  62. }
  63. catch (BadImageFormatException)
  64. { //Not a .NET assembly
  65. }
  66. return installed;
  67. }
  68. public async Task GetAvailableMods()
  69. {
  70. bool preview = GetExe()?.Contains("Preview") ?? false;
  71. using (var client = GetClient())
  72. {
  73. string str = await client.DownloadStringTaskAsync("https://exmods.org/mods/modlist.tsv");
  74. foreach (string line in str.Trim().Split('\n'))
  75. {
  76. var sp = line.Split('\t');
  77. if (sp.Length < 2) continue;
  78. var mod = new ModInfo
  79. {
  80. Author = sp[0].Trim(),
  81. Name = sp[1].Trim()
  82. };
  83. if (await FetchModInfo(mod, preview, true)) //If it's actually a mod
  84. AddUpdateModInList(mod);
  85. }
  86. }
  87. if (gcmm.LatestVersion == null) //Only check once
  88. {
  89. await FetchModInfo(gcipa, preview, false);
  90. await FetchModInfo(gcmm, preview, false);
  91. if (gcmm.Updatable)
  92. if (MessageBox.Show("There is a GCMM update available! Do you want to download it now? If yes, extract it over this installation.\n\n" + gcmm.UpdateDetails, "Mod Manager update", MessageBoxButtons.YesNo)
  93. == DialogResult.Yes)
  94. Process.Start(gcmm.DownloadURL);
  95. }
  96. }
  97. public async Task<bool> FetchModInfo(ModInfo mod, bool preview, bool desc)
  98. {
  99. string repoURL = "/api/v1/repos/" + mod.Author + "/" + mod.Name + "/releases";
  100. using (var client = GetClient())
  101. {
  102. var arr = JArray.Parse(await client.DownloadStringTaskAsync(repoURL));
  103. var release = arr.FirstOrDefault(rel =>
  104. {
  105. if ((bool) rel["prerelease"] || (bool) rel["draft"])
  106. return false;
  107. var vs = rel["tag_name"].ToString();
  108. int ind = vs.IndexOf('-');
  109. if (ind != -1)
  110. {
  111. if (vs.Substring(ind + 1).Equals("preview", StringComparison.InvariantCultureIgnoreCase)
  112. && !preview)
  113. return false;
  114. }
  115. return true;
  116. });
  117. if (release == null)
  118. return false;
  119. var verstr = release["tag_name"].ToString().Replace("v", "");
  120. int index = verstr.IndexOf('-');
  121. if (index != -1)
  122. verstr = verstr.Substring(0, index);
  123. JToken asset;
  124. if (release["assets"].Count() == 1)
  125. asset = release["assets"].First;
  126. else
  127. asset = release["assets"].FirstOrDefault(token =>
  128. {
  129. string name = token["name"].ToString();
  130. return name == mod.Name + ".dll" || name == mod.Name + ".zip";
  131. });
  132. mod.DownloadURL = asset?["browser_download_url"]?.ToString();
  133. mod.LastUpdated = (DateTime)release["published_at"];
  134. var ver = verstr.Split('.').Select(str => int.Parse(str)).ToArray();
  135. int getver(byte i) => ver.Length > i ? ver[i] : 0; //By default it sets values not present to -1, but we need them to be 0
  136. mod.LatestVersion = new Version(getver(0), getver(1), getver(2), getver(3));
  137. mod.UpdateDetails = release["name"] + "\n\n" + release["body"].ToString();
  138. if (desc)
  139. {
  140. try
  141. {
  142. var obj = JObject.Parse(await client.DownloadStringTaskAsync("/api/v1/repos/" + mod.Author + "/" + mod.Name + "/contents/README.md"));
  143. mod.Description = Encoding.UTF8.GetString(Convert.FromBase64String(obj["content"].ToString()));
  144. }
  145. catch (WebException)
  146. { //It returns a HTTP 500 if it doesn't exist...
  147. }
  148. }
  149. return true;
  150. }
  151. }
  152. public void AddUpdateModInList(ModInfo mod)
  153. {
  154. if (mods.ContainsKey(mod.Name) ^ modlist.Items.ContainsKey(mod.Name)) //The ListView's keys aren't case sensitive
  155. throw new InvalidOperationException("The mod isn't present in one of the two places: " + mod.Name);
  156. ListViewItem item;
  157. if (modlist.Items.ContainsKey(mod.Name))
  158. {
  159. var omod = mods[mod.Name];
  160. item = modlist.Items[mod.Name];
  161. var items = item.SubItems;
  162. omod.Author = mod.Author ?? omod.Author;
  163. omod.Version = mod.Version ?? omod.Version; //If the object comes from the dictionary then it's directly modified (uninstall)
  164. omod.LatestVersion = mod.LatestVersion ?? omod.LatestVersion;
  165. omod.LastUpdated = mod.LastUpdated == default ? omod.LastUpdated : mod.LastUpdated;
  166. omod.Description = mod.Description ?? omod.Description;
  167. omod.DownloadURL = mod.DownloadURL ?? omod.DownloadURL;
  168. omod.UpdateDetails = mod.UpdateDetails ?? omod.UpdateDetails;
  169. items[1].Text = omod.Author ?? "";
  170. items[2].Text = (omod.Version ?? omod.LatestVersion)?.ToString();
  171. items[3].Text = omod.LatestVersion != null ? omod.LastUpdated.ToString() : "";
  172. item.Group = omod.Installed ? modlist.Groups["installed"] : modlist.Groups["available"];
  173. modlist.Sort();
  174. mod = omod;
  175. }
  176. else
  177. {
  178. mods.Add(mod.Name, mod);
  179. item = new ListViewItem(new[] { mod.Name, mod.Author ?? "", (mod.Version ?? mod.LatestVersion)?.ToString() ?? "", mod.LatestVersion != null ? mod.LastUpdated.ToString() : "" }, modlist.Groups[mod.Installed ? "installed" : "available"]);
  180. item.Name = mod.Name;
  181. modlist.Items.Add(item);
  182. }
  183. if (mod.LatestVersion != null && mod.Version != null && mod.Version < mod.LatestVersion)
  184. item.ForeColor = Color.Blue;
  185. else if (mod.LastUpdated < lastGameUpdateTime)
  186. item.ForeColor = Color.DarkOrange;
  187. else
  188. item.ForeColor = modlist.ForeColor;
  189. }
  190. public void CheckUninstalledMods(HashSet<string> installed)
  191. {
  192. List<string> delete = new List<string>();
  193. foreach (string name in mods.Keys.Except(installed))
  194. {
  195. var mod = mods[name];
  196. mod.Version = null;
  197. if (mod.Author != null)
  198. AddUpdateModInList(mod);
  199. else
  200. delete.Add(name);
  201. }
  202. delete.ForEach(name => { mods.Remove(name); modlist.Items[name].Remove(); });
  203. }
  204. }
  205. }