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.

718 lines
29 KiB

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