123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959 |
- using System.Text;
- using UnityEngine;
- using System.Collections;
- using System;
- using Facebook.Unity;
- using Prime31;
- #if UNITY_ANDROID
- //using FacebookAccess = Prime31.FacebookAndroid;
- #elif UNITY_IPHONE
- //using FacebookAccess = Prime31.FacebookBinding;
- #elif UNITY_WEBPLAYER
- using FacebookAccess = FacebookWeb;
- #endif
- public class FacebookHelper : MonoBehaviour
- {
- #region Unity Singleton
- private static FacebookHelper _instance;
- public static FacebookHelper Instance
- {
- get
- {
- if (_instance == null)
- {
- _instance = FindObjectOfType(typeof(FacebookHelper)) as FacebookHelper;
- if (_instance == null)
- {
- AVDebug.LogError(string.Format("No gameObject with {0} component exists. Make sure to create a gameObject with {0} component", new System.Diagnostics.StackFrame().GetMethod().DeclaringType));
- }
- }
- return _instance;
- }
- }
- void Awake()
- {
- if (_instance != null && _instance != this)
- {
- AVDebug.LogWarning(string.Format("{0} Instance already exists on another gameObject. Destroying this gameObject {1}", this.GetType().Name, gameObject.name));
- Destroy(gameObject);
- return;
- }
- _instance = this;
- DontDestroyOnLoad(gameObject);
- RegisterListeners();
- }
- void OnDestroy()
- {
- //Reset any actions
- OnSuccessfulLoginWithPermissions = null;
- OnQueryHasLikedPageComplete = null;
- OnLogout = null;
- UnregisterListeners();
- }
- #endregion
- Action OnSuccessfulLoginWithPermissions;
- public static void AddSuccessfulLoginWithPermissionsListener(Action listener)
- {
- Instance.OnSuccessfulLoginWithPermissions += listener;
- }
- public static void RemoveSuccessfulLoginWithPermissionsListener(Action listener)
- {
- if (_instance != null) //if it hasn't been destroyed
- {
- _instance.OnSuccessfulLoginWithPermissions -= listener;
- }
- }
- Action<bool> OnQueryHasLikedPageComplete;
- public static void AddQueryHasLikedPageCompleteListener(Action<bool> listener)
- {
- Instance.OnQueryHasLikedPageComplete += listener;
- }
- public static void RemoveQueryHasLikedPageCompleteListener(Action<bool> listener)
- {
- if (_instance != null) //if it hasn't been destroyed
- {
- _instance.OnQueryHasLikedPageComplete -= listener;
- }
- }
- Action OnLogout;
- public static void AddLogoutListener(Action listener)
- {
- Instance.OnLogout += listener;
- }
- public static void RemoveLogoutListener(Action listener)
- {
- if (_instance != null) //if it hasn't been destroyed
- {
- _instance.OnLogout -= listener;
- }
- }
- public ScreenBase progressIndicator;
- public CommonInfoDialog commonInfoDialog;
- public ScreenBase facebookLoginRequiredScreen;
- public const string LAST_SEEN_CHALLENGE_IDS_KEY = "LastSeenChallengeIds";
- const string HAS_LIKED_PAGE = "HasLikedPage";
- const float REQUESTS_MONITOR_INTERVAL_SECONDS = 10f;
- const float TIME_BETWEEN_CHALLENGE_RESULTS_IN_SECONDS = 120f;
- [HideInInspector]
- public ReceivedRequestsArgs lastReceivedRequests;
- ChallengeResult[] _loadedChallengeResults;
- public ChallengeResult[] LoadedChallengeResults { get { return _loadedChallengeResults; } }
- void RegisterListeners()
- {
- FaceBookRequester.instance.ReceivedRequest += HandleFaceBookRequesterinstanceReceivedRequest;
- //FacebookManager.reauthorizationFailedEvent += OnReauthFailed;
- //FacebookManager.sessionOpenedEvent += OnSessionOpened;
- //FacebookManager.reauthorizationSucceededEvent += OnReauthSucceeded;
- MessageCenter.AddReceivedRequestsListener(OnReceivedRequests);
- NotificationCenter.AddListener(OnGameStart, NotificationType.GameStart);
- NotificationCenter.AddListener(OnGameOver, NotificationType.GameOver);
- DebugViewManager.OnDebugView += OnDebugView;
- }
- string log;
- void HandleFaceBookRequesterinstanceReceivedRequest(RequestInfo[] requestInfo)
- {
- StringBuilder strb = new StringBuilder();
- AVDebug.Log("Request Length " + requestInfo.Length);
- foreach (RequestInfo r in requestInfo)
- {
- strb.AppendLine("************************************************");
- strb.AppendLine(string.Format("* Name: {0}", r.senderName));
- strb.AppendLine(string.Format("* Message: {0}", r.message));
- strb.AppendLine(string.Format("* Data: {0}", r.data));
- strb.AppendLine(string.Format("* Time Created: {0}", r.createdTime));
- strb.AppendLine("************************************************");
- }
- log = strb.ToString();
- AVDebug.Log(log);
-
- }
- void UnregisterListeners()
- {
- //FacebookManager.reauthorizationFailedEvent -= OnReauthFailed;
- //FacebookManager.sessionOpenedEvent -= OnSessionOpened;
- //FacebookManager.reauthorizationSucceededEvent -= OnReauthSucceeded;
- MessageCenter.RemoveReceivedRequestsListener(OnReceivedRequests);
- NotificationCenter.RemoveListener(OnGameStart, NotificationType.GameStart);
- NotificationCenter.RemoveListener(OnGameOver, NotificationType.GameOver);
- DebugViewManager.OnDebugView -= OnDebugView;
- }
- void OnDebugView()
- {
- if (GUILayout.Button("Send Dummy Challenge"))
- {
- string gameData = "";
- MessageCenter.Instance.SendChallenge(0, 1000, gameData, Localization.instance.Get("challenge.facebookRequest.title"), Localization.instance.Get("challenge.facebookRequest.message"), null);
- }
- }
- #if UNITY_WEBPLAYER && !ADMIN_BUILD
- void Start()
- {
- //force logging in, otherwise we would have invalid session (even if he already logged in, in the previous web session)
- LogIn();
- }
- #endif
- void OnSessionOpened()
- {
- AVDebug.Log("FacebookHelper OnSessionOpened");
- if (HasAcceptedPublishPermissions())
- {
- SocialManager.Instance.StartMonitoring(REQUESTS_MONITOR_INTERVAL_SECONDS);
- }
- }
- #if UNITY_EDITOR
- //THIS METHOD IS FOR FAKING IN THE EDITOR
- public bool IsLoggedIn()
- {
- if (!ConnectivityPollManager.HasInternet)
- {
- return false;
- }
- return PlayerPrefs.GetInt("IsFacebookLoggedIn", 0) == 1;
- }
- //THIS METHOD IS FOR FAKING IN THE EDITOR
- public void LogIn()
- {
- PlayerPrefs.SetInt("IsFacebookLoggedIn", 1);
- if (progressIndicator != null)
- {
- progressIndicator.Show();
- }
- StartCoroutine(DelayLogInCompleteCoroutine());
- }
- //THIS METHOD IS FOR FAKING IN THE EDITOR
- IEnumerator DelayLogInCompleteCoroutine()
- {
- yield return new WaitForSeconds(1);
- OnReauthSucceeded();
- }
- //THIS METHOD IS FOR FAKING IN THE EDITOR
- public void LogOut()
- {
- PlayerPrefs.SetInt("IsFacebookLoggedIn", 0);
- }
- //THIS METHOD IS FOR FAKING IN THE EDITOR
- public void QueryHasLikedPage()
- {
- //iCTS requirement: no Like Page
- if (OnQueryHasLikedPageComplete != null)
- {
- OnQueryHasLikedPageComplete(true);
- }
- /*
- if (!HasLikedPage())
- {
- StartCoroutine(DelayQueryHasLikedPageCompleteCoroutine());
- } else
- {
- if (OnQueryHasLikedPageComplete != null)
- {
- OnQueryHasLikedPageComplete(true);
- }
- }
- */
- }
- //THIS METHOD IS FOR FAKING IN THE EDITOR
- IEnumerator DelayQueryHasLikedPageCompleteCoroutine()
- {
- yield return new WaitForSeconds(1);
- bool hasAlreadyLikedPage = HasLikedPage();
- if (OnQueryHasLikedPageComplete != null)
- {
- OnQueryHasLikedPageComplete(hasAlreadyLikedPage);
- }
- }
- //THIS METHOD IS FOR FAKING IN THE EDITOR
- public void RequestLives()
- {
- if (WrapperFB.IsLoggedIn)
- {
- progressIndicator.Show();
- StartCoroutine(DelayedRequestLivesCoroutine());
- } else
- {
- ShowFacebookLoginRequired();
- }
- }
- //THIS METHOD IS FOR FAKING IN THE EDITOR
- IEnumerator DelayedRequestLivesCoroutine()
- {
- yield return new WaitForSeconds(1);
- progressIndicator.Hide();
- commonInfoDialog.SetTitleAndText("facebook.lifeRequest.success.title","facebook.lifeRequest.success.text");
- commonInfoDialog.Show();
- LivesManager.Instance.RechargeOneLife();
- PlayerPrefs.SetInt("Live", 1);
- PlayerPrefs.Save();
- }
- //THIS METHOD IS FOR FAKING IN THE EDITOR
- public void SendLife(RequestInfo request, Action<bool> onComplete)
- {
- progressIndicator.Show();
- StartCoroutine(DelayedGiveLivesCoroutine(onComplete));
- }
- //THIS METHOD IS FOR FAKING IN THE EDITOR
- IEnumerator DelayedGiveLivesCoroutine(Action<bool> onComplete)
- {
- yield return new WaitForSeconds(1);
- progressIndicator.Hide();
- commonInfoDialog.SetTitleAndText("facebook.lifeGiftRequest.success.title","facebook.lifeGiftRequest.success.text");
- commonInfoDialog.Show();
- onComplete(true);
- }
- //THIS METHOD IS FOR FAKING IN THE EDITOR
- public void AcceptLife(RequestInfo request, Action<bool> onComplete)
- {
- LivesManager.Instance.RechargeLife();
- onComplete(true);
-
- }
- #else
- public bool IsLoggedIn()
- {
- if (!ConnectivityPollManager.HasInternet)
- {
- return false;
- }
- //MenuManager._instance.LabelDebug.text = MenuManager._instance.LabelDebug.text + "HasAcceptedPublishPermissions()" +(HasAcceptedPublishPermissions())+"\n";
- //MenuManager._instance.LabelDebug.text = MenuManager._instance.LabelDebug.text + "SocialManager.Instance.isSessionValid" +(SocialManager.Instance.isSessionValid)+"\n";
- return SocialManager.Instance.isSessionValid ;//&& HasAcceptedPublishPermissions();
- }
- public void LogIn()
- {
- Debug.Log("LogIn");
- if (SocialManager.Instance.isSessionValid) //This covers the edge case that he accepted the read permissions but not , then removed the app from facebook, and then tries to login again, causing a 400 bad request
- {
- Debug.Log("LogOut");
- //MenuManager._instance.LabelDebug.text = MenuManager._instance.LabelDebug.text + "logout Login"+"\n";
- LogOut();
- }
-
- SocialManager.Instance.Login(OnLoginComplete);
- //MenuManager._instance.LabelDebug.text = MenuManager._instance.LabelDebug.text + " Login"+"\n";
- //progressIndicator.Show();
- }
- public void LogOut()
- {
- SocialManager.Instance.Logout();
- if (OnLogout != null)
- {
- AVDebug.Log("Calling OnLogout");
- OnLogout();
- //MenuManager._instance.LabelDebug.text = MenuManager._instance.LabelDebug.text + "OnLogout"+"\n";
- }
- PlayerPrefs.SetInt(HAS_LIKED_PAGE, 0);
- PlayerPrefs.Save();
- }
- public void QueryHasLikedPage()
- {
- //iCTS requirement: no Like Page
- if (OnQueryHasLikedPageComplete != null)
- {
- OnQueryHasLikedPageComplete(true);
- }
- /*
- bool hasAlreadyLikedPage = HasLikedPage();
- AVDebug.Log("Has already liked page " + hasAlreadyLikedPage);
- if (!hasAlreadyLikedPage)
- {
- AVDebug.Log("Querying for page like of "+GameConstants.LIKE_PAGE_ID);
- SocialManager.Instance.GetLikeStatus(GameConstants.LIKE_PAGE_ID, OnGetLikeStatusComplete);
- } else
- {
- AVDebug.Log("Firing OnQueryHasLikedPageComplete immediately with isLiked = true");
- //fire the event immediately
- if (OnQueryHasLikedPageComplete != null)
- {
- OnQueryHasLikedPageComplete(true);
- }
- }
- */
- }
- public void RequestLives()
- {
- if (WrapperFB.IsLoggedIn)
- {
- progressIndicator.Show();
- FB.Mobile.AppInvite(new Uri("https://fb.me/953733298039600"), callback: this.HandleResult);
-
- }
- else
- {
- ShowFacebookLoginRequired();
- }
- }
-
- public void SendLife(RequestInfo request, Action<bool> onComplete)
- {
- Logger.LogFlurryEvent("Player send a life");
- AVDebug.Log("Sending life to "+request.senderID);
- progressIndicator.Show();
- SocialManager.Instance.SendUserToUserRequest(request.senderID, Localization.instance.Get("facebook.lifeGiftRequest"), Localization.instance.Get("facebook.lifeGiftRequest"),"type=life", (isSuccessful,requests)=>
- {
- progressIndicator.Hide();
- if (isSuccessful)
- {
- MessageCenter.Instance.DeleteRequest(request.requestID, (isDeleteRequestSuccessful) =>
- {
- if (isDeleteRequestSuccessful)
- {
- commonInfoDialog.SetTitleAndText("facebook.lifeGiftRequest.success.title","facebook.lifeGiftRequest.success.text");
- lastReceivedRequests.lifeDemandRequests.Remove(request);
- } else
- {
- commonInfoDialog.SetTitleAndText("facebook.lifeGiftRequest.failed.title","facebook.lifeGiftRequest.failed.text");
- }
- if (onComplete != null)
- {
- onComplete(isDeleteRequestSuccessful);
- }
- });
- } else
- {
- commonInfoDialog.SetTitleAndText("facebook.lifeGiftRequest.failed.title","facebook.lifeGiftRequest.failed.text");
- if (onComplete != null)
- {
- onComplete(false);
- }
- }
- commonInfoDialog.Show();
- });
- }
- public void AcceptLife(RequestInfo request, Action<bool> onComplete)
- {
- progressIndicator.Show();
- MessageCenter.Instance.DeleteRequest(request.requestID, (isSuccessful) =>
- {
- progressIndicator.Hide();
- AVDebug.Log("Accept Life successful "+isSuccessful);
- if (isSuccessful)
- {
- Logger.LogFlurryEvent("Player accepted a life");
- LivesManager.Instance.RechargeLife();
- lastReceivedRequests.lifeRequests.Remove(request);
- } else
- {
- Logger.LogFlurryEvent("Player accept life failed");
- commonInfoDialog.SetTitleAndText("facebook.lifeAccept.failed.title","facebook.lifeAccept.failed.text");
- commonInfoDialog.Show();
- }
- if (onComplete != null)
- {
- onComplete(isSuccessful);
- }
- });
- }
- #endif
- public bool HasAcceptedPublishPermissions()
- {
- #if UNITY_EDITOR
-
- return true;
- #else
-
- /*if (FacebookAccess.getSessionPermissions() == null)
- {
- return false;
- }*/
- /*foreach (var VARIABLE in FacebookAccess.getSessionPermissions())
- {
- //MenuManager._instance.LabelDebug.text = MenuManager._instance.LabelDebug.text + "FacebookAccess.getSessionPermissions()1" + VARIABLE.ToString() + "\n";
-
- }*/
- /*//sDebug.Log (FacebookAccess.getSessionPermissions().Count);*/
- return true;//FacebookAccess.getSessionPermissions().Contains("publish_actions");
- #endif
- }
- /// <summary>
- /// We want to open the page to like in the facebook app, if the app is installed.
- /// If it was native XCode we could do something like here: http://stackoverflow.com/questions/8984468/how-to-open-facebook-page-in-facebook-app-in-iphone
- /// But the easiest solution (and also portable on Android) was to base it on time. If it didn't flip, then use safari, as explained here
- /// http://forum.unity3d.com/threads/143623-Open-facebook-app-instead-safari-iOS-C
- /// </summary>
- public void LikePage()
- {
- #if UNITY_EDITOR
- PlayerPrefs.SetInt(HAS_LIKED_PAGE, 1);
- PlayerPrefs.Save();
- QueryHasLikedPage();
- #else
- #if UNITY_WEBPLAYER
- StopCoroutine("QueryContinouslyForPageLikeCoroutine");
- StartCoroutine("QueryContinouslyForPageLikeCoroutine");
- #endif
- OpenFacebookPage(GameConstants.LIKE_PAGE_ID, GameConstants.PAGE_TO_LIKE);
- #endif
- }
- public void OpenFacebookPage(string pageID, string pageURL)
- {
- #if UNITY_IPHONE
- float startTime;
- startTime = Time.timeSinceLevelLoad;
- //open the facebook app
- Application.OpenURL("fb://profile/"+pageID);
- if (Time.timeSinceLevelLoad - startTime <= 1f)
- {
- //fail. Open safari.
- Application.OpenURL(pageURL);
- }
- #elif UNITY_WEBPLAYER
- Application.ExternalCall("OpenPage", pageURL);
- #else
- //Android screws up when trying to open up the facebook app
- Application.OpenURL(pageURL);
- #endif
- }
- #if UNITY_WEBPLAYER
- IEnumerator QueryContinouslyForPageLikeCoroutine()
- {
- while (true)
- {
- yield return new WaitForSeconds(3);
- if (HasLikedPage())
- {
- yield break;
- }
- QueryHasLikedPage();
- }
- }
- #endif
- public void Reset()
- {
- LogOut();
- PlayerPrefs.SetInt(HAS_LIKED_PAGE, 0);
- PlayerPrefs.Save();
- }
- public void ShowFacebookLoginRequired()
- {
- facebookLoginRequiredScreen.Show();
- }
- bool HasLikedPage()
- {
- //iCTS requirement: no Like Page
- return true;
- //return PlayerPrefs.GetInt(HAS_LIKED_PAGE, 0) == 1;
- }
- #region Challenges
- public void SendChallenge()
- {
- progressIndicator.Show();
- //For now we don't need to send anything special as game data
- string gameData = "";
- MessageCenter.Instance.SendChallenge(LevelsManager.Instance.CurrentLevelIndex, GameDataManager.Instance.Score, gameData, Localization.instance.Get("challenge.facebookRequest.title"), Localization.instance.Get("challenge.facebookRequest.message"), (isSuccessful) =>
- {
- progressIndicator.Hide();
- AVDebug.Log("Sent challenge: " + isSuccessful);
- if (isSuccessful)
- {
- commonInfoDialog.SetTitleAndText("challenge.requestSuccess.title", "challenge.requestSuccess.text");
- Logger.LogFlurryEvent("Challenge Sent");
- } else
- {
- commonInfoDialog.SetTitleAndText("challenge.requestFailed.title", "challenge.requestFailed.text");
- Logger.LogFlurryEvent("Challenge Sent Failed or Cancelled");
- }
- commonInfoDialog.Show();
- });
- }
- public void AcceptChallenge(ChallengeRequestUIData challengeRequest)
- {
- progressIndicator.Show();
- MessageCenter.Instance.AcceptChallenge(challengeRequest.requestInfo, (isAcceptChallengeSuccessful, challenge) =>
- {
- progressIndicator.Hide();
- if (isAcceptChallengeSuccessful)
- {
- SocialManager.Instance.UpdateIncomingRequests();
- NotificationCenter.Post(NotificationType.AcceptChallenge, challengeRequest);
- Logger.LogFlurryEvent("Challenge Accepted");
- } else
- {
- AVDebug.LogWarning("AcceptChallenge failed");
- Logger.LogFlurryEvent("Challenge Accepting Failed");
- commonInfoDialog.SetTitleAndText("challenge.acceptFailed.title", "challenge.acceptFailed.text");
- commonInfoDialog.Show();
- }
- });
- }
- public void DeclineChallenge(ChallengeRequestUIData challengeRequest, Action<bool> onComplete)
- {
- Logger.LogFlurryEvent("Challenge Declined");
- //This is decline, but in order to remove the challenge, we need to accept it
- MessageCenter.Instance.AcceptChallenge(challengeRequest.requestInfo, (isAcceptChallengeSuccessful, challenge) =>
- {
- if (isAcceptChallengeSuccessful)
- {
- string userId = SocialManager.Instance.userID;
- int score = 0; //Let's send a zero to close and forfeit this challenge
- GameDatabaseManager.Instance.ReportChallengeScore(userId, challengeRequest.challengeId, score, (isGameDatabaseReportScoreSuccessful) =>
- {
- if(isGameDatabaseReportScoreSuccessful)
- {
- SocialManager.Instance.ReportScore(score, (isSocialManagerReportScoreSuccessful) =>
- {
- if (!isSocialManagerReportScoreSuccessful)
- {
- AVDebug.LogWarning("ReportScore Failed");
- if (onComplete != null)
- {
- onComplete(isSocialManagerReportScoreSuccessful);
- }
- }
- });
- } else
- {
- AVDebug.LogWarning("ReportChallengeScore Failed");
- commonInfoDialog.SetTitleAndText("challenge.declineFailed.title", "challenge.declineFailed.text");
- commonInfoDialog.Show();
- if (onComplete != null)
- {
- onComplete(false);
- }
- }
- });
- } else
- {
- AVDebug.LogWarning("AcceptChallenge failed");
- commonInfoDialog.SetTitleAndText("challenge.declineFailed.title", "challenge.declineFailed.text");
- commonInfoDialog.Show();
- if (onComplete != null)
- {
- onComplete(false);
- }
- }
- });
- }
- public void SubmitChallengeScore(int challengeId)
- {
- string userId = SocialManager.Instance.userID;
- int score = GameDataManager.Instance.Score;
- if (LevelsManager.Instance.CurrentLevel.AreAllObjectivesMet())
- {
- GameDatabaseManager.Instance.ReportChallengeScore(userId, challengeId, score, (isGameDatabaseReportScoreSuccessful) =>
- {
- AVDebug.Log("isGameDatabaseReportScoreSuccessful " + (isGameDatabaseReportScoreSuccessful ? "Successful" : "Failed"));
- if(isGameDatabaseReportScoreSuccessful)
- {
- SocialManager.Instance.ReportScore(score, (isSocialManagerReportScoreSuccessful) =>
- {
- AVDebug.Log("isSocialManagerReportScoreSuccessful " + (isSocialManagerReportScoreSuccessful ? "Successful" : "Failed"));
- });
- } else
- {
- commonInfoDialog.SetTitleAndText("challenge.submitScoreFailed.title", "challenge.submitScoreFailed.text");
- commonInfoDialog.Show();
- }
- });
- } else
- {
- //Even if not all the objectives were met... send social network notifications
- SocialManager.Instance.ReportScore(score, (isSocialManagerReportScoreSuccessful) =>
- {
- AVDebug.Log("isSocialManagerReportScoreSuccessful " + (isSocialManagerReportScoreSuccessful ? "Successful" : "Failed"));
- });
- }
- }
- public void GetChallengeResultsFromServer()
- {
- AVDebug.Log("Getting challenge results from server");
- string userId = SocialManager.Instance.userID;
- GameDatabaseManager.Instance.LoadChallengeResults(userId, 5, (isSuccessful, challengeResults) =>
- {
- if (isSuccessful)
- {
- AVDebug.Log("Loaded challenge results");
- _loadedChallengeResults = challengeResults;
- } else
- {
- AVDebug.Log("Failed loading challenge results");
- }
- if (isSuccessful && challengeResults != null)
- {
- //Finding how many are really new
- int[] lastSeenChallengeIds = GetLastSeenChallengeIds();
- int newResults = 0;
- foreach (ChallengeResult result in challengeResults)
- {
- if (!result.WasChallengeDeclined() &&
- IsChallengeResultNew(result, lastSeenChallengeIds))
- {
- ++newResults;
- }
- }
-
- //Notify of the count of new challenge results
- NotificationCenter.Post(NotificationType.ReceivedNewChallengeResults, newResults);
- }
- });
- }
- int[] GetLastSeenChallengeIds()
- {
- string lastChallengeIdsString = PlayerPrefs.GetString(LAST_SEEN_CHALLENGE_IDS_KEY, "");
- string[] lastChallengeIdsAsStrings = lastChallengeIdsString.Split(',');
- int[] lastChallengeIds = new int[lastChallengeIdsAsStrings.Length];
- for (int i = 0; i < lastChallengeIds.Length; i++)
- {
- int.TryParse(lastChallengeIdsAsStrings[i], out lastChallengeIds[i]);
- }
- return lastChallengeIds;
- }
- bool IsChallengeResultNew(ChallengeResult result, int[] lastChallengeIds)
- {
- foreach (int id in lastChallengeIds)
- {
- if (id == result.challenge.id)
- {
- return false;
- }
- }
- return true;
- }
- #endregion
- void OnLoginComplete(bool isSuccessful, string errorReason)
- {
- if (isSuccessful)
- {
- #if UNITY_ANDROID
- StartCoroutine(DelayGetFacebookPermissions());
- progressIndicator.Hide();
- #else
- //SocialManager.Instance.GetPublishPermissions();
- #endif
- } else
- {
- AVDebug.Log("Log in failed! "+errorReason);
- progressIndicator.Hide();
- #if UNITY_IPHONE
- //this only occurs on iPhone when they use facebook Single Sign-on and have clicked on Don't allow in a previous session
- if (errorReason == "com.facebook.sdk:SystemLoginDisallowedWithoutError")
- {
- commonInfoDialog.SetTitleAndText("facebook.login.failed.title", "facebook.login.failedCheckSingleSignonSettings.text");
- } else
- #endif
- {
- commonInfoDialog.SetTitleAndText("facebook.login.failed.title", "facebook.login.failed.text");
- }
- commonInfoDialog.Show();
- }
- }
- void OnReauthFailed(P31Error message)
- {
- //MenuManager._instance.LabelDebug.text = MenuManager._instance.LabelDebug.text + "OnReauthFailed)" + "\n";
- progressIndicator.Hide();
- AVDebug.LogWarning("Facebook Reauth Failed ... Logging out: "+message);
- LogOut();
- commonInfoDialog.SetTitleAndText("facebook.login.failed.title", "facebook.login.failedAcceptingPublishPermissions.text");
- commonInfoDialog.Show();
- }
- void OnReauthSucceeded()
- {
- if(progressIndicator!= null)
- progressIndicator.Hide();
- AVDebug.Log("Facebook Reauth Succeeded: ");
- if (HasAcceptedPublishPermissions())
- {
- if (OnSuccessfulLoginWithPermissions != null)
- {
- OnSuccessfulLoginWithPermissions();
- }
- SocialManager.Instance.StartMonitoring( REQUESTS_MONITOR_INTERVAL_SECONDS );
- QueryHasLikedPage();
- } else
- {
- commonInfoDialog.SetTitleAndText("facebook.login.failed.title", "facebook.login.failedAcceptingPublishPermissions.text");
- commonInfoDialog.Show();
- LogOut(); //if he doesn't accept permissions, just log him out
- }
- }
- void OnGetLikeStatusComplete(bool isLiked)
- {
- AVDebug.Log("OnGetLikeStatusComplete "+isLiked);
- PlayerPrefs.SetInt(HAS_LIKED_PAGE, isLiked ? 1 : 0);
- PlayerPrefs.Save();
- //Submit any score after he has liked the page
- if (isLiked)
- {
- Logger.LogFlurryEvent("Player has liked facebook page");
- }
- if (OnQueryHasLikedPageComplete != null)
- {
- OnQueryHasLikedPageComplete(isLiked);
- }
- }
- /// <summary>
- /// Due to Android probs, we have to wait a bit due to some app switching problems
- /// </summary>
- IEnumerator DelayGetFacebookPermissions()
- {
- yield return new WaitForSeconds(0.5f);
- SocialManager.Instance.GetPublishPermissions();
- }
- void OnReceivedRequests(ReceivedRequestsArgs requests)
- {
- lastReceivedRequests = requests;
- //On receiving requests, lets ask for any results
- GetChallengeResultsFromServer();
- }
- void OnGameStart(Notification note)
- {
- if (SocialManager.Instance.isSessionValid)
- {
- SocialManager.Instance.StopMonitoring();
- }
- }
- void OnGameOver(Notification note)
- {
- if (SocialManager.Instance.isSessionValid && HasAcceptedPublishPermissions())
- {
- SocialManager.Instance.StartMonitoring(REQUESTS_MONITOR_INTERVAL_SECONDS);
- }
- //only submit score if he has achieved all objectives
- if (!LevelsManager.Instance.CurrentLevel.AreAllObjectivesMet())
- {
- return;
- }
- progressIndicator.Show();
- ServerTime.Instance.RetrieveServerTime( (serverTime) =>
- {
- progressIndicator.Hide();
- if (serverTime != -1)
- {
- TimeManager.Instance.EndServerTime = serverTime;
- #if DEBUG
- long realPlayTime = TimeManager.Instance.EndServerTime - TimeManager.Instance.StartServerTime;
- Debug.Log("Real Play Time : "+realPlayTime);
- #endif
- ContinueToSubmitScore();
- } else
- {
- //show error
- commonInfoDialog.SetTitleAndText("serverError.title", "serverError.text");
- commonInfoDialog.Show();
- }
- });
- }
- void Test()
- {
- //Submit score to game database and facebook
- int score = GameDataManager.Instance.Score;
- string replayData = RecordingManager.Instance.GetReplayData();
- SubmitScore(LevelsManager.Instance.CurrentLevelIndex, 100, replayData);
- }
- void ContinueToSubmitScore()
- {
- //Submit score to game database and facebook
- int score = GameDataManager.Instance.Score;
- string replayData = RecordingManager.Instance.GetReplayData();
- SubmitScore(LevelsManager.Instance.CurrentLevelIndex, score, replayData);
- }
- void SubmitScore(int levelIndex, int score, string replayData)
- {
- if (ConnectivityPollManager.HasInternet &&
- HasLikedPage() &&
- !string.IsNullOrEmpty(SocialManager.Instance.userID))
- {
-
- SocialManager.Instance.userID = PlayerPrefs.GetString("FB_ID");
- AVDebug.Log("Reporting Score for level "+levelIndex+" with score of " + score + " for user "+SocialManager.Instance.userID);
- GameDatabaseManager.Instance.ReportScore(SocialManager.Instance.userID, score, levelIndex.ToString(), replayData, (isGameDatabaseScoreSubmitSuccessful) =>
- {
- Debug.Log("isGameDatabaseScoreSubmitSuccessful "+isGameDatabaseScoreSubmitSuccessful);
- Debug.Log(levelIndex);
- if (isGameDatabaseScoreSubmitSuccessful)
- {
- AVDebug.Log("Reporting score on facebook");
- SocialManager.Instance.ReportScore(score, (isSocialManagerScoreSubmitSuccessful) =>
- {
- //We don't care much if it wasn't successful on posting to facebook, since competition highscore list is on ourservers.
- AVDebug.Log("isSocialManagerScoreSubmitSuccessful " +isSocialManagerScoreSubmitSuccessful);
- });
- } else
- {
- AVDebug.LogWarning("Failed submitting score...");
- commonInfoDialog.SetTitleAndText("scoreSubmitError.title","scoreSubmitError.text");
- commonInfoDialog.Show();
- }
- });
- } else
- {
- AVDebug.Log("Player has not liked page, logged in to facebook or isOffline...");
- }
- }
- private void HandleResult(IResult result)
- {
- //SocialManager.Instance.SendUserToUserRequest(Localization.instance.Get("facebook.lifeRequest.title"), Localization.instance.Get("facebook.lifeRequest"), "type=lifeDemand", (isSuccessful, requests) =>
- {
- progressIndicator.Hide();
- if (!string.IsNullOrEmpty(result.RawResult))
- {
- Logger.LogFlurryEvent("Player request lives", "count", result.RawResult.Length.ToString());
- commonInfoDialog.SetTitleAndText("facebook.lifeRequest.success.title", "facebook.lifeRequest.success.text");
- /* foreach (string r in requests.recipientIDs)
- {
- AVDebug.Log("Sent life demand " + r);
- }*/
- Debug.Log("Sendlife");
- LivesManager.Instance.RechargeOneLife();
- PlayerPrefs.SetInt("Live", 1);
- PlayerPrefs.Save();
- }
- else
- {
- Debug.Log("FailedLife");
- Logger.LogFlurryEvent("Player request lives failed or cancelled");
- commonInfoDialog.SetTitleAndText("facebook.lifeRequest.failed.title", "facebook.lifeRequest.failed.text");
- }
- commonInfoDialog.Show();
- }//);
- }
- void Update()
- {
- if (Input.GetKeyDown(KeyCode.A))
- {
- Test();
- }
- }
- }
|