FBWrapper.mm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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. if (accessToken.length) {
  138. [self reply:request data:@{@"accessToken": accessToken, @"tokenType": @"access"} cancelled:NO error:nil];
  139. } else if (authenticationToken.length) {
  140. // The standard entry point generates its own nonce. Return the
  141. // SDK token's nonce, never an unrelated locally generated value.
  142. NSString *nonce = result.authenticationToken.nonce;
  143. if (!nonce.length) {
  144. [self reply:request data:nil cancelled:NO error:@"Facebook 身份令牌缺少 nonce。"];
  145. return;
  146. }
  147. [self reply:request data:@{@"authenticationToken": authenticationToken,
  148. @"tokenType": @"authentication", @"nonce": nonce} cancelled:NO error:nil];
  149. } else {
  150. [self reply:request data:nil cancelled:NO error:@"Facebook 登录未返回有效令牌。"];
  151. }
  152. });
  153. };
  154. if (hasFacebookApp) {
  155. // Same entry point as Unity startLogin:scope:isPublishPermLogin:.
  156. // nil asks the SDK to find its presenting view controller automatically.
  157. [self.loginManager logInWithPermissions:permissions
  158. fromViewController:nil
  159. handler:loginHandler];
  160. } else {
  161. // Same configuration-based entry point as Unity loginWithTrackingPreference:.
  162. FBSDKLoginConfiguration *config = [[FBSDKLoginConfiguration alloc]
  163. initWithPermissions:permissions tracking:FBSDKLoginTrackingLimited
  164. nonce:NSUUID.UUID.UUIDString appSwitch:FBSDKAppSwitchDisabled];
  165. if (!config) {
  166. self.loginPending = NO;
  167. [self reply:request data:nil cancelled:NO error:@"Facebook 登录配置创建失败。"];
  168. return;
  169. }
  170. [self.loginManager logInFromViewController:nil configuration:config completion:loginHandler];
  171. }
  172. }
  173. - (void)share:(NSDictionary *)request params:(NSDictionary *)params {
  174. if (self.shareRequest || self.loginPending || !self.presenter) {
  175. [self reply:request data:nil cancelled:NO error:@"已有 Facebook 操作进行中,或没有可用窗口。"];
  176. return;
  177. }
  178. NSString *value = [params[@"url"] isKindOfClass:NSString.class] ? params[@"url"] : @"";
  179. NSURL *url = [NSURL URLWithString:value];
  180. if (!url.host.length || ![@[@"https", @"http"] containsObject:url.scheme.lowercaseString]) {
  181. [self reply:request data:nil cancelled:NO error:@"分享链接必须为有效的 HTTP(S) URL。"];
  182. return;
  183. }
  184. FBSDKShareLinkContent *content = [FBSDKShareLinkContent new];
  185. content.contentURL = url;
  186. if ([params[@"quote"] isKindOfClass:NSString.class]) content.quote = params[@"quote"];
  187. if ([params[@"hashtag"] isKindOfClass:NSString.class] && [params[@"hashtag"] length]) {
  188. content.hashtag = [[FBSDKHashtag alloc] initWithString:params[@"hashtag"]];
  189. }
  190. self.shareRequest = request;
  191. self.shareDialog = [[FBSDKShareDialog alloc] initWithViewController:self.presenter content:content delegate:self];
  192. self.shareDialog.mode = FBSDKShareDialogModeAutomatic;
  193. if (![self.shareDialog canShow] || ![self.shareDialog show]) {
  194. if (self.shareRequest) [self reply:request data:nil cancelled:NO error:@"无法打开 Facebook 分享窗口。"];
  195. self.shareRequest = nil;
  196. self.shareDialog = nil;
  197. }
  198. }
  199. - (void)sharer:(id<FBSDKSharing>)sharer didCompleteWithResults:(NSDictionary *)results {
  200. if (self.shareRequest) [self reply:self.shareRequest data:@{@"postId": results[@"postId"] ?: @""} cancelled:NO error:nil];
  201. self.shareRequest = nil; self.shareDialog = nil;
  202. }
  203. - (void)sharer:(id<FBSDKSharing>)sharer didFailWithError:(NSError *)error {
  204. if (self.shareRequest) [self reply:self.shareRequest data:nil cancelled:NO error:error.localizedDescription];
  205. self.shareRequest = nil; self.shareDialog = nil;
  206. }
  207. - (void)sharerDidCancel:(id<FBSDKSharing>)sharer {
  208. if (self.shareRequest) [self reply:self.shareRequest data:nil cancelled:YES error:nil];
  209. self.shareRequest = nil; self.shareDialog = nil;
  210. }
  211. - (void)event:(NSDictionary *)request params:(NSDictionary *)params {
  212. NSString *method = request[@"method"];
  213. NSDictionary *values = params[@"parameters"] ?: @{};
  214. if (![values isKindOfClass:NSDictionary.class]) {
  215. [self reply:request data:nil cancelled:NO error:@"事件参数必须为字典。"];
  216. return;
  217. }
  218. for (id key in values) {
  219. id value = values[key];
  220. if (![key isKindOfClass:NSString.class] ||
  221. (![value isKindOfClass:NSString.class] && ![value isKindOfClass:NSNumber.class])) {
  222. [self reply:request data:nil cancelled:NO error:@"事件参数只支持字符串或数字。"];
  223. return;
  224. }
  225. }
  226. if ([method isEqualToString:@"flushEvents"]) {
  227. [FBSDKAppEvents.shared flush];
  228. } else if ([method isEqualToString:@"logPurchase"]) {
  229. NSNumber *amount = params[@"amount"];
  230. NSString *currency = params[@"currency"];
  231. if (![amount isKindOfClass:NSNumber.class] || !std::isfinite(amount.doubleValue) || amount.doubleValue < 0 ||
  232. ![currency isKindOfClass:NSString.class] ||
  233. [currency rangeOfString:@"^[A-Za-z]{3}$" options:NSRegularExpressionSearch].location == NSNotFound) {
  234. [self reply:request data:nil cancelled:NO error:@"购买金额或 ISO 4217 货币代码无效。"];
  235. return;
  236. }
  237. [FBSDKAppEvents.shared logPurchase:amount.doubleValue currency:currency.uppercaseString parameters:values];
  238. } else {
  239. NSString *name = params[@"eventName"];
  240. NSNumber *sum = params[@"valueToSum"];
  241. if (![name isKindOfClass:NSString.class] || !name.length ||
  242. (sum && (![sum isKindOfClass:NSNumber.class] || !std::isfinite(sum.doubleValue)))) {
  243. [self reply:request data:nil cancelled:NO error:@"事件名称或累计数值无效。"];
  244. return;
  245. }
  246. if (sum) [FBSDKAppEvents.shared logEvent:name valueToSum:sum.doubleValue parameters:values];
  247. else [FBSDKAppEvents.shared logEvent:name parameters:values];
  248. }
  249. // Accepted by the local SDK, not a delivery receipt from Meta.
  250. [self reply:request data:@{@"accepted": @YES} cancelled:NO error:nil];
  251. }
  252. @end