FBWrapper.mm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. // Limited Login works without an ATT prompt. Each attempt gets its own nonce.
  118. NSString *nonce = NSUUID.UUID.UUIDString;
  119. FBSDKLoginConfiguration *config = [[FBSDKLoginConfiguration alloc]
  120. initWithPermissions:@[@"public_profile", @"email"] tracking:FBSDKLoginTrackingLimited nonce:nonce];
  121. self.loginPending = YES;
  122. [self.loginManager logInFromViewController:self.presenter configuration:config
  123. completion:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
  124. self.loginPending = NO;
  125. if (error) { [self reply:request data:nil cancelled:NO error:error.localizedDescription]; return; }
  126. if (result.isCancelled) { [self reply:request data:nil cancelled:YES error:nil]; return; }
  127. NSString *token = result.authenticationToken.tokenString;
  128. if (!token.length) { [self reply:request data:nil cancelled:NO error:@"Facebook 未返回身份令牌。"] ; return; }
  129. [self reply:request data:@{@"authenticationToken": token, @"nonce": nonce} cancelled:NO error:nil];
  130. }];
  131. }
  132. - (void)share:(NSDictionary *)request params:(NSDictionary *)params {
  133. if (self.shareRequest || self.loginPending || !self.presenter) {
  134. [self reply:request data:nil cancelled:NO error:@"已有 Facebook 操作进行中,或没有可用窗口。"];
  135. return;
  136. }
  137. NSString *value = [params[@"url"] isKindOfClass:NSString.class] ? params[@"url"] : @"";
  138. NSURL *url = [NSURL URLWithString:value];
  139. if (!url.host.length || ![@[@"https", @"http"] containsObject:url.scheme.lowercaseString]) {
  140. [self reply:request data:nil cancelled:NO error:@"分享链接必须为有效的 HTTP(S) URL。"];
  141. return;
  142. }
  143. FBSDKShareLinkContent *content = [FBSDKShareLinkContent new];
  144. content.contentURL = url;
  145. if ([params[@"quote"] isKindOfClass:NSString.class]) content.quote = params[@"quote"];
  146. if ([params[@"hashtag"] isKindOfClass:NSString.class] && [params[@"hashtag"] length]) {
  147. content.hashtag = [[FBSDKHashtag alloc] initWithString:params[@"hashtag"]];
  148. }
  149. self.shareRequest = request;
  150. self.shareDialog = [[FBSDKShareDialog alloc] initWithViewController:self.presenter content:content delegate:self];
  151. self.shareDialog.mode = FBSDKShareDialogModeAutomatic;
  152. if (![self.shareDialog canShow] || ![self.shareDialog show]) {
  153. if (self.shareRequest) [self reply:request data:nil cancelled:NO error:@"无法打开 Facebook 分享窗口。"];
  154. self.shareRequest = nil;
  155. self.shareDialog = nil;
  156. }
  157. }
  158. - (void)sharer:(id<FBSDKSharing>)sharer didCompleteWithResults:(NSDictionary *)results {
  159. if (self.shareRequest) [self reply:self.shareRequest data:@{@"postId": results[@"postId"] ?: @""} cancelled:NO error:nil];
  160. self.shareRequest = nil; self.shareDialog = nil;
  161. }
  162. - (void)sharer:(id<FBSDKSharing>)sharer didFailWithError:(NSError *)error {
  163. if (self.shareRequest) [self reply:self.shareRequest data:nil cancelled:NO error:error.localizedDescription];
  164. self.shareRequest = nil; self.shareDialog = nil;
  165. }
  166. - (void)sharerDidCancel:(id<FBSDKSharing>)sharer {
  167. if (self.shareRequest) [self reply:self.shareRequest data:nil cancelled:YES error:nil];
  168. self.shareRequest = nil; self.shareDialog = nil;
  169. }
  170. - (void)event:(NSDictionary *)request params:(NSDictionary *)params {
  171. NSString *method = request[@"method"];
  172. NSDictionary *values = params[@"parameters"] ?: @{};
  173. if (![values isKindOfClass:NSDictionary.class]) {
  174. [self reply:request data:nil cancelled:NO error:@"事件参数必须为字典。"];
  175. return;
  176. }
  177. for (id key in values) {
  178. id value = values[key];
  179. if (![key isKindOfClass:NSString.class] ||
  180. (![value isKindOfClass:NSString.class] && ![value isKindOfClass:NSNumber.class])) {
  181. [self reply:request data:nil cancelled:NO error:@"事件参数只支持字符串或数字。"];
  182. return;
  183. }
  184. }
  185. if ([method isEqualToString:@"flushEvents"]) {
  186. [FBSDKAppEvents.shared flush];
  187. } else if ([method isEqualToString:@"logPurchase"]) {
  188. NSNumber *amount = params[@"amount"];
  189. NSString *currency = params[@"currency"];
  190. if (![amount isKindOfClass:NSNumber.class] || !std::isfinite(amount.doubleValue) || amount.doubleValue < 0 ||
  191. ![currency isKindOfClass:NSString.class] ||
  192. [currency rangeOfString:@"^[A-Za-z]{3}$" options:NSRegularExpressionSearch].location == NSNotFound) {
  193. [self reply:request data:nil cancelled:NO error:@"购买金额或 ISO 4217 货币代码无效。"];
  194. return;
  195. }
  196. [FBSDKAppEvents.shared logPurchase:amount.doubleValue currency:currency.uppercaseString parameters:values];
  197. } else {
  198. NSString *name = params[@"eventName"];
  199. NSNumber *sum = params[@"valueToSum"];
  200. if (![name isKindOfClass:NSString.class] || !name.length ||
  201. (sum && (![sum isKindOfClass:NSNumber.class] || !std::isfinite(sum.doubleValue)))) {
  202. [self reply:request data:nil cancelled:NO error:@"事件名称或累计数值无效。"];
  203. return;
  204. }
  205. if (sum) [FBSDKAppEvents.shared logEvent:name valueToSum:sum.doubleValue parameters:values];
  206. else [FBSDKAppEvents.shared logEvent:name parameters:values];
  207. }
  208. // Accepted by the local SDK, not a delivery receipt from Meta.
  209. [self reply:request data:@{@"accepted": @YES} cancelled:NO error:nil];
  210. }
  211. @end