WrapperFB.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. using System;
  2. using UnityEngine;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using Facebook.Unity;
  6. using Facebook.Unity.Example;
  7. using Prime31;
  8. public class WrapperFB : MonoBehaviour
  9. {
  10. public GameObject LogoutGop;
  11. public GameObject LoginGop;
  12. public static GameObject LoginGo;
  13. public static GameObject LogoutGo;
  14. public static string Name { get; private set; }
  15. public static string Id { get; private set; }
  16. public static string Email { get; private set; }
  17. public static bool InitDone { get; private set; }
  18. public delegate void EventHandler(object target);
  19. public static event EventHandler OnLoggedIn;
  20. public static event EventHandler LoginFailedHandler;
  21. public static GameObject Go;
  22. // Use this for initialization
  23. // public void Start()
  24. // {
  25. // //Go = gameObject;
  26. // //Name = PlayerPrefs.GetString("FB_USER_NAME", "");
  27. //#if UNITY_EDITOR
  28. //#endif
  29. // }
  30. public void LoginFacebook()
  31. {
  32. if (!FB.IsLoggedIn)
  33. {
  34. // Continue with Facebook SDK
  35. var perms = new List<string>() { "public_profile", "email", "user_friends" };
  36. FB.LogInWithReadPermissions(perms, FBAuthCallback);
  37. }
  38. else
  39. {
  40. FBAuthCallback(null);
  41. }
  42. }
  43. private void FBAuthCallback(ILoginResult result)
  44. {
  45. if (FB.IsLoggedIn)
  46. {
  47. // AccessToken class will have session details
  48. var aToken = Facebook.Unity.AccessToken.CurrentAccessToken;
  49. // Print current access token's User ID
  50. Debug.Log(aToken.UserId);
  51. // Print current access token's granted permissions
  52. foreach (string perm in aToken.Permissions)
  53. {
  54. Debug.Log(perm);
  55. }
  56. }
  57. else
  58. {
  59. Debug.Log("User cancelled login");
  60. }
  61. }
  62. public static void UpdateLoginButton()
  63. {
  64. if (PlayerPrefs.GetInt("Login") == 1)
  65. {
  66. LogoutGo.SetActive(true);
  67. LoginGo.SetActive(false);
  68. }
  69. else
  70. {
  71. LogoutGo.SetActive(false);
  72. LoginGo.SetActive(true);
  73. }
  74. }
  75. public static void Init()
  76. {
  77. FB.Init(() =>
  78. {
  79. InitDone = true;
  80. });
  81. }
  82. void Update()
  83. {
  84. //if (WrapperFB.IsLoggedIn)
  85. //{
  86. // LogoutGo.SetActive(true);
  87. // LoginGo.SetActive(false);
  88. //}
  89. //else
  90. //{
  91. // LogoutGo.SetActive(false);
  92. // LoginGo.SetActive(true);
  93. //}
  94. }
  95. public static void LoggedIn(GameObject unit)
  96. {
  97. if (OnLoggedIn != null)
  98. {
  99. OnLoggedIn(unit);
  100. }
  101. }
  102. private IEnumerator ShowLoginPopup()
  103. {
  104. yield return new WaitForSeconds(1);
  105. //LoginManager.Instance.WrongMessages.Show();
  106. }
  107. public static bool IsLoggedIn
  108. {
  109. get { return UserTokenInfo.ExpirationTime > DateTime.Now; }
  110. }
  111. public static string UserID
  112. {
  113. get { return UserTokenInfo.UserID; }
  114. }
  115. public static string AccessToken
  116. {
  117. get { return UserTokenInfo.AccessToken; }
  118. }
  119. private static void DispNAme(IGraphResult result)
  120. {
  121. if (result.Error != null)
  122. {
  123. }
  124. else
  125. {
  126. if (result.ResultDictionary != null)
  127. {
  128. foreach (string key in result.ResultDictionary.Keys)
  129. {
  130. Debug.Log(key + " : " + result.ResultDictionary[key].ToString());
  131. // first_name : Chris
  132. // id : 12345678901234567
  133. }
  134. }
  135. PlayerPrefs.SetString("FB_USER_NAME", result.ResultDictionary["name"].ToString());
  136. PlayerPrefs.SetString("FB_ID", result.ResultDictionary["id"].ToString());
  137. PlayerPrefs.Save();
  138. //SocialManager.Instance.GraphRequestCallback(result);
  139. }
  140. }
  141. public void CallFBLogout()
  142. {
  143. FB.LogOut();
  144. if (WrapperFB.IsLoggedIn)
  145. {
  146. LogoutGo.SetActive(true);
  147. LoginGo.SetActive(false);
  148. }
  149. else
  150. {
  151. LogoutGo.SetActive(false);
  152. LoginGo.SetActive(true);
  153. }
  154. }
  155. public static void Login()
  156. {
  157. Debug.Log("Login");
  158. #if UNITY_EDITOR
  159. //PlayerPrefs.SetInt("Login", 1);
  160. //LoginManager.Instance.WrongMessages.Hide();
  161. #endif
  162. FB.LogInWithReadPermissions(new List<string> { "email", "public_profile", "user_friends" }, result =>
  163. {
  164. if (result != null && !result.Cancelled && string.IsNullOrEmpty(result.Error))
  165. {
  166. Debug.Log("LOGIN");
  167. UserTokenInfo.LoginToken(result.AccessToken);
  168. //Name = result.ResultDictionary["first_name"].ToString() + " " + result.ResultDictionary["last_name"].ToString();
  169. PlayerPrefs.SetInt("Login",1);
  170. if (PlayerPrefs.GetInt("Login") == 1)
  171. {
  172. LogoutGo.SetActive(true);
  173. LoginGo.SetActive(false);
  174. }
  175. else
  176. {
  177. LogoutGo.SetActive(false);
  178. LoginGo.SetActive(true);
  179. }
  180. //LoginManager.Instance.WrongMessages.Hide();
  181. LoggedIn(Go);
  182. FB.API("/me",
  183. HttpMethod.GET,
  184. DispNAme)
  185. ;
  186. }
  187. else if (!string.IsNullOrEmpty(result.Error))
  188. {
  189. LoginFailedHandler(result.Error);
  190. }
  191. });
  192. }
  193. // public static void Logout()
  194. // {
  195. //#if UNITY_EDITOR
  196. // PlayerPrefs.SetInt("Login", 0);
  197. //#endif
  198. // PlayerPrefs.SetInt("Login", 0);
  199. // if (PlayerPrefs.GetInt("Login") == 1)
  200. // {
  201. // LogoutGo.SetActive(true);
  202. // LoginGo.SetActive(false);
  203. // }
  204. // else
  205. // {
  206. // LogoutGo.SetActive(false);
  207. // LoginGo.SetActive(true);
  208. // }
  209. // UserTokenInfo.LogOut();
  210. // FB.LogOut();
  211. // }
  212. public static void HandleResult(IResult result)
  213. {
  214. if (result == null)
  215. {
  216. LastResponse = "Null Response\n";
  217. LogView.AddLog(LastResponse);
  218. Debug.Log(LastResponse);
  219. return;
  220. }
  221. LastResponseTexture = null;
  222. // Some platforms return the empty string instead of null.
  223. if (!string.IsNullOrEmpty(result.Error))
  224. {
  225. Status = "Error - Check log for details";
  226. LastResponse = "Error Response:\n" + result.Error;
  227. LogView.AddLog(result.Error);
  228. Debug.Log(LastResponse);
  229. }
  230. else if (result.Cancelled)
  231. {
  232. Status = "Cancelled - Check log for details";
  233. LastResponse = "Cancelled Response:\n" + result.RawResult;
  234. LogView.AddLog(result.RawResult);
  235. Debug.Log(LastResponse);
  236. //if (MenuManager._instance.gameOverSummaryScreen.isActiveAndEnabled && !MenuManager._instance.IsLevelEnd)
  237. //{
  238. // MenuManager._instance.gameOverSummaryScreen.Hide();
  239. //}
  240. //NoLivesLeftDetector.Instance.NoLivesAddFriendForOneLiveGameOver.Hide();
  241. //GameDataManager.Instance.HasStartedSpawningEnemies = false;
  242. //MenuManager._instance.IsLevelEnd = false;
  243. //NotificationCenter.Post(NotificationType.GameOver);
  244. //NotificationCenter.Post(NotificationType.MenuTransition, MenuManager.MenuTransition.ExitToMainMenu);
  245. //MenuManager._instance.playScreen.SetActive(false);
  246. }
  247. else if (!string.IsNullOrEmpty(result.RawResult))
  248. {
  249. Status = "Success - Check log for details";
  250. LastResponse = "Success Response:\n" + result.RawResult;
  251. LogView.AddLog(result.RawResult);
  252. Debug.Log(LastResponse);
  253. var countLifeInDay = PlayerPrefs.GetInt("CounterLifeInDay");
  254. if (countLifeInDay == 0)
  255. {
  256. //NotificationCenter.Post(NotificationType.GetLife);
  257. //if (MenuManager._instance.gameOverSummaryScreen.isActiveAndEnabled && !MenuManager._instance.IsLevelEnd)
  258. //{
  259. // MenuManager._instance.gameOverSummaryScreen.Hide();
  260. //}
  261. }
  262. else
  263. {
  264. }
  265. PlayerPrefs.SetInt("CounterLifeInDay", countLifeInDay + 1);
  266. PlayerPrefs.Save();
  267. //LivesManager.Instance.AddLife();
  268. //NoLivesLeftDetector.Instance.NoLivesAddFriendForOneLiveGameOver.Hide();
  269. }
  270. else
  271. {
  272. LastResponse = "Empty Response\n";
  273. LogView.AddLog(LastResponse);
  274. Debug.Log(LastResponse);
  275. }
  276. }
  277. public static string Status { get; set; }
  278. public static object LastResponseTexture { get; set; }
  279. public static string LastResponse { get; set; }
  280. public static void PostFB()
  281. {
  282. Facebook.Unity.FB.
  283. FeedShare(
  284. string.Empty,
  285. new Uri("https://game.gamatic.com/app_condom_dk/Kondomspillet4.html"),
  286. "",
  287. "",
  288. "",
  289. new Uri("https://game.gamatic.com/RubIt/facebookShareWonChallenge2.png"),
  290. string.Empty,
  291. HandleResultPost);
  292. }
  293. public void Post()
  294. {
  295. PostFB();
  296. }
  297. private static void HandleResultPost(IResult result)
  298. {
  299. if (result == null)
  300. {
  301. LastResponse = "Null Response\n";
  302. LogView.AddLog(LastResponse);
  303. Debug.Log(LastResponse);
  304. return;
  305. }
  306. LastResponseTexture = null;
  307. // Some platforms return the empty string instead of null.
  308. if (!string.IsNullOrEmpty(result.Error))
  309. {
  310. Status = "Error - Check log for details";
  311. LastResponse = "Error Response:\n" + result.Error;
  312. LogView.AddLog(result.Error);
  313. Debug.Log(LastResponse);
  314. }
  315. else if (result.Cancelled)
  316. {
  317. Status = "Cancelled - Check log for details";
  318. LastResponse = "Cancelled Response:\n" + result.RawResult;
  319. LogView.AddLog(result.RawResult);
  320. Debug.Log(LastResponse);
  321. }
  322. else if (!string.IsNullOrEmpty(result.RawResult))
  323. {
  324. Status = "Success - Check log for details";
  325. LastResponse = "Success Response:\n" + result.RawResult;
  326. LogView.AddLog(result.RawResult);
  327. //LoginManager.Instance.WrongMessages.Hide();
  328. Debug.Log(LastResponse);
  329. //MenuManager._instance.FBShareDialog.Hide();
  330. }
  331. else
  332. {
  333. LastResponse = "Empty Response\n";
  334. LogView.AddLog(LastResponse);
  335. Debug.Log(LastResponse);
  336. }
  337. }
  338. public static void InviteFriends()
  339. {
  340. FB.Mobile.AppInvite(new Uri("https://fb.me/126548434714783"), callback: HandleResult);
  341. }
  342. //public static string Name { get; private set; }
  343. //public static bool InitDone { get; private set; }
  344. private static WrapperFB _instance;
  345. // Use this for initialization
  346. void Start()
  347. {
  348. LoginGo = LoginGop;
  349. LogoutGo = LogoutGop;
  350. if (PlayerPrefs.GetInt("Login") == 1)
  351. {
  352. LogoutGo.SetActive(true);
  353. LoginGo.SetActive(false);
  354. }
  355. else
  356. {
  357. LogoutGo.SetActive(false);
  358. LoginGo.SetActive(true);
  359. }
  360. //ServerGiftManager.Instance.BaseRegistration((states, s) =>
  361. //{
  362. // // Debug.LogError("ServerGiftManager.Instance.BaseRegistration: " + states);
  363. //});
  364. if (_instance)
  365. {
  366. Destroy(gameObject);
  367. return;
  368. }
  369. _instance = this;
  370. Name = PlayerPrefs.GetString("FB_USER_NAME", "");
  371. FB.Init(() =>
  372. {
  373. InitDone = true;
  374. //Invite(i =>
  375. //{
  376. //});
  377. });
  378. DontDestroyOnLoad(gameObject);
  379. }
  380. //private void Update()
  381. //{
  382. // if (Input.GetKeyDown(KeyCode.F2) && InitDone && IsLoggedIn)
  383. // {
  384. // Logout();
  385. // }
  386. //}
  387. //public static bool IsLoggedIn
  388. //{
  389. // get { return UserTokenInfo.ExpirationTime > DateTime.Now; }
  390. //}
  391. //public static string UserID
  392. //{
  393. // get { return UserTokenInfo.UserID; }
  394. //}
  395. //public static string AccessToken
  396. //{
  397. // get { return UserTokenInfo.AccessToken; }
  398. //}
  399. public static void Login(Action onSuccess, Action onError)
  400. {
  401. FB.LogInWithReadPermissions(new List<string> { "email", "public_profile", "user_friends" }, result =>
  402. {
  403. if (result != null && !result.Cancelled && string.IsNullOrEmpty(result.Error))
  404. {
  405. UserTokenInfo.LoginToken(result.AccessToken);
  406. if (onSuccess != null)
  407. {
  408. onSuccess();
  409. }
  410. var aToken = Facebook.Unity.AccessToken.CurrentAccessToken;
  411. // Print current access token's User ID
  412. Debug.Log(aToken.UserId);
  413. // Print current access token's granted permissions
  414. bool email = false;
  415. foreach (string perm in aToken.Permissions)
  416. {
  417. if (perm == "email")
  418. {
  419. email = true;
  420. }
  421. Debug.Log(perm);
  422. }
  423. FB.API("/me?fields=id,name,email", HttpMethod.GET, resultMe =>
  424. {
  425. if (resultMe != null && !resultMe.Cancelled && string.IsNullOrEmpty(resultMe.Error))
  426. {
  427. Name = resultMe.ResultDictionary["name"].ToString();
  428. if (email)
  429. {
  430. Email = resultMe.ResultDictionary["email"].ToString();
  431. }
  432. Id = resultMe.ResultDictionary["id"].ToString();
  433. PlayerPrefs.SetString("FB_USER_NAME", Name);
  434. PlayerPrefs.Save();
  435. ServerGiftManager.Instance.FullRegistrationFB(Name, Email, "FB", Id, states =>
  436. {
  437. switch (states)
  438. {
  439. case ServerGiftManager.RegistrationStates.UpdateDone:
  440. RegistrationManager.Instance.ChangeRegistration.Hide();
  441. Debug.Log("new");
  442. //todo: handle - user info was updated (everything goes good)
  443. break;
  444. case ServerGiftManager.RegistrationStates.Old:
  445. Debug.Log("Old");
  446. //todo: handle - old user returns (everything goes good)
  447. break;
  448. case ServerGiftManager.RegistrationStates.SantaNameNotUnique:
  449. //todo: handle - user should guess another name for santa (no data was updated!)
  450. break;
  451. case ServerGiftManager.RegistrationStates.IdentificatorNotIsset:
  452. //todo: handle - you must run base registration first! (no data was updated!)
  453. break;
  454. case ServerGiftManager.RegistrationStates.ContactsIsNotEnough:
  455. //todo: handle - santaName or phone or e-mail is empty (no data was updated!)
  456. break;
  457. case ServerGiftManager.RegistrationStates.Error:
  458. //todo: handle - unknown error happens - maybe internet connection errors (no data was updated!)
  459. break;
  460. }
  461. });
  462. }
  463. });
  464. }
  465. else
  466. {
  467. Debug.LogError(result);
  468. Debug.LogError(result.Error);
  469. Debug.LogError(result.Cancelled);
  470. Debug.LogError(result.RawResult);
  471. if (onError != null)
  472. {
  473. onError();
  474. }
  475. }
  476. });
  477. }
  478. public static void ShareWin(int distance)
  479. {
  480. FB.FeedShare("", new Uri("http://www.kringlan.is/"), "Viltu vinna páskaegg?", "Ég náði " + distance + " stigum í Páskaleik Kringlunnar -– þúsundir vinninga og Páskaegg frá Góu í boði!", "", new Uri(GameConstants.SERVER_BASE_URL + "FB.png"), "",
  481. result =>
  482. {
  483. if (!string.IsNullOrEmpty(result.Error))
  484. {
  485. Debug.LogError(result.Error);
  486. }
  487. else if (result.Cancelled)
  488. {
  489. }
  490. else if (!string.IsNullOrEmpty(result.RawResult))
  491. {
  492. //NGUIMenuScript.Instance.AddLife();
  493. }
  494. Debug.LogError(result.RawResult);
  495. });
  496. }
  497. public static void ShareWeekWin()
  498. {
  499. FB.FeedShare("", new Uri("http://www.kringlan.is/"), "download and run", "I am a winner!", "", new Uri(GameConstants.SERVER_BASE_URL + "FB.png"), "",
  500. result =>
  501. {
  502. if (!string.IsNullOrEmpty(result.Error))
  503. {
  504. Debug.LogError(result.Error);
  505. }
  506. Debug.LogError(result.RawResult);
  507. });
  508. }
  509. public static void Logout(Action onSuccess)
  510. {
  511. PlayerPrefs.SetString("REGISTRATION", "FB");
  512. PlayerPrefs.SetString("FB_USER_NAME", "");
  513. PlayerPrefs.Save();
  514. UserTokenInfo.LogOut();
  515. FB.LogOut();
  516. if (onSuccess != null)
  517. {
  518. onSuccess();
  519. }
  520. PlayerPrefs.SetInt("Login", 0);
  521. if (PlayerPrefs.GetInt("Login") == 1)
  522. {
  523. LogoutGo.SetActive(true);
  524. LoginGo.SetActive(false);
  525. }
  526. else
  527. {
  528. LogoutGo.SetActive(false);
  529. LoginGo.SetActive(true);
  530. }
  531. }
  532. #region INVITE
  533. private static string FriendSelectorTitle = "Join the Easter Marathon";
  534. private static string FriendSelectorMessage = "Help me to collect more eggs";
  535. // private static string [] FriendSelectorFilters = {"all", "app_users", "app_non_users"};
  536. private static string[] FriendSelectorFilters = { "app_non_users" };
  537. private static string FriendSelectorData = "{}";
  538. private static int maxRecipients = 5;
  539. private static void CallAppRequestAsFriendSelector()
  540. {
  541. string[] excludeIds = null;
  542. //FB.AppRequest(
  543. // FriendSelectorMessage,
  544. // null,
  545. // FriendSelectorFilters,
  546. // excludeIds,
  547. // maxRecipients,
  548. // FriendSelectorData,
  549. // FriendSelectorTitle,
  550. // Callback
  551. //);
  552. FB.AppRequest(FriendSelectorMessage, null, null, null, 5, "", FriendSelectorTitle, Callback);
  553. }
  554. public static void Invite(Action<int> onDone)
  555. {
  556. CallAppRequestAsFriendSelector();
  557. }
  558. private static Action<int> _onInviteDone;
  559. private static void Callback(IAppRequestResult result)
  560. {
  561. Debug.LogWarning(result);
  562. if (_onInviteDone != null)
  563. {
  564. if (result != null && !result.Cancelled && string.IsNullOrEmpty(result.Error))
  565. {
  566. var friends = 0;
  567. foreach (var v in result.To)
  568. {
  569. friends++;
  570. }
  571. _onInviteDone(friends);
  572. }
  573. else
  574. {
  575. _onInviteDone(0);
  576. }
  577. }
  578. }
  579. #endregion
  580. }