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.

607 lines
23 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Diagnostics.CodeAnalysis;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Runtime.Serialization;
  9. using System.Security.Cryptography;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using Ionic.Zip;
  13. using IPA.Loader;
  14. using IPA.Utilities;
  15. using Newtonsoft.Json;
  16. using SemVer;
  17. using UnityEngine;
  18. using UnityEngine.Networking;
  19. using static IPA.Loader.PluginManager;
  20. using Logger = IPA.Logging.Logger;
  21. using Version = SemVer.Version;
  22. namespace IPA.Updating.ModSaber
  23. {
  24. [SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
  25. internal class Updater : MonoBehaviour
  26. {
  27. public static Updater Instance;
  28. public void Awake()
  29. {
  30. try
  31. {
  32. if (Instance != null)
  33. Destroy(this);
  34. else
  35. {
  36. Instance = this;
  37. CheckForUpdates();
  38. }
  39. }
  40. catch (Exception e)
  41. {
  42. Logger.updater.Error(e);
  43. }
  44. }
  45. private void CheckForUpdates()
  46. {
  47. StartCoroutine(CheckForUpdatesCoroutine());
  48. }
  49. private class DependencyObject
  50. {
  51. public string Name { get; set; }
  52. public Version Version { get; set; }
  53. public Version ResolvedVersion { get; set; }
  54. public Range Requirement { get; set; }
  55. public Range Conflicts { get; set; }
  56. public bool Resolved { get; set; }
  57. public bool Has { get; set; }
  58. public HashSet<string> Consumers { get; set; } = new HashSet<string>();
  59. public bool MetaRequestFailed { get; set; }
  60. public PluginLoader.PluginInfo LocalPluginMeta { get; set; }
  61. public override string ToString()
  62. {
  63. return $"{Name}@{Version}{(Resolved ? $" -> {ResolvedVersion}" : "")} - ({Requirement} ! {Conflicts}) {(Has ? " Already have" : "")}";
  64. }
  65. }
  66. private readonly Dictionary<string, string> requestCache = new Dictionary<string, string>();
  67. private IEnumerator GetModsaberEndpoint(string url, Ref<string> result)
  68. {
  69. if (requestCache.TryGetValue(url, out string value))
  70. {
  71. result.Value = value;
  72. }
  73. else
  74. {
  75. using (var request = UnityWebRequest.Get(ApiEndpoint.ApiBase + url))
  76. {
  77. yield return request.SendWebRequest();
  78. if (request.isNetworkError)
  79. {
  80. result.Error = new NetworkException($"Network error while trying to download: {request.error}");
  81. yield break;
  82. }
  83. if (request.isHttpError)
  84. {
  85. if (request.responseCode == 404)
  86. {
  87. result.Error = new NetworkException("Not found");
  88. yield break;
  89. }
  90. result.Error = new NetworkException($"Server returned error {request.error} while getting data");
  91. yield break;
  92. }
  93. result.Value = request.downloadHandler.text;
  94. requestCache[url] = result.Value;
  95. }
  96. }
  97. }
  98. private readonly Dictionary<string, ApiEndpoint.Mod> modCache = new Dictionary<string, ApiEndpoint.Mod>();
  99. private IEnumerator GetModInfo(string modName, string ver, Ref<ApiEndpoint.Mod> result)
  100. {
  101. var uri = string.Format(ApiEndpoint.GetModInfoEndpoint, Uri.EscapeUriString(modName), Uri.EscapeUriString(ver));
  102. if (modCache.TryGetValue(uri, out ApiEndpoint.Mod value))
  103. {
  104. result.Value = value;
  105. }
  106. else
  107. {
  108. Ref<string> reqResult = new Ref<string>("");
  109. yield return GetModsaberEndpoint(uri, reqResult);
  110. try
  111. {
  112. result.Value = JsonConvert.DeserializeObject<ApiEndpoint.Mod>(reqResult.Value);
  113. modCache[uri] = result.Value;
  114. }
  115. catch (Exception e)
  116. {
  117. result.Error = new Exception("Error decoding response", e);
  118. }
  119. }
  120. }
  121. private readonly Dictionary<string, List<ApiEndpoint.Mod>> modVersionsCache = new Dictionary<string, List<ApiEndpoint.Mod>>();
  122. private IEnumerator GetModVersionsMatching(string modName, string range, Ref<List<ApiEndpoint.Mod>> result)
  123. {
  124. var uri = string.Format(ApiEndpoint.GetModsWithSemver, Uri.EscapeUriString(modName), Uri.EscapeUriString(range));
  125. if (modVersionsCache.TryGetValue(uri, out List<ApiEndpoint.Mod> value))
  126. {
  127. result.Value = value;
  128. }
  129. else
  130. {
  131. Ref<string> reqResult = new Ref<string>("");
  132. yield return GetModsaberEndpoint(uri, reqResult);
  133. try
  134. {
  135. result.Value = JsonConvert.DeserializeObject<List<ApiEndpoint.Mod>>(reqResult.Value);
  136. modVersionsCache[uri] = result.Value;
  137. }
  138. catch (Exception e)
  139. {
  140. result.Error = new Exception("Error decoding response", e);
  141. }
  142. }
  143. }
  144. private IEnumerator CheckForUpdatesCoroutine()
  145. {
  146. var depList = new Ref<List<DependencyObject>>(new List<DependencyObject>());
  147. foreach (var plugin in BSMetas)
  148. { // initialize with data to resolve (1.1)
  149. if (plugin.Metadata.Id != null)
  150. { // updatable
  151. var msinfo = plugin.Metadata;
  152. depList.Value.Add(new DependencyObject {
  153. Name = msinfo.Id,
  154. Version = msinfo.Version,
  155. Requirement = new Range($">={msinfo.Version}"),
  156. LocalPluginMeta = plugin
  157. });
  158. }
  159. }
  160. foreach (var dep in depList.Value)
  161. Logger.updater.Debug($"Phantom Dependency: {dep}");
  162. yield return DependencyResolveFirstPass(depList);
  163. foreach (var dep in depList.Value)
  164. Logger.updater.Debug($"Dependency: {dep}");
  165. yield return DependencyResolveSecondPass(depList);
  166. foreach (var dep in depList.Value)
  167. Logger.updater.Debug($"Dependency: {dep}");
  168. DependendyResolveFinalPass(depList);
  169. }
  170. private IEnumerator DependencyResolveFirstPass(Ref<List<DependencyObject>> list)
  171. {
  172. for (int i = 0; i < list.Value.Count; i++)
  173. { // Grab dependencies (1.2)
  174. var dep = list.Value[i];
  175. var mod = new Ref<ApiEndpoint.Mod>(null);
  176. #region TEMPORARY get latest // SHOULD BE GREATEST OF VERSION // not going to happen because of disagreements with ModSaber
  177. yield return GetModInfo(dep.Name, "", mod);
  178. #endregion
  179. try { mod.Verify(); }
  180. catch (Exception e)
  181. {
  182. Logger.updater.Error($"Error getting info for {dep.Name}");
  183. Logger.updater.Error(e);
  184. dep.MetaRequestFailed = true;
  185. continue;
  186. }
  187. list.Value.AddRange(mod.Value.Links.Dependencies.Select(d => new DependencyObject { Name = d.Name, Requirement = d.VersionRange, Consumers = new HashSet<string> { dep.Name } }));
  188. list.Value.AddRange(mod.Value.Links.Conflicts.Select(d => new DependencyObject { Name = d.Name, Conflicts = d.VersionRange, Consumers = new HashSet<string> { dep.Name } }));
  189. }
  190. var depNames = new HashSet<string>();
  191. var final = new List<DependencyObject>();
  192. foreach (var dep in list.Value)
  193. { // agregate ranges and the like (1.3)
  194. if (!depNames.Contains(dep.Name))
  195. { // should add it
  196. depNames.Add(dep.Name);
  197. final.Add(dep);
  198. }
  199. else
  200. {
  201. var toMod = final.First(d => d.Name == dep.Name);
  202. if (dep.Requirement != null)
  203. {
  204. toMod.Requirement = toMod.Requirement.Intersect(dep.Requirement);
  205. foreach (var consume in dep.Consumers)
  206. toMod.Consumers.Add(consume);
  207. }
  208. else if (dep.Conflicts != null)
  209. {
  210. toMod.Conflicts = toMod.Conflicts == null
  211. ? dep.Conflicts
  212. : new Range($"{toMod.Conflicts} || {dep.Conflicts}");
  213. }
  214. }
  215. }
  216. list.Value = final;
  217. }
  218. private IEnumerator DependencyResolveSecondPass(Ref<List<DependencyObject>> list)
  219. {
  220. foreach(var dep in list.Value)
  221. {
  222. dep.Has = dep.Version != null; // dep.Version is only not null if its already installed
  223. if (dep.MetaRequestFailed)
  224. {
  225. Logger.updater.Warn($"{dep.Name} info request failed, not trying again");
  226. continue;
  227. }
  228. var modsMatching = new Ref<List<ApiEndpoint.Mod>>(null);
  229. yield return GetModVersionsMatching(dep.Name, dep.Requirement.ToString(), modsMatching);
  230. try { modsMatching.Verify(); }
  231. catch (Exception e)
  232. {
  233. Logger.updater.Error($"Error getting mod list for {dep.Name}");
  234. Logger.updater.Error(e);
  235. dep.MetaRequestFailed = true;
  236. continue;
  237. }
  238. var ver = modsMatching.Value.Where(nullCheck => nullCheck != null)
  239. .Where(versionCheck => versionCheck.GameVersion.Version == BeatSaber.GameVersion && versionCheck.Approval.Status)
  240. .Where(conflictsCheck => dep.Conflicts == null || !dep.Conflicts.IsSatisfied(conflictsCheck.Version))
  241. .Select(mod => mod.Version).Max(); // (2.1)
  242. // ReSharper disable once AssignmentInConditionalExpression
  243. if (dep.Resolved = ver != null) dep.ResolvedVersion = ver; // (2.2)
  244. dep.Has = dep.Version == dep.ResolvedVersion && dep.Resolved; // dep.Version is only not null if its already installed
  245. }
  246. }
  247. private void DependendyResolveFinalPass(Ref<List<DependencyObject>> list)
  248. { // also starts download of mods
  249. var toDl = new List<DependencyObject>();
  250. foreach (var dep in list.Value)
  251. { // figure out which ones need to be downloaded (3.1)
  252. if (dep.Resolved)
  253. {
  254. Logger.updater.Debug($"Resolved: {dep}");
  255. if (!dep.Has)
  256. {
  257. Logger.updater.Debug($"To Download: {dep}");
  258. toDl.Add(dep);
  259. }
  260. }
  261. else if (!dep.Has)
  262. {
  263. Logger.updater.Warn($"Could not resolve dependency {dep}");
  264. }
  265. }
  266. Logger.updater.Debug($"To Download {string.Join(", ", toDl.Select(d => $"{d.Name}@{d.ResolvedVersion}"))}");
  267. string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + Path.GetRandomFileName());
  268. Directory.CreateDirectory(tempDirectory);
  269. Logger.updater.Debug($"Temp directory: {tempDirectory}");
  270. foreach (var item in toDl)
  271. StartCoroutine(UpdateModCoroutine(item));
  272. }
  273. private IEnumerator UpdateModCoroutine(DependencyObject item)
  274. { // (3.2)
  275. Logger.updater.Debug($"Release: {BeatSaber.ReleaseType}");
  276. var mod = new Ref<ApiEndpoint.Mod>(null);
  277. yield return GetModInfo(item.Name, item.ResolvedVersion.ToString(), mod);
  278. try { mod.Verify(); }
  279. catch (Exception e)
  280. {
  281. Logger.updater.Error($"Error occurred while trying to get information for {item}");
  282. Logger.updater.Error(e);
  283. yield break;
  284. }
  285. ApiEndpoint.Mod.PlatformFile platformFile;
  286. if (BeatSaber.ReleaseType == BeatSaber.Release.Steam || mod.Value.Files.Oculus == null)
  287. platformFile = mod.Value.Files.Steam;
  288. else
  289. platformFile = mod.Value.Files.Oculus;
  290. string url = platformFile.DownloadPath;
  291. Logger.updater.Debug($"URL = {url}");
  292. const int maxTries = 3;
  293. int tries = maxTries;
  294. while (tries > 0)
  295. {
  296. if (tries-- != maxTries)
  297. Logger.updater.Debug("Re-trying download...");
  298. using (var stream = new MemoryStream())
  299. using (var request = UnityWebRequest.Get(url))
  300. using (var taskTokenSource = new CancellationTokenSource())
  301. {
  302. var dlh = new StreamDownloadHandler(stream);
  303. request.downloadHandler = dlh;
  304. Logger.updater.Debug("Sending request");
  305. //Logger.updater.Debug(request?.downloadHandler?.ToString() ?? "DLH==NULL");
  306. yield return request.SendWebRequest();
  307. Logger.updater.Debug("Download finished");
  308. if (request.isNetworkError)
  309. {
  310. Logger.updater.Error("Network error while trying to update mod");
  311. Logger.updater.Error(request.error);
  312. taskTokenSource.Cancel();
  313. continue;
  314. }
  315. if (request.isHttpError)
  316. {
  317. Logger.updater.Error("Server returned an error code while trying to update mod");
  318. Logger.updater.Error(request.error);
  319. taskTokenSource.Cancel();
  320. continue;
  321. }
  322. stream.Seek(0, SeekOrigin.Begin); // reset to beginning
  323. var downloadTask = Task.Run(() =>
  324. { // use slightly more multi threaded approach than co-routines
  325. // ReSharper disable once AccessToDisposedClosure
  326. ExtractPluginAsync(stream, item, platformFile);
  327. }, taskTokenSource.Token);
  328. while (!(downloadTask.IsCompleted || downloadTask.IsCanceled || downloadTask.IsFaulted))
  329. yield return null; // pause co-routine until task is done
  330. if (downloadTask.IsFaulted)
  331. {
  332. if (downloadTask.Exception != null && downloadTask.Exception.InnerExceptions.Any(e => e is ModsaberInterceptException))
  333. { // any exception is an intercept exception
  334. Logger.updater.Error($"Modsaber did not return expected data for {item.Name}");
  335. }
  336. Logger.updater.Error($"Error downloading mod {item.Name}");
  337. Logger.updater.Error(downloadTask.Exception);
  338. continue;
  339. }
  340. break;
  341. }
  342. }
  343. if (tries == 0)
  344. Logger.updater.Warn($"Plugin download failed {maxTries} times, not re-trying");
  345. else
  346. Logger.updater.Debug("Download complete");
  347. }
  348. internal class StreamDownloadHandler : DownloadHandlerScript
  349. {
  350. public MemoryStream Stream { get; set; }
  351. public StreamDownloadHandler(MemoryStream stream)
  352. {
  353. Stream = stream;
  354. }
  355. protected override void ReceiveContentLength(int contentLength)
  356. {
  357. Stream.Capacity = contentLength;
  358. Logger.updater.Debug($"Got content length: {contentLength}");
  359. }
  360. protected override void CompleteContent()
  361. {
  362. Logger.updater.Debug("Download complete");
  363. }
  364. protected override bool ReceiveData(byte[] rData, int dataLength)
  365. {
  366. if (rData == null || rData.Length < 1)
  367. {
  368. Logger.updater.Debug("CustomWebRequest :: ReceiveData - received a null/empty buffer");
  369. return false;
  370. }
  371. Stream.Write(rData, 0, dataLength);
  372. return true;
  373. }
  374. protected override byte[] GetData() { return null; }
  375. protected override float GetProgress()
  376. {
  377. return 0f;
  378. }
  379. public override string ToString()
  380. {
  381. return $"{base.ToString()} ({Stream})";
  382. }
  383. }
  384. private void ExtractPluginAsync(MemoryStream stream, DependencyObject item, ApiEndpoint.Mod.PlatformFile fileInfo)
  385. { // (3.3)
  386. Logger.updater.Debug($"Extracting ZIP file for {item.Name}");
  387. var data = stream.GetBuffer();
  388. SHA1 sha = new SHA1CryptoServiceProvider();
  389. var hash = sha.ComputeHash(data);
  390. if (!Utils.UnsafeCompare(hash, fileInfo.Hash))
  391. throw new Exception("The hash for the file doesn't match what is defined");
  392. var targetDir = Path.Combine(BeatSaber.InstallPath, "IPA", Path.GetRandomFileName() + "_Pending");
  393. Directory.CreateDirectory(targetDir);
  394. var eventualOutput = Path.Combine(BeatSaber.InstallPath, "IPA", "Pending");
  395. if (!Directory.Exists(eventualOutput))
  396. Directory.CreateDirectory(eventualOutput);
  397. try
  398. {
  399. bool shouldDeleteOldFile = !(item.LocalPluginMeta?.Plugin is SelfPlugin);
  400. using (var zipFile = ZipFile.Read(stream))
  401. {
  402. Logger.updater.Debug("Streams opened");
  403. foreach (var entry in zipFile)
  404. {
  405. if (entry.IsDirectory)
  406. {
  407. Logger.updater.Debug($"Creating directory {entry.FileName}");
  408. Directory.CreateDirectory(Path.Combine(targetDir, entry.FileName));
  409. }
  410. else
  411. {
  412. using (var ostream = new MemoryStream((int)entry.UncompressedSize))
  413. {
  414. entry.Extract(ostream);
  415. ostream.Seek(0, SeekOrigin.Begin);
  416. sha = new SHA1CryptoServiceProvider();
  417. var fileHash = sha.ComputeHash(ostream);
  418. try
  419. {
  420. if (!Utils.UnsafeCompare(fileHash, fileInfo.FileHashes[entry.FileName]))
  421. throw new Exception("The hash for the file doesn't match what is defined");
  422. }
  423. catch (KeyNotFoundException)
  424. {
  425. throw new ModsaberInterceptException("ModSaber did not send the hashes for the zip's content!");
  426. }
  427. ostream.Seek(0, SeekOrigin.Begin);
  428. FileInfo targetFile = new FileInfo(Path.Combine(targetDir, entry.FileName));
  429. Directory.CreateDirectory(targetFile.DirectoryName ?? throw new InvalidOperationException());
  430. if (Utils.GetRelativePath(targetFile.FullName, targetDir) == Utils.GetRelativePath(item.LocalPluginMeta?.Metadata.File.FullName, BeatSaber.InstallPath))
  431. shouldDeleteOldFile = false; // overwriting old file, no need to delete
  432. /*if (targetFile.Exists)
  433. backup.Add(targetFile);
  434. else
  435. newFiles.Add(targetFile);*/
  436. Logger.updater.Debug($"Extracting file {targetFile.FullName}");
  437. targetFile.Delete();
  438. using (var fstream = targetFile.Create())
  439. ostream.CopyTo(fstream);
  440. }
  441. }
  442. }
  443. }
  444. if (shouldDeleteOldFile && item.LocalPluginMeta != null)
  445. File.AppendAllLines(Path.Combine(targetDir, SpecialDeletionsFile), new[] { Utils.GetRelativePath(item.LocalPluginMeta?.Metadata.File.FullName, BeatSaber.InstallPath) });
  446. }
  447. catch (Exception)
  448. { // something failed; restore
  449. /*foreach (var file in newFiles)
  450. file.Delete();
  451. backup.Restore();
  452. backup.Delete();*/
  453. Directory.Delete(targetDir, true); // delete extraction site
  454. throw;
  455. }
  456. if (item.LocalPluginMeta?.Plugin is SelfPlugin)
  457. { // currently updating self, so copy to working dir and update
  458. Utils.CopyAll(new DirectoryInfo(targetDir), new DirectoryInfo(BeatSaber.InstallPath));
  459. if (File.Exists(Path.Combine(BeatSaber.InstallPath, SpecialDeletionsFile))) File.Delete(Path.Combine(BeatSaber.InstallPath, SpecialDeletionsFile));
  460. Process.Start(new ProcessStartInfo
  461. {
  462. FileName = item.LocalPluginMeta?.Metadata.File.FullName,
  463. Arguments = $"-nw={Process.GetCurrentProcess().Id}",
  464. UseShellExecute = false
  465. });
  466. }
  467. else
  468. Utils.CopyAll(new DirectoryInfo(targetDir), new DirectoryInfo(eventualOutput), SpecialDeletionsFile);
  469. Directory.Delete(targetDir, true); // delete extraction site
  470. Logger.updater.Debug("Extractor exited");
  471. }
  472. internal const string SpecialDeletionsFile = "$$delete";
  473. }
  474. [Serializable]
  475. internal class NetworkException : Exception
  476. {
  477. public NetworkException()
  478. {
  479. }
  480. public NetworkException(string message) : base(message)
  481. {
  482. }
  483. public NetworkException(string message, Exception innerException) : base(message, innerException)
  484. {
  485. }
  486. protected NetworkException(SerializationInfo info, StreamingContext context) : base(info, context)
  487. {
  488. }
  489. }
  490. [Serializable]
  491. internal class ModsaberInterceptException : Exception
  492. {
  493. public ModsaberInterceptException()
  494. {
  495. }
  496. public ModsaberInterceptException(string message) : base(message)
  497. {
  498. }
  499. public ModsaberInterceptException(string message, Exception innerException) : base(message, innerException)
  500. {
  501. }
  502. protected ModsaberInterceptException(SerializationInfo info, StreamingContext context) : base(info, context)
  503. {
  504. }
  505. }
  506. }