FIRCoreDiagnostics.m 26 KB

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