-
Notifications
You must be signed in to change notification settings - Fork 75
/
RpcClient.cs
815 lines (723 loc) · 34.9 KB
/
RpcClient.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using GeoCoordinatePortable;
using Google.Protobuf;
using Newtonsoft.Json;
using POGOLib.Official.Logging;
using POGOLib.Official.Util;
using POGOProtos.Map;
using POGOProtos.Networking.Envelopes;
using POGOProtos.Networking.Requests;
using POGOProtos.Networking.Requests.Messages;
using POGOProtos.Networking.Responses;
using POGOProtos.Enums;
using POGOProtos.Networking.Platform;
using POGOProtos.Networking.Platform.Requests;
using POGOProtos.Networking.Platform.Responses;
namespace POGOLib.Official.Net
{
public class RpcClient : IDisposable
{
/// <summary>
/// The authenticated <see cref="Session" />.
/// </summary>
private readonly Session _session;
/// <summary>
/// The class responsible for all encryption / signing regarding <see cref="RpcClient"/>.
/// </summary>
private readonly RpcEncryption _rpcEncryption;
/// <summary>
/// The current request count we are at.
/// </summary>
private ulong _requestCount;
/// <summary>
/// The rpc url we have to call.
/// </summary>
private string _requestUrl;
private string _mapKey;
private readonly List<RequestType> _defaultRequests = new List<RequestType>
{
RequestType.CheckChallenge,
RequestType.GetHatchedEggs,
RequestType.GetInventory,
RequestType.CheckAwardedBadges,
RequestType.DownloadSettings
};
private readonly ConcurrentQueue<RequestEnvelope> _rpcQueue = new ConcurrentQueue<RequestEnvelope>();
private readonly ConcurrentDictionary<RequestEnvelope, ByteString> _rpcResponses = new ConcurrentDictionary<RequestEnvelope, ByteString>();
private readonly Semaphore _rpcQueueMutex = new Semaphore(1, 1);
internal RpcClient(Session session)
{
_session = session;
_rpcEncryption = new RpcEncryption(session);
_mapKey = string.Empty;
}
internal DateTime LastRpcRequest { get; private set; }
internal DateTime LastRpcMapObjectsRequest { get; private set; }
internal GeoCoordinate LastGeoCoordinateMapObjectsRequest { get; private set; } = new GeoCoordinate();
internal Platform GetPlatform()
{
return _session.Device.DeviceInfo.DeviceBrand == "Apple" ? Platform.Ios : Platform.Android;
}
private long PositiveRandom()
{
long ret = _session.Random.Next() | (_session.Random.Next() << 32);
// lrand48 ensures it's never < 0
// So do the same
if (ret < 0)
ret = -ret;
return ret;
}
private void IncrementRequestCount()
{
// Request counts on android jump more than 1 at a time according to logs
// They are fully sequential on iOS though
// So mimic that same behavior here.
switch (GetPlatform())
{
case Platform.Android:
_requestCount += (uint)_session.Random.Next(2, 15);
break;
case Platform.Ios:
_requestCount++;
break;
}
}
/// <summary>
/// Sends all requests which the (ios-)client sends on startup
/// </summary>
internal async Task<bool> StartupAsync()
{
// Send GetPlayer to check if we're connected and authenticated
GetPlayerResponse playerResponse;
do
{
var response = await SendRemoteProcedureCallAsync(new[]
{
new Request
{
RequestType = RequestType.GetPlayer
},
new Request
{
RequestType = RequestType.CheckChallenge,
RequestMessage = new CheckChallengeMessage
{
DebugRequest = false
}.ToByteString()
}
});
playerResponse = GetPlayerResponse.Parser.ParseFrom(response);
if (!playerResponse.Success)
{
await Task.Delay(TimeSpan.FromMilliseconds(1000));
}
} while (!playerResponse.Success);
_session.Player.Data = playerResponse.PlayerData;
return true;
}
// TODO: Reimplement
#region Unused assets code
// public async Task<GetAssetDigestResponse> GetAssetsAsync()
// {
// // check if template cache has been set
//
// // Get DownloadRemoteConfig
// var remoteConfigResponse = await SendRemoteProcedureCallAsync(new Request
// {
// RequestType = RequestType.DownloadRemoteConfigVersion,
// RequestMessage = new DownloadRemoteConfigVersionMessage
// {
// Platform = Platform.Android,
// AppVersion = 2903
// }.ToByteString()
// });
//
// var remoteConfigParsed = DownloadRemoteConfigVersionResponse.Parser.ParseFrom(remoteConfigResponse);
// var timestamp = (ulong) TimeUtil.GetCurrentTimestampInMilliseconds();
//
// // TODO: the timestamp comparisons seem to be used for determining if the stored data is invalid and needs refreshed,
// // however, looking at this code I'm not sure it's implemented correctly - or if these refactors still match the behavior of
// // the previous code... same concern with the next method GetItemTemplates()..
//
// var cachedMsg = _session.DataCache.GetCachedAssetDigest();
// if (cachedMsg != null && remoteConfigParsed.AssetDigestTimestampMs <= timestamp)
// {
// return cachedMsg;
// }
// else
// {
// // GetAssetDigest
// var assetDigestResponse = await SendRemoteProcedureCallAsync(new Request
// {
// RequestType = RequestType.GetAssetDigest,
// RequestMessage = new GetAssetDigestMessage
// {
// Platform = Platform.Android,
// AppVersion = 2903
// }.ToByteString()
// });
// var msg = GetAssetDigestResponse.Parser.ParseFrom(assetDigestResponse);
// _session.DataCache.SaveData(DataCacheExtensions.AssetDigestFile, msg);
// return msg;
// }
// }
//
// public async Task<DownloadItemTemplatesResponse> GetItemTemplatesAsync()
// {
// // Get DownloadRemoteConfig
// var remoteConfigResponse = await SendRemoteProcedureCallAsync(new Request
// {
// RequestType = RequestType.DownloadRemoteConfigVersion,
// RequestMessage = new DownloadRemoteConfigVersionMessage
// {
// Platform = Platform.Android,
// AppVersion = 2903
// }.ToByteString()
// });
//
// var remoteConfigParsed = DownloadRemoteConfigVersionResponse.Parser.ParseFrom(remoteConfigResponse);
// var timestamp = (ulong) TimeUtil.GetCurrentTimestampInMilliseconds();
//
// var cachedMsg = _session.DataCache.GetCachedItemTemplates();
// if (cachedMsg != null && remoteConfigParsed.AssetDigestTimestampMs <= timestamp)
// {
// return cachedMsg;
// }
// else
// {
// // GetAssetDigest
// var itemTemplateResponse = await SendRemoteProcedureCallAsync(new Request
// {
// RequestType = RequestType.DownloadItemTemplates
// });
// var msg = DownloadItemTemplatesResponse.Parser.ParseFrom(itemTemplateResponse);
// _session.DataCache.SaveData(DataCacheExtensions.ItemTemplatesFile, msg);
// return msg;
// }
// }
#endregion
/// <summary>
/// It is not recommended to call this. Map objects will update automatically and fire the map update event.
/// </summary>
public async Task RefreshMapObjectsAsync()
{
var cellIds = MapUtil.GetCellIdsForLatLong(_session.Player.Coordinate.Latitude, _session.Player.Coordinate.Longitude);
var sinceTimeMs = cellIds.Select(x => (long) 0).ToArray();
var response = await SendRemoteProcedureCallAsync(new Request
{
RequestType = RequestType.GetMapObjects,
RequestMessage = new GetMapObjectsMessage
{
CellId =
{
cellIds
},
SinceTimestampMs =
{
sinceTimeMs
},
Latitude = _session.Player.Coordinate.Latitude,
Longitude = _session.Player.Coordinate.Longitude
}.ToByteString()
});
if (response != null)
{
var mapObjects = GetMapObjectsResponse.Parser.ParseFrom(response);
if (mapObjects.Status == MapObjectsStatus.Success)
{
// TODO: Cleaner?
var pokemonCatchable = mapObjects.MapCells.SelectMany(c => c.CatchablePokemons).Count();
var pokemonWild = mapObjects.MapCells.SelectMany(c => c.WildPokemons).Count();
var pokemonNearby = mapObjects.MapCells.SelectMany(c => c.NearbyPokemons).Count();
var pokemonCount = pokemonCatchable + pokemonWild + pokemonNearby;
Logger.Debug($"Received '{mapObjects.MapCells.Count}' map cells.");
Logger.Debug($"Received '{pokemonCount}' pokemons. Catchable({pokemonCatchable}) Wild({pokemonWild}) Nearby({pokemonNearby})");
Logger.Debug($"Received '{mapObjects.MapCells.SelectMany(c => c.Forts).Count()}' forts.");
if (mapObjects.MapCells.Count == 0)
{
Logger.Error("We received 0 map cells, are your GPS coordinates correct?");
return;
}
_session.Map.Cells = mapObjects.MapCells;
}
else
{
Logger.Error($"GetMapObjects status is: '{mapObjects.Status}'.");
}
}
else if (_session.State != SessionState.Paused)
{
// POGOLib didn't expect this.
throw new NullReferenceException(nameof(response));
}
}
/// <summary>
/// Gets the next request id for the <see cref="RequestEnvelope" />.
/// </summary>
/// <returns></returns>
private ulong GetNextRequestId()
{
if (_requestCount == 1)
{
IncrementRequestCount();
switch (GetPlatform())
{
case Platform.Android:
// lrand48 is "broken" in that the first run of it will return a static value.
// So the first time we send a request, we need to match that initial value.
// Note: On android srand(4) is called in .init_array which seeds the initial value.
return 0x53B77E48000000B0;
case Platform.Ios:
// Same as lrand48, iOS uses "rand()" without a pre-seed which always gives the same first value.
return 0x41A700000002;
}
}
// Note that the API expects a "positive" random value here. (At least on Android it does due to lrand48 implementation details)
// So we'll just use the same for iOS since it doesn't hurt, and means less code required.
ulong r = (((ulong)PositiveRandom() | ((_requestCount + 1) >> 31)) << 32) | (_requestCount + 1);
IncrementRequestCount();
return r;
}
/// <summary>
/// Gets a collection of requests that should be sent in every request to PokémonGo along with your own
/// <see cref="Request" />.
/// </summary>
/// <returns></returns>
private IEnumerable<Request> GetDefaultRequests()
{
var request = new List<Request>
{
new Request
{
RequestType = RequestType.CheckChallenge,
RequestMessage = new CheckChallengeMessage
{
DebugRequest = false
}.ToByteString()
},
new Request
{
RequestType = RequestType.GetHatchedEggs
},
new Request
{
RequestType = RequestType.GetInventory,
RequestMessage = new GetInventoryMessage
{
LastTimestampMs = _session.Player.Inventory.LastInventoryTimestampMs
}.ToByteString()
},
new Request
{
RequestType = RequestType.CheckAwardedBadges
}
};
if (string.IsNullOrEmpty(_session.GlobalSettingsHash))
{
request.Add(new Request
{
RequestType = RequestType.DownloadSettings
});
}
else
{
request.Add(new Request
{
RequestType = RequestType.DownloadSettings,
RequestMessage = new DownloadSettingsMessage
{
Hash = _session.GlobalSettingsHash
}.ToByteString()
});
}
//If Incense is active we add this:
//request.Add(new Request
//{
// RequestType = RequestType.GetIncensePokemon,
// RequestMessage = new GetIncensePokemonMessage
// {
// PlayerLatitude = _session.Player.Coordinate.Latitude,
// PlayerLongitude = _session.Player.Coordinate.Longitude
// }.ToByteString()
//});
return request;
}
/// <summary>
/// Gets a <see cref="RequestEnvelope" /> with authentication data.
/// </summary>
/// <param name="request"></param>
/// <param name="addDefaultRequests"></param>
/// <returns></returns>
public async Task<RequestEnvelope> GetRequestEnvelopeAsync(IEnumerable<Request> request, bool addDefaultRequests)
{
var requestEnvelope = new RequestEnvelope
{
StatusCode = 2,
RequestId = GetNextRequestId(),
Latitude = _session.Player.Coordinate.Latitude,
Longitude = _session.Player.Coordinate.Longitude
};
requestEnvelope.Requests.AddRange(request);
if (addDefaultRequests)
requestEnvelope.Requests.AddRange(GetDefaultRequests());
if (_session.AccessToken.AuthTicket != null && _session.AccessToken.AuthTicket.ExpireTimestampMs < ((ulong)TimeUtil.GetCurrentTimestampInMilliseconds() - (60000 * 2)))
{
// Check for almost expired AuthTicket (2 minute buffer). Null out the AuthTicket so that AccessToken is used.
_session.AccessToken.AuthTicket = null;
}
if (_session.AccessToken.AuthTicket == null || _session.AccessToken.IsExpired)
{
if (_session.AccessToken.IsExpired)
{
await _session.Reauthenticate();
}
requestEnvelope.AuthInfo = new RequestEnvelope.Types.AuthInfo
{
Provider = _session.AccessToken.ProviderID,
Token = new RequestEnvelope.Types.AuthInfo.Types.JWT
{
Contents = _session.AccessToken.Token,
Unknown2 = 59
}
};
}
else
{
requestEnvelope.AuthTicket = _session.AccessToken.AuthTicket;
}
if (requestEnvelope.Requests.Count > 0 &&
requestEnvelope.Requests[0].RequestType == RequestType.GetMapObjects)
{
requestEnvelope.Requests.Add(new Request
{
RequestType = RequestType.GetInbox,
RequestMessage = ByteString.Empty
});
}
requestEnvelope.PlatformRequests.Add(await _rpcEncryption.GenerateSignatureAsync(requestEnvelope));
if (requestEnvelope.Requests.Count > 0 && (
requestEnvelope.Requests[0].RequestType == RequestType.GetMapObjects ||
requestEnvelope.Requests[0].RequestType == RequestType.GetPlayer))
{
requestEnvelope.PlatformRequests.Add(new RequestEnvelope.Types.PlatformRequest
{
Type = PlatformRequestType.UnknownPtr8,
RequestMessage = new UnknownPtr8Request
{
Message = _mapKey
}.ToByteString()
});
}
return requestEnvelope;
}
public async Task<ByteString> SendRemoteProcedureCallAsync(RequestType requestType)
{
return await SendRemoteProcedureCallAsync(new Request
{
RequestType = requestType
});
}
public async Task<ByteString> SendRemoteProcedureCallAsync(Request request, bool addDefaultRequests = true)
{
return await SendRemoteProcedureCall(await GetRequestEnvelopeAsync(new[] {request}, addDefaultRequests));
}
public async Task<ByteString> SendRemoteProcedureCallAsync(Request[] request, bool addDefaultRequests = false)
{
return await SendRemoteProcedureCall(await GetRequestEnvelopeAsync(request, addDefaultRequests));
}
private Task<ByteString> SendRemoteProcedureCall(RequestEnvelope requestEnvelope)
{
return Task.Run(async () =>
{
_rpcQueue.Enqueue(requestEnvelope);
try
{
_rpcQueueMutex.WaitOne();
RequestEnvelope processRequestEnvelope;
while (_rpcQueue.TryDequeue(out processRequestEnvelope))
{
var diff = Math.Max(0, DateTime.Now.Millisecond - LastRpcRequest.Millisecond);
if (diff < Configuration.ThrottleDifference)
{
var delay = Configuration.ThrottleDifference - diff + (int)(_session.Random.NextDouble() * 0);
await Task.Delay(delay);
}
_rpcResponses.GetOrAdd(processRequestEnvelope, await PerformRemoteProcedureCallAsync(processRequestEnvelope));
}
ByteString ret;
_rpcResponses.TryRemove(requestEnvelope, out ret);
return ret;
}
finally
{
_rpcQueueMutex.Release();
}
});
}
private async Task<ByteString> PerformRemoteProcedureCallAsync(RequestEnvelope requestEnvelope)
{
try
{
switch (_session.State)
{
case SessionState.Stopped:
Logger.Error("We tried to send a request while the session was stopped.");
return null;
case SessionState.Paused:
var requests = requestEnvelope.Requests.Select(x => x.RequestType).ToList();
if (requests.Count != 1 || requests[0] != RequestType.VerifyChallenge)
{
Logger.Error("We tried to send a request while the session was paused. The only request allowed is VerifyChallenge.");
return null;
}
break;
}
using (var requestData = new ByteArrayContent(requestEnvelope.ToByteArray()))
{
Logger.Debug($"Sending RPC Request: '{string.Join(", ", requestEnvelope.Requests.Select(x => x.RequestType))}'");
Logger.Debug($"=> Platform Request: '{string.Join(", ", requestEnvelope.PlatformRequests.Select(x => x.Type))}'");
using (var response = await _session.HttpClient.PostAsync(_requestUrl ?? Constants.ApiUrl, requestData))
{
if (!response.IsSuccessStatusCode)
{
Logger.Debug(await response.Content.ReadAsStringAsync());
throw new Exception("Received a non-success HTTP status code from the RPC server, see the console for the response.");
}
var responseBytes = response.Content.ReadAsByteArrayAsync().Result;
var responseEnvelope = ResponseEnvelope.Parser.ParseFrom(responseBytes);
switch (responseEnvelope.StatusCode)
{
// Valid response.
case ResponseEnvelope.Types.StatusCode.Ok:
// Success!?
break;
// Valid response and new rpc url.
case ResponseEnvelope.Types.StatusCode.OkRpcUrlInResponse:
if (Regex.IsMatch(responseEnvelope.ApiUrl, "pgorelease\\.nianticlabs\\.com\\/plfe\\/\\d+"))
{
_requestUrl = $"https://{responseEnvelope.ApiUrl}/rpc";
}
else
{
throw new Exception($"Received an incorrect API url: '{responseEnvelope.ApiUrl}', status code was: '{responseEnvelope.StatusCode}'.");
}
break;
// A new rpc endpoint is available.
case ResponseEnvelope.Types.StatusCode.Redirect:
if (Regex.IsMatch(responseEnvelope.ApiUrl, "pgorelease\\.nianticlabs\\.com\\/plfe\\/\\d+"))
{
_requestUrl = $"https://{responseEnvelope.ApiUrl}/rpc";
return await PerformRemoteProcedureCallAsync(requestEnvelope);
}
throw new Exception($"Received an incorrect API url: '{responseEnvelope.ApiUrl}', status code was: '{responseEnvelope.StatusCode}'.");
// The login token is invalid.
// TODO: Make cleaner to reduce duplicate code with the GetRequestEnvelopeAsync method.
case ResponseEnvelope.Types.StatusCode.InvalidAuthToken:
Logger.Debug("Received StatusCode 102, reauthenticating.");
_session.AccessToken.Expire();
await _session.Reauthenticate();
// Apply new token.
requestEnvelope.AuthInfo = new RequestEnvelope.Types.AuthInfo
{
Provider = _session.AccessToken.ProviderID,
Token = new RequestEnvelope.Types.AuthInfo.Types.JWT
{
Contents = _session.AccessToken.Token,
Unknown2 = 59
}
};
// Re-sign envelope.
var signature = requestEnvelope.PlatformRequests.FirstOrDefault(x => x.Type == PlatformRequestType.SendEncryptedSignature);
if (signature != null)
{
requestEnvelope.PlatformRequests.Remove(signature);
}
requestEnvelope.PlatformRequests.Insert(0, await _rpcEncryption.GenerateSignatureAsync(requestEnvelope));
// Re-send envelope.
return await PerformRemoteProcedureCallAsync(requestEnvelope);
default:
Logger.Info($"Unknown status code: {responseEnvelope.StatusCode}");
break;
}
LastRpcRequest = DateTime.UtcNow;
if (requestEnvelope.Requests[0].RequestType == RequestType.GetMapObjects)
{
LastRpcMapObjectsRequest = LastRpcRequest;
LastGeoCoordinateMapObjectsRequest = _session.Player.Coordinate;
}
if (responseEnvelope.AuthTicket != null)
{
_session.AccessToken.AuthTicket = responseEnvelope.AuthTicket;
Logger.Debug("Received a new AuthTicket from Pokemon!");
}
var mapPlatform = responseEnvelope.PlatformReturns.FirstOrDefault(x => x.Type == PlatformRequestType.UnknownPtr8);
if (mapPlatform != null)
{
var unknownPtr8Response = UnknownPtr8Response.Parser.ParseFrom(mapPlatform.Response);
_mapKey = unknownPtr8Response.Message;
}
return HandleResponseEnvelope(requestEnvelope, responseEnvelope);
}
}
}
catch (Exception e)
{
Logger.Error($"SendRemoteProcedureCall exception: {e}");
return null;
}
}
/// <summary>
/// Responsible for handling the received <see cref="ResponseEnvelope" />.
/// </summary>
/// <param name="requestEnvelope">The <see cref="RequestEnvelope"/> prepared by <see cref="PerformRemoteProcedureCallAsync"/>.</param>
/// <param name="responseEnvelope">The <see cref="ResponseEnvelope"/> received from <see cref="SendRemoteProcedureCallAsync(POGOProtos.Networking.Requests.Request)" />.</param>
/// <returns>Returns the <see cref="ByteString" />response of the <see cref="Request"/>.</returns>
private ByteString HandleResponseEnvelope(RequestEnvelope requestEnvelope, ResponseEnvelope responseEnvelope)
{
if (responseEnvelope.Returns.Count == 0)
{
throw new Exception("There were 0 responses.");
}
// Take requested response and remove from returns.
var requestResponse = responseEnvelope.Returns[0];
// Handle the default responses.
HandleDefaultResponses(requestEnvelope, responseEnvelope.Returns);
// Handle responses which affect the inventory
HandleInventoryResponses(requestEnvelope.Requests[0], requestResponse);
return requestResponse;
}
private void HandleInventoryResponses(Request request, ByteString requestResponse)
{
ulong pokemonId = 0;
switch (request.RequestType)
{
case RequestType.ReleasePokemon:
var releaseResponse = ReleasePokemonResponse.Parser.ParseFrom(requestResponse);
if (releaseResponse.Result == ReleasePokemonResponse.Types.Result.Success ||
releaseResponse.Result == ReleasePokemonResponse.Types.Result.Failed)
{
var releaseMessage = ReleasePokemonMessage.Parser.ParseFrom(request.RequestMessage);
pokemonId = releaseMessage.PokemonId;
}
break;
case RequestType.EvolvePokemon:
var evolveResponse = EvolvePokemonResponse.Parser.ParseFrom(requestResponse);
if (evolveResponse.Result == EvolvePokemonResponse.Types.Result.Success ||
evolveResponse.Result == EvolvePokemonResponse.Types.Result.FailedPokemonMissing)
{
var releaseMessage = ReleasePokemonMessage.Parser.ParseFrom(request.RequestMessage);
pokemonId = releaseMessage.PokemonId;
}
break;
}
if (pokemonId > 0)
{
var pokemons = _session.Player.Inventory.InventoryItems.Where(
i =>
i?.InventoryItemData?.PokemonData != null &&
i.InventoryItemData.PokemonData.Id.Equals(pokemonId));
_session.Player.Inventory.RemoveInventoryItems(pokemons);
}
}
/// <summary>
/// Handles the default heartbeat responses.
/// </summary>
/// <param name="requestEnvelope"></param>
/// <param name="returns">The payload of the <see cref="ResponseEnvelope" />.</param>
private void HandleDefaultResponses(RequestEnvelope requestEnvelope, IList<ByteString> returns)
{
var responseIndexes = new Dictionary<int, RequestType>();
for (var i = 0; i < requestEnvelope.Requests.Count; i++)
{
var request = requestEnvelope.Requests[i];
if (_defaultRequests.Contains(request.RequestType))
responseIndexes.Add(i, request.RequestType);
}
foreach (var responseIndex in responseIndexes)
{
var bytes = returns[responseIndex.Key];
switch (responseIndex.Value)
{
case RequestType.GetHatchedEggs:
var hatchedEggs = GetHatchedEggsResponse.Parser.ParseFrom(bytes);
if (hatchedEggs.Success)
{
// TODO: Throw event, wrap in an object.
}
break;
case RequestType.GetInventory:
var inventory = GetInventoryResponse.Parser.ParseFrom(bytes);
if (inventory.Success)
{
if (inventory.InventoryDelta.NewTimestampMs >=
_session.Player.Inventory.LastInventoryTimestampMs)
{
_session.Player.Inventory.LastInventoryTimestampMs =
inventory.InventoryDelta.NewTimestampMs;
if (inventory.InventoryDelta != null &&
inventory.InventoryDelta.InventoryItems.Count > 0)
{
_session.Player.Inventory.UpdateInventoryItems(inventory.InventoryDelta);
}
}
}
break;
case RequestType.CheckAwardedBadges:
var awardedBadges = CheckAwardedBadgesResponse.Parser.ParseFrom(bytes);
if (awardedBadges.Success)
{
// TODO: Throw event, wrap in an object.
}
break;
case RequestType.DownloadSettings:
var downloadSettings = DownloadSettingsResponse.Parser.ParseFrom(bytes);
if (string.IsNullOrEmpty(downloadSettings.Error))
{
if (downloadSettings.Settings == null)
{
continue;
}
if (_session.GlobalSettings == null || _session.GlobalSettingsHash != downloadSettings.Hash)
{
_session.GlobalSettingsHash = downloadSettings.Hash;
_session.GlobalSettings = downloadSettings.Settings;
}
else
{
_session.GlobalSettings = downloadSettings.Settings;
}
}
else
{
Logger.Debug($"DownloadSettingsResponse.Error: '{downloadSettings.Error}'");
}
break;
case RequestType.CheckChallenge:
var checkChallenge = CheckChallengeResponse.Parser.ParseFrom(bytes);
if (checkChallenge.ShowChallenge)
{
_session.Pause();
_session.OnCaptchaReceived(checkChallenge.ChallengeUrl);
}
break;
}
}
}
public void Dispose()
{
Dispose(true);
}
internal void Dispose(bool disposing)
{
if (!disposing) return;
_rpcQueueMutex?.Dispose();
}
}
}