FacebookHelper.cs 29 KB

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