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
|
#include "stdafx.h"
#include "DQRNetworkManager.h"
#include "PartyController.h"
#include <collection.h>
#include <ppltasks.h>
#include <ws2tcpip.h>
#include "..\Minecraft.World\StringHelpers.h"
#include "base64.h"
#ifdef _DURANGO
#include "..\Minecraft.World\DurangoStats.h"
#endif
#include "ChatIntegrationLayer.h"
using namespace Concurrency;
using namespace Windows::Foundation::Collections;
// Returns true if we are already processing a request to find game parties of friends
bool DQRNetworkManager::FriendPartyManagerIsBusy()
{
if( m_GetFriendPartyThread )
{
if( m_GetFriendPartyThread->isRunning() )
{
return true;
}
}
return false;
}
// Returns the total count of game parties that we found for our friends
int DQRNetworkManager::FriendPartyManagerGetCount()
{
return m_sessionResultCount;
}
// Initiate the (asynchronous) search for game parties of our friends
bool DQRNetworkManager::FriendPartyManagerSearch()
{
if( m_GetFriendPartyThread )
{
if( m_GetFriendPartyThread->isRunning() )
{
return false;
}
}
m_sessionResultCount = 0;
delete [] m_sessionSearchResults;
m_sessionSearchResults = nullptr;
m_GetFriendPartyThread = new C4JThread(&_GetFriendsThreadProc,this,"GetFriendsThreadProc");
m_GetFriendPartyThread->Run();
return true;
}
// Get a particular search result for a game party that we have discovered. Index should be from 0 to the value returned by FriendPartyManagerGetCount.
void DQRNetworkManager::FriendPartyManagerGetSessionInfo(int idx, SessionSearchResult *searchResult)
{
assert( idx < m_sessionResultCount );
assert( ( m_GetFriendPartyThread == nullptr ) || ( !m_GetFriendPartyThread->isRunning()) );
// Need to make sure that copied data has independently allocated m_extData, so both copies can be freed
*searchResult = m_sessionSearchResults[idx];
searchResult->m_extData = malloc(sizeof(GameSessionData));
memcpy(searchResult->m_extData, m_sessionSearchResults[idx].m_extData, sizeof(GameSessionData));
}
int DQRNetworkManager::_GetFriendsThreadProc(void* lpParameter)
{
DQRNetworkManager *pDQR = static_cast<DQRNetworkManager *>(lpParameter);
return pDQR->GetFriendsThreadProc();
}
// This is the main thread that is kicked off to find game sessions associated with our friends. We have to do this
// by finding parties associated with our friends, and from the parties get the assocated game session.
int DQRNetworkManager::GetFriendsThreadProc()
{
LogComment(L"Starting GetFriendsThreadProc");
WXS::User^ primaryUser = ProfileManager.GetUser(0);
if( primaryUser == nullptr )
{
return -1;
}
MXS::XboxLiveContext^ primaryUserXboxLiveContext = ref new MXS::XboxLiveContext(primaryUser);
if( primaryUserXboxLiveContext == nullptr )
{
return -1;
}
MXSS::XboxSocialRelationshipResult^ socialRelationshipResult = nullptr;
// First get our friends list (people we follow who may or may not follow us back), note we're requesting all friends
auto getSocialRelationshipsAsync = primaryUserXboxLiveContext->SocialService->GetSocialRelationshipsAsync(MXSS::SocialRelationship::All, 0, 1100);
create_task(getSocialRelationshipsAsync).then([this,&socialRelationshipResult](task<MXSS::XboxSocialRelationshipResult^> t)
{
try
{
socialRelationshipResult = t.get();
}
catch (Platform::COMException^ ex)
{
LogCommentWithError( L"GetSocialRelationshipsAsync failed", ex->HResult );
}
})
.wait();
if( socialRelationshipResult == nullptr )
{
return -1;
}
IVector<Platform::String^>^ friendXUIDs = ref new Platform::Collections::Vector<Platform::String^>;
// Now construct a vector of these users, that follow us back - these are our "friends"
for( int i = 0; i < socialRelationshipResult->TotalCount; i++ )
{
MXSS::XboxSocialRelationship^ relationship = socialRelationshipResult->Items->GetAt(i);
if(relationship->IsFollowingCaller)
{
friendXUIDs->Append(relationship->XboxUserId);
}
}
// If we don't have any such friends, we're done
if( friendXUIDs->Size == 0 )
{
return 0;
}
// Now get party associations for these friends
auto getPartyAssociationsAsync = WXM::Party::GetUserPartyAssociationsAsync(primaryUser, friendXUIDs->GetView() );
IVectorView<WXM::UserPartyAssociation^>^ partyResults = nullptr;
create_task(getPartyAssociationsAsync).then([this,&partyResults](task<IVectorView<WXM::UserPartyAssociation^>^> t)
{
try
{
partyResults = t.get();
}
catch (Platform::COMException^ ex)
{
LogCommentWithError( L"getPartyAssociationsAsync failed", ex->HResult );
}
})
.wait();
if( partyResults == nullptr )
{
return -1;
}
if( partyResults->Size == 0 )
{
return 0;
}
// Filter these parties by whether we have permission to see them online
partyResults = FilterPartiesByPermission(primaryUserXboxLiveContext, partyResults);
// At this point, we have Party Ids for our friends. Now we need to get Party Views for each of these Ids.
LogComment("Parties found");
// Get party views for each of the user party associations that we have. These seem to be able to (individually) raise errors, so
// accumulate results into 2 matched vectors declared below so that we can ignore any broken UserPartyAssociations from now
vector<WXM::PartyView^> partyViewVector;
vector<WXM::UserPartyAssociation^> partyResultsVector;
vector<task<void>> taskVector;
for each(WXM::UserPartyAssociation^ remoteParty in partyResults)
{
auto asyncOp = WXM::Party::GetPartyViewByPartyIdAsync( primaryUser, remoteParty->PartyId );
task<WXM::PartyView^> asyncTask = create_task(asyncOp);
taskVector.push_back(asyncTask.then([this, &partyViewVector, &partyResultsVector, remoteParty] (task<WXM::PartyView^> t)
{
try
{
WXM::PartyView^ partyView = t.get();
if( partyView != nullptr )
{
app.DebugPrintf("Got party view\n");
EnterCriticalSection(&m_csPartyViewVector);
partyViewVector.push_back(partyView);
partyResultsVector.push_back(remoteParty);
LeaveCriticalSection(&m_csPartyViewVector);
}
}
catch ( Platform::COMException^ ex )
{
app.DebugPrintf("Getting party view error 0x%x\n",ex->HResult);
}
}));
}
for( auto it = taskVector.begin(); it != taskVector.end(); it++ )
{
it->wait();
}
if( partyViewVector.size() == 0 )
{
return 0;
}
// Filter the party view, and party results vector (partyResultsVector) this is matched to, to remove any that don't have game sessions - or game sessions that aren't this game
vector<WXM::PartyView^> partyViewVectorFiltered;
vector<WXM::UserPartyAssociation^> partyResultsFiltered;
for( int i = 0; i < partyViewVector.size(); i++ )
{
WXM::PartyView^ partyView = partyViewVector[i];
if( partyView->Joinability == WXM::SessionJoinability::JoinableByFriends )
{
if( partyView->GameSession )
{
if( partyView->GameSession->ServiceConfigurationId == SERVICE_CONFIG_ID )
{
partyViewVectorFiltered.push_back( partyView );
partyResultsFiltered.push_back( partyResultsVector[i] );
}
}
}
}
// We now have matched vectors:
//
// partyResultsFiltered
// partyViewVectorFiltered
//
// and, from the party views, we can now attempt to get game sessions
vector<MXSM::MultiplayerSession^> sessionVector;
vector<WXM::PartyView^> partyViewVectorValid;
vector<WXM::UserPartyAssociation^> partyResultsValid;
for( int i = 0; i < partyViewVectorFiltered.size(); i++ )
{
WXM::PartyView^ partyView = partyViewVectorFiltered[i];
Microsoft::Xbox::Services::Multiplayer::MultiplayerSessionReference^ sessionRef = ConvertToMicrosoftXboxServicesMultiplayerSessionReference(partyView->GameSession);
LogComment(L"Party view vector " + sessionRef->SessionName + L" " + partyResultsFiltered[i]->QueriedXboxUserIds->GetAt(0));
MXSM::MultiplayerSession^ session = nullptr;
auto asyncOp = primaryUserXboxLiveContext->MultiplayerService->GetCurrentSessionAsync( sessionRef );
create_task(asyncOp).then([&session] (task<MXSM::MultiplayerSession^> t)
{
try
{
session = t.get();
}
catch (Platform::COMException^ ex)
{
}
})
.wait();
if( session )
{
sessionVector.push_back(session);
partyViewVectorValid.push_back(partyView);
partyResultsValid.push_back(partyResultsFiltered[i]);
}
}
if( sessionVector.size() == 0 )
{
return 0;
}
// We now have matched vectors:
//
// partyResultsValid
// partyViewVectorValid
// sessionVector
// The next stage is to resolve the display names for the XUIDs of all the players in each of the sessions. It is possible that
// a session won't have any XUIDs to resolve, which would make GetUserProfilesAsync unhappy, so we'll only be creating a task
// when there are members. Creating new matching arrays for party results and sessions, to match the results (we don't care about the party view anymore)
vector<task<IVectorView<MXSS::XboxUserProfile^>^>> nameResolveTaskVector;
vector<IVectorView<MXSS::XboxUserProfile^>^> nameResolveVector;
vector<MXSM::MultiplayerSession^> newSessionVector;
vector<WXM::UserPartyAssociation^> newPartyVector;
for( int j = 0; j < sessionVector.size(); j++ )
{
MXSM::MultiplayerSession^ session = sessionVector[j];
IVector<Platform::String^>^ memberXUIDs = ref new Platform::Collections::Vector<Platform::String^>;
Windows::Data::Json::JsonArray^ roomSyncArray = nullptr;
try
{
Windows::Data::Json::JsonObject^ customJson = Windows::Data::Json::JsonObject::Parse(session->SessionProperties->SessionCustomPropertiesJson);
Windows::Data::Json::JsonValue^ customValue = customJson->GetNamedValue(L"RoomSyncData");
roomSyncArray = customValue->GetArray();
LogComment("Attempting to parse RoomSyncData");
for( int i = 0; i < roomSyncArray->Size; i++ )
{
LogComment(roomSyncArray->GetAt(i)->GetString());
}
}
catch (Platform::COMException^ ex)
{
LogCommentWithError( L"Custom RoomSyncData Parse/GetNamedValue failed", ex->HResult );
continue;
}
if( roomSyncArray && ( roomSyncArray->Size > 0 ) )
{
// For each session, we want to order these XUIDs so the display name of the first one is what we will name the session by. Prioritise doing this by:
//
// (1) If the host player (indicated by having a small id of 0) is our friend, use that
// (2) Otherwise use anyone who is our friend
// Default to true
bool friendsOfFriends = true;
int hostIndexFound = -1;
int friendIndexFound = -1;
friendsOfFriends = IsSessionFriendsOfFriends(session);
for( int i = 0; i < roomSyncArray->Size; i++ )
{
Platform::String^ roomSyncXuid = roomSyncArray->GetAt(i)->GetString();
// Determine if this player is a friend
bool isFriend = false;
for each( Platform::String^ friendXUID in friendXUIDs )
{
if( friendXUID == roomSyncXuid )
{
isFriend = true;
break;
}
}
bool isHost = i == 0;
// Store that what we found at this index if it is a friend, or a friend who is a host
if( isFriend && ( friendsOfFriends || isHost ) )
{
friendIndexFound = i;
if( isHost ) // Host is always in slot 0
{
hostIndexFound = i;
}
}
}
// Prefer to use index of host who is our friend
int bestIndex = friendIndexFound;
if( hostIndexFound != -1 )
{
bestIndex = hostIndexFound;
}
// Only consider if we have at least found one friend in the list of players
if( bestIndex != -1 )
{
// Compile list of XUIDs to resolve with our specially chosen player as entry 0, then the rest
memberXUIDs->Append(roomSyncArray->GetAt(bestIndex)->GetString());
for( int i = 0; i < roomSyncArray->Size; i++ )
{
if( i != bestIndex )
{
memberXUIDs->Append(roomSyncArray->GetAt(i)->GetString());
}
}
nameResolveTaskVector.push_back( create_task( primaryUserXboxLiveContext->ProfileService->GetUserProfilesAsync( memberXUIDs->GetView() ) ) );
newSessionVector.push_back(session);
newPartyVector.push_back(partyResultsValid[j]);
}
}
}
try
{
auto joinTask = when_all(begin(nameResolveTaskVector), end(nameResolveTaskVector) ).then([this, &nameResolveVector](vector<IVectorView<MXSS::XboxUserProfile^>^> results)
{
nameResolveVector = results;
})
.wait();
}
catch(Platform::COMException^ ex)
{
return -1;
}
// We now have matched vectors:
//
// newPartyVector - contains the party Ids that we'll need should we wish to join
// nameResolveVector - contains vectors views of the names of the members of the session each of these parties is in
// newSessionVector - contains the session information itself associated with each of the parties
// Construct the final result vector
m_sessionResultCount = newSessionVector.size();
m_sessionSearchResults = new SessionSearchResult[m_sessionResultCount];
for( int i = 0; i < m_sessionResultCount; i++ )
{
m_sessionSearchResults[i].m_partyId = newPartyVector[i]->PartyId->Data();
m_sessionSearchResults[i].m_sessionName = newSessionVector[i]->SessionReference->SessionName->Data();
for( int j = 0; j < nameResolveVector[i]->Size; j++ )
{
m_sessionSearchResults[i].m_playerNames[j] = nameResolveVector[i]->GetAt(j)->GameDisplayName->Data();
m_sessionSearchResults[i].m_playerXuids[j] = static_cast<PlayerUID>(nameResolveVector[i]->GetAt(j)->XboxUserId->Data());
}
m_sessionSearchResults[i].m_playerCount = nameResolveVector[i]->Size;
m_sessionSearchResults[i].m_usedSlotCount = newSessionVector[i]->Members->Size;
if( m_sessionSearchResults[i].m_usedSlotCount > MAX_ONLINE_PLAYER_COUNT )
{
// Don't think this could ever happen, but no harm in checking
m_sessionSearchResults[i].m_usedSlotCount = MAX_ONLINE_PLAYER_COUNT;
}
for( int j = 0; j < m_sessionSearchResults[i].m_usedSlotCount; j++ )
{
m_sessionSearchResults[i].m_sessionXuids[j] = wstring( newSessionVector[i]->Members->GetAt(j)->XboxUserId->Data() );
}
m_sessionSearchResults[i].m_extData = malloc( sizeof(GameSessionData) );
memset( m_sessionSearchResults[i].m_extData, 0, sizeof(GameSessionData) );
GetGameSessionData(newSessionVector[i], m_sessionSearchResults[i].m_extData);
}
return 0;
}
// Filters list of parties based on online presence permission (whether the friend is set to invisible or not)
IVectorView<WXM::UserPartyAssociation^>^ DQRNetworkManager::FilterPartiesByPermission(MXS::XboxLiveContext ^context, IVectorView<WXM::UserPartyAssociation^>^ partyResults)
{
Platform::Collections::Vector<WXM::UserPartyAssociation^>^ filteredPartyResults = ref new Platform::Collections::Vector<WXM::UserPartyAssociation^>();
// List of permissions we want
auto permissionIds = ref new Platform::Collections::Vector<Platform::String^>(1, ref new Platform::String(L"ViewTargetPresence"));
// List of target users
auto targetXboxUserIds = ref new Platform::Collections::Vector<Platform::String^>();
for (int i = 0; i < partyResults->Size; i++)
{
assert(partyResults->GetAt(i)->QueriedXboxUserIds->Size > 0);
targetXboxUserIds->Append( partyResults->GetAt(i)->QueriedXboxUserIds->GetAt(0) );
}
// Check
auto checkPermissionsAsync = context->PrivacyService->CheckMultiplePermissionsWithMultipleTargetUsersAsync(permissionIds->GetView(), targetXboxUserIds->GetView());
create_task(checkPermissionsAsync).then([&partyResults, &filteredPartyResults](task<IVectorView<MXS::Privacy::MultiplePermissionsCheckResult^>^> t)
{
try
{
auto results = t.get();
// For each party, check to see if we have permission for the user
for (int i = 0; i < partyResults->Size; i++)
{
// For each permissions result
for (int j = 0; j < results->Size; j++)
{
auto result = results->GetAt(j);
// If allowed to see this user AND it's the same user, add the party to the just
if ((result->Items->GetAt(0)->IsAllowed) && (partyResults->GetAt(i)->QueriedXboxUserIds->GetAt(0) == result->XboxUserId))
{
filteredPartyResults->Append(partyResults->GetAt(i));
break;
}
}
}
}
catch (Platform::COMException^ ex)
{
LogCommentWithError( L"CheckMultiplePermissionsWithMultipleTargetUsersAsync failed", ex->HResult );
}
})
.wait();
app.DebugPrintf("DQRNetworkManager::FilterPartiesByPermission: Removed %i parties because of online presence permissions\n", partyResults->Size - filteredPartyResults->Size);
return filteredPartyResults->GetView();
}
// Get all friends (list of XUIDs) syncronously from the service (slow, may take 300ms+), returns empty list if something goes wrong
Platform::Collections::Vector<Platform::String^>^ DQRNetworkManager::GetFriends()
{
auto friends = ref new Platform::Collections::Vector<Platform::String^>;
auto primaryUser = ProfileManager.GetUser(0);
if (primaryUser == nullptr)
{
// Return empty
return friends;
}
auto xboxLiveContext = ref new MXS::XboxLiveContext(primaryUser);
// Request ALL friends because there's no other way to check friendships without using the REST API
auto getSocialRelationshipsAsync = xboxLiveContext->SocialService->GetSocialRelationshipsAsync(MXSS::SocialRelationship::All, 0, 1100);
MXSS::XboxSocialRelationshipResult^ socialRelationshipResult = nullptr;
// First get our friends list (people we follow who may or may not follow us back)
Concurrency::create_task(getSocialRelationshipsAsync).then([&socialRelationshipResult](Concurrency::task<MXSS::XboxSocialRelationshipResult^> t)
{
try
{
socialRelationshipResult = t.get();
}
catch (Platform::COMException^ ex)
{
app.DebugPrintf("DQRNetworkManager::GetFriends: GetSocialRelationshipsAsync failed ()\n", ex->HResult);
}
})
.wait();
if (socialRelationshipResult == nullptr)
{
// Return empty
return friends;
}
app.DebugPrintf("DQRNetworkManager::GetFriends: Retrieved %i relationships\n", socialRelationshipResult->TotalCount);
// Now construct a vector of these users, that follow us back - these are our "friends"
for( int i = 0; i < socialRelationshipResult->TotalCount; i++ )
{
MXSS::XboxSocialRelationship^ relationship = socialRelationshipResult->Items->GetAt(i);
if(relationship->IsFollowingCaller)
{
app.DebugPrintf("DQRNetworkManager::GetFriends: Found friend \"%ls\"\n", relationship->XboxUserId->Data());
friends->Append(relationship->XboxUserId);
}
}
app.DebugPrintf("DQRNetworkManager::GetFriends: Found %i 2-way friendships\n", friends->Size);
return friends;
}
// If data for game settings exists returns FriendsOfFriends value, otherwise returns true
bool DQRNetworkManager::IsSessionFriendsOfFriends(MXSM::MultiplayerSession^ session)
{
// Default to true, don't want to incorrectly prevent joining
bool friendsOfFriends = true;
// We retrieve the game session data later too, shouldn't really duplicate this
void *gameSessionData = malloc( sizeof(GameSessionData));
memset(gameSessionData, 0, sizeof(GameSessionData));
bool result = GetGameSessionData(session, gameSessionData);
if (result)
{
friendsOfFriends = app.GetGameHostOption(static_cast<GameSessionData *>(gameSessionData)->m_uiGameHostSettings, eGameHostOption_FriendsOfFriends);
}
free(gameSessionData);
return friendsOfFriends;
}
// Parses custom json data from session and populates game session data param, return true if parse succeeded
bool DQRNetworkManager::GetGameSessionData(MXSM::MultiplayerSession^ session, void *gameSessionData)
{
Platform::String ^gameSessionDataJson = session->SessionProperties->SessionCustomPropertiesJson;
if( gameSessionDataJson )
{
try
{
Windows::Data::Json::JsonObject^ customParam = Windows::Data::Json::JsonObject::Parse(gameSessionDataJson);
Windows::Data::Json::JsonValue^ customValue = customParam->GetNamedValue(L"GameSessionData");
Platform::String ^customValueString = customValue->GetString();
if( customValueString )
{
base64_decode( customValueString, static_cast<unsigned char *>(gameSessionData), sizeof(GameSessionData) );
return true;
}
}
catch (Platform::COMException^ ex)
{
LogCommentWithError( L"Custom GameSessionData parameter Parse/GetNamedValue failed", ex->HResult );
}
}
return false;
}
|