Exemplo n.º 1
0
        ///<summary></summary>
        /// <seealso cref="GooglePlayGames.BasicApi.IPlayGamesClient.SignOut"/>
        public void SignOut()
        {
            if (mTokenClient == null)
            {
                return;
            }

            if (mInvitationCallback != null)
            {
                using (var invitationsClient = getInvitationsClient())
                    using (var task = invitationsClient.Call <AndroidJavaObject>(
                               "unregisterInvitationCallback", mInvitationCallback))
                    {
                        AndroidTaskUtils.AddOnCompleteListener <AndroidJavaObject>(
                            task,
                            completedTask =>
                        {
                            mInvitationCallback = null;
                            mTokenClient.Signout();
                            mAuthState = AuthState.Unauthenticated;
                        });
                    }
            }
            else
            {
                mTokenClient.Signout();
                mAuthState = AuthState.Unauthenticated;
            }
        }
Exemplo n.º 2
0
        ///<summary></summary>
        /// <seealso cref="GooglePlayGames.BasicApi.IPlayGamesClient.LoadMoreScores"/>
        public void LoadMoreScores(ScorePageToken token, int rowCount,
                                   Action <LeaderboardScoreData> callback)
        {
            using (var client = getLeaderboardsClient())
                using (var task = client.Call <AndroidJavaObject>("loadMoreScores",
                                                                  token.InternalObject, rowCount, AndroidJavaConverter.ToPageDirection(token.Direction)))
                {
                    AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                        task,
                        annotatedData =>
                    {
                        using (var leaderboardScores = annotatedData.Call <AndroidJavaObject>("get"))
                        {
                            InvokeCallbackOnGameThread(callback, CreateLeaderboardScoreData(
                                                           token.LeaderboardId,
                                                           token.Collection,
                                                           token.TimeSpan,
                                                           annotatedData.Call <bool>("isStale")
                                    ? ResponseStatus.SuccessWithStale
                                    : ResponseStatus.Success,
                                                           leaderboardScores));
                            leaderboardScores.Call("release");
                        }
                    });

                    AndroidTaskUtils.AddOnFailureListener(
                        task,
                        exception =>
                    {
                        Debug.Log("LoadMoreScores failed");
                        InvokeCallbackOnGameThread(callback,
                                                   new LeaderboardScoreData(token.LeaderboardId, ResponseStatus.InternalError));
                    });
                }
        }
        public void Rematch(TurnBasedMatch match, Action <bool, TurnBasedMatch> callback)
        {
            callback = ToOnGameThread(callback);

            FindEqualVersionMatch(match, (success, foundMatch) =>
            {
                if (!success)
                {
                    callback(false, null);
                    return;
                }

                using (var task = mClient.Call <AndroidJavaObject>("rematch", match.MatchId))
                {
                    AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                        task,
                        turnBasedMatch =>
                        callback(true, AndroidJavaConverter.ToTurnBasedMatch(turnBasedMatch)));

                    AndroidTaskUtils.AddOnFailureListener(
                        task,
                        e => callback(false, null));
                }
            });
        }
        private void FindInvitationWithId(string invitationId, Action <Invitation> callback)
        {
            using (var task = mClient.Call <AndroidJavaObject>("loadMatchesByStatus", new int[] { 0, 1, 2, 3 }))
            {
                AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                    task,
                    annotatedData =>
                {
                    using (var matchesResponse = annotatedData.Call <AndroidJavaObject>("get"))
                        using (var invitationsBuffer = matchesResponse.Call <AndroidJavaObject>("getInvitations"))
                        {
                            int count = invitationsBuffer.Call <int>("getCount");
                            for (int i = 0; i < count; ++i)
                            {
                                Invitation invitation =
                                    AndroidJavaConverter.ToInvitation(
                                        invitationsBuffer.Call <AndroidJavaObject>("get", (int)i));
                                if (invitation.InvitationId == invitationId)
                                {
                                    callback(invitation);
                                    return;
                                }
                            }
                        }

                    callback(null);
                });

                AndroidTaskUtils.AddOnFailureListener(task, e => callback(null));
            }
        }
        public void StartDiscovery(string serviceId, TimeSpan?advertisingDuration,
                                   IDiscoveryListener listener)
        {
            Misc.CheckNotNull(serviceId, "serviceId");
            Misc.CheckNotNull(listener, "listener");

            var listenerOnGameThread = new OnGameThreadDiscoveryListener(listener);

            if (advertisingDuration.HasValue && advertisingDuration.Value.Ticks < 0)
            {
                throw new InvalidOperationException("advertisingDuration must be positive");
            }

            using (var endpointDiscoveryCallback = new AndroidJavaObject(
                       "com.google.games.bridge.EndpointDiscoveryCallbackProxy",
                       new EndpointDiscoveryCallback(listenerOnGameThread)))
                using (var discoveryOptions = CreateDiscoveryOptions())
                    using (var task = mClient.Call <AndroidJavaObject>("startDiscovery", serviceId, endpointDiscoveryCallback,
                                                                       discoveryOptions))
                    {
                        AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                            task,
                            v => NearbyHelperObject.StartDiscoveryTimer(advertisingDuration)
                            );
                    }
        }
Exemplo n.º 6
0
        public void GetAllInvitations(Action <Invitation[]> callback)
        {
            callback = ToOnGameThread(callback);
            using (var task = mInvitationsClient.Call <AndroidJavaObject>("loadInvitations"))
            {
                AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                    task,
                    annotatedData =>
                {
                    using (var invitationBuffer = annotatedData.Call <AndroidJavaObject>("get"))
                    {
                        int count = invitationBuffer.Call <int>("getCount");
                        Invitation[] invitations = new Invitation[count];
                        for (int i = 0; i < count; i++)
                        {
                            using (var invitationObject = invitationBuffer.Call <AndroidJavaObject>("get", i))
                            {
                                invitations[i] = AndroidJavaConverter.ToInvitation(invitationObject);
                            }
                        }

                        callback(invitations);
                    }
                });

                AndroidTaskUtils.AddOnFailureListener(
                    task,
                    exception => callback(null));
            }
        }
        private void GetMatchAndroidJavaObject(string matchId, Action <bool, AndroidJavaObject> callback)
        {
            using (var task = mClient.Call <AndroidJavaObject>("loadMatch", matchId))
            {
                AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                    task,
                    annotatedData =>
                {
                    using (var turnBasedMatch = annotatedData.Call <AndroidJavaObject>("get"))
                    {
                        if (turnBasedMatch == null)
                        {
                            OurUtils.Logger.e(string.Format("Could not find match {0}", matchId));
                            callback(false, null);
                        }
                        else
                        {
                            callback(true, turnBasedMatch);
                        }
                    }
                });

                AndroidTaskUtils.AddOnFailureListener(task, exception => callback(false, null));
            }
        }
        public void CreateQuickMatch(uint minOpponents, uint maxOpponents, uint variant,
                                     ulong exclusiveBitmask, Action <bool, TurnBasedMatch> callback)
        {
            callback = ToOnGameThread(callback);

            using (var matchConfigClass =
                       new AndroidJavaClass("com.google.android.gms.games.multiplayer.turnbased.TurnBasedMatchConfig"))
                using (var matchConfigBuilder = matchConfigClass.CallStatic <AndroidJavaObject>("builder"))
                    using (var autoMatchCriteria = matchConfigClass.CallStatic <AndroidJavaObject>("createAutoMatchCriteria",
                                                                                                   (int)minOpponents, (int)maxOpponents, (long)exclusiveBitmask))
                    {
                        matchConfigBuilder.Call <AndroidJavaObject>("setAutoMatchCriteria", autoMatchCriteria);

                        if (variant != 0)
                        {
                            matchConfigBuilder.Call <AndroidJavaObject>("setVariant", (int)variant);
                        }

                        using (var matchConfig = matchConfigBuilder.Call <AndroidJavaObject>("build"))
                            using (var task = mClient.Call <AndroidJavaObject>("createMatch", matchConfig))
                            {
                                AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                                    task,
                                    turnBasedMatch =>
                                    callback(true, AndroidJavaConverter.ToTurnBasedMatch(turnBasedMatch)));

                                AndroidTaskUtils.AddOnFailureListener(task, e => callback(false, null));
                            }
                    }
        }
        public void GetAllInvitations(Action <Invitation[]> callback)
        {
            callback = ToOnGameThread(callback);

            using (var task = mClient.Call <AndroidJavaObject>("loadMatchesByStatus", new int[] { 0, 1, 2, 3 }))
            {
                AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                    task,
                    annotatedData =>
                {
                    using (var matchesResponse = annotatedData.Call <AndroidJavaObject>("get"))
                        using (var invitationsBuffer = matchesResponse.Call <AndroidJavaObject>("getInvitations"))
                        {
                            int count = invitationsBuffer.Call <int>("getCount");
                            Invitation[] invitations = new Invitation[count];
                            for (int i = 0; i < count; i++)
                            {
                                using (var invitation = invitationsBuffer.Call <AndroidJavaObject>("get", (int)i))
                                {
                                    invitations[i] = AndroidJavaConverter.ToInvitation(invitation);
                                }
                            }

                            callback(invitations);
                        }
                });

                AndroidTaskUtils.AddOnFailureListener(task, e => callback(null));
            }
        }
        public void GetMatch(string matchId, Action <bool, TurnBasedMatch> callback)
        {
            callback = ToOnGameThread(callback);

            using (var task = mClient.Call <AndroidJavaObject>("loadMatch", matchId))
            {
                AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                    task,
                    annotatedData =>
                {
                    using (var turnBasedMatch = annotatedData.Call <AndroidJavaObject>("get"))
                    {
                        if (turnBasedMatch == null)
                        {
                            OurUtils.Logger.e(string.Format("Could not find match {0}", matchId));
                            callback(false, null);
                        }
                        else
                        {
                            callback(true, AndroidJavaConverter.ToTurnBasedMatch(turnBasedMatch));
                        }
                    }
                });

                AndroidTaskUtils.AddOnFailureListener(task, e => callback(false, null));
            }
        }
        public void StartAdvertising(string name, List <string> appIdentifiers,
                                     TimeSpan?advertisingDuration, Action <AdvertisingResult> resultCallback,
                                     Action <ConnectionRequest> connectionRequestCallback)
        {
            Misc.CheckNotNull(resultCallback, "resultCallback");
            Misc.CheckNotNull(connectionRequestCallback, "connectionRequestCallback");

            if (advertisingDuration.HasValue && advertisingDuration.Value.Ticks < 0)
            {
                throw new InvalidOperationException("advertisingDuration must be positive");
            }

            connectionRequestCallback = ToOnGameThread(connectionRequestCallback);
            resultCallback            = ToOnGameThread(resultCallback);

            AdvertisingConnectionLifecycleCallbackProxy callbackProxy =
                new AdvertisingConnectionLifecycleCallbackProxy(resultCallback, connectionRequestCallback, this);

            using (var connectionLifecycleCallback =
                       new AndroidJavaObject("com.google.games.bridge.ConnectionLifecycleCallbackProxy", callbackProxy))
                using (var advertisingOptions = CreateAdvertisingOptions())
                    using (var task = mClient.Call <AndroidJavaObject>("startAdvertising", name, GetServiceId(),
                                                                       connectionLifecycleCallback, advertisingOptions))
                    {
                        AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                            task,
                            v => NearbyHelperObject.StartAdvertisingTimer(advertisingDuration)
                            );
                    }
        }
Exemplo n.º 12
0
        public void RequestPermissions(string[] scopes, Action <SignInStatus> callback)
        {
            using (var bridgeClass = new AndroidJavaClass(HelperFragmentClass))
                using (var currentActivity = AndroidHelperFragment.GetActivity())
                    using (var task =
                               bridgeClass.CallStatic <AndroidJavaObject>("showRequestPermissionsUi", currentActivity,
                                                                          oauthScopes.Union(scopes).ToArray()))
                    {
                        AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(task, /* disposeResult= */ false,
                                                                                  accountWithNewScopes =>
                        {
                            if (accountWithNewScopes == null)
                            {
                                callback(SignInStatus.InternalError);
                                return;
                            }

                            account     = accountWithNewScopes;
                            email       = account.Call <string>("getEmail");
                            idToken     = account.Call <string>("getIdToken");
                            authCode    = account.Call <string>("getServerAuthCode");
                            oauthScopes = oauthScopes.Union(scopes).ToList();
                            callback(SignInStatus.Success);
                        });

                        AndroidTaskUtils.AddOnFailureListener(task, e =>
                        {
                            var failCode = SignInHelper.ToSignInStatus(e.Call <int>("getStatusCode"));
                            OurUtils.Logger.e("Exception requesting new permissions: " + failCode);
                            callback(failCode);
                        });
                    }
        }
Exemplo n.º 13
0
        public static void ShowInvitationInboxUI(Action <UIStatus, Invitation> cb)
        {
            using (var helperFragment = new AndroidJavaClass(HelperFragmentClass))
                using (var task = helperFragment.CallStatic <AndroidJavaObject>("showInvitationInboxUI",
                                                                                AndroidHelperFragment.GetActivity()))
                {
                    AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                        task,
                        result =>
                    {
                        int status = result.Get <int>("status");
                        if ((UIStatus)status != UIStatus.Valid)
                        {
                            cb.Invoke((UIStatus)status, null);
                            return;
                        }

                        using (var invitation = result.Get <AndroidJavaObject>("invitation"))
                        {
                            cb.Invoke((UIStatus)status, AndroidJavaConverter.ToInvitation(invitation));
                        }
                    });

                    AndroidTaskUtils.AddOnFailureListener(
                        task,
                        exception =>
                    {
                        Debug.Log("ShowInvitationInboxUI failed with exception");
                        cb.Invoke(UIStatus.InternalError, null);
                    });
                }
        }
Exemplo n.º 14
0
            public void ChooseMetadata(ISavedGameMetadata chosenMetadata)
            {
                AndroidSnapshotMetadata convertedMetadata = chosenMetadata as AndroidSnapshotMetadata;

                if (convertedMetadata != mOriginal && convertedMetadata != mUnmerged)
                {
                    OurUtils.Logger.e("Caller attempted to choose a version of the metadata that was not part " +
                                      "of the conflict");
                    mCompleteCallback(SavedGameRequestStatus.BadInputError, null);
                    return;
                }

                using (var task = mSnapshotsClient.Call <AndroidJavaObject>(
                           "resolveConflict", mConflict.Call <string>("getConflictId"), convertedMetadata.JavaSnapshot))
                {
                    AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                        task,
                        dataOrConflict => mRetryFileOpen());

                    mAndroidSavedGameClient.AddOnFailureListenerWithSignOut(
                        task,
                        exception => {
                        OurUtils.Logger.d("ChooseMetadata failed: " + exception.Call <string>("toString"));
                        var status = mAndroidSavedGameClient.mAndroidClient.IsAuthenticated() ?
                                     SavedGameRequestStatus.InternalError :
                                     SavedGameRequestStatus.AuthenticationError;
                        mCompleteCallback(status, null);
                    }
                        );
                }
            }
Exemplo n.º 15
0
        public static void ShowSelectSnapshotUI(bool showCreateSaveUI, bool showDeleteSaveUI,
                                                int maxDisplayedSavedGames, string uiTitle, Action <SelectUIStatus, ISavedGameMetadata> cb)
        {
            using (var helperFragment = new AndroidJavaClass(HelperFragmentClass))
                using (var task = helperFragment.CallStatic <AndroidJavaObject>("showSelectSnapshotUi",
                                                                                GetActivity(), uiTitle, showCreateSaveUI, showDeleteSaveUI,
                                                                                maxDisplayedSavedGames))
                {
                    AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                        task,
                        result =>
                    {
                        var status = (SelectUIStatus)result.Get <int>("status");
                        Logger.d("ShowSelectSnapshotUI result " + status);

                        var javaMetadata = result.Get <AndroidJavaObject>("metadata");
                        var metadata     =
                            javaMetadata == null
                                ? null
                                : new AndroidSnapshotMetadata(javaMetadata, /* contents= */ null);

                        cb.Invoke(status, metadata);
                    });

                    AndroidTaskUtils.AddOnFailureListener(
                        task,
                        exception =>
                    {
                        Logger.e("ShowSelectSnapshotUI failed with exception");
                        cb.Invoke(SelectUIStatus.InternalError, null);
                    });
                }
        }
Exemplo n.º 16
0
        public void CreateWithInvitationScreen(uint minOpponents, uint maxOpponents, uint variant,
                                               Action <UIStatus, TurnBasedMatch> callback)
        {
            callback = ToOnGameThread(callback);

            AndroidHelperFragment.ShowTbmpSelectOpponentsUI(minOpponents, maxOpponents,
                                                            (status, result) =>
            {
                if (status != UIStatus.Valid)
                {
                    callback(status, null);
                    return;
                }

                using (var matchConfigClass =
                           new AndroidJavaClass("com.google.android.gms.games.multiplayer.turnbased.TurnBasedMatchConfig"))
                    using (var matchConfigBuilder = matchConfigClass.CallStatic <AndroidJavaObject>("builder"))
                    {
                        if (result.MinAutomatchingPlayers > 0)
                        {
                            using (var autoMatchCriteria = matchConfigClass.CallStatic <AndroidJavaObject>(
                                       "createAutoMatchCriteria", result.MinAutomatchingPlayers,
                                       result.MaxAutomatchingPlayers, /* exclusiveBitMask= */ (long)0))
                                using (matchConfigBuilder.Call <AndroidJavaObject>("setAutoMatchCriteria",
                                                                                   autoMatchCriteria))
                                    ;
                        }

                        if (variant != 0)
                        {
                            using (matchConfigBuilder.Call <AndroidJavaObject>("setVariant", (int)variant));
                        }

                        using (var invitedPlayersObject = new AndroidJavaObject("java.util.ArrayList"))
                        {
                            for (int i = 0; i < result.PlayerIdsToInvite.Count; ++i)
                            {
                                invitedPlayersObject.Call <bool>("add", result.PlayerIdsToInvite[i]);
                            }

                            using (matchConfigBuilder.Call <AndroidJavaObject>("addInvitedPlayers", invitedPlayersObject)
                                   );
                        }

                        using (var matchConfig = matchConfigBuilder.Call <AndroidJavaObject>("build"))
                            using (var task = mClient.Call <AndroidJavaObject>("createMatch", matchConfig))
                            {
                                AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                                    task,
                                    turnBasedMatch =>
                                    callback(UIStatus.Valid, AndroidJavaConverter.ToTurnBasedMatch(turnBasedMatch)));

                                AndroidTaskUtils.AddOnFailureListener(
                                    task,
                                    exception => callback(UIStatus.InternalError, null));
                            }
                    }
            });
        }
Exemplo n.º 17
0
        ///<summary></summary>
        /// <seealso cref="GooglePlayGames.BasicApi.IPlayGamesClient.LoadAchievements"/>
        public void LoadAchievements(Action <Achievement[]> callback)
        {
            using (var achievementsClient = getAchievementsClient())
                using (var task = achievementsClient.Call <AndroidJavaObject>("load", /* forceReload= */ false))
                {
                    AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                        task,
                        annotatedData =>
                    {
                        using (var achievementBuffer = annotatedData.Call <AndroidJavaObject>("get"))
                        {
                            int count            = achievementBuffer.Call <int>("getCount");
                            Achievement[] result = new Achievement[count];
                            for (int i = 0; i < count; ++i)
                            {
                                Achievement achievement = new Achievement();
                                using (var javaAchievement = achievementBuffer.Call <AndroidJavaObject>("get", i))
                                {
                                    achievement.Id          = javaAchievement.Call <string>("getAchievementId");
                                    achievement.Description = javaAchievement.Call <string>("getDescription");
                                    achievement.Name        = javaAchievement.Call <string>("getName");
                                    achievement.Points      = javaAchievement.Call <ulong>("getXpValue");

                                    long timestamp = javaAchievement.Call <long>("getLastUpdatedTimestamp");
                                    achievement.LastModifiedTime = AndroidJavaConverter.ToDateTime(timestamp);

                                    achievement.RevealedImageUrl = javaAchievement.Call <string>("getRevealedImageUrl");
                                    achievement.UnlockedImageUrl = javaAchievement.Call <string>("getUnlockedImageUrl");
                                    achievement.IsIncremental    =
                                        javaAchievement.Call <int>("getType") == 1 /* TYPE_INCREMENTAL */;
                                    if (achievement.IsIncremental)
                                    {
                                        achievement.CurrentSteps = javaAchievement.Call <int>("getCurrentSteps");
                                        achievement.TotalSteps   = javaAchievement.Call <int>("getTotalSteps");
                                    }

                                    int state = javaAchievement.Call <int>("getState");
                                    achievement.IsUnlocked = state == 0 /* STATE_UNLOCKED */;
                                    achievement.IsRevealed = state == 1 /* STATE_REVEALED */;
                                }

                                result[i] = achievement;
                            }

                            achievementBuffer.Call("release");
                            InvokeCallbackOnGameThread(callback, result);
                        }
                    });

                    AndroidTaskUtils.AddOnFailureListener(
                        task,
                        exception =>
                    {
                        Debug.Log("LoadAchievements failed");
                        InvokeCallbackOnGameThread(callback, new Achievement[0]);
                    });
                }
        }
Exemplo n.º 18
0
        public void CommitUpdate(ISavedGameMetadata metadata, SavedGameMetadataUpdate updateForMetadata,
                                 byte[] updatedBinaryData, Action <SavedGameRequestStatus, ISavedGameMetadata> callback)
        {
            Misc.CheckNotNull(metadata);
            Misc.CheckNotNull(updatedBinaryData);
            Misc.CheckNotNull(callback);

            callback = ToOnGameThread(callback);

            AndroidSnapshotMetadata convertedMetadata = metadata as AndroidSnapshotMetadata;

            if (convertedMetadata == null)
            {
                OurUtils.Logger.e("Encountered metadata that was not generated by this ISavedGameClient");
                callback(SavedGameRequestStatus.BadInputError, null);
                return;
            }

            if (!convertedMetadata.IsOpen)
            {
                OurUtils.Logger.e("This method requires an open ISavedGameMetadata.");
                callback(SavedGameRequestStatus.BadInputError, null);
                return;
            }

            if (!convertedMetadata.JavaContents.Call <bool>("writeBytes", updatedBinaryData))
            {
                OurUtils.Logger.e("This method requires an open ISavedGameMetadata.");
                callback(SavedGameRequestStatus.BadInputError, null);
            }

            using (var convertedMetadataChange = AsMetadataChange(updateForMetadata))
                using (var task = mSnapshotsClient.Call <AndroidJavaObject>("commitAndClose", convertedMetadata.JavaSnapshot,
                                                                            convertedMetadataChange))
                {
                    AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                        task,
                        /* disposeResult= */ false,
                        snapshotMetadata =>
                    {
                        Debug.Log("commitAndClose.succeed");
                        callback(SavedGameRequestStatus.Success,
                                 new AndroidSnapshotMetadata(snapshotMetadata, /* contents= */ null));
                    });

                    AddOnFailureListenerWithSignOut(
                        task,
                        exception =>
                    {
                        Debug.Log("commitAndClose.failed: " + exception.Call <string>("toString"));
                        var status = mAndroidClient.IsAuthenticated() ?
                                     SavedGameRequestStatus.InternalError :
                                     SavedGameRequestStatus.AuthenticationError;
                        callback(status, null);
                    });
                }
        }
Exemplo n.º 19
0
        public void AcceptInvitation(string invitationId, RealTimeMultiplayerListener listener)
        {
            var listenerOnGameThread = new OnGameThreadForwardingListener(listener);

            lock (mSessionLock)
            {
                if (GetRoomStatus() == RoomStatus.Active)
                {
                    OurUtils.Logger.e("Received attempt to accept invitation without cleaning up " +
                                      "active session.");
                    listenerOnGameThread.OnRoomConnected(false);
                    return;
                }

                FindInvitation(invitationId, fail => listenerOnGameThread.OnRoomConnected(false),
                               invitation =>
                {
                    mInvitation = invitation;

                    using (var roomConfigClass =
                               new AndroidJavaClass("com.google.android.gms.games.multiplayer.realtime.RoomConfig"))
                        using (var roomUpdateCallback = new AndroidJavaObject(
                                   "com.google.games.bridge.RoomUpdateCallbackProxy",
                                   new RoomUpdateCallbackProxy(/* parent= */ this, listenerOnGameThread)))
                            using (var roomConfigBuilder =
                                       roomConfigClass.CallStatic <AndroidJavaObject>("builder", roomUpdateCallback))
                                using (var messageReceivedListener =
                                           new AndroidJavaObject(
                                               "com.google.games.bridge.RealTimeMessageReceivedListenerProxy",
                                               new MessageReceivedListenerProxy(listenerOnGameThread)))
                                    using (roomConfigBuilder.Call <AndroidJavaObject>("setOnMessageReceivedListener",
                                                                                      messageReceivedListener))
                                        using (var roomStatusUpdateCallback =
                                                   new AndroidJavaObject("com.google.games.bridge.RoomStatusUpdateCallbackProxy",
                                                                         new RoomStatusUpdateCallbackProxy(this, listenerOnGameThread)))
                                            using (roomConfigBuilder.Call <AndroidJavaObject>("setRoomStatusUpdateCallback",
                                                                                              roomStatusUpdateCallback))
                                                using (roomConfigBuilder.Call <AndroidJavaObject>("setInvitationIdToAccept", invitationId))
                                                {
                                                    mRoomConfig = roomConfigBuilder.Call <AndroidJavaObject>("build");
                                                    mListener   = listenerOnGameThread;

                                                    using (var task = mRtmpClient.Call <AndroidJavaObject>("join", mRoomConfig))
                                                    {
                                                        AndroidTaskUtils.AddOnFailureListener(
                                                            task,
                                                            e =>
                                                        {
                                                            listenerOnGameThread.OnRoomConnected(false);
                                                            CleanSession();
                                                        });
                                                    }
                                                }
                });
            }
        }
Exemplo n.º 20
0
        public void FetchEvent(DataSource source, string eventId, Action <ResponseStatus, IEvent> callback)
        {
            callback = ToOnGameThread(callback);
            var ids = new string[1];

            ids[0] = eventId;
            using (var task = mEventsClient.Call <AndroidJavaObject>("loadByIds",
                                                                     source == DataSource.ReadNetworkOnly ? true : false, ids))
            {
                AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                    task,
                    annotatedData =>
                {
                    using (var buffer = annotatedData.Call <AndroidJavaObject>("get"))
                    {
                        var count = buffer.Call <int>("getCount");
                        if (count > 0)
                        {
                            using (var eventJava = buffer.Call <AndroidJavaObject>("get", 0))
                            {
                                callback.Invoke(
                                    annotatedData.Call <bool>("isStale")
                                            ? ResponseStatus.SuccessWithStale
                                            : ResponseStatus.Success,
                                    CreateEvent(eventJava)
                                    );
                            }
                        }
                        else
                        {
                            callback.Invoke(
                                annotatedData.Call <bool>("isStale")
                                        ? ResponseStatus.SuccessWithStale
                                        : ResponseStatus.Success,
                                null
                                );
                        }

                        buffer.Call("release");
                    }
                });

                AndroidTaskUtils.AddOnFailureListener(
                    task,
                    exception =>
                {
                    Debug.Log("FetchEvent failed");
                    callback.Invoke(ResponseStatus.InternalError, null);
                });
            }
        }
Exemplo n.º 21
0
        public void GetCaptureCapabilities(Action <ResponseStatus, VideoCapabilities> callback)
        {
            callback = ToOnGameThread(callback);
            using (var task = mVideosClient.Call <AndroidJavaObject>("getCaptureCapabilities"))
            {
                AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                    task,
                    videoCapabilities => callback(ResponseStatus.Success, CreateVideoCapabilities(videoCapabilities)));

                AndroidTaskUtils.AddOnFailureListener(
                    task,
                    exception => callback(ResponseStatus.InternalError, null));
            }
        }
 private void AddOnFailureListenerWithSignOut(AndroidJavaObject task, Action <AndroidJavaObject> callback)
 {
     AndroidTaskUtils.AddOnFailureListener(
         task,
         exception =>
     {
         var statusCode = exception.Call <int>("getStatusCode");
         if (statusCode == /* CommonStatusCodes.SignInRequired */ 4 ||
             statusCode == /* GamesClientStatusCodes.CLIENT_RECONNECT_REQUIRED */ 26502)
         {
             mAndroidClient.SignOut();
         }
         callback(exception);
     });
 }
Exemplo n.º 23
0
        public void IsCaptureAvailable(VideoCaptureMode captureMode, Action <ResponseStatus, bool> callback)
        {
            callback = ToOnGameThread(callback);
            using (var task =
                       mVideosClient.Call <AndroidJavaObject>("isCaptureAvailable", ToVideoCaptureMode(captureMode)))
            {
                AndroidTaskUtils.AddOnSuccessListener <bool>(
                    task,
                    isCaptureAvailable => callback(ResponseStatus.Success, isCaptureAvailable));

                AndroidTaskUtils.AddOnFailureListener(
                    task,
                    exception => callback(ResponseStatus.InternalError, false));
            }
        }
Exemplo n.º 24
0
            public void ResolveConflict(ISavedGameMetadata chosenMetadata, SavedGameMetadataUpdate metadataUpdate,
                                        byte[] updatedData)
            {
                var convertedMetadata = chosenMetadata as AndroidSnapshotMetadata;

                if (convertedMetadata != mOriginal && convertedMetadata != mUnmerged)
                {
                    Logger.e("Caller attempted to choose a version of the metadata that was not part " +
                             "of the conflict");
                    mCompleteCallback(SavedGameRequestStatus.BadInputError, null);
                    return;
                }

                using (var contentUpdate = mConflict.Call <AndroidJavaObject>("getResolutionSnapshotContents"))
                {
                    if (!contentUpdate.Call <bool>("writeBytes", updatedData))
                    {
                        Logger.e("Can't update snapshot contents during conflict resolution.");
                        mCompleteCallback(SavedGameRequestStatus.BadInputError, null);
                    }

                    using (var convertedMetadataChange = AsMetadataChange(metadataUpdate))
                        using (var task = mSnapshotsClient.Call <AndroidJavaObject>(
                                   "resolveConflict",
                                   mConflict.Call <string>("getConflictId"),
                                   convertedMetadata.JavaMetadata.Call <string>("getSnapshotId"),
                                   convertedMetadataChange,
                                   contentUpdate))
                        {
                            AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                                task,
                                dataOrConflict => mRetryFileOpen());

                            mAndroidSavedGameClient.AddOnFailureListenerWithSignOut(
                                task,
                                exception =>
                            {
                                Logger.d("ResolveConflict failed: " + exception.Call <string>("toString"));
                                var status = mAndroidSavedGameClient.mAndroidClient.IsAuthenticated()
                                    ? SavedGameRequestStatus.InternalError
                                    : SavedGameRequestStatus.AuthenticationError;
                                mCompleteCallback(status, null);
                            }
                                );
                        }
                }
            }
Exemplo n.º 25
0
        ///<summary></summary>
        /// <seealso cref="GooglePlayGames.BasicApi.IPlayGamesClient.GetPlayerStats"/>
        public void GetPlayerStats(Action <CommonStatusCodes, PlayerStats> callback)
        {
            using (var playerStatsClient = getPlayerStatsClient())
                using (var task = playerStatsClient.Call <AndroidJavaObject>("loadPlayerStats", /* forceReload= */ false))
                {
                    AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                        task,
                        annotatedData =>
                    {
                        using (var playerStatsJava = annotatedData.Call <AndroidJavaObject>("get"))
                        {
                            int numberOfPurchases        = playerStatsJava.Call <int>("getNumberOfPurchases");
                            float avgSessionLength       = playerStatsJava.Call <float>("getAverageSessionLength");
                            int daysSinceLastPlayed      = playerStatsJava.Call <int>("getDaysSinceLastPlayed");
                            int numberOfSessions         = playerStatsJava.Call <int>("getNumberOfSessions");
                            float sessionPercentile      = playerStatsJava.Call <float>("getSessionPercentile");
                            float spendPercentile        = playerStatsJava.Call <float>("getSpendPercentile");
                            float spendProbability       = playerStatsJava.Call <float>("getSpendProbability");
                            float churnProbability       = playerStatsJava.Call <float>("getChurnProbability");
                            float highSpenderProbability = playerStatsJava.Call <float>("getHighSpenderProbability");
                            float totalSpendNext28Days   = playerStatsJava.Call <float>("getTotalSpendNext28Days");

                            PlayerStats result = new PlayerStats(
                                numberOfPurchases,
                                avgSessionLength,
                                daysSinceLastPlayed,
                                numberOfSessions,
                                sessionPercentile,
                                spendPercentile,
                                spendProbability,
                                churnProbability,
                                highSpenderProbability,
                                totalSpendNext28Days);

                            InvokeCallbackOnGameThread(callback, CommonStatusCodes.Success, result);
                        }
                    });

                    AndroidTaskUtils.AddOnFailureListener(
                        task,
                        e =>
                    {
                        Debug.Log("GetPlayerStats failed");
                        InvokeCallbackOnGameThread(callback, CommonStatusCodes.InternalError, new PlayerStats());
                    });
                }
        }
Exemplo n.º 26
0
        public void FetchAllSavedGames(DataSource source,
                                       Action <SavedGameRequestStatus, List <ISavedGameMetadata> > callback)
        {
            Misc.CheckNotNull(callback);

            callback = ToOnGameThread(callback);

            using (var task =
                       mSnapshotsClient.Call <AndroidJavaObject>("load", /* forecReload= */
                                                                 source == DataSource.ReadNetworkOnly))
            {
                AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                    task,
                    annotatedData =>
                {
                    using (var buffer = annotatedData.Call <AndroidJavaObject>("get"))
                    {
                        var count  = buffer.Call <int>("getCount");
                        var result = new List <ISavedGameMetadata>();
                        for (var i = 0; i < count; ++i)
                        {
                            using (var metadata = buffer.Call <AndroidJavaObject>("get", i))
                            {
                                result.Add(new AndroidSnapshotMetadata(
                                               metadata.Call <AndroidJavaObject>("freeze"), /* contents= */ null));
                            }
                        }

                        buffer.Call("release");
                        callback(SavedGameRequestStatus.Success, result);
                    }
                });

                AddOnFailureListenerWithSignOut(
                    task,
                    exception =>
                {
                    Logger.d("FetchAllSavedGames failed: " + exception.Call <string>("toString"));
                    var status = mAndroidClient.IsAuthenticated()
                            ? SavedGameRequestStatus.InternalError
                            : SavedGameRequestStatus.AuthenticationError;
                    callback(status, new List <ISavedGameMetadata>());
                }
                    );
            }
        }
Exemplo n.º 27
0
        ///<summary></summary>
        /// <seealso cref="GooglePlayGames.BasicApi.IPlayGamesClient.LoadScores"/>
        public void LoadScores(string leaderboardId, LeaderboardStart start,
                               int rowCount, LeaderboardCollection collection,
                               LeaderboardTimeSpan timeSpan,
                               Action <LeaderboardScoreData> callback)
        {
            using (var client = getLeaderboardsClient())
            {
                string loadScoresMethod =
                    start == LeaderboardStart.TopScores ? "loadTopScores" : "loadPlayerCenteredScores";
                using (var task = client.Call <AndroidJavaObject>(
                           loadScoresMethod,
                           leaderboardId,
                           AndroidJavaConverter.ToLeaderboardVariantTimeSpan(timeSpan),
                           AndroidJavaConverter.ToLeaderboardVariantCollection(collection),
                           rowCount))
                {
                    AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                        task,
                        annotatedData =>
                    {
                        using (var leaderboardScores = annotatedData.Call <AndroidJavaObject>("get"))
                        {
                            InvokeCallbackOnGameThread(callback, CreateLeaderboardScoreData(
                                                           leaderboardId,
                                                           collection,
                                                           timeSpan,
                                                           annotatedData.Call <bool>("isStale")
                                        ? ResponseStatus.SuccessWithStale
                                        : ResponseStatus.Success,
                                                           leaderboardScores));
                            leaderboardScores.Call("release");
                        }
                    });

                    AndroidTaskUtils.AddOnFailureListener(
                        task,
                        exception =>
                    {
                        Debug.Log("LoadScores failed");
                        InvokeCallbackOnGameThread(callback,
                                                   new LeaderboardScoreData(leaderboardId, ResponseStatus.InternalError));
                    });
                }
            }
        }
Exemplo n.º 28
0
        private static void ShowSelectOpponentsUI(uint minOpponents, uint maxOpponents, bool isRealTime,
                                                  Action <UIStatus, InvitationResultHolder> cb)
        {
            string methodName = isRealTime ? "showRtmpSelectOpponentsUi" : "showTbmpSelectOpponentsUi";

            using (var helperFragment = new AndroidJavaClass(HelperFragmentClass))
                using (var task = helperFragment.CallStatic <AndroidJavaObject>(methodName,
                                                                                AndroidHelperFragment.GetActivity(), (int)minOpponents, (int)maxOpponents))
                {
                    AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                        task,
                        result =>
                    {
                        int status = result.Get <int>("status");
                        if ((UIStatus)status != UIStatus.Valid)
                        {
                            cb.Invoke((UIStatus)status, null);
                            return;
                        }

                        List <string> playerIdsToInvite;
                        using (var ids = result.Get <AndroidJavaObject>("playerIdsToInvite"))
                        {
                            playerIdsToInvite = CreatePlayerIdsToInvite(ids);
                        }

                        InvitationResultHolder resultHolder = new InvitationResultHolder(
                            result.Get <int>("minAutomatchingPlayers"),
                            result.Get <int>("maxAutomatchingPlayers"),
                            playerIdsToInvite
                            );

                        cb.Invoke((UIStatus)status, resultHolder);
                    });

                    AndroidTaskUtils.AddOnFailureListener(
                        task,
                        exception =>
                    {
                        Debug.Log("showSelectOpponentsUi failed with exception");
                        cb.Invoke(UIStatus.InternalError, null);
                    });
                }
        }
        public void AcknowledgeFinished(TurnBasedMatch match, Action <bool> callback)
        {
            callback = ToOnGameThread(callback);

            FindEqualVersionMatch(match, (success, foundMatch) =>
            {
                if (!success)
                {
                    callback(false);
                    return;
                }

                using (var task = mClient.Call <AndroidJavaObject>("dismissMatch", foundMatch.MatchId))
                {
                    AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(task, v => callback(true));
                    AndroidTaskUtils.AddOnFailureListener(task, e => callback(false));
                }
            });
        }
        public void LeaveDuringTurn(TurnBasedMatch match, string pendingParticipantId,
                                    Action <bool> callback)
        {
            callback = ToOnGameThread(callback);

            FindEqualVersionMatchWithParticipant(match, pendingParticipantId, callback,
                                                 (pendingParticipant, foundMatch) =>
            {
                using (var task =
                           mClient.Call <AndroidJavaObject>("leaveMatchDuringTurn", match.MatchId, pendingParticipantId))
                {
                    AndroidTaskUtils.AddOnSuccessListener <AndroidJavaObject>(
                        task,
                        v => callback(true));

                    AndroidTaskUtils.AddOnFailureListener(task, e => callback(false));
                }
            });
        }