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.

604 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; } // a range of versions that are not allowed to be downloaded
  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. yield return GetModInfo(dep.Name, "", mod);
  177. try { mod.Verify(); }
  178. catch (Exception e)
  179. {
  180. Logger.updater.Error($"Error getting info for {dep.Name}");
  181. Logger.updater.Error(e);
  182. dep.MetaRequestFailed = true;
  183. continue;
  184. }
  185. list.Value.AddRange(mod.Value.Links.Dependencies.Select(d => new DependencyObject { Name = d.Name, Requirement = d.VersionRange, Consumers = new HashSet<string> { dep.Name } }));
  186. list.Value.AddRange(mod.Value.Links.Conflicts.Select(d => new DependencyObject { Name = d.Name, Conflicts = d.VersionRange, Consumers = new HashSet<string> { dep.Name } }));
  187. }
  188. var depNames = new HashSet<string>();
  189. var final = new List<DependencyObject>();
  190. foreach (var dep in list.Value)
  191. { // agregate ranges and the like (1.3)
  192. if (!depNames.Contains(dep.Name))
  193. { // should add it
  194. depNames.Add(dep.Name);
  195. final.Add(dep);
  196. }
  197. else
  198. {
  199. var toMod = final.First(d => d.Name == dep.Name);
  200. if (dep.Requirement != null)
  201. {
  202. toMod.Requirement = toMod.Requirement.Intersect(dep.Requirement);
  203. foreach (var consume in dep.Consumers)
  204. toMod.Consumers.Add(consume);
  205. }
  206. else if (dep.Conflicts != null)
  207. {
  208. toMod.Conflicts = toMod.Conflicts == null
  209. ? dep.Conflicts
  210. : new Range($"{toMod.Conflicts} || {dep.Conflicts}");
  211. }
  212. }
  213. }
  214. list.Value = final;
  215. }
  216. private IEnumerator DependencyResolveSecondPass(Ref<List<DependencyObject>> list)
  217. {
  218. foreach(var dep in list.Value)
  219. {
  220. dep.Has = dep.Version != null; // dep.Version is only not null if its already installed
  221. if (dep.MetaRequestFailed)
  222. {
  223. Logger.updater.Warn($"{dep.Name} info request failed, not trying again");
  224. continue;
  225. }
  226. var modsMatching = new Ref<List<ApiEndpoint.Mod>>(null);
  227. yield return GetModVersionsMatching(dep.Name, dep.Requirement.ToString(), modsMatching);
  228. try { modsMatching.Verify(); }
  229. catch (Exception e)
  230. {
  231. Logger.updater.Error($"Error getting mod list for {dep.Name}");
  232. Logger.updater.Error(e);
  233. dep.MetaRequestFailed = true;
  234. continue;
  235. }
  236. var ver = modsMatching.Value
  237. .Where(nullCheck => nullCheck != null) // entry is not null
  238. .Where(versionCheck => versionCheck.GameVersion.Version == BeatSaber.GameVersion) // game version matches
  239. .Where(approvalCheck => approvalCheck.Approval.Status) // version approved
  240. .Where(conflictsCheck => dep.Conflicts == null || !dep.Conflicts.IsSatisfied(conflictsCheck.Version)) // not a conflicting version
  241. .Select(mod => mod.Version).Max(); // (2.1) get the max version
  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. foreach (var item in toDl)
  268. StartCoroutine(UpdateModCoroutine(item));
  269. }
  270. private IEnumerator UpdateModCoroutine(DependencyObject item)
  271. { // (3.2)
  272. Logger.updater.Debug($"Release: {BeatSaber.ReleaseType}");
  273. var mod = new Ref<ApiEndpoint.Mod>(null);
  274. yield return GetModInfo(item.Name, item.ResolvedVersion.ToString(), mod);
  275. try { mod.Verify(); }
  276. catch (Exception e)
  277. {
  278. Logger.updater.Error($"Error occurred while trying to get information for {item}");
  279. Logger.updater.Error(e);
  280. yield break;
  281. }
  282. ApiEndpoint.Mod.PlatformFile platformFile;
  283. if (BeatSaber.ReleaseType == BeatSaber.Release.Steam || mod.Value.Files.Oculus == null)
  284. platformFile = mod.Value.Files.Steam;
  285. else
  286. platformFile = mod.Value.Files.Oculus;
  287. string url = platformFile.DownloadPath;
  288. Logger.updater.Debug($"URL = {url}");
  289. const int maxTries = 3;
  290. int tries = maxTries;
  291. while (tries > 0)
  292. {
  293. if (tries-- != maxTries)
  294. Logger.updater.Debug("Re-trying download...");
  295. using (var stream = new MemoryStream())
  296. using (var request = UnityWebRequest.Get(url))
  297. using (var taskTokenSource = new CancellationTokenSource())
  298. {
  299. var dlh = new StreamDownloadHandler(stream);
  300. request.downloadHandler = dlh;
  301. Logger.updater.Debug("Sending request");
  302. //Logger.updater.Debug(request?.downloadHandler?.ToString() ?? "DLH==NULL");
  303. yield return request.SendWebRequest();
  304. Logger.updater.Debug("Download finished");
  305. if (request.isNetworkError)
  306. {
  307. Logger.updater.Error("Network error while trying to update mod");
  308. Logger.updater.Error(request.error);
  309. taskTokenSource.Cancel();
  310. continue;
  311. }
  312. if (request.isHttpError)
  313. {
  314. Logger.updater.Error("Server returned an error code while trying to update mod");
  315. Logger.updater.Error(request.error);
  316. taskTokenSource.Cancel();
  317. continue;
  318. }
  319. stream.Seek(0, SeekOrigin.Begin); // reset to beginning
  320. var downloadTask = Task.Run(() =>
  321. { // use slightly more multi threaded approach than co-routines
  322. // ReSharper disable once AccessToDisposedClosure
  323. ExtractPluginAsync(stream, item, platformFile);
  324. }, taskTokenSource.Token);
  325. while (!(downloadTask.IsCompleted || downloadTask.IsCanceled || downloadTask.IsFaulted))
  326. yield return null; // pause co-routine until task is done
  327. if (downloadTask.IsFaulted)
  328. {
  329. if (downloadTask.Exception != null && downloadTask.Exception.InnerExceptions.Any(e => e is ModsaberInterceptException))
  330. { // any exception is an intercept exception
  331. Logger.updater.Error($"Modsaber did not return expected data for {item.Name}");
  332. }
  333. Logger.updater.Error($"Error downloading mod {item.Name}");
  334. Logger.updater.Error(downloadTask.Exception);
  335. continue;
  336. }
  337. break;
  338. }
  339. }
  340. if (tries == 0)
  341. Logger.updater.Warn($"Plugin download failed {maxTries} times, not re-trying");
  342. else
  343. Logger.updater.Debug("Download complete");
  344. }
  345. internal class StreamDownloadHandler : DownloadHandlerScript
  346. {
  347. public MemoryStream Stream { get; set; }
  348. public StreamDownloadHandler(MemoryStream stream)
  349. {
  350. Stream = stream;
  351. }
  352. protected override void ReceiveContentLength(int contentLength)
  353. {
  354. Stream.Capacity = contentLength;
  355. Logger.updater.Debug($"Got content length: {contentLength}");
  356. }
  357. protected override void CompleteContent()
  358. {
  359. Logger.updater.Debug("Download complete");
  360. }
  361. protected override bool ReceiveData(byte[] rData, int dataLength)
  362. {
  363. if (rData == null || rData.Length < 1)
  364. {
  365. Logger.updater.Debug("CustomWebRequest :: ReceiveData - received a null/empty buffer");
  366. return false;
  367. }
  368. Stream.Write(rData, 0, dataLength);
  369. return true;
  370. }
  371. protected override byte[] GetData() { return null; }
  372. protected override float GetProgress()
  373. {
  374. return 0f;
  375. }
  376. public override string ToString()
  377. {
  378. return $"{base.ToString()} ({Stream})";
  379. }
  380. }
  381. private void ExtractPluginAsync(MemoryStream stream, DependencyObject item, ApiEndpoint.Mod.PlatformFile fileInfo)
  382. { // (3.3)
  383. Logger.updater.Debug($"Extracting ZIP file for {item.Name}");
  384. var data = stream.GetBuffer();
  385. SHA1 sha = new SHA1CryptoServiceProvider();
  386. var hash = sha.ComputeHash(data);
  387. if (!Utils.UnsafeCompare(hash, fileInfo.Hash))
  388. throw new Exception("The hash for the file doesn't match what is defined");
  389. var targetDir = Path.Combine(BeatSaber.InstallPath, "IPA", Path.GetRandomFileName() + "_Pending");
  390. Directory.CreateDirectory(targetDir);
  391. var eventualOutput = Path.Combine(BeatSaber.InstallPath, "IPA", "Pending");
  392. if (!Directory.Exists(eventualOutput))
  393. Directory.CreateDirectory(eventualOutput);
  394. try
  395. {
  396. bool shouldDeleteOldFile = !(item.LocalPluginMeta?.Metadata.IsSelf).Unwrap();
  397. using (var zipFile = ZipFile.Read(stream))
  398. {
  399. Logger.updater.Debug("Streams opened");
  400. foreach (var entry in zipFile)
  401. {
  402. if (entry.IsDirectory)
  403. {
  404. Logger.updater.Debug($"Creating directory {entry.FileName}");
  405. Directory.CreateDirectory(Path.Combine(targetDir, entry.FileName));
  406. }
  407. else
  408. {
  409. using (var ostream = new MemoryStream((int)entry.UncompressedSize))
  410. {
  411. entry.Extract(ostream);
  412. ostream.Seek(0, SeekOrigin.Begin);
  413. sha = new SHA1CryptoServiceProvider();
  414. var fileHash = sha.ComputeHash(ostream);
  415. try
  416. {
  417. if (!Utils.UnsafeCompare(fileHash, fileInfo.FileHashes[entry.FileName]))
  418. throw new Exception("The hash for the file doesn't match what is defined");
  419. }
  420. catch (KeyNotFoundException)
  421. {
  422. throw new ModsaberInterceptException("ModSaber did not send the hashes for the zip's content!");
  423. }
  424. ostream.Seek(0, SeekOrigin.Begin);
  425. FileInfo targetFile = new FileInfo(Path.Combine(targetDir, entry.FileName));
  426. Directory.CreateDirectory(targetFile.DirectoryName ?? throw new InvalidOperationException());
  427. if (Utils.GetRelativePath(targetFile.FullName, targetDir) == Utils.GetRelativePath(item.LocalPluginMeta?.Metadata.File.FullName, BeatSaber.InstallPath))
  428. shouldDeleteOldFile = false; // overwriting old file, no need to delete
  429. /*if (targetFile.Exists)
  430. backup.Add(targetFile);
  431. else
  432. newFiles.Add(targetFile);*/
  433. Logger.updater.Debug($"Extracting file {targetFile.FullName}");
  434. targetFile.Delete();
  435. using (var fstream = targetFile.Create())
  436. ostream.CopyTo(fstream);
  437. }
  438. }
  439. }
  440. }
  441. if (shouldDeleteOldFile && item.LocalPluginMeta != null)
  442. File.AppendAllLines(Path.Combine(targetDir, SpecialDeletionsFile), new[] { Utils.GetRelativePath(item.LocalPluginMeta?.Metadata.File.FullName, BeatSaber.InstallPath) });
  443. }
  444. catch (Exception)
  445. { // something failed; restore
  446. /*foreach (var file in newFiles)
  447. file.Delete();
  448. backup.Restore();
  449. backup.Delete();*/
  450. Directory.Delete(targetDir, true); // delete extraction site
  451. throw;
  452. }
  453. if ((item.LocalPluginMeta?.Metadata.IsSelf).Unwrap())
  454. { // currently updating self, so copy to working dir and update
  455. Utils.CopyAll(new DirectoryInfo(targetDir), new DirectoryInfo(BeatSaber.InstallPath));
  456. var deleteFile = Path.Combine(BeatSaber.InstallPath, SpecialDeletionsFile);
  457. if (File.Exists(deleteFile)) File.Delete(deleteFile);
  458. Process.Start(new ProcessStartInfo
  459. {
  460. // will never actually be null
  461. FileName = item.LocalPluginMeta?.Metadata.File.FullName ?? throw new InvalidOperationException(),
  462. Arguments = $"-nw={Process.GetCurrentProcess().Id}",
  463. UseShellExecute = false
  464. });
  465. }
  466. else
  467. Utils.CopyAll(new DirectoryInfo(targetDir), new DirectoryInfo(eventualOutput), SpecialDeletionsFile);
  468. Directory.Delete(targetDir, true); // delete extraction site
  469. Logger.updater.Debug("Extractor exited");
  470. }
  471. internal const string SpecialDeletionsFile = "$$delete";
  472. }
  473. [Serializable]
  474. internal class NetworkException : Exception
  475. {
  476. public NetworkException()
  477. {
  478. }
  479. public NetworkException(string message) : base(message)
  480. {
  481. }
  482. public NetworkException(string message, Exception innerException) : base(message, innerException)
  483. {
  484. }
  485. protected NetworkException(SerializationInfo info, StreamingContext context) : base(info, context)
  486. {
  487. }
  488. }
  489. [Serializable]
  490. internal class ModsaberInterceptException : Exception
  491. {
  492. public ModsaberInterceptException()
  493. {
  494. }
  495. public ModsaberInterceptException(string message) : base(message)
  496. {
  497. }
  498. public ModsaberInterceptException(string message, Exception innerException) : base(message, innerException)
  499. {
  500. }
  501. protected ModsaberInterceptException(SerializationInfo info, StreamingContext context) : base(info, context)
  502. {
  503. }
  504. }
  505. }