Ejemplo n.º 1
0
        public void OnAppRequestsComplete(string message)
        {
            var rawResult = (Dictionary <string, object>)MiniJSON.Json.Deserialize(message);

            if (rawResult.ContainsKey(CallbackIdKey))
            {
                var result     = new Dictionary <string, object>();
                var callbackId = (string)rawResult[CallbackIdKey];
                rawResult.Remove(CallbackIdKey);
                if (rawResult.Count > 0)
                {
                    List <string> to = new List <string>(rawResult.Count - 1);
                    foreach (string key in rawResult.Keys)
                    {
                        if (!key.StartsWith("to"))
                        {
                            result[key] = rawResult[key];
                            continue;
                        }
                        to.Add((string)rawResult[key]);
                    }
                    result.Add("to", to);
                    rawResult.Clear();
                    FbDebug.Log("Call the callback " + callbackId + " with " + MiniJSON.Json.Serialize(result));
                    OnFacebookResponse(callbackId, new FBResult(MiniJSON.Json.Serialize(result)));
                }
                else
                {
                    //if we make it here java returned a callback message with only an id
                    //this isnt supposed to happen
                    OnFacebookResponse(callbackId, new FBResult(MiniJSON.Json.Serialize(result), "Malformed request response.  Please file a bug with facebook here: https://developers.facebook.com/bugs/create"));
                }
            }
        }
Ejemplo n.º 2
0
        public override void Init(
            InitDelegate onInitComplete,
            string appId,
            bool cookie                         = false,
            bool logging                        = true,
            bool status                         = true,
            bool xfbml                          = false,
            string channelUrl                   = "",
            string authResponse                 = null,
            bool frictionlessRequests           = false,
            HideUnityDelegate hideUnityDelegate = null)
        {
            if (appId == null || appId == "")
            {
                throw new ArgumentException("appId cannot be null or empty!");
            }

            FbDebug.Log("start android init");

            var parameters = new Dictionary <string, object>();

            if (appId != "")
            {
                parameters.Add("appId", appId);
            }
            if (cookie != false)
            {
                parameters.Add("cookie", true);
            }
            if (logging != true)
            {
                parameters.Add("logging", false);
            }
            if (status != true)
            {
                parameters.Add("status", false);
            }
            if (xfbml != false)
            {
                parameters.Add("xfbml", true);
            }
            if (channelUrl != "")
            {
                parameters.Add("channelUrl", channelUrl);
            }
            if (authResponse != null)
            {
                parameters.Add("authResponse", authResponse);
            }
            if (frictionlessRequests != false)
            {
                parameters.Add("frictionlessRequests", true);
            }

            var paramJson = MiniJSON.Json.Serialize(parameters);

            this.onInitComplete = onInitComplete;

            this.CallFB("Init", paramJson.ToString());
        }
Ejemplo n.º 3
0
 public void OnLogoutComplete(string message)
 {
     FbDebug.Log("OnLogoutComplete");
     isLoggedIn  = false;
     userId      = "";
     accessToken = "";
 }
        public void UpdatePlayerData(Player player)
        {
            try{
                string jsonString;
                if (player.Revision != null)
                {
                    jsonString = "{\"_id\":\"" + player.Id + "\",\"_rev\":\"" + player.Revision + "\",\"Name\":\"" + player.Name + "\",\"Coins\":" + player.Coins + ",\"Highscore\":" + player.Highscore + "}";
                }
                else
                {
                    jsonString = "{\"Name\":\"" + player.Name + "\",\"Coins\":" + player.Coins + ",\"Highscore\":" + player.Highscore + "}";
                }

                HTTP.Request request = new HTTP.Request("put", this.baseUrl + "players/" + player.Id, new MemoryStream(Encoding.UTF8.GetBytes(jsonString)));
                request.synchronous = true;
                request.Send((requestObject) => {
                    JSONObject playerJSON  = new JSONObject(requestObject.response.Text);
                    List <JSONObject> json = playerJSON.list;
                    player.Revision        = json[2].str;
                });
                while (!request.isDone)
                {
                }
            }
            catch (Exception e)
            {
                FbDebug.Log(e.StackTrace);
            }
        }
        public Match GetMatchForId(string id)
        {
            try{
                HTTP.Request request = new HTTP.Request("get", this.baseUrl + ("matches/" + id));
                request.Send();
                while (!request.isDone)
                {
                }
                JSONObject        matchesJson = new JSONObject(request.response.Text);
                List <JSONObject> json        = matchesJson.list;
                if (!(json[0].str == "not_found" && json[1].str == "missing"))
                {
                    Match match = new Match();
                    //match.Id = json[0].str;
                    //match.Revision = json[1].str;
                    //match.ChallengerId = json[2].str;
                    //match.ChallengedId = json[3].str;
                    match.ChallengerScore = (int)json[4].n;
                    match.ChallengedScore = (int)json[5].n;
                    //match.Winner = json[6].str;
                    match.Seed = (int)json[7].n;

                    return(match);
                }
            }
            catch (Exception e)
            {
                FbDebug.Log(e.StackTrace);
            }
            return(null);
        }
Ejemplo n.º 6
0
 void OnLoggedIn()
 {
     FbDebug.Log("Logged in. ID: " + FB.UserId);
     // Request player info and profile picture
     FB.API("/me?fields=id,first_name,friends.limit(100).fields(first_name,id)", Facebook.HttpMethod.GET, APICallback);
     FB.API(Util.GetPictureURL("me", 128, 128), Facebook.HttpMethod.GET, MyPictureCallback);
 }
Ejemplo n.º 7
0
    public static void EndGame()
    {
        if (immortal)
        {
            return;
        }
        GameObject[] friends = GameObject.FindGameObjectsWithTag("Friend");
        GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
        foreach (GameObject t in friends)
        {
            Destroy(t);
        }
        foreach (GameObject t in enemies)
        {
            Destroy(t);
        }
        FbDebug.Log("EndGame Instance.highScore = " + Instance.highScore + "\nInstance.score = " + Instance.score);


        Instance.highScore = Instance.score;
        FbDebug.Log("Player has new high score :" + Instance.score);


        Application.LoadLevel("MainMenu");
        Time.timeScale = 0.0f;
    }
Ejemplo n.º 8
0
 public void GetFbProfileInfo()
 {
     FbDebug.Log("Logged in. ID: " + FB.UserId);
     // Reqest player info and profile picture
     FB.API("/me?fields=id,first_name,friends.limit(100).fields(first_name,id,picture)", Facebook.HttpMethod.GET, APICallback);
     FB.API(Util.GetPictureURL("me", 1024, 1024), Facebook.HttpMethod.GET, MyPictureCallback);
 }
 public override void AppEventsLogPurchase(
     float logPurchase,
     string currency = "USD",
     Dictionary <string, object> parameters = null)
 {
     FbDebug.Log("Pew! Pretending to send this off.  Doesn't actually work in the editor");
 }
Ejemplo n.º 10
0
    /**
     * onInitComplete - Delegate is called when FB.Init() finished initializing everything.
     *                  By passing in a delegate you can find out when you can safely call the other methods.
     */
    public static void Init(Facebook.InitDelegate onInitComplete, Facebook.HideUnityDelegate onHideUnity = null, string authResponse = null)
    {
        if (!isInitCalled)
        {
            FB.authResponse   = authResponse;
            FB.OnInitComplete = onInitComplete;
            FB.OnHideUnity    = onHideUnity;

            FbDebug.Info(String.Format("Using SDK {0}, Build {1}", FBBuildVersionAttribute.SDKVersion, FBBuildVersionAttribute.GetBuildVersionOfType(typeof(IFacebook))));

#if UNITY_EDITOR
            FBComponentFactory.GetComponent <EditorFacebookLoader>();
#elif UNITY_WEBPLAYER
            FBComponentFactory.GetComponent <CanvasFacebookLoader>();
#elif UNITY_IOS
            FBComponentFactory.GetComponent <IOSFacebookLoader>();
#elif UNITY_ANDROID
            FBComponentFactory.GetComponent <AndroidFacebookLoader>();
#else
            throw new NotImplementedException("Facebook API does not yet support this platform");
#endif
            FB.isInitCalled = true;
            return;
        }

        FbDebug.Warn("FB.Init() has already been called.  You only need to call this once and only once.");

        // Init again if possible just in case something bad actually happened.
        if (FacebookImpl != null)
        {
            OnDllLoaded();
        }
    }
 public static void Log(string msg)
 {
     if (allowLogging)
     {
         FbDebug.Log(msg);
     }
 }
Ejemplo n.º 12
0
    private static void OnDllLoaded()
    {
        var versionInfo = FBBuildVersionAttribute.GetVersionAttributeOfType(FacebookImpl.GetType());

        if (versionInfo == null)
        {
            FbDebug.Warn("Finished loading Facebook dll, but could not find version info");
        }
        else
        {
            FbDebug.Log(string.Format("Finished loading Facebook dll. Version {0} Build {1}", versionInfo.SdkVersion, versionInfo.BuildVersion));
        }
        FacebookImpl.Init(
            OnInitComplete,
            appId,
            cookie,
            logging,
            status,
            xfbml,
            FBSettings.ChannelUrl,
            authResponse,
            frictionlessRequests,
            OnHideUnity
            );
    }
Ejemplo n.º 13
0
    public static void likeFriends(FBResult result)
    {
        if (result.Error != null)
        {
            FbDebug.Error(result.Error);
            Debug.LogError(result.Error);

            FB.API("fql?q=SELECT+uid+FROM+page_fan+WHERE+page_id=1477936459088484+AND+uid+IN+(SELECT+uid1+FROM+friend+WHERE+uid2=" + FB.UserId + ")", Facebook.HttpMethod.GET, likeFriends);
            return;
        }

        List <object> likesFriends = Util.DeserializeLikeFriends(result.Text);

        var x = 0;

        foreach (object temp in likesFriends)
        {
            Dictionary <string, object> t = (Dictionary <string, object>)temp;
            string uid = System.Convert.ToString(t["uid"]);

            if (LikeUs.instance != null)
            {
                LikeUs.instance.setFriendsFid(uid, x);
            }

            x++;

            if (x > 10)
            {
                break;
            }
        }
    }
Ejemplo n.º 14
0
    public void GetUserHighScoreProfilePicture(UserHighScore userHighScore, int?width = null, int?height = null, string type = null)
    {
        string path = Path.Combine(Application.persistentDataPath, userHighScore.UserId + "_ProfilePicture.png");

        if (File.Exists(path) && DateTime.Now - File.GetLastWriteTime(path) < TimeSpan.FromDays(this.DaysToKeepProfilePicture))
        {
            userHighScore.ProfilePicture = TextureIo.ReadTextureFromFile(
                path, width ?? userHighScore.ProfilePicture.width, height ?? userHighScore.ProfilePicture.height);
        }
        else
        {
            string url = this.GetPictureURL(userHighScore.UserId, width, height, type);
            FB.API(
                url,
                HttpMethod.GET,
                result =>
            {
                if (result.Error != null)
                {
                    FbDebug.Error(result.Error);

                    return;
                }

                userHighScore.ProfilePicture = result.Texture;
                TextureIo.SaveTextureToFile(path, userHighScore.ProfilePicture);
            });
        }
    }
 public static void Warn(string msg)
 {
     if (allowLogging)
     {
         FbDebug.Warn(msg);
     }
 }
 public override void AppEventsLogEvent(
     string logEvent,
     float?valueToSum = null,
     Dictionary <string, object> parameters = null)
 {
     FbDebug.Log("Pew! Pretending to send this off.  Doesn't actually work in the editor");
 }
 public static void Error(string msg)
 {
     if (allowLogging)
     {
         FbDebug.Error(msg);
     }
 }
Ejemplo n.º 18
0
        private static bool IsVersion42OrLater()
        {
            string version = Application.unityVersion;

            string[] versionComponents = version.Split('.');

            int majorVersion = 0;
            int minorVersion = 0;

            try
            {
                if (versionComponents != null && versionComponents.Length > 0 && versionComponents[0] != null)
                {
                    majorVersion = Convert.ToInt32(versionComponents[0]);
                }
                if (versionComponents != null && versionComponents.Length > 1 && versionComponents[1] != null)
                {
                    minorVersion = Convert.ToInt32(versionComponents[1]);
                }
            }
            catch (System.Exception e)
            {
                FbDebug.Error("Error parsing Unity version number: " + e);
            }

            return(majorVersion > 4 || (majorVersion == 4 && minorVersion >= 2));
        }
Ejemplo n.º 19
0
        public static IEnumerator LoadFacebookClass(string className, LoadedDllCallback callback)
        {
            var url = string.Format(IntegratedPluginCanvasLocation.DllUrl, className);
            var www = new WWW(url);

            FbDebug.Log("loading dll: " + url);
            yield return(www);

            if (www.error != null)
            {
                FbDebug.Error(www.error);
                if (retryLoadCount < maxRetryLoadCount)
                {
                    ++retryLoadCount;
#if UNITY_WEBPLAYER
                    FBComponentFactory.AddComponent <CanvasFacebookLoader>();
#endif
                }
                www.Dispose();
                yield break;
            }

            var assembly = Security.LoadAndVerifyAssembly(www.bytes,
                                                          "B8GvecdX0rQ47kzhCEwlrRzYKA8LKeiZxy1HI3HfnhdgUATvBwQQViji8ot44dADM55QuHk5+hwrLso" +
                                                          "au32IDmRDQTclMSsTsIywGRo/nE5vbmRMMIECYXBFhliz+kvK0RWZ57XPxw0s7YhGnNLav0EE2QH/m+9a" +
                                                          "jlLOY+2ckxSoSEHLpotllyZLktRK+oFiDPvmzXLDUMOnwK9RFRSh2VBmoyWTZx8BYqWjqug3kAljJk/Xw" +
                                                          "TYZT9Ie+HvzLO5DBSqMNYbEX03WaNfpaq9GKBF/Oz37AHelf1Es36amP1v2Aut3nmIk2xxN6zwzBXyEyw" +
                                                          "90vJ/O8suikU+8kDDbZA==");
            if (assembly == null)
            {
                FbDebug.Error("Could not securely load assembly from " + url);
                www.Dispose();
                yield break;
            }

            var facebookClass = assembly.GetType(facebookNamespace + className);
            if (facebookClass == null)
            {
                FbDebug.Error(className + " not found in assembly!");
                www.Dispose();
                yield break;
            }

            // load the Facebook component into the gameobject
            // using the "as" cast so it'll null if it fails to cast, instead of exception
            var fb = typeof(FBComponentFactory)
                     .GetMethod("GetComponent")
                     .MakeGenericMethod(facebookClass)
                     .Invoke(null, new object[] { IfNotExist.AddNew }) as IFacebook;

            if (fb == null)
            {
                FbDebug.Error(className + " couldn't be created.");
                www.Dispose();
                yield break;
            }

            callback(fb);
            www.Dispose();
        }
Ejemplo n.º 20
0
 private void onChallengeClicked()
 {
     FbDebug.Log("onChallengeClicked");
     if (GameStateManager.Score != 0 && GameStateManager.FriendID != null)
     {
         string[] recipient = { GameStateManager.FriendID };
         FB.AppRequest(
             message: "I just smashed you " + GameStateManager.Score.ToString() + " times! Can you beat it?",
             to: recipient,
             filters: "",
             excludeIds: null,
             maxRecipients: null,
             data: "{\"challenge_score\":" + GameStateManager.Score.ToString() + "}",
             title: "Friend Smash Challenge!",
             callback: appRequestCallback
             );
     }
     else
     {
         FB.AppRequest(
             message: "Friend Smash is smashing! Check it out.",
             title: "Play Friend Smash with me!",
             callback: appRequestCallback
             );
     }
 }
Ejemplo n.º 21
0
    void ScoresCallback(FBResult result)
    {
        FbDebug.Log("ScoresCallback");
        if (result.Error != null)
        {
            FbDebug.Error(result.Error);
            return;
        }

        scores = new List <object>();
        List <object> scoresList = Util.DeserializeScores(result.Text);

        foreach (object score in scoresList)
        {
            var entry = (Dictionary <string, object>)score;
            var user  = (Dictionary <string, object>)entry["user"];

            string userId = (string)user["id"];

            if (string.Equals(userId, FB.UserId))
            {
                // This entry is the current player
                int playerHighScore = getScoreFromEntry(entry);
                FbDebug.Log("Local players score on server is " + playerHighScore);
                if (playerHighScore < GameStateManager.Score)
                {
                    FbDebug.Log("Locally overriding with just acquired score: " + GameStateManager.Score);
                    playerHighScore = GameStateManager.Score;
                }

                entry["score"]             = playerHighScore.ToString();
                GameStateManager.HighScore = playerHighScore;
            }

            scores.Add(entry);
            if (!friendImages.ContainsKey(userId))
            {
                // We don't have this players image yet, request it now
                FB.API(Util.GetPictureURL(userId, 128, 128), Facebook.HttpMethod.GET, pictureResult =>
                {
                    if (pictureResult.Error != null)
                    {
                        FbDebug.Error(pictureResult.Error);
                    }
                    else
                    {
                        friendImages.Add(userId, pictureResult.Texture);
                    }
                });
            }
        }

        // Now sort the entries based on score
        scores.Sort(delegate(object firstObj,
                             object secondObj)
        {
            return(-getScoreFromEntry(firstObj).CompareTo(getScoreFromEntry(secondObj)));
        }
                    );
    }
 public static void Info(string msg)
 {
     if (allowLogging)
     {
         FbDebug.Info(msg);
     }
 }
Ejemplo n.º 23
0
    public static void likeMe(FBResult result)
    {
        if (result.Error != null)
        {
            FbDebug.Error(result.Error);
            Debug.LogError(result.Error);

            FB.API("fql?q=SELECT+uid+FROM+page_fan+WHERE+page_id=1477936459088484+AND+uid=" + FB.UserId + ")", Facebook.HttpMethod.GET, likeMe);
            return;
        }

        List <object> checkMy = Util.DeserializeLikeFriends(result.Text);

        foreach (object temp in checkMy)
        {
            Dictionary <string, object> t = (Dictionary <string, object>)temp;
            string uid = System.Convert.ToString(t["uid"]);

            if (uid.Equals(FB.UserId))
            {
                if (LikeUs.instance != null)
                {
                    LikeUs.instance.setLikeButtonSet(true);
                }
                return;
            }
        }

        if (LikeUs.instance != null)
        {
            LikeUs.instance.setLikeButtonSet(false);
        }
    }
Ejemplo n.º 24
0
    /**
     * If you need a more programmatic way to set the facebook app id and other setting call this function.
     * Useful for a build pipeline that requires no human input.
     */
    public static void Init(
        InitDelegate onInitComplete,
        string appId,
        bool cookie  = true,
        bool logging = true,
        bool status  = true,
        bool xfbml   = false,
        bool frictionlessRequests     = true,
        HideUnityDelegate onHideUnity = null,
        string authResponse           = null)
    {
        FB.appId   = appId;
        FB.cookie  = cookie;
        FB.logging = logging;
        FB.status  = status;
        FB.xfbml   = xfbml;
        FB.frictionlessRequests = frictionlessRequests;
        FB.authResponse         = authResponse;
        FB.OnInitComplete       = onInitComplete;
        FB.OnHideUnity          = onHideUnity;

        if (!isInitCalled)
        {
            var versionInfo = FBBuildVersionAttribute.GetVersionAttributeOfType(typeof(IFacebook));

            if (versionInfo == null)
            {
                FbDebug.Warn("Cannot find Facebook SDK Version");
            }
            else
            {
                FbDebug.Info(String.Format("Using SDK {0}, Build {1}", versionInfo.SdkVersion, versionInfo.BuildVersion));
            }

#if UNITY_EDITOR
            FBComponentFactory.GetComponent <EditorFacebookLoader>();
#elif UNITY_WEBPLAYER
            FBComponentFactory.GetComponent <CanvasFacebookLoader>();
#elif UNITY_IOS
            FBComponentFactory.GetComponent <IOSFacebookLoader>();
#elif UNITY_ANDROID
            FBComponentFactory.GetComponent <AndroidFacebookLoader>();
#elif UNITY_WP8
            FBComponentFactory.GetComponent <WindowsPhoneFacebookLoader>();
#else
            throw new NotImplementedException("Facebook API does not yet support this platform");
#endif
            isInitCalled = true;
            return;
        }

        FbDebug.Warn("FB.Init() has already been called.  You only need to call this once and only once.");

        // Init again if possible just in case something bad actually happened.
        if (FacebookImpl != null)
        {
            OnDllLoaded();
        }
    }
Ejemplo n.º 25
0
    public WWW POSTGETMESSAGE(string page, string data)
    {
        FbDebug.Log("postgetmessage test : " + data);
        WWW www = new WWW(CDefine.serverURL, Encoding.Default.GetBytes(data));

        StartCoroutine(WaitForGetMessage(www));
        return(www);
    }
 public override void GetDeepLink(FacebookDelegate callback)
 {
     FbDebug.Info("No Deep Linking in the Editor");
     if (callback != null)
     {
         callback(new FBResult("<platform dependent>"));
     }
 }
Ejemplo n.º 27
0
    public WWW POSTSENDMESSAGE(string page, string data, string fid, CallBackClass.SendMessageCallBack callback)
    {
        FbDebug.Log("postsendmessage test : " + data);
        WWW www = new WWW(CDefine.serverURL, Encoding.Default.GetBytes(data));

        StartCoroutine(WaitForSendMessage(www, fid, callback));
        return(www);
    }
Ejemplo n.º 28
0
        public static IEnumerator LoadFacebookClass(string className, LoadedDllCallback callback)
        {
            var url = string.Format(IntegratedPluginCanvasLocation.DllUrl, className);
            var www = new WWW(url);

            FbDebug.Log("loading dll: " + url);
            yield return(www);
        }
Ejemplo n.º 29
0
        private void CallFB(string method, string args)
        {
#if UNITY_ANDROID
            FB.CallStatic(method, args);
#else
            FbDebug.Error("Using Android when not on an Android build!  Doesn't Work!");
#endif
        }
Ejemplo n.º 30
0
    public WWW POSTLOGIN(string page, string data)
    {
        FbDebug.Log("postloing test : " + data);
        WWW www = new WWW(CDefine.serverURL, Encoding.Default.GetBytes(data));

        StartCoroutine(WaitForRequest(www));
        return(www);
    }