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.

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