PageRenderTime 60ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/Assets/Facebook/Scripts/AndroidFacebook.cs

https://bitbucket.org/chiphuc113/unknowproject
C# | 549 lines | 463 code | 74 blank | 12 comment | 78 complexity | e29def6cc47d791af22956d63359ea9a MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace Facebook
  5. {
  6. sealed class AndroidFacebook : AbstractFacebook, IFacebook
  7. {
  8. public const int BrowserDialogMode = 0;
  9. private const string AndroidJavaFacebookClass = "com.facebook.unity.FB";
  10. private const string CallbackIdKey = "callback_id";
  11. // key Hash used for Android SDK
  12. private string keyHash;
  13. public string KeyHash { get { return keyHash; } }
  14. #region IFacebook
  15. public override int DialogMode { get { return BrowserDialogMode; } set { } }
  16. public override bool LimitEventUsage
  17. {
  18. get
  19. {
  20. return limitEventUsage;
  21. }
  22. set
  23. {
  24. limitEventUsage = value;
  25. CallFB("SetLimitEventUsage", value.ToString());
  26. }
  27. }
  28. #endregion
  29. private FacebookDelegate deepLinkDelegate;
  30. #region FBJava
  31. #if UNITY_ANDROID
  32. private AndroidJavaClass fbJava;
  33. private AndroidJavaClass FB
  34. {
  35. get
  36. {
  37. if (fbJava == null)
  38. {
  39. fbJava = new AndroidJavaClass(AndroidJavaFacebookClass);
  40. if (fbJava == null)
  41. {
  42. throw new MissingReferenceException(string.Format("AndroidFacebook failed to load {0} class", AndroidJavaFacebookClass));
  43. }
  44. }
  45. return fbJava;
  46. }
  47. }
  48. #endif
  49. private void CallFB(string method, string args)
  50. {
  51. #if UNITY_ANDROID
  52. FB.CallStatic(method, args);
  53. #else
  54. FbDebug.Error("Using Android when not on an Android build! Doesn't Work!");
  55. #endif
  56. }
  57. #endregion
  58. #region FBAndroid
  59. protected override void OnAwake()
  60. {
  61. keyHash = "";
  62. #if UNITY_ANDROID && DEBUG
  63. AndroidJNIHelper.debug = true;
  64. #endif
  65. }
  66. private bool IsErrorResponse(string response)
  67. {
  68. //var res = MiniJSON.Json.Deserialize(response);
  69. return false;
  70. }
  71. private InitDelegate onInitComplete = null;
  72. public override void Init(
  73. InitDelegate onInitComplete,
  74. string appId,
  75. bool cookie = false,
  76. bool logging = true,
  77. bool status = true,
  78. bool xfbml = false,
  79. string channelUrl = "",
  80. string authResponse = null,
  81. bool frictionlessRequests = false,
  82. HideUnityDelegate hideUnityDelegate = null)
  83. {
  84. if (string.IsNullOrEmpty(appId))
  85. {
  86. throw new ArgumentException("appId cannot be null or empty!");
  87. }
  88. var parameters = new Dictionary<string, object>();
  89. parameters.Add("appId", appId);
  90. if (cookie != false)
  91. {
  92. parameters.Add("cookie", true);
  93. }
  94. if (logging != true)
  95. {
  96. parameters.Add("logging", false);
  97. }
  98. if (status != true)
  99. {
  100. parameters.Add("status", false);
  101. }
  102. if (xfbml != false)
  103. {
  104. parameters.Add("xfbml", true);
  105. }
  106. if (!string.IsNullOrEmpty(channelUrl))
  107. {
  108. parameters.Add("channelUrl", channelUrl);
  109. }
  110. if (!string.IsNullOrEmpty(authResponse))
  111. {
  112. parameters.Add("authResponse", authResponse);
  113. }
  114. if (frictionlessRequests != false)
  115. {
  116. parameters.Add("frictionlessRequests", true);
  117. }
  118. var paramJson = MiniJSON.Json.Serialize(parameters);
  119. this.onInitComplete = onInitComplete;
  120. this.CallFB("Init", paramJson.ToString());
  121. }
  122. public void OnInitComplete(string message)
  123. {
  124. OnLoginComplete(message);
  125. if (this.onInitComplete != null)
  126. {
  127. this.onInitComplete();
  128. }
  129. }
  130. public override void Login(string scope = "", FacebookDelegate callback = null)
  131. {
  132. var parameters = new Dictionary<string, object>();
  133. parameters.Add("scope", scope);
  134. var paramJson = MiniJSON.Json.Serialize(parameters);
  135. AddAuthDelegate(callback);
  136. this.CallFB("Login", paramJson);
  137. }
  138. public void OnLoginComplete(string message)
  139. {
  140. var parameters = (Dictionary<string, object>)MiniJSON.Json.Deserialize(message);
  141. if (parameters.ContainsKey("user_id"))
  142. {
  143. isLoggedIn = true;
  144. userId = (string)parameters["user_id"];
  145. accessToken = (string)parameters["access_token"];
  146. accessTokenExpiresAt = FromTimestamp(int.Parse((string)parameters["expiration_timestamp"]));
  147. }
  148. if (parameters.ContainsKey("key_hash"))
  149. {
  150. keyHash = (string)parameters["key_hash"];
  151. }
  152. OnAuthResponse(new FBResult(message));
  153. }
  154. //TODO: move into AbstractFacebook
  155. public void OnAccessTokenRefresh(string message)
  156. {
  157. var parameters = (Dictionary<string, object>)MiniJSON.Json.Deserialize(message);
  158. if (parameters.ContainsKey("access_token"))
  159. {
  160. accessToken = (string)parameters["access_token"];
  161. accessTokenExpiresAt = FromTimestamp(int.Parse((string)parameters["expiration_timestamp"]));
  162. }
  163. }
  164. public override void Logout()
  165. {
  166. this.CallFB("Logout", "");
  167. }
  168. public void OnLogoutComplete(string message)
  169. {
  170. isLoggedIn = false;
  171. userId = "";
  172. accessToken = "";
  173. }
  174. public override void AppRequest(
  175. string message,
  176. OGActionType actionType,
  177. string objectId,
  178. string[] to = null,
  179. string filters = "",
  180. string[] excludeIds = null,
  181. int? maxRecipients = null,
  182. string data = "",
  183. string title = "",
  184. FacebookDelegate callback = null)
  185. {
  186. if (string.IsNullOrEmpty(message))
  187. {
  188. throw new ArgumentNullException("message", "message cannot be null or empty!");
  189. }
  190. if (actionType != null && string.IsNullOrEmpty(objectId))
  191. {
  192. throw new ArgumentNullException("objectId", "You cannot provide an actionType without an objectId");
  193. }
  194. if (actionType == null && !string.IsNullOrEmpty(objectId))
  195. {
  196. throw new ArgumentNullException("actionType", "You cannot provide an objectId without an actionType");
  197. }
  198. var paramsDict = new Dictionary<string, object>();
  199. // Marshal all the above into the thing
  200. paramsDict["message"] = message;
  201. if (callback != null)
  202. {
  203. paramsDict["callback_id"] = AddFacebookDelegate(callback);
  204. }
  205. if (actionType != null && !string.IsNullOrEmpty(objectId))
  206. {
  207. paramsDict["action_type"] = actionType.ToString();
  208. paramsDict["object_id"] = objectId;
  209. }
  210. if (to != null)
  211. {
  212. paramsDict["to"] = string.Join(",", to);
  213. }
  214. if (!string.IsNullOrEmpty(filters))
  215. {
  216. paramsDict["filters"] = filters;
  217. }
  218. if (maxRecipients != null)
  219. {
  220. paramsDict["max_recipients"] = maxRecipients.Value;
  221. }
  222. if (!string.IsNullOrEmpty(data))
  223. {
  224. paramsDict["data"] = data;
  225. }
  226. if (!string.IsNullOrEmpty(title))
  227. {
  228. paramsDict["title"] = title;
  229. }
  230. CallFB("AppRequest", MiniJSON.Json.Serialize(paramsDict));
  231. }
  232. public void OnAppRequestsComplete(string message)
  233. {
  234. var rawResult = (Dictionary<string, object>)MiniJSON.Json.Deserialize(message);
  235. if (rawResult.ContainsKey(CallbackIdKey))
  236. {
  237. var result = new Dictionary<string, object>();
  238. var callbackId = (string)rawResult[CallbackIdKey];
  239. rawResult.Remove(CallbackIdKey);
  240. if (rawResult.Count > 0)
  241. {
  242. List<string> to = new List<string>(rawResult.Count - 1);
  243. foreach (string key in rawResult.Keys)
  244. {
  245. if (!key.StartsWith("to"))
  246. {
  247. result[key] = rawResult[key];
  248. continue;
  249. }
  250. to.Add((string)rawResult[key]);
  251. }
  252. result.Add("to", to);
  253. rawResult.Clear();
  254. OnFacebookResponse(callbackId, new FBResult(MiniJSON.Json.Serialize(result)));
  255. }
  256. else
  257. {
  258. //if we make it here java returned a callback message with only an id
  259. //this isnt supposed to happen
  260. OnFacebookResponse(callbackId, new FBResult(MiniJSON.Json.Serialize(result), "Malformed request response. Please file a bug with facebook here: https://developers.facebook.com/bugs/create"));
  261. }
  262. }
  263. }
  264. public override void FeedRequest(
  265. string toId = "",
  266. string link = "",
  267. string linkName = "",
  268. string linkCaption = "",
  269. string linkDescription = "",
  270. string picture = "",
  271. string mediaSource = "",
  272. string actionName = "",
  273. string actionLink = "",
  274. string reference = "",
  275. Dictionary<string, string[]> properties = null,
  276. FacebookDelegate callback = null)
  277. {
  278. Dictionary<string, object> paramsDict = new Dictionary<string, object>();
  279. // Marshal all the above into the thing
  280. if (callback != null)
  281. {
  282. paramsDict["callback_id"] = AddFacebookDelegate(callback);
  283. }
  284. if (!string.IsNullOrEmpty(toId))
  285. {
  286. paramsDict.Add("to", toId);
  287. }
  288. if (!string.IsNullOrEmpty(link))
  289. {
  290. paramsDict.Add("link", link);
  291. }
  292. if (!string.IsNullOrEmpty(linkName))
  293. {
  294. paramsDict.Add("name", linkName);
  295. }
  296. if (!string.IsNullOrEmpty(linkCaption))
  297. {
  298. paramsDict.Add("caption", linkCaption);
  299. }
  300. if (!string.IsNullOrEmpty(linkDescription))
  301. {
  302. paramsDict.Add("description", linkDescription);
  303. }
  304. if (!string.IsNullOrEmpty(picture))
  305. {
  306. paramsDict.Add("picture", picture);
  307. }
  308. if (!string.IsNullOrEmpty(mediaSource))
  309. {
  310. paramsDict.Add("source", mediaSource);
  311. }
  312. if (!string.IsNullOrEmpty(actionName) && !string.IsNullOrEmpty(actionLink))
  313. {
  314. Dictionary<string, object> dict = new Dictionary<string, object>();
  315. dict.Add("name", actionName);
  316. dict.Add("link", actionLink);
  317. paramsDict.Add("actions", new[] { dict });
  318. }
  319. if (!string.IsNullOrEmpty(reference))
  320. {
  321. paramsDict.Add("ref", reference);
  322. }
  323. if (properties != null)
  324. {
  325. Dictionary<string, object> newObj = new Dictionary<string, object>();
  326. foreach (KeyValuePair<string, string[]> pair in properties)
  327. {
  328. if (pair.Value.Length < 1)
  329. continue;
  330. if (pair.Value.Length == 1)
  331. {
  332. // String-string
  333. newObj.Add(pair.Key, pair.Value[0]);
  334. }
  335. else
  336. {
  337. // String-Object with two parameters
  338. Dictionary<string, object> innerObj = new Dictionary<string, object>();
  339. innerObj.Add("text", pair.Value[0]);
  340. innerObj.Add("href", pair.Value[1]);
  341. newObj.Add(pair.Key, innerObj);
  342. }
  343. }
  344. paramsDict.Add("properties", newObj);
  345. }
  346. CallFB("FeedRequest", MiniJSON.Json.Serialize(paramsDict));
  347. }
  348. public void OnFeedRequestComplete(string message)
  349. {
  350. var rawResult = (Dictionary<string, object>)MiniJSON.Json.Deserialize(message);
  351. if (rawResult.ContainsKey(CallbackIdKey))
  352. {
  353. var result = new Dictionary<string, object>();
  354. var callbackId = (string)rawResult[CallbackIdKey];
  355. rawResult.Remove(CallbackIdKey);
  356. if (rawResult.Count > 0)
  357. {
  358. foreach (string key in rawResult.Keys)
  359. {
  360. result[key] = rawResult[key];
  361. }
  362. rawResult.Clear();
  363. OnFacebookResponse(callbackId, new FBResult(MiniJSON.Json.Serialize(result)));
  364. }
  365. else
  366. {
  367. //if we make it here java returned a callback message with only a callback id
  368. //this isnt supposed to happen
  369. OnFacebookResponse(callbackId, new FBResult(MiniJSON.Json.Serialize(result), "Malformed request response. Please file a bug with facebook here: https://developers.facebook.com/bugs/create"));
  370. }
  371. }
  372. }
  373. public override void Pay(
  374. string product,
  375. string action = "purchaseitem",
  376. int quantity = 1,
  377. int? quantityMin = null,
  378. int? quantityMax = null,
  379. string requestId = null,
  380. string pricepointId = null,
  381. string testCurrency = null,
  382. FacebookDelegate callback = null)
  383. {
  384. throw new PlatformNotSupportedException("There is no Facebook Pay Dialog on Android");
  385. }
  386. public override void GetDeepLink(FacebookDelegate callback)
  387. {
  388. if (callback != null)
  389. {
  390. deepLinkDelegate = callback;
  391. CallFB("GetDeepLink", "");
  392. }
  393. }
  394. public void OnGetDeepLinkComplete(string message)
  395. {
  396. var rawResult = (Dictionary<string, object>) MiniJSON.Json.Deserialize(message);
  397. if (deepLinkDelegate != null)
  398. {
  399. object deepLink = "";
  400. rawResult.TryGetValue("deep_link", out deepLink);
  401. deepLinkDelegate(new FBResult(deepLink.ToString()));
  402. }
  403. }
  404. public override void AppEventsLogEvent(
  405. string logEvent,
  406. float? valueToSum = null,
  407. Dictionary<string, object> parameters = null)
  408. {
  409. var paramsDict = new Dictionary<string, object>();
  410. paramsDict["logEvent"] = logEvent;
  411. if (valueToSum.HasValue)
  412. {
  413. paramsDict["valueToSum"] = valueToSum.Value;
  414. }
  415. if (parameters != null)
  416. {
  417. paramsDict["parameters"] = ToStringDict(parameters);
  418. }
  419. CallFB("AppEvents", MiniJSON.Json.Serialize(paramsDict));
  420. }
  421. public override void AppEventsLogPurchase(
  422. float logPurchase,
  423. string currency = "USD",
  424. Dictionary<string, object> parameters = null)
  425. {
  426. var paramsDict = new Dictionary<string, object>();
  427. paramsDict["logPurchase"] = logPurchase;
  428. paramsDict["currency"] = (!string.IsNullOrEmpty(currency)) ? currency : "USD";
  429. if (parameters != null)
  430. {
  431. paramsDict["parameters"] = ToStringDict(parameters);
  432. }
  433. CallFB("AppEvents", MiniJSON.Json.Serialize(paramsDict));
  434. }
  435. #endregion
  436. #region Helper Functions
  437. public override void PublishInstall(string appId, FacebookDelegate callback = null)
  438. {
  439. var parameters = new Dictionary<string, string>(2);
  440. parameters["app_id"] = appId;
  441. if (callback != null)
  442. {
  443. parameters["callback_id"] = AddFacebookDelegate(callback);
  444. }
  445. CallFB("PublishInstall", MiniJSON.Json.Serialize(parameters));
  446. }
  447. public void OnPublishInstallComplete(string message)
  448. {
  449. var response = (Dictionary<string, object>)MiniJSON.Json.Deserialize(message);
  450. if (response.ContainsKey("callback_id"))
  451. {
  452. OnFacebookResponse((string)response["callback_id"], new FBResult(""));
  453. }
  454. }
  455. private Dictionary<string, string> ToStringDict(Dictionary<string, object> dict)
  456. {
  457. if (dict == null)
  458. {
  459. return null;
  460. }
  461. var newDict = new Dictionary<string, string>();
  462. foreach (KeyValuePair<string, object> kvp in dict)
  463. {
  464. newDict[kvp.Key] = kvp.Value.ToString();
  465. }
  466. return newDict;
  467. }
  468. //TODO: move into AbstractFacebook
  469. private DateTime FromTimestamp(int timestamp)
  470. {
  471. return new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(timestamp);
  472. }
  473. #endregion
  474. }
  475. }