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.

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