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.

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