/// <summary>
        /// Gets an updated balance for eth and enj
        /// </summary>
        /// <param name="identity">Identity to get new balances for</param>
        public void UpdateBalances(Identity identity)
        {
            if (identity.ethereum_address != "")
            {
                GraphQuery.POST(string.Format(Enjin.IdentityTemplate.GetQuery["UpdateBalances"], identity.id.ToString(), identity.ethereum_address));

                if (Enjin.ServerResponse != ResponseCodes.SUCCESS)
                {
                    return;
                }

                var resultGQL = JSON.Parse(GraphQuery.queryReturn);

                _ethBalance = System.Convert.ToDouble(resultGQL["data"]["balances"][0]["eth_balance"].Value);

                if (resultGQL["data"]["balances"][0]["enj_balance"].Value == "null")
                {
                    _enjBalance = 0;
                }
                else
                {
                    _enjBalance = System.Convert.ToDouble(resultGQL["data"]["balances"][0]["enj_balance"].Value);
                }
            }
            else
            {
                _ethBalance = 0;
                _enjBalance = 0;
            }
        }
Пример #2
0
        public void TestToString()
        {
            var query = new GraphQuery("user");

            query.Filters["id"] = "6";
            query.Fields        = new[]
            {
                new GraphQueryField("first_name"),
                new GraphQueryField("last_name"),
                new GraphQueryField("address")
                {
                    NestedFields = new []
                    {
                        new GraphQueryField("street"),
                        new GraphQueryField("city"),
                        new GraphQueryField("state"),
                        new GraphQueryField("zip"),
                    }
                },
            };

            var formatted = query.ToString();

            Assert.That(formatted, Is.EqualTo("user (id: 6) { first_name, last_name, address { street, city, state, zip } }"));
        }
Пример #3
0
        public async Task ShouldCalculateBetweennessMetric()
        {
            var query = new GraphQuery()
            {
                NetworkId = _fake.Network.Id,
                QueryText = @"SELECT * CALCULATE betweenness"
            };
            var result =
                (await _handler.Execute(query)).Vertices.Select(v => (double)v.Props["betweenness"]).ToArray();
            var expected = new[]
            {
                3.66666,
                0.83333,
                8.33333,
                8.33333,
                0.83333,
                0,
                0,
                14,
                8,
                0
            };

            var maxValue = expected.Max();

            for (int i = 0; i < expected.Length; i++)
            {
                expected[i] = Math.Round(1000 * expected[i] / maxValue) / 1000;
                result[i]   = (double)Math.Round(1000 * result[i]) / 1000;
            }

            Assert.AreEqual(JsonConvert.SerializeObject(expected), JsonConvert.SerializeObject(result));
        }
Пример #4
0
        public async Task ShouldCalculateEigenvector()
        {
            var query = new GraphQuery()
            {
                NetworkId = _fake.Network.Id,
                QueryText = @"SELECT * CALCULATE eigenvector"
            };
            var result =
                (await _handler.Execute(query)).Vertices.Select(v => (double)v.Props["eigenvector"]).ToArray();
            var expected = new[]
            {
                0.171,
                0.125,
                0.142,
                0.142,
                0.125,
                0.101,
                0.101,
                0.070,
                0.017,
                0.004
            };

            var maxValue = expected.Max();

            for (int i = 0; i < expected.Length; i++)
            {
                expected[i] = Math.Round(100 * expected[i] / maxValue) / 100;
                result[i]   = (double)Math.Round(100 * result[i]) / 100;
            }


            Assert.AreEqual(JsonConvert.SerializeObject(expected), JsonConvert.SerializeObject(result));
        }
Пример #5
0
        /// <summary>
        /// Melts a specific amount of tokens
        /// </summary>
        /// <param name="index">Index of item within a nonfungible item</param>
        /// <param name="identityID">Identity ID of user</param>
        /// <param name="tokenID">CryptoItem ID</param>
        /// <param name="amount">Numbner of cryptoItemss to melt</param>
        /// <returns>Melt request data from API</returns>
        public Request MeltItem(int identityID, string itemID, string index, int amount, System.Action <RequestEvent> callback)
        {
            if (index != "")
            {
                _query = @"mutation meltToken{request:CreateEnjinRequest(type:MELT,identity_id:$identityid^,melt_token_data:{token_id:""$itemid^"",token_index:""$index^"",value:$amount^}){id,encoded_data,state}}";
                GraphQuery.variable["index"] = index.ToString();
            }
            else
            {
                _query = @"mutation meltToken{request:CreateEnjinRequest(type:MELT,identity_id:$identityid^,melt_token_data:{token_id:""$itemid^"",value:$amount^}){id,encoded_data,state}}";
            }

            GraphQuery.variable["identityid"] = identityID.ToString();
            GraphQuery.variable["itemid"]     = itemID.ToString();
            GraphQuery.variable["amount"]     = amount.ToString();
            GraphQuery.POST(_query);

            if (Enjin.ServerResponse == ResponseCodes.SUCCESS)
            {
                Request request = JsonUtility.FromJson <Request>(EnjinHelpers.GetJSONString(GraphQuery.queryReturn, 2));
                Enjin.RequestCallbacks.Add(request.id, callback);

                return(request);
            }

            return(null);
        }
        /// <summary>
        /// Searches the CryptoItems globally for matching term
        /// </summary>
        /// <param name="term">term is what user is searching for</param>
        /// <returns>Array of CryptoItems found in search</returns>
        public CryptoItem[] SearchCryptoItems(string term)
        {
            string query = string.Empty;

            query = @"query searchCryptoItem{result:EnjinSearch(term:""$term^""){__typename... on EnjinToken {index,token_id,name,creator,totalSupply,reserve,circulatingSupply,supplyModel,meltValue,meltFeeRatio,meltFeeMaxRatio,transferable,transferFeeSettings{type,token_id,value},nonFungible,icon,balance,isCreator}}}";
            GraphQuery.variable["term"] = term;
            GraphQuery.POST(query);

            List <CryptoItem> searchResults = new List <CryptoItem>();
            //var results = JsonUtility.FromJson<JSONArrayHelper<CryptoItem>>(EnjinHelpers.GetJSONString(Regex.Replace(GraphQuery.queryReturn, @"(""[^""\\]*(?:\\.[^""\\]*)*"")|\s+", "$1"), 1)).result;

            var    results = JSON.Parse(GraphQuery.queryReturn);
            string temp    = EnjinHelpers.GetJSONString(Regex.Replace(GraphQuery.queryReturn, @"(""[^""\\]*(?:\\.[^""\\]*)*"")|\s+", "$1"), 1);
            var    temp2   = JsonUtility.FromJson <JSONArrayHelper <CryptoItem> >(temp);

            for (int i = 0; i < temp2.result.Length; i++)
            {
                if (temp2.result[i].token_id != null)
                {
                    temp2.result[i].supplyModel              = (SupplyModel)Enum.Parse(typeof(SupplyModel), results["data"]["result"][i]["supplyModel"].Value);
                    temp2.result[i].transferable             = (Transferable)Enum.Parse(typeof(Transferable), results["data"]["result"][i]["transferable"].Value);
                    temp2.result[i].transferFeeSettings.type = (TransferType)Enum.Parse(typeof(TransferType), results["data"]["result"][i]["transferFeeSettings"]["type"].Value);
                    searchResults.Add(temp2.result[i]);
                }
            }

            //foreach (CryptoItem item in results)
            //{
            //    if (item.token_id != null)
            //        searchResults.Add(item);
            //}

            return(searchResults.ToArray());
        }
Пример #7
0
        public async Task should_handle_start()
        {
            /* Given */
            var query = new GraphQuery
            {
                OperationName = "test",
                Query         = "query",
                Variables     = JObject.FromObject(new { test = "variable" })
            };

            var messageContext = CreateMessage(
                MessageTypes.GQL_START, query);

            _subscriptionExecuter.SubscribeAsync(Arg.Any <ExecutionOptions>())
            .Returns(CreateStreamResult);

            /* When */
            await _sut.HandleMessageAsync(messageContext).ConfigureAwait(false);

            /* Then */
            await _subscriptionExecuter.Received()
            .SubscribeAsync(Arg.Is <ExecutionOptions>(
                                context => context.Schema == _schema &&
                                context.Query == query.Query &&
                                context.Inputs.ContainsKey("test")))
            .ConfigureAwait(false);

            var connectionSubscriptions = _sut.Subscriptions[messageContext.ConnectionId];

            Assert.True(connectionSubscriptions.ContainsKey(messageContext.Op.Id));
        }
        public App GetApp()
        {
            GraphQuery.POST(Enjin.PlatformTemplate.GetQuery["GetApp"]);

            var resultGQL  = JSON.Parse(GraphQuery.queryReturn);
            var resultJson = resultGQL["data"]["result"];
            // TODO: Convert this to json parsing to datatype (Updates to read back in GraphQuery.cs)
            App appData = new App()
            {
                id          = resultJson["id"].AsInt,
                name        = resultJson["name"].Value,
                description = resultJson["description"].Value,
                image       = resultJson["image"].Value
            };

            var walletsJson = resultJson["wallets"].AsArray;

            for (int i = 0; i < walletsJson.Count; i++)
            {
                appData.wallets.Add(new Wallet()
                {
                    ethAddress = walletsJson[i]["ethAddress"].Value
                });
            }

            return(appData);
        }
        public JSONNode AuthPlayer(string id)
        {
            GraphQuery.POST(string.Format(global::Enjin.SDK.Core.Enjin.PlatformTemplate.GetQuery["AuthPlayer"], id));
            var resultGql = JSON.Parse(GraphQuery.queryReturn);

            return(resultGql["data"]["result"]);
        }
Пример #10
0
        /// <summary>
        /// Updates a roles name & permissions
        /// </summary>
        /// <param name="name">Name of role to update</param>
        /// <param name="newName">New name to update role to</param>
        /// <param name="permissions">Array of permissions to update</param>
        /// <returns>(True / False) if update was successful</returns>
        public bool UpdateRole(string name, string newName, string[] permissions)
        {
            string query;

            if (newName == "")
            {
                query = @"mutation updateRole{result:UpdateEnjinRole(name:""$roleName^"",permissions:$permissions[]^){id,name,permissions{name}}}";
            }
            else
            {
                query = @"mutation updateRole{result:UpdateEnjinRole(name:""$roleName^"",new_name:""$roleNewName^"",permissions:$permissions[]^){id,name,permissions{name}}}";
                GraphQuery.variable["roleNewName"] = newName;
            }

            GraphQuery.variable["roleName"]   = name;
            GraphQuery.array["permissions[]"] = permissions;
            GraphQuery.POST(query);

            if (Enjin.ServerResponse == ResponseCodes.SUCCESS)
            {
                return(true);
            }

            return(false);
        }
Пример #11
0
        /// <summary>
        /// Sends a Token on the Trusted Platform and blockchain using full CryptoItem.
        /// Allows for fungible and nonfungible token requests
        /// </summary>
        /// <param name="identityID">Identity ID of requestor</param>
        /// <param name="item">CryptoItem to be sent</param>
        /// <param name="recipientID">Identity ID of reciving wallet</param>
        /// <param name="value">Number of tokens to be sent</param>
        /// /// <param name="value">Callback function to execute when request is fulfilled</param>
        /// <returns>Create request data from API</returns>
        public Request SendItem(int identityID, CryptoItem item, int recipientID, int value, System.Action <RequestEvent> callback)
        {
            _query = @"mutation sendItem{CreateEnjinRequest(type:SEND,identity_id:$identity_id^,send_token_data:{recipient_identity_id:$recipient_id^, token_id: ""$token_id^"", ";
            if (item.nonFungible)
            {
                _query += @"token_index: ""$item_index^"", ";
            }
            _query += "value:$value^}){id,encoded_data,state}}";

            GraphQuery.variable["identity_id"] = identityID.ToString();
            GraphQuery.variable["token_id"]    = item.token_id.ToString();
            if (item.nonFungible)
            {
                GraphQuery.variable["item_index"] = item.index.ToString();
            }
            GraphQuery.variable["recipient_id"] = recipientID.ToString();
            GraphQuery.variable["value"]        = value.ToString();
            GraphQuery.POST(_query);

            if (Enjin.ServerResponse == ResponseCodes.SUCCESS)
            {
                return(JsonUtility.FromJson <Request>(EnjinHelpers.GetJSONString(GraphQuery.queryReturn, 2)));
            }

            return(null);
        }
Пример #12
0
        /// <summary>
        /// Verifies the user login
        /// </summary>
        /// <param name="username">username</param>
        /// <param name="password">user password</param>
        /// <returns>User if valid null if not valid</returns>
        public static User VerifyLogin(string username, string password)
        {
            _loginState = LoginState.VALID;
            User currentUser = new User();

            string _query = @"query login{result:EnjinOauth(email:""$user^"",password:""$pass^""){id,access_tokens,roles{name}identities{app_id}}}";

            GraphQuery.variable["user"] = username;
            GraphQuery.variable["pass"] = password;
            GraphQuery.POST(_query, "login");

            if (_serverCode == ResponseCodes.DATACONFLICT || _serverCode == ResponseCodes.UNAUTHORIZED || _serverCode == ResponseCodes.BADREQUEST || _serverCode == ResponseCodes.NOTFOUND)
            {
                _loginState = LoginState.INVALIDUSERPASS;
            }
            else if (_serverCode == ResponseCodes.UNKNOWNERROR)
            {
                _loginState = LoginState.INVALIDTPURL;
            }
            else if (_serverCode == ResponseCodes.INTERNAL)
            {
                _loginState = LoginState.INVALIDUSERPASS;
            }

            if (_serverCode == ResponseCodes.SUCCESS)
            {
                var resultGQL = JSON.Parse(GraphQuery.queryReturn);
                currentUser = GetUser(resultGQL["data"]["result"]["id"].AsInt);
                currentUser.access_token = resultGQL["data"]["result"]["access_tokens"][0]["access_token"].Value;
            }

            return(currentUser);
        }
Пример #13
0
        /// <summary>
        /// Melts a specific amount of tokens
        /// </summary>
        /// <param name="identityID">Identity ID of user</param>
        /// <param name="itemID">CryptoItem ID</param>
        /// <param name="index">Index of item within a nonfungible item</param>
        /// <param name="amount">Numbner of cryptoItemss to melt</param>
        /// <returns>Melt request data from API</returns>
        public Request MeltItem(int identityID, string itemID, string index, int amount, System.Action <string> handler,
                                bool async = false)
        {
            if (index != "")
            {
                _query =
                    @"mutation meltToken{request:CreateEnjinRequest(appId:$appId^,type:MELT,identityId:$identityid^,melt_token_data:{token_id:""$itemid^"",token_index:""$index^"",value:$amount^}){id,encodedData,state}}";
                GraphQuery.variable["index"] = index;
            }
            else
            {
                _query =
                    @"mutation meltToken{request:CreateEnjinRequest(appId:$appId^,type:MELT,identityId:$identityid^,melt_token_data:{token_id:""$itemid^"",value:$amount^}){id,encodedData,state}}";
            }

            GraphQuery.variable["appId"]      = Enjin.AppID.ToString();
            GraphQuery.variable["identityid"] = identityID.ToString();
            GraphQuery.variable["itemid"]     = itemID;
            GraphQuery.variable["amount"]     = amount.ToString();
            GraphQuery.POST(_query, "", async, (queryReturn) => { handler?.Invoke(queryReturn); });

            if (GraphQuery.queryStatus == GraphQuery.Status.Complete)
            {
                return(JsonUtility.FromJson <Request>(EnjinHelpers.GetJSONString(GraphQuery.queryReturn, 2)));
            }

            return(null);
        }
        /// <summary>
        /// Gets all items in a pagination format
        /// </summary>
        /// <param name="page">Page to get</param>
        /// <param name="limit">Total items per page</param>
        /// <param name="identityID">Identity ID of user</param>
        /// <returns></returns>
        public PaginationHelper <CryptoItem> GetItems(int page, int limit, int identityID)
        {
            string query = string.Empty;

            if (limit == 0)
            {
                query = @"query getAllItems{result:EnjinIdentities(id:$id^){tokens(pagination:{page:$page^},include_creator_tokens:true){items{index,token_id,name,creator,totalSupply,reserve,circulatingSupply,supplyModel,meltValue,meltFeeRatio,meltFeeMaxRatio,transferable,transferFeeSettings{type,token_id,value},nonFungible,icon,balance,isCreator,markedForDelete}cursor{total,hasPages,perPage,currentPage}}}}";
            }
            else
            {
                query = @"query getAllItems{result:EnjinIdentities(id:$id^){tokens(pagination:{limit:$limit^,page:$page^},include_creator_tokens:true){items{index,token_id,name,creator,totalSupply,reserve,circulatingSupply,supplyModel,meltValue,meltFeeRatio,meltFeeMaxRatio,transferable,transferFeeSettings{type,token_id,value},nonFungible,icon,balance,isCreator,markedForDelete}cursor{total,hasPages,perPage,currentPage}}}}";
                GraphQuery.variable["limit"] = limit.ToString();
            }

            GraphQuery.variable["id"]   = identityID.ToString();
            GraphQuery.variable["page"] = page.ToString();
            GraphQuery.POST(query);

            var    results = JSON.Parse(GraphQuery.queryReturn);
            string temp    = EnjinHelpers.GetJSONString(Regex.Replace(GraphQuery.queryReturn, @"(""[^""\\]*(?:\\.[^""\\]*)*"")|\s+", "$1"), 3);
            var    temp2   = JsonUtility.FromJson <PaginationHelper <CryptoItem> >(temp);

            for (int i = 0; i < temp2.items.Length; i++)
            {
                temp2.items[i].supplyModel              = (SupplyModel)Enum.Parse(typeof(SupplyModel), results["data"]["result"][0]["tokens"]["items"][i]["supplyModel"].Value);
                temp2.items[i].transferable             = (Transferable)Enum.Parse(typeof(Transferable), results["data"]["result"][0]["tokens"]["items"][i]["transferable"].Value);
                temp2.items[i].transferFeeSettings.type = (TransferType)Enum.Parse(typeof(TransferType), results["data"]["result"][0]["tokens"]["items"][i]["transferFeeSettings"]["type"].Value);
            }

            return(temp2);
        }
Пример #15
0
        public Request SendItems(CryptoItemBatch sendItems, int userId)
        {
            _query = @"mutation advancedSend{CreateEnjinRequest(appId:$appId^,identityId:" + userId +
                     ",type:ADVANCED_SEND,advanced_send_token_data:{transfers:[";

            for (int i = 0; i < sendItems.Items.Count; i++)
            {
                _query += "{" + sendItems.Items[i] + "}";

                if (i < sendItems.Items.Count - 1)
                {
                    _query += ",";
                }
            }

            _query += "]}){id,encodedData}}";
            GraphQuery.variable["appId"] = Enjin.AppID.ToString();
            GraphQuery.POST(_query);

            Debug.Log("<color=white>[DEBUG INFO]</color> " + _query);

            if (Enjin.ServerResponse == ResponseCodes.SUCCESS)
            {
                return(JsonUtility.FromJson <Request>(EnjinHelpers.GetJSONString(GraphQuery.queryReturn, 2)));
            }

            return(null);
        }
Пример #16
0
        /// <summary>
        /// Sends a Token on the Trusted Platform and blockchain using full CryptoItem.
        /// Allows for fungible and nonfungible token requests
        /// </summary>
        /// <param name="identityID">Identity ID of requestor</param>
        /// <param name="item">CryptoItem to be sent</param>
        /// <param name="recipientID">Identity ID of reciving wallet</param>
        /// <param name="value">Number of tokens to be sent</param>
        /// /// <param name="value">Callback function to execute when request is fulfilled</param>
        /// <returns>Create request data from API</returns>
        public Request SendItem(int identityID, CryptoItem item, int recipientID, int value,
                                System.Action <string> handler, bool async = false)
        {
            _query =
                @"mutation sendItem{CreateEnjinRequest(appId:$appId^,type:SEND,identityId:$identityId^,send_token_data:{recipient_identity_id:$recipient_id^, token_id: ""$token_id^"", ";
            if (item.nonFungible)
            {
                _query += @"token_index: ""$item_index^"", ";
            }

            _query += "value:$value^}){id,encodedData,state}}";

            GraphQuery.variable["appId"]      = Enjin.AppID.ToString();
            GraphQuery.variable["identityId"] = identityID.ToString();
            GraphQuery.variable["token_id"]   = item.id;
            if (item.nonFungible)
            {
                GraphQuery.variable["item_index"] = item.index;
            }

            GraphQuery.variable["recipient_id"] = recipientID.ToString();
            GraphQuery.variable["value"]        = value.ToString();
            GraphQuery.POST(_query, "", async, (queryReturn) => { handler?.Invoke(queryReturn); });

            if (GraphQuery.queryStatus == GraphQuery.Status.Complete)
            {
                return(JsonUtility.FromJson <Request>(EnjinHelpers.GetJSONString(GraphQuery.queryReturn, 2)));
            }

            return(null);
        }
Пример #17
0
        /// <summary>
        /// Gets all applicaitons user has access to
        /// </summary>
        /// <returns>List of all applications user has access to</returns>
        public List <AppSelectorData> GetAppsByUserID(int userID)
        {
            GraphQuery.POST(string.Format(Enjin.PlatformTemplate.GetQuery["GetAppsByUserID"], userID), Enjin.AccessToken);

            var resultGQL = JSON.Parse(GraphQuery.queryReturn);
            int count     = resultGQL["data"]["result"][0]["identities"].Count;
            List <AppSelectorData> appList = new List <AppSelectorData>();

            for (int i = 0; i < count; i++)
            {
                try
                {
                    appList.Add(new AppSelectorData
                    {
                        appID      = resultGQL["data"]["result"][0]["identities"][i]["app_id"].AsInt,
                        identityID = resultGQL["data"]["result"][0]["identities"][i]["id"].AsInt,
                        appName    = resultGQL["data"]["result"][0]["identities"][i]["app"]["name"].Value
                    });
                }
                catch (NullReferenceException)
                {
                    Enjin.AppID = -1;
                }
            }

            return(appList);
        }
        /// <summary>
        /// Creates a new CryptoItem for current selected application
        /// </summary>
        /// <param name="newItem">CryptoItem to create</param>
        /// <param name="identityID">CryptoItem creator user identity ID</param>
        /// <returns>Request data</returns>
        public Request CreateCryptoItem(CryptoItem newItem, int identityID)
        {
            string query = string.Empty;

            if (newItem.icon != null)
            {
                query = "mutation createCryptoItem{request:CreateEnjinRequest(type:CREATE,identity_id:$identity^,create_token_data:{name:\"$name^\",totalSupply:$totalSupply^,initialReserve:$reserve^,supplyModel:$model^,meltValue:\"$meltValue^\",meltFeeRatio:$meltFee^,transferable:$transferable^,transferFeeSettings:{type:$fType^, token_id:\"$fToken^\",value:\"$fValue^\"},nonFungible:$nonFungible^,icon:\"$icon^\"}){id,encoded_data,state}}";
                GraphQuery.variable["icon"] = newItem.icon;
            }
            else
            {
                query = "mutation createCryptoItem{request:CreateEnjinRequest(type:CREATE,identity_id:$identity^,create_token_data:{name:\"$name^\",totalSupply:$totalSupply^,initialReserve:$reserve^,supplyModel:$model^,meltValue:\"$meltValue^\",meltFeeRatio:$meltFee^,transferable:$transferable^,transferFeeSettings:{type:$fType^, token_id:\"$fToken^\",value:\"$fValue^\"},nonFungible:$nonFungible^}){id,encoded_data,state}}";
            }

            GraphQuery.variable["name"]         = newItem.name;
            GraphQuery.variable["identity"]     = identityID.ToString();
            GraphQuery.variable["totalSupply"]  = newItem.totalSupply;
            GraphQuery.variable["reserve"]      = newItem.reserve;
            GraphQuery.variable["model"]        = newItem.supplyModel.ToString();
            GraphQuery.variable["meltValue"]    = newItem.meltValue;
            GraphQuery.variable["meltFee"]      = newItem.meltFeeRatio.ToString();
            GraphQuery.variable["transferable"] = newItem.transferable.ToString();
            GraphQuery.variable["fType"]        = newItem.transferFeeSettings.type.ToString();
            GraphQuery.variable["fToken"]       = newItem.transferFeeSettings.token_id;
            GraphQuery.variable["fValue"]       = newItem.transferFeeSettings.value.ToString();
            GraphQuery.variable["nonFungible"]  = newItem.nonFungible.ToString().ToLower();
            GraphQuery.POST(query);

            return(JsonUtility.FromJson <Request>(EnjinHelpers.GetJSONString(GraphQuery.queryReturn, 2)));
        }
Пример #19
0
        /// <summary>
        /// Logs user into platform
        /// </summary>
        /// <param name="username">User's username</param>
        /// <param name="password">User's password</param>
        /// <returns></returns>
        public static User Login(string username, string password)
        {
            User currentUser = new User();

            if (PlayerPrefs.HasKey("UserData"))
            {
                try
                {
                    _userCreds = JsonUtility.FromJson <UserCredentials>(PlayerPrefs.GetString("UserData"));

                    if (username == _userCreds.email && password == _userCreds.key)
                    {
                        AppID                    = _userCreds.appID;
                        _accessToken             = _userCreds.accessToken;
                        currentUser              = GetUserRaw(_userCreds.userID);
                        currentUser.access_token = _accessToken;
                    }
                }
                catch (System.Exception e)
                {
                    Debug.LogWarning("[EXECUTION WARNING] " + e.Message);
                    PlayerPrefs.DeleteKey("UserData");
                }
            }

            if (currentUser != null)
            {
                _loginState = LoginState.VALID;
                GraphQuery.POST(string.Format(PlatformTemplate.GetQuery["Login"], username, password), "login");

                switch (_serverCode)
                {
                case ResponseCodes.DATACONFLICT:
                case ResponseCodes.UNAUTHORIZED:
                case ResponseCodes.INTERNAL:
                case ResponseCodes.BADREQUEST:
                case ResponseCodes.NOTFOUND:
                    _loginState = LoginState.INVALIDUSERPASS;
                    break;

                case ResponseCodes.UNKNOWNERROR:
                    _loginState = LoginState.INVALIDTPURL;
                    break;

                case ResponseCodes.SUCCESS:
                    var resultGQL = JSON.Parse(GraphQuery.queryReturn);

                    _accessToken = resultGQL["data"]["result"]["access_tokens"][0]["access_token"].Value;
                    AppID        = resultGQL["data"]["result"]["identities"][0]["app_id"].AsInt;
                    currentUser  = GetUserRaw(resultGQL["data"]["result"]["id"].AsInt);
                    StoreUserData(currentUser, password);
                    break;
                }
            }

            currentUser.access_token = _accessToken;

            return(currentUser);
        }
Пример #20
0
        /// <summary>
        /// Gets the platform information for intiializing platform
        /// </summary>
        /// <returns>PlatformInfo object containing platform info</returns>
        private PlatformInfo GetPlatformInfo()
        {
            GraphQuery.POST(Enjin.PlatformTemplate.GetQuery["GetPlatformInfo"], Enjin.AccessToken);

            Debug.Log(">>> fetched string " + EnjinHelpers.GetJSONString(GraphQuery.queryReturn));

            return(JsonUtility.FromJson <PlatformInfo>(EnjinHelpers.GetJSONString(GraphQuery.queryReturn)));
        }
Пример #21
0
        public void Query_Create_IsCorrect()
        {
            var query = GraphQuery.Query <GraphQueryTests>("queryName");

            Assert.Null(query.LastNode);
            Assert.Null(query.Node.Value);
            Assert.Empty(query.Node.Childs);
        }
Пример #22
0
        /// <summary>
        /// Gets the application ID by name
        /// </summary>
        /// <param name="appName">Name of application</param>
        /// <returns>Application ID</returns>
        public int GetAppIDByName(string appName)
        {
            GraphQuery.POST(string.Format(Enjin.PlatformTemplate.GetQuery["GetAppByID"], appName), Enjin.AccessToken);

            var resultGQL = JSON.Parse(GraphQuery.queryReturn);

            return(resultGQL["data"]["result"][0]["id"].AsInt);
        }
Пример #23
0
        private string _query;      // Query string to be sent to API

        /// <summary>
        /// Gets a specific request by ID
        /// </summary>
        /// <param name="id">Request ID</param>
        /// <returns>Request of specified ID</returns>
        public Request Get(int id)
        {
            _query = "query getRequest{request:EnjinTransactions(id:$id^){id,transaction_id,app_id,type,icon,title,value,state,accepted,updated_at,created_at}}";
            GraphQuery.variable["id"] = id.ToString();
            GraphQuery.POST(_query);

            return(JsonUtility.FromJson <Request>(EnjinHelpers.GetJSONString(_query, 1)));
        }
Пример #24
0
        /// <summary>
        /// Creates the actual response from the request and a computed set of intervals
        /// </summary>
        /// <param name="req">The request to service</param>
        /// <param name="ranges">The computed range buckets</param>
        /// <returns>A JSON result</returns>
        protected virtual async Task <IResult> CreateGraphResponse(GraphQuery req, TimeRange[] ranges)
        {
            switch (req.Type.ToLowerInvariant())
            {
            case "signup":
                return(Json(await DB.RunInTransactionAsync(db =>
                                                           new {
                    WaitListSize =
                        ranges.Select(t =>
                                      db.SelectCount <Database.Signup.SignupEntry>(x => x.Status == Database.Signup.SignupStatus.Confirmed && x.When > t.From && x.When <= t.To)
                                      ).ToArray(),
                    ActivatedUsers =
                        ranges.Select(t =>
                                      db.SelectCount <Database.Signup.SignupEntry>(x => x.Status == Database.Signup.SignupStatus.Activated && x.WhenActivated > t.From && x.WhenActivated <= t.To)
                                      ).ToArray(),
                    ConfirmedSignups =
                        ranges.Select(t =>
                                      db.SelectCount <Database.Signup.SignupEntry>(x => x.LastAttempt > t.From && x.LastAttempt <= t.To && x.Status == Database.Signup.SignupStatus.Confirmed)
                                      ).ToArray(),
                    NonConfirmedSignups =
                        ranges.Select(t =>
                                      db.SelectCount <Database.Signup.SignupEntry>(x => x.LastAttempt > t.From && x.LastAttempt <= t.To && (x.Status == Database.Signup.SignupStatus.Created || x.Status == Database.Signup.SignupStatus.Failed))
                                      ).ToArray()
                })));

            case "email":
                return(Json(await DB.RunInTransactionAsync(db =>
                                                           new {
                    Sent =
                        ranges.Select(t =>
                                      db.SelectCount <Database.SentEmailLog>(x => x.When > t.From && x.When <= t.To)
                                      ).ToArray()
                }
                                                           )));

            case "http":
                return(Json(await HttpLogModule.RunInTransactionAsync(db =>
                                                                      new
                {
                    OK =
                        ranges.Select(t =>
                                      db.SelectCount <Ceen.Extras.LogModule.HttpLogEntry>(x => x.Started > t.From && x.Started <= t.To && x.ResponseStatusCode <= 399)
                                      ).ToArray(),
                    ClientError =
                        ranges.Select(t =>
                                      db.SelectCount <Ceen.Extras.LogModule.HttpLogEntry>(x => x.Started > t.From && x.Started <= t.To && x.ResponseStatusCode > 399 && x.ResponseStatusCode <= 499)
                                      ).ToArray(),
                    ServerError =
                        ranges.Select(t =>
                                      db.SelectCount <Ceen.Extras.LogModule.HttpLogEntry>(x => x.Started > t.From && x.Started <= t.To && x.ResponseStatusCode >= 500)
                                      ).ToArray()
                }
                                                                      )));

            default:
                return(Status(BadRequest, "No such query type"));
            }
        }
Пример #25
0
        /// <summary>
        /// Gets all requests made on the platform
        /// </summary>
        /// <returns>All requests on the platform</returns>
        public Request[] GetAll()
        {
            _query = "query getAllRequests{request:EnjinTransactions{id,transaction_id,app_id,type,icon,title,value,state,accepted,updated_at,created_at}}";
            GraphQuery.POST(_query);

            var tData = JsonUtility.FromJson <JSONArrayHelper <Request> >(EnjinHelpers.GetJSONString(_query, 1));

            return(tData.result);
        }
        public JSONNode AuthApp(int appId, string secret)
        {
            var query = string.Format(Enjin.PlatformTemplate.GetQuery["AuthApp"], appId, secret);

            GraphQuery.POST(query, "login");
            var resultGql = JSON.Parse(GraphQuery.queryReturn);

            return(resultGql["data"]["result"]);
        }
 private Task <SubscriptionExecutionResult> SubscribeAsync(GraphQuery query)
 {
     return(_subscriptionExecuter.SubscribeAsync(new ExecutionOptions
     {
         Schema = _schema,
         OperationName = query.OperationName,
         Inputs = query.GetInputs(),
         Query = query.Query
     }));
 }
Пример #28
0
        public void TestSimple()
        {
            var query = GraphQuery.Parse("test");

            Assert.That(query, Is.Not.Null);
            Assert.That(query.ObjectType, Is.EqualTo("test"));
            Assert.That(query.Filters, Is.Not.Null);
            Assert.That(query.Filters.Count, Is.EqualTo(0));
            Assert.That(query.Fields, Is.Not.Null);
            Assert.That(query.Fields.Count(), Is.EqualTo(0));
        }
        /// <summary>
        /// Creates a new User
        /// </summary>
        /// <param name="name">User's username</param>
        /// <returns>Created user object</returns>
        public User Create(string name)
        {
            GraphQuery.POST(string.Format(Enjin.UserTemplate.GetQuery["CreateUser"], name));

            if (Enjin.ServerResponse == ResponseCodes.SUCCESS)
            {
                return(JsonUtility.FromJson <User>(EnjinHelpers.GetJSONString(GraphQuery.queryReturn, 2)));
            }

            return(null);
        }
        /// <summary>
        /// Unlinks identity from wallet
        /// </summary>
        /// <param name="id">ID of identity to unlink</param>
        /// <returns>Updated identity</returns>
        public bool UnLink(int id)
        {
            GraphQuery.POST(string.Format(Enjin.IdentityTemplate.GetQuery["UnlinkIdentity"], id.ToString()));

            if (Enjin.ServerResponse != ResponseCodes.SUCCESS)
            {
                return(false);
            }

            return(true);
        }