Beispiel #1
0
    public DelegateTask(InitializationHandler initialize, UpdateHandler update = null, SuccessHandler onSuccess = null, FailureHandler onFailure = null)
    {
        this.initialize = initialize;
        this.update     = update ?? (() => true);

        /*
         *      if (update != null)
         *              this.update = update;
         *      else
         *      {
         *              this.update = () => true; // = >
         *
         *              this.update = () =>
         *              {
         *                      return true;
         *              };
         *
         *              // this is the same as
         *
         *              bool UpdateMethod()
         *              {
         *                      return true;
         *              }
         *
         *              this.update = UpdateMethod;
         *      }*/

        this.onSuccess = onSuccess;
        this.onFailure = onFailure;
    }
Beispiel #2
0
    public DelegateTask(InitializationHandler initialize, UpdateHandler update = null, SuccessHandler onSuccess = null, FailureHandler onFailure = null)
    {
        this.initialize = initialize;
        this.update     = update ?? (() => true);

        if (update != null)
        {
            this.update = update;
        }
        else
        {
            this.update = () => true;             // = >

            this.update = () =>
            {
                return(true);
            };

            // this is the same as

            bool UpdateMethod()
            {
                return(true);
            }

            this.update = UpdateMethod;
        }

        this.onSuccess = onSuccess;
        this.onFailure = onFailure;
    }
Beispiel #3
0
 public static void FetchTournaments(SuccessHandler success, FriendlyErrorHandler failure)
 {
     fetchedTournamentsCallback = () => {
         success();
     };
     ArbiterBinding.FetchTournaments(FetchTournamentsSuccessHandler, failure);
 }
Beispiel #4
0
    /// <summary>
    /// Loads data.
    /// </summary>
    /// <param name="success">Callback triggers on successful data load.</param>
    /// <param name="error">Callback triggers on error.</param>
    public static Coroutine LoadData(SuccessHandler success, ErrorHandler error)
    {
        drWWW www = new drWWW(drAPI.loadData);

        www.OnSuccess += delegate {
            Hashtable result = www.result as Hashtable;

            if (result["data"] == null) {
                drDebug.LogWarning("No data exists in the data store to load");
           		return;
            }

            if (data == null) {
                data = new Dictionary<string, object>();
            }

            StoreReturnData(result["data"] as Hashtable);

            drDebug.Log("Loaded data");
        }; www.OnSuccess += success;

        www.OnError += delegate (string errorMessage) {
            drDebug.LogError("Error loading data: " + errorMessage);
        }; www.OnError += error;

        return www.Fetch();
    }
Beispiel #5
0
 public CallbackTuple(SuccessHandler success, ErrorHandler failure, FriendlyErrorHandler friendlyFailure, CodedErrorHandler codedFailure)
 {
     Success         = success;
     Failure         = failure;
     FriendlyFailure = friendlyFailure;
     CodedFailure    = codedFailure;
 }
Beispiel #6
0
    /// <summary>
    /// Awards an achievement.
    /// </summary>
    /// <param name="achievementName">The name of the achievement to award.</param>
    /// <param name="success">Callback triggers on successful award.</param>
    /// <param name="error">Callback triggers on error.</param>
    public static Coroutine AwardAchievement(string achievementName, SuccessHandler success, ErrorHandler error)
    {
        drWWW www = new drWWW(drAPI.awardAchievement);
        www.AddField("name", achievementName);

        www.OnSuccess += delegate {
            if (!(bool)www.result) { // This should never occur, but the check is here just in case
                drDebug.LogWarning("Did not award achievement \"" + achievementName + "\"");
                return;
            }

            if (!_awardedAchievements.Contains(achievementName)) {
                _awardedAchievements.Add(achievementName);
            }

            drClient.RefreshCanvasComponent(drClient.CanvasComponent.Achievements);
            drDebug.Log("Awarded achievement " + achievementName);
        }; www.OnSuccess += success;

        www.OnError += delegate (string errorMessage) {
            drDebug.LogError("Error awarding achievement \"" + achievementName + "\": " + errorMessage);
        }; www.OnError += error;

        return www.Fetch();
    }
Beispiel #7
0
        public static void LoadTextureItem(string ID, SuccessHandler onSuccess, ErrorHandler onError, string directory = "")
        {
            if (TextureVault.Get(ID, directory))
            {
                ID        = TextureVault.GenerateIdentifier(ID);
                directory = TextureVault.GetDirectory(directory);

                string fileName = TextureVault.GetFilename(directory, ID);


                if (textureCache.ContainsKey(fileName))
                {
                    Touch(fileName);
                    Debug.Log("From Cache " + fileName + " " + textureCache.Count);
                    onSuccess(textureCache[fileName].texture);
                    return;
                }

                byte[] data = File.ReadAllBytes(fileName);

                Texture2D texture2D = new Texture2D(2, 2);
                if (texture2D.LoadImage(data, true))
                {
                    textureCache.Add(fileName, new TextureVaultHistory(fileName, texture2D));
                    CleanupCache();
                    onSuccess(texture2D);
                    return;
                }
            }
            onError();
        }
Beispiel #8
0
    public DelegateTask(InitializationHandler initialize, UpdateHandler update = null, SuccessHandler onSuccess = null, FailureHandler onFailure = null)
    {
        this.initialize = initialize;
        this.update     = update ?? (() => true);

        this.onSuccess = onSuccess;
        this.onFailure = onFailure;
    }
Beispiel #9
0
 public static void ShowUnviewedTournaments(SuccessHandler callback)
 {
     if (!UserExists)
     {
         Debug.LogWarning("Make sure user is logged in before showing their unviewed tournaments!");
         return;
     }
     ArbiterBinding.ShowUnviewedTournaments(callback, defaultErrorHandler);
 }
Beispiel #10
0
        public static void AcceptCashChallenge(string challengeId, SuccessHandler success, FriendlyErrorHandler failure)
        {
            SetCallbacksWithFriendlyErrors(ACCEPT_SCORE_CHALLENGE, success, failure);
#if UNITY_EDITOR
            ReportIgnore("AcceptCashChallenge");
#elif UNITY_IOS
            _acceptCashChallenge(challengeId);
#endif
        }
Beispiel #11
0
        public static void ShowCashChallengeRules(string challengeId, SuccessHandler callback)
        {
            SetCallbacksWithErrors(SHOW_SCORE_CHALLENGE_RULES, callback, null);
#if UNITY_EDITOR
            ReportIgnore("ShowCashChallengeRules");
#elif UNITY_IOS
            _showCashChallengeRules(challengeId);
#endif
        }
Beispiel #12
0
        public static void ShowWalkThrough(string walkThroughId, SuccessHandler callback)
        {
            SetCallbacksWithErrors(SHOW_WALK_THROUGH, callback, null);
#if UNITY_EDITOR
            ReportIgnore("ShowWalkThrough");
#elif UNITY_IOS
            _showWalkThrough(walkThroughId);
#endif
        }
Beispiel #13
0
 private static void SetSimpleCallback(string key, SuccessHandler callback)
 {
     if (callback == null)
     {
         callback = () => {}
     }
     ;
     callbacks[key] = new CallbackTuple(callback, (e) => {}, (e, d) => {});
 }
Beispiel #14
0
        public void Publishes_to_multicast_handlers_with_interfaces_with_concrete_consumer()
        {
            var handler = new SuccessHandler();
            var hub     = new Hub();

            hub.Subscribe(handler);
            hub.Publish(new InheritedEvent());
            Assert.Equal(1, handler.Handled);
        }
Beispiel #15
0
        public static void Logout(SuccessHandler success, ErrorHandler failure)
        {
            SetCallbacksWithErrors(LOGOUT, success, failure);
#if UNITY_EDITOR
            ReportIgnore("Logout");
            success();
#elif UNITY_IOS
            _logout();
#endif
        }
Beispiel #16
0
        public static void ShowPreviousTournaments(SuccessHandler success, ErrorHandler failure)
        {
            SetCallbacksWithErrors(SHOW_PREIVOUS_TOURNAMENTS, success, failure);
#if UNITY_EDITOR
            ReportIgnore("ViewPreviousTournaments");
            success();
#elif UNITY_IOS
            _showPreviousTournaments();
#endif
        }
Beispiel #17
0
        public static void ShowUnviewedTournaments(SuccessHandler success, ErrorHandler failure)
        {
            SetCallbacksWithErrors(SHOW_UNVIEWED_TOURNAMENTS, success, failure);
#if UNITY_EDITOR
            ReportIgnore("ShowUnviewedTournaments");
            success();
#elif UNITY_IOS
            _showUnviewedTournaments();
#endif
        }
Beispiel #18
0
        public static void Init(string gameApiKey, string accessToken, SuccessHandler success, ErrorHandler failure)
        {
            SetCallbacksWithErrors(INIT, success, failure);
#if UNITY_EDITOR
            ReportIgnore("Initialize");
            success();
#elif UNITY_IOS
            _init(gameApiKey, accessToken);
#endif
        }
Beispiel #19
0
    private static void tryFetchWallet(SuccessHandler success, ErrorHandler failure)
    {
        if (!IsAuthenticated)
        {
            Debug.LogWarning("Cannot get an Arbiter Wallet without first logging in");
            return;
        }

        ArbiterBinding.FetchWallet(success, failure);
    }
Beispiel #20
0
        public static Habit AddLog(Habit h)
        {
            HabitResultHandler success = new SuccessHandler(new StreakSuccess());
            HabitResultHandler fail    = new FailHandler(new StreakFail());

            h.Attach(success);
            h.Attach(fail);
            h.AddLogs();
            return(h);
        }
Beispiel #21
0
    public static void JoinTournament(string buyIn, Dictionary <string, string> filters, JoinTournamentCallback success, FriendlyErrorHandler failure)
    {
        Func <Tournament, bool> isScorableByCurrentUser = (tournament) => {
            return((tournament.Status == Tournament.StatusType.Initializing ||
                    tournament.Status == Tournament.StatusType.InProgress) &&
                   tournament.UserCanReportScore(user.Id));
        };

        TournamentsCallback gotTournamentsPollHelper = (tournaments) => {
            List <Tournament> joinableTournaments = tournaments.Where(iTourn => isScorableByCurrentUser(iTourn)).ToList();
            if (joinableTournaments.Count > 0)
            {
                tournamentPoller.Stop();
                success(joinableTournaments[0]);
            }
            // Else wait for the poller to call this anon func again...
        };

        int       retries     = 0;
        const int MAX_RETRIES = 6;
        Action    askAgain    = () => {
            retries++;
            if (retries > MAX_RETRIES)
            {
                List <string> errors = new List <string>();
                errors.Add("Tournament request limit exceeded. Ceasing new requests.");
                List <string> descriptions = new List <string>();
                descriptions.Add("The tournament timed-out. Please try again later.");
                failure(errors, descriptions);
                tournamentPoller.Stop();
            }
            else
            {
                ArbiterBinding.FetchTournaments(gotTournamentsPollHelper, failure);
            }
        };

        SuccessHandler gotRequestResponse = () => {
            tournamentPoller.SetAction(askAgain);
        };

        TournamentsCallback gotTournamentsFirstTimeHelper = (tournaments) => {
            List <Tournament> joinableTournaments = tournaments.Where(iTourn => isScorableByCurrentUser(iTourn)).ToList();
            if (joinableTournaments.Count > 0)
            {
                success(joinableTournaments[0]);
            }
            else
            {
                RequestTournament(buyIn, filters, gotRequestResponse, failure);
            }
        };

        ArbiterBinding.FetchTournaments(gotTournamentsFirstTimeHelper, failure);
    }
Beispiel #22
0
        public static void ShowNativeDialog(string title, string message, SuccessHandler callback)
        {
            SetSimpleCallback(SHOW_NATIVE_DIALOG, callback);
#if UNITY_EDITOR
            callback();
#elif UNITY_IOS
            _showNativeDialog(title, message);
#else
            throw new PlatformNotSupportedException();
#endif
        }
Beispiel #23
0
        public void Handlers_can_return_true_safely()
        {
            var handler = new SuccessHandler();
            var hub     = new Hub();

            hub.Subscribe(handler);
            bool result = hub.Publish(new InheritedEvent());

            Assert.Equal(1, handler.Handled);
            Assert.True(result);
        }
        public async Task <Response> Handle(UpdateChosenDrink command)
        {
            var request = new UpdatePartyGuestRequest
            {
                Id            = command.Id,
                ChosenDrinkId = command.ChosenDrinkId
            };

            await _dataProvider.UpdatePartyGuest(request);

            return(SuccessHandler.ReturnUpdateSuccess(EntityName));
        }
        public async Task <Response> Handle(UpdateLocation command)
        {
            var request = new UpdatePartyRequest()
            {
                Id       = command.Id,
                Location = command.Location
            };

            await _dataProvider.UpdateParty(request);

            return(SuccessHandler.ReturnUpdateSuccess(EntityName));
        }
        public async Task <Response> Handle(UpdateFavouriteDrink command)
        {
            var request = new UpdatePersonRequest()
            {
                Id = command.Id,
                FavouriteDrinkId = command.FavouriteDrinkId
            };

            await _dataProvider.UpdatePerson(request);

            return(SuccessHandler.ReturnUpdateSuccess(EntityName));
        }
Beispiel #27
0
        public async Task <Response> Handle(UpdateVipStatus command)
        {
            var request = new UpdatePartyGuestRequest
            {
                Id    = command.Id,
                IsVIP = command.IsVip
            };

            await _dataProvider.UpdatePartyGuest(request);

            return(SuccessHandler.ReturnUpdateSuccess(EntityName));
        }
Beispiel #28
0
        public static void FetchWallet(SuccessHandler success, ErrorHandler failure)
        {
            callbacks[FETCH_WALLET] = new CallbackTuple(success, failure, (e, d) => {});
#if UNITY_EDITOR
            ReportIgnore("FetchWallet");
            Arbiter.wallet         = new Wallet();
            Arbiter.wallet.Balance = "12345";
            success();
#elif UNITY_IOS
            _fetchWallet();
#endif
        }
Beispiel #29
0
        public async Task <Response> Handle(UpdateEmail command)
        {
            var request = new UpdatePersonRequest()
            {
                Id    = command.Id,
                Email = command.Email
            };

            await _dataProvider.UpdatePerson(request);

            return(SuccessHandler.ReturnUpdateSuccess(EntityName));
        }
Beispiel #30
0
        public static void RejectCashChallenge(string challengeId, SuccessHandler callback)
        {
            SetSimpleCallback(REJECT_SCORE_CHALLENGE, callback);
#if UNITY_EDITOR
            ReportIgnore("RejectCashChallenge");
            if (callback != null)
            {
                callback();
            }
#elif UNITY_IOS
            _rejectCashChallenge(challengeId);
#endif
        }
Beispiel #31
0
        public static void SendPromoCredits(string amount, SuccessHandler success, ErrorHandler failure)
        {
            SetCallbacksWithErrors(SEND_PROMO_CREDITS, success, failure);
#if UNITY_EDITOR
            ReportIgnore("SendPromoCredits");
            if (success != null)
            {
                success();
            }
#elif UNITY_IOS
            _sendPromoCredits(amount);
#endif
        }
Beispiel #32
0
        public static void ShowTournamentDetailsPanel(string tournamentId, SuccessHandler callback)
        {
            SetSimpleCallback(SHOW_TOURNAMENT_PANEL, callback);
#if UNITY_EDITOR
            ReportIgnore("ShowTournamentDetailsPanel");
            if (callback != null)
            {
                callback();
            }
#elif UNITY_IOS
            _showTournamentDetailsPanel(tournamentId);
#endif
        }
Beispiel #33
0
        public void Get(string url, IDictionary<string, string> parameters, string expectedDataType, SuccessHandler onSuccess, ErrorHandler onError)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string k in parameters.Keys)
            {
                if (sb.Length > 0) sb.Append('&');
                sb.Append(HttpUtility.UrlEncode(k + "=" + parameters[k]));
            }
            string u2;
            if (url.IndexOf('?') > 0)
                u2 = url + "&" + sb.ToString();
            else
                u2 = url + "?" + sb.ToString();

            HttpWebRequest wrq = (HttpWebRequest) HttpWebRequest.Create(u2);
            HttpWebResponse resp = (HttpWebResponse) wrq.GetResponse();

            WebClient wc = new WebClient();
        }
Beispiel #34
0
    /// <summary>
    /// Submits a score to the leaderboard.
    /// </summary>
    /// <param name="score">The player's score.</param>
    /// <param name="success">Callback triggers on successful score submission.</param>
    /// <param name="error">Callback triggers on error.</param>
    public static Coroutine SubmitScore(int score, SuccessHandler success, ErrorHandler error)
    {
        drWWW www = new drWWW(drAPI.submitScore);
        www.AddField("score", score);

        www.OnSuccess += delegate {
            if (!(bool)www.result) {
                drDebug.LogWarning("Score not recorded; it did not beat the user's current high score");
                return;
            }

            drClient.RefreshCanvasComponent(drClient.CanvasComponent.Leaderboard);
            drClient.RefreshCanvasComponent(drClient.CanvasComponent.ActivityFeed);
            drDebug.Log("Submitted new score");
        }; www.OnSuccess += success;

        www.OnError += delegate (string errorMessage) {
            drDebug.LogError("Error submitting score: " + errorMessage);
        }; www.OnError += error;

        return www.Fetch();
    }
Beispiel #35
0
    /// <summary>
    /// FeFetches the user's awarded achievements.
    /// </summary>
    /// <param name="success">Callback triggers on successful fetch.</param>
    /// <param name="error">Callback triggers on error.</param>
    public static Coroutine FetchAchievements(SuccessHandler success, ErrorHandler error)
    {
        drWWW www = new drWWW(drAPI.fetchAchievements);

        www.OnSuccess += delegate {
            Hashtable result = www.result as Hashtable;
            Hashtable achievements = result["achievements"] as Hashtable;
            ArrayList awarded = achievements["awarded"] as ArrayList;
            ArrayList unawarded = achievements["unawarded"] as ArrayList;

            _awardedAchievements = new List<string>();

            foreach (Hashtable achievement in awarded) {
                _awardedAchievements.Add(achievement["name"] as string);
            }

            drDebug.Log("Fetched " + awarded.Count + " awarded achievements of " + (awarded.Count + unawarded.Count) + " total");
        }; www.OnSuccess += success;

        www.OnError += delegate (string errorMessage) {
            drDebug.LogError("Error fetching achievements: " + errorMessage);
        }; www.OnError += error;

        return www.Fetch();
    }
Beispiel #36
0
 /// <summary>
 /// Fetches the server time.
 /// </summary>
 /// <param name="success">Callback triggers on successful time fetch.</param>
 public static Coroutine FetchServerTime(SuccessHandler success)
 {
     return FetchServerTime(success, null);
 }
Beispiel #37
0
    /// <summary>
    /// Fetches the items in the inventory.
    /// </summary>
    /// <param name="success">Callback triggers on successful fetch.</param>
    /// <param name="error">Callback triggers on error.</param>
    public static Coroutine FetchItems(SuccessHandler success, ErrorHandler error)
    {
        drWWW www = new drWWW(drAPI.fetchItems);

        www.OnSuccess += delegate {
            Hashtable result = www.result as Hashtable;
            _inventory = new List<Item>();

            foreach (Hashtable item in result["items"] as ArrayList) {
                _inventory.Add(new Item(item));
            }

            drDebug.Log("Fetched " + inventory.Length + " inventory items");
        }; www.OnSuccess += success;

        www.OnError += delegate (string errorMessage) {
            drDebug.LogError("Error fetching items: " + errorMessage);
        }; www.OnError += error;

        return www.Fetch();
    }
Beispiel #38
0
 /// <summary>
 /// Fetches the items in the inventory.
 /// </summary>
 /// <param name="success">Callback triggers on successful fetch.</param>
 public static Coroutine FetchItems(SuccessHandler success)
 {
     return FetchItems(success, null);
 }
Beispiel #39
0
    /// <summary>
    /// Removes an item from the inventory. A common use for this is consumable items (health packs, powerups, etc.) that get used up.
    /// </summary>
    /// <param name="itemName">The name of the item.</param>
    /// <param name="quantity">The quantity of the item to remove.</param>
    /// <param name="success">Callback triggers on successful remove.</param>
    /// <param name="error">Callback triggers on error.</param>
    public static Coroutine RemoveItem(string itemName, int quantity, SuccessHandler success, ErrorHandler error)
    {
        drWWW www = new drWWW(drAPI.removeItem);
        www.AddField("name",     itemName);
        www.AddField("quantity", quantity);

        www.OnSuccess += delegate {
            if (!(bool)www.result) {
                drDebug.LogWarning("Item " + itemName + " not removed from inventory");
         			return;
            }

            Item itemToRemove = GetItem(itemName);

            if (itemToRemove == null) {
                drDebug.LogWarning("Item " + itemName + " is not contained in your inventory");
                return;
            }

            itemToRemove.quantity -= quantity;

            if (itemToRemove.quantity < 0) {
                drDebug.LogWarning("Item " + itemName + " has a quantity less than " + quantity);
            }

            // Remove the item entirely if its quantity is zero
            if (itemToRemove.quantity <= 0) {
                _inventory.Remove(itemToRemove);
            }

            drClient.RefreshCanvasComponent(drClient.CanvasComponent.Inventory);
            drDebug.Log("Item " + itemName + " removed from inventory");
        }; www.OnSuccess += success;

        www.OnError += delegate (string errorMessage) {
            drDebug.LogError("Error removing item: " + errorMessage);
        }; www.OnError += error;

        return www.Fetch();
    }
Beispiel #40
0
 /// <summary>
 /// Fetches the user's awarded achievements.
 /// </summary>
 /// <param name="success">Callback triggers on successful fetch.</param>
 public static Coroutine FetchAchievements(SuccessHandler success)
 {
     return FetchAchievements(success, null);
 }
Beispiel #41
0
 static IEnumerator SendCoroutine(string method, Dictionary<string, object> parameters, SuccessHandler successCallback, ErrorHandler errorCallback)
 {
     yield break;
 }
Beispiel #42
0
 /// <summary>
 /// Loads data.
 /// </summary>
 /// <param name="success">Callback triggers on successful data load.</param>
 public static Coroutine LoadData(SuccessHandler success)
 {
     return LoadData(success, null);
 }
Beispiel #43
0
    /// <summary>
    /// Saves data.
    /// </summary
    /// <param name="data">The data to save.</param>
    /// <param name="success">Callback triggers on successful data save.</param>
    /// <param name="error">Callback triggers on error.</param>
    public static Coroutine SaveData(Hashtable data, SuccessHandler success, ErrorHandler error)
    {
        string json = JSON.JsonEncode(data);

        drWWW www = new drWWW(drAPI.saveData);
        www.AddField("data", json);

        www.OnSuccess += delegate {
            if (!(bool)www.result) {
                drDebug.LogWarning("No data saved");
                return;
            }

            StoreReturnData(data);

            drDebug.Log("Data saved");
        }; www.OnSuccess += success;

        www.OnError += delegate (string errorMessage) {
            drDebug.LogError("Error saving data: " + errorMessage);
        }; www.OnError += error;

        return www.Fetch();
    }
Beispiel #44
0
 /// <summary>
 /// Saves data with the specified key.
 /// </summary
 /// <param name="key">The key to save the data by.</param>
 /// <param name="data">The data to save.</param>
 /// <param name="success">Callback triggers on successful data save.</param>
 public static Coroutine SaveDataByKey(string key, object data, SuccessHandler success)
 {
     return SaveDataByKey(key, data, success, null);
 }
Beispiel #45
0
 /// <summary>
 /// Submits an item to the activity feed.
 /// </summary>
 /// <param name="message">The text to display (140 character maximum).</param>
 /// <param name="success">Callback triggers on successful activity feed submission.</param>
 public static Coroutine SubmitActivity(string message, SuccessHandler success)
 {
     return SubmitActivity(message, success, null);
 }
Beispiel #46
0
    /// <summary>
    /// Sends data to Lumos' servers.
    /// </summary>
    /// <param name="successCallback">Callback to run on successful response.</param>
    /// <param name="errorCallback">Callback to run on failed response.</param>
    static IEnumerator SendCoroutine(string method, Dictionary<string, object> parameters, SuccessHandler successCallback, ErrorHandler errorCallback)
    {
        if (Application.isEditor && !Lumos.instance.runInEditor) {
            yield break;
        }

        // Skip out early if there's no internet connection
        if (Application.internetReachability == NetworkReachability.NotReachable) {
            if (errorCallback != null) {
                errorCallback();
            }

            yield break;
        }

        // Generate request
        parameters.Add("app_id", Lumos.appId);
        var json = LumosUtil.Json.Serialize(parameters);
        //var json = LitJson.JsonMapper.ToJson(parameters);
        var postData = Encoding.ASCII.GetBytes(json);
        var www = new WWW(url + method, postData, headers);

        // Send info to server
        yield return www;
        Lumos.Log("Request: " + json);
        Lumos.Log("Response: " + www.text);

        // Parse the response
        try {
            if (www.error != null) {
                throw new Exception(www.error);
            }

            var response = LumosUtil.Json.Deserialize(www.text) as IDictionary;
            lastResponse = response;

            // Display returned info if there is any
            if (response.Count != 0 && response.Contains("result")) {
                var result = response["result"];
                Lumos.Log("Success: " + result);
            }

            if (successCallback != null) {
                successCallback();
            }
        } catch (Exception e) {
            Lumos.LogError("Failure: " + e.Message);

            if (errorCallback != null) {
                errorCallback();
            }
        }
    }
Beispiel #47
0
 /// <summary>
 /// Sends data to Lumos' servers.
 /// </summary>
 /// <param name="successCallback">Callback to run on successful response.</param>
 /// <param name="errorCallback">Callback to run on failed response.</param>
 public static Coroutine Send(string method, Dictionary<string, object> parameters, SuccessHandler successCallback, ErrorHandler errorCallback)
 {
     return Lumos.RunRoutine(SendCoroutine(method, parameters, successCallback, errorCallback));
 }
Beispiel #48
0
 /// <summary>
 /// Fetches the server time.
 /// </summary>
 /// <param name="success">Callback triggers on successful session fetch.</param>
 public static Coroutine FetchSession(SuccessHandler success)
 {
     return FetchSession(success, null);
 }
Beispiel #49
0
    /// <summary>
    /// Loads data with the specified key.
    /// </summary>
    /// <param name="key">The key to load the data by.</param>
    /// <param name="success">Callback triggers on successful data load.</param>
    /// <param name="error">Callback triggers on error.</param>
    public static Coroutine LoadDataByKey(string key, SuccessHandler success, ErrorHandler error)
    {
        drWWW www = new drWWW(drAPI.loadDataByKey);
        www.AddField("key", key);

        www.OnSuccess += delegate {
            Hashtable result = www.result as Hashtable;

            if (result["data"] == null) {
                drDebug.LogWarning("No data with key " + key + " exists in the data store to load");
           		return;
            }

            StoreReturnData(result["data"] as Hashtable);

            drDebug.Log("Loaded data with key " + key);
        }; www.OnSuccess += success;

        www.OnError += delegate (string errorMessage) {
            drDebug.LogError("Error loading data with key " + key + ": " + errorMessage);
        }; www.OnError += error;

        return www.Fetch();
    }
Beispiel #50
0
    /// <summary>
    /// Fetches the server time.
    /// </summary>
    /// <param name="success">Callback triggers on successful session fetch.</param>
    /// <param name="error">Callback triggers on error.</param>
    public static Coroutine FetchSession(SuccessHandler success, ErrorHandler error)
    {
        drWWW www = new drWWW(drAPI.fetchSession);

        www.OnSuccess += delegate {
            Hashtable result = www.result as Hashtable;
            drClient.sessionId = result["_token"].ToString();
            drDebug.Log("Fetched session " + drClient.sessionId);
        }; www.OnSuccess += success;

        www.OnError += delegate (string errorMessage) {
            drDebug.LogError("Error fetching session: " + errorMessage);
        }; www.OnError += error;

        return www.Fetch();
    }
Beispiel #51
0
    /// <summary>
    /// Saves data with the specified key.
    /// </summary
    /// <param name="key">The key to save the data by.</param>
    /// <param name="data">The data to save.</param>
    /// <param name="success">Callback triggers on successful data save.</param>
    /// <param name="error">Callback triggers on error.</param>
    public static Coroutine SaveDataByKey(string key, object data, SuccessHandler success, ErrorHandler error)
    {
        Hashtable dataTable = new Hashtable();
        dataTable.Add("key",   key);
        dataTable.Add("value", data);
        string json = JSON.JsonEncode(dataTable);

        drWWW www = new drWWW(drAPI.saveDataByKey);
        www.AddField("data", json);

        www.OnSuccess += delegate {
            if (!(bool)www.result) {
                drDebug.LogWarning("No data saved with key " + key);
                return;
            }

            Hashtable toSave = new Hashtable();
            toSave.Add(key, data);

            StoreReturnData(toSave);

            drDebug.Log("Saved data with key " + key);
        }; www.OnSuccess += success;

        www.OnError += delegate (string errorMessage) {
            drDebug.LogError("Error saving data: " + errorMessage);
        }; www.OnError += error;

        return www.Fetch();
    }
Beispiel #52
0
    /// <summary>
    /// Submits an item to the activity feed.
    /// </summary>
    /// <param name="message">The text to display (140 character maximum).</param>
    /// <param name="success">Callback triggers on successful activity feed submission.</param>
    /// <param name="error">Callback triggers on error.</param>
    public static Coroutine SubmitActivity(string message, SuccessHandler success, ErrorHandler error)
    {
        if (message == null || message == "") {
            drDebug.LogWarning("Message not submitted to activity feed: a null or empty message was supplied");
            return null;
        } else if (message.Length > 140) {
            drDebug.LogWarning("Message not submitted to activity feed: amessage have to be less than or equal to 140 characters");
            return null;
        }

        drWWW www = new drWWW(drAPI.addCustomActivity);
        www.AddField("message", message);

        www.OnSuccess += delegate {
            if (!(bool)www.result) { // This should never occur, but the check is here just in case
                drDebug.LogWarning("Message not submitted to activity feed");
         			return;
            }

            drClient.RefreshCanvasComponent(drClient.CanvasComponent.ActivityFeed);
            drDebug.Log("Message submitted to activity feed");
        }; www.OnSuccess += success;

        www.OnError += delegate (string errorMessage) {
            drDebug.LogError("Error submitting to activity feed: " + errorMessage);
        }; www.OnError += error;

        return www.Fetch();
    }
Beispiel #53
0
 /// <summary>
 /// Submits a score to the leaderboard.
 /// </summary>
 /// <param name="score">The player's score.</param>
 /// <param name="success">Callback triggers on successful score submission.</param>
 public static Coroutine SubmitScore(int score, SuccessHandler success)
 {
     return SubmitScore(score, success, null);
 }
Beispiel #54
0
    /// <summary>
    /// Fetches the server time.
    /// </summary>
    /// <param name="success">Callback triggers on successful time fetch.</param>
    /// <param name="error">Callback triggers on error.</param>
    public static Coroutine FetchServerTime(SuccessHandler success, ErrorHandler error)
    {
        drWWW www = new drWWW(drAPI.fetchServerTime);

        www.OnSuccess += delegate {
            serverTimeAtLastFetch = drUtil.ConvertFromUnixTimestamp((double)www.result);
            timeFetched = System.DateTime.Now;
            drDebug.Log("Fetched time from server");
        }; www.OnSuccess += success;

        www.OnError += delegate (string errorMessage) {
            drDebug.LogError("Error fetching server time: " + errorMessage);
        }; www.OnError += error;

        return www.Fetch();
    }
Beispiel #55
0
 /// <summary>
 /// Saves data.
 /// </summary
 /// <param name="data">The data to save.</param>
 /// <param name="success">Callback triggers on successful data save.</param>
 public static Coroutine SaveData(Hashtable data, SuccessHandler success)
 {
     return SaveData(data, success, null);
 }
Beispiel #56
0
 /// <summary>
 /// Removes an item from the inventory. A common use for this is consumable items (health packs, powerups, etc.) that get used up.
 /// </summary>
 /// <param name="itemName">The name of the item.</param>
 /// <param name="quantity">The quantity of the item to remove.</param>
 /// <param name="success">Callback triggers on successful remove.</param>
 public static Coroutine RemoveItem(string itemName, int quantity, SuccessHandler success)
 {
     return RemoveItem(itemName, quantity, success, null);
 }
Beispiel #57
0
 /// <summary>
 /// Loads data with the specified key.
 /// </summary>
 /// <param name="key">The key to load the data by.</param>
 /// <param name="success">Callback triggers on successful data load.</param>
 public static Coroutine LoadDataByKey(string key, SuccessHandler success)
 {
     return LoadDataByKey(key, success, null);
 }
Beispiel #58
0
 /// <summary>
 /// Removes an item from the inventory. A common use for this is consumable items (health packs, powerups, etc.) that get used up.
 /// </summary>
 /// <param name="itemName">The name of the item.</param>
 /// <param name="success">Callback triggers on successful remove.</param>
 /// <param name="error">Callback triggers on error.</param>
 public static Coroutine RemoveItem(string itemName, SuccessHandler success, ErrorHandler error)
 {
     return RemoveItem(itemName, 1, success, null);
 }
Beispiel #59
0
 public void Post(string url, IDictionary<string, string> parameters, string expectedDataType, SuccessHandler onSuccess, ErrorHandler onError)
 {
 }
Beispiel #60
0
 /// <summary>
 /// Awards an achievement.
 /// </summary>
 /// <param name="achievementName">The name of the achievement to award.</param>
 /// <param name="success">Callback triggers on successful award.</param>
 public static Coroutine AwardAchievement(string achievementName, SuccessHandler success)
 {
     return AwardAchievement(achievementName, success, null);
 }