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 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 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. if (msinfo.Features.FirstOrDefault(f => f is NoUpdateFeature) != null)
  177. { // disable updating, by only matching self, so that dependencies can still be resolved
  178. dep.Requirement = new Range(msinfo.Version.ToString());
  179. }
  180. depList.Value.Add(dep);
  181. }
  182. }
  183. foreach (var meta in PluginLoader.ignoredPlugins.Keys)
  184. { // update ignored
  185. if (meta.Id != null)
  186. { // updatable
  187. var dep = new DependencyObject
  188. {
  189. Name = meta.Id,
  190. Version = meta.Version,
  191. Requirement = new Range($">={meta.Version}"),
  192. LocalPluginMeta = meta
  193. };
  194. if (meta.Features.FirstOrDefault(f => f is NoUpdateFeature) != null)
  195. { // disable updating, by only matching self
  196. dep.Requirement = new Range(meta.Version.ToString());
  197. }
  198. depList.Value.Add(dep);
  199. }
  200. }
  201. foreach (var meta in DisabledPlugins)
  202. { // update ignored
  203. if (meta.Id != null)
  204. { // updatable
  205. var dep = new DependencyObject
  206. {
  207. Name = meta.Id,
  208. Version = meta.Version,
  209. Requirement = new Range($">={meta.Version}"),
  210. LocalPluginMeta = meta
  211. };
  212. if (meta.Features.FirstOrDefault(f => f is NoUpdateFeature) != null)
  213. { // disable updating, by only matching self
  214. dep.Requirement = new Range(meta.Version.ToString());
  215. }
  216. depList.Value.Add(dep);
  217. }
  218. }
  219. #pragma warning disable CS0618 // Type or member is obsolete
  220. foreach (var plug in Plugins)
  221. { // throw these in the updater on the off chance that they are set up properly
  222. try
  223. {
  224. var dep = new DependencyObject
  225. {
  226. Name = plug.Name,
  227. Version = new Version(plug.Version),
  228. Requirement = new Range($">={plug.Version}"),
  229. IsLegacy = true,
  230. LocalPluginMeta = null
  231. };
  232. depList.Value.Add(dep);
  233. }
  234. catch (Exception e)
  235. {
  236. Logger.updater.Warn($"Error trying to add legacy plugin {plug.Name} to updater");
  237. Logger.updater.Warn(e);
  238. }
  239. }
  240. #pragma warning restore CS0618 // Type or member is obsolete
  241. foreach (var dep in depList.Value)
  242. Logger.updater.Debug($"Phantom Dependency: {dep}");
  243. yield return ResolveDependencyRanges(depList);
  244. foreach (var dep in depList.Value)
  245. Logger.updater.Debug($"Dependency: {dep}");
  246. yield return ResolveDependencyPresence(depList);
  247. foreach (var dep in depList.Value)
  248. Logger.updater.Debug($"Dependency: {dep}");
  249. CheckDependencies(depList);
  250. onComplete?.Invoke(depList);
  251. if (!ModListPresent && SelfConfig.Updates_.AutoUpdate_)
  252. StartDownload(depList.Value);
  253. }
  254. internal IEnumerator ResolveDependencyRanges(Ref<List<DependencyObject>> list)
  255. {
  256. for (int i = 0; i < list.Value.Count; i++)
  257. { // Grab dependencies (1.2)
  258. var dep = list.Value[i];
  259. var mod = new Ref<ApiEndpoint.Mod>(null);
  260. yield return GetModInfo(dep.Name, "", mod);
  261. try { mod.Verify(); }
  262. catch (Exception e)
  263. {
  264. Logger.updater.Error($"Error getting info for {dep.Name}");
  265. if (SelfConfig.Debug_.ShowHandledErrorStackTraces_)
  266. Logger.updater.Error(e);
  267. dep.MetaRequestFailed = true;
  268. continue;
  269. }
  270. list.Value.AddRange(mod.Value.Dependencies.Select(m => new DependencyObject
  271. {
  272. Name = m.Name,
  273. Requirement = new Range($"^{m.Version}"),
  274. Consumers = new HashSet<string> { dep.Name }
  275. }));
  276. // currently no conflicts exist in BeatMods
  277. //list.Value.AddRange(mod.Value.Links.Dependencies.Select(d => new DependencyObject { Name = d.Name, Requirement = d.VersionRange, Consumers = new HashSet<string> { dep.Name } }));
  278. //list.Value.AddRange(mod.Value.Links.Conflicts.Select(d => new DependencyObject { Name = d.Name, Conflicts = d.VersionRange, Consumers = new HashSet<string> { dep.Name } }));
  279. }
  280. var depNames = new HashSet<string>();
  281. var final = new List<DependencyObject>();
  282. foreach (var dep in list.Value)
  283. { // agregate ranges and the like (1.3)
  284. if (!depNames.Contains(dep.Name))
  285. { // should add it
  286. depNames.Add(dep.Name);
  287. final.Add(dep);
  288. }
  289. else
  290. {
  291. var toMod = final.First(d => d.Name == dep.Name);
  292. if (dep.Requirement != null)
  293. {
  294. toMod.Requirement = toMod.Requirement.Intersect(dep.Requirement);
  295. foreach (var consume in dep.Consumers)
  296. toMod.Consumers.Add(consume);
  297. }
  298. if (dep.Conflicts != null)
  299. {
  300. toMod.Conflicts = toMod.Conflicts == null
  301. ? dep.Conflicts
  302. : new Range($"{toMod.Conflicts} || {dep.Conflicts}");
  303. }
  304. }
  305. }
  306. list.Value = final;
  307. }
  308. internal IEnumerator ResolveDependencyPresence(Ref<List<DependencyObject>> list)
  309. {
  310. foreach(var dep in list.Value)
  311. {
  312. dep.Has = dep.Version != null; // dep.Version is only not null if its already installed
  313. if (dep.MetaRequestFailed)
  314. {
  315. Logger.updater.Warn($"{dep.Name} info request failed, not trying again");
  316. continue;
  317. }
  318. var modsMatching = new Ref<List<ApiEndpoint.Mod>>(null);
  319. yield return GetModVersionsMatching(dep.Name, dep.Requirement, modsMatching);
  320. try { modsMatching.Verify(); }
  321. catch (Exception e)
  322. {
  323. Logger.updater.Error($"Error getting mod list for {dep.Name}");
  324. if (SelfConfig.Debug_.ShowHandledErrorStackTraces_)
  325. Logger.updater.Error(e);
  326. dep.MetaRequestFailed = true;
  327. continue;
  328. }
  329. var ver = modsMatching.Value
  330. .NonNull() // entry is not null
  331. .Where(versionCheck => versionCheck.GameVersion == BeatSaber.GameVersion) // game version matches
  332. .Where(approvalCheck => approvalCheck.Status == ApiEndpoint.Mod.ApprovedStatus) // version approved
  333. // TODO: fix; it seems wrong somehow
  334. .Where(conflictsCheck => dep.Conflicts == null || !dep.Conflicts.IsSatisfied(conflictsCheck.Version)) // not a conflicting version
  335. .Select(mod => mod.Version).Max(); // (2.1) get the max version
  336. dep.Resolved = ver != null;
  337. if (dep.Resolved) dep.ResolvedVersion = ver; // (2.2)
  338. dep.Has = dep.Resolved && dep.Version == dep.ResolvedVersion;
  339. }
  340. }
  341. internal void CheckDependencies(Ref<List<DependencyObject>> list)
  342. {
  343. var toDl = new List<DependencyObject>();
  344. foreach (var dep in list.Value)
  345. { // figure out which ones need to be downloaded (3.1)
  346. if (dep.Resolved)
  347. {
  348. Logger.updater.Debug($"Resolved: {dep}");
  349. if (!dep.Has)
  350. {
  351. Logger.updater.Debug($"To Download: {dep}");
  352. toDl.Add(dep);
  353. }
  354. }
  355. else if (!dep.Has)
  356. {
  357. if (dep.Version != null && dep.Requirement.IsSatisfied(dep.Version))
  358. Logger.updater.Notice($"Mod {dep.Name} running a newer version than is on BeatMods ({dep.Version})");
  359. else
  360. Logger.updater.Warn($"Could not resolve dependency {dep}");
  361. }
  362. }
  363. Logger.updater.Debug($"To Download {string.Join(", ", toDl.Select(d => $"{d.Name}@{d.ResolvedVersion}"))}");
  364. list.Value = toDl;
  365. }
  366. internal delegate void DownloadStart(DependencyObject obj);
  367. internal delegate void DownloadProgress(DependencyObject obj, long totalBytes, long currentBytes, double progress);
  368. internal delegate void DownloadFailed(DependencyObject obj, string error);
  369. internal delegate void DownloadFinish(DependencyObject obj);
  370. /// <summary>
  371. /// This will still be called even if there was an error. Called after all three download/install attempts, or after a successful installation.
  372. /// ALWAYS called.
  373. /// </summary>
  374. /// <param name="obj"></param>
  375. /// <param name="didError"></param>
  376. internal delegate void InstallFinish(DependencyObject obj, bool didError);
  377. /// <summary>
  378. /// This can be called multiple times
  379. /// </summary>
  380. /// <param name="obj"></param>
  381. /// <param name="error"></param>
  382. internal delegate void InstallFailed(DependencyObject obj, Exception error);
  383. internal void StartDownload(IEnumerable<DependencyObject> download, DownloadStart downloadStart = null,
  384. DownloadProgress downloadProgress = null, DownloadFailed downloadFail = null, DownloadFinish downloadFinish = null,
  385. InstallFailed installFail = null, InstallFinish installFinish = null)
  386. {
  387. foreach (var item in download)
  388. StartCoroutine(UpdateModCoroutine(item, downloadStart, downloadProgress, downloadFail, downloadFinish, installFail, installFinish));
  389. }
  390. private static IEnumerator UpdateModCoroutine(DependencyObject item, DownloadStart downloadStart,
  391. DownloadProgress progress, DownloadFailed dlFail, DownloadFinish finish,
  392. InstallFailed installFail, InstallFinish installFinish)
  393. { // (3.2)
  394. Logger.updater.Debug($"Release: {BeatSaber.ReleaseType}");
  395. var mod = new Ref<ApiEndpoint.Mod>(null);
  396. yield return GetModInfo(item.Name, item.ResolvedVersion.ToString(), mod);
  397. try { mod.Verify(); }
  398. catch (Exception e)
  399. {
  400. Logger.updater.Error($"Error occurred while trying to get information for {item}");
  401. if (SelfConfig.Debug_.ShowHandledErrorStackTraces_)
  402. Logger.updater.Error(e);
  403. yield break;
  404. }
  405. var releaseName = BeatSaber.ReleaseType == BeatSaber.Release.Steam
  406. ? ApiEndpoint.Mod.DownloadsObject.TypeSteam : ApiEndpoint.Mod.DownloadsObject.TypeOculus;
  407. var platformFile = mod.Value.Downloads.First(f => f.Type == ApiEndpoint.Mod.DownloadsObject.TypeUniversal || f.Type == releaseName);
  408. string url = ApiEndpoint.BeatModBase + platformFile.Path;
  409. Logger.updater.Debug($"URL = {url}");
  410. const int maxTries = 3;
  411. int tries = maxTries;
  412. while (tries > 0)
  413. {
  414. if (tries-- != maxTries)
  415. Logger.updater.Debug("Re-trying download...");
  416. using (var stream = new MemoryStream())
  417. using (var request = UnityWebRequest.Get(url))
  418. using (var taskTokenSource = new CancellationTokenSource())
  419. {
  420. var dlh = new StreamDownloadHandler(stream, (int i1, int i2, double d) => progress?.Invoke(item, i1, i2, d));
  421. request.downloadHandler = dlh;
  422. downloadStart?.Invoke(item);
  423. Logger.updater.Debug("Sending request");
  424. //Logger.updater.Debug(request?.downloadHandler?.ToString() ?? "DLH==NULL");
  425. yield return request.SendWebRequest();
  426. Logger.updater.Debug("Download finished");
  427. if (request.isNetworkError)
  428. {
  429. Logger.updater.Error("Network error while trying to update mod");
  430. Logger.updater.Error(request.error);
  431. dlFail?.Invoke(item, request.error);
  432. taskTokenSource.Cancel();
  433. continue;
  434. }
  435. if (request.isHttpError)
  436. {
  437. Logger.updater.Error("Server returned an error code while trying to update mod");
  438. Logger.updater.Error(request.error);
  439. dlFail?.Invoke(item, request.error);
  440. taskTokenSource.Cancel();
  441. continue;
  442. }
  443. finish?.Invoke(item);
  444. stream.Seek(0, SeekOrigin.Begin); // reset to beginning
  445. var downloadTask = Task.Run(() =>
  446. { // use slightly more multi threaded approach than co-routines
  447. // ReSharper disable once AccessToDisposedClosure
  448. ExtractPluginAsync(stream, item, platformFile);
  449. }, taskTokenSource.Token);
  450. while (!(downloadTask.IsCompleted || downloadTask.IsCanceled || downloadTask.IsFaulted))
  451. yield return null; // pause co-routine until task is done
  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(BeatSaber.InstallPath, "IPA", Path.GetRandomFileName() + "_Pending");
  531. Directory.CreateDirectory(targetDir);
  532. var eventualOutput = Path.Combine(BeatSaber.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, BeatSaber.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, BeatSaber.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(BeatSaber.InstallPath));
  595. var deleteFile = Path.Combine(BeatSaber.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. }