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.

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