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.

216 lines
9.4KB

  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 TBMM
  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 = "TBMM.exe";
  55. if (File.Exists(mmpath))
  56. {
  57. var an = AssemblyName.GetAssemblyName(mmpath);
  58. tbmm.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. LastUpdated = sp.Length > 2 ? DateTime.Parse(sp[2].Trim()) : default
  81. };
  82. if (await FetchModInfo(mod, preview, true)) //If it's actually a mod
  83. AddUpdateModInList(mod);
  84. }
  85. }
  86. if (tbmm.LatestVersion == null) //Only check once
  87. {
  88. await FetchModInfo(gcipa, preview, false);
  89. await FetchModInfo(tbmm, preview, false);
  90. if (tbmm.Updatable)
  91. if (MessageBox.Show("There is a TBMM update available! Do you want to download it now? If yes, extract it over this installation.\n\n" + tbmm.UpdateDetails, "Mod Manager update", MessageBoxButtons.YesNo)
  92. == DialogResult.Yes)
  93. Process.Start(tbmm.DownloadURL);
  94. }
  95. }
  96. public async Task<bool> FetchModInfo(ModInfo mod, bool preview, bool desc)
  97. {
  98. string repoURL = "/api/v1/repos/" + mod.Author + "/" + mod.Name + "/releases";
  99. using (var client = GetClient())
  100. {
  101. var arr = JArray.Parse(await client.DownloadStringTaskAsync(repoURL));
  102. var release = arr.FirstOrDefault(rel =>
  103. {
  104. if ((bool) rel["prerelease"] || (bool) rel["draft"])
  105. return false;
  106. var vs = rel["tag_name"].ToString();
  107. int ind = vs.IndexOf('-');
  108. if (ind != -1)
  109. {
  110. if (vs.Substring(ind + 1).Equals("preview", StringComparison.InvariantCultureIgnoreCase)
  111. && !preview)
  112. return false;
  113. }
  114. return true;
  115. });
  116. if (release == null)
  117. return false;
  118. var verstr = release["tag_name"].ToString().Replace("v", "");
  119. int index = verstr.IndexOf('-');
  120. if (index != -1)
  121. verstr = verstr.Substring(0, index);
  122. JToken asset;
  123. if (release["assets"].Count() == 1)
  124. asset = release["assets"].First;
  125. else
  126. asset = release["assets"].FirstOrDefault(token =>
  127. {
  128. string name = token["name"].ToString();
  129. return name == mod.Name + ".dll" || name == mod.Name + ".zip";
  130. });
  131. mod.DownloadURL = asset?["browser_download_url"]?.ToString();
  132. var lastUpdated = (DateTime)release["published_at"];
  133. if (mod.LastUpdated < lastUpdated)
  134. mod.LastUpdated = lastUpdated; //If there's a newer release than the last known working date
  135. var ver = verstr.Split('.').Select(str => int.Parse(str)).ToArray();
  136. 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
  137. mod.LatestVersion = new Version(getver(0), getver(1), getver(2), getver(3));
  138. mod.UpdateDetails = release["name"] + "\n\n" + release["body"].ToString();
  139. if (desc)
  140. {
  141. try
  142. {
  143. var obj = JObject.Parse(await client.DownloadStringTaskAsync("/api/v1/repos/" + mod.Author + "/" + mod.Name + "/contents/README.md"));
  144. mod.Description = Encoding.UTF8.GetString(Convert.FromBase64String(obj["content"].ToString()));
  145. }
  146. catch (WebException)
  147. { //It returns a HTTP 500 if it doesn't exist...
  148. }
  149. }
  150. return true;
  151. }
  152. }
  153. public void AddUpdateModInList(ModInfo mod)
  154. {
  155. if (mods.ContainsKey(mod.Name) ^ modlist.Items.ContainsKey(mod.Name)) //The ListView's keys aren't case sensitive
  156. throw new InvalidOperationException("The mod isn't present in one of the two places: " + mod.Name);
  157. ListViewItem item;
  158. if (modlist.Items.ContainsKey(mod.Name))
  159. {
  160. var omod = mods[mod.Name];
  161. item = modlist.Items[mod.Name];
  162. var items = item.SubItems;
  163. omod.Author = mod.Author ?? omod.Author;
  164. omod.Version = mod.Version ?? omod.Version; //If the object comes from the dictionary then it's directly modified (uninstall)
  165. omod.LatestVersion = mod.LatestVersion ?? omod.LatestVersion;
  166. omod.LastUpdated = mod.LastUpdated == default ? omod.LastUpdated : mod.LastUpdated;
  167. omod.Description = mod.Description ?? omod.Description;
  168. omod.DownloadURL = mod.DownloadURL ?? omod.DownloadURL;
  169. omod.UpdateDetails = mod.UpdateDetails ?? omod.UpdateDetails;
  170. items[1].Text = omod.Author ?? "";
  171. items[2].Text = (omod.Version ?? omod.LatestVersion)?.ToString();
  172. items[3].Text = omod.LatestVersion != null ? omod.LastUpdated.ToString() : "";
  173. item.Group = omod.Installed ? modlist.Groups["installed"] : modlist.Groups["available"];
  174. modlist.Sort();
  175. mod = omod;
  176. }
  177. else
  178. {
  179. mods.Add(mod.Name, mod);
  180. 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"]);
  181. item.Name = mod.Name;
  182. modlist.Items.Add(item);
  183. }
  184. if (mod.LatestVersion != null && mod.Version != null && mod.Version < mod.LatestVersion)
  185. item.ForeColor = Color.Blue;
  186. else if (mod.LastUpdated != default && mod.LastUpdated < lastGameUpdateTime)
  187. item.ForeColor = Color.OrangeRed;
  188. else
  189. item.ForeColor = modlist.ForeColor;
  190. }
  191. public void CheckUninstalledMods(HashSet<string> installed)
  192. {
  193. List<string> delete = new List<string>();
  194. foreach (string name in mods.Keys.Except(installed))
  195. {
  196. var mod = mods[name];
  197. mod.Version = null;
  198. if (mod.Author != null)
  199. AddUpdateModInList(mod);
  200. else
  201. delete.Add(name);
  202. }
  203. delete.ForEach(name => { mods.Remove(name); modlist.Items[name].Remove(); });
  204. }
  205. }
  206. }