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.

346 lines
13 KiB

6 years ago
  1. using IllusionInjector.Updating.Backup;
  2. using IllusionInjector.Utilities;
  3. using Ionic.Zip;
  4. using Newtonsoft.Json;
  5. using System;
  6. using System.Collections;
  7. using System.Collections.Generic;
  8. using System.Diagnostics;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Security.Cryptography;
  12. using System.Text;
  13. using System.Text.RegularExpressions;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. using UnityEngine;
  17. using UnityEngine.Networking;
  18. using Logger = IllusionInjector.Logging.Logger;
  19. namespace IllusionInjector.Updating.ModsaberML
  20. {
  21. class Updater : MonoBehaviour
  22. {
  23. public static Updater instance;
  24. public void Awake()
  25. {
  26. try
  27. {
  28. if (instance != null)
  29. Destroy(this);
  30. else
  31. {
  32. instance = this;
  33. CheckForUpdates();
  34. }
  35. }
  36. catch (Exception e)
  37. {
  38. Logger.log.Error(e);
  39. }
  40. }
  41. public void CheckForUpdates()
  42. {
  43. StartCoroutine(CheckForUpdatesCoroutine());
  44. }
  45. private struct UpdateStruct
  46. {
  47. public PluginManager.BSPluginMeta plugin;
  48. public ApiEndpoint.Mod externInfo;
  49. }
  50. IEnumerator CheckForUpdatesCoroutine()
  51. {
  52. Logger.log.Info("Checking for mod updates...");
  53. var toUpdate = new List<UpdateStruct>();
  54. var GameVersion = new Version(Application.version);
  55. foreach (var plugin in PluginManager.BSMetas)
  56. {
  57. var info = plugin.ModsaberInfo;
  58. if (info == null) continue;
  59. using (var request = UnityWebRequest.Get(ApiEndpoint.ApiBase + string.Format(ApiEndpoint.GetApprovedEndpoint, info.InternalName)))
  60. {
  61. yield return request.SendWebRequest();
  62. if (request.isNetworkError)
  63. {
  64. Logger.log.Error("Network error while trying to update mods");
  65. Logger.log.Error(request.error);
  66. continue;
  67. }
  68. if (request.isHttpError)
  69. {
  70. if (request.responseCode == 404)
  71. {
  72. Logger.log.Error($"Mod {plugin.Plugin.Name} not found under name {info.InternalName}");
  73. continue;
  74. }
  75. Logger.log.Error($"Server returned an error code while trying to update mod {plugin.Plugin.Name}");
  76. Logger.log.Error(request.error);
  77. continue;
  78. }
  79. var json = request.downloadHandler.text;
  80. ApiEndpoint.Mod modRegistry;
  81. try
  82. {
  83. modRegistry = JsonConvert.DeserializeObject<ApiEndpoint.Mod>(json);
  84. Logger.log.Debug(modRegistry.ToString());
  85. }
  86. catch (Exception e)
  87. {
  88. Logger.log.Error($"Parse error while trying to update mods");
  89. Logger.log.Error(e);
  90. continue;
  91. }
  92. Logger.log.Debug($"Found Modsaber.ML registration for {plugin.Plugin.Name} ({info.InternalName})");
  93. Logger.log.Debug($"Installed version: {info.CurrentVersion}; Latest version: {modRegistry.Version}");
  94. if (modRegistry.Version > info.CurrentVersion)
  95. {
  96. Logger.log.Debug($"{plugin.Plugin.Name} needs an update!");
  97. if (modRegistry.GameVersion == GameVersion)
  98. {
  99. Logger.log.Debug($"Queueing update...");
  100. toUpdate.Add(new UpdateStruct
  101. {
  102. plugin = plugin,
  103. externInfo = modRegistry
  104. });
  105. }
  106. else
  107. {
  108. Logger.log.Warn($"Update avaliable for {plugin.Plugin.Name}, but for a different Beat Saber version!");
  109. }
  110. }
  111. }
  112. }
  113. Logger.log.Info($"{toUpdate.Count} mods need updating");
  114. if (toUpdate.Count == 0) yield break;
  115. string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + Path.GetRandomFileName());
  116. Directory.CreateDirectory(tempDirectory);
  117. foreach (var item in toUpdate)
  118. {
  119. StartCoroutine(UpdateModCoroutine(item, tempDirectory));
  120. }
  121. }
  122. class StreamDownloadHandler : DownloadHandlerScript
  123. {
  124. public MemoryStream Stream { get; set; }
  125. public StreamDownloadHandler(MemoryStream stream) : base()
  126. {
  127. Stream = stream;
  128. }
  129. protected override void ReceiveContentLength(int contentLength)
  130. {
  131. Stream.Capacity = contentLength;
  132. Logger.log.Debug($"Got content length: {contentLength}");
  133. }
  134. protected override void CompleteContent()
  135. {
  136. Logger.log.Debug("Download complete");
  137. }
  138. protected override bool ReceiveData(byte[] data, int dataLength)
  139. {
  140. if (data == null || data.Length < 1)
  141. {
  142. Logger.log.Debug("CustomWebRequest :: ReceiveData - received a null/empty buffer");
  143. return false;
  144. }
  145. Stream.Write(data, 0, dataLength);
  146. return true;
  147. }
  148. protected override byte[] GetData() { return null; }
  149. protected override float GetProgress()
  150. {
  151. return 0f;
  152. }
  153. public override string ToString()
  154. {
  155. return $"{base.ToString()} ({Stream?.ToString()})";
  156. }
  157. }
  158. private void ExtractPluginAsync(MemoryStream stream, UpdateStruct item, ApiEndpoint.Mod.PlatformFile fileInfo, string tempDirectory)
  159. {
  160. Logger.log.Debug($"Extracting ZIP file for {item.plugin.Plugin.Name}");
  161. var data = stream.GetBuffer();
  162. SHA1 sha = new SHA1CryptoServiceProvider();
  163. var hash = sha.ComputeHash(data);
  164. if (!LoneFunctions.UnsafeCompare(hash, fileInfo.Hash))
  165. throw new Exception("The hash for the file doesn't match what is defined");
  166. var newFiles = new List<FileInfo>();
  167. var backup = new BackupUnit(tempDirectory, $"backup-{item.plugin.ModsaberInfo.InternalName}");
  168. try
  169. {
  170. bool shouldDeleteOldFile = true;
  171. using (var zipFile = ZipFile.Read(stream))
  172. {
  173. Logger.log.Debug("Streams opened");
  174. foreach (var entry in zipFile)
  175. {
  176. if (entry.IsDirectory)
  177. {
  178. Logger.log.Debug($"Creating directory {entry.FileName}");
  179. Directory.CreateDirectory(Path.Combine(Environment.CurrentDirectory, entry.FileName));
  180. }
  181. else
  182. {
  183. using (var ostream = new MemoryStream((int)entry.UncompressedSize))
  184. {
  185. entry.Extract(ostream);
  186. ostream.Seek(0, SeekOrigin.Begin);
  187. sha = new SHA1CryptoServiceProvider();
  188. var fileHash = sha.ComputeHash(ostream);
  189. if (!LoneFunctions.UnsafeCompare(fileHash, fileInfo.FileHashes[entry.FileName]))
  190. throw new Exception("The hash for the file doesn't match what is defined");
  191. ostream.Seek(0, SeekOrigin.Begin);
  192. FileInfo targetFile = new FileInfo(Path.Combine(Environment.CurrentDirectory, entry.FileName));
  193. Directory.CreateDirectory(targetFile.DirectoryName);
  194. if (targetFile.FullName == item.plugin.Filename)
  195. shouldDeleteOldFile = false; // overwriting old file, no need to delete
  196. if (targetFile.Exists)
  197. backup.Add(targetFile);
  198. else
  199. newFiles.Add(targetFile);
  200. Logger.log.Debug($"Extracting file {targetFile.FullName}");
  201. var fstream = targetFile.Create();
  202. ostream.CopyTo(fstream);
  203. }
  204. }
  205. }
  206. }
  207. if (item.plugin.Plugin is SelfPlugin)
  208. { // currently updating self
  209. Process.Start(new ProcessStartInfo
  210. {
  211. FileName = item.plugin.Filename,
  212. Arguments = $"--waitfor={Process.GetCurrentProcess().Id} --nowait",
  213. UseShellExecute = false
  214. });
  215. }
  216. else if (shouldDeleteOldFile)
  217. File.Delete(item.plugin.Filename);
  218. }
  219. catch (Exception)
  220. { // something failed; restore
  221. foreach (var file in newFiles)
  222. file.Delete();
  223. backup.Restore();
  224. backup.Delete();
  225. throw;
  226. }
  227. backup.Delete();
  228. Logger.log.Debug("Downloader exited");
  229. }
  230. IEnumerator UpdateModCoroutine(UpdateStruct item, string tempDirectory)
  231. {
  232. Logger.log.Debug($"Steam avaliable: {SteamCheck.IsAvailable}");
  233. ApiEndpoint.Mod.PlatformFile platformFile;
  234. if (SteamCheck.IsAvailable || item.externInfo.Files.Oculus == null)
  235. platformFile = item.externInfo.Files.Steam;
  236. else
  237. platformFile = item.externInfo.Files.Oculus;
  238. string url = platformFile.DownloadPath;
  239. Logger.log.Debug($"URL = {url}");
  240. const int MaxTries = 3;
  241. int maxTries = MaxTries;
  242. while (maxTries > 0)
  243. {
  244. if (maxTries-- != MaxTries)
  245. Logger.log.Info($"Re-trying download...");
  246. using (var stream = new MemoryStream())
  247. using (var request = UnityWebRequest.Get(url))
  248. using (var taskTokenSource = new CancellationTokenSource())
  249. {
  250. var dlh = new StreamDownloadHandler(stream);
  251. request.downloadHandler = dlh;
  252. Logger.log.Debug("Sending request");
  253. //Logger.log.Debug(request?.downloadHandler?.ToString() ?? "DLH==NULL");
  254. yield return request.SendWebRequest();
  255. Logger.log.Debug("Download finished");
  256. if (request.isNetworkError)
  257. {
  258. Logger.log.Error("Network error while trying to update mod");
  259. Logger.log.Error(request.error);
  260. taskTokenSource.Cancel();
  261. continue;
  262. }
  263. if (request.isHttpError)
  264. {
  265. Logger.log.Error($"Server returned an error code while trying to update mod");
  266. Logger.log.Error(request.error);
  267. taskTokenSource.Cancel();
  268. continue;
  269. }
  270. stream.Seek(0, SeekOrigin.Begin); // reset to beginning
  271. var downloadTask = Task.Run(() =>
  272. { // use slightly more multithreaded approach than coroutines
  273. ExtractPluginAsync(stream, item, platformFile, tempDirectory);
  274. }, taskTokenSource.Token);
  275. while (!(downloadTask.IsCompleted || downloadTask.IsCanceled || downloadTask.IsFaulted))
  276. yield return null; // pause coroutine until task is done
  277. if (downloadTask.IsFaulted)
  278. {
  279. Logger.log.Error($"Error downloading mod {item.plugin.Plugin.Name}");
  280. Logger.log.Error(downloadTask.Exception);
  281. continue;
  282. }
  283. break;
  284. }
  285. }
  286. if (maxTries == 0)
  287. Logger.log.Warn($"Plugin download failed {MaxTries} times, not re-trying");
  288. else
  289. Logger.log.Debug("Download complete");
  290. }
  291. }
  292. }