FacebookHelper.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. using System.Text;
  2. using UnityEngine;
  3. using System.Collections;
  4. using System;
  5. using System.Linq;
  6. using Facebook.Unity;
  7. using Prime31;
  8. using ICTS.Localization;
  9. #if UNITY_ANDROID
  10. //using FacebookAccess = Prime31.FacebookAndroid;
  11. #elif UNITY_IPHONE
  12. //using FacebookAccess = Prime31.FacebookBinding;
  13. #elif UNITY_WEBPLAYER
  14. using FacebookAccess = FacebookWeb;
  15. #endif
  16. public class FacebookHelper : MonoBehaviour
  17. {
  18. #region Unity Singleton
  19. private static FacebookHelper _instance;
  20. public static FacebookHelper Instance
  21. {
  22. get
  23. {
  24. if (_instance == null)
  25. {
  26. _instance = FindObjectOfType(typeof(FacebookHelper)) as FacebookHelper;
  27. if (_instance == null)
  28. {
  29. 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));
  30. }
  31. }
  32. return _instance;
  33. }
  34. }
  35. void Awake()
  36. {
  37. if (_instance != null && _instance != this)
  38. {
  39. AVDebug.LogWarning(string.Format("{0} Instance already exists on another gameObject. Destroying this gameObject {1}", this.GetType().Name, gameObject.name));
  40. Destroy(gameObject);
  41. return;
  42. }
  43. _instance = this;
  44. DontDestroyOnLoad(gameObject);
  45. RegisterListeners();
  46. }
  47. void OnDestroy()
  48. {
  49. //Reset any actions
  50. OnSuccessfulLoginWithPermissions = null;
  51. OnQueryHasLikedPageComplete = null;
  52. OnLogout = null;
  53. UnregisterListeners();
  54. }
  55. #endregion
  56. Action OnSuccessfulLoginWithPermissions;
  57. public static void AddSuccessfulLoginWithPermissionsListener(Action listener)
  58. {
  59. Instance.OnSuccessfulLoginWithPermissions += listener;
  60. }
  61. public static void RemoveSuccessfulLoginWithPermissionsListener(Action listener)
  62. {
  63. if (_instance != null) //if it hasn't been destroyed
  64. {
  65. _instance.OnSuccessfulLoginWithPermissions -= listener;
  66. }
  67. }
  68. Action<bool> OnQueryHasLikedPageComplete;
  69. public static void AddQueryHasLikedPageCompleteListener(Action<bool> listener)
  70. {
  71. Instance.OnQueryHasLikedPageComplete += listener;
  72. }
  73. public static void RemoveQueryHasLikedPageCompleteListener(Action<bool> listener)
  74. {
  75. if (_instance != null) //if it hasn't been destroyed
  76. {
  77. _instance.OnQueryHasLikedPageComplete -= listener;
  78. }
  79. }
  80. Action OnLogout;
  81. public static void AddLogoutListener(Action listener)
  82. {
  83. Instance.OnLogout += listener;
  84. }
  85. public static void RemoveLogoutListener(Action listener)
  86. {
  87. if (_instance != null) //if it hasn't been destroyed
  88. {
  89. _instance.OnLogout -= listener;
  90. }
  91. }
  92. public ScreenBase progressIndicator;
  93. public CommonInfoDialog commonInfoDialog;
  94. public ScreenBase facebookLoginRequiredScreen;
  95. public const string LAST_SEEN_CHALLENGE_IDS_KEY = "LastSeenChallengeIds";
  96. const string HAS_LIKED_PAGE = "HasLikedPage";
  97. const float REQUESTS_MONITOR_INTERVAL_SECONDS = 10f;
  98. const float TIME_BETWEEN_CHALLENGE_RESULTS_IN_SECONDS = 120f;
  99. [HideInInspector]
  100. public ReceivedRequestsArgs lastReceivedRequests;
  101. ChallengeResult[] _loadedChallengeResults;
  102. public ChallengeResult[] LoadedChallengeResults { get { return _loadedChallengeResults; } }
  103. void RegisterListeners()
  104. {
  105. FaceBookRequester.instance.ReceivedRequest += HandleFaceBookRequesterinstanceReceivedRequest;
  106. //FacebookManager.reauthorizationFailedEvent += OnReauthFailed;
  107. //FacebookManager.sessionOpenedEvent += OnSessionOpened;
  108. //FacebookManager.reauthorizationSucceededEvent += OnReauthSucceeded;
  109. MessageCenter.AddReceivedRequestsListener(OnReceivedRequests);
  110. NotificationCenter.AddListener(OnGameStart, NotificationType.GameStart);
  111. NotificationCenter.AddListener(OnGameOver, NotificationType.GameOver);
  112. DebugViewManager.OnDebugView += OnDebugView;
  113. }
  114. string log;
  115. void HandleFaceBookRequesterinstanceReceivedRequest(RequestInfo[] requestInfo)
  116. {
  117. StringBuilder strb = new StringBuilder();
  118. AVDebug.Log("Request Length " + requestInfo.Length);
  119. foreach (RequestInfo r in requestInfo)
  120. {
  121. strb.AppendLine("************************************************");
  122. strb.AppendLine(string.Format("* Name: {0}", r.senderName));
  123. strb.AppendLine(string.Format("* Message: {0}", r.message));
  124. strb.AppendLine(string.Format("* Data: {0}", r.data));
  125. strb.AppendLine(string.Format("* Time Created: {0}", r.createdTime));
  126. strb.AppendLine("************************************************");
  127. }
  128. log = strb.ToString();
  129. AVDebug.Log(log);
  130. }
  131. void UnregisterListeners()
  132. {
  133. //FacebookManager.reauthorizationFailedEvent -= OnReauthFailed;
  134. //FacebookManager.sessionOpenedEvent -= OnSessionOpened;
  135. //FacebookManager.reauthorizationSucceededEvent -= OnReauthSucceeded;
  136. MessageCenter.RemoveReceivedRequestsListener(OnReceivedRequests);
  137. NotificationCenter.RemoveListener(OnGameStart, NotificationType.GameStart);
  138. NotificationCenter.RemoveListener(OnGameOver, NotificationType.GameOver);
  139. DebugViewManager.OnDebugView -= OnDebugView;
  140. }
  141. void OnDebugView()
  142. {
  143. if (GUILayout.Button("Send Dummy Challenge"))
  144. {
  145. string gameData = "";
  146. MessageCenter.Instance.SendChallenge(0, 1000, gameData, Localization.instance.Get("challenge.facebookRequest.title"), Localization.instance.Get("challenge.facebookRequest.message"), null);
  147. }
  148. }
  149. #if UNITY_WEBPLAYER && !ADMIN_BUILD
  150. void Start()
  151. {
  152. //force logging in, otherwise we would have invalid session (even if he already logged in, in the previous web session)
  153. LogIn();
  154. }
  155. #endif
  156. void OnSessionOpened()
  157. {
  158. AVDebug.Log("FacebookHelper OnSessionOpened");
  159. if (HasAcceptedPublishPermissions())
  160. {
  161. SocialManager.Instance.StartMonitoring(REQUESTS_MONITOR_INTERVAL_SECONDS);
  162. }
  163. }
  164. #if UNITY_EDITOR
  165. //THIS METHOD IS FOR FAKING IN THE EDITOR
  166. public bool IsLoggedIn()
  167. {
  168. if (!ConnectivityPollManager.HasInternet)
  169. {
  170. Debug.Log("Not internet");
  171. return false;
  172. }
  173. return PlayerPrefs.GetInt("IsFacebookLoggedIn", 0) == 1;
  174. }
  175. //THIS METHOD IS FOR FAKING IN THE EDITOR
  176. public void LogIn()
  177. {
  178. PlayerPrefs.SetInt("IsFacebookLoggedIn", 1);
  179. if (progressIndicator != null)
  180. {
  181. progressIndicator.Show();
  182. }
  183. PlayerPrefs.Save();
  184. StartCoroutine(DelayLogInCompleteCoroutine());
  185. }
  186. //THIS METHOD IS FOR FAKING IN THE EDITOR
  187. IEnumerator DelayLogInCompleteCoroutine()
  188. {
  189. yield return new WaitForSeconds(1);
  190. OnReauthSucceeded();
  191. }
  192. //THIS METHOD IS FOR FAKING IN THE EDITOR
  193. public void LogOut()
  194. {
  195. PlayerPrefs.SetInt("IsFacebookLoggedIn", 0);
  196. }
  197. //THIS METHOD IS FOR FAKING IN THE EDITOR
  198. public void QueryHasLikedPage()
  199. {
  200. //iCTS requirement: no Like Page
  201. if (OnQueryHasLikedPageComplete != null)
  202. {
  203. OnQueryHasLikedPageComplete(true);
  204. }
  205. /*
  206. if (!HasLikedPage())
  207. {
  208. StartCoroutine(DelayQueryHasLikedPageCompleteCoroutine());
  209. } else
  210. {
  211. if (OnQueryHasLikedPageComplete != null)
  212. {
  213. OnQueryHasLikedPageComplete(true);
  214. }
  215. }
  216. */
  217. }
  218. //THIS METHOD IS FOR FAKING IN THE EDITOR
  219. IEnumerator DelayQueryHasLikedPageCompleteCoroutine()
  220. {
  221. yield return new WaitForSeconds(1);
  222. bool hasAlreadyLikedPage = HasLikedPage();
  223. if (OnQueryHasLikedPageComplete != null)
  224. {
  225. OnQueryHasLikedPageComplete(hasAlreadyLikedPage);
  226. }
  227. }
  228. //THIS METHOD IS FOR FAKING IN THE EDITOR
  229. public void RequestLives()
  230. {
  231. if (WrapperFB.IsLoggedIn)
  232. {
  233. progressIndicator.Show();
  234. StartCoroutine(DelayedRequestLivesCoroutine());
  235. } else
  236. {
  237. ShowFacebookLoginRequired();
  238. }
  239. }
  240. //THIS METHOD IS FOR FAKING IN THE EDITOR
  241. IEnumerator DelayedRequestLivesCoroutine()
  242. {
  243. yield return new WaitForSeconds(1);
  244. progressIndicator.Hide();
  245. commonInfoDialog.SetTitleAndText("facebook.lifeRequest.success.title","facebook.lifeRequest.success.text");
  246. commonInfoDialog.Show();
  247. LivesManager.Instance.RechargeOneLife();
  248. PlayerPrefs.SetInt("Live", 1);
  249. PlayerPrefs.Save();
  250. }
  251. //THIS METHOD IS FOR FAKING IN THE EDITOR
  252. public void SendLife(RequestInfo request, Action<bool> onComplete)
  253. {
  254. progressIndicator.Show();
  255. StartCoroutine(DelayedGiveLivesCoroutine(onComplete));
  256. }
  257. //THIS METHOD IS FOR FAKING IN THE EDITOR
  258. IEnumerator DelayedGiveLivesCoroutine(Action<bool> onComplete)
  259. {
  260. yield return new WaitForSeconds(1);
  261. progressIndicator.Hide();
  262. commonInfoDialog.SetTitleAndText("facebook.lifeGiftRequest.success.title","facebook.lifeGiftRequest.success.text");
  263. commonInfoDialog.Show();
  264. onComplete(true);
  265. }
  266. //THIS METHOD IS FOR FAKING IN THE EDITOR
  267. public void AcceptLife(RequestInfo request, Action<bool> onComplete)
  268. {
  269. LivesManager.Instance.RechargeLife();
  270. onComplete(true);
  271. }
  272. #else
  273. public bool IsLoggedIn()
  274. {
  275. if (!ConnectivityPollManager.HasInternet)
  276. {
  277. return false;
  278. }
  279. //MenuManager._instance.LabelDebug.text = MenuManager._instance.LabelDebug.text + "HasAcceptedPublishPermissions()" +(HasAcceptedPublishPermissions())+"\n";
  280. //MenuManager._instance.LabelDebug.text = MenuManager._instance.LabelDebug.text + "SocialManager.Instance.isSessionValid" +(SocialManager.Instance.isSessionValid)+"\n";
  281. return SocialManager.Instance.isSessionValid ;//&& HasAcceptedPublishPermissions();
  282. }
  283. public void LogIn()
  284. {
  285. Debug.Log("LogIn");
  286. 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
  287. {
  288. Debug.Log("LogOut");
  289. //MenuManager._instance.LabelDebug.text = MenuManager._instance.LabelDebug.text + "logout Login"+"\n";
  290. LogOut();
  291. }
  292. SocialManager.Instance.Login(OnLoginComplete);
  293. //MenuManager._instance.LabelDebug.text = MenuManager._instance.LabelDebug.text + " Login"+"\n";
  294. //progressIndicator.Show();
  295. }
  296. public void LogOut()
  297. {
  298. SocialManager.Instance.Logout();
  299. if (OnLogout != null)
  300. {
  301. AVDebug.Log("Calling OnLogout");
  302. OnLogout();
  303. //MenuManager._instance.LabelDebug.text = MenuManager._instance.LabelDebug.text + "OnLogout"+"\n";
  304. }
  305. PlayerPrefs.SetInt(HAS_LIKED_PAGE, 0);
  306. PlayerPrefs.Save();
  307. }
  308. public void QueryHasLikedPage()
  309. {
  310. //iCTS requirement: no Like Page
  311. if (OnQueryHasLikedPageComplete != null)
  312. {
  313. OnQueryHasLikedPageComplete(true);
  314. }
  315. /*
  316. bool hasAlreadyLikedPage = HasLikedPage();
  317. AVDebug.Log("Has already liked page " + hasAlreadyLikedPage);
  318. if (!hasAlreadyLikedPage)
  319. {
  320. AVDebug.Log("Querying for page like of "+GameConstants.LIKE_PAGE_ID);
  321. SocialManager.Instance.GetLikeStatus(GameConstants.LIKE_PAGE_ID, OnGetLikeStatusComplete);
  322. } else
  323. {
  324. AVDebug.Log("Firing OnQueryHasLikedPageComplete immediately with isLiked = true");
  325. //fire the event immediately
  326. if (OnQueryHasLikedPageComplete != null)
  327. {
  328. OnQueryHasLikedPageComplete(true);
  329. }
  330. }
  331. */
  332. }
  333. public void RequestLives()
  334. {
  335. if (WrapperFB.IsLoggedIn)
  336. {
  337. progressIndicator.Show();
  338. //FB.Mobile.AppInvite(new Uri("https://fb.me/953733298039600"), callback: this.HandleResult);
  339. }
  340. else
  341. {
  342. ShowFacebookLoginRequired();
  343. }
  344. }
  345. public void SendLife(RequestInfo request, Action<bool> onComplete)
  346. {
  347. Logger.LogFlurryEvent("Player send a life");
  348. AVDebug.Log("Sending life to "+request.senderID);
  349. progressIndicator.Show();
  350. SocialManager.Instance.SendUserToUserRequest(request.senderID, Localization.instance.Get("facebook.lifeGiftRequest"), Localization.instance.Get("facebook.lifeGiftRequest"),"type=life", (isSuccessful,requests)=>
  351. {
  352. progressIndicator.Hide();
  353. if (isSuccessful)
  354. {
  355. MessageCenter.Instance.DeleteRequest(request.requestID, (isDeleteRequestSuccessful) =>
  356. {
  357. if (isDeleteRequestSuccessful)
  358. {
  359. commonInfoDialog.SetTitleAndText("facebook.lifeGiftRequest.success.title","facebook.lifeGiftRequest.success.text");
  360. lastReceivedRequests.lifeDemandRequests.Remove(request);
  361. } else
  362. {
  363. commonInfoDialog.SetTitleAndText("facebook.lifeGiftRequest.failed.title","facebook.lifeGiftRequest.failed.text");
  364. }
  365. if (onComplete != null)
  366. {
  367. onComplete(isDeleteRequestSuccessful);
  368. }
  369. });
  370. } else
  371. {
  372. commonInfoDialog.SetTitleAndText("facebook.lifeGiftRequest.failed.title","facebook.lifeGiftRequest.failed.text");
  373. if (onComplete != null)
  374. {
  375. onComplete(false);
  376. }
  377. }
  378. commonInfoDialog.Show();
  379. });
  380. }
  381. public void AcceptLife(RequestInfo request, Action<bool> onComplete)
  382. {
  383. progressIndicator.Show();
  384. MessageCenter.Instance.DeleteRequest(request.requestID, (isSuccessful) =>
  385. {
  386. progressIndicator.Hide();
  387. AVDebug.Log("Accept Life successful "+isSuccessful);
  388. if (isSuccessful)
  389. {
  390. Logger.LogFlurryEvent("Player accepted a life");
  391. LivesManager.Instance.RechargeLife();
  392. lastReceivedRequests.lifeRequests.Remove(request);
  393. } else
  394. {
  395. Logger.LogFlurryEvent("Player accept life failed");
  396. commonInfoDialog.SetTitleAndText("facebook.lifeAccept.failed.title","facebook.lifeAccept.failed.text");
  397. commonInfoDialog.Show();
  398. }
  399. if (onComplete != null)
  400. {
  401. onComplete(isSuccessful);
  402. }
  403. });
  404. }
  405. #endif
  406. public bool HasAcceptedPublishPermissions()
  407. {
  408. #if UNITY_EDITOR
  409. return true;
  410. #else
  411. /*if (FacebookAccess.getSessionPermissions() == null)
  412. {
  413. return false;
  414. }*/
  415. /*foreach (var VARIABLE in FacebookAccess.getSessionPermissions())
  416. {
  417. //MenuManager._instance.LabelDebug.text = MenuManager._instance.LabelDebug.text + "FacebookAccess.getSessionPermissions()1" + VARIABLE.ToString() + "\n";
  418. }*/
  419. /*//sDebug.Log (FacebookAccess.getSessionPermissions().Count);*/
  420. return true;//FacebookAccess.getSessionPermissions().Contains("publish_actions");
  421. #endif
  422. }
  423. /// <summary>
  424. /// We want to open the page to like in the facebook app, if the app is installed.
  425. /// 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
  426. /// 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
  427. /// http://forum.unity3d.com/threads/143623-Open-facebook-app-instead-safari-iOS-C
  428. /// </summary>
  429. public void LikePage()
  430. {
  431. #if UNITY_EDITOR
  432. PlayerPrefs.SetInt(HAS_LIKED_PAGE, 1);
  433. PlayerPrefs.Save();
  434. QueryHasLikedPage();
  435. #else
  436. #if UNITY_WEBPLAYER
  437. StopCoroutine("QueryContinouslyForPageLikeCoroutine");
  438. StartCoroutine("QueryContinouslyForPageLikeCoroutine");
  439. #endif
  440. OpenFacebookPage(GameConstants.LIKE_PAGE_ID, GameConstants.PAGE_TO_LIKE);
  441. #endif
  442. }
  443. public void OpenFacebookPage(string pageID, string pageURL)
  444. {
  445. #if UNITY_IPHONE
  446. float startTime;
  447. startTime = Time.timeSinceLevelLoad;
  448. //open the facebook app
  449. Application.OpenURL("fb://profile/"+pageID);
  450. if (Time.timeSinceLevelLoad - startTime <= 1f)
  451. {
  452. //fail. Open safari.
  453. Application.OpenURL(pageURL);
  454. }
  455. #elif UNITY_WEBPLAYER
  456. Application.ExternalCall("OpenPage", pageURL);
  457. #else
  458. //Android screws up when trying to open up the facebook app
  459. Application.OpenURL(pageURL);
  460. #endif
  461. }
  462. #if UNITY_WEBPLAYER
  463. IEnumerator QueryContinouslyForPageLikeCoroutine()
  464. {
  465. while (true)
  466. {
  467. yield return new WaitForSeconds(3);
  468. if (HasLikedPage())
  469. {
  470. yield break;
  471. }
  472. QueryHasLikedPage();
  473. }
  474. }
  475. #endif
  476. public void Reset()
  477. {
  478. LogOut();
  479. PlayerPrefs.SetInt(HAS_LIKED_PAGE, 0);
  480. PlayerPrefs.Save();
  481. }
  482. public void ShowFacebookLoginRequired()
  483. {
  484. Debug.Log("SHOW DIIALOG NO LOGIN");
  485. facebookLoginRequiredScreen.Show();
  486. }
  487. bool HasLikedPage()
  488. {
  489. //iCTS requirement: no Like Page
  490. return true;
  491. //return PlayerPrefs.GetInt(HAS_LIKED_PAGE, 0) == 1;
  492. }
  493. #region Challenges
  494. public void SendChallenge()
  495. {
  496. progressIndicator.Show();
  497. //For now we don't need to send anything special as game data
  498. string gameData = "";
  499. MessageCenter.Instance.SendChallenge(LevelsManager.Instance.CurrentLevelIndex, GameDataManager.Instance.Score, gameData, Localization.instance.Get("challenge.facebookRequest.title"), Localization.instance.Get("challenge.facebookRequest.message"), (isSuccessful) =>
  500. {
  501. progressIndicator.Hide();
  502. AVDebug.Log("Sent challenge: " + isSuccessful);
  503. if (isSuccessful)
  504. {
  505. commonInfoDialog.SetTitleAndText("challenge.requestSuccess.title", "challenge.requestSuccess.text");
  506. Logger.LogFlurryEvent("Challenge Sent");
  507. } else
  508. {
  509. commonInfoDialog.SetTitleAndText("challenge.requestFailed.title", "challenge.requestFailed.text");
  510. Logger.LogFlurryEvent("Challenge Sent Failed or Cancelled");
  511. }
  512. commonInfoDialog.Show();
  513. });
  514. }
  515. public void AcceptChallenge(ChallengeRequestUIData challengeRequest)
  516. {
  517. progressIndicator.Show();
  518. MessageCenter.Instance.AcceptChallenge(challengeRequest.requestInfo, (isAcceptChallengeSuccessful, challenge) =>
  519. {
  520. progressIndicator.Hide();
  521. if (isAcceptChallengeSuccessful)
  522. {
  523. SocialManager.Instance.UpdateIncomingRequests();
  524. NotificationCenter.Post(NotificationType.AcceptChallenge, challengeRequest);
  525. Logger.LogFlurryEvent("Challenge Accepted");
  526. } else
  527. {
  528. AVDebug.LogWarning("AcceptChallenge failed");
  529. Logger.LogFlurryEvent("Challenge Accepting Failed");
  530. commonInfoDialog.SetTitleAndText("challenge.acceptFailed.title", "challenge.acceptFailed.text");
  531. commonInfoDialog.Show();
  532. }
  533. });
  534. }
  535. public void DeclineChallenge(ChallengeRequestUIData challengeRequest, Action<bool> onComplete)
  536. {
  537. Logger.LogFlurryEvent("Challenge Declined");
  538. //This is decline, but in order to remove the challenge, we need to accept it
  539. MessageCenter.Instance.AcceptChallenge(challengeRequest.requestInfo, (isAcceptChallengeSuccessful, challenge) =>
  540. {
  541. if (isAcceptChallengeSuccessful)
  542. {
  543. string userId = SocialManager.Instance.userID;
  544. int score = 0; //Let's send a zero to close and forfeit this challenge
  545. GameDatabaseManager.Instance.ReportChallengeScore(userId, challengeRequest.challengeId, score, (isGameDatabaseReportScoreSuccessful) =>
  546. {
  547. if(isGameDatabaseReportScoreSuccessful)
  548. {
  549. SocialManager.Instance.ReportScore(score, (isSocialManagerReportScoreSuccessful) =>
  550. {
  551. if (!isSocialManagerReportScoreSuccessful)
  552. {
  553. AVDebug.LogWarning("ReportScore Failed");
  554. if (onComplete != null)
  555. {
  556. onComplete(isSocialManagerReportScoreSuccessful);
  557. }
  558. }
  559. });
  560. } else
  561. {
  562. AVDebug.LogWarning("ReportChallengeScore Failed");
  563. commonInfoDialog.SetTitleAndText("challenge.declineFailed.title", "challenge.declineFailed.text");
  564. commonInfoDialog.Show();
  565. if (onComplete != null)
  566. {
  567. onComplete(false);
  568. }
  569. }
  570. });
  571. } else
  572. {
  573. AVDebug.LogWarning("AcceptChallenge failed");
  574. commonInfoDialog.SetTitleAndText("challenge.declineFailed.title", "challenge.declineFailed.text");
  575. commonInfoDialog.Show();
  576. if (onComplete != null)
  577. {
  578. onComplete(false);
  579. }
  580. }
  581. });
  582. }
  583. public void SubmitChallengeScore(int challengeId)
  584. {
  585. string userId = SocialManager.Instance.userID;
  586. int score = GameDataManager.Instance.Score;
  587. if (LevelsManager.Instance.CurrentLevel.AreAllObjectivesMet())
  588. {
  589. GameDatabaseManager.Instance.ReportChallengeScore(userId, challengeId, score, (isGameDatabaseReportScoreSuccessful) =>
  590. {
  591. AVDebug.Log("isGameDatabaseReportScoreSuccessful " + (isGameDatabaseReportScoreSuccessful ? "Successful" : "Failed"));
  592. if(isGameDatabaseReportScoreSuccessful)
  593. {
  594. SocialManager.Instance.ReportScore(score, (isSocialManagerReportScoreSuccessful) =>
  595. {
  596. AVDebug.Log("isSocialManagerReportScoreSuccessful " + (isSocialManagerReportScoreSuccessful ? "Successful" : "Failed"));
  597. });
  598. } else
  599. {
  600. commonInfoDialog.SetTitleAndText("challenge.submitScoreFailed.title", "challenge.submitScoreFailed.text");
  601. commonInfoDialog.Show();
  602. }
  603. });
  604. } else
  605. {
  606. //Even if not all the objectives were met... send social network notifications
  607. SocialManager.Instance.ReportScore(score, (isSocialManagerReportScoreSuccessful) =>
  608. {
  609. AVDebug.Log("isSocialManagerReportScoreSuccessful " + (isSocialManagerReportScoreSuccessful ? "Successful" : "Failed"));
  610. });
  611. }
  612. }
  613. public void GetChallengeResultsFromServer()
  614. {
  615. AVDebug.Log("Getting challenge results from server");
  616. string userId = SocialManager.Instance.userID;
  617. GameDatabaseManager.Instance.LoadChallengeResults(userId, 5, (isSuccessful, challengeResults) =>
  618. {
  619. if (isSuccessful)
  620. {
  621. AVDebug.Log("Loaded challenge results");
  622. _loadedChallengeResults = challengeResults;
  623. } else
  624. {
  625. AVDebug.Log("Failed loading challenge results");
  626. }
  627. if (isSuccessful && challengeResults != null)
  628. {
  629. //Finding how many are really new
  630. int[] lastSeenChallengeIds = GetLastSeenChallengeIds();
  631. int newResults = 0;
  632. foreach (ChallengeResult result in challengeResults)
  633. {
  634. if (!result.WasChallengeDeclined() &&
  635. IsChallengeResultNew(result, lastSeenChallengeIds))
  636. {
  637. ++newResults;
  638. }
  639. }
  640. //Notify of the count of new challenge results
  641. NotificationCenter.Post(NotificationType.ReceivedNewChallengeResults, newResults);
  642. }
  643. });
  644. }
  645. int[] GetLastSeenChallengeIds()
  646. {
  647. string lastChallengeIdsString = PlayerPrefs.GetString(LAST_SEEN_CHALLENGE_IDS_KEY, "");
  648. string[] lastChallengeIdsAsStrings = lastChallengeIdsString.Split(',');
  649. int[] lastChallengeIds = new int[lastChallengeIdsAsStrings.Length];
  650. for (int i = 0; i < lastChallengeIds.Length; i++)
  651. {
  652. int.TryParse(lastChallengeIdsAsStrings[i], out lastChallengeIds[i]);
  653. }
  654. return lastChallengeIds;
  655. }
  656. bool IsChallengeResultNew(ChallengeResult result, int[] lastChallengeIds)
  657. {
  658. foreach (int id in lastChallengeIds)
  659. {
  660. if (id == result.challenge.id)
  661. {
  662. return false;
  663. }
  664. }
  665. return true;
  666. }
  667. #endregion
  668. void OnLoginComplete(bool isSuccessful, string errorReason)
  669. {
  670. if (isSuccessful)
  671. {
  672. #if UNITY_ANDROID
  673. StartCoroutine(DelayGetFacebookPermissions());
  674. progressIndicator.Hide();
  675. #else
  676. //SocialManager.Instance.GetPublishPermissions();
  677. #endif
  678. } else
  679. {
  680. AVDebug.Log("Log in failed! "+errorReason);
  681. progressIndicator.Hide();
  682. #if UNITY_IPHONE
  683. //this only occurs on iPhone when they use facebook Single Sign-on and have clicked on Don't allow in a previous session
  684. if (errorReason == "com.facebook.sdk:SystemLoginDisallowedWithoutError")
  685. {
  686. commonInfoDialog.SetTitleAndText("facebook.login.failed.title", "facebook.login.failedCheckSingleSignonSettings.text");
  687. } else
  688. #endif
  689. {
  690. commonInfoDialog.SetTitleAndText("facebook.login.failed.title", "facebook.login.failed.text");
  691. }
  692. commonInfoDialog.Show();
  693. }
  694. }
  695. void OnReauthFailed(P31Error message)
  696. {
  697. //MenuManager._instance.LabelDebug.text = MenuManager._instance.LabelDebug.text + "OnReauthFailed)" + "\n";
  698. progressIndicator.Hide();
  699. AVDebug.LogWarning("Facebook Reauth Failed ... Logging out: "+message);
  700. LogOut();
  701. commonInfoDialog.SetTitleAndText("facebook.login.failed.title", "facebook.login.failedAcceptingPublishPermissions.text");
  702. commonInfoDialog.Show();
  703. }
  704. void OnReauthSucceeded()
  705. {
  706. if(progressIndicator!= null)
  707. progressIndicator.Hide();
  708. AVDebug.Log("Facebook Reauth Succeeded: ");
  709. if (HasAcceptedPublishPermissions())
  710. {
  711. if (OnSuccessfulLoginWithPermissions != null)
  712. {
  713. OnSuccessfulLoginWithPermissions();
  714. }
  715. SocialManager.Instance.StartMonitoring( REQUESTS_MONITOR_INTERVAL_SECONDS );
  716. QueryHasLikedPage();
  717. } else
  718. {
  719. commonInfoDialog.SetTitleAndText("facebook.login.failed.title", "facebook.login.failedAcceptingPublishPermissions.text");
  720. commonInfoDialog.Show();
  721. LogOut(); //if he doesn't accept permissions, just log him out
  722. }
  723. }
  724. void OnGetLikeStatusComplete(bool isLiked)
  725. {
  726. AVDebug.Log("OnGetLikeStatusComplete "+isLiked);
  727. PlayerPrefs.SetInt(HAS_LIKED_PAGE, isLiked ? 1 : 0);
  728. PlayerPrefs.Save();
  729. //Submit any score after he has liked the page
  730. if (isLiked)
  731. {
  732. Logger.LogFlurryEvent("Player has liked facebook page");
  733. }
  734. if (OnQueryHasLikedPageComplete != null)
  735. {
  736. OnQueryHasLikedPageComplete(isLiked);
  737. }
  738. }
  739. /// <summary>
  740. /// Due to Android probs, we have to wait a bit due to some app switching problems
  741. /// </summary>
  742. IEnumerator DelayGetFacebookPermissions()
  743. {
  744. yield return new WaitForSeconds(0.5f);
  745. SocialManager.Instance.GetPublishPermissions();
  746. }
  747. void OnReceivedRequests(ReceivedRequestsArgs requests)
  748. {
  749. lastReceivedRequests = requests;
  750. //On receiving requests, lets ask for any results
  751. GetChallengeResultsFromServer();
  752. }
  753. void OnGameStart(Notification note)
  754. {
  755. if (SocialManager.Instance.isSessionValid)
  756. {
  757. SocialManager.Instance.StopMonitoring();
  758. }
  759. }
  760. void OnGameOver(Notification note)
  761. {
  762. if (SocialManager.Instance.isSessionValid && HasAcceptedPublishPermissions())
  763. {
  764. SocialManager.Instance.StartMonitoring(REQUESTS_MONITOR_INTERVAL_SECONDS);
  765. }
  766. //only submit score if he has achieved all objectives
  767. if (!LevelsManager.Instance.CurrentLevel.AreAllObjectivesMet())
  768. {
  769. return;
  770. }
  771. progressIndicator.Show();
  772. ServerTime.Instance.RetrieveServerTime( (serverTime) =>
  773. {
  774. progressIndicator.Hide();
  775. if (serverTime != -1)
  776. {
  777. TimeManager.Instance.EndServerTime = serverTime;
  778. #if DEBUG
  779. long realPlayTime = TimeManager.Instance.EndServerTime - TimeManager.Instance.StartServerTime;
  780. Debug.Log("Real Play Time : "+realPlayTime);
  781. Debug.LogError("Real Play Time : " + realPlayTime);
  782. #endif
  783. ContinueToSubmitScore();
  784. } else
  785. {
  786. //show error
  787. commonInfoDialog.SetTitleAndText("serverError.title", "serverError.text");
  788. commonInfoDialog.Show();
  789. }
  790. });
  791. }
  792. void ContinueToSubmitScore()
  793. {
  794. //Submit score to game database and facebook
  795. int score = GameDataManager.Instance.Score;
  796. string replayData = RecordingManager.Instance.GetReplayData();
  797. Debug.Log("Score " + score + " " + LevelsManager.Instance.CurrentLevelIndex);
  798. SubmitScore(LevelsManager.Instance.CurrentLevelIndex++, score, replayData);
  799. }
  800. void SubmitScore(int levelIndex, int score, string replayData)
  801. {
  802. if (ConnectivityPollManager.HasInternet &&
  803. HasLikedPage() &&
  804. !string.IsNullOrEmpty(SocialManager.Instance.userID))
  805. {
  806. Debug.Log("Reporting Score for level "+levelIndex+" with score of " + score + " for user "+SocialManager.Instance.userID);
  807. GameDatabaseManager.Instance.ReportScore(SocialManager.Instance.userID, score, levelIndex.ToString(), replayData, (isGameDatabaseScoreSubmitSuccessful) =>
  808. {
  809. Debug.Log("isGameDatabaseScoreSubmitSuccessful "+isGameDatabaseScoreSubmitSuccessful);
  810. Debug.Log(levelIndex);
  811. if (isGameDatabaseScoreSubmitSuccessful)
  812. {
  813. AVDebug.Log("Reporting score on facebook");
  814. SocialManager.Instance.ReportScore(score, (isSocialManagerScoreSubmitSuccessful) =>
  815. {
  816. //We don't care much if it wasn't successful on posting to facebook, since competition highscore list is on ourservers.
  817. AVDebug.Log("isSocialManagerScoreSubmitSuccessful " +isSocialManagerScoreSubmitSuccessful);
  818. });
  819. } else
  820. {
  821. AVDebug.LogWarning("Failed submitting score...");
  822. commonInfoDialog.SetTitleAndText("scoreSubmitError.title","scoreSubmitError.text");
  823. commonInfoDialog.Show();
  824. }
  825. });
  826. } else
  827. {
  828. Debug.Log("Player has not liked page, logged in to facebook or isOffline... " + SocialManager.Instance.userID + " " + ConnectivityPollManager.HasInternet);
  829. }
  830. }
  831. private void HandleResult(IResult result)
  832. {
  833. //SocialManager.Instance.SendUserToUserRequest(Localization.instance.Get("facebook.lifeRequest.title"), Localization.instance.Get("facebook.lifeRequest"), "type=lifeDemand", (isSuccessful, requests) =>
  834. {
  835. progressIndicator.Hide();
  836. if (!string.IsNullOrEmpty(result.RawResult))
  837. {
  838. Logger.LogFlurryEvent("Player request lives", "count", result.RawResult.Length.ToString());
  839. commonInfoDialog.SetTitleAndText("facebook.lifeRequest.success.title", "facebook.lifeRequest.success.text");
  840. /* foreach (string r in requests.recipientIDs)
  841. {
  842. AVDebug.Log("Sent life demand " + r);
  843. }*/
  844. Debug.Log("Sendlife");
  845. LivesManager.Instance.RechargeOneLife();
  846. PlayerPrefs.SetInt("Live", 1);
  847. PlayerPrefs.Save();
  848. }
  849. else
  850. {
  851. Debug.Log("FailedLife");
  852. Logger.LogFlurryEvent("Player request lives failed or cancelled");
  853. commonInfoDialog.SetTitleAndText("facebook.lifeRequest.failed.title", "facebook.lifeRequest.failed.text");
  854. }
  855. commonInfoDialog.Show();
  856. }//);
  857. }
  858. }