Techblox Mod Manager / Launcher
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

229 satır
9.8KB

  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. tbmm.Version = Assembly.GetExecutingAssembly().GetName().Version;
  53. return installed;
  54. }
  55. public async Task GetAvailableMods()
  56. {
  57. bool preview = GetExe()?.Contains("Preview") ?? false;
  58. using (var client = GetClient())
  59. {
  60. string str = await client.DownloadStringTaskAsync("https://exmods.org/mods/modlist.tsv");
  61. foreach (string line in str.Trim().Split('\n'))
  62. {
  63. var sp = line.Split('\t');
  64. if (sp.Length < 2) continue;
  65. DateTime updated = default;
  66. bool broken = false;
  67. if (sp.Length > 2)
  68. {
  69. if (DateTime.TryParse(sp[2].Trim(), out var updatedAt))
  70. updated = updatedAt;
  71. else if (sp[2].Trim().ToLower() == "broken")
  72. broken = true;
  73. }
  74. var mod = new ModInfo
  75. {
  76. Author = sp[0].Trim(),
  77. Name = sp[1].Trim(),
  78. LastUpdated = updated,
  79. Broken = broken
  80. };
  81. if (await FetchModInfo(mod, preview, true)) //If it's actually a mod
  82. AddUpdateModInList(mod);
  83. }
  84. }
  85. if (tbmm.LatestVersion == null) //Only check once
  86. {
  87. await FetchModInfo(gcipa, preview, false);
  88. await FetchModInfo(tbmm, preview, false);
  89. if (tbmm.Updatable)
  90. 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)
  91. == DialogResult.Yes)
  92. Process.Start(tbmm.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. string str;
  101. try
  102. {
  103. str = await client.DownloadStringTaskAsync(repoURL);
  104. }
  105. catch (WebException)
  106. {
  107. return false;
  108. }
  109. var arr = JArray.Parse(str);
  110. var release = arr.FirstOrDefault(rel =>
  111. {
  112. if ((bool) rel["prerelease"] || (bool) rel["draft"])
  113. return false;
  114. var vs = rel["tag_name"].ToString();
  115. int ind = vs.IndexOf('-');
  116. if (ind != -1)
  117. {
  118. if (vs.Substring(ind + 1).Equals("preview", StringComparison.InvariantCultureIgnoreCase)
  119. && !preview)
  120. return false;
  121. }
  122. return true;
  123. });
  124. if (release == null)
  125. return false;
  126. var verstr = release["tag_name"].ToString().Replace("v", "");
  127. int index = verstr.IndexOf('-');
  128. if (index != -1)
  129. verstr = verstr.Substring(0, index);
  130. JToken asset;
  131. if (release["assets"].Count() == 1)
  132. asset = release["assets"].First;
  133. else
  134. asset = release["assets"].FirstOrDefault(token =>
  135. {
  136. string name = token["name"].ToString();
  137. return name == mod.Name + ".dll" || name == mod.Name + ".zip";
  138. });
  139. mod.DownloadURL = asset?["browser_download_url"]?.ToString();
  140. var lastUpdated = (DateTime)release["published_at"];
  141. if (mod.LastUpdated < lastUpdated)
  142. mod.LastUpdated = lastUpdated; //If there's a newer release than the last known working date
  143. var ver = verstr.Split('.').Select(str => int.Parse(str)).ToArray();
  144. 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
  145. mod.LatestVersion = new Version(getver(0), getver(1), getver(2), getver(3));
  146. mod.UpdateDetails = release["name"] + "\n\n" + release["body"];
  147. if (desc)
  148. {
  149. try
  150. {
  151. var obj = JObject.Parse(await client.DownloadStringTaskAsync("/api/v1/repos/" + mod.Author + "/" + mod.Name + "/contents/README.md"));
  152. mod.Description = Encoding.UTF8.GetString(Convert.FromBase64String(obj["content"]?.ToString() ?? string.Empty));
  153. }
  154. catch (WebException)
  155. { //It returns a HTTP 500 if it doesn't exist...
  156. }
  157. }
  158. return true;
  159. }
  160. }
  161. public void AddUpdateModInList(ModInfo mod)
  162. {
  163. if (mods.ContainsKey(mod.Name) ^ modlist.Items.ContainsKey(mod.Name)) //The ListView's keys aren't case sensitive
  164. throw new InvalidOperationException("The mod isn't present in one of the two places: " + mod.Name);
  165. ListViewItem item;
  166. if (modlist.Items.ContainsKey(mod.Name))
  167. {
  168. var omod = mods[mod.Name];
  169. item = modlist.Items[mod.Name];
  170. var items = item.SubItems;
  171. omod.Author = mod.Author ?? omod.Author;
  172. omod.Version = mod.Version ?? omod.Version; //If the object comes from the dictionary then it's directly modified (uninstall)
  173. omod.LatestVersion = mod.LatestVersion ?? omod.LatestVersion;
  174. omod.LastUpdated = mod.LastUpdated == default ? omod.LastUpdated : mod.LastUpdated;
  175. omod.Description = mod.Description ?? omod.Description;
  176. omod.DownloadURL = mod.DownloadURL ?? omod.DownloadURL;
  177. omod.UpdateDetails = mod.UpdateDetails ?? omod.UpdateDetails;
  178. items[1].Text = omod.Author ?? "";
  179. items[2].Text = (omod.Version ?? omod.LatestVersion)?.ToString();
  180. items[3].Text = omod.LatestVersion != null ? omod.LastUpdated.ToString() : "";
  181. item.Group = omod.Installed ? modlist.Groups["installed"] : modlist.Groups["available"];
  182. modlist.Sort();
  183. mod = omod;
  184. }
  185. else
  186. {
  187. mods.Add(mod.Name, mod);
  188. 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"]);
  189. item.Name = mod.Name;
  190. modlist.Items.Add(item);
  191. }
  192. if (mod.LatestVersion != null && mod.Version != null && mod.Version < mod.LatestVersion)
  193. item.ForeColor = Color.Blue;
  194. else if(mod.Broken)
  195. item.ForeColor = Color.Red;
  196. else if (mod.LastUpdated != default && mod.LastUpdated < lastGameUpdateTime)
  197. item.ForeColor = Color.OrangeRed;
  198. else
  199. item.ForeColor = modlist.ForeColor;
  200. }
  201. public void CheckUninstalledMods(HashSet<string> installed)
  202. {
  203. List<string> delete = new List<string>();
  204. foreach (string name in mods.Keys.Except(installed))
  205. {
  206. var mod = mods[name];
  207. mod.Version = null;
  208. if (mod.Author != null)
  209. AddUpdateModInList(mod);
  210. else
  211. delete.Add(name);
  212. }
  213. delete.ForEach(name => { mods.Remove(name); modlist.Items[name].Remove(); });
  214. }
  215. }
  216. }