Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
WPF: DropboxCoreService - Added initialization, app unlinking, fixed …
…a lot of bugs. ResumePlaybackPresenter - Now refreshing cloud login status.
  • Loading branch information
ycastonguay committed Oct 26, 2013
1 parent affbcc4 commit 087c047
Show file tree
Hide file tree
Showing 7 changed files with 225 additions and 69 deletions.
1 change: 1 addition & 0 deletions MPfm/MPfm.Library/MPfm.Library.csproj
Expand Up @@ -183,6 +183,7 @@
<Compile Include="Objects\Folder.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Services\DropboxCoreService.cs" />
<Compile Include="Services\Exceptions\CloudAppNotLinkedException.cs" />
<Compile Include="Services\Interfaces\ICloudLibraryService.cs" />
<Compile Include="UpdateLibrary\UpdateLibraryProgressDataSong.cs" />
<Compile Include="UpdateLibrary\UpdateLibraryFinishedData.cs" />
Expand Down
112 changes: 89 additions & 23 deletions MPfm/MPfm.Library/Services/DropboxCoreService.cs
Expand Up @@ -19,6 +19,7 @@
using MPfm.Core;
using MPfm.Core.Helpers;
using MPfm.Library.Objects;
using MPfm.Library.Services.Exceptions;
using MPfm.Sound.Playlists;
using Newtonsoft.Json;
#if !IOS && !ANDROID && !WINDOWS_PHONE
Expand Down Expand Up @@ -51,6 +52,8 @@ public class DropboxCoreService : ICloudLibraryService
private DropboxServiceProvider _dropboxServiceProvider;
private OAuthToken _oauthToken;

public bool HasLinkedAccount { get; private set; }

public event CloudDataChanged OnCloudDataChanged;
public event CloudAuthenticationStatusChanged OnCloudAuthenticationStatusChanged;

Expand All @@ -65,30 +68,68 @@ public class DropboxCoreService : ICloudLibraryService

private void Initialize()
{
}
try
{
Console.WriteLine("DropboxCoreService - Initialize - Initializing service...");
var diskToken = LoadTokenFromDisk();
var oauthAccessToken = new OAuthToken(diskToken.Value, diskToken.Secret);

public bool HasLinkedAccount { get; private set; }
_dropboxServiceProvider = new DropboxServiceProvider(DropboxAppKey, DropboxAppSecret, AccessLevel.AppFolder);
_dropbox = _dropboxServiceProvider.GetApi(oauthAccessToken.Value, oauthAccessToken.Secret);
//dropbox.Locale = CultureInfo.CurrentUICulture.IetfLanguageTag;
HasLinkedAccount = true;
Console.WriteLine("DropboxCoreService - Initialize - Finished initializing service!");
}
catch (AggregateException ae)
{
HasLinkedAccount = false;
ae.Handle(ex =>
{
if (ex is DropboxApiException)
{
Console.WriteLine("DropboxCoreService - Initialize - Exception: {0}", ex);
return true;
}
// Ignore exceptions; if we cannot login on initialize, the user will have to relink the app later.
// The UI should check the HasLinkedAccount property to see if Dropbox is available.
return true;
});
}
catch (Exception ex)
{
// Ignore exceptions (see previous comment)
}
}

public void LinkApp(object view)
{
try
{
// Create provider
_dropboxServiceProvider = new DropboxServiceProvider(DropboxAppKey, DropboxAppSecret, AccessLevel.AppFolder);

// Update status
if (OnCloudAuthenticationStatusChanged != null)
OnCloudAuthenticationStatusChanged(CloudAuthenticationStatusType.GetRequestToken);

// If the Initialize method has failed the service provider will be null!
if(_dropboxServiceProvider == null)
_dropboxServiceProvider = new DropboxServiceProvider(DropboxAppKey, DropboxAppSecret, AccessLevel.AppFolder);

// Authorization without callback url
_oauthToken = _dropboxServiceProvider.OAuthOperations.FetchRequestTokenAsync(null, null).Result;

// Update status
if (OnCloudAuthenticationStatusChanged != null)
OnCloudAuthenticationStatusChanged(CloudAuthenticationStatusType.OpenWebBrowser);

// Try to get a previously saved token
var token = LoadToken();
AuthenticationToken token = null;
try
{
// Try to get a previously saved token
token = LoadTokenFromDisk();
}
catch
{
// Ignore exception; use the web browser to get a new token
}

if (token == null)
{
// Open web browser for authentication
Expand All @@ -104,6 +145,7 @@ public void LinkApp(object view)
}
catch (AggregateException ae)
{
HasLinkedAccount = false;
ae.Handle(ex =>
{
if (ex is DropboxApiException)
Expand All @@ -118,50 +160,49 @@ public void LinkApp(object view)

public void ContinueLinkApp()
{
ContinueLinkApp(null);
}

private void ContinueLinkApp(AuthenticationToken token)
{
try
{
// Get access token either from parameter or from API
OAuthToken oauthAccessToken = null;
if (token == null)
{
Console.Write("Getting access token...");
AuthorizedRequestToken requestToken = new AuthorizedRequestToken(_oauthToken, null);
oauthAccessToken = _dropboxServiceProvider.OAuthOperations.ExchangeForAccessTokenAsync(requestToken, null).Result;
Console.WriteLine("Done - FetchAccessToken - secret: {0} value: {1}", oauthAccessToken.Secret, oauthAccessToken.Value);
}
else
{
oauthAccessToken = new OAuthToken(token.Value, token.Secret);
}

// Update status
if (OnCloudAuthenticationStatusChanged != null)
OnCloudAuthenticationStatusChanged(CloudAuthenticationStatusType.RequestAccessToken);

// Connect to Dropbox API
// Get Dropbox API instance
_dropbox = _dropboxServiceProvider.GetApi(oauthAccessToken.Value, oauthAccessToken.Secret);
//dropbox.Locale = CultureInfo.CurrentUICulture.IetfLanguageTag;

// Get user name from profile
// Test Dropbox API connection (get user name from profile)
DropboxProfile profile = _dropbox.GetUserProfileAsync().Result;
Console.WriteLine("Hi " + profile.DisplayName + "!");
HasLinkedAccount = true;

// Save token to hard disk
SaveToken(new AuthenticationToken() {
SaveTokenToDisk(new AuthenticationToken() {
Value = oauthAccessToken.Value,
Secret = oauthAccessToken.Secret,
UserName = profile.DisplayName
});

// Update status

if (OnCloudAuthenticationStatusChanged != null)
OnCloudAuthenticationStatusChanged(CloudAuthenticationStatusType.ConnectedToDropbox);
}
catch (AggregateException ae)
{
HasLinkedAccount = false;
ae.Handle(ex =>
{
if (ex is DropboxApiException)
Expand All @@ -174,7 +215,7 @@ private void ContinueLinkApp(AuthenticationToken token)
}
}

private AuthenticationToken LoadToken()
private AuthenticationToken LoadTokenFromDisk()
{
FileStream fileStream = null;
try
Expand All @@ -190,7 +231,8 @@ private AuthenticationToken LoadToken()
}
catch (Exception ex)
{
Tracing.Log("DropboxCoreService - LoadToken - Failed to load token: {0}", ex);
Tracing.Log("DropboxCoreService - LoadTokenFromDisk - Failed to load token: {0}", ex);
throw;
}
finally
{
Expand All @@ -201,7 +243,7 @@ private AuthenticationToken LoadToken()
return null;
}

private void SaveToken(AuthenticationToken token)
private void SaveTokenToDisk(AuthenticationToken token)
{
FileStream fileStream = null;
try
Expand All @@ -223,7 +265,8 @@ private void SaveToken(AuthenticationToken token)
}
catch (Exception ex)
{
Tracing.Log("DropboxCoreService - SaveToken - Failed to save token: {0}", ex);
Tracing.Log("DropboxCoreService - SaveTokenToDisk - Failed to save token: {0}", ex);
throw;
}
finally
{
Expand All @@ -232,9 +275,26 @@ private void SaveToken(AuthenticationToken token)
}
}

private void DeleteTokenFromDisk()
{
try
{
string filePath = Path.Combine(PathHelper.HomeDirectory, "dropbox.json");
if(File.Exists(filePath))
File.Delete(filePath);
}
catch (Exception ex)
{
Tracing.Log("DropboxCoreService - DeleteTokenFromDisk - Failed to delete token: {0}", ex);
throw;
}
}

public void UnlinkApp()
{
//_dropbox.
DeleteTokenFromDisk();
HasLinkedAccount = false;
_dropbox = null;
}

public void InitializeAppFolder()
Expand Down Expand Up @@ -367,6 +427,9 @@ public string PushDeviceInfo(AudioFile audioFile, long positionBytes, string pos
{
try
{
if(!HasLinkedAccount)
throw new CloudAppNotLinkedException();

var device = new CloudDeviceInfo()
{
AudioFileId = audioFile.Id,
Expand Down Expand Up @@ -408,6 +471,9 @@ public IEnumerable<CloudDeviceInfo> PullDeviceInfos()

try
{
if (!HasLinkedAccount)
throw new CloudAppNotLinkedException();

var entries = _dropbox.SearchAsync("/Devices", ".json").Result;
foreach (var entry in entries)
{
Expand Down
29 changes: 14 additions & 15 deletions MPfm/MPfm.MVP/Presenters/CloudPreferencesPresenter.cs
Expand Up @@ -37,7 +37,6 @@ public class CloudPreferencesPresenter : BasePresenter<ICloudPreferencesView>, I
private readonly NavigationManager _navigationManager;
private readonly ITinyMessengerHub _messengerHub;
private readonly ICloudLibraryService _cloudLibraryService;
private bool _isApplicationLinked;

public CloudPreferencesPresenter(ITinyMessengerHub messengerHub, ICloudLibraryService cloudLibraryService)
{
Expand All @@ -64,14 +63,12 @@ public override void BindView(ICloudPreferencesView view)

private void Initialize()
{
_isApplicationLinked = _cloudLibraryService.HasLinkedAccount;
RefreshPreferences();
RefreshState();
}

private void CloudConnectStatusChanged(CloudConnectStatusChangedMessage cloudConnectStatusChangedMessage)
{
_isApplicationLinked = cloudConnectStatusChangedMessage.IsApplicationLinked;
RefreshState();
}

Expand All @@ -81,25 +78,27 @@ private void SetCloudPreferences(CloudPreferencesEntity entity)

private void LoginLogoutDropbox()
{
//if (_cloudLibraryService.HasLinkedAccount)
// _cloudLibraryService.UnlinkApp();
//else
// _cloudLibraryService.LinkApp(View);

//RefreshState();
if (_cloudLibraryService.HasLinkedAccount)
{
_cloudLibraryService.UnlinkApp();
}
else
{
#if IOS || ANDROID || WINDOWS_PHONE || WINDOWSSTORE
_mobileNavigationManager.CreateCloudConnectView();
#else
_navigationManager.CreateCloudConnectView();
#endif
}

#if IOS || ANDROID || WINDOWS_PHONE || WINDOWSSTORE
_mobileNavigationManager.CreateCloudConnectView();
#else
_navigationManager.CreateCloudConnectView();
#endif
RefreshState();
}

private void RefreshState()
{
var state = new CloudPreferencesStateEntity()
{
IsDropboxLinkedToApp = _isApplicationLinked
IsDropboxLinkedToApp = _cloudLibraryService.HasLinkedAccount
};
View.RefreshCloudPreferencesState(state);
}
Expand Down

0 comments on commit 087c047

Please sign in to comment.