-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXboxOwnershipFilterPlugin.cs
More file actions
868 lines (756 loc) · 34.2 KB
/
Copy pathXboxOwnershipFilterPlugin.cs
File metadata and controls
868 lines (756 loc) · 34.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
using Playnite.SDK;
using Playnite.SDK.Events;
using Playnite.SDK.Plugins;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
using XboxOwnershipFilter.Models;
using XboxOwnershipFilter.Services;
using XboxOwnershipFilter.Settings;
using XboxOwnershipFilter.ViewModels;
using XboxOwnershipFilter.Views;
namespace XboxOwnershipFilter
{
public class XboxOwnershipFilterPlugin : GenericPlugin
{
private static readonly ILogger logger = LogManager.GetLogger();
private const string MenuSection = "Xbox Ownership Filter";
private readonly FilterSettingsViewModel settingsViewModel;
private readonly OwnershipStore store;
private readonly LibraryFilterService filterService;
private readonly XboxStoreClient storeClient;
private readonly AuditLog audit;
public override Guid Id { get; } = Guid.Parse("9f2c1a44-6b3d-4c8e-a1f7-2d5e8b0c3a91");
public XboxOwnershipFilterPlugin(IPlayniteAPI api) : base(api)
{
Properties = new GenericPluginProperties { HasSettings = true };
store = new OwnershipStore(GetPluginUserDataPath());
settingsViewModel = new FilterSettingsViewModel(this);
audit = new AuditLog(GetPluginUserDataPath());
filterService = new LibraryFilterService(api, store, () => settingsViewModel.Settings, audit);
storeClient = new XboxStoreClient(api, () => settingsViewModel.Settings.Market);
}
public override void OnLibraryUpdated(OnLibraryUpdatedEventArgs args)
{
var settings = settingsViewModel.Settings;
// Runs regardless of the configured action: a game that was un-excluded should
// get its playtime back as soon as it reappears, even if filtering is switched off.
try
{
filterService.RestorePendingPlaytime();
}
catch (Exception e)
{
logger.Error(e, "Failed to restore pending playtime.");
}
if (!settings.RunOnLibraryUpdate)
{
return;
}
// Exclude is destructive. Never let it fire unattended on the first run,
// before the user has had a chance to build an owned list.
if (settings.AnyDestructive && !settings.HasCompletedFirstRun)
{
PlayniteApi.Notifications.Add(new NotificationMessage(
"xof-firstrun",
"Xbox Ownership Filter is set to Exclude but has not been run manually yet. " +
"Open its settings and review the preview before enabling automatic runs.",
NotificationType.Info));
return;
}
filterService.Trigger = "LibraryUpdate";
RunFilter(interactive: false);
}
public override IEnumerable<MainMenuItem> GetMainMenuItems(GetMainMenuItemsArgs args)
{
// Two entries. Everything else, including the reports and the reset controls,
// lives inside the manager window rather than cluttering the Extensions menu.
yield return new MainMenuItem
{
// "@" places the item directly in Playnite's Extensions menu. Without it the
// item lands in the main menu root, which is exactly as intrusive as it sounds.
MenuSection = "@",
Description = "Xbox Ownership Filter",
Action = _ => OpenManager()
};
yield return new MainMenuItem
{
MenuSection = "@",
Description = "Xbox Ownership Filter: detect owned games",
Action = _ => RunDetection()
};
}
public override IEnumerable<GameMenuItem> GetGameMenuItems(GetGameMenuItemsArgs args)
{
var xboxGames = args.Games
.Where(g => g.PluginId == LibraryFilterService.XboxLibraryId)
.ToList();
if (xboxGames.Count == 0)
{
yield break;
}
yield return new GameMenuItem
{
Description = xboxGames.Count == 1
? "Mark as owned on Xbox"
: $"Mark {xboxGames.Count} games as owned on Xbox",
MenuSection = MenuSection,
Action = _ =>
{
foreach (var game in xboxGames)
{
store.MarkOwned(game.GameId);
}
store.Save();
filterService.Apply(dryRun: false);
}
};
yield return new GameMenuItem
{
Description = "Unmark as owned on Xbox",
MenuSection = MenuSection,
Action = _ =>
{
foreach (var game in xboxGames)
{
store.UnmarkOwned(game.GameId);
}
store.Save();
filterService.Apply(dryRun: false);
}
};
}
/// <summary>
/// Shown once, because a library missing its console and uninstalled titles looks like
/// a detection failure rather than an import setting. Dismissible permanently.
/// </summary>
private void ShowLibraryTipIfNeeded()
{
if (settingsViewModel.Settings.LibraryTipDismissed)
{
return;
}
var answer = PlayniteApi.Dialogs.ShowMessage(
"Playnite imports only your installed PC games from Xbox unless you tell it "
+ "otherwise, so console titles and anything not currently installed will be "
+ "missing from this list.\n\n"
+ "To include them:\n"
+ "Settings -> Library -> Configure integrations -> Xbox\n"
+ "then enable importing uninstalled games and console games.\n\n"
+ "Show this again next time?",
"Xbox Ownership Filter",
System.Windows.MessageBoxButton.YesNo);
if (answer == System.Windows.MessageBoxResult.No)
{
settingsViewModel.Settings.LibraryTipDismissed = true;
SavePluginSettings(settingsViewModel.Settings);
}
}
public void OpenManager()
{
var window = PlayniteApi.Dialogs.CreateWindow(new WindowCreationOptions
{
ShowMinimizeButton = false,
ShowMaximizeButton = true,
ShowCloseButton = true
});
ShowLibraryTipIfNeeded();
window.Title = "Xbox Ownership Filter";
window.Content = new ManagerView
{
DataContext = new ManagerViewModel(this, PlayniteApi, store, filterService, settingsViewModel.Settings)
};
window.Width = 1080;
window.Height = 700;
window.MinWidth = 900;
window.MinHeight = 560;
window.Owner = PlayniteApi.Dialogs.GetCurrentAppWindow();
window.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
ShowAndReturnFocus(window);
}
/// <summary>
/// Signs in if needed, then pulls the entitlement list and caches it. Runs on a
/// background thread behind Playnite's progress dialog, because paging through
/// entitlements and resolving the catalog takes several seconds.
/// </summary>
public void RunDetection()
{
var optionsVm = new DetectionOptionsViewModel
{
Options = settingsViewModel.Settings.DetectionOptions.Clone()
};
var optionsWindow = PlayniteApi.Dialogs.CreateWindow(new WindowCreationOptions
{
ShowMinimizeButton = false,
ShowMaximizeButton = false,
ShowCloseButton = true
});
optionsWindow.Title = "Detect owned games";
optionsWindow.Content = new DetectionOptionsView { DataContext = optionsVm };
optionsWindow.Width = 560;
optionsWindow.SizeToContent = System.Windows.SizeToContent.Height;
optionsWindow.ResizeMode = System.Windows.ResizeMode.NoResize;
optionsWindow.Owner = PlayniteApi.Dialogs.GetCurrentAppWindow();
optionsWindow.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
optionsWindow.ShowDialog();
if (!optionsVm.Confirmed)
{
return;
}
settingsViewModel.Settings.DetectionOptions = optionsVm.Options;
SavePluginSettings(settingsViewModel.Settings);
if (!storeClient.HasTicket && !storeClient.Login(silentOnly: false))
{
PlayniteApi.Dialogs.ShowErrorMessage(
"Sign-in did not complete, so nothing was detected.",
"Xbox Ownership Filter");
return;
}
DetectionResult detection = null;
Exception failure = null;
PlayniteApi.Dialogs.ActivateGlobalProgress(progress =>
{
try
{
progress.Text = "Contacting Microsoft Store services...";
var libraryPfns = filterService.GetXboxGames()
.Select(g => g.GameId)
.Where(id => !string.IsNullOrEmpty(id))
.ToList();
detection = storeClient
.GetOwnedAsync(optionsVm.Options, libraryPfns, store.State.TitleIdByPfn,
text => progress.Text = text)
.GetAwaiter()
.GetResult();
}
catch (Exception e)
{
failure = e;
}
},
new GlobalProgressOptions("Detecting owned Xbox games", false) { IsIndeterminate = true });
if (failure != null)
{
logger.Error(failure, "Detection failed.");
// The ticket may simply have expired; drop it so the next attempt signs in again.
storeClient.ClearTicket();
PlayniteApi.Dialogs.ShowErrorMessage(
$"Detection failed: {failure.Message}\n\nSee playnite.log for details.",
"Xbox Ownership Filter");
return;
}
var detected = detection.Set;
filterService.SaveDetection(detection);
// Cross-reference against the actual library before reporting anything, so the
// numbers describe this Playnite install rather than the Microsoft account.
var xboxGames = filterService.GetXboxGames();
var byGameId = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var game in xboxGames)
{
if (!string.IsNullOrEmpty(game.GameId) && !byGameId.ContainsKey(game.GameId))
{
byGameId[game.GameId] = game.Name;
}
}
foreach (var entry in detection.Entries)
{
foreach (var pair in byGameId)
{
var titleId = OwnershipSet.ExtractConsoleTitleId(pair.Key);
var hit = titleId != null
? string.Equals(titleId, entry.XboxTitleId, StringComparison.OrdinalIgnoreCase)
: string.Equals(pair.Key, entry.PackageFamilyName, StringComparison.OrdinalIgnoreCase);
if (hit)
{
entry.InLibrary = true;
entry.LibraryName = pair.Value;
break;
}
}
}
audit.WriteDetection(detection.Entries);
// Everything the run could not account for, with the identifiers it tried.
var unmatched = new List<UnmatchedRow>();
foreach (var game in xboxGames)
{
if (string.IsNullOrEmpty(game.GameId) || detected.Matches(game.GameId))
{
continue;
}
var consoleTitleId = OwnershipSet.ExtractConsoleTitleId(game.GameId);
string looked;
var haveLookup = detection.LibraryTitleIdByPfn.TryGetValue(game.GameId, out looked);
string legacyIds;
if (!detection.LibraryLegacyIdsByPfn.TryGetValue(game.GameId, out legacyIds))
{
legacyIds = string.Empty;
}
unmatched.Add(new UnmatchedRow
{
GameName = game.Name,
GameId = game.GameId,
IdKind = consoleTitleId != null ? "Console title id" : "Package family name",
TitleId = consoleTitleId ?? looked,
LegacyIds = legacyIds,
LookupResult = consoleTitleId != null
? "n/a"
: !haveLookup ? "not attempted"
: string.IsNullOrEmpty(looked) ? "catalog returned no title id"
: "title id found but you hold no entitlement for it",
Note = consoleTitleId != null
? "No entitlement matched this console title id."
: "No entitlement matched this package family name.",
});
}
audit.WriteUnmatched(unmatched);
var matched = xboxGames.Count(g => detected.Matches(g.GameId));
var settings = settingsViewModel.Settings;
if (detection.EditionMatches.Count > 0)
{
logger.Info($"{detection.EditionMatches.Count} entrie(s) matched a different "
+ "edition of a title you own.");
}
var summary =
$"Your Microsoft account holds {detection.Entries.Count} entitlement(s).\n\n"
+ $"{matched} of your {xboxGames.Count} Xbox library entries matched. "
+ $"The remaining {xboxGames.Count - matched} appear to be Game Pass.\n\n"
+ "Entitlements are broader than purchases: Games with Gold grants, demos, and "
+ "bundled items all count. Open the detection report to see the ownership type "
+ "and status behind each match.\n\n"
+ "Your manual ticks are untouched. Detection only ever adds.";
var vm = new DetectionResultViewModel
{
Headline = $"{matched} of your {xboxGames.Count} Xbox entries are owned.",
Detail = $"Your Microsoft account holds {detection.Entries.Count} entitlement(s). "
+ $"The remaining {xboxGames.Count - matched} library entries appear to be Game Pass.",
Breakdown = BuildBreakdown(detection),
Incomplete = detection.IsComplete ? string.Empty
: $"This run was incomplete ({detection.CatalogFailures} lookup(s) failed"
+ (detection.HitPageLimit ? ", page limit reached" : string.Empty)
+ "). The previous detection snapshot was kept, so nothing was lost; "
+ "run detection again when the connection is stable.",
Caveat = detection.CountByReason.ContainsKey(OwnershipReason.LicenceGrant)
? "If any of these look wrong, tick or untick the game in the manager and that "
+ "choice will stick through future runs. The detection report lists the SKU, "
+ "price, and granting purchase behind every verdict."
: "The detection report lists the SKU, price, and granting purchase behind "
+ "every verdict.",
};
var window = PlayniteApi.Dialogs.CreateWindow(new WindowCreationOptions
{
ShowMinimizeButton = false,
ShowMaximizeButton = false,
ShowCloseButton = true
});
window.Title = "Detection complete";
window.Content = new DetectionResultView { DataContext = vm };
window.Width = 560;
window.SizeToContent = System.Windows.SizeToContent.Height;
window.ResizeMode = System.Windows.ResizeMode.NoResize;
window.Owner = PlayniteApi.Dialogs.GetCurrentAppWindow();
window.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
ShowAndReturnFocus(window);
if (vm.Choice == DetectionChoice.Later)
{
return;
}
// Any choice other than "later" is consent to count detection toward ownership.
settings.UseAutoDetection = true;
SavePluginSettings(settings);
if (vm.Choice == DetectionChoice.Report)
{
OpenDetectionReport();
return;
}
if (vm.Choice == DetectionChoice.Review)
{
OpenManager();
return;
}
if (vm.Choice == DetectionChoice.Apply)
{
settings.NotOwnedAction = FilterAction.HideAndTag;
settings.HasCompletedFirstRun = true;
SavePluginSettings(settings);
filterService.Trigger = "DetectionApply";
RunFilter(interactive: true);
}
}
/// <summary>
/// Opens the CSV change log, or reports where it will be if nothing has run yet.
/// </summary>
private static string BuildBreakdown(DetectionResult detection)
{
var order = new[]
{
OwnershipReason.Purchased,
OwnershipReason.BundleComponent,
OwnershipReason.FreeToPlay,
OwnershipReason.Delisted,
OwnershipReason.AddOnOwner,
OwnershipReason.LicenceGrant,
OwnershipReason.Demo,
OwnershipReason.Inactive,
};
var labels = new Dictionary<OwnershipReason, string>
{
{ OwnershipReason.Purchased, "Bought outright" },
{ OwnershipReason.BundleComponent, "Included in something you bought" },
{ OwnershipReason.FreeToPlay, "Free to play" },
{ OwnershipReason.Delisted, "No longer sold (assumed owned)" },
{ OwnershipReason.AddOnOwner, "You own add-ons for it" },
{ OwnershipReason.LicenceGrant, "Games with Gold or promotional" },
{ OwnershipReason.Demo, "Demo, beta, or trial" },
{ OwnershipReason.Inactive, "Expired or revoked" },
};
var opts = detection.Options;
var counted = new Dictionary<OwnershipReason, bool>
{
{ OwnershipReason.Purchased, true },
{ OwnershipReason.BundleComponent, opts.CountBundleComponents },
{ OwnershipReason.FreeToPlay, opts.CountFreeToPlay },
{ OwnershipReason.Delisted, true },
{ OwnershipReason.AddOnOwner, opts.CountAddOnOwnership },
{ OwnershipReason.LicenceGrant, opts.CountLicenceGrants },
{ OwnershipReason.Demo, opts.CountDemos },
{ OwnershipReason.Inactive, false },
};
var lines = new List<string>();
foreach (var reason in order)
{
int n;
if (!detection.CountByReason.TryGetValue(reason, out n) || n == 0)
{
continue;
}
lines.Add($"{n,5} {labels[reason]}{(counted[reason] ? string.Empty : " (not counted)")}");
}
return string.Join("\n", lines);
}
public void OpenAuditLog()
{
OpenReport(audit.FilePath,
"Nothing has been logged yet. The log is written the first time the filter runs.");
}
public void OpenDetectionReport()
{
OpenReport(audit.DetectionFilePath,
"No detection report yet. Run detection first.");
}
/// <summary>
/// Runs the classification engine against a user-supplied CSV: no sign-in, no
/// network, no state or library changes. Exists so rule changes and other people's
/// bug reports can be tested in seconds against manufactured data instead of live
/// detection against one account.
/// </summary>
public void SimulateFromCsv()
{
var path = PlayniteApi.Dialogs.SelectFile("CSV files|*.csv");
if (string.IsNullOrEmpty(path))
{
return;
}
try
{
var output = DetectionSimulator.Run(
path, settingsViewModel.Settings.DetectionOptions.Clone());
OpenReport(output, "The simulation produced no output file.");
}
catch (Exception e)
{
logger.Error(e, "Simulation failed.");
PlayniteApi.Dialogs.ShowErrorMessage(
"Simulation failed: " + e.Message, "Xbox Ownership Filter");
}
}
/// <summary>
/// Discards the in-memory Store token. The next detection run signs back in without
/// asking, because Microsoft still has a session and the browser still has its
/// cookies. Useful for switching accounts on a shared machine only in combination
/// with the fuller option below.
/// </summary>
/// <summary>
/// Opens Advanced as its own window rather than an expander. Inline, it doubled the
/// height of a header whose settings are touched once and then left alone, at the
/// expense of the game list underneath.
/// </summary>
/// <summary>
/// Hands focus back to Playnite when a plugin window closes. Without it the desktop
/// picks whatever was behind, which after a few dialogs means the user has to go
/// looking for the window they were working in.
/// </summary>
private void ShowAndReturnFocus(System.Windows.Window window)
{
window.ShowDialog();
try
{
var main = PlayniteApi.Dialogs.GetCurrentAppWindow();
if (main != null)
{
main.Activate();
}
}
catch (Exception e)
{
logger.Error(e, "Could not return focus to Playnite.");
}
}
public void OpenAdvancedWindow(object dataContext, System.Windows.Window owner)
{
var window = PlayniteApi.Dialogs.CreateWindow(new WindowCreationOptions
{
ShowMinimizeButton = false,
ShowMaximizeButton = false,
ShowCloseButton = true
});
window.Title = "Xbox Ownership Filter: advanced";
window.Content = new AdvancedView { DataContext = dataContext };
window.DataContext = dataContext;
window.Width = 560;
window.Height = 460;
window.MinWidth = 440;
window.MinHeight = 320;
window.Owner = owner ?? PlayniteApi.Dialogs.GetCurrentAppWindow();
window.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
window.ShowDialog();
// Back to the manager rather than Playnite: the manager is still open behind it.
if (owner != null)
{
owner.Activate();
}
}
public void SignOut()
{
var hadTicket = storeClient.HasTicket;
storeClient.ClearTicket();
if (!hadTicket)
{
PlayniteApi.Dialogs.ShowMessage(
"There was no active sign-in to discard. The token only lives in memory, "
+ "so it is already gone whenever Playnite restarts.\n\n"
+ "Microsoft may still remember the account, which is why detection can "
+ "reconnect without prompting. Use \"Sign out and forget account\" to "
+ "clear that as well.",
"Xbox Ownership Filter");
return;
}
PlayniteApi.Dialogs.ShowMessage(
"The access token was discarded.\n\n"
+ "Microsoft still remembers this sign-in, so the next detection run will "
+ "reconnect without prompting. To be asked for an account again, use "
+ "\"Sign out and forget account\".\n\n"
+ "Your detection results and ownership list are untouched.",
"Xbox Ownership Filter");
}
/// <summary>
/// Ends the session at Microsoft's end as well as locally.
///
/// Deleting cookies alone leaves the account chooser still offering the account,
/// because the server remembers the session; visiting Microsoft's sign-out endpoint is
/// what actually ends it. Both are needed, and the order matters: sign out first,
/// because that request needs the cookies it is about to invalidate.
/// </summary>
public void SignOutAndForget()
{
var confirm = PlayniteApi.Dialogs.ShowMessage(
"Sign out of Microsoft in Playnite and forget this account?\n\n"
+ "The next detection run will ask which account to use. This affects only "
+ "this plugin's sign-in; your detection results and ownership list are "
+ "untouched, and your Xbox library plugin is unaffected.",
"Xbox Ownership Filter",
System.Windows.MessageBoxButton.YesNo);
if (confirm != System.Windows.MessageBoxResult.Yes)
{
return;
}
storeClient.ClearTicket();
Exception failure = null;
// Off the UI thread. NavigateAndWait blocks until the page loads, and the browser
// needs the UI thread to get there, so calling it directly from the manager window
// meant the work silently never happened.
PlayniteApi.Dialogs.ActivateGlobalProgress(progress =>
{
try
{
progress.Text = "Signing out of Microsoft...";
using (var view = PlayniteApi.WebViews.CreateOffscreenView())
{
// Load a page from the sign-in domain first. Until the browser has
// been somewhere, there is no cookie store to sign out of or clear,
// which is why this did nothing when run before any detection.
try
{
view.NavigateAndWait("https://login.live.com/");
}
catch (Exception e)
{
logger.Error(e, "Could not open the sign-in domain before signing out.");
}
try
{
view.NavigateAndWait(XboxStoreClient.LogoutUrl);
}
catch (Exception e)
{
logger.Error(e, "Microsoft sign-out endpoint could not be reached.");
}
progress.Text = "Clearing sign-in data...";
var domains = new[]
{
"login.live.com",
".live.com",
"live.com",
"account.live.com",
"account.microsoft.com",
"login.microsoftonline.com",
"login.microsoft.com",
".microsoft.com",
"microsoft.com",
"msauth.net",
"msftauth.net",
"xboxlive.com",
".xboxlive.com",
};
foreach (var domain in domains)
{
try
{
view.DeleteDomainCookies(domain);
}
catch (Exception e)
{
logger.Error(e, $"Could not clear cookies for {domain}.");
}
}
}
}
catch (Exception e)
{
failure = e;
}
}, new GlobalProgressOptions("Signing out...", false) { IsIndeterminate = true });
if (failure == null)
{
PlayniteApi.Dialogs.ShowMessage(
"Signed out and account forgotten. The next detection run will ask which "
+ "account to use.\n\nYour detection results and ownership list are untouched.",
"Xbox Ownership Filter");
return;
}
logger.Error(failure, "Full sign-out failed.");
PlayniteApi.Dialogs.ShowErrorMessage(
"The token was discarded, but the browser session could not be fully cleared. "
+ "See the log for details.",
"Xbox Ownership Filter");
}
public void OpenUnmatchedReport()
{
OpenReport(audit.UnmatchedFilePath,
"No unmatched report yet. Run detection first.");
}
private void OpenReport(string path, string missingMessage)
{
try
{
if (System.IO.File.Exists(path))
{
System.Diagnostics.Process.Start(path);
}
else
{
PlayniteApi.Dialogs.ShowMessage(
missingMessage + "\n\n" + path, "Xbox Ownership Filter");
}
}
catch (Exception e)
{
logger.Error(e, $"Could not open {path}.");
PlayniteApi.Dialogs.ShowErrorMessage(path, "Could not open the file");
}
}
public void ShowDryRun()
{
filterService.Trigger = "Preview";
var result = filterService.Apply(dryRun: true);
PlayniteApi.Dialogs.ShowMessage(FormatResult(result), "Preview");
}
private void RunFilter(bool interactive)
{
var settings = settingsViewModel.Settings;
if (settings.AnyDestructive && settings.ConfirmBeforeExclude && interactive)
{
var preview = filterService.Apply(dryRun: true);
var answer = PlayniteApi.Dialogs.ShowMessage(
$"This will permanently remove {preview.ExcludeCount} Xbox entries from your library " +
"and add them to Playnite's import exclusion list.\n\n" +
"They can be restored later from the manager window, and their playtime and " +
"last-played date are written back automatically once the Xbox library " +
"reimports them.\n\nContinue?",
"Confirm exclusion",
System.Windows.MessageBoxButton.YesNo);
if (answer != System.Windows.MessageBoxResult.Yes)
{
return;
}
}
try
{
var result = filterService.Apply(dryRun: false);
if (!settings.HasCompletedFirstRun)
{
settings.HasCompletedFirstRun = true;
SavePluginSettings(settings);
}
if (interactive)
{
PlayniteApi.Dialogs.ShowMessage(FormatResult(result), "Done");
}
else
{
logger.Info($"Filter pass affected {result.Affected.Count} games.");
}
}
catch (Exception e)
{
logger.Error(e, "Filter pass failed.");
if (interactive)
{
PlayniteApi.Dialogs.ShowErrorMessage(e.Message, "Xbox Ownership Filter");
}
}
}
private static string FormatResult(FilterResult result)
{
var verb = result.WasDryRun ? "would be" : "were";
string Count(PlayabilityCategory c) =>
result.CountByCategory.TryGetValue(c, out var n) ? n.ToString() : "0";
var text =
$"{result.TotalXboxCount} Xbox entries.\n\n" +
$" owned, PC build : {Count(PlayabilityCategory.OwnedPc)}\n" +
$" owned, console : {Count(PlayabilityCategory.OwnedConsole)}\n" +
$" not owned : {Count(PlayabilityCategory.NotOwned)}\n\n" +
$"{result.Affected.Count} {verb} affected";
if (result.ExcludeCount > 0)
{
text += $", of which {result.ExcludeCount} {verb} deleted";
}
text += ".\n";
if (result.Restored.Count > 0)
{
text += $"{result.Restored.Count} {verb} restored.\n";
}
if (result.Affected.Count > 0)
{
text += "\n" + string.Join("\n", result.Affected.Take(25));
if (result.Affected.Count > 25)
{
text += $"\n... and {result.Affected.Count - 25} more.";
}
}
return text;
}
public override ISettings GetSettings(bool firstRunSettings) => settingsViewModel;
public override UserControl GetSettingsView(bool firstRunSettings) => new FilterSettingsView();
}
}