StoreExtensionHelper.cs
1 // Copyright (c) Microsoft Corporation 2 // The Microsoft Corporation licenses this file to you under the MIT license. 3 // See the LICENSE file in the project root for more information. 4 5 using System; 6 using System.ComponentModel; 7 using System.Linq; 8 using System.Threading.Tasks; 9 using System.Windows.Input; 10 using ManagedCommon; 11 using Windows.Management.Deployment; 12 using Windows.System; 13 14 namespace Microsoft.PowerToys.Settings.UI.Helpers 15 { 16 /// <summary> 17 /// Helper class to manage installation status and installation command for a Microsoft Store extension. 18 /// </summary> 19 public class StoreExtensionHelper : INotifyPropertyChanged 20 { 21 private readonly string _packageFamilyName; 22 private readonly string _storeUri; 23 private readonly string _extensionName; 24 private bool? _isInstalled; 25 26 public event PropertyChangedEventHandler PropertyChanged; 27 28 public StoreExtensionHelper(string packageFamilyName, string storeUri, string extensionName) 29 { 30 _packageFamilyName = packageFamilyName ?? throw new ArgumentNullException(nameof(packageFamilyName)); 31 _storeUri = storeUri ?? throw new ArgumentNullException(nameof(storeUri)); 32 _extensionName = extensionName ?? throw new ArgumentNullException(nameof(extensionName)); 33 InstallCommand = new AsyncCommand(InstallExtensionAsync); 34 } 35 36 /// <summary> 37 /// Gets a value indicating whether the extension is installed. 38 /// </summary> 39 public bool IsInstalled 40 { 41 get 42 { 43 if (!_isInstalled.HasValue) 44 { 45 _isInstalled = CheckExtensionInstalled(); 46 } 47 48 return _isInstalled.Value; 49 } 50 } 51 52 /// <summary> 53 /// Gets the command to install the extension. 54 /// </summary> 55 public ICommand InstallCommand { get; } 56 57 /// <summary> 58 /// Refreshes the installation status of the extension. 59 /// </summary> 60 public void RefreshStatus() 61 { 62 _isInstalled = null; 63 OnPropertyChanged(nameof(IsInstalled)); 64 } 65 66 private bool CheckExtensionInstalled() 67 { 68 try 69 { 70 var packageManager = new PackageManager(); 71 var packages = packageManager.FindPackagesForUser(string.Empty, _packageFamilyName); 72 return packages.Any(); 73 } 74 catch (Exception ex) 75 { 76 Logger.LogError($"Failed to check extension installation status: {_packageFamilyName}", ex); 77 return false; 78 } 79 } 80 81 private async Task InstallExtensionAsync() 82 { 83 try 84 { 85 await Launcher.LaunchUriAsync(new Uri(_storeUri)); 86 } 87 catch (Exception ex) 88 { 89 Logger.LogError($"Failed to open {_extensionName} extension store page", ex); 90 } 91 } 92 93 protected virtual void OnPropertyChanged(string propertyName) 94 { 95 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 96 } 97 } 98 }