FIRCoreDiagnostics.m 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. /*
  2. * Copyright 2019 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import <objc/runtime.h>
  17. #include <sys/utsname.h>
  18. #import "GoogleDataTransport/GDTCORLibrary/Internal/GoogleDataTransportInternal.h"
  19. #import "GoogleUtilities/Environment/Private/GULAppEnvironmentUtil.h"
  20. #import "GoogleUtilities/Environment/Private/GULHeartbeatDateStorage.h"
  21. #import "GoogleUtilities/Logger/Private/GULLogger.h"
  22. #import "Interop/CoreDiagnostics/Public/FIRCoreDiagnosticsData.h"
  23. #import "Interop/CoreDiagnostics/Public/FIRCoreDiagnosticsInterop.h"
  24. #import <nanopb/pb.h>
  25. #import <nanopb/pb_decode.h>
  26. #import <nanopb/pb_encode.h>
  27. #import "Firebase/CoreDiagnostics/FIRCDLibrary/Protogen/nanopb/firebasecore.nanopb.h"
  28. /** The logger service string to use when printing to the console. */
  29. static GULLoggerService kFIRCoreDiagnostics = @"[FirebaseCoreDiagnostics/FIRCoreDiagnostics]";
  30. #ifdef FIREBASE_BUILD_ZIP_FILE
  31. static BOOL kUsingZipFile = YES;
  32. #else // FIREBASE_BUILD_ZIP_FILE
  33. static BOOL kUsingZipFile = NO;
  34. #endif // FIREBASE_BUILD_ZIP_FILE
  35. #if SWIFT_PACKAGE
  36. #define kDeploymentType logs_proto_mobilesdk_ios_ICoreConfiguration_DeploymentType_SPM
  37. #elif FIREBASE_BUILD_CARTHAGE
  38. #define kDeploymentType logs_proto_mobilesdk_ios_ICoreConfiguration_DeploymentType_CARTHAGE
  39. #elif FIREBASE_BUILD_ZIP_FILE
  40. #define kDeploymentType logs_proto_mobilesdk_ios_ICoreConfiguration_DeploymentType_ZIP_FILE
  41. #else
  42. #define kDeploymentType logs_proto_mobilesdk_ios_ICoreConfiguration_DeploymentType_COCOAPODS
  43. #endif
  44. static NSString *const kFIRServiceMLVisionOnDeviceAutoML = @"MLVisionOnDeviceAutoML";
  45. static NSString *const kFIRServiceMLVisionOnDeviceFace = @"MLVisionOnDeviceFace";
  46. static NSString *const kFIRServiceMLVisionOnDeviceBarcode = @"MLVisionOnDeviceBarcode";
  47. static NSString *const kFIRServiceMLVisionOnDeviceText = @"MLVisionOnDeviceText";
  48. static NSString *const kFIRServiceMLVisionOnDeviceLabel = @"MLVisionOnDeviceLabel";
  49. static NSString *const kFIRServiceMLVisionOnDeviceObjectDetection =
  50. @"MLVisionOnDeviceObjectDetection";
  51. static NSString *const kFIRServiceMLModelInterpreter = @"MLModelInterpreter";
  52. static NSString *const kFIRServiceAdMob = @"AdMob";
  53. static NSString *const kFIRServiceAuth = @"Auth";
  54. static NSString *const kFIRServiceAuthUI = @"AuthUI";
  55. static NSString *const kFIRServiceCrash = @"Crash";
  56. static NSString *const kFIRServiceDatabase = @"Database";
  57. static NSString *const kFIRServiceDynamicLinks = @"DynamicLinks";
  58. static NSString *const kFIRServiceFirestore = @"Firestore";
  59. static NSString *const kFIRServiceFunctions = @"Functions";
  60. static NSString *const kFIRServiceIAM = @"InAppMessaging";
  61. static NSString *const kFIRServiceInstanceID = @"InstanceID";
  62. static NSString *const kFIRServiceInvites = @"Invites";
  63. static NSString *const kFIRServiceMessaging = @"Messaging";
  64. static NSString *const kFIRServiceMeasurement = @"Measurement";
  65. static NSString *const kFIRServicePerformance = @"Performance";
  66. static NSString *const kFIRServiceRemoteConfig = @"RemoteConfig";
  67. static NSString *const kFIRServiceStorage = @"Storage";
  68. static NSString *const kGGLServiceAnalytics = @"Analytics";
  69. static NSString *const kGGLServiceSignIn = @"SignIn";
  70. static NSString *const kFIRAppDiagnosticsConfigurationTypeKey =
  71. @"FIRAppDiagnosticsConfigurationTypeKey";
  72. static NSString *const kFIRAppDiagnosticsFIRAppKey = @"FIRAppDiagnosticsFIRAppKey";
  73. static NSString *const kFIRAppDiagnosticsSDKNameKey = @"FIRAppDiagnosticsSDKNameKey";
  74. static NSString *const kFIRAppDiagnosticsSDKVersionKey = @"FIRAppDiagnosticsSDKVersionKey";
  75. static NSString *const kFIRCoreDiagnosticsHeartbeatTag = @"FIRCoreDiagnostics";
  76. /**
  77. * The file name to the recent heartbeat date.
  78. */
  79. NSString *const kFIRCoreDiagnosticsHeartbeatDateFileName = @"FIREBASE_DIAGNOSTICS_HEARTBEAT_DATE";
  80. /**
  81. * @note This should implement the GDTCOREventDataObject protocol, but can't because of
  82. * weak-linking.
  83. */
  84. @interface FIRCoreDiagnosticsLog : NSObject
  85. /** The config that will be converted to proto bytes. */
  86. @property(nonatomic) logs_proto_mobilesdk_ios_ICoreConfiguration config;
  87. @end
  88. @implementation FIRCoreDiagnosticsLog
  89. - (instancetype)initWithConfig:(logs_proto_mobilesdk_ios_ICoreConfiguration)config {
  90. self = [super init];
  91. if (self) {
  92. _config = config;
  93. }
  94. return self;
  95. }
  96. // Provided and required by the GDTCOREventDataObject protocol.
  97. - (NSData *)transportBytes {
  98. pb_ostream_t sizestream = PB_OSTREAM_SIZING;
  99. // Encode 1 time to determine the size.
  100. if (!pb_encode(&sizestream, logs_proto_mobilesdk_ios_ICoreConfiguration_fields, &_config)) {
  101. GDTCORLogError(GDTCORMCETransportBytesError, @"Error in nanopb encoding for size: %s",
  102. PB_GET_ERROR(&sizestream));
  103. }
  104. // Encode a 2nd time to actually get the bytes from it.
  105. size_t bufferSize = sizestream.bytes_written;
  106. CFMutableDataRef dataRef = CFDataCreateMutable(CFAllocatorGetDefault(), bufferSize);
  107. CFDataSetLength(dataRef, bufferSize);
  108. pb_ostream_t ostream = pb_ostream_from_buffer((void *)CFDataGetBytePtr(dataRef), bufferSize);
  109. if (!pb_encode(&ostream, logs_proto_mobilesdk_ios_ICoreConfiguration_fields, &_config)) {
  110. GDTCORLogError(GDTCORMCETransportBytesError, @"Error in nanopb encoding for bytes: %s",
  111. PB_GET_ERROR(&ostream));
  112. }
  113. CFDataSetLength(dataRef, ostream.bytes_written);
  114. return CFBridgingRelease(dataRef);
  115. }
  116. - (void)dealloc {
  117. pb_release(logs_proto_mobilesdk_ios_ICoreConfiguration_fields, &_config);
  118. }
  119. @end
  120. NS_ASSUME_NONNULL_BEGIN
  121. /** This class produces a protobuf containing diagnostics and usage data to be logged. */
  122. @interface FIRCoreDiagnostics : NSObject <FIRCoreDiagnosticsInterop>
  123. /** The queue on which all diagnostics collection will occur. */
  124. @property(nonatomic, readonly) dispatch_queue_t diagnosticsQueue;
  125. /** The transport object used to send data. */
  126. @property(nonatomic, readonly) GDTCORTransport *transport;
  127. /** The storage to store the date of the last sent heartbeat. */
  128. @property(nonatomic, readonly) GULHeartbeatDateStorage *heartbeatDateStorage;
  129. @end
  130. NS_ASSUME_NONNULL_END
  131. @implementation FIRCoreDiagnostics
  132. + (instancetype)sharedInstance {
  133. static FIRCoreDiagnostics *sharedInstance;
  134. static dispatch_once_t onceToken;
  135. dispatch_once(&onceToken, ^{
  136. sharedInstance = [[FIRCoreDiagnostics alloc] init];
  137. });
  138. return sharedInstance;
  139. }
  140. - (instancetype)init {
  141. GDTCORTransport *transport = [[GDTCORTransport alloc] initWithMappingID:@"137"
  142. transformers:nil
  143. target:kGDTCORTargetFLL];
  144. GULHeartbeatDateStorage *dateStorage =
  145. [[GULHeartbeatDateStorage alloc] initWithFileName:kFIRCoreDiagnosticsHeartbeatDateFileName];
  146. return [self initWithTransport:transport heartbeatDateStorage:dateStorage];
  147. }
  148. /** Initializer for unit tests.
  149. *
  150. * @param transport A `GDTCORTransport` instance which that be used to send event.
  151. * @param heartbeatDateStorage An instanse of date storage to track heartbeat sending.
  152. * @return Returns the initialized `FIRCoreDiagnostics` instance.
  153. */
  154. - (instancetype)initWithTransport:(GDTCORTransport *)transport
  155. heartbeatDateStorage:(GULHeartbeatDateStorage *)heartbeatDateStorage {
  156. self = [super init];
  157. if (self) {
  158. _diagnosticsQueue =
  159. dispatch_queue_create("com.google.FIRCoreDiagnostics", DISPATCH_QUEUE_SERIAL);
  160. _transport = transport;
  161. _heartbeatDateStorage = heartbeatDateStorage;
  162. }
  163. return self;
  164. }
  165. #pragma mark - Metadata helpers
  166. /** Returns the model of iOS device. Sample platform strings are @"iPhone7,1" for iPhone 6 Plus,
  167. * @"iPhone7,2" for iPhone 6, etc. Refer to the Hardware strings at
  168. * https://en.wikipedia.org/wiki/List_of_iOS_devices
  169. *
  170. * @return The device model as an NSString.
  171. */
  172. + (NSString *)deviceModel {
  173. static NSString *deviceModel = nil;
  174. if (deviceModel == nil) {
  175. struct utsname systemInfo;
  176. uname(&systemInfo);
  177. deviceModel = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
  178. }
  179. return deviceModel;
  180. }
  181. #pragma mark - nanopb helper functions
  182. /** Callocs a pb_bytes_array and copies the given NSString's bytes into the bytes array.
  183. *
  184. * @note Memory needs to be free manually, through pb_free or pb_release.
  185. * @param string The string to encode as pb_bytes.
  186. */
  187. pb_bytes_array_t *FIREncodeString(NSString *string) {
  188. NSData *stringBytes = [string dataUsingEncoding:NSUTF8StringEncoding];
  189. return FIREncodeData(stringBytes);
  190. }
  191. /** Callocs a pb_bytes_array and copies the given NSData bytes into the bytes array.
  192. *
  193. * @note Memory needs to be free manually, through pb_free or pb_release.
  194. * @param data The data to copy into the new bytes array.
  195. */
  196. pb_bytes_array_t *FIREncodeData(NSData *data) {
  197. pb_bytes_array_t *pbBytesArray = calloc(1, PB_BYTES_ARRAY_T_ALLOCSIZE(data.length));
  198. if (pbBytesArray != NULL) {
  199. [data getBytes:pbBytesArray->bytes length:data.length];
  200. pbBytesArray->size = (pb_size_t)data.length;
  201. }
  202. return pbBytesArray;
  203. }
  204. /** Maps a service string to the representative nanopb enum.
  205. *
  206. * @param serviceString The SDK service string to convert.
  207. * @return The representative nanopb enum.
  208. */
  209. logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType FIRMapFromServiceStringToTypeEnum(
  210. NSString *serviceString) {
  211. static NSDictionary<NSString *, NSNumber *> *serviceStringToTypeEnum;
  212. if (serviceStringToTypeEnum == nil) {
  213. serviceStringToTypeEnum = @{
  214. kFIRServiceAdMob : @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_ADMOB),
  215. kFIRServiceMessaging : @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_MESSAGING),
  216. kFIRServiceMeasurement :
  217. @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_MEASUREMENT),
  218. kFIRServiceRemoteConfig :
  219. @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_REMOTE_CONFIG),
  220. kFIRServiceDatabase : @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_DATABASE),
  221. kFIRServiceDynamicLinks :
  222. @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_DYNAMIC_LINKS),
  223. kFIRServiceAuth : @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_AUTH),
  224. kFIRServiceAuthUI : @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_AUTH_UI),
  225. kFIRServiceFirestore : @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_FIRESTORE),
  226. kFIRServiceFunctions : @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_FUNCTIONS),
  227. kFIRServicePerformance :
  228. @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_PERFORMANCE),
  229. kFIRServiceStorage : @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_STORAGE),
  230. kFIRServiceMLVisionOnDeviceAutoML :
  231. @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_ML_VISION_ON_DEVICE_AUTOML),
  232. kFIRServiceMLVisionOnDeviceFace :
  233. @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_ML_VISION_ON_DEVICE_FACE),
  234. kFIRServiceMLVisionOnDeviceBarcode :
  235. @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_ML_VISION_ON_DEVICE_BARCODE),
  236. kFIRServiceMLVisionOnDeviceText :
  237. @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_ML_VISION_ON_DEVICE_TEXT),
  238. kFIRServiceMLVisionOnDeviceLabel :
  239. @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_ML_VISION_ON_DEVICE_LABEL),
  240. kFIRServiceMLVisionOnDeviceObjectDetection : @(
  241. logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_ML_VISION_ON_DEVICE_OBJECT_DETECTION),
  242. kFIRServiceMLModelInterpreter :
  243. @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_ML_MODEL_INTERPRETER),
  244. kGGLServiceAnalytics : @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_ANALYTICS),
  245. kGGLServiceSignIn : @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_SIGN_IN),
  246. kFIRServiceIAM : @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_IN_APP_MESSAGING),
  247. };
  248. }
  249. if (serviceStringToTypeEnum[serviceString] != nil) {
  250. return (int32_t)serviceStringToTypeEnum[serviceString].longLongValue;
  251. }
  252. return logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_UNKNOWN_SDK_SERVICE;
  253. }
  254. #pragma mark - Proto population functions
  255. /** Populates the given proto with data related to an SDK logDiagnostics call from the
  256. * diagnosticObjects dictionary.
  257. *
  258. * @param config The proto to populate
  259. * @param diagnosticObjects The dictionary of diagnostics objects.
  260. */
  261. void FIRPopulateProtoWithInfoFromUserInfoParams(logs_proto_mobilesdk_ios_ICoreConfiguration *config,
  262. NSDictionary<NSString *, id> *diagnosticObjects) {
  263. NSNumber *configurationType = diagnosticObjects[kFIRCDConfigurationTypeKey];
  264. if (configurationType != nil) {
  265. switch (configurationType.integerValue) {
  266. case logs_proto_mobilesdk_ios_ICoreConfiguration_ConfigurationType_CORE:
  267. config->configuration_type =
  268. logs_proto_mobilesdk_ios_ICoreConfiguration_ConfigurationType_CORE;
  269. config->has_configuration_type = 1;
  270. break;
  271. case logs_proto_mobilesdk_ios_ICoreConfiguration_ConfigurationType_SDK:
  272. config->configuration_type =
  273. logs_proto_mobilesdk_ios_ICoreConfiguration_ConfigurationType_SDK;
  274. config->has_configuration_type = 1;
  275. break;
  276. default:
  277. break;
  278. }
  279. }
  280. NSString *sdkName = diagnosticObjects[kFIRCDSdkNameKey];
  281. if (sdkName) {
  282. config->sdk_name = FIRMapFromServiceStringToTypeEnum(sdkName);
  283. config->has_sdk_name = 1;
  284. }
  285. NSString *version = diagnosticObjects[kFIRCDSdkVersionKey];
  286. if (version) {
  287. config->sdk_version = FIREncodeString(version);
  288. }
  289. }
  290. /** Populates the given proto with data from the calling FIRApp using the given
  291. * diagnosticObjects dictionary.
  292. *
  293. * @param config The proto to populate
  294. * @param diagnosticObjects The dictionary of diagnostics objects.
  295. */
  296. void FIRPopulateProtoWithCommonInfoFromApp(logs_proto_mobilesdk_ios_ICoreConfiguration *config,
  297. NSDictionary<NSString *, id> *diagnosticObjects) {
  298. config->pod_name = logs_proto_mobilesdk_ios_ICoreConfiguration_PodName_FIREBASE;
  299. config->has_pod_name = 1;
  300. if (!diagnosticObjects[kFIRCDllAppsCountKey]) {
  301. GDTCORLogError(GDTCORMCEGeneralError, @"%@",
  302. @"App count is a required value in the data dict.");
  303. }
  304. config->app_count = (int32_t)[diagnosticObjects[kFIRCDllAppsCountKey] integerValue];
  305. config->has_app_count = 1;
  306. NSString *googleAppID = diagnosticObjects[kFIRCDGoogleAppIDKey];
  307. if (googleAppID.length) {
  308. config->app_id = FIREncodeString(googleAppID);
  309. }
  310. NSString *bundleID = diagnosticObjects[kFIRCDBundleIDKey];
  311. if (bundleID.length) {
  312. config->bundle_id = FIREncodeString(bundleID);
  313. }
  314. NSString *firebaseUserAgent = diagnosticObjects[kFIRCDFirebaseUserAgentKey];
  315. if (firebaseUserAgent.length) {
  316. config->platform_info = FIREncodeString(firebaseUserAgent);
  317. }
  318. NSNumber *usingOptionsFromDefaultPlist = diagnosticObjects[kFIRCDUsingOptionsFromDefaultPlistKey];
  319. if (usingOptionsFromDefaultPlist != nil) {
  320. config->use_default_app = [usingOptionsFromDefaultPlist boolValue];
  321. config->has_use_default_app = 1;
  322. }
  323. NSString *libraryVersionID = diagnosticObjects[kFIRCDLibraryVersionIDKey];
  324. if (libraryVersionID) {
  325. config->icore_version = FIREncodeString(libraryVersionID);
  326. }
  327. NSString *deviceModel = [FIRCoreDiagnostics deviceModel];
  328. if (deviceModel.length) {
  329. config->device_model = FIREncodeString(deviceModel);
  330. }
  331. NSString *osVersion = [GULAppEnvironmentUtil systemVersion];
  332. if (osVersion.length) {
  333. config->os_version = FIREncodeString(osVersion);
  334. }
  335. config->using_zip_file = kUsingZipFile;
  336. config->has_using_zip_file = 1;
  337. config->deployment_type = kDeploymentType;
  338. config->has_deployment_type = 1;
  339. config->deployed_in_app_store = [GULAppEnvironmentUtil isFromAppStore];
  340. config->has_deployed_in_app_store = 1;
  341. }
  342. /** Populates the given proto with installed services data.
  343. *
  344. * @param config The proto to populate
  345. */
  346. void FIRPopulateProtoWithInstalledServices(logs_proto_mobilesdk_ios_ICoreConfiguration *config) {
  347. NSMutableArray<NSNumber *> *sdkServiceInstalledArray = [NSMutableArray array];
  348. // AdMob
  349. if (NSClassFromString(@"GADBannerView") != nil) {
  350. [sdkServiceInstalledArray addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceAdMob))];
  351. }
  352. // CloudMessaging
  353. if (NSClassFromString(@"FIRMessaging") != nil) {
  354. [sdkServiceInstalledArray addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceMessaging))];
  355. }
  356. // RemoteConfig
  357. if (NSClassFromString(@"FIRRemoteConfig") != nil) {
  358. [sdkServiceInstalledArray
  359. addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceRemoteConfig))];
  360. }
  361. // Measurement/Analtyics
  362. if (NSClassFromString(@"FIRAnalytics") != nil) {
  363. [sdkServiceInstalledArray
  364. addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceMeasurement))];
  365. }
  366. // ML Vision On Device AutoML.
  367. if (NSClassFromString(@"FIRVisionOnDeviceAutoMLImageLabelerOptions") != nil) {
  368. [sdkServiceInstalledArray
  369. addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceMLVisionOnDeviceAutoML))];
  370. }
  371. // ML Vision On Device Face.
  372. if (NSClassFromString(@"FIRVisionFaceDetector") != nil &&
  373. NSClassFromString(@"GMVFaceDetector") != nil) {
  374. [sdkServiceInstalledArray
  375. addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceMLVisionOnDeviceFace))];
  376. }
  377. // ML Vision On Device Barcode.
  378. if (NSClassFromString(@"FIRVisionBarcodeDetector") != nil &&
  379. NSClassFromString(@"GMVBarcodeDetector") != nil) {
  380. [sdkServiceInstalledArray
  381. addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceMLVisionOnDeviceBarcode))];
  382. }
  383. // ML Vision On Device Text.
  384. if (NSClassFromString(@"FIRVisionTextDetector") != nil &&
  385. NSClassFromString(@"GMVTextDetector") != nil) {
  386. [sdkServiceInstalledArray
  387. addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceMLVisionOnDeviceText))];
  388. }
  389. // ML Vision On Device Image Label.
  390. if (NSClassFromString(@"FIRVisionLabelDetector") != nil &&
  391. NSClassFromString(@"GMVLabelDetector") != nil) {
  392. [sdkServiceInstalledArray
  393. addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceMLVisionOnDeviceLabel))];
  394. }
  395. // ML Vision On Device Object.
  396. if (NSClassFromString(@"FIRVisionObjectDetector") != nil) {
  397. [sdkServiceInstalledArray
  398. addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceMLVisionOnDeviceObjectDetection))];
  399. }
  400. // ML Model Interpreter
  401. if (NSClassFromString(@"FIRCustomModelInterpreter") != nil) {
  402. [sdkServiceInstalledArray
  403. addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceMLModelInterpreter))];
  404. }
  405. // Database
  406. if (NSClassFromString(@"FIRDatabase") != nil) {
  407. [sdkServiceInstalledArray addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceDatabase))];
  408. }
  409. // DynamicDeepLink
  410. if (NSClassFromString(@"FIRDynamicLinks") != nil) {
  411. [sdkServiceInstalledArray
  412. addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceDynamicLinks))];
  413. }
  414. // Auth
  415. if (NSClassFromString(@"FIRAuth") != nil) {
  416. [sdkServiceInstalledArray addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceAuth))];
  417. }
  418. // AuthUI
  419. if (NSClassFromString(@"FUIAuth") != nil) {
  420. [sdkServiceInstalledArray addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceAuthUI))];
  421. }
  422. // Firestore
  423. if (NSClassFromString(@"FIRFirestore") != nil) {
  424. [sdkServiceInstalledArray addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceFirestore))];
  425. }
  426. // Functions
  427. if (NSClassFromString(@"FIRFunctions") != nil) {
  428. [sdkServiceInstalledArray addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceFunctions))];
  429. }
  430. // Performance
  431. if (NSClassFromString(@"FIRPerformance") != nil) {
  432. [sdkServiceInstalledArray
  433. addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServicePerformance))];
  434. }
  435. // Storage
  436. if (NSClassFromString(@"FIRStorage") != nil) {
  437. [sdkServiceInstalledArray addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceStorage))];
  438. }
  439. // SignIn via Google pod
  440. if (NSClassFromString(@"GIDSignIn") != nil && NSClassFromString(@"GGLContext") != nil) {
  441. [sdkServiceInstalledArray addObject:@(FIRMapFromServiceStringToTypeEnum(kGGLServiceSignIn))];
  442. }
  443. // Analytics via Google pod
  444. if (NSClassFromString(@"GAI") != nil && NSClassFromString(@"GGLContext") != nil) {
  445. [sdkServiceInstalledArray addObject:@(FIRMapFromServiceStringToTypeEnum(kGGLServiceAnalytics))];
  446. }
  447. // In-App Messaging
  448. if (NSClassFromString(@"FIRInAppMessaging") != nil) {
  449. [sdkServiceInstalledArray addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceIAM))];
  450. }
  451. logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType *servicesInstalled =
  452. calloc(sdkServiceInstalledArray.count,
  453. sizeof(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType));
  454. if (servicesInstalled == NULL) {
  455. return;
  456. }
  457. for (NSUInteger i = 0; i < sdkServiceInstalledArray.count; i++) {
  458. NSNumber *typeEnum = sdkServiceInstalledArray[i];
  459. logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType serviceType =
  460. (int32_t)typeEnum.integerValue;
  461. servicesInstalled[i] = serviceType;
  462. }
  463. config->sdk_service_installed = servicesInstalled;
  464. config->sdk_service_installed_count = (int32_t)sdkServiceInstalledArray.count;
  465. }
  466. /** Populates the proto with the number of linked frameworks.
  467. *
  468. * @param config The proto to populate.
  469. */
  470. void FIRPopulateProtoWithNumberOfLinkedFrameworks(
  471. logs_proto_mobilesdk_ios_ICoreConfiguration *config) {
  472. int numFrameworks = -1; // Subtract the app binary itself.
  473. unsigned int numImages;
  474. const char **imageNames = objc_copyImageNames(&numImages);
  475. for (unsigned int i = 0; i < numImages; i++) {
  476. NSString *imageName = [NSString stringWithUTF8String:imageNames[i]];
  477. if ([imageName rangeOfString:@"System/Library"].length != 0 // Apple .frameworks
  478. || [imageName rangeOfString:@"Developer/Library"].length != 0 // Xcode debug .frameworks
  479. || [imageName rangeOfString:@"usr/lib"].length != 0) { // Public .dylibs
  480. continue;
  481. }
  482. numFrameworks++;
  483. }
  484. free(imageNames);
  485. config->dynamic_framework_count = numFrameworks;
  486. config->has_dynamic_framework_count = 1;
  487. }
  488. /** Populates the proto with Info.plist values.
  489. *
  490. * @param config The proto to populate.
  491. */
  492. void FIRPopulateProtoWithInfoPlistValues(logs_proto_mobilesdk_ios_ICoreConfiguration *config) {
  493. NSDictionary<NSString *, id> *info = [[NSBundle mainBundle] infoDictionary];
  494. NSString *xcodeVersion = info[@"DTXcodeBuild"] ?: @"";
  495. NSString *sdkVersion = info[@"DTSDKBuild"] ?: @"";
  496. NSString *combinedVersions = [NSString stringWithFormat:@"%@-%@", xcodeVersion, sdkVersion];
  497. config->apple_framework_version = FIREncodeString(combinedVersions);
  498. NSString *minVersion = info[@"MinimumOSVersion"];
  499. if (minVersion) {
  500. config->min_supported_ios_version = FIREncodeString(minVersion);
  501. }
  502. // Apps can turn off swizzling in the Info.plist, check if they've explicitly set the value and
  503. // report it. It's enabled by default.
  504. NSNumber *appDelegateSwizzledNum = info[@"FirebaseAppDelegateProxyEnabled"];
  505. BOOL appDelegateSwizzled = YES;
  506. if ([appDelegateSwizzledNum isKindOfClass:[NSNumber class]]) {
  507. appDelegateSwizzled = [appDelegateSwizzledNum boolValue];
  508. }
  509. config->swizzling_enabled = appDelegateSwizzled;
  510. config->has_swizzling_enabled = 1;
  511. }
  512. #pragma mark - FIRCoreDiagnosticsInterop
  513. + (void)sendDiagnosticsData:(nonnull id<FIRCoreDiagnosticsData>)diagnosticsData {
  514. FIRCoreDiagnostics *diagnostics = [FIRCoreDiagnostics sharedInstance];
  515. [diagnostics sendDiagnosticsData:diagnosticsData];
  516. }
  517. - (void)sendDiagnosticsData:(nonnull id<FIRCoreDiagnosticsData>)diagnosticsData {
  518. dispatch_async(self.diagnosticsQueue, ^{
  519. NSDictionary<NSString *, id> *diagnosticObjects = diagnosticsData.diagnosticObjects;
  520. NSNumber *isDataCollectionDefaultEnabled =
  521. diagnosticObjects[kFIRCDIsDataCollectionDefaultEnabledKey];
  522. if (isDataCollectionDefaultEnabled && ![isDataCollectionDefaultEnabled boolValue]) {
  523. return;
  524. }
  525. // Create the proto.
  526. logs_proto_mobilesdk_ios_ICoreConfiguration icore_config =
  527. logs_proto_mobilesdk_ios_ICoreConfiguration_init_default;
  528. icore_config.using_gdt = 1;
  529. icore_config.has_using_gdt = 1;
  530. // Populate the proto with information.
  531. FIRPopulateProtoWithInfoFromUserInfoParams(&icore_config, diagnosticObjects);
  532. FIRPopulateProtoWithCommonInfoFromApp(&icore_config, diagnosticObjects);
  533. FIRPopulateProtoWithInstalledServices(&icore_config);
  534. FIRPopulateProtoWithNumberOfLinkedFrameworks(&icore_config);
  535. FIRPopulateProtoWithInfoPlistValues(&icore_config);
  536. [self setHeartbeatFlagIfNeededToConfig:&icore_config];
  537. // This log object is capable of converting the proto to bytes.
  538. FIRCoreDiagnosticsLog *log = [[FIRCoreDiagnosticsLog alloc] initWithConfig:icore_config];
  539. // Send the log as a telemetry event.
  540. GDTCOREvent *event = [self.transport eventForTransport];
  541. event.dataObject = (id<GDTCOREventDataObject>)log;
  542. [self.transport sendTelemetryEvent:event];
  543. });
  544. }
  545. #pragma mark - Heartbeat
  546. - (void)setHeartbeatFlagIfNeededToConfig:(logs_proto_mobilesdk_ios_ICoreConfiguration *)config {
  547. // Check if need to send a heartbeat.
  548. NSDate *currentDate = [NSDate date];
  549. NSDate *lastCheckin =
  550. [self.heartbeatDateStorage heartbeatDateForTag:kFIRCoreDiagnosticsHeartbeatTag];
  551. if (lastCheckin) {
  552. // Ensure the previous checkin was on a different date in the past.
  553. if ([self isDate:currentDate inSameDayOrBeforeThan:lastCheckin]) {
  554. return;
  555. }
  556. }
  557. // Update heartbeat sent date.
  558. [self.heartbeatDateStorage setHearbeatDate:currentDate forTag:kFIRCoreDiagnosticsHeartbeatTag];
  559. // Set the flag.
  560. config->sdk_name = logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_ICORE;
  561. config->has_sdk_name = 1;
  562. }
  563. - (BOOL)isDate:(NSDate *)date1 inSameDayOrBeforeThan:(NSDate *)date2 {
  564. return [[NSCalendar currentCalendar] isDate:date1 inSameDayAsDate:date2] ||
  565. [date1 compare:date2] == NSOrderedAscending;
  566. }
  567. @end