Skip to content

Commit

Permalink
NR Update Microsoft.Graph to v5
Browse files Browse the repository at this point in the history
  • Loading branch information
jbe2277 committed Dec 30, 2023
1 parent dd04c37 commit 220c642
Show file tree
Hide file tree
Showing 11 changed files with 72 additions and 79 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Microsoft.AppCenter.Crashes;
using System.Waf.Applications;
using System.Waf.Applications;
using System.Waf.Applications.Services;
using System.Windows.Input;
using Waf.NewsReader.Applications.Properties;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,4 @@ public interface IWebStorageService : INotifyPropertyChanged
Task<string?> UploadFile(Stream source);
}

public sealed record UserAccount(string UserName, string Email);
public sealed record UserAccount(string UserName, string? Email);
Original file line number Diff line number Diff line change
@@ -1,7 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application android:allowBackup="true" android:icon="@mipmap/appicon" android:roundIcon="@mipmap/appicon_round" android:supportsRtl="true" android:usesCleartextTraffic="true">
<activity android:name="microsoft.identity.client.BrowserTabActivity" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="wafe5b8cee6-8ba0-46c5-96ef-a3c8a1e2bb26" android:host="auth" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<queries>
<intent>
<action android:name="android.support.customtabs.action.CustomTabsService" />
</intent>
</queries>

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
using Autofac;
using Waf.NewsReader.MauiSystem.Platforms.Android.Services;
using Waf.NewsReader.Presentation.Services;

namespace Waf.NewsReader.MauiSystem.Platforms.Android;

internal sealed class AndroidModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<IdentityService>().As<IIdentityService>().SingleInstance();
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
using Autofac;
using Waf.NewsReader.Applications.Services;
using Waf.NewsReader.MauiSystem.Platforms.iOS.Services;
using Waf.NewsReader.Presentation.Services;

namespace Waf.NewsReader.MauiSystem.Platforms.iOS;

internal sealed class IosModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<IdentityService>().As<IIdentityService>().SingleInstance();
builder.RegisterType<LocalizationService>().As<ILocalizationService>().SingleInstance();
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
<PackageReference Include="Microsoft.Maui.Controls" Version="$(MauiVersion)" />
<PackageReference Include="Microsoft.Maui.Controls.Compatibility" Version="$(MauiVersion)" />

<PackageReference Include="Microsoft.Graph" Version="4.54.0" />
<PackageReference Include="Microsoft.Identity.Client" Version="4.55.0" />
<PackageReference Include="Microsoft.Graph" Version="5.37.0" />
<PackageReference Include="Microsoft.Identity.Client" Version="4.58.1" />
<PackageReference Include="System.ServiceModel.Syndication" Version="8.0.0" />
</ItemGroup>

Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
using Microsoft.AppCenter.Crashes;
using Microsoft.Graph;
using Microsoft.Graph;
using Microsoft.Identity.Client;
using System.Net;
using System.Net.Http.Headers;
using Waf.NewsReader.Applications;
using Microsoft.Kiota.Abstractions.Authentication;
using Waf.NewsReader.Applications.Services;

namespace Waf.NewsReader.Presentation.Services;
Expand All @@ -26,15 +23,19 @@ internal sealed partial class WebStorageService : Model, IWebStorageService
private GraphServiceClient? graphClient;
private UserAccount? currentAccount;

public WebStorageService(IIdentityService? identityService = null)
public WebStorageService()
{
string? appId = null;
GetApplicationId(ref appId);
if (appId != null)
{
var builder = PublicClientApplicationBuilder.Create(appId);
builder.WithRedirectUri("wafe5b8cee6-8ba0-46c5-96ef-a3c8a1e2bb26://auth");
identityService?.Build(builder);
#if ANDROID
builder.WithParentActivityOrWindow(() => Platform.CurrentActivity);
#elif IOS
builder.WithIosKeychainSecurityGroup(Foundation.NSBundle.MainBundle.BundleIdentifier);
#endif
publicClient = builder.Build();
}
}
Expand All @@ -58,8 +59,7 @@ public async Task<bool> TrySilentSignIn()
}
catch (Exception ex)
{
Log.Default.TrackError(ex, "Silent login failed");
// Ignore (e.g. no internet access)
Log.Default.TrackError(ex, "Silent login failed"); // Ignore (e.g. no internet access)
}
return false;
}
Expand All @@ -71,8 +71,7 @@ public async Task SignIn()
{
try
{
var interactiveRequest = publicClient.AcquireTokenInteractive(scopes);
await interactiveRequest.ExecuteAsync();
await publicClient.AcquireTokenInteractive(scopes).ExecuteAsync();
}
catch (MsalClientException ex) when (ex.ErrorCode == MsalError.AuthenticationCanceledError)
{
Expand All @@ -95,7 +94,7 @@ public async Task SignOut()

private async Task<string?> TrySilentSignInCore()
{
if (publicClient == null) return null;
if (publicClient is null) return null;
try
{
var accounts = await publicClient.GetAccountsAsync();
Expand All @@ -114,42 +113,60 @@ public async Task SignOut()

private async Task InitGraphClient()
{
graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(
async requestMessage =>
{
if (publicClient == null) return;
var accounts = await publicClient.GetAccountsAsync().ConfigureAwait(false);
if (!accounts.Any()) return;
var result = await publicClient.AcquireTokenSilent(scopes, accounts.First()).ExecuteAsync().ConfigureAwait(false);
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
}));
var user = await graphClient.Me.Request().GetAsync();
CurrentAccount = new(!string.IsNullOrEmpty(user.DisplayName) ? user.DisplayName : user.UserPrincipalName, user.Mail);
if (publicClient is null) return;
var authenticationProvider = new BaseBearerTokenAuthenticationProvider(new TokenProvider(publicClient));
graphClient = new GraphServiceClient(authenticationProvider);
var user = await graphClient.Me.GetAsync();
ArgumentNullException.ThrowIfNull(user);
CurrentAccount = new(!string.IsNullOrEmpty(user.DisplayName) ? user.DisplayName : user.UserPrincipalName ?? "", user.Mail);
}

public async Task<(Stream? stream, string? cTag)> DownloadFile(string? cTag)
{
if (graphClient == null) return default;
var item = graphClient.Me.Drive.Special.AppRoot.ItemWithPath(dataFileName);
try
var item = await GetItem(dataFileName).ConfigureAwait(false);
var metaItem = await item.GetAsync().ConfigureAwait(false);
ArgumentNullException.ThrowIfNull(metaItem);
if (metaItem.CTag != cTag)
{
var metaItem = await item.Request().GetAsync().ConfigureAwait(false);
if (metaItem.CTag != cTag)
{
return (await item.Content.Request().GetAsync().ConfigureAwait(false), metaItem.CTag);
}
return (await item.Content.GetAsync().ConfigureAwait(false), metaItem.CTag);
}
catch (ServiceException ex) when (ex.StatusCode == HttpStatusCode.NotFound) { }
// TODO: catch (ServiceException ex) when (ex.StatusCode == HttpStatusCode.NotFound) { }
return default;
}

public async Task<string?> UploadFile(Stream source)
{
if (graphClient == null) return null;
var driveItem = await graphClient.Me.Drive.Special.AppRoot.ItemWithPath(dataFileName)
.Content.Request().PutAsync<DriveItem>(source).ConfigureAwait(false);
return driveItem.CTag;
var item = await GetItem(dataFileName).ConfigureAwait(false);
var newItem = await item.Content.PutAsync(source).ConfigureAwait(false);
ArgumentNullException.ThrowIfNull(newItem);
return newItem.CTag;
}

private async Task<CustomDriveItemItemRequestBuilder> GetItem(string fileName)
{
if (graphClient is null) throw new InvalidOperationException("graphClient is null");
var driveItem = await graphClient.Me.Drive.GetAsync().ConfigureAwait(false);
ArgumentNullException.ThrowIfNull(driveItem);
var appRootFolder = await graphClient.Drives[driveItem.Id].Special["AppRoot"].GetAsync().ConfigureAwait(false);
ArgumentNullException.ThrowIfNull(appRootFolder);
return graphClient.Drives[driveItem.Id].Items[appRootFolder.Id].ItemWithPath(fileName);
}

static partial void GetApplicationId(ref string? applicationId);


private sealed class TokenProvider(IPublicClientApplication publicClient) : IAccessTokenProvider
{
public AllowedHostsValidator AllowedHostsValidator { get; } = new();

public async Task<string> GetAuthorizationTokenAsync(Uri uri, Dictionary<string, object>? additionalAuthenticationContext = null, CancellationToken cancellationToken = default)
{
var accounts = await publicClient.GetAccountsAsync().ConfigureAwait(false);
if (!accounts.Any()) return "";
var result = await publicClient.AcquireTokenSilent(scopes, accounts.First()).ExecuteAsync(cancellationToken).ConfigureAwait(false);
return result.AccessToken;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public async Task PushAsync(object page)
// Pushing of a page which already exists in the navigation stack is not allowed -> InvalidOperationException: 'Page must not already have a parent.'
// If the specified page already exists in the navigaton stack then remove all pages after the page and pop to it.
if (idx == navi.NavigationStack.Count - 1) return;
for (int i = 0; i < navi.NavigationStack.Count - idx - 2; i++) navi.RemovePage(navi.NavigationStack[navi.NavigationStack.Count - 2]);
for (int i = 0; i < navi.NavigationStack.Count - idx - 2; i++) navi.RemovePage(navi.NavigationStack[^2]);
await navi.PopAsync();
}
else await navi.PushAsync((Page)page);
Expand Down

0 comments on commit 220c642

Please sign in to comment.