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.

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