Skip to content
This repository has been archived by the owner on Aug 17, 2020. It is now read-only.

Commit

Permalink
Merge pull request #691 from jakubsuchybio/30minexpire
Browse files Browse the repository at this point in the history
Fix #645; Enhance exception handling and async update timer;
  • Loading branch information
ST-Apps authored Aug 14, 2016
2 parents 7d6ef10 + e8a8c99 commit 05f1ab4
Show file tree
Hide file tree
Showing 9 changed files with 115 additions and 68 deletions.
8 changes: 4 additions & 4 deletions PokemonGo-UWP/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ sealed partial class App : BootStrapper
/// Stores the current <see cref="DisplayRequest"/> instance for the app.
/// </summary>
private readonly DisplayRequest _displayRequest;

#endregion

#region Properties
Expand Down Expand Up @@ -83,7 +83,7 @@ public App()
private static async void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
e.Handled = true;
await ExceptionHandler.HandleException();
await ExceptionHandler.HandleException(new Exception(e.Message));
// We should be logging these exceptions too so they can be tracked down.
HockeyClient.Current.TrackException(e.Exception);
}
Expand All @@ -96,7 +96,7 @@ private static void TaskScheduler_UnobservedTaskException(object sender, Unobser
}

/// <summary>
///
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
Expand Down Expand Up @@ -195,7 +195,7 @@ public override async Task OnInitializeAsync(IActivatedEventArgs args)
}

/// <summary>
///
///
/// </summary>
/// <param name="startKind"></param>
/// <param name="args"></param>
Expand Down
4 changes: 2 additions & 2 deletions PokemonGo-UWP/Entities/FortDataWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,11 @@ public FortDataWrapper(FortData fortData)
/// the actual capture method.
/// </summary>
public DelegateCommand TrySearchPokestop => _trySearchPokestop ?? (
_trySearchPokestop = new DelegateCommand(() =>
_trySearchPokestop = new DelegateCommand(async () =>
{
NavigationHelper.NavigationState["CurrentPokestop"] = this;
// Disable map update
GameClient.ToggleUpdateTimer(false);
await GameClient.ToggleUpdateTimer(false);
BootStrapper.Current.NavigationService.Navigate(typeof(SearchPokestopPage));
}, () => true)
);
Expand Down
4 changes: 2 additions & 2 deletions PokemonGo-UWP/Entities/MapPokemonWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,11 @@ public MapPokemonWrapper(MapPokemon mapPokemon)
/// We're just navigating to the capture page, reporting that the player wants to capture the selected Pokemon.
/// </summary>
public DelegateCommand TryCatchPokemon => _tryCatchPokemon ?? (
_tryCatchPokemon = new DelegateCommand(() =>
_tryCatchPokemon = new DelegateCommand(async () =>
{
NavigationHelper.NavigationState["CurrentPokemon"] = this;
// Disable map update
GameClient.ToggleUpdateTimer(false);
await GameClient.ToggleUpdateTimer(false);
BootStrapper.Current.NavigationService.Navigate(typeof(CapturePokemonPage));
}, () => true)
);
Expand Down
107 changes: 70 additions & 37 deletions PokemonGo-UWP/Utils/GameClient.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel;
Expand All @@ -12,6 +13,7 @@
using PokemonGo.RocketAPI.Enums;
using PokemonGo.RocketAPI.Extensions;
using PokemonGo_UWP.Entities;
using PokemonGo_UWP.ViewModels;
using POGOProtos.Data;
using POGOProtos.Data.Player;
using POGOProtos.Enums;
Expand All @@ -23,6 +25,7 @@
using POGOProtos.Settings;
using POGOProtos.Settings.Master;
using Q42.WinRT.Data;
using Template10.Common;
using Template10.Utils;
using Universal_Authenticator_v2.Views;

Expand Down Expand Up @@ -56,13 +59,11 @@ public async Task<ApiOperation> HandleApiFailure(RequestEnvelope request, Respon
await Task.Delay(500);
_retryCount++;

if (_retryCount%5 == 0)
{
// Let's try to refresh the session by getting a new token
await
(_clientSettings.AuthType == AuthType.Google
? DoGoogleLogin(_clientSettings.GoogleUsername, _clientSettings.GooglePassword)
: DoPtcLogin(_clientSettings.PtcUsername, _clientSettings.PtcPassword));
if (_retryCount % 5 == 0)
{
await DoRelogin();
Debug.WriteLine("[Relogin] Stopping API via ApiHandledException.");
throw new ApiHandledException("Relogin completed.");
}

return ApiOperation.Retry;
Expand Down Expand Up @@ -234,15 +235,15 @@ public static async Task InitializeClient()
}
catch (Exception e)
{
if (e is PokemonGo.RocketAPI.Exceptions.AccessTokenExpiredException)
{
await Relogin();
}
else throw;
if (e is PokemonGo.RocketAPI.Exceptions.AccessTokenExpiredException)
{
await Relogin();
}
else throw;
}
}
public static async Task<bool> Relogin()
{
public static async Task<bool> Relogin()
{
switch (_clientSettings.AuthType)
{
case AuthType.Ptc:
Expand All @@ -266,7 +267,7 @@ public static async Task<bool> Relogin()
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns>true if login worked</returns>
public static async Task<bool> DoPtcLogin(string username, string password)
public static async Task<bool> DoPtcLogin(string username, string password)
{
_clientSettings = new Settings
{
Expand Down Expand Up @@ -303,7 +304,7 @@ public static async Task<bool> DoGoogleLogin(string email, string password)
AuthType = AuthType.Google
};

_client = new Client(_clientSettings, new ApiFailure(), DeviceInfos.Instance);
_client = new Client(_clientSettings, new ApiFailure(), DeviceInfos.Instance);
// Get Google token
var authToken = await _client.Login.DoLogin();
// Update current token even if it's null
Expand Down Expand Up @@ -333,13 +334,37 @@ public static void DoLogout()
NearbyPokestops.Clear();
}

public static async Task DoRelogin()
{
Debug.WriteLine("[Relogin] Started.");
DoLogout();

var token = _client.AuthToken;

await
(_clientSettings.AuthType == AuthType.Google
? DoGoogleLogin(_clientSettings.GoogleUsername, _clientSettings.GooglePassword)
: DoPtcLogin(_clientSettings.PtcUsername, _clientSettings.PtcPassword));

if (token != _client.AuthToken)
Debug.WriteLine("[Relogin] Token successfuly changed.");

Debug.WriteLine("[Relogin] Reloading gps and playerdata.");
await GameView.StartGpsDataService();
await GameView.UpdatePlayerData(true);
Debug.WriteLine("[Relogin] Restarting MapUpdate timer.");
_lastUpdate = DateTime.Now;
await ToggleUpdateTimer();
}

#endregion

#region Data Updating

private static Geolocator _geolocator;

public static Geoposition Geoposition { get; private set; }
public static GameMapPageViewModel GameView { get; set; }

private static DispatcherTimer _mapUpdateTimer;

Expand Down Expand Up @@ -375,7 +400,7 @@ public static async Task InitializeDataUpdate()
GameSetting =
await
DataCache.GetAsync(nameof(GameSetting), async () => (await _client.Download.GetSettings()).Settings,
DateTime.Now.AddMonths(1));
DateTime.Now.AddMonths(1));
// Update geolocator settings based on server
_geolocator.MovementThreshold = GameSetting.MapSettings.GetMapObjectsMinDistanceMeters;
_mapUpdateTimer = new DispatcherTimer
Expand All @@ -388,9 +413,17 @@ public static async Task InitializeDataUpdate()
if ((DateTime.Now - _lastUpdate).Seconds <= GameSetting.MapSettings.GetMapObjectsMinRefreshSeconds)
return;
Logger.Write("Updating map");
await UpdateMapObjects();
try
{
await UpdateMapObjects();
}
catch (Exception ex)
{
await ExceptionHandler.HandleException(ex);
}
};
// Update before starting timer
// Update before starting timer
Busy.SetBusy(true, Resources.CodeResources.GetString("GettingUserDataText"));
await UpdateMapObjects();
await UpdateInventory();
Expand All @@ -407,7 +440,7 @@ public static async Task InitializeDataUpdate()
/// Toggles the update timer based on the isEnabled value
/// </summary>
/// <param name="isEnabled"></param>
public static async void ToggleUpdateTimer(bool isEnabled = true)
public static async Task ToggleUpdateTimer(bool isEnabled = true)
{
if (isEnabled)
{
Expand All @@ -429,7 +462,7 @@ public static async void ToggleUpdateTimer(bool isEnabled = true)
/// </summary>
/// <returns></returns>
private static async Task UpdateMapObjects()
{
{
// Get all map objects from server
var mapObjects = await GetMapObjects(Geoposition);
_lastUpdate = DateTime.Now;
Expand All @@ -443,7 +476,7 @@ private static async Task UpdateMapObjects()
// update nearby pokemons
var newNearByPokemons = mapObjects.Item1.MapCells.SelectMany(x => x.NearbyPokemons).ToArray();
Logger.Write($"Found {newNearByPokemons.Length} nearby pokemons");
// for this collection the ordering is important, so we follow a slightly different update mechanism
// for this collection the ordering is important, so we follow a slightly different update mechanism
NearbyPokemons.UpdateByIndexWith(newNearByPokemons, x => new NearbyPokemonWrapper(x));

// update poke stops on map (gyms are ignored for now)
Expand Down Expand Up @@ -527,14 +560,14 @@ public static async Task<LevelUpRewardsResponse> UpdatePlayerStats(bool checkFor

// Update candies
CandyInventory.AddRange(from item in InventoryDelta.InventoryItems
where item.InventoryItemData?.Candy != null
where item.InventoryItemData?.Candy.FamilyId != PokemonFamilyId.FamilyUnset
group item by item.InventoryItemData?.Candy.FamilyId into family
select new Candy
{
FamilyId = family.FirstOrDefault().InventoryItemData.Candy.FamilyId,
Candy_ = family.FirstOrDefault().InventoryItemData.Candy.Candy_
},true);
where item.InventoryItemData?.Candy != null
where item.InventoryItemData?.Candy.FamilyId != PokemonFamilyId.FamilyUnset
group item by item.InventoryItemData?.Candy.FamilyId into family
select new Candy
{
FamilyId = family.FirstOrDefault().InventoryItemData.Candy.FamilyId,
Candy_ = family.FirstOrDefault().InventoryItemData.Candy.Candy_
}, true);

return null;
}
Expand Down Expand Up @@ -618,7 +651,7 @@ public static async Task UpdateInventory()
.GroupBy(item => item.InventoryItemData.Item)
.Select(item => item.First().InventoryItemData.Item), true);

// Update incbuators
// Update incbuators
FreeIncubatorsInventory.AddRange(fullInventory.Where(item => item.InventoryItemData.EggIncubators != null)
.SelectMany(item => item.InventoryItemData.EggIncubators.EggIncubator)
.Where(item => item != null && item.PokemonId == 0), true);
Expand All @@ -632,21 +665,21 @@ public static async Task UpdateInventory()
EggsInventory.AddRange(fullInventory.Select(item => item.InventoryItemData.PokemonData)
.Where(item => item != null && item.IsEgg), true);

// Update Pokedex
// Update Pokedex
PokedexInventory.AddRange(fullInventory.Where(item => item.InventoryItemData.PokedexEntry != null)
.Select(item => item.InventoryItemData.PokedexEntry), true);

// Update Player stats
PlayerStats =
fullInventory.First(item => item.InventoryItemData.PlayerStats != null).InventoryItemData.PlayerStats;
fullInventory.First(item => item.InventoryItemData.PlayerStats != null).InventoryItemData.PlayerStats;

}

#endregion

#region Pokemon Handling

#region Pokedex
#region Pokedex

/// <summary>
/// Gets extra data for the current pokemon
Expand Down Expand Up @@ -687,7 +720,7 @@ public static async Task<CatchPokemonResponse> CatchPokemon(ulong encounterId, s
var random = new Random();
return
await
_client.Encounter.CatchPokemon(encounterId, spawnpointId, captureItem, random.NextDouble()*1.95D,
_client.Encounter.CatchPokemon(encounterId, spawnpointId, captureItem, random.NextDouble() * 1.95D,
random.NextDouble(), 1, hitPokemon);
}

Expand All @@ -709,7 +742,7 @@ public static async Task<UseItemCaptureResponse> UseCaptureItem(ulong encounterI
#region Power Up & Evolving & Transfer

/// <summary>
///
///
/// </summary>
/// <param name="pokemon"></param>
/// <returns></returns>
Expand All @@ -719,7 +752,7 @@ public static async Task<UpgradePokemonResponse> PowerUpPokemon(PokemonData poke
}

/// <summary>
///
///
/// </summary>
/// <param name="pokemon"></param>
/// <returns></returns>
Expand Down
14 changes: 13 additions & 1 deletion PokemonGo-UWP/Utils/Helpers/ExceptionHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,26 @@
using Template10.Common;
using Universal_Authenticator_v2.Views;
using System;
using System.Diagnostics;

namespace PokemonGo_UWP.Utils
{
internal class ApiHandledException : Exception
{
public ApiHandledException(string reloginCompleted) : base(reloginCompleted)
{
}
}
public static class ExceptionHandler
{
public static async Task HandleException(Exception e = null)
{
if (e.GetType().Namespace.Equals("PokemonGo.RocketAPI.Exceptions"))
if (e != null && (e.GetType().FullName.Contains("ApiHandledException") || e.Message == "Relogin completed."))
{
Debug.WriteLine("[Relogin] ApiHandledException from API handled.");
Debug.WriteLine("[Relogin] Successfuly ended.");
}
else if (e != null && e.GetType().Namespace.Equals("PokemonGo.RocketAPI.Exceptions"))
{
await
new MessageDialog(Resources.CodeResources.GetString("LoginExpired")).ShowAsyncQueue();
Expand Down
6 changes: 3 additions & 3 deletions PokemonGo-UWP/ViewModels/CapturePokemonPageViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -190,10 +190,10 @@ public CaptureAward CurrentCaptureAward
/// Going back to map page
/// </summary>
public DelegateCommand EscapeEncounterCommand => _escapeEncounterCommand ?? (
_escapeEncounterCommand = new DelegateCommand(() =>
_escapeEncounterCommand = new DelegateCommand(async () =>
{
// Re-enable update timer
GameClient.ToggleUpdateTimer();
await GameClient.ToggleUpdateTimer();
NavigationService.GoBack();
}, () => true));

Expand Down Expand Up @@ -314,7 +314,7 @@ await GameClient.CatchPokemon(CurrentPokemon.EncounterId, CurrentPokemon.Spawnpo
GameClient.CatchablePokemons.Remove(CurrentPokemon);
GameClient.NearbyPokemons.Remove(nearbyPokemon);
// We just go back because there's nothing else to do
GameClient.ToggleUpdateTimer();
await GameClient.ToggleUpdateTimer();
break;
case CatchPokemonResponse.Types.CatchStatus.CatchMissed:
Logger.Write($"We missed {CurrentPokemon.PokemonId}");
Expand Down
Loading

0 comments on commit 05f1ab4

Please sign in to comment.