Techblox Mod Manager / Launcher
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

213 lines
9.1KB

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