FBWrapper.mm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. #import "FBWrapper.h"
  2. // Swift-generated headers need these protocol definitions when compiled as Objective-C++.
  3. #import <SafariServices/SafariServices.h>
  4. #import <AuthenticationServices/AuthenticationServices.h>
  5. #import <FBSDKCoreKit/FBSDKCoreKit.h>
  6. #import <FBSDKCoreKit/FBSDKCoreKit-Swift.h>
  7. #import <FBSDKLoginKit/FBSDKLoginKit.h>
  8. #import <FBSDKLoginKit/FBSDKLoginKit-Swift.h>
  9. #import <FBSDKShareKit/FBSDKShareKit.h>
  10. #import <FBSDKShareKit/FBSDKShareKit-Swift.h>
  11. #import "platform/apple/JsbBridgeWrapper.h"
  12. #include "application/ApplicationManager.h"
  13. #include "application/BaseApplication.h"
  14. #include "base/Scheduler.h"
  15. #include "engine/BaseEngine.h"
  16. #include <cmath>
  17. @interface FBWrapper () <FBSDKSharingDelegate>
  18. @property(nonatomic, strong) FBSDKLoginManager *loginManager;
  19. @property(nonatomic, strong) FBSDKShareDialog *shareDialog;
  20. @property(nonatomic, strong) NSDictionary *shareRequest;
  21. @property(nonatomic, copy) NSString *startupError;
  22. @property(nonatomic) BOOL loginPending;
  23. @end
  24. @implementation FBWrapper
  25. + (instancetype)shared {
  26. static FBWrapper *instance;
  27. static dispatch_once_t once;
  28. dispatch_once(&once, ^{ instance = [FBWrapper new]; });
  29. return instance;
  30. }
  31. - (void)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options {
  32. // Register even on configuration failure so JS receives a useful error instead of timing out.
  33. // Creator 3.8.8's MRC bridge releases the listener after adding it to its array.
  34. // Keep this outer block capture-free (no self or local variables): a global block
  35. // has static lifetime and is safe with that ownership behavior. GCD owns the
  36. // inner block and retains its payload until the main-queue callback runs.
  37. static OnScriptEventListener const requestListener = ^(NSString *payload) {
  38. dispatch_async(dispatch_get_main_queue(), ^{
  39. [[FBWrapper shared] handlePayload:payload];
  40. });
  41. };
  42. [[JsbBridgeWrapper sharedInstance] addScriptEventListener:@"facebook.request" listener:requestListener];
  43. NSDictionary *info = NSBundle.mainBundle.infoDictionary;
  44. if (![info[@"FacebookAppID"] isKindOfClass:NSString.class] || ![info[@"FacebookAppID"] length] ||
  45. ![info[@"FacebookClientToken"] isKindOfClass:NSString.class] || ![info[@"FacebookClientToken"] length]) {
  46. self.startupError = @"请在 native/engine/ios/Info.plist 中填写 FacebookAppID 和 FacebookClientToken。";
  47. return;
  48. }
  49. @try {
  50. [[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:options];
  51. self.loginManager = [FBSDKLoginManager new];
  52. } @catch (NSException *exception) {
  53. self.startupError = exception.reason ?: @"Facebook 初始化失败。";
  54. }
  55. }
  56. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary *)options {
  57. if (!self.loginManager) return NO;
  58. return [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url options:options];
  59. }
  60. - (void)reply:(NSDictionary *)request data:(NSDictionary *)data cancelled:(BOOL)cancelled error:(NSString *)error {
  61. NSMutableDictionary *response = [@{@"requestId": request[@"requestId"] ?: @"",
  62. @"method": request[@"method"] ?: @"", @"success": @(!error), @"cancelled": @(cancelled)} mutableCopy];
  63. if (data) response[@"data"] = data;
  64. if (error) response[@"error"] = @{@"code": @"FACEBOOK_IOS_ERROR", @"message": error};
  65. NSData *json = [NSJSONSerialization dataWithJSONObject:response options:0 error:nil];
  66. NSString *payload = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
  67. auto app = CC_CURRENT_APPLICATION();
  68. if (!app || !app->getEngine() || !payload) return;
  69. app->getEngine()->getScheduler()->performFunctionInCocosThread([payload]() {
  70. [[JsbBridgeWrapper sharedInstance] dispatchEventToScript:@"facebook.response" arg:payload];
  71. });
  72. }
  73. - (UIViewController *)presenter {
  74. UIViewController *controller = UIApplication.sharedApplication.delegate.window.rootViewController;
  75. while (controller.presentedViewController) controller = controller.presentedViewController;
  76. return controller;
  77. }
  78. - (void)handlePayload:(NSString *)payload {
  79. id decoded = [NSJSONSerialization JSONObjectWithData:[payload dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
  80. if (![decoded isKindOfClass:NSDictionary.class]) return;
  81. NSDictionary *request = decoded;
  82. if (![request[@"requestId"] isKindOfClass:NSString.class] || ![request[@"method"] isKindOfClass:NSString.class]) return;
  83. NSString *method = request[@"method"];
  84. NSDictionary *params = [request[@"params"] isKindOfClass:NSDictionary.class] ? request[@"params"] : @{};
  85. @try {
  86. if (!self.loginManager) {
  87. [self reply:request data:nil cancelled:NO error:self.startupError ?: @"Facebook SDK 未初始化。"];
  88. } else if ([method isEqualToString:@"init"]) {
  89. [self reply:request data:@{} cancelled:NO error:nil];
  90. } else if ([method isEqualToString:@"login"]) {
  91. [self login:request];
  92. } else if ([method isEqualToString:@"logout"]) {
  93. if (self.loginPending) {
  94. [self reply:request data:nil cancelled:NO error:@"Facebook 登录仍在进行中。"];
  95. return;
  96. }
  97. [self.loginManager logOut];
  98. [self reply:request data:@{} cancelled:NO error:nil];
  99. } else if ([method isEqualToString:@"share"]) {
  100. [self share:request params:params];
  101. } else if ([method isEqualToString:@"logEvent"] || [method isEqualToString:@"logPurchase"] || [method isEqualToString:@"flushEvents"]) {
  102. [self event:request params:params];
  103. } else {
  104. [self reply:request data:nil cancelled:NO error:@"不支持的 Facebook 方法。"];
  105. }
  106. } @catch (NSException *exception) {
  107. if ([method isEqualToString:@"login"]) self.loginPending = NO;
  108. if ([method isEqualToString:@"share"]) { self.shareRequest = nil; self.shareDialog = nil; }
  109. [self reply:request data:nil cancelled:NO error:exception.reason ?: @"Facebook SDK 调用失败。"];
  110. }
  111. }
  112. - (void)login:(NSDictionary *)request {
  113. if (self.loginPending || self.shareRequest || !self.presenter) {
  114. [self reply:request data:nil cancelled:NO error:@"已有 Facebook 操作进行中,或没有可用窗口。"];
  115. return;
  116. }
  117. if (UIApplication.sharedApplication.applicationState != UIApplicationStateActive) {
  118. [self reply:request data:nil cancelled:NO error:@"请返回游戏前台后重试 Facebook 登录。"];
  119. return;
  120. }
  121. BOOL hasFacebookApp = [UIApplication.sharedApplication canOpenURL:[NSURL URLWithString:@"fbapi://"]] &&
  122. [UIApplication.sharedApplication canOpenURL:[NSURL URLWithString:@"fbauth2://"]];
  123. NSArray<NSString *> *permissions = @[@"public_profile", @"email"];
  124. // Match Unity FBUnityInterface: create a manager for this login and let the
  125. // SDK handle the standard flow. Retain it through the asynchronous callback.
  126. self.loginManager = [[FBSDKLoginManager alloc] init];
  127. self.loginPending = YES;
  128. void (^loginHandler)(FBSDKLoginManagerLoginResult *, NSError *) = ^(FBSDKLoginManagerLoginResult *result, NSError *error) {
  129. dispatch_async(dispatch_get_main_queue(), ^{
  130. self.loginPending = NO;
  131. if (error || result.isCancelled) {
  132. [self reply:request data:nil cancelled:!error && result.isCancelled error:error.localizedDescription];
  133. return;
  134. }
  135. NSString *accessToken = result.token.tokenString;
  136. NSString *authenticationToken = result.authenticationToken.tokenString;
  137. FBSDKProfile *profile = FBSDKProfile.currentProfile;
  138. NSString *userID = result.token.userID.length ? result.token.userID : profile.userID;
  139. // Do not attach a cached profile's name to a different token's user.
  140. NSString *name = [profile.userID isEqualToString:userID] ? profile.name : nil;
  141. NSDictionary *userInfo = @{@"userId": userID ?: @"", @"name": name ?: @""};
  142. if (accessToken.length) {
  143. NSMutableDictionary *data = [userInfo mutableCopy];
  144. data[@"accessToken"] = accessToken;
  145. data[@"tokenType"] = @"access";
  146. [self reply:request data:data cancelled:NO error:nil];
  147. } else if (authenticationToken.length) {
  148. // The standard entry point generates its own nonce. Return the
  149. // SDK token's nonce, never an unrelated locally generated value.
  150. NSString *nonce = result.authenticationToken.nonce;
  151. if (!nonce.length) {
  152. [self reply:request data:nil cancelled:NO error:@"Facebook 身份令牌缺少 nonce。"];
  153. return;
  154. }
  155. NSMutableDictionary *data = [userInfo mutableCopy];
  156. data[@"authenticationToken"] = authenticationToken;
  157. data[@"tokenType"] = @"authentication";
  158. data[@"nonce"] = nonce;
  159. [self reply:request data:data cancelled:NO error:nil];
  160. } else {
  161. [self reply:request data:nil cancelled:NO error:@"Facebook 登录未返回有效令牌。"];
  162. }
  163. });
  164. };
  165. if (hasFacebookApp) {
  166. // Same entry point as Unity startLogin:scope:isPublishPermLogin:.
  167. // nil asks the SDK to find its presenting view controller automatically.
  168. [self.loginManager logInWithPermissions:permissions
  169. fromViewController:nil
  170. handler:loginHandler];
  171. } else {
  172. // Same configuration-based entry point as Unity loginWithTrackingPreference:.
  173. FBSDKLoginConfiguration *config = [[FBSDKLoginConfiguration alloc]
  174. initWithPermissions:permissions tracking:FBSDKLoginTrackingLimited
  175. nonce:NSUUID.UUID.UUIDString appSwitch:FBSDKAppSwitchDisabled];
  176. if (!config) {
  177. self.loginPending = NO;
  178. [self reply:request data:nil cancelled:NO error:@"Facebook 登录配置创建失败。"];
  179. return;
  180. }
  181. [self.loginManager logInFromViewController:nil configuration:config completion:loginHandler];
  182. }
  183. }
  184. - (void)share:(NSDictionary *)request params:(NSDictionary *)params {
  185. if (self.shareRequest || self.loginPending || !self.presenter) {
  186. [self reply:request data:nil cancelled:NO error:@"已有 Facebook 操作进行中,或没有可用窗口。"];
  187. return;
  188. }
  189. NSString *value = [params[@"url"] isKindOfClass:NSString.class] ? params[@"url"] : @"";
  190. NSURL *url = [NSURL URLWithString:value];
  191. if (!url.host.length || ![@[@"https", @"http"] containsObject:url.scheme.lowercaseString]) {
  192. [self reply:request data:nil cancelled:NO error:@"分享链接必须为有效的 HTTP(S) URL。"];
  193. return;
  194. }
  195. FBSDKShareLinkContent *content = [FBSDKShareLinkContent new];
  196. content.contentURL = url;
  197. if ([params[@"quote"] isKindOfClass:NSString.class]) content.quote = params[@"quote"];
  198. if ([params[@"hashtag"] isKindOfClass:NSString.class] && [params[@"hashtag"] length]) {
  199. content.hashtag = [[FBSDKHashtag alloc] initWithString:params[@"hashtag"]];
  200. }
  201. self.shareRequest = request;
  202. self.shareDialog = [[FBSDKShareDialog alloc] initWithViewController:self.presenter content:content delegate:self];
  203. self.shareDialog.mode = FBSDKShareDialogModeAutomatic;
  204. if (![self.shareDialog canShow] || ![self.shareDialog show]) {
  205. if (self.shareRequest) [self reply:request data:nil cancelled:NO error:@"无法打开 Facebook 分享窗口。"];
  206. self.shareRequest = nil;
  207. self.shareDialog = nil;
  208. }
  209. }
  210. - (void)sharer:(id<FBSDKSharing>)sharer didCompleteWithResults:(NSDictionary *)results {
  211. if (self.shareRequest) [self reply:self.shareRequest data:@{@"postId": results[@"postId"] ?: @""} cancelled:NO error:nil];
  212. self.shareRequest = nil; self.shareDialog = nil;
  213. }
  214. - (void)sharer:(id<FBSDKSharing>)sharer didFailWithError:(NSError *)error {
  215. if (self.shareRequest) [self reply:self.shareRequest data:nil cancelled:NO error:error.localizedDescription];
  216. self.shareRequest = nil; self.shareDialog = nil;
  217. }
  218. - (void)sharerDidCancel:(id<FBSDKSharing>)sharer {
  219. if (self.shareRequest) [self reply:self.shareRequest data:nil cancelled:YES error:nil];
  220. self.shareRequest = nil; self.shareDialog = nil;
  221. }
  222. - (void)event:(NSDictionary *)request params:(NSDictionary *)params {
  223. NSString *method = request[@"method"];
  224. NSDictionary *values = params[@"parameters"] ?: @{};
  225. if (![values isKindOfClass:NSDictionary.class]) {
  226. [self reply:request data:nil cancelled:NO error:@"事件参数必须为字典。"];
  227. return;
  228. }
  229. for (id key in values) {
  230. id value = values[key];
  231. if (![key isKindOfClass:NSString.class] ||
  232. (![value isKindOfClass:NSString.class] && ![value isKindOfClass:NSNumber.class])) {
  233. [self reply:request data:nil cancelled:NO error:@"事件参数只支持字符串或数字。"];
  234. return;
  235. }
  236. }
  237. if ([method isEqualToString:@"flushEvents"]) {
  238. [FBSDKAppEvents.shared flush];
  239. } else if ([method isEqualToString:@"logPurchase"]) {
  240. NSNumber *amount = params[@"amount"];
  241. NSString *currency = params[@"currency"];
  242. if (![amount isKindOfClass:NSNumber.class] || !std::isfinite(amount.doubleValue) || amount.doubleValue < 0 ||
  243. ![currency isKindOfClass:NSString.class] ||
  244. [currency rangeOfString:@"^[A-Za-z]{3}$" options:NSRegularExpressionSearch].location == NSNotFound) {
  245. [self reply:request data:nil cancelled:NO error:@"购买金额或 ISO 4217 货币代码无效。"];
  246. return;
  247. }
  248. [FBSDKAppEvents.shared logPurchase:amount.doubleValue currency:currency.uppercaseString parameters:values];
  249. } else {
  250. NSString *name = params[@"eventName"];
  251. NSNumber *sum = params[@"valueToSum"];
  252. if (![name isKindOfClass:NSString.class] || !name.length ||
  253. (sum && (![sum isKindOfClass:NSNumber.class] || !std::isfinite(sum.doubleValue)))) {
  254. [self reply:request data:nil cancelled:NO error:@"事件名称或累计数值无效。"];
  255. return;
  256. }
  257. if (sum) [FBSDKAppEvents.shared logEvent:name valueToSum:sum.doubleValue parameters:values];
  258. else [FBSDKAppEvents.shared logEvent:name parameters:values];
  259. }
  260. // Accepted by the local SDK, not a delivery receipt from Meta.
  261. [self reply:request data:@{@"accepted": @YES} cancelled:NO error:nil];
  262. }
  263. @end