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

Commit 05f1ab4

Browse files
authored
Merge pull request #691 from jakubsuchybio/30minexpire
Fix #645; Enhance exception handling and async update timer;
2 parents 7d6ef10 + e8a8c99 commit 05f1ab4

9 files changed

Lines changed: 115 additions & 68 deletions

File tree

PokemonGo-UWP/App.xaml.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ sealed partial class App : BootStrapper
4040
/// Stores the current <see cref="DisplayRequest"/> instance for the app.
4141
/// </summary>
4242
private readonly DisplayRequest _displayRequest;
43-
43+
4444
#endregion
4545

4646
#region Properties
@@ -83,7 +83,7 @@ public App()
8383
private static async void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
8484
{
8585
e.Handled = true;
86-
await ExceptionHandler.HandleException();
86+
await ExceptionHandler.HandleException(new Exception(e.Message));
8787
// We should be logging these exceptions too so they can be tracked down.
8888
HockeyClient.Current.TrackException(e.Exception);
8989
}
@@ -96,7 +96,7 @@ private static void TaskScheduler_UnobservedTaskException(object sender, Unobser
9696
}
9797

9898
/// <summary>
99-
///
99+
///
100100
/// </summary>
101101
/// <param name="sender"></param>
102102
/// <param name="e"></param>
@@ -195,7 +195,7 @@ public override async Task OnInitializeAsync(IActivatedEventArgs args)
195195
}
196196

197197
/// <summary>
198-
///
198+
///
199199
/// </summary>
200200
/// <param name="startKind"></param>
201201
/// <param name="args"></param>

PokemonGo-UWP/Entities/FortDataWrapper.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,11 +59,11 @@ public FortDataWrapper(FortData fortData)
5959
/// the actual capture method.
6060
/// </summary>
6161
public DelegateCommand TrySearchPokestop => _trySearchPokestop ?? (
62-
_trySearchPokestop = new DelegateCommand(() =>
62+
_trySearchPokestop = new DelegateCommand(async () =>
6363
{
6464
NavigationHelper.NavigationState["CurrentPokestop"] = this;
6565
// Disable map update
66-
GameClient.ToggleUpdateTimer(false);
66+
await GameClient.ToggleUpdateTimer(false);
6767
BootStrapper.Current.NavigationService.Navigate(typeof(SearchPokestopPage));
6868
}, () => true)
6969
);

PokemonGo-UWP/Entities/MapPokemonWrapper.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,11 @@ public MapPokemonWrapper(MapPokemon mapPokemon)
3232
/// We're just navigating to the capture page, reporting that the player wants to capture the selected Pokemon.
3333
/// </summary>
3434
public DelegateCommand TryCatchPokemon => _tryCatchPokemon ?? (
35-
_tryCatchPokemon = new DelegateCommand(() =>
35+
_tryCatchPokemon = new DelegateCommand(async () =>
3636
{
3737
NavigationHelper.NavigationState["CurrentPokemon"] = this;
3838
// Disable map update
39-
GameClient.ToggleUpdateTimer(false);
39+
await GameClient.ToggleUpdateTimer(false);
4040
BootStrapper.Current.NavigationService.Navigate(typeof(CapturePokemonPage));
4141
}, () => true)
4242
);

PokemonGo-UWP/Utils/GameClient.cs

Lines changed: 70 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System;
22
using System.Collections.Generic;
33
using System.Collections.ObjectModel;
4+
using System.Diagnostics;
45
using System.Linq;
56
using System.Threading.Tasks;
67
using Windows.ApplicationModel;
@@ -12,6 +13,7 @@
1213
using PokemonGo.RocketAPI.Enums;
1314
using PokemonGo.RocketAPI.Extensions;
1415
using PokemonGo_UWP.Entities;
16+
using PokemonGo_UWP.ViewModels;
1517
using POGOProtos.Data;
1618
using POGOProtos.Data.Player;
1719
using POGOProtos.Enums;
@@ -23,6 +25,7 @@
2325
using POGOProtos.Settings;
2426
using POGOProtos.Settings.Master;
2527
using Q42.WinRT.Data;
28+
using Template10.Common;
2629
using Template10.Utils;
2730
using Universal_Authenticator_v2.Views;
2831

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

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

6869
return ApiOperation.Retry;
@@ -234,15 +235,15 @@ public static async Task InitializeClient()
234235
}
235236
catch (Exception e)
236237
{
237-
if (e is PokemonGo.RocketAPI.Exceptions.AccessTokenExpiredException)
238-
{
239-
await Relogin();
240-
}
241-
else throw;
238+
if (e is PokemonGo.RocketAPI.Exceptions.AccessTokenExpiredException)
239+
{
240+
await Relogin();
241+
}
242+
else throw;
242243
}
243244
}
244-
public static async Task<bool> Relogin()
245-
{
245+
public static async Task<bool> Relogin()
246+
{
246247
switch (_clientSettings.AuthType)
247248
{
248249
case AuthType.Ptc:
@@ -266,7 +267,7 @@ public static async Task<bool> Relogin()
266267
/// <param name="username"></param>
267268
/// <param name="password"></param>
268269
/// <returns>true if login worked</returns>
269-
public static async Task<bool> DoPtcLogin(string username, string password)
270+
public static async Task<bool> DoPtcLogin(string username, string password)
270271
{
271272
_clientSettings = new Settings
272273
{
@@ -303,7 +304,7 @@ public static async Task<bool> DoGoogleLogin(string email, string password)
303304
AuthType = AuthType.Google
304305
};
305306

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

337+
public static async Task DoRelogin()
338+
{
339+
Debug.WriteLine("[Relogin] Started.");
340+
DoLogout();
341+
342+
var token = _client.AuthToken;
343+
344+
await
345+
(_clientSettings.AuthType == AuthType.Google
346+
? DoGoogleLogin(_clientSettings.GoogleUsername, _clientSettings.GooglePassword)
347+
: DoPtcLogin(_clientSettings.PtcUsername, _clientSettings.PtcPassword));
348+
349+
if (token != _client.AuthToken)
350+
Debug.WriteLine("[Relogin] Token successfuly changed.");
351+
352+
Debug.WriteLine("[Relogin] Reloading gps and playerdata.");
353+
await GameView.StartGpsDataService();
354+
await GameView.UpdatePlayerData(true);
355+
Debug.WriteLine("[Relogin] Restarting MapUpdate timer.");
356+
_lastUpdate = DateTime.Now;
357+
await ToggleUpdateTimer();
358+
}
359+
336360
#endregion
337361

338362
#region Data Updating
339363

340364
private static Geolocator _geolocator;
341365

342366
public static Geoposition Geoposition { get; private set; }
367+
public static GameMapPageViewModel GameView { get; set; }
343368

344369
private static DispatcherTimer _mapUpdateTimer;
345370

@@ -375,7 +400,7 @@ public static async Task InitializeDataUpdate()
375400
GameSetting =
376401
await
377402
DataCache.GetAsync(nameof(GameSetting), async () => (await _client.Download.GetSettings()).Settings,
378-
DateTime.Now.AddMonths(1));
403+
DateTime.Now.AddMonths(1));
379404
// Update geolocator settings based on server
380405
_geolocator.MovementThreshold = GameSetting.MapSettings.GetMapObjectsMinDistanceMeters;
381406
_mapUpdateTimer = new DispatcherTimer
@@ -388,9 +413,17 @@ public static async Task InitializeDataUpdate()
388413
if ((DateTime.Now - _lastUpdate).Seconds <= GameSetting.MapSettings.GetMapObjectsMinRefreshSeconds)
389414
return;
390415
Logger.Write("Updating map");
391-
await UpdateMapObjects();
416+
417+
try
418+
{
419+
await UpdateMapObjects();
420+
}
421+
catch (Exception ex)
422+
{
423+
await ExceptionHandler.HandleException(ex);
424+
}
392425
};
393-
// Update before starting timer
426+
// Update before starting timer
394427
Busy.SetBusy(true, Resources.CodeResources.GetString("GettingUserDataText"));
395428
await UpdateMapObjects();
396429
await UpdateInventory();
@@ -407,7 +440,7 @@ public static async Task InitializeDataUpdate()
407440
/// Toggles the update timer based on the isEnabled value
408441
/// </summary>
409442
/// <param name="isEnabled"></param>
410-
public static async void ToggleUpdateTimer(bool isEnabled = true)
443+
public static async Task ToggleUpdateTimer(bool isEnabled = true)
411444
{
412445
if (isEnabled)
413446
{
@@ -429,7 +462,7 @@ public static async void ToggleUpdateTimer(bool isEnabled = true)
429462
/// </summary>
430463
/// <returns></returns>
431464
private static async Task UpdateMapObjects()
432-
{
465+
{
433466
// Get all map objects from server
434467
var mapObjects = await GetMapObjects(Geoposition);
435468
_lastUpdate = DateTime.Now;
@@ -443,7 +476,7 @@ private static async Task UpdateMapObjects()
443476
// update nearby pokemons
444477
var newNearByPokemons = mapObjects.Item1.MapCells.SelectMany(x => x.NearbyPokemons).ToArray();
445478
Logger.Write($"Found {newNearByPokemons.Length} nearby pokemons");
446-
// for this collection the ordering is important, so we follow a slightly different update mechanism
479+
// for this collection the ordering is important, so we follow a slightly different update mechanism
447480
NearbyPokemons.UpdateByIndexWith(newNearByPokemons, x => new NearbyPokemonWrapper(x));
448481

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

528561
// Update candies
529562
CandyInventory.AddRange(from item in InventoryDelta.InventoryItems
530-
where item.InventoryItemData?.Candy != null
531-
where item.InventoryItemData?.Candy.FamilyId != PokemonFamilyId.FamilyUnset
532-
group item by item.InventoryItemData?.Candy.FamilyId into family
533-
select new Candy
534-
{
535-
FamilyId = family.FirstOrDefault().InventoryItemData.Candy.FamilyId,
536-
Candy_ = family.FirstOrDefault().InventoryItemData.Candy.Candy_
537-
},true);
563+
where item.InventoryItemData?.Candy != null
564+
where item.InventoryItemData?.Candy.FamilyId != PokemonFamilyId.FamilyUnset
565+
group item by item.InventoryItemData?.Candy.FamilyId into family
566+
select new Candy
567+
{
568+
FamilyId = family.FirstOrDefault().InventoryItemData.Candy.FamilyId,
569+
Candy_ = family.FirstOrDefault().InventoryItemData.Candy.Candy_
570+
}, true);
538571

539572
return null;
540573
}
@@ -618,7 +651,7 @@ public static async Task UpdateInventory()
618651
.GroupBy(item => item.InventoryItemData.Item)
619652
.Select(item => item.First().InventoryItemData.Item), true);
620653

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

635-
// Update Pokedex
668+
// Update Pokedex
636669
PokedexInventory.AddRange(fullInventory.Where(item => item.InventoryItemData.PokedexEntry != null)
637670
.Select(item => item.InventoryItemData.PokedexEntry), true);
638671

639672
// Update Player stats
640673
PlayerStats =
641-
fullInventory.First(item => item.InventoryItemData.PlayerStats != null).InventoryItemData.PlayerStats;
674+
fullInventory.First(item => item.InventoryItemData.PlayerStats != null).InventoryItemData.PlayerStats;
642675

643676
}
644677

645678
#endregion
646679

647680
#region Pokemon Handling
648681

649-
#region Pokedex
682+
#region Pokedex
650683

651684
/// <summary>
652685
/// Gets extra data for the current pokemon
@@ -687,7 +720,7 @@ public static async Task<CatchPokemonResponse> CatchPokemon(ulong encounterId, s
687720
var random = new Random();
688721
return
689722
await
690-
_client.Encounter.CatchPokemon(encounterId, spawnpointId, captureItem, random.NextDouble()*1.95D,
723+
_client.Encounter.CatchPokemon(encounterId, spawnpointId, captureItem, random.NextDouble() * 1.95D,
691724
random.NextDouble(), 1, hitPokemon);
692725
}
693726

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

711744
/// <summary>
712-
///
745+
///
713746
/// </summary>
714747
/// <param name="pokemon"></param>
715748
/// <returns></returns>
@@ -719,7 +752,7 @@ public static async Task<UpgradePokemonResponse> PowerUpPokemon(PokemonData poke
719752
}
720753

721754
/// <summary>
722-
///
755+
///
723756
/// </summary>
724757
/// <param name="pokemon"></param>
725758
/// <returns></returns>

PokemonGo-UWP/Utils/Helpers/ExceptionHandler.cs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,26 @@
44
using Template10.Common;
55
using Universal_Authenticator_v2.Views;
66
using System;
7+
using System.Diagnostics;
78

89
namespace PokemonGo_UWP.Utils
910
{
11+
internal class ApiHandledException : Exception
12+
{
13+
public ApiHandledException(string reloginCompleted) : base(reloginCompleted)
14+
{
15+
}
16+
}
1017
public static class ExceptionHandler
1118
{
1219
public static async Task HandleException(Exception e = null)
1320
{
14-
if (e.GetType().Namespace.Equals("PokemonGo.RocketAPI.Exceptions"))
21+
if (e != null && (e.GetType().FullName.Contains("ApiHandledException") || e.Message == "Relogin completed."))
22+
{
23+
Debug.WriteLine("[Relogin] ApiHandledException from API handled.");
24+
Debug.WriteLine("[Relogin] Successfuly ended.");
25+
}
26+
else if (e != null && e.GetType().Namespace.Equals("PokemonGo.RocketAPI.Exceptions"))
1527
{
1628
await
1729
new MessageDialog(Resources.CodeResources.GetString("LoginExpired")).ShowAsyncQueue();

PokemonGo-UWP/ViewModels/CapturePokemonPageViewModel.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -190,10 +190,10 @@ public CaptureAward CurrentCaptureAward
190190
/// Going back to map page
191191
/// </summary>
192192
public DelegateCommand EscapeEncounterCommand => _escapeEncounterCommand ?? (
193-
_escapeEncounterCommand = new DelegateCommand(() =>
193+
_escapeEncounterCommand = new DelegateCommand(async () =>
194194
{
195195
// Re-enable update timer
196-
GameClient.ToggleUpdateTimer();
196+
await GameClient.ToggleUpdateTimer();
197197
NavigationService.GoBack();
198198
}, () => true));
199199

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

0 commit comments

Comments
 (0)