-
Notifications
You must be signed in to change notification settings - Fork 122
/
Copy pathanalytics_ios.mm
473 lines (423 loc) · 18 KB
/
analytics_ios.mm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
/*
* Copyright 2016 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import <Foundation/Foundation.h>
#import "FIRAnalytics+Consent.h"
#import "FIRAnalytics+OnDevice.h"
#import "FIRAnalytics.h"
#include "analytics/src/include/firebase/analytics.h"
#include "analytics/src/analytics_common.h"
#include "app/src/assert.h"
#include "app/src/include/firebase/internal/mutex.h"
#include "app/src/include/firebase/version.h"
#include "app/src/log.h"
#include "app/src/thread.h"
#include "app/src/time.h"
#include "app/src/util.h"
#include "app/src/util_ios.h"
namespace firebase {
namespace analytics {
// Used to workaround b/143656277 and b/110166640
class AnalyticsDataResetter {
private:
enum ResetState {
kResetStateNone = 0,
kResetStateRequested,
kResetStateRetry,
};
public:
// Initialize the class.
AnalyticsDataResetter() : reset_state_(kResetStateNone), reset_timestamp_(0) {}
// Reset analytics data.
void Reset() {
MutexLock lock(mutex_);
reset_timestamp_ = firebase::internal::GetTimestampEpoch();
reset_state_ = kResetStateRequested;
instance_id_ = util::StringFromNSString([FIRAnalytics appInstanceID]);
[FIRAnalytics resetAnalyticsData];
}
// Get the instance ID, returning a non-empty string if it's valid or an empty string if it's
// still being reset.
std::string GetInstanceId() {
MutexLock lock(mutex_);
std::string current_instance_id = util::StringFromNSString([FIRAnalytics appInstanceID]);
uint64_t reset_time_elapsed_milliseconds = GetResetTimeElapsedMilliseconds();
switch (reset_state_) {
case kResetStateNone:
break;
case kResetStateRequested:
if (reset_time_elapsed_milliseconds >= kResetRetryIntervalMilliseconds) {
// Firebase Analytics on iOS can take a while to initialize, in this case we try to reset
// again if the instance ID hasn't changed for a while.
reset_state_ = kResetStateRetry;
reset_timestamp_ = firebase::internal::GetTimestampEpoch();
[FIRAnalytics resetAnalyticsData];
return std::string();
}
FIREBASE_CASE_FALLTHROUGH;
case kResetStateRetry:
if ((current_instance_id.empty() || current_instance_id == instance_id_) &&
reset_time_elapsed_milliseconds < kResetTimeoutMilliseconds) {
return std::string();
}
break;
}
instance_id_ = current_instance_id;
return current_instance_id;
}
private:
// Get the time elapsed in milliseconds since reset was requested.
uint64_t GetResetTimeElapsedMilliseconds() const {
return firebase::internal::GetTimestampEpoch() - reset_timestamp_;
}
private:
Mutex mutex_;
// Reset attempt.
ResetState reset_state_;
// When a reset was last requested.
uint64_t reset_timestamp_;
// Instance ID before it was reset.
std::string instance_id_;
// Time to wait before trying to reset again.
static const uint64_t kResetRetryIntervalMilliseconds;
// Time to wait before giving up on resetting the ID.
static const uint64_t kResetTimeoutMilliseconds;
};
DEFINE_FIREBASE_VERSION_STRING(FirebaseAnalytics);
const uint64_t AnalyticsDataResetter::kResetRetryIntervalMilliseconds = 1000;
const uint64_t AnalyticsDataResetter::kResetTimeoutMilliseconds = 5000;
static const double kMillisecondsPerSecond = 1000.0;
static Mutex g_mutex; // NOLINT
static bool g_initialized = false;
static AnalyticsDataResetter* g_resetter = nullptr;
// Initialize the API.
void Initialize(const ::firebase::App& app) {
MutexLock lock(g_mutex);
g_initialized = true;
g_resetter = new AnalyticsDataResetter();
internal::RegisterTerminateOnDefaultAppDestroy();
internal::FutureData::Create();
}
namespace internal {
// Determine whether the analytics module is initialized.
bool IsInitialized() { return g_initialized; }
} // namespace internal
// Terminate the API.
void Terminate() {
MutexLock lock(g_mutex);
internal::FutureData::Destroy();
internal::UnregisterTerminateOnDefaultAppDestroy();
delete g_resetter;
g_resetter = nullptr;
g_initialized = false;
}
// Enable / disable measurement and reporting.
void SetAnalyticsCollectionEnabled(bool enabled) {
FIREBASE_ASSERT_RETURN_VOID(internal::IsInitialized());
[FIRAnalytics setAnalyticsCollectionEnabled:enabled];
}
void SetConsent(const std::map<ConsentType, ConsentStatus>& consent_settings) {
FIREBASE_ASSERT_RETURN_VOID(internal::IsInitialized());
NSMutableDictionary* consent_settings_dict =
[[NSMutableDictionary alloc] initWithCapacity:consent_settings.size()];
for (auto it = consent_settings.begin(); it != consent_settings.end(); ++it) {
FIRConsentType consent_type;
switch (it->first) {
case kConsentTypeAdStorage:
consent_type = FIRConsentTypeAdStorage;
break;
case kConsentTypeAnalyticsStorage:
consent_type = FIRConsentTypeAnalyticsStorage;
break;
case kConsentTypeAdUserData:
consent_type = FIRConsentTypeAdUserData;
break;
case kConsentTypeAdPersonalization:
consent_type = FIRConsentTypeAdPersonalization;
break;
default:
LogError("Unknown ConsentType value: %d", it->first);
return;
};
FIRConsentStatus consent_status;
switch (it->second) {
case kConsentStatusGranted:
consent_status = FIRConsentStatusGranted;
break;
case kConsentStatusDenied:
consent_status = FIRConsentStatusDenied;
break;
default:
LogError("Unknown ConsentStatus value: %d", it->second);
return;
};
[consent_settings_dict setObject:consent_status forKey:consent_type];
}
[FIRAnalytics setConsent:consent_settings_dict];
}
// Due to overloads of LogEvent(), it's possible for users to call variants that require a
// string with a nullptr. To prevent a crash and instead yield a warning, pass an empty string
// to logEventWithName: methods instead. See b/30061553 for the background.
NSString* SafeString(const char* event_name) { return @(event_name ? event_name : ""); }
// Log an event with one string parameter.
void LogEvent(const char* name, const char* parameter_name, const char* parameter_value) {
FIREBASE_ASSERT_RETURN_VOID(internal::IsInitialized());
[FIRAnalytics logEventWithName:@(name)
parameters:@{SafeString(parameter_name) : SafeString(parameter_value)}];
}
// Log an event with one double parameter.
void LogEvent(const char* name, const char* parameter_name, const double parameter_value) {
FIREBASE_ASSERT_RETURN_VOID(internal::IsInitialized());
[FIRAnalytics
logEventWithName:@(name)
parameters:@{SafeString(parameter_name) : [NSNumber numberWithDouble:parameter_value]}];
}
// Log an event with one 64-bit integer parameter.
void LogEvent(const char* name, const char* parameter_name, const int64_t parameter_value) {
FIREBASE_ASSERT_RETURN_VOID(internal::IsInitialized());
[FIRAnalytics logEventWithName:@(name)
parameters:@{
SafeString(parameter_name) : [NSNumber numberWithLongLong:parameter_value]
}];
}
/// Log an event with one integer parameter (stored as a 64-bit integer).
void LogEvent(const char* name, const char* parameter_name, const int parameter_value) {
LogEvent(name, parameter_name, static_cast<int64_t>(parameter_value));
}
/// Log an event with no parameters.
void LogEvent(const char* name) {
FIREBASE_ASSERT_RETURN_VOID(internal::IsInitialized());
[FIRAnalytics logEventWithName:@(name) parameters:@{}];
}
// Declared here so that it can be used, defined below.
NSDictionary* MapToDictionary(const std::map<Variant, Variant>& map);
// Converts the given vector of Maps into an ObjC NSArray of ObjC NSDictionaries.
NSArray* VectorOfMapsToArray(const std::vector<Variant>& vector) {
NSMutableArray* array = [NSMutableArray arrayWithCapacity:vector.size()];
for (const Variant& element : vector) {
if (element.is_map()) {
NSDictionary* dict = MapToDictionary(element.map());
[array addObject:dict];
} else {
LogError("VectorOfMapsToArray: Unsupported type (%s) within vector.",
Variant::TypeName(element.type()));
}
}
return array;
}
// Converts and adds the Variant to the given Dictionary.
bool AddVariantToDictionary(NSMutableDictionary* dict, NSString* key, const Variant& value) {
if (value.is_int64()) {
[dict setObject:[NSNumber numberWithLongLong:value.int64_value()] forKey:key];
} else if (value.is_double()) {
[dict setObject:[NSNumber numberWithDouble:value.double_value()] forKey:key];
} else if (value.is_string()) {
[dict setObject:SafeString(value.string_value()) forKey:key];
} else if (value.is_bool()) {
// Just use integer 0 or 1.
[dict setObject:[NSNumber numberWithLongLong:value.bool_value() ? 1 : 0] forKey:key];
} else if (value.is_null()) {
// Just use integer 0 for null.
[dict setObject:[NSNumber numberWithLongLong:0] forKey:key];
} else if (value.is_vector()) {
NSArray* array = VectorOfMapsToArray(value.vector());
[dict setObject:array forKey:key];
} else if (value.is_map()) {
NSDictionary* inner_dict = MapToDictionary(value.map());
[dict setObject:inner_dict forKey:key];
} else {
// A Variant type that couldn't be handled was passed in.
return false;
}
return true;
}
// Converts the given map into an ObjC dictionary of ObjC objects.
NSDictionary* MapToDictionary(const std::map<Variant, Variant>& map) {
NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithCapacity:map.size()];
for (const auto& pair : map) {
// Only add elements that use a string key
if (!pair.first.is_string()) {
continue;
}
NSString* key = SafeString(pair.first.string_value());
const Variant& value = pair.second;
if (!AddVariantToDictionary(dict, key, value)) {
LogError("MapToDictionary: Unsupported type (%s) within map with key %s.",
Variant::TypeName(value.type()), key);
}
}
return dict;
}
// Log an event with associated parameters.
void LogEvent(const char* name, const Parameter* parameters, size_t number_of_parameters) {
FIREBASE_ASSERT_RETURN_VOID(internal::IsInitialized());
NSMutableDictionary* parameters_dict =
[NSMutableDictionary dictionaryWithCapacity:number_of_parameters];
for (size_t i = 0; i < number_of_parameters; ++i) {
const Parameter& parameter = parameters[i];
NSString* parameter_name = SafeString(parameter.name);
if (!AddVariantToDictionary(parameters_dict, parameter_name, parameter.value)) {
// A Variant type that couldn't be handled was passed in.
LogError("LogEvent(%s): %s is not a valid parameter value type. "
"No event was logged.",
parameter.name, Variant::TypeName(parameter.value.type()));
}
}
[FIRAnalytics logEventWithName:@(name) parameters:parameters_dict];
}
void SetDefaultEventParameters(const std::map<std::string, Variant>& default_parameters) {
FIREBASE_ASSERT_RETURN_VOID(internal::IsInitialized());
// Convert the std::map<std::string, Variant> to NSDictionary*
// The keys must be strings for FIRAnalytics.
NSMutableDictionary* parameters_dict =
[NSMutableDictionary dictionaryWithCapacity:default_parameters.size()];
for (const auto& pair : default_parameters) {
NSString* key = firebase::util::StringToNSString(pair.first);
// A null Variant indicates the default parameter for that key should be
// cleared. In ObjC, setting a key to [NSNull null] in the dictionary
// achieves this.
id value = pair.second.is_null() ? [NSNull null] : firebase::util::VariantToId(pair.second);
if (value) {
[parameters_dict setObject:value forKey:key];
} else {
// VariantToId could return nil if the variant type is unsupported.
// Log an error but continue, as NSNull case is handled above.
LogError("SetDefaultEventParameters: Failed to convert value for key %s.",
pair.first.c_str());
}
}
[FIRAnalytics setDefaultEventParameters:parameters_dict];
}
void ClearDefaultEventParameters() {
FIREBASE_ASSERT_RETURN_VOID(internal::IsInitialized());
// Passing nil to the underlying SDK method clears all parameters.
[FIRAnalytics setDefaultEventParameters:nil];
}
/// Initiates on-device conversion measurement given a user email address on iOS (no-op on
/// Android). On iOS, requires dependency GoogleAppMeasurementOnDeviceConversion to be linked
/// in, otherwise it is a no-op.
void InitiateOnDeviceConversionMeasurementWithEmailAddress(const char* email_address) {
FIREBASE_ASSERT_RETURN_VOID(internal::IsInitialized());
[FIRAnalytics initiateOnDeviceConversionMeasurementWithEmailAddress:@(email_address)];
}
/// Initiates on-device conversion measurement given a phone number on iOS (no-op on
/// Android). On iOS, requires dependency GoogleAppMeasurementOnDeviceConversion to be linked
/// in, otherwise it is a no-op.
void InitiateOnDeviceConversionMeasurementWithPhoneNumber(const char* phone_number) {
FIREBASE_ASSERT_RETURN_VOID(internal::IsInitialized());
[FIRAnalytics initiateOnDeviceConversionMeasurementWithPhoneNumber:@(phone_number)];
}
/// Initiates on-device conversion measurement given a hashed user email address
/// on iOS (no-op on Android). On iOS, requires dependency
/// GoogleAppMeasurementOnDeviceConversion to be linked in, otherwise it is a
/// no-op.
void InitiateOnDeviceConversionMeasurementWithHashedEmailAddress(
std::vector<unsigned char> hashed_email) {
FIREBASE_ASSERT_RETURN_VOID(internal::IsInitialized());
NSData* hashed_email_data =
firebase::util::BytesToNSData(hashed_email.data(), hashed_email.size());
[FIRAnalytics initiateOnDeviceConversionMeasurementWithHashedEmailAddress:hashed_email_data];
}
/// Initiates on-device conversion measurement given a hashed phone number on
/// iOS (no-op on Android). On iOS, requires dependency
/// GoogleAppMeasurementOnDeviceConversion to be linked in, otherwise it is a
/// no-op.
void InitiateOnDeviceConversionMeasurementWithHashedPhoneNumber(
std::vector<unsigned char> hashed_phone) {
FIREBASE_ASSERT_RETURN_VOID(internal::IsInitialized());
NSData* hashed_phone_data =
firebase::util::BytesToNSData(hashed_phone.data(), hashed_phone.size());
[FIRAnalytics initiateOnDeviceConversionMeasurementWithHashedPhoneNumber:hashed_phone_data];
}
// Set a user property to the given value.
void SetUserProperty(const char* name, const char* value) {
FIREBASE_ASSERT_RETURN_VOID(internal::IsInitialized());
[FIRAnalytics setUserPropertyString:(value ? @(value) : nil) forName:@(name)];
}
// Sets the user ID property. This feature must be used in accordance with
// <a href="https://www.google.com/policies/privacy">
// Google's Privacy Policy</a>
void SetUserId(const char* user_id) {
FIREBASE_ASSERT_RETURN_VOID(internal::IsInitialized());
[FIRAnalytics setUserID:(user_id ? @(user_id) : nil)];
}
// Sets the duration of inactivity that terminates the current session.
void SetSessionTimeoutDuration(int64_t milliseconds) {
FIREBASE_ASSERT_RETURN_VOID(internal::IsInitialized());
[FIRAnalytics
setSessionTimeoutInterval:static_cast<NSTimeInterval>(milliseconds) / kMillisecondsPerSecond];
}
void ResetAnalyticsData() {
MutexLock lock(g_mutex);
FIREBASE_ASSERT_RETURN_VOID(internal::IsInitialized());
g_resetter->Reset();
}
Future<std::string> GetAnalyticsInstanceId() {
MutexLock lock(g_mutex);
FIREBASE_ASSERT_RETURN(Future<std::string>(), internal::IsInitialized());
auto* api = internal::FutureData::Get()->api();
const auto future_handle =
api->SafeAlloc<std::string>(internal::kAnalyticsFnGetAnalyticsInstanceId);
static int kPollTimeMs = 100;
Thread get_id_thread(
[](SafeFutureHandle<std::string>* handle) {
for (;;) {
{
MutexLock lock(g_mutex);
if (!internal::IsInitialized()) break;
std::string instance_id = g_resetter->GetInstanceId();
if (!instance_id.empty()) {
internal::FutureData::Get()->api()->CompleteWithResult(*handle, 0, "", instance_id);
break;
}
}
firebase::internal::Sleep(kPollTimeMs);
}
delete handle;
},
new SafeFutureHandle<std::string>(future_handle));
get_id_thread.Detach();
return Future<std::string>(api, future_handle.get());
}
Future<std::string> GetAnalyticsInstanceIdLastResult() {
MutexLock lock(g_mutex);
FIREBASE_ASSERT_RETURN(Future<std::string>(), internal::IsInitialized());
return static_cast<const Future<std::string>&>(
internal::FutureData::Get()->api()->LastResult(internal::kAnalyticsFnGetAnalyticsInstanceId));
}
Future<int64_t> GetSessionId() {
MutexLock lock(g_mutex);
FIREBASE_ASSERT_RETURN(Future<int64_t>(), internal::IsInitialized());
auto* api = internal::FutureData::Get()->api();
const auto future_handle = api->SafeAlloc<int64_t>(internal::kAnalyticsFnGetSessionId);
[FIRAnalytics sessionIDWithCompletion:^(int64_t session_id, NSError* _Nullable error) {
MutexLock lock(g_mutex);
if (!internal::IsInitialized()) return;
if (error) {
api->Complete(future_handle, -1, util::NSStringToString(error.localizedDescription).c_str());
} else {
api->CompleteWithResult(future_handle, 0, "", session_id);
}
}];
return MakeFuture<int64_t>(api, future_handle);
}
Future<int64_t> GetSessionIdLastResult() {
MutexLock lock(g_mutex);
FIREBASE_ASSERT_RETURN(Future<int64_t>(), internal::IsInitialized());
return static_cast<const Future<int64_t>&>(
internal::FutureData::Get()->api()->LastResult(internal::kAnalyticsFnGetSessionId));
}
} // namespace analytics
} // namespace firebase