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
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
  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.Utilities;
  14. using Newtonsoft.Json;
  15. using SemVer;
  16. using UnityEngine;
  17. using UnityEngine.Networking;
  18. using static IPA.Loader.PluginManager;
  19. using Logger = IPA.Logging.Logger;
  20. using Version = SemVer.Version;
  21. namespace IPA.Updating.ModSaber
  22. {
  23. [SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
  24. internal class Updater : MonoBehaviour
  25. {
  26. public static Updater Instance;
  27. public void Awake()
  28. {
  29. try
  30. {
  31. if (Instance != null)
  32. Destroy(this);
  33. else
  34. {
  35. Instance = this;
  36. CheckForUpdates();
  37. }
  38. }
  39. catch (Exception e)
  40. {
  41. Logger.updater.Error(e);
  42. }
  43. }
  44. private void CheckForUpdates()
  45. {
  46. StartCoroutine(CheckForUpdatesCoroutine());
  47. }
  48. private class DependencyObject
  49. {
  50. public string Name { get; set; }
  51. public Version Version { get; set; }
  52. public Version ResolvedVersion { get; set; }
  53. public Range Requirement { get; set; }
  54. public Range Conflicts { get; set; }
  55. public bool Resolved { get; set; }
  56. public bool Has { get; set; }
  57. public HashSet<string> Consumers { get; set; } = new HashSet<string>();
  58. public bool MetaRequestFailed { get; set; }
  59. public PluginInfo LocalPluginMeta { get; set; }
  60. public override string ToString()
  61. {
  62. return $"{Name}@{Version}{(Resolved ? $" -> {ResolvedVersion}" : "")} - ({Requirement} ! {Conflicts}) {(Has ? " Already have" : "")}";
  63. }
  64. }
  65. private Dictionary<string, string> requestCache = new Dictionary<string, string>();
  66. private IEnumerator GetModsaberEndpoint(string url, Ref<string> result)
  67. {
  68. if (requestCache.TryGetValue(url, out string value))
  69. {
  70. result.Value = value;
  71. }
  72. else
  73. {
  74. using (var request = UnityWebRequest.Get(ApiEndpoint.ApiBase + url))
  75. {
  76. yield return request.SendWebRequest();
  77. if (request.isNetworkError)
  78. {
  79. result.Error = new NetworkException($"Network error while trying to download: {request.error}");
  80. yield break;
  81. }
  82. if (request.isHttpError)
  83. {
  84. if (request.responseCode == 404)
  85. {
  86. result.Error = new NetworkException("Not found");
  87. yield break;
  88. }
  89. result.Error = new NetworkException($"Server returned error {request.error} while getting data");
  90. yield break;
  91. }
  92. result.Value = request.downloadHandler.text;
  93. requestCache[url] = result.Value;
  94. }
  95. }
  96. }
  97. private readonly Dictionary<string, ApiEndpoint.Mod> modCache = new Dictionary<string, ApiEndpoint.Mod>();
  98. private IEnumerator GetModInfo(string modName, string ver, Ref<ApiEndpoint.Mod> result)
  99. {
  100. var uri = string.Format(ApiEndpoint.GetModInfoEndpoint, Uri.EscapeUriString(modName), Uri.EscapeUriString(ver));
  101. if (modCache.TryGetValue(uri, out ApiEndpoint.Mod value))
  102. {
  103. result.Value = value;
  104. }
  105. else
  106. {
  107. Ref<string> reqResult = new Ref<string>("");
  108. yield return GetModsaberEndpoint(uri, reqResult);
  109. try
  110. {
  111. result.Value = JsonConvert.DeserializeObject<ApiEndpoint.Mod>(reqResult.Value);
  112. modCache[uri] = result.Value;
  113. }
  114. catch (Exception e)
  115. {
  116. result.Error = new Exception("Error decoding response", e);
  117. }
  118. }
  119. }
  120. private readonly Dictionary<string, List<ApiEndpoint.Mod>> modVersionsCache = new Dictionary<string, List<ApiEndpoint.Mod>>();
  121. private IEnumerator GetModVersionsMatching(string modName, string range, Ref<List<ApiEndpoint.Mod>> result)
  122. {
  123. var uri = string.Format(ApiEndpoint.GetModsWithSemver, Uri.EscapeUriString(modName), Uri.EscapeUriString(range));
  124. if (modVersionsCache.TryGetValue(uri, out List<ApiEndpoint.Mod> value))
  125. {
  126. result.Value = value;
  127. }
  128. else
  129. {
  130. Ref<string> reqResult = new Ref<string>("");
  131. yield return GetModsaberEndpoint(uri, reqResult);
  132. try
  133. {
  134. result.Value = JsonConvert.DeserializeObject<List<ApiEndpoint.Mod>>(reqResult.Value);
  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. { // initialize with data to resolve (1.1)
  148. if (plugin.ModSaberInfo != null)
  149. { // updatable
  150. var msinfo = plugin.ModSaberInfo;
  151. depList.Value.Add(new DependencyObject {
  152. Name = msinfo.InternalName,
  153. Version = new Version(msinfo.CurrentVersion),
  154. Requirement = new Range($">={msinfo.CurrentVersion}"),
  155. LocalPluginMeta = plugin
  156. });
  157. }
  158. }
  159. foreach (var dep in depList.Value)
  160. Logger.updater.Debug($"Phantom Dependency: {dep}");
  161. yield return DependencyResolveFirstPass(depList);
  162. foreach (var dep in depList.Value)
  163. Logger.updater.Debug($"Dependency: {dep}");
  164. yield return DependencyResolveSecondPass(depList);
  165. foreach (var dep in depList.Value)
  166. Logger.updater.Debug($"Dependency: {dep}");
  167. DependendyResolveFinalPass(depList);
  168. }
  169. private IEnumerator DependencyResolveFirstPass(Ref<List<DependencyObject>> list)
  170. {
  171. for (int i = 0; i < list.Value.Count; i++)
  172. { // Grab dependencies (1.2)
  173. var dep = list.Value[i];
  174. var mod = new Ref<ApiEndpoint.Mod>(null);
  175. #region TEMPORARY get latest // SHOULD BE GREATEST OF VERSION // not going to happen because of disagreements with ModSaber
  176. yield return GetModInfo(dep.Name, "", mod);
  177. #endregion
  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(d => new DependencyObject { Name = d.Name, Requirement = d.VersionRange, Consumers = new HashSet<string> { dep.Name } }));
  187. list.Value.AddRange(mod.Value.Conflicts.Select(d => new DependencyObject { Name = d.Name, Conflicts = d.VersionRange, Consumers = new HashSet<string> { dep.Name } }));
  188. }
  189. var depNames = new HashSet<string>();
  190. var final = new List<DependencyObject>();
  191. foreach (var dep in list.Value)
  192. { // agregate ranges and the like (1.3)
  193. if (!depNames.Contains(dep.Name))
  194. { // should add it
  195. depNames.Add(dep.Name);
  196. final.Add(dep);
  197. }
  198. else
  199. {
  200. var toMod = final.Where(d => d.Name == dep.Name).First();
  201. if (dep.Requirement != null)
  202. {
  203. toMod.Requirement = toMod.Requirement.Intersect(dep.Requirement);
  204. foreach (var consume in dep.Consumers)
  205. toMod.Consumers.Add(consume);
  206. }
  207. else if (dep.Conflicts != null)
  208. {
  209. if (toMod.Conflicts == null)
  210. toMod.Conflicts = dep.Conflicts;
  211. else
  212. toMod.Conflicts = new Range($"{toMod.Conflicts} || {dep.Conflicts}"); // there should be a better way to do this
  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 == BeatSaber.GameVersion && versionCheck.Approved)
  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 (!LoneFunctions.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 (!LoneFunctions.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 (LoneFunctions.GetRelativePath(targetFile.FullName, targetDir) == LoneFunctions.GetRelativePath(item.LocalPluginMeta?.Filename, 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[] { LoneFunctions.GetRelativePath(item.LocalPluginMeta.Filename, 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. LoneFunctions.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.Filename,
  463. Arguments = $"-nw={Process.GetCurrentProcess().Id}",
  464. UseShellExecute = false
  465. });
  466. }
  467. else
  468. LoneFunctions.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. }