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.

753 lines
30 KiB

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