Techblox Mod Manager / Launcher
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

216 строки
9.3KB

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