FIRMessagingUtilities.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. /*
  2. * Copyright 2017 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 "FirebaseMessaging/Sources/FIRMessagingUtilities.h"
  17. #import <GoogleUtilities/GULAppEnvironmentUtil.h>
  18. #import <GoogleUtilities/GULUserDefaults.h>
  19. #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
  20. #import "FirebaseMessaging/Sources/FIRMessagingLogger.h"
  21. NSString *const kFIRMessagingInstanceIDUserDefaultsKeyLocale =
  22. @"com.firebase.instanceid.user_defaults.locale"; // locale key stored in GULUserDefaults
  23. static NSString *const kFIRMessagingAPNSSandboxPrefix = @"s_";
  24. static NSString *const kFIRMessagingAPNSProdPrefix = @"p_";
  25. static NSString *const kFIRMessagingWatchKitExtensionPoint = @"com.apple.watchkit";
  26. #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
  27. static NSString *const kEntitlementsAPSEnvironmentKey = @"Entitlements.aps-environment";
  28. #else
  29. static NSString *const kEntitlementsAPSEnvironmentKey =
  30. @"Entitlements.com.apple.developer.aps-environment";
  31. #endif
  32. static NSString *const kAPSEnvironmentDevelopmentValue = @"development";
  33. #pragma mark - URL Helpers
  34. NSString *FIRMessagingTokenRegisterServer(void) {
  35. return @"https://fcmtoken.googleapis.com/register";
  36. }
  37. #pragma mark - Time
  38. int64_t FIRMessagingCurrentTimestampInSeconds(void) {
  39. return (int64_t)[[NSDate date] timeIntervalSince1970];
  40. }
  41. int64_t FIRMessagingCurrentTimestampInMilliseconds(void) {
  42. return (int64_t)(FIRMessagingCurrentTimestampInSeconds() * 1000.0);
  43. }
  44. #pragma mark - App Info
  45. NSString *FIRMessagingCurrentAppVersion(void) {
  46. NSString *version = [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"];
  47. if (![version length]) {
  48. FIRMessagingLoggerError(kFIRMessagingMessageCodeUtilities000,
  49. @"Could not find current app version");
  50. return @"";
  51. }
  52. return version;
  53. }
  54. NSString *FIRMessagingBundleIDByRemovingLastPartFrom(NSString *bundleID) {
  55. NSString *bundleIDComponentsSeparator = @".";
  56. NSMutableArray<NSString *> *bundleIDComponents =
  57. [[bundleID componentsSeparatedByString:bundleIDComponentsSeparator] mutableCopy];
  58. [bundleIDComponents removeLastObject];
  59. return [bundleIDComponents componentsJoinedByString:bundleIDComponentsSeparator];
  60. }
  61. NSString *FIRMessagingAppIdentifier(void) {
  62. NSString *bundleID = [[NSBundle mainBundle] bundleIdentifier];
  63. #if TARGET_OS_WATCH
  64. if (FIRMessagingIsWatchKitExtension()) {
  65. // The code is running in watchKit extension target but the actually bundleID is in the watchKit
  66. // target. So we need to remove the last part of the bundle ID in watchKit extension to match
  67. // the one in watchKit target.
  68. return FIRMessagingBundleIDByRemovingLastPartFrom(bundleID);
  69. } else {
  70. return bundleID;
  71. }
  72. #else
  73. return bundleID;
  74. #endif
  75. }
  76. NSString *FIRMessagingFirebaseAppID(void) {
  77. return [FIROptions defaultOptions].googleAppID;
  78. }
  79. BOOL FIRMessagingIsWatchKitExtension(void) {
  80. #if TARGET_OS_WATCH
  81. NSDictionary<NSString *, id> *infoDict = [[NSBundle mainBundle] infoDictionary];
  82. NSDictionary<NSString *, id> *extensionAttrDict = infoDict[@"NSExtension"];
  83. if (!extensionAttrDict) {
  84. return NO;
  85. }
  86. NSString *extensionPointId = extensionAttrDict[@"NSExtensionPointIdentifier"];
  87. if (extensionPointId) {
  88. return [extensionPointId isEqualToString:kFIRMessagingWatchKitExtensionPoint];
  89. } else {
  90. return NO;
  91. }
  92. #else
  93. return NO;
  94. #endif
  95. }
  96. NSSearchPathDirectory FIRMessagingSupportedDirectory(void) {
  97. #if TARGET_OS_TV
  98. return NSCachesDirectory;
  99. #else
  100. return NSApplicationSupportDirectory;
  101. #endif
  102. }
  103. #pragma mark - Locales
  104. NSDictionary *FIRMessagingFirebaselocalesMap(void) {
  105. return @{
  106. // Albanian
  107. @"sq" : @[ @"sq_AL" ],
  108. // Belarusian
  109. @"be" : @[ @"be_BY" ],
  110. // Bulgarian
  111. @"bg" : @[ @"bg_BG" ],
  112. // Catalan
  113. @"ca" : @[ @"ca", @"ca_ES" ],
  114. // Croatian
  115. @"hr" : @[ @"hr", @"hr_HR" ],
  116. // Czech
  117. @"cs" : @[ @"cs", @"cs_CZ" ],
  118. // Danish
  119. @"da" : @[ @"da", @"da_DK" ],
  120. // Estonian
  121. @"et" : @[ @"et_EE" ],
  122. // Finnish
  123. @"fi" : @[ @"fi", @"fi_FI" ],
  124. // Hebrew
  125. @"he" : @[ @"he", @"iw_IL" ],
  126. // Hindi
  127. @"hi" : @[ @"hi_IN" ],
  128. // Hungarian
  129. @"hu" : @[ @"hu", @"hu_HU" ],
  130. // Icelandic
  131. @"is" : @[ @"is_IS" ],
  132. // Indonesian
  133. @"id" : @[ @"id", @"in_ID", @"id_ID" ],
  134. // Irish
  135. @"ga" : @[ @"ga_IE" ],
  136. // Korean
  137. @"ko" : @[ @"ko", @"ko_KR", @"ko-KR" ],
  138. // Latvian
  139. @"lv" : @[ @"lv_LV" ],
  140. // Lithuanian
  141. @"lt" : @[ @"lt_LT" ],
  142. // Macedonian
  143. @"mk" : @[ @"mk_MK" ],
  144. // Malay
  145. @"ms" : @[ @"ms_MY" ],
  146. // Maltese
  147. @"mt" : @[ @"mt_MT" ],
  148. // Polish
  149. @"pl" : @[ @"pl", @"pl_PL", @"pl-PL" ],
  150. // Romanian
  151. @"ro" : @[ @"ro", @"ro_RO" ],
  152. // Russian
  153. @"ru" : @[ @"ru_RU", @"ru", @"ru_BY", @"ru_KZ", @"ru-RU" ],
  154. // Slovak
  155. @"sk" : @[ @"sk", @"sk_SK" ],
  156. // Slovenian
  157. @"sl" : @[ @"sl_SI" ],
  158. // Swedish
  159. @"sv" : @[ @"sv", @"sv_SE", @"sv-SE" ],
  160. // Turkish
  161. @"tr" : @[ @"tr", @"tr-TR", @"tr_TR" ],
  162. // Ukrainian
  163. @"uk" : @[ @"uk", @"uk_UA" ],
  164. // Vietnamese
  165. @"vi" : @[ @"vi", @"vi_VN" ],
  166. // The following are groups of locales or locales that sub-divide a
  167. // language).
  168. // Arabic
  169. @"ar" : @[
  170. @"ar", @"ar_DZ", @"ar_BH", @"ar_EG", @"ar_IQ", @"ar_JO", @"ar_KW",
  171. @"ar_LB", @"ar_LY", @"ar_MA", @"ar_OM", @"ar_QA", @"ar_SA", @"ar_SD",
  172. @"ar_SY", @"ar_TN", @"ar_AE", @"ar_YE", @"ar_GB", @"ar-IQ", @"ar_US"
  173. ],
  174. // Simplified Chinese
  175. @"zh_Hans" : @[ @"zh_CN", @"zh_SG", @"zh-Hans" ],
  176. // Traditional Chinese
  177. @"zh_Hant" : @[ @"zh_HK", @"zh_TW", @"zh-Hant", @"zh-HK", @"zh-TW" ],
  178. // Dutch
  179. @"nl" : @[ @"nl", @"nl_BE", @"nl_NL", @"nl-NL" ],
  180. // English
  181. @"en" : @[
  182. @"en", @"en_AU", @"en_CA", @"en_IN", @"en_IE", @"en_MT", @"en_NZ", @"en_PH",
  183. @"en_SG", @"en_ZA", @"en_GB", @"en_US", @"en_AE", @"en-AE", @"en_AS", @"en-AU",
  184. @"en_BD", @"en-CA", @"en_EG", @"en_ES", @"en_GB", @"en-GB", @"en_HK", @"en_ID",
  185. @"en-IN", @"en_NG", @"en-PH", @"en_PK", @"en-SG", @"en-US"
  186. ],
  187. // French
  188. @"fr" :
  189. @[ @"fr", @"fr_BE", @"fr_CA", @"fr_FR", @"fr_LU", @"fr_CH", @"fr-CA", @"fr-FR", @"fr_MA" ],
  190. // German
  191. @"de" : @[ @"de", @"de_AT", @"de_DE", @"de_LU", @"de_CH", @"de-DE" ],
  192. // Greek
  193. @"el" : @[ @"el", @"el_CY", @"el_GR" ],
  194. // Italian
  195. @"it" : @[ @"it", @"it_IT", @"it_CH", @"it-IT" ],
  196. // Japanese
  197. @"ja" : @[ @"ja", @"ja_JP", @"ja_JP_JP", @"ja-JP" ],
  198. // Norwegian
  199. @"no" : @[ @"nb", @"no_NO", @"no_NO_NY", @"nb_NO" ],
  200. // Brazilian Portuguese
  201. @"pt_BR" : @[ @"pt_BR", @"pt-BR" ],
  202. // European Portuguese
  203. @"pt_PT" : @[ @"pt", @"pt_PT", @"pt-PT" ],
  204. // Serbian
  205. @"sr" : @[ @"sr_BA", @"sr_ME", @"sr_RS", @"sr_Latn_BA", @"sr_Latn_ME", @"sr_Latn_RS" ],
  206. // European Spanish
  207. @"es_ES" : @[ @"es", @"es_ES", @"es-ES" ],
  208. // Mexican Spanish
  209. @"es_MX" : @[ @"es-MX", @"es_MX", @"es_US", @"es-US" ],
  210. // Latin American Spanish
  211. @"es_419" : @[
  212. @"es_AR", @"es_BO", @"es_CL", @"es_CO", @"es_CR", @"es_DO", @"es_EC",
  213. @"es_SV", @"es_GT", @"es_HN", @"es_NI", @"es_PA", @"es_PY", @"es_PE",
  214. @"es_PR", @"es_UY", @"es_VE", @"es-AR", @"es-CL", @"es-CO"
  215. ],
  216. // Thai
  217. @"th" : @[ @"th", @"th_TH", @"th_TH_TH" ],
  218. };
  219. }
  220. NSArray *FIRMessagingFirebaseLocales(void) {
  221. NSMutableArray *locales = [NSMutableArray array];
  222. NSDictionary *localesMap = FIRMessagingFirebaselocalesMap();
  223. for (NSString *key in localesMap) {
  224. [locales addObjectsFromArray:localesMap[key]];
  225. }
  226. return locales;
  227. }
  228. NSString *FIRMessagingCurrentLocale(void) {
  229. NSArray *locales = FIRMessagingFirebaseLocales();
  230. NSArray *preferredLocalizations =
  231. [NSBundle preferredLocalizationsFromArray:locales
  232. forPreferences:[NSLocale preferredLanguages]];
  233. NSString *legalDocsLanguage = [preferredLocalizations firstObject];
  234. // Use en as the default language
  235. return legalDocsLanguage ? legalDocsLanguage : @"en";
  236. }
  237. BOOL FIRMessagingHasLocaleChanged(void) {
  238. NSString *lastLocale = [[GULUserDefaults standardUserDefaults]
  239. stringForKey:kFIRMessagingInstanceIDUserDefaultsKeyLocale];
  240. NSString *currentLocale = FIRMessagingCurrentLocale();
  241. if (lastLocale) {
  242. if ([currentLocale isEqualToString:lastLocale]) {
  243. return NO;
  244. }
  245. }
  246. return YES;
  247. }
  248. NSString *FIRMessagingStringForAPNSDeviceToken(NSData *deviceToken) {
  249. NSMutableString *APNSToken = [NSMutableString string];
  250. unsigned char *bytes = (unsigned char *)[deviceToken bytes];
  251. for (int i = 0; i < (int)deviceToken.length; i++) {
  252. [APNSToken appendFormat:@"%02x", bytes[i]];
  253. }
  254. return APNSToken;
  255. }
  256. NSString *FIRMessagingAPNSTupleStringForTokenAndServerType(NSData *deviceToken, BOOL isSandbox) {
  257. if (deviceToken == nil) {
  258. // A nil deviceToken leads to an invalid tuple string, so return nil.
  259. return nil;
  260. }
  261. NSString *prefix = isSandbox ? kFIRMessagingAPNSSandboxPrefix : kFIRMessagingAPNSProdPrefix;
  262. NSString *APNSString = FIRMessagingStringForAPNSDeviceToken(deviceToken);
  263. NSString *APNSTupleString = [NSString stringWithFormat:@"%@%@", prefix, APNSString];
  264. return APNSTupleString;
  265. }
  266. BOOL FIRMessagingIsProductionApp(void) {
  267. const BOOL defaultAppTypeProd = YES;
  268. NSError *error = nil;
  269. if ([GULAppEnvironmentUtil isSimulator]) {
  270. FIRMessagingLoggerError(kFIRMessagingMessageCodeInstanceID014,
  271. @"Running InstanceID on a simulator doesn't have APNS. "
  272. @"Use prod profile by default.");
  273. return defaultAppTypeProd;
  274. }
  275. if ([GULAppEnvironmentUtil isFromAppStore]) {
  276. // Apps distributed via AppStore or TestFlight use the Production APNS certificates.
  277. return defaultAppTypeProd;
  278. }
  279. #if TARGET_OS_OSX || TARGET_OS_MACCATALYST
  280. NSString *path = [[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]
  281. stringByAppendingPathComponent:@"embedded.provisionprofile"];
  282. #elif TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH || \
  283. (defined(TARGET_OS_VISION) && TARGET_OS_VISION)
  284. NSString *path = [[[NSBundle mainBundle] bundlePath]
  285. stringByAppendingPathComponent:@"embedded.mobileprovision"];
  286. #endif
  287. if ([GULAppEnvironmentUtil isAppStoreReceiptSandbox] && !path.length) {
  288. // Distributed via TestFlight
  289. return defaultAppTypeProd;
  290. }
  291. NSMutableData *profileData = [NSMutableData dataWithContentsOfFile:path options:0 error:&error];
  292. if (!profileData.length || error) {
  293. NSString *errorString =
  294. [NSString stringWithFormat:@"Error while reading embedded mobileprovision %@", error];
  295. FIRMessagingLoggerError(kFIRMessagingMessageCodeInstanceID014, @"%@", errorString);
  296. return defaultAppTypeProd;
  297. }
  298. // The "embedded.mobileprovision" sometimes contains characters with value 0, which signals the
  299. // end of a c-string and halts the ASCII parser, or with value > 127, which violates strict 7-bit
  300. // ASCII. Replace any 0s or invalid characters in the input.
  301. uint8_t *profileBytes = (uint8_t *)profileData.bytes;
  302. for (int i = 0; i < profileData.length; i++) {
  303. uint8_t currentByte = profileBytes[i];
  304. if (!currentByte || currentByte > 127) {
  305. profileBytes[i] = '.';
  306. }
  307. }
  308. NSString *embeddedProfile = [[NSString alloc] initWithBytesNoCopy:profileBytes
  309. length:profileData.length
  310. encoding:NSASCIIStringEncoding
  311. freeWhenDone:NO];
  312. if (error || !embeddedProfile.length) {
  313. NSString *errorString =
  314. [NSString stringWithFormat:@"Error while reading embedded mobileprovision %@", error];
  315. FIRMessagingLoggerError(kFIRMessagingMessageCodeInstanceID014, @"%@", errorString);
  316. return defaultAppTypeProd;
  317. }
  318. NSScanner *scanner = [NSScanner scannerWithString:embeddedProfile];
  319. NSString *plistContents;
  320. if ([scanner scanUpToString:@"<plist" intoString:nil]) {
  321. if ([scanner scanUpToString:@"</plist>" intoString:&plistContents]) {
  322. plistContents = [plistContents stringByAppendingString:@"</plist>"];
  323. }
  324. }
  325. if (!plistContents.length) {
  326. return defaultAppTypeProd;
  327. }
  328. NSData *data = [plistContents dataUsingEncoding:NSUTF8StringEncoding];
  329. if (!data.length) {
  330. FIRMessagingLoggerError(kFIRMessagingMessageCodeInstanceID014,
  331. @"Couldn't read plist fetched from embedded mobileprovision");
  332. return defaultAppTypeProd;
  333. }
  334. NSError *plistMapError;
  335. id plistData = [NSPropertyListSerialization propertyListWithData:data
  336. options:NSPropertyListImmutable
  337. format:nil
  338. error:&plistMapError];
  339. if (plistMapError || ![plistData isKindOfClass:[NSDictionary class]]) {
  340. NSString *errorString =
  341. [NSString stringWithFormat:@"Error while converting assumed plist to dict %@",
  342. plistMapError.localizedDescription];
  343. FIRMessagingLoggerError(kFIRMessagingMessageCodeInstanceID014, @"%@", errorString);
  344. return defaultAppTypeProd;
  345. }
  346. NSDictionary *plistMap = (NSDictionary *)plistData;
  347. if ([plistMap valueForKeyPath:@"ProvisionedDevices"]) {
  348. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeInstanceID012,
  349. @"Provisioning profile has specifically provisioned devices, "
  350. @"most likely a Dev profile.");
  351. }
  352. NSString *apsEnvironment = [plistMap valueForKeyPath:kEntitlementsAPSEnvironmentKey];
  353. NSString *debugString __unused =
  354. [NSString stringWithFormat:@"APNS Environment in profile: %@", apsEnvironment];
  355. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeInstanceID013, @"%@", debugString);
  356. // No aps-environment in the profile.
  357. if (!apsEnvironment.length) {
  358. FIRMessagingLoggerError(kFIRMessagingMessageCodeInstanceID014,
  359. @"No aps-environment set. If testing on a device APNS is not "
  360. @"correctly configured. Please recheck your provisioning "
  361. @"profiles. If testing on a simulator this is fine since APNS "
  362. @"doesn't work on the simulator.");
  363. return defaultAppTypeProd;
  364. }
  365. if ([apsEnvironment isEqualToString:kAPSEnvironmentDevelopmentValue]) {
  366. return NO;
  367. }
  368. return defaultAppTypeProd;
  369. }
  370. BOOL FIRMessagingIsSandboxApp(void) {
  371. static BOOL isSandboxApp = YES;
  372. static dispatch_once_t onceToken;
  373. dispatch_once(&onceToken, ^{
  374. isSandboxApp = !FIRMessagingIsProductionApp();
  375. });
  376. return isSandboxApp;
  377. }