diff --git a/Crashlytics/Crashlytics.framework/Versions/A/Crashlytics b/Crashlytics/Crashlytics.framework/Versions/A/Crashlytics index 8a09fe3c..bb0d23de 100644 Binary files a/Crashlytics/Crashlytics.framework/Versions/A/Crashlytics and b/Crashlytics/Crashlytics.framework/Versions/A/Crashlytics differ diff --git a/Crashlytics/Crashlytics.framework/Versions/A/Headers/Crashlytics.h b/Crashlytics/Crashlytics.framework/Versions/A/Headers/Crashlytics.h index 2cf1bbe7..989d276b 100644 --- a/Crashlytics/Crashlytics.framework/Versions/A/Headers/Crashlytics.h +++ b/Crashlytics/Crashlytics.framework/Versions/A/Headers/Crashlytics.h @@ -148,6 +148,26 @@ OBJC_EXTERN void CLSNSLog(NSString *format, ...); @end +/** + * The CLSCrashReport protocol exposes methods that you can call on crash report objects passed + * to delegate methods. If you want these values or the entire object to stay in memory retain + * them or copy them. + **/ +@protocol CLSCrashReport +@optional + +/** + * Returns the session identifier for the crash report. + **/ +- (NSString *)identifier; + +/** + * Returns the custom key value data for the crash report. + **/ +- (NSDictionary *)customKeys; + +@end + /** * * The CrashlyticsDelegate protocol provides a mechanism for your application to take @@ -169,4 +189,15 @@ OBJC_EXTERN void CLSNSLog(NSString *format, ...); **/ - (void)crashlyticsDidDetectCrashDuringPreviousExecution:(Crashlytics *)crashlytics; +/** + * + * Just like crashlyticsDidDetectCrashDuringPreviousExecution this delegate method is + * called once a Crashlytics instance has determined that the last execution of the + * application ended in a crash. A CLSCrashReport is passed back that contains data about + * the last crash report that was generated. See the CLSCrashReport protocol for method details. + * This method is called after crashlyticsDidDetectCrashDuringPreviousExecution. + * + **/ +- (void)crashlytics:(Crashlytics *)crashlytics didDetectCrashDuringPreviousExecution:(id )crash; + @end diff --git a/Crashlytics/Crashlytics.framework/Versions/A/Resources/Info.plist b/Crashlytics/Crashlytics.framework/Versions/A/Resources/Info.plist index 975d2452..e7e6418b 100644 Binary files a/Crashlytics/Crashlytics.framework/Versions/A/Resources/Info.plist and b/Crashlytics/Crashlytics.framework/Versions/A/Resources/Info.plist differ diff --git a/Crashlytics/Crashlytics.framework/run b/Crashlytics/Crashlytics.framework/run index 018498b2..0d4ea176 100755 Binary files a/Crashlytics/Crashlytics.framework/run and b/Crashlytics/Crashlytics.framework/run differ diff --git a/External/Pearl b/External/Pearl index 4ceb992d..b8cf787a 160000 --- a/External/Pearl +++ b/External/Pearl @@ -1 +1 @@ -Subproject commit 4ceb992dc59e9d085b241239b63df4754da90de7 +Subproject commit b8cf787af604299c5363846c5b2fcbd9e3083253 diff --git a/Localytics/LocalyticsDatabase.h b/Localytics/LocalyticsDatabase.h index 9a1e1d58..f159089d 100644 --- a/Localytics/LocalyticsDatabase.h +++ b/Localytics/LocalyticsDatabase.h @@ -1,57 +1,70 @@ -// -// LocalyticsDatabase.h -// LocalyticsDemo -// -// Created by jkaufman on 5/26/11. -// Copyright 2011 Localytics. All rights reserved. -// - -#import -#import - -#define MAX_DATABASE_SIZE 500000 // The maximum allowed disk size of the primary database file at open, in bytes -#define VACUUM_THRESHOLD 0.8 // The database is vacuumed after its size exceeds this proportion of the maximum. - -@interface LocalyticsDatabase : NSObject { - sqlite3 *_databaseConnection; -} - -+ (LocalyticsDatabase *)sharedLocalyticsDatabase; - -- (NSUInteger)databaseSize; -- (int)eventCount; -- (NSTimeInterval)createdTimestamp; - -- (BOOL)beginTransaction:(NSString *)name; -- (BOOL)releaseTransaction:(NSString *)name; -- (BOOL)rollbackTransaction:(NSString *)name; - -- (BOOL)incrementLastUploadNumber:(int *)uploadNumber; -- (BOOL)incrementLastSessionNumber:(int *)sessionNumber; - -- (BOOL)addEventWithBlobString:(NSString *)blob; -- (BOOL)addCloseEventWithBlobString:(NSString *)blob; -- (BOOL)addFlowEventWithBlobString:(NSString *)blob; -- (BOOL)removeLastCloseAndFlowEvents; - -- (BOOL)addHeaderWithSequenceNumber:(int)number blobString:(NSString *)blob rowId:(sqlite3_int64 *)insertedRowId; -- (int)unstagedEventCount; -- (BOOL)stageEventsForUpload:(sqlite3_int64)headerId; -- (BOOL)updateAppKey:(NSString *)appKey; -- (NSString *)uploadBlobString; -- (BOOL)deleteUploadedData; -- (BOOL)resetAnalyticsData; -- (BOOL)vacuumIfRequired; - -- (NSTimeInterval)lastSessionStartTimestamp; -- (BOOL)setLastsessionStartTimestamp:(NSTimeInterval)timestamp; - -- (BOOL)isOptedOut; -- (BOOL)setOptedOut:(BOOL)optOut; -- (NSString *)installId; -- (NSString *)appKey; // Most recent app key-- may not be that used to open the session. - -- (NSString *)customDimension:(int)dimension; -- (BOOL)setCustomDimension:(int)dimension value:(NSString *)value; - -@end +// +// LocalyticsDatabase.h +// Copyright (C) 2012 Char Software Inc., DBA Localytics +// +// This code is provided under the Localytics Modified BSD License. +// A copy of this license has been distributed in a file called LICENSE +// with this source code. +// +// Please visit www.localytics.com for more information. + +#import +#import + +#define MAX_DATABASE_SIZE 500000 // The maximum allowed disk size of the primary database file at open, in bytes +#define VACUUM_THRESHOLD 0.8 // The database is vacuumed after its size exceeds this proportion of the maximum. + +@interface LocalyticsDatabase : NSObject { + sqlite3 *_databaseConnection; +} + ++ (LocalyticsDatabase *)sharedLocalyticsDatabase; + +- (NSUInteger)databaseSize; +- (int)eventCount; +- (NSTimeInterval)createdTimestamp; + +- (BOOL)beginTransaction:(NSString *)name; +- (BOOL)releaseTransaction:(NSString *)name; +- (BOOL)rollbackTransaction:(NSString *)name; + +- (BOOL)incrementLastUploadNumber:(int *)uploadNumber; +- (BOOL)incrementLastSessionNumber:(int *)sessionNumber; + +- (BOOL)addEventWithBlobString:(NSString *)blob; +- (BOOL)addCloseEventWithBlobString:(NSString *)blob; +- (BOOL)queueCloseEventWithBlobString:(NSString *)blob; +- (NSString *)dequeueCloseEventBlobString; +- (BOOL)addFlowEventWithBlobString:(NSString *)blob; +- (BOOL)removeLastCloseAndFlowEvents; + +- (BOOL)addHeaderWithSequenceNumber:(int)number blobString:(NSString *)blob rowId:(sqlite3_int64 *)insertedRowId; +- (int)unstagedEventCount; +- (BOOL)stageEventsForUpload:(sqlite3_int64)headerId; +- (BOOL)updateAppKey:(NSString *)appKey; +- (NSString *)uploadBlobString; +- (BOOL)deleteUploadedData; +- (BOOL)resetAnalyticsData; +- (BOOL)vacuumIfRequired; + +- (NSTimeInterval)lastSessionStartTimestamp; +- (BOOL)setLastsessionStartTimestamp:(NSTimeInterval)timestamp; + +- (BOOL)isOptedOut; +- (BOOL)setOptedOut:(BOOL)optOut; +- (NSString *)installId; +- (NSString *)appKey; // Most recent app key-- may not be that used to open the session. + +- (NSString *)customDimension:(int)dimension; +- (BOOL)setCustomDimension:(int)dimension value:(NSString *)value; + +- (NSString *)customerId; +- (BOOL)setCustomerId:(NSString *)newCustomerId; + +- (NSInteger)safeIntegerValueFromDictionary:(NSDictionary *)dict forKey:(NSString *)key; +- (NSString *)safeStringValueFromDictionary:(NSDictionary *)dict forKey:(NSString *)key; +- (NSDictionary *)safeDictionaryFromDictionary:(NSDictionary *)dict forKey:(NSString *)key; +- (NSArray *)safeListFromDictionary:(NSDictionary *)dict forKey:(NSString *)key; + + +@end diff --git a/Localytics/LocalyticsDatabase.m b/Localytics/LocalyticsDatabase.m index 3b3700fe..2dc9216c 100644 --- a/Localytics/LocalyticsDatabase.m +++ b/Localytics/LocalyticsDatabase.m @@ -1,743 +1,1037 @@ -// -// LocalyticsDatabase.m -// LocalyticsDemo -// -// Created by jkaufman on 5/26/11. -// Copyright 2011 Localytics. All rights reserved. -// - -#import "LocalyticsDatabase.h" - -#define LOCALYTICS_DIR @".localytics" // Name for the directory in which Localytics database is stored -#define LOCALYTICS_DB @"localytics" // File name for the database (without extension) -#define BUSY_TIMEOUT 30 // Maximum time SQlite will busy-wait for the database to unlock before returning SQLITE_BUSY - -@interface LocalyticsDatabase () - - (int)schemaVersion; - - (void)createSchema; - - (void)upgradeToSchemaV2; - - (void)upgradeToSchemaV3; - - (void)moveDbToCaches; - - (NSString *)randomUUID; -@end - -@implementation LocalyticsDatabase - -// The singleton database object. -static LocalyticsDatabase *_sharedLocalyticsDatabase = nil; - -+ (NSString *)localyticsDirectoryPath { - NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); - return [[paths objectAtIndex:0] stringByAppendingPathComponent:LOCALYTICS_DIR]; -} - -+ (NSString *)localyticsDatabasePath { - NSString *path = [[LocalyticsDatabase localyticsDirectoryPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.sqlite", LOCALYTICS_DB]]; - return path; -} - -#pragma mark Singleton Class -+ (LocalyticsDatabase *)sharedLocalyticsDatabase { - @synchronized(self) { - if (_sharedLocalyticsDatabase == nil) { - _sharedLocalyticsDatabase = [[self alloc] init]; - } - } - return _sharedLocalyticsDatabase; -} - -- (LocalyticsDatabase *)init { - if((self = [super init])) { - - // Mover any data that a previous library may have left in the documents directory - [self moveDbToCaches]; - - // Create directory structure for Localytics. - NSString *directoryPath = [LocalyticsDatabase localyticsDirectoryPath]; - if (![[NSFileManager defaultManager] fileExistsAtPath:directoryPath]) { - [[NSFileManager defaultManager] createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:nil]; - } - - // Attempt to open database. It will be created if it does not exist, already. - NSString *dbPath = [LocalyticsDatabase localyticsDatabasePath]; - int code = sqlite3_open([dbPath UTF8String], &_databaseConnection); - - // If we were unable to open the database, it is likely corrupted. Clobber it and move on. - if (code != SQLITE_OK) { - [[NSFileManager defaultManager] removeItemAtPath:dbPath error:nil]; - code = sqlite3_open([dbPath UTF8String], &_databaseConnection); - } - - // Check db connection, creating schema if necessary. - if (code == SQLITE_OK) { - sqlite3_busy_timeout(_databaseConnection, BUSY_TIMEOUT); // Defaults to 0, otherwise. - if ([self schemaVersion] == 0) { - [self createSchema]; - } - } - - // Perform any Migrations if necessary - if ([self schemaVersion] < 2) { - [self upgradeToSchemaV2]; - } - if ([self schemaVersion] < 3) { - [self upgradeToSchemaV3]; - } - } - - return self; -} - -#pragma mark - Database - -- (BOOL)beginTransaction:(NSString *)name { - const char *sql = [[NSString stringWithFormat:@"SAVEPOINT %@", name] cStringUsingEncoding:NSUTF8StringEncoding]; - int code = sqlite3_exec(_databaseConnection, sql, NULL, NULL, NULL); - return code == SQLITE_OK; -} - -- (BOOL)releaseTransaction:(NSString *)name { - const char *sql = [[NSString stringWithFormat:@"RELEASE SAVEPOINT %@", name] cStringUsingEncoding:NSUTF8StringEncoding]; - int code = sqlite3_exec(_databaseConnection, sql, NULL, NULL, NULL); - return code == SQLITE_OK; -} - -- (BOOL)rollbackTransaction:(NSString *)name { - const char *sql = [[NSString stringWithFormat:@"ROLLBACK SAVEPOINT %@", name] cStringUsingEncoding:NSUTF8StringEncoding]; - int code = sqlite3_exec(_databaseConnection, sql, NULL, NULL, NULL); - return code == SQLITE_OK; -} - -- (int)schemaVersion { - int version = 0; - const char *sql = "SELECT MAX(schema_version) FROM localytics_info"; - sqlite3_stmt *selectSchemaVersion; - if(sqlite3_prepare_v2(_databaseConnection, sql, -1, &selectSchemaVersion, NULL) == SQLITE_OK) { - if(sqlite3_step(selectSchemaVersion) == SQLITE_ROW) { - version = sqlite3_column_int(selectSchemaVersion, 0); - } - } - sqlite3_finalize(selectSchemaVersion); - return version; -} - -- (NSString *)installId { - NSString *installId = nil; - - sqlite3_stmt *selectInstallId; - sqlite3_prepare_v2(_databaseConnection, "SELECT install_id FROM localytics_info", -1, &selectInstallId, NULL); - int code = sqlite3_step(selectInstallId); - if (code == SQLITE_ROW && sqlite3_column_text(selectInstallId, 0)) { - installId = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectInstallId, 0)]; - } - sqlite3_finalize(selectInstallId); - - return installId; -} - -- (NSString *)appKey { - NSString *appKey = nil; - - sqlite3_stmt *selectAppKey; - sqlite3_prepare_v2(_databaseConnection, "SELECT app_key FROM localytics_info", -1, &selectAppKey, NULL); - int code = sqlite3_step(selectAppKey); - if (code == SQLITE_ROW && sqlite3_column_text(selectAppKey, 0)) { - appKey = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectAppKey, 0)]; - } - sqlite3_finalize(selectAppKey); - - return appKey; -} - -// Due to the new iOS storage guidelines it is necessary to move the database out of the documents directory -// and into the /library/caches directory -- (void)moveDbToCaches { - NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); - NSString *localyticsDocumentsDirectory = [[documentPaths objectAtIndex:0] stringByAppendingPathComponent:LOCALYTICS_DIR]; - NSArray *cachesPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); - NSString *localyticsCachesDirectory = [[cachesPaths objectAtIndex:0] stringByAppendingPathComponent:LOCALYTICS_DIR]; - - // If the old directory doesn't exist, there is nothing else to do here - if([[NSFileManager defaultManager] fileExistsAtPath:localyticsDocumentsDirectory] == NO) - { - return; - } - - // Try to move the directory - if(NO == [[NSFileManager defaultManager] moveItemAtPath:localyticsDocumentsDirectory - toPath:localyticsCachesDirectory - error:nil]) - { - // If the move failed try and, delete the old directory - [ [NSFileManager defaultManager] removeItemAtPath:localyticsDocumentsDirectory error:nil]; - } -} - -- (void)createSchema { - int code = SQLITE_OK; - - // Execute schema creation within a single transaction. - code = sqlite3_exec(_databaseConnection, "BEGIN", NULL, NULL, NULL); - - if (code == SQLITE_OK) { - code = sqlite3_exec(_databaseConnection, - "CREATE TABLE upload_headers (" - "sequence_number INTEGER PRIMARY KEY, " - "blob_string TEXT)", - NULL, NULL, NULL); - } - - if (code == SQLITE_OK) { - code = sqlite3_exec(_databaseConnection, - "CREATE TABLE events (" - "event_id INTEGER PRIMARY KEY AUTOINCREMENT, " // In case foreign key constraints are reintroduced. - "upload_header INTEGER, " - "blob_string TEXT NOT NULL)", - NULL, NULL, NULL); - } - - if (code == SQLITE_OK) { - code = sqlite3_exec(_databaseConnection, - "CREATE TABLE localytics_info (" - "schema_version INTEGER PRIMARY KEY, " - "last_upload_number INTEGER, " - "last_session_number INTEGER, " - "opt_out BOOLEAN, " - "last_close_event INTEGER, " - "last_flow_event INTEGER, " - "last_session_start REAL, " - "app_key CHAR(64), " - "custom_d0 CHAR(64), " - "custom_d1 CHAR(64), " - "custom_d2 CHAR(64), " - "custom_d3 CHAR(64) " - ")", - NULL, NULL, NULL); - } - - if (code == SQLITE_OK) { - code = sqlite3_exec(_databaseConnection, - "INSERT INTO localytics_info (schema_version, last_upload_number, last_session_number, opt_out) " - "VALUES (3, 0, 0, 0)", NULL, NULL, NULL); - } - - // Commit transaction. - if (code == SQLITE_OK || code == SQLITE_DONE) { - sqlite3_exec(_databaseConnection, "COMMIT", NULL, NULL, NULL); - } else { - sqlite3_exec(_databaseConnection, "ROLLBACK", NULL, NULL, NULL); - } -} - -// V2 adds a unique identifier for each installation -// This identifier has been moved to user preferences so the database an live in the caches directory -// Also adds storage for custom dimensions -- (void)upgradeToSchemaV2 { - int code = SQLITE_OK; - - code = sqlite3_exec(_databaseConnection, "BEGIN", NULL, NULL, NULL); - - if (code == SQLITE_OK) { - code = sqlite3_exec(_databaseConnection, - "ALTER TABLE localytics_info ADD install_id CHAR(40)", - NULL, NULL, NULL); - } - - if (code == SQLITE_OK) { - code = sqlite3_exec(_databaseConnection, - "ALTER TABLE localytics_info ADD custom_d0 CHAR(64)", - NULL, NULL, NULL); - } - - if (code == SQLITE_OK) { - code = sqlite3_exec(_databaseConnection, - "ALTER TABLE localytics_info ADD custom_d1 CHAR(64)", - NULL, NULL, NULL); - } - - if (code == SQLITE_OK) { - code = sqlite3_exec(_databaseConnection, - "ALTER TABLE localytics_info ADD custom_d2 CHAR(64)", - NULL, NULL, NULL); - } - - if (code == SQLITE_OK) { - sqlite3_exec(_databaseConnection, - "ALTER TABLE localytics_info ADD custom_d3 CHAR(64)", - NULL, NULL, NULL); - } - - // Attempt to set schema version and install_id regardless of the result code following the ALTER statements above. - // This is necessary because a previous version of the library performed the migration without setting these values. - // The transaction will succeed even if the individual statements fail with errors (eg. "duplicate column name"). - sqlite3_stmt *updateLocalyticsInfo; - sqlite3_prepare_v2(_databaseConnection, "UPDATE localytics_info set install_id = ?, schema_version = 2 ", -1, &updateLocalyticsInfo, NULL); - sqlite3_bind_text (updateLocalyticsInfo, 1, [[self randomUUID] UTF8String], -1, SQLITE_TRANSIENT); - code = sqlite3_step(updateLocalyticsInfo); - sqlite3_finalize(updateLocalyticsInfo); - - // Commit transaction. - if (code == SQLITE_OK || code == SQLITE_DONE) { - sqlite3_exec(_databaseConnection, "COMMIT", NULL, NULL, NULL); - } else { - sqlite3_exec(_databaseConnection, "ROLLBACK", NULL, NULL, NULL); - } -} - -// V3 adds a field for the last app key and patches a V2 migration issue. -- (void)upgradeToSchemaV3 { - sqlite3_exec(_databaseConnection, - "ALTER TABLE localytics_info ADD app_key CHAR(64)", - NULL, NULL, NULL); -} - -- (NSUInteger)databaseSize { - NSUInteger size = 0; - NSDictionary *fileAttributes = [[NSFileManager defaultManager] - attributesOfItemAtPath:[LocalyticsDatabase localyticsDatabasePath] - error:nil]; - size = [fileAttributes fileSize]; - return size; -} - -- (int) eventCount { - int count = 0; - const char *sql = "SELECT count(*) FROM events"; - sqlite3_stmt *selectEventCount; - - if(sqlite3_prepare_v2(_databaseConnection, sql, -1, &selectEventCount, NULL) == SQLITE_OK) - { - if(sqlite3_step(selectEventCount) == SQLITE_ROW) { - count = sqlite3_column_int(selectEventCount, 0); - } - } - sqlite3_finalize(selectEventCount); - - return count; -} - -- (NSTimeInterval)createdTimestamp { - NSTimeInterval timestamp = 0; - NSDictionary *fileAttributes = [[NSFileManager defaultManager] - attributesOfItemAtPath:[LocalyticsDatabase localyticsDatabasePath] - error:nil]; - timestamp = [[fileAttributes fileCreationDate] timeIntervalSince1970]; - return timestamp; -} - -- (NSTimeInterval)lastSessionStartTimestamp { - - NSTimeInterval lastSessionStart = 0; - - sqlite3_stmt *selectLastSessionStart; - sqlite3_prepare_v2(_databaseConnection, "SELECT last_session_start FROM localytics_info", -1, &selectLastSessionStart, NULL); - int code = sqlite3_step(selectLastSessionStart); - if (code == SQLITE_ROW) { - lastSessionStart = sqlite3_column_double(selectLastSessionStart, 0) == 1; - } - sqlite3_finalize(selectLastSessionStart); - - return lastSessionStart; -} - -- (BOOL)setLastsessionStartTimestamp:(NSTimeInterval)timestamp { - sqlite3_stmt *updateLastSessionStart; - sqlite3_prepare_v2(_databaseConnection, "UPDATE localytics_info SET last_session_start = ?", -1, &updateLastSessionStart, NULL); - sqlite3_bind_double(updateLastSessionStart, 1, timestamp); - int code = sqlite3_step(updateLastSessionStart); - sqlite3_finalize(updateLastSessionStart); - - return code == SQLITE_DONE; -} - -- (BOOL)isOptedOut { - BOOL optedOut = NO; - - sqlite3_stmt *selectOptOut; - sqlite3_prepare_v2(_databaseConnection, "SELECT opt_out FROM localytics_info", -1, &selectOptOut, NULL); - int code = sqlite3_step(selectOptOut); - if (code == SQLITE_ROW) { - optedOut = sqlite3_column_int(selectOptOut, 0) == 1; - } - sqlite3_finalize(selectOptOut); - - return optedOut; -} - -- (BOOL)setOptedOut:(BOOL)optOut { - sqlite3_stmt *updateOptedOut; - sqlite3_prepare_v2(_databaseConnection, "UPDATE localytics_info SET opt_out = ?", -1, &updateOptedOut, NULL); - sqlite3_bind_int(updateOptedOut, 1, optOut); - int code = sqlite3_step(updateOptedOut); - sqlite3_finalize(updateOptedOut); - - return code == SQLITE_OK; -} - -- (NSString *)customDimension:(int)dimension { - if(dimension < 0 || dimension > 3) { - return nil; - } - - NSString *value = nil; - NSString *query = [NSString stringWithFormat:@"select custom_d%i from localytics_info", dimension]; - - sqlite3_stmt *selectCustomDim; - sqlite3_prepare_v2(_databaseConnection, [query UTF8String], -1, &selectCustomDim, NULL); - int code = sqlite3_step(selectCustomDim); - if (code == SQLITE_ROW && sqlite3_column_text(selectCustomDim, 0)) { - value = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectCustomDim, 0)]; - } - sqlite3_finalize(selectCustomDim); - - return value; -} - -- (BOOL)setCustomDimension:(int)dimension value:(NSString *)value { - if(dimension < 0 || dimension > 3) { - return false; - } - - NSString *query = [NSString stringWithFormat:@"update localytics_info SET custom_d%i = %@", - dimension, - (value == nil) ? @"null" : [NSString stringWithFormat:@"\"%@\"", value]]; - - int code = sqlite3_exec(_databaseConnection, [query UTF8String], NULL, NULL, NULL); - - return code == SQLITE_OK; -} - -- (BOOL)incrementLastUploadNumber:(int *)uploadNumber { - NSString *t = @"increment_upload_number"; - int code = SQLITE_OK; - - code = [self beginTransaction:t] ? SQLITE_OK : SQLITE_ERROR; - - if(code == SQLITE_OK) { - // Increment value - code = sqlite3_exec(_databaseConnection, - "UPDATE localytics_info " - "SET last_upload_number = (last_upload_number + 1)", - NULL, NULL, NULL); - } - - if(code == SQLITE_OK) { - // Retrieve new value - sqlite3_stmt *selectUploadNumber; - sqlite3_prepare_v2(_databaseConnection, - "SELECT last_upload_number FROM localytics_info", - -1, &selectUploadNumber, NULL); - code = sqlite3_step(selectUploadNumber); - if (code == SQLITE_ROW) { - *uploadNumber = sqlite3_column_int(selectUploadNumber, 0); - } - sqlite3_finalize(selectUploadNumber); - } - - if(code == SQLITE_ROW) { - [self releaseTransaction:t]; - } else { - [self rollbackTransaction:t]; - } - - return code == SQLITE_ROW; -} - -- (BOOL)incrementLastSessionNumber:(int *)sessionNumber { - NSString *t = @"increment_session_number"; - int code = [self beginTransaction:t] ? SQLITE_OK : SQLITE_ERROR; - - if(code == SQLITE_OK) { - // Increment value - code = sqlite3_exec(_databaseConnection, - "UPDATE localytics_info " - "SET last_session_number = (last_session_number + 1)", - NULL, NULL, NULL); - } - - if(code == SQLITE_OK) { - // Retrieve new value - sqlite3_stmt *selectSessionNumber; - sqlite3_prepare_v2(_databaseConnection, - "SELECT last_session_number FROM localytics_info", - -1, &selectSessionNumber, NULL); - code = sqlite3_step(selectSessionNumber); - if (code == SQLITE_ROW && sessionNumber != NULL) { - *sessionNumber = sqlite3_column_int(selectSessionNumber, 0); - } - sqlite3_finalize(selectSessionNumber); - } - - if(code == SQLITE_ROW) { - [self releaseTransaction:t]; - } else { - [self rollbackTransaction:t]; - } - - return code == SQLITE_ROW; -} - -- (BOOL)addEventWithBlobString:(NSString *)blob { - - int code = SQLITE_OK; - sqlite3_stmt *insertEvent; - sqlite3_prepare_v2(_databaseConnection, "INSERT INTO events (blob_string) VALUES (?)", -1, &insertEvent, NULL); - sqlite3_bind_text(insertEvent, 1, [blob UTF8String], -1, SQLITE_TRANSIENT); - code = sqlite3_step(insertEvent); - sqlite3_finalize(insertEvent); - - return code == SQLITE_DONE; -} - -- (BOOL)addCloseEventWithBlobString:(NSString *)blob { - NSString *t = @"add_close_event"; - BOOL success = [self beginTransaction:t]; - - // Add close event. - if (success) { - success = [self addEventWithBlobString:blob]; - } - - // Record row id to localytics_info so that it can be removed if the session resumes. - if (success) { - sqlite3_stmt *updateCloseEvent; - sqlite3_prepare_v2(_databaseConnection, "UPDATE localytics_info SET last_close_event = (SELECT event_id FROM events WHERE rowid = ?)", -1, &updateCloseEvent, NULL); - sqlite3_int64 lastRow = sqlite3_last_insert_rowid(_databaseConnection); - sqlite3_bind_int64(updateCloseEvent, 1, lastRow); - int code = sqlite3_step(updateCloseEvent); - sqlite3_finalize(updateCloseEvent); - success = code == SQLITE_DONE; - } - - if (success) { - [self releaseTransaction:t]; - } else { - [self rollbackTransaction:t]; - } - return success; -} - -- (BOOL)addFlowEventWithBlobString:(NSString *)blob { - NSString *t = @"add_flow_event"; - BOOL success = [self beginTransaction:t]; - - // Add flow event. - if (success) { - success = [self addEventWithBlobString:blob]; - } - - // Record row id to localytics_info so that it can be removed if the session resumes. - if (success) { - sqlite3_stmt *updateFlowEvent; - sqlite3_prepare_v2(_databaseConnection, "UPDATE localytics_info SET last_flow_event = (SELECT event_id FROM events WHERE rowid = ?)", -1, &updateFlowEvent, NULL); - sqlite3_int64 lastRow = sqlite3_last_insert_rowid(_databaseConnection); - sqlite3_bind_int64(updateFlowEvent, 1, lastRow); - int code = sqlite3_step(updateFlowEvent); - sqlite3_finalize(updateFlowEvent); - success = code == SQLITE_DONE; - } - - if (success) { - [self releaseTransaction:t]; - } else { - [self rollbackTransaction:t]; - } - return success; -} - -- (BOOL)removeLastCloseAndFlowEvents { - // Attempt to remove the last recorded close event. - // Fail quietly if none was saved or it was previously removed. - int code = sqlite3_exec(_databaseConnection, "DELETE FROM events WHERE event_id = (SELECT last_close_event FROM localytics_info) OR event_id = (SELECT last_flow_event FROM localytics_info)", NULL, NULL, NULL); - - return code == SQLITE_OK; -} - -- (BOOL)addHeaderWithSequenceNumber:(int)number blobString:(NSString *)blob rowId:(sqlite3_int64 *)insertedRowId { - sqlite3_stmt *insertHeader; - sqlite3_prepare_v2(_databaseConnection, "INSERT INTO upload_headers (sequence_number, blob_string) VALUES (?, ?)", -1, &insertHeader, NULL); - sqlite3_bind_int(insertHeader, 1, number); - sqlite3_bind_text(insertHeader, 2, [blob UTF8String], -1, SQLITE_TRANSIENT); - int code = sqlite3_step(insertHeader); - sqlite3_finalize(insertHeader); - - if (code == SQLITE_DONE && insertedRowId != NULL) { - *insertedRowId = sqlite3_last_insert_rowid(_databaseConnection); - } - - return code == SQLITE_DONE; -} - -- (int)unstagedEventCount { - int rowCount = 0; - sqlite3_stmt *selectEventCount; - sqlite3_prepare_v2(_databaseConnection, "SELECT COUNT(*) FROM events WHERE UPLOAD_HEADER IS NULL", -1, &selectEventCount, NULL); - int code = sqlite3_step(selectEventCount); - if (code == SQLITE_ROW) { - rowCount = sqlite3_column_int(selectEventCount, 0); - } - sqlite3_finalize(selectEventCount); - - return rowCount; -} - -- (BOOL)stageEventsForUpload:(sqlite3_int64)headerId { - - // Associate all outstanding events with the given upload header ID. - NSString *stageEvents = [NSString stringWithFormat:@"UPDATE events SET upload_header = ? WHERE upload_header IS NULL"]; - sqlite3_stmt *updateEvents; - sqlite3_prepare_v2(_databaseConnection, [stageEvents UTF8String], -1, &updateEvents, NULL); - sqlite3_bind_int(updateEvents, 1, headerId); - int code = sqlite3_step(updateEvents); - sqlite3_finalize(updateEvents); - BOOL success = (code == SQLITE_DONE); - - return success; -} - -- (BOOL)updateAppKey:(NSString *)appKey { - sqlite3_stmt *updateAppKey; - sqlite3_prepare_v2(_databaseConnection, "UPDATE localytics_info set app_key = ?", -1, &updateAppKey, NULL); - sqlite3_bind_text (updateAppKey, 1, [appKey UTF8String], -1, SQLITE_TRANSIENT); - int code = sqlite3_step(updateAppKey); - sqlite3_finalize(updateAppKey); - BOOL success = (code == SQLITE_DONE); - - return success; -} - -- (NSString *)uploadBlobString { - - // Retrieve the blob strings of each upload header and its child events, in order. - const char *sql = "SELECT * FROM ( " - " SELECT h.blob_string AS 'blob', h.sequence_number as 'seq', 0 FROM upload_headers h" - " UNION ALL " - " SELECT e.blob_string AS 'blob', e.upload_header as 'seq', 1 FROM events e" - ") " - "ORDER BY 2, 3"; - sqlite3_stmt *selectBlobs; - sqlite3_prepare_v2(_databaseConnection, sql, -1, &selectBlobs, NULL); - NSMutableString *uploadBlobString = [NSMutableString string]; - while (sqlite3_step(selectBlobs) == SQLITE_ROW) { - const char *blob = (const char *)sqlite3_column_text(selectBlobs, 0); - if (blob != NULL) { - NSString *blobString = [[NSString alloc] initWithCString:blob encoding:NSUTF8StringEncoding]; - [uploadBlobString appendString:blobString]; - [blobString release]; - } - } - sqlite3_finalize(selectBlobs); - - return [[uploadBlobString copy] autorelease]; -} - -- (BOOL)deleteUploadedData { - // Delete all headers and staged events. - NSString *t = @"delete_upload_data"; - int code = [self beginTransaction:t] ? SQLITE_OK : SQLITE_ERROR; - - if (code == SQLITE_OK) { - code = sqlite3_exec(_databaseConnection, "DELETE FROM events WHERE upload_header IS NOT NULL", NULL, NULL, NULL); - } - - if (code == SQLITE_OK) { - code = sqlite3_exec(_databaseConnection, "DELETE FROM upload_headers", NULL, NULL, NULL); - } - - if (code == SQLITE_OK) { - [self releaseTransaction:t]; - } else { - [self rollbackTransaction:t]; - } - - return code == SQLITE_OK; -} - -- (BOOL)resetAnalyticsData { - // Delete or zero all analytics data. - // Reset: headers, events, session number, upload number, last session start, last close event, and last flow event. - // Unaffected: schema version, opt out status, install ID (deprecated), and app key. - - NSString *t = @"reset_analytics_data"; - int code = [self beginTransaction:t] ? SQLITE_OK : SQLITE_ERROR; - - if (code == SQLITE_OK) { - code = sqlite3_exec(_databaseConnection, "DELETE FROM events", NULL, NULL, NULL); - } - - if (code == SQLITE_OK) { - code = sqlite3_exec(_databaseConnection, "DELETE FROM upload_headers", NULL, NULL, NULL); - } - - if (code == SQLITE_OK) { - code = sqlite3_exec(_databaseConnection,"UPDATE localytics_info SET last_session_number = 0, last_upload_number = 0," - "last_close_event = null, last_flow_event = null, last_session_start = null, " - "custom_d0 = null, custom_d1 = null, custom_d2 = null, custom_d3 = null", - NULL, NULL, NULL); - } - - if (code == SQLITE_OK) { - [self releaseTransaction:t]; - } else { - [self rollbackTransaction:t]; - } - - return code == SQLITE_OK; -} - -- (BOOL)vacuumIfRequired { - int code = SQLITE_OK; - if ([self databaseSize] > MAX_DATABASE_SIZE * VACUUM_THRESHOLD) { - code = sqlite3_exec(_databaseConnection, "VACUUM", NULL, NULL, NULL); - } - - return code == SQLITE_OK; -} - -- (NSString *)randomUUID { - CFUUIDRef theUUID = CFUUIDCreate(NULL); - CFStringRef stringUUID = CFUUIDCreateString(NULL, theUUID); - CFRelease(theUUID); - return [(NSString *)stringUUID autorelease]; -} - -#pragma mark - Lifecycle - -+ (id)allocWithZone:(NSZone *)zone { - @synchronized(self) { - if (_sharedLocalyticsDatabase == nil) { - _sharedLocalyticsDatabase = [super allocWithZone:zone]; - return _sharedLocalyticsDatabase; - } - } - // returns nil on subsequent allocations - return nil; -} - -- (id)copyWithZone:(NSZone *)zone { - return self; -} - -- (id)retain { - return self; -} - -- (unsigned)retainCount { - // maximum value of an unsigned int - prevents additional retains for the class - return UINT_MAX; -} - -- (oneway void)release { - // ignore release commands -} - -- (id)autorelease { - return self; -} - -- (void)dealloc { - sqlite3_close(_databaseConnection); - [super dealloc]; -} - -@end +// +// LocalyticsDatabase.m +// Copyright (C) 2012 Char Software Inc., DBA Localytics +// +// This code is provided under the Localytics Modified BSD License. +// A copy of this license has been distributed in a file called LICENSE +// with this source code. +// +// Please visit www.localytics.com for more information. + +#import "LocalyticsDatabase.h" + +#define LOCALYTICS_DIR @".localytics" // Name for the directory in which Localytics database is stored +#define LOCALYTICS_DB @"localytics" // File name for the database (without extension) +#define BUSY_TIMEOUT 30 // Maximum time SQlite will busy-wait for the database to unlock before returning SQLITE_BUSY + +@interface LocalyticsDatabase () + - (int)schemaVersion; + - (void)createSchema; + - (void)upgradeToSchemaV2; + - (void)upgradeToSchemaV3; + - (void)upgradeToSchemaV4; + - (void)upgradeToSchemaV5; + - (void)upgradeToSchemaV6; +- (void)upgradeToSchemaV7; + - (void)moveDbToCaches; + - (NSString *)randomUUID; +@end + +@implementation LocalyticsDatabase + +// The singleton database object. +static LocalyticsDatabase *_sharedLocalyticsDatabase = nil; + ++ (NSString *)localyticsDirectoryPath { + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); + return [[paths objectAtIndex:0] stringByAppendingPathComponent:LOCALYTICS_DIR]; +} + ++ (NSString *)localyticsDatabasePath { + NSString *path = [[LocalyticsDatabase localyticsDirectoryPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.sqlite", LOCALYTICS_DB]]; + return path; +} + +#pragma mark Singleton Class ++ (LocalyticsDatabase *)sharedLocalyticsDatabase { + @synchronized(self) { + if (_sharedLocalyticsDatabase == nil) { + _sharedLocalyticsDatabase = [[self alloc] init]; + } + } + return _sharedLocalyticsDatabase; +} + +- (LocalyticsDatabase *)init { + if((self = [super init])) { + + // Mover any data that a previous library may have left in the documents directory + [self moveDbToCaches]; + + // Create directory structure for Localytics. + NSString *directoryPath = [LocalyticsDatabase localyticsDirectoryPath]; + if (![[NSFileManager defaultManager] fileExistsAtPath:directoryPath]) { + [[NSFileManager defaultManager] createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:nil]; + } + + // Attempt to open database. It will be created if it does not exist, already. + NSString *dbPath = [LocalyticsDatabase localyticsDatabasePath]; + int code = sqlite3_open([dbPath UTF8String], &_databaseConnection); + + // If we were unable to open the database, it is likely corrupted. Clobber it and move on. + if (code != SQLITE_OK) { + [[NSFileManager defaultManager] removeItemAtPath:dbPath error:nil]; + code = sqlite3_open([dbPath UTF8String], &_databaseConnection); + } + + // Enable foreign key constraints. + if (code == SQLITE_OK) { + const char *sql = [@"PRAGMA foreign_keys = ON;" cStringUsingEncoding:NSUTF8StringEncoding]; + code = sqlite3_exec(_databaseConnection, sql, NULL, NULL, NULL); + } + + // Check db connection, creating schema if necessary. + if (code == SQLITE_OK) { + sqlite3_busy_timeout(_databaseConnection, BUSY_TIMEOUT); // Defaults to 0, otherwise. + if ([self schemaVersion] == 0) { + [self createSchema]; + } + } + + // Perform any Migrations if necessary + if ([self schemaVersion] < 2) { + [self upgradeToSchemaV2]; + } + if ([self schemaVersion] < 3) { + [self upgradeToSchemaV3]; + } + if ([self schemaVersion] < 4) { + [self upgradeToSchemaV4]; + } + if ([self schemaVersion] < 5) { + [self upgradeToSchemaV5]; + } + if ([self schemaVersion] < 6) { + [self upgradeToSchemaV6]; + } + if ([self schemaVersion] < 7) { + [self upgradeToSchemaV7]; + } + } + + return self; +} + +#pragma mark - Database + +- (BOOL)beginTransaction:(NSString *)name { + const char *sql = [[NSString stringWithFormat:@"SAVEPOINT %@", name] cStringUsingEncoding:NSUTF8StringEncoding]; + int code = sqlite3_exec(_databaseConnection, sql, NULL, NULL, NULL); + return code == SQLITE_OK; +} + +- (BOOL)releaseTransaction:(NSString *)name { + const char *sql = [[NSString stringWithFormat:@"RELEASE SAVEPOINT %@", name] cStringUsingEncoding:NSUTF8StringEncoding]; + int code = sqlite3_exec(_databaseConnection, sql, NULL, NULL, NULL); + return code == SQLITE_OK; +} + +- (BOOL)rollbackTransaction:(NSString *)name { + const char *sql = [[NSString stringWithFormat:@"ROLLBACK SAVEPOINT %@", name] cStringUsingEncoding:NSUTF8StringEncoding]; + int code = sqlite3_exec(_databaseConnection, sql, NULL, NULL, NULL); + return code == SQLITE_OK; +} + +- (int)schemaVersion { + int version = 0; + const char *sql = "SELECT MAX(schema_version) FROM localytics_info"; + sqlite3_stmt *selectSchemaVersion; + if(sqlite3_prepare_v2(_databaseConnection, sql, -1, &selectSchemaVersion, NULL) == SQLITE_OK) { + if(sqlite3_step(selectSchemaVersion) == SQLITE_ROW) { + version = sqlite3_column_int(selectSchemaVersion, 0); + } + } + sqlite3_finalize(selectSchemaVersion); + return version; +} + +- (NSString *)installId { + NSString *installId = nil; + + sqlite3_stmt *selectInstallId; + sqlite3_prepare_v2(_databaseConnection, "SELECT install_id FROM localytics_info", -1, &selectInstallId, NULL); + int code = sqlite3_step(selectInstallId); + if (code == SQLITE_ROW && sqlite3_column_text(selectInstallId, 0)) { + installId = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectInstallId, 0)]; + } + sqlite3_finalize(selectInstallId); + + return installId; +} + +- (NSString *)appKey { + NSString *appKey = nil; + + sqlite3_stmt *selectAppKey; + sqlite3_prepare_v2(_databaseConnection, "SELECT app_key FROM localytics_info", -1, &selectAppKey, NULL); + int code = sqlite3_step(selectAppKey); + if (code == SQLITE_ROW && sqlite3_column_text(selectAppKey, 0)) { + appKey = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectAppKey, 0)]; + } + sqlite3_finalize(selectAppKey); + + return appKey; +} + +// Due to the new iOS storage guidelines it is necessary to move the database out of the documents directory +// and into the /library/caches directory +- (void)moveDbToCaches { + NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *localyticsDocumentsDirectory = [[documentPaths objectAtIndex:0] stringByAppendingPathComponent:LOCALYTICS_DIR]; + NSArray *cachesPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); + NSString *localyticsCachesDirectory = [[cachesPaths objectAtIndex:0] stringByAppendingPathComponent:LOCALYTICS_DIR]; + + // If the old directory doesn't exist, there is nothing else to do here + if([[NSFileManager defaultManager] fileExistsAtPath:localyticsDocumentsDirectory] == NO) + { + return; + } + + // Try to move the directory + if(NO == [[NSFileManager defaultManager] moveItemAtPath:localyticsDocumentsDirectory + toPath:localyticsCachesDirectory + error:nil]) + { + // If the move failed try and, delete the old directory + [ [NSFileManager defaultManager] removeItemAtPath:localyticsDocumentsDirectory error:nil]; + } +} + +- (void)createSchema { + int code = SQLITE_OK; + + // Execute schema creation within a single transaction. + code = sqlite3_exec(_databaseConnection, "BEGIN", NULL, NULL, NULL); + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection, + "CREATE TABLE upload_headers (" + "sequence_number INTEGER PRIMARY KEY, " + "blob_string TEXT)", + NULL, NULL, NULL); + } + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection, + "CREATE TABLE events (" + "event_id INTEGER PRIMARY KEY AUTOINCREMENT, " // In case foreign key constraints are reintroduced. + "upload_header INTEGER, " + "blob_string TEXT NOT NULL)", + NULL, NULL, NULL); + } + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection, + "CREATE TABLE localytics_info (" + "schema_version INTEGER PRIMARY KEY, " + "last_upload_number INTEGER, " + "last_session_number INTEGER, " + "opt_out BOOLEAN, " + "last_close_event INTEGER, " + "last_flow_event INTEGER, " + "last_session_start REAL, " + "app_key CHAR(64), " + "custom_d0 CHAR(64), " + "custom_d1 CHAR(64), " + "custom_d2 CHAR(64), " + "custom_d3 CHAR(64) " + ")", + NULL, NULL, NULL); + } + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection, + "INSERT INTO localytics_info (schema_version, last_upload_number, last_session_number, opt_out) " + "VALUES (3, 0, 0, 0)", NULL, NULL, NULL); + } + + // Commit transaction. + if (code == SQLITE_OK || code == SQLITE_DONE) { + sqlite3_exec(_databaseConnection, "COMMIT", NULL, NULL, NULL); + } else { + sqlite3_exec(_databaseConnection, "ROLLBACK", NULL, NULL, NULL); + } +} + +// V2 adds a unique identifier for each installation +// This identifier has been moved to user preferences so the database an live in the caches directory +// Also adds storage for custom dimensions +- (void)upgradeToSchemaV2 { + int code = SQLITE_OK; + + code = sqlite3_exec(_databaseConnection, "BEGIN", NULL, NULL, NULL); + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection, + "ALTER TABLE localytics_info ADD install_id CHAR(40)", + NULL, NULL, NULL); + } + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection, + "ALTER TABLE localytics_info ADD custom_d0 CHAR(64)", + NULL, NULL, NULL); + } + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection, + "ALTER TABLE localytics_info ADD custom_d1 CHAR(64)", + NULL, NULL, NULL); + } + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection, + "ALTER TABLE localytics_info ADD custom_d2 CHAR(64)", + NULL, NULL, NULL); + } + + if (code == SQLITE_OK) { + sqlite3_exec(_databaseConnection, + "ALTER TABLE localytics_info ADD custom_d3 CHAR(64)", + NULL, NULL, NULL); + } + + // Attempt to set schema version and install_id regardless of the result code following the ALTER statements above. + // This is necessary because a previous version of the library performed the migration without setting these values. + // The transaction will succeed even if the individual statements fail with errors (eg. "duplicate column name"). + sqlite3_stmt *updateLocalyticsInfo; + sqlite3_prepare_v2(_databaseConnection, "UPDATE localytics_info set install_id = ?, schema_version = 2 ", -1, &updateLocalyticsInfo, NULL); + sqlite3_bind_text (updateLocalyticsInfo, 1, [[self randomUUID] UTF8String], -1, SQLITE_TRANSIENT); + code = sqlite3_step(updateLocalyticsInfo); + sqlite3_finalize(updateLocalyticsInfo); + + // Commit transaction. + if (code == SQLITE_OK || code == SQLITE_DONE) { + sqlite3_exec(_databaseConnection, "COMMIT", NULL, NULL, NULL); + } else { + sqlite3_exec(_databaseConnection, "ROLLBACK", NULL, NULL, NULL); + } +} + +// V3 adds a field for the last app key and patches a V2 migration issue. +- (void)upgradeToSchemaV3 { + int code = sqlite3_exec(_databaseConnection, "BEGIN", NULL, NULL, NULL); + + if (code == SQLITE_OK) { + sqlite3_exec(_databaseConnection, + "ALTER TABLE localytics_info ADD app_key CHAR(64)", + NULL, NULL, NULL); + } + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection, + "UPDATE localytics_info set schema_version = 3", + NULL, NULL, NULL); + } + + // Commit transaction. + if (code == SQLITE_OK || code == SQLITE_DONE) { + sqlite3_exec(_databaseConnection, "COMMIT", NULL, NULL, NULL); + } else { + sqlite3_exec(_databaseConnection, "ROLLBACK", NULL, NULL, NULL); + } +} + +// V4 adds a field for the customer id. +- (void)upgradeToSchemaV4 { + int code = sqlite3_exec(_databaseConnection, "BEGIN", NULL, NULL, NULL); + + if (code == SQLITE_OK) { + sqlite3_exec(_databaseConnection, + "ALTER TABLE localytics_info ADD customer_id CHAR(64)", + NULL, NULL, NULL); + } + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection, + "UPDATE localytics_info set schema_version = 4", + NULL, NULL, NULL); + } + + // Commit transaction. + if (code == SQLITE_OK || code == SQLITE_DONE) { + sqlite3_exec(_databaseConnection, "COMMIT", NULL, NULL, NULL); + } else { + sqlite3_exec(_databaseConnection, "ROLLBACK", NULL, NULL, NULL); + } +} + +// V5 adds AMP related tables. +- (void)upgradeToSchemaV5 { + + int code = sqlite3_exec(_databaseConnection, "BEGIN", NULL, NULL, NULL); + + //The AMP DB table was initially created here. in Version 7 it will be dropped and re-added with the correct data types. + //therefore the code that creates it is no longer going to be called here. + + //we still want to change the schema version + + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection, + "UPDATE localytics_info set schema_version = 5", + NULL, NULL, NULL); + } + + // Commit transaction. + if (code == SQLITE_OK || code == SQLITE_DONE) { + sqlite3_exec(_databaseConnection, "COMMIT", NULL, NULL, NULL); + } else { + sqlite3_exec(_databaseConnection, "ROLLBACK", NULL, NULL, NULL); + } +} + +// V6 adds a field for the queued close event blob string. +- (void)upgradeToSchemaV6 { + int code = sqlite3_exec(_databaseConnection, "BEGIN", NULL, NULL, NULL); + + if (code == SQLITE_OK) { + sqlite3_exec(_databaseConnection, + "ALTER TABLE localytics_info ADD queued_close_event_blob TEXT", + NULL, NULL, NULL); + } + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection, + "UPDATE localytics_info set schema_version = 6", + NULL, NULL, NULL); + } + + // Commit transaction. + if (code == SQLITE_OK || code == SQLITE_DONE) { + sqlite3_exec(_databaseConnection, "COMMIT", NULL, NULL, NULL); + } else { + sqlite3_exec(_databaseConnection, "ROLLBACK", NULL, NULL, NULL); + } +} + +-(void)upgradeToSchemaV7 { + int code = sqlite3_exec(_databaseConnection, "BEGIN", NULL, NULL, NULL); + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection, "DROP TABLE IF EXISTS localytics_amp_rule", NULL, NULL, NULL); + } + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection, + "CREATE TABLE IF NOT EXISTS localytics_amp_rule (" + "rule_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "rule_name TEXT UNIQUE, " + "expiration INTEGER, " + "phone_location TEXT, " + "phone_size_width INTEGER, " + "phone_size_height INTEGER, " + "tablet_location TEXT, " + "tablet_size_width INTEGER, " + "tablet_size_height INTEGER, " + "display_seconds INTEGER, " + "display_session INTEGER, " + "version INTEGER, " + "did_display INTEGER, " + "times_to_display INTEGER, " + "internet_required INTEGER, " + "ab_test TEXT" + ")", + NULL, NULL, NULL); + } + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection, + "CREATE TABLE IF NOT EXISTS localytics_amp_ruleevent (" + "rule_id INTEGER, " + "event_name TEXT, " + "FOREIGN KEY(rule_id) REFERENCES localytics_amp_rule(rule_id) ON DELETE CASCADE " + ")", + NULL, NULL, NULL); + } + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection, + "UPDATE localytics_info set schema_version = 7", + NULL, NULL, NULL); + } + + // Commit transaction. + if (code == SQLITE_OK || code == SQLITE_DONE) { + sqlite3_exec(_databaseConnection, "COMMIT", NULL, NULL, NULL); + } else { + sqlite3_exec(_databaseConnection, "ROLLBACK", NULL, NULL, NULL); + } +} + +- (NSUInteger)databaseSize { + NSUInteger size = 0; + NSDictionary *fileAttributes = [[NSFileManager defaultManager] + attributesOfItemAtPath:[LocalyticsDatabase localyticsDatabasePath] + error:nil]; + size = [fileAttributes fileSize]; + return size; +} + +- (int) eventCount { + int count = 0; + const char *sql = "SELECT count(*) FROM events"; + sqlite3_stmt *selectEventCount; + + if(sqlite3_prepare_v2(_databaseConnection, sql, -1, &selectEventCount, NULL) == SQLITE_OK) + { + if(sqlite3_step(selectEventCount) == SQLITE_ROW) { + count = sqlite3_column_int(selectEventCount, 0); + } + } + sqlite3_finalize(selectEventCount); + + return count; +} + +- (NSTimeInterval)createdTimestamp { + NSTimeInterval timestamp = 0; + NSDictionary *fileAttributes = [[NSFileManager defaultManager] + attributesOfItemAtPath:[LocalyticsDatabase localyticsDatabasePath] + error:nil]; + timestamp = [[fileAttributes fileCreationDate] timeIntervalSince1970]; + return timestamp; +} + +- (NSTimeInterval)lastSessionStartTimestamp { + + NSTimeInterval lastSessionStart = 0; + + sqlite3_stmt *selectLastSessionStart; + sqlite3_prepare_v2(_databaseConnection, "SELECT last_session_start FROM localytics_info", -1, &selectLastSessionStart, NULL); + int code = sqlite3_step(selectLastSessionStart); + if (code == SQLITE_ROW) { + lastSessionStart = sqlite3_column_double(selectLastSessionStart, 0); + } + sqlite3_finalize(selectLastSessionStart); + + return lastSessionStart; +} + +- (BOOL)setLastsessionStartTimestamp:(NSTimeInterval)timestamp { + sqlite3_stmt *updateLastSessionStart; + sqlite3_prepare_v2(_databaseConnection, "UPDATE localytics_info SET last_session_start = ?", -1, &updateLastSessionStart, NULL); + sqlite3_bind_double(updateLastSessionStart, 1, timestamp); + int code = sqlite3_step(updateLastSessionStart); + sqlite3_finalize(updateLastSessionStart); + + return code == SQLITE_DONE; +} + +- (BOOL)isOptedOut { + BOOL optedOut = NO; + + sqlite3_stmt *selectOptOut; + sqlite3_prepare_v2(_databaseConnection, "SELECT opt_out FROM localytics_info", -1, &selectOptOut, NULL); + int code = sqlite3_step(selectOptOut); + if (code == SQLITE_ROW) { + optedOut = sqlite3_column_int(selectOptOut, 0) == 1; + } + sqlite3_finalize(selectOptOut); + + return optedOut; +} + +- (BOOL)setOptedOut:(BOOL)optOut { + sqlite3_stmt *updateOptedOut; + sqlite3_prepare_v2(_databaseConnection, "UPDATE localytics_info SET opt_out = ?", -1, &updateOptedOut, NULL); + sqlite3_bind_int(updateOptedOut, 1, optOut); + int code = sqlite3_step(updateOptedOut); + sqlite3_finalize(updateOptedOut); + + return code == SQLITE_OK; +} + +- (NSString *)customDimension:(int)dimension { + if(dimension < 0 || dimension > 3) { + return nil; + } + + NSString *value = nil; + NSString *query = [NSString stringWithFormat:@"select custom_d%i from localytics_info", dimension]; + + sqlite3_stmt *selectCustomDim; + sqlite3_prepare_v2(_databaseConnection, [query UTF8String], -1, &selectCustomDim, NULL); + int code = sqlite3_step(selectCustomDim); + if (code == SQLITE_ROW && sqlite3_column_text(selectCustomDim, 0)) { + value = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectCustomDim, 0)]; + } + sqlite3_finalize(selectCustomDim); + + return value; +} + +- (BOOL)setCustomDimension:(int)dimension value:(NSString *)value { + if(dimension < 0 || dimension > 3) { + return false; + } + + NSString *query = [NSString stringWithFormat:@"update localytics_info SET custom_d%i = %@", + dimension, + (value == nil) ? @"null" : [NSString stringWithFormat:@"\"%@\"", value]]; + + int code = sqlite3_exec(_databaseConnection, [query UTF8String], NULL, NULL, NULL); + + return code == SQLITE_OK; +} + +- (BOOL)incrementLastUploadNumber:(int *)uploadNumber { + NSString *t = @"increment_upload_number"; + int code = SQLITE_OK; + + code = [self beginTransaction:t] ? SQLITE_OK : SQLITE_ERROR; + + if(code == SQLITE_OK) { + // Increment value + code = sqlite3_exec(_databaseConnection, + "UPDATE localytics_info " + "SET last_upload_number = (last_upload_number + 1)", + NULL, NULL, NULL); + } + + if(code == SQLITE_OK) { + // Retrieve new value + sqlite3_stmt *selectUploadNumber; + sqlite3_prepare_v2(_databaseConnection, + "SELECT last_upload_number FROM localytics_info", + -1, &selectUploadNumber, NULL); + code = sqlite3_step(selectUploadNumber); + if (code == SQLITE_ROW) { + *uploadNumber = sqlite3_column_int(selectUploadNumber, 0); + } + sqlite3_finalize(selectUploadNumber); + } + + if(code == SQLITE_ROW) { + [self releaseTransaction:t]; + } else { + [self rollbackTransaction:t]; + } + + return code == SQLITE_ROW; +} + +- (BOOL)incrementLastSessionNumber:(int *)sessionNumber { + NSString *t = @"increment_session_number"; + int code = [self beginTransaction:t] ? SQLITE_OK : SQLITE_ERROR; + + if(code == SQLITE_OK) { + // Increment value + code = sqlite3_exec(_databaseConnection, + "UPDATE localytics_info " + "SET last_session_number = (last_session_number + 1)", + NULL, NULL, NULL); + } + + if(code == SQLITE_OK) { + // Retrieve new value + sqlite3_stmt *selectSessionNumber; + sqlite3_prepare_v2(_databaseConnection, + "SELECT last_session_number FROM localytics_info", + -1, &selectSessionNumber, NULL); + code = sqlite3_step(selectSessionNumber); + if (code == SQLITE_ROW && sessionNumber != NULL) { + *sessionNumber = sqlite3_column_int(selectSessionNumber, 0); + } + sqlite3_finalize(selectSessionNumber); + } + + if(code == SQLITE_ROW) { + [self releaseTransaction:t]; + } else { + [self rollbackTransaction:t]; + } + + return code == SQLITE_ROW; +} + +- (BOOL)addEventWithBlobString:(NSString *)blob { + + int code = SQLITE_OK; + sqlite3_stmt *insertEvent; + sqlite3_prepare_v2(_databaseConnection, "INSERT INTO events (blob_string) VALUES (?)", -1, &insertEvent, NULL); + sqlite3_bind_text(insertEvent, 1, [blob UTF8String], -1, SQLITE_TRANSIENT); + code = sqlite3_step(insertEvent); + sqlite3_finalize(insertEvent); + + return code == SQLITE_DONE; +} + +- (BOOL)addCloseEventWithBlobString:(NSString *)blob { + NSString *t = @"add_close_event"; + BOOL success = [self beginTransaction:t]; + + // Add close event. + if (success) { + success = [self addEventWithBlobString:blob]; + } + + // Record row id to localytics_info so that it can be removed if the session resumes. + if (success) { + sqlite3_stmt *updateCloseEvent; + sqlite3_prepare_v2(_databaseConnection, "UPDATE localytics_info SET last_close_event = (SELECT event_id FROM events WHERE rowid = ?)", -1, &updateCloseEvent, NULL); + sqlite3_int64 lastRow = sqlite3_last_insert_rowid(_databaseConnection); + sqlite3_bind_int64(updateCloseEvent, 1, lastRow); + int code = sqlite3_step(updateCloseEvent); + sqlite3_finalize(updateCloseEvent); + success = code == SQLITE_DONE; + } + + if (success) { + [self releaseTransaction:t]; + } else { + [self rollbackTransaction:t]; + } + return success; +} + +- (BOOL)queueCloseEventWithBlobString:(NSString *)blob { + NSString *t = @"queue_close_event"; + BOOL success = [self beginTransaction:t]; + + // Queue close event. + if (success) { + sqlite3_stmt *queueCloseEvent; + sqlite3_prepare_v2(_databaseConnection, "UPDATE localytics_info SET queued_close_event_blob = ?", -1, &queueCloseEvent, NULL); + sqlite3_bind_text(queueCloseEvent, 1, [blob UTF8String], -1, SQLITE_TRANSIENT); + int code = sqlite3_step(queueCloseEvent); + sqlite3_finalize(queueCloseEvent); + success = code == SQLITE_DONE; + } + + if (success) { + [self releaseTransaction:t]; + } else { + [self rollbackTransaction:t]; + } + return success; +} + +- (NSString *)dequeueCloseEventBlobString { + NSString *value = nil; + NSString *query = @"SELECT queued_close_event_blob FROM localytics_info"; + + sqlite3_stmt *selectStmt; + sqlite3_prepare_v2(_databaseConnection, [query UTF8String], -1, &selectStmt, NULL); + int code = sqlite3_step(selectStmt); + if (code == SQLITE_ROW && sqlite3_column_text(selectStmt, 0)) { + value = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectStmt, 0)]; + } + sqlite3_finalize(selectStmt); + + // Clear the queued close event blob. + [self queueCloseEventWithBlobString:nil]; + + return value; +} + +- (BOOL)addFlowEventWithBlobString:(NSString *)blob { + NSString *t = @"add_flow_event"; + BOOL success = [self beginTransaction:t]; + + // Add flow event. + if (success) { + success = [self addEventWithBlobString:blob]; + } + + // Record row id to localytics_info so that it can be removed if the session resumes. + if (success) { + sqlite3_stmt *updateFlowEvent; + sqlite3_prepare_v2(_databaseConnection, "UPDATE localytics_info SET last_flow_event = (SELECT event_id FROM events WHERE rowid = ?)", -1, &updateFlowEvent, NULL); + sqlite3_int64 lastRow = sqlite3_last_insert_rowid(_databaseConnection); + sqlite3_bind_int64(updateFlowEvent, 1, lastRow); + int code = sqlite3_step(updateFlowEvent); + sqlite3_finalize(updateFlowEvent); + success = code == SQLITE_DONE; + } + + if (success) { + [self releaseTransaction:t]; + } else { + [self rollbackTransaction:t]; + } + return success; +} + +- (BOOL)removeLastCloseAndFlowEvents { + // Attempt to remove the last recorded close event. + // Fail quietly if none was saved or it was previously removed. + int code = sqlite3_exec(_databaseConnection, "DELETE FROM events WHERE event_id = (SELECT last_close_event FROM localytics_info) OR event_id = (SELECT last_flow_event FROM localytics_info)", NULL, NULL, NULL); + + return code == SQLITE_OK; +} + +- (BOOL)addHeaderWithSequenceNumber:(int)number blobString:(NSString *)blob rowId:(sqlite3_int64 *)insertedRowId { + sqlite3_stmt *insertHeader; + sqlite3_prepare_v2(_databaseConnection, "INSERT INTO upload_headers (sequence_number, blob_string) VALUES (?, ?)", -1, &insertHeader, NULL); + sqlite3_bind_int(insertHeader, 1, number); + sqlite3_bind_text(insertHeader, 2, [blob UTF8String], -1, SQLITE_TRANSIENT); + int code = sqlite3_step(insertHeader); + sqlite3_finalize(insertHeader); + + if (code == SQLITE_DONE && insertedRowId != NULL) { + *insertedRowId = sqlite3_last_insert_rowid(_databaseConnection); + } + + return code == SQLITE_DONE; +} + +- (int)unstagedEventCount { + int rowCount = 0; + sqlite3_stmt *selectEventCount; + sqlite3_prepare_v2(_databaseConnection, "SELECT COUNT(*) FROM events WHERE UPLOAD_HEADER IS NULL", -1, &selectEventCount, NULL); + int code = sqlite3_step(selectEventCount); + if (code == SQLITE_ROW) { + rowCount = sqlite3_column_int(selectEventCount, 0); + } + sqlite3_finalize(selectEventCount); + + return rowCount; +} + +- (BOOL)stageEventsForUpload:(sqlite3_int64)headerId { + + // Associate all outstanding events with the given upload header ID. + NSString *stageEvents = [NSString stringWithFormat:@"UPDATE events SET upload_header = ? WHERE upload_header IS NULL"]; + sqlite3_stmt *updateEvents; + sqlite3_prepare_v2(_databaseConnection, [stageEvents UTF8String], -1, &updateEvents, NULL); + sqlite3_bind_int(updateEvents, 1, headerId); + int code = sqlite3_step(updateEvents); + sqlite3_finalize(updateEvents); + BOOL success = (code == SQLITE_DONE); + + return success; +} + +- (BOOL)updateAppKey:(NSString *)appKey { + sqlite3_stmt *updateAppKey; + sqlite3_prepare_v2(_databaseConnection, "UPDATE localytics_info set app_key = ?", -1, &updateAppKey, NULL); + sqlite3_bind_text (updateAppKey, 1, [appKey UTF8String], -1, SQLITE_TRANSIENT); + int code = sqlite3_step(updateAppKey); + sqlite3_finalize(updateAppKey); + BOOL success = (code == SQLITE_DONE); + + return success; +} + +- (NSString *)uploadBlobString { + + // Retrieve the blob strings of each upload header and its child events, in order. + const char *sql = "SELECT * FROM ( " + " SELECT h.blob_string AS 'blob', h.sequence_number as 'seq', 0 FROM upload_headers h" + " UNION ALL " + " SELECT e.blob_string AS 'blob', e.upload_header as 'seq', 1 FROM events e" + ") " + "ORDER BY 2, 3"; + sqlite3_stmt *selectBlobs; + sqlite3_prepare_v2(_databaseConnection, sql, -1, &selectBlobs, NULL); + NSMutableString *uploadBlobString = [NSMutableString string]; + while (sqlite3_step(selectBlobs) == SQLITE_ROW) { + const char *blob = (const char *)sqlite3_column_text(selectBlobs, 0); + if (blob != NULL) { + NSString *blobString = [[NSString alloc] initWithCString:blob encoding:NSUTF8StringEncoding]; + [uploadBlobString appendString:blobString]; + [blobString release]; + } + } + sqlite3_finalize(selectBlobs); + + return [[uploadBlobString copy] autorelease]; +} + +- (BOOL)deleteUploadedData { + // Delete all headers and staged events. + NSString *t = @"delete_upload_data"; + int code = [self beginTransaction:t] ? SQLITE_OK : SQLITE_ERROR; + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection, "DELETE FROM events WHERE upload_header IS NOT NULL", NULL, NULL, NULL); + } + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection, "DELETE FROM upload_headers", NULL, NULL, NULL); + } + + if (code == SQLITE_OK) { + [self releaseTransaction:t]; + } else { + [self rollbackTransaction:t]; + } + + return code == SQLITE_OK; +} + +- (BOOL)resetAnalyticsData { + // Delete or zero all analytics data. + // Reset: headers, events, session number, upload number, last session start, last close event, and last flow event. + // Unaffected: schema version, opt out status, install ID (deprecated), and app key. + + NSString *t = @"reset_analytics_data"; + int code = [self beginTransaction:t] ? SQLITE_OK : SQLITE_ERROR; + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection, "DELETE FROM events", NULL, NULL, NULL); + } + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection, "DELETE FROM upload_headers", NULL, NULL, NULL); + } + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection, "DELETE FROM localytics_amp_rule", NULL, NULL, NULL); + } + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection, "DELETE FROM localytics_amp_ruleevent", NULL, NULL, NULL); + } + + if (code == SQLITE_OK) { + code = sqlite3_exec(_databaseConnection,"UPDATE localytics_info SET last_session_number = 0, last_upload_number = 0," + "last_close_event = null, last_flow_event = null, last_session_start = null, " + "custom_d0 = null, custom_d1 = null, custom_d2 = null, custom_d3 = null, " + "customer_id = null, queued_close_event_blob = null ", + NULL, NULL, NULL); + } + + + if (code == SQLITE_OK) { + [self releaseTransaction:t]; + } else { + [self rollbackTransaction:t]; + } + + return code == SQLITE_OK; +} + +- (BOOL)vacuumIfRequired { + int code = SQLITE_OK; + if ([self databaseSize] > MAX_DATABASE_SIZE * VACUUM_THRESHOLD) { + code = sqlite3_exec(_databaseConnection, "VACUUM", NULL, NULL, NULL); + } + + return code == SQLITE_OK; +} + +- (NSString *)randomUUID { + CFUUIDRef theUUID = CFUUIDCreate(NULL); + CFStringRef stringUUID = CFUUIDCreateString(NULL, theUUID); + CFRelease(theUUID); + return [(NSString *)stringUUID autorelease]; +} + +- (NSString *)customerId { + NSString *customerId = nil; + + sqlite3_stmt *selectCustomerId; + sqlite3_prepare_v2(_databaseConnection, "SELECT customer_id FROM localytics_info", -1, &selectCustomerId, NULL); + int code = sqlite3_step(selectCustomerId); + if (code == SQLITE_ROW && sqlite3_column_text(selectCustomerId, 0)) { + customerId = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectCustomerId, 0)]; + } + sqlite3_finalize(selectCustomerId); + + return customerId; +} + +- (BOOL)setCustomerId:(NSString *)newCustomerId +{ + sqlite3_stmt *updateCustomerId; + sqlite3_prepare_v2(_databaseConnection, "UPDATE localytics_info set customer_id = ?", -1, &updateCustomerId, NULL); + sqlite3_bind_text (updateCustomerId, 1, [newCustomerId UTF8String], -1, SQLITE_TRANSIENT); + int code = sqlite3_step(updateCustomerId); + sqlite3_finalize(updateCustomerId); + BOOL success = (code == SQLITE_DONE); + + return success; +} + +#pragma mark - Safe NSDictionary value methods + +- (NSInteger)safeIntegerValueFromDictionary:(NSDictionary *)dict forKey:(NSString *)key +{ + NSInteger integerValue = 0; + id value = [dict objectForKey:key]; + if ([value isKindOfClass:[NSNumber class]] || [value isKindOfClass:[NSString class]]) { + integerValue = [value integerValue]; + } else if ([value isKindOfClass:[NSNull class]]) { + integerValue = 0; + } + + return integerValue; +} + +- (NSString *)safeStringValueFromDictionary:(NSDictionary *)dict forKey:(NSString *)key +{ + NSString *stringValue = nil; + id value = [dict objectForKey:key]; + if ([value isKindOfClass:[NSString class]]) { + stringValue = value; + } else if ([value isKindOfClass:[NSNumber class]]) { + stringValue = [value stringValue]; + } else if ([value isKindOfClass:[NSNull class]]) { + stringValue = nil; + } + + return stringValue; +} + +- (NSDictionary *)safeDictionaryFromDictionary:(NSDictionary *)dict forKey:(NSString *)key +{ + NSDictionary *dictValue = nil; + id value = [dict objectForKey:key]; + if ([value isKindOfClass:[NSDictionary class]]) { + dictValue = value; + } + return dictValue; +} + +- (NSArray *)safeListFromDictionary:(NSDictionary *)dict forKey:(NSString *)key +{ + NSArray *arrayValue = nil; + id value = [dict objectForKey:key]; + if ([value isKindOfClass:[NSArray class]]) { + arrayValue = value; + } + return arrayValue; +} + +#pragma mark - Lifecycle + ++ (id)allocWithZone:(NSZone *)zone { + @synchronized(self) { + if (_sharedLocalyticsDatabase == nil) { + _sharedLocalyticsDatabase = [super allocWithZone:zone]; + return _sharedLocalyticsDatabase; + } + } + // returns nil on subsequent allocations + return nil; +} + +- (id)copyWithZone:(NSZone *)zone { + return self; +} + +- (id)retain { + return self; +} + +- (unsigned)retainCount { + // maximum value of an unsigned int - prevents additional retains for the class + return UINT_MAX; +} + +- (oneway void)release { + // ignore release commands +} + +- (id)autorelease { + return self; +} + +- (void)dealloc { + sqlite3_close(_databaseConnection); + [super dealloc]; +} + +@end diff --git a/Localytics/LocalyticsSession.h b/Localytics/LocalyticsSession.h index e204469d..6b18ca91 100644 --- a/Localytics/LocalyticsSession.h +++ b/Localytics/LocalyticsSession.h @@ -1,216 +1,251 @@ -// LocalyticsSession.h -// Copyright (C) 2009 Char Software Inc., DBA Localytics -// -// This code is provided under the Localytics Modified BSD License. -// A copy of this license has been distributed in a file called LICENSE -// with this source code. -// -// Please visit www.localytics.com for more information. - -#import - -// Set this to true to enable localytics traces (useful for debugging) -#define DO_LOCALYTICS_LOGGING false - -/*! - @class LocalyticsSession - @discussion The class which manages creating, collecting, & uploading a Localytics session. - Please see the following guides for information on how to best use this - library, sample code, and other useful information: - - - Best Practices -
    -
  • Instantiate the LocalyticsSession object in applicationDidFinishLaunching.
  • -
  • Open your session and begin your uploads in applicationDidFinishLaunching. This way the - upload has time to complete and it all happens before your users have a - chance to begin any data intensive actions of their own.
  • -
  • Close the session in applicationWillTerminate, and in applicationDidEnterBackground.
  • -
  • Resume the session in applicationWillEnterForeground.
  • -
  • Do not call any Localytics functions inside a loop. Instead, calls - such as tagEvent should follow user actions. This limits the - amount of data which is stored and uploaded.
  • -
  • Do not use multiple LocalticsSession objects to upload data with - multiple application keys. This can cause invalid state.
  • -
- - @author Localytics - */ -@interface LocalyticsSession : NSObject { - - BOOL _hasInitialized; // Whether or not the session object has been initialized. - BOOL _isSessionOpen; // Whether or not this session has been opened. - float _backgroundSessionTimeout; // If an App stays in the background for more - // than this many seconds, start a new session - // when it returns to foreground. - @private - #pragma mark Member Variables - dispatch_queue_t _queue; // Queue of Localytics block objects. - dispatch_group_t _criticalGroup; // Group of blocks the must complete before backgrounding. - NSString *_sessionUUID; // Unique identifier for this session. - NSString *_applicationKey; // Unique identifier for the instrumented application - NSTimeInterval _lastSessionStartTimestamp; // The start time of the most recent session. - NSDate *_sessionResumeTime; // Time session was started or resumed. - NSDate *_sessionCloseTime; // Time session was closed. - NSMutableString *_unstagedFlowEvents; // Comma-delimited list of app screens and events tagged during this - // session that have NOT been staged for upload. - NSMutableString *_stagedFlowEvents; // App screens and events tagged during this session that HAVE been staged - // for upload. - NSMutableString *_screens; // Comma-delimited list of screens tagged during this session. - NSTimeInterval _sessionActiveDuration; // Duration that session open. - BOOL _sessionHasBeenOpen; // Whether or not this session has ever been open. -} - -@property dispatch_queue_t queue; -@property dispatch_group_t criticalGroup; -@property BOOL isSessionOpen; -@property BOOL hasInitialized; -@property float backgroundSessionTimeout; - -#pragma mark Public Methods -/*! - @method sharedLocalyticsSession - @abstract Accesses the Session object. This is a Singleton class which maintains - a single session throughout your application. It is possible to manage your own - session, but this is the easiest way to access the Localytics object throughout your code. - The class is accessed within the code using the following syntax: - [[LocalyticsSession sharedLocalyticsSession] functionHere] - So, to tag an event, all that is necessary, anywhere in the code is: - [[LocalyticsSession sharedLocalyticsSession] tagEvent:@"MY_EVENT"]; - */ -+ (LocalyticsSession *)sharedLocalyticsSession; - -/*! - @method LocalyticsSession - @abstract Initializes the Localytics Object. Not necessary if you choose to use startSession. - @param applicationKey The key unique for each application generated at www.localytics.com - */ -- (void)LocalyticsSession:(NSString *)appKey; - -/*! - @method startSession - @abstract An optional convenience initialize method that also calls the LocalyticsSession, open & - upload methods. Best Practice is to call open & upload immediately after Localytics Session when loading an app, - this method fascilitates that behavior. - It is recommended that this call be placed in applicationDidFinishLaunching. - @param applicationKey The key unique for each application generated - at www.localytics.com - */ -- (void)startSession:(NSString *)appKey; - -/*! - @method setOptIn - @abstract (OPTIONAL) Allows the application to control whether or not it will collect user data. - Even if this call is used, it is necessary to continue calling upload(). No new data will be - collected, so nothing new will be uploaded but it is necessary to upload an event telling the - server this user has opted out. - @param optedIn True if the user is opted in, false otherwise. - */ -- (void)setOptIn:(BOOL)optedIn; - -/*! - @method isOptedIn - @abstract (OPTIONAL) Whether or not this user has is opted in or out. The only way they can be - opted out is if setOptIn(false) has been called before this. This function should only be - used to pre-populate a checkbox in an options menu. It is not recommended that an application - branch based on Localytics instrumentation because this creates an additional test case. If - the app is opted out, all subsequent Localytics calls will return immediately. - @result true if the user is opted in, false otherwise. - */ -- (BOOL)isOptedIn; - -/*! - @method open - @abstract Opens the Localytics session. Not necessary if you choose to use startSession. - The session time as presented on the website is the time between open and the - final close so it is recommended to open the session as early as possible, and close - it at the last moment. The session must be opened before any tags can - be written. It is recommended that this call be placed in applicationDidFinishLaunching. -
- If for any reason this is called more than once every subsequent open call - will be ignored. - */ -- (void)open; - -/*! - @method resume - @abstract Resumes the Localytics session. When the App enters the background, the session is - closed and the time of closing is recorded. When the app returns to the foreground, the session - is resumed. If the time since closing is greater than BACKGROUND_SESSION_TIMEOUT, (15 seconds - by default) a new session is created, and uploading is triggered. Otherwise, the previous session - is reopened. -*/ -- (void)resume; - -/*! - @method close - @abstract Closes the Localytics session. This should be called in - applicationWillTerminate. -
- If close is not called, the session will still be uploaded but no - events will be processed and the session time will not appear. This is - because the session is not yet closed so it should not be used in - comparison with sessions which are closed. - */ -- (void)close; - -/*! - @method tagEvent - @abstract Allows a session to tag a particular event as having occurred. For - example, if a view has three buttons, it might make sense to tag - each button click with the name of the button which was clicked. - For another example, in a game with many levels it might be valuable - to create a new tag every time the user gets to a new level in order - to determine how far the average user is progressing in the game. -
- Tagging Best Practices -
    -
  • DO NOT use tags to record personally identifiable information.
  • -
  • The best way to use tags is to create all the tag strings as predefined - constants and only use those. This is more efficient and removes the risk of - collecting personal information.
  • -
  • Do not set tags inside loops or any other place which gets called - frequently. This can cause a lot of data to be stored and uploaded.
  • -
-
- See the tagging guide at: http://wiki.localytics.com/ - @param event The name of the event which occurred. - */ -- (void)tagEvent:(NSString *)event; - -- (void)tagEvent:(NSString *)event attributes:(NSDictionary *)attributes; - -- (void)tagEvent:(NSString *)event attributes:(NSDictionary *)attributes reportAttributes:(NSDictionary *)reportAttributes; - -/*! - @method tagScreen - @abstract Allows tagging the flow of screens encountered during the session. - @param screen The name of the screen - */ -- (void)tagScreen:(NSString *)screen; - -/*! - @method upload - @abstract Creates a low priority thread which uploads any Localytics data already stored - on the device. This should be done early in the process life in order to - guarantee as much time as possible for slow connections to complete. It is also reasonable - to upload again when the application is exiting because if the upload is cancelled the data - will just get uploaded the next time the app comes up. - */ -- (void)upload; - -/*! - @method setCustomDimension - @abstract (ENTERPRISE ONLY) Sets the value of a custom dimension. Custom dimensions are dimensions - which contain user defined data unlike the predefined dimensions such as carrier, model, and country. - Once a value for a custom dimension is set, the device it was set on will continue to upload that value - until the value is changed. To clear a value pass nil as the value. - The proper use of custom dimensions involves defining a dimension with less than ten distinct possible - values and assigning it to one of the four available custom dimensions. Once assigned this definition should - never be changed without changing the App Key otherwise old installs of the application will pollute new data. - */ -- (void)setCustomDimension:(int)dimension value:(NSString *)value; - -@end +// LocalyticsSession.h +// Copyright (C) 2012 Char Software Inc., DBA Localytics +// +// This code is provided under the Localytics Modified BSD License. +// A copy of this license has been distributed in a file called LICENSE +// with this source code. +// +// Please visit www.localytics.com for more information. + +#import +#import + +// Set this to true to enable localytics traces (useful for debugging) +#define DO_LOCALYTICS_LOGGING false + +/*! + @class LocalyticsSession + @discussion The class which manages creating, collecting, & uploading a Localytics session. + Please see the following guides for information on how to best use this + library, sample code, and other useful information: + + + Best Practices +
    +
  • Instantiate the LocalyticsSession object in applicationDidFinishLaunching.
  • +
  • Open your session and begin your uploads in applicationDidFinishLaunching. This way the + upload has time to complete and it all happens before your users have a + chance to begin any data intensive actions of their own.
  • +
  • Close the session in applicationWillTerminate, and in applicationDidEnterBackground.
  • +
  • Resume the session in applicationWillEnterForeground.
  • +
  • Do not call any Localytics functions inside a loop. Instead, calls + such as tagEvent should follow user actions. This limits the + amount of data which is stored and uploaded.
  • +
  • Do not use multiple LocalticsSession objects to upload data with + multiple application keys. This can cause invalid state.
  • +
+ + @author Localytics + */ + +@interface LocalyticsSession : NSObject { + + BOOL _hasInitialized; // Whether or not the session object has been initialized. + BOOL _isSessionOpen; // Whether or not this session has been opened. + float _backgroundSessionTimeout; // If an App stays in the background for more + // than this many seconds, start a new session + // when it returns to foreground. + @private + #pragma mark Member Variables + dispatch_queue_t _queue; // Queue of Localytics block objects. + dispatch_group_t _criticalGroup; // Group of blocks the must complete before backgrounding. + NSString *_sessionUUID; // Unique identifier for this session. + NSString *_applicationKey; // Unique identifier for the instrumented application + NSTimeInterval _lastSessionStartTimestamp; // The start time of the most recent session. + NSDate *_sessionResumeTime; // Time session was started or resumed. + NSDate *_sessionCloseTime; // Time session was closed. + NSMutableString *_unstagedFlowEvents; // Comma-delimited list of app screens and events tagged during this + // session that have NOT been staged for upload. + NSMutableString *_stagedFlowEvents; // App screens and events tagged during this session that HAVE been staged + // for upload. + NSMutableString *_screens; // Comma-delimited list of screens tagged during this session. + NSTimeInterval _sessionActiveDuration; // Duration that session open. + BOOL _sessionHasBeenOpen; // Whether or not this session has ever been open. +} + +@property (nonatomic,readonly) dispatch_queue_t queue; +@property (nonatomic,readonly) dispatch_group_t criticalGroup; +@property BOOL isSessionOpen; +@property BOOL hasInitialized; +@property float backgroundSessionTimeout; + +- (void)logMessage:(NSString *)message; +@property (nonatomic, assign, readonly) NSTimeInterval lastSessionStartTimestamp; +@property (nonatomic, assign, readonly) NSInteger sessionNumber; + + +/*! + @property enableHTTPS + @abstract Determines whether or not HTTPS is used when calling the Localytics + post URL. The default is NO. + */ +@property (nonatomic, assign) BOOL enableHTTPS; // Defaults to NO. + +#pragma mark Public Methods +/*! + @method sharedLocalyticsSession + @abstract Accesses the Session object. This is a Singleton class which maintains + a single session throughout your application. It is possible to manage your own + session, but this is the easiest way to access the Localytics object throughout your code. + The class is accessed within the code using the following syntax: + [[LocalyticsSession sharedLocalyticsSession] functionHere] + So, to tag an event, all that is necessary, anywhere in the code is: + [[LocalyticsSession sharedLocalyticsSession] tagEvent:@"MY_EVENT"]; + */ ++ (LocalyticsSession *)sharedLocalyticsSession; + +/*! + @method LocalyticsSession + @abstract Initializes the Localytics Object. Not necessary if you choose to use startSession. + @param applicationKey The key unique for each application generated at www.localytics.com + */ +- (void)LocalyticsSession:(NSString *)appKey; + +/*! + @method startSession + @abstract An optional convenience initialize method that also calls the LocalyticsSession, open & + upload methods. Best Practice is to call open & upload immediately after Localytics Session when loading an app, + this method fascilitates that behavior. + It is recommended that this call be placed in applicationDidFinishLaunching. + @param applicationKey The key unique for each application generated + at www.localytics.com + */ +- (void)startSession:(NSString *)appKey; + +/*! + @method setOptIn + @abstract (OPTIONAL) Allows the application to control whether or not it will collect user data. + Even if this call is used, it is necessary to continue calling upload(). No new data will be + collected, so nothing new will be uploaded but it is necessary to upload an event telling the + server this user has opted out. + @param optedIn True if the user is opted in, false otherwise. + */ +- (void)setOptIn:(BOOL)optedIn; + +/*! + @method isOptedIn + @abstract (OPTIONAL) Whether or not this user has is opted in or out. The only way they can be + opted out is if setOptIn(false) has been called before this. This function should only be + used to pre-populate a checkbox in an options menu. It is not recommended that an application + branch based on Localytics instrumentation because this creates an additional test case. If + the app is opted out, all subsequent Localytics calls will return immediately. + @result true if the user is opted in, false otherwise. + */ +- (BOOL)isOptedIn; + +/*! + @method open + @abstract Opens the Localytics session. Not necessary if you choose to use startSession. + The session time as presented on the website is the time between open and the + final close so it is recommended to open the session as early as possible, and close + it at the last moment. The session must be opened before any tags can + be written. It is recommended that this call be placed in applicationDidFinishLaunching. +
+ If for any reason this is called more than once every subsequent open call + will be ignored. + */ +- (void)open; + +/*! + @method resume + @abstract Resumes the Localytics session. When the App enters the background, the session is + closed and the time of closing is recorded. When the app returns to the foreground, the session + is resumed. If the time since closing is greater than BACKGROUND_SESSION_TIMEOUT, (15 seconds + by default) a new session is created, and uploading is triggered. Otherwise, the previous session + is reopened. It is possible to use the return value to determine whether or not a session was resumed. + This may be useful to some customers looking to do conditional instrumentation at the close of a session. + It is perfectly reasonable to ignore the return value. + @result YES if the sesion was resumed NO if it wasn't (suggesting a new session was created instead).*/ +- (BOOL)resume; + +/*! + @method close + @abstract Closes the Localytics session. This should be called in + applicationWillTerminate. +
+ If close is not called, the session will still be uploaded but no + events will be processed and the session time will not appear. This is + because the session is not yet closed so it should not be used in + comparison with sessions which are closed. + */ +- (void)close; + +/*! + @method tagEvent + @abstract Allows a session to tag a particular event as having occurred. For + example, if a view has three buttons, it might make sense to tag + each button click with the name of the button which was clicked. + For another example, in a game with many levels it might be valuable + to create a new tag every time the user gets to a new level in order + to determine how far the average user is progressing in the game. +
+ Tagging Best Practices +
    +
  • DO NOT use tags to record personally identifiable information.
  • +
  • The best way to use tags is to create all the tag strings as predefined + constants and only use those. This is more efficient and removes the risk of + collecting personal information.
  • +
  • Do not set tags inside loops or any other place which gets called + frequently. This can cause a lot of data to be stored and uploaded.
  • +
+
+ See the tagging guide at: http://wiki.localytics.com/ + @param event The name of the event which occurred. + */ +- (void)tagEvent:(NSString *)event; + +- (void)tagEvent:(NSString *)event attributes:(NSDictionary *)attributes; + +- (void)tagEvent:(NSString *)event attributes:(NSDictionary *)attributes reportAttributes:(NSDictionary *)reportAttributes; + +/*! + @method tagScreen + @abstract Allows tagging the flow of screens encountered during the session. + @param screen The name of the screen + */ +- (void)tagScreen:(NSString *)screen; + +/*! + @method upload + @abstract Creates a low priority thread which uploads any Localytics data already stored + on the device. This should be done early in the process life in order to + guarantee as much time as possible for slow connections to complete. It is also reasonable + to upload again when the application is exiting because if the upload is cancelled the data + will just get uploaded the next time the app comes up. + */ +- (void)upload; + +/*! + @method setCustomDimension + @abstract (ENTERPRISE ONLY) Sets the value of a custom dimension. Custom dimensions are dimensions + which contain user defined data unlike the predefined dimensions such as carrier, model, and country. + Once a value for a custom dimension is set, the device it was set on will continue to upload that value + until the value is changed. To clear a value pass nil as the value. + The proper use of custom dimensions involves defining a dimension with less than ten distinct possible + values and assigning it to one of the four available custom dimensions. Once assigned this definition should + never be changed without changing the App Key otherwise old installs of the application will pollute new data. + */ +- (void)setCustomDimension:(int)dimension value:(NSString *)value; + +/*! + @method setLocation + @abstract Stores the user's location. This will be used in all event and session calls. + If your application has already collected the user's location, it may be passed to Localytics + via this function. This will cause all events and the session close to include the locatin + information. It is not required that you call this function. + @param deviceLocation The user's location. + */ +- (void)setLocation:(CLLocationCoordinate2D)deviceLocation; + +/*! + @method ampTrigger + @abstract Displays the AMP message for the specific event. + Is a stub implementation here to prevent crashes if this class is accidentally used inplace of + the LocalyticsAmpSession + @param event Name of the event. + */ +- (void)ampTrigger:(NSString *)event; + +@end diff --git a/Localytics/LocalyticsSession.m b/Localytics/LocalyticsSession.m index 8f75c36d..c0599b38 100644 --- a/Localytics/LocalyticsSession.m +++ b/Localytics/LocalyticsSession.m @@ -1,1148 +1,1278 @@ -// LocalyticsSession.m -// Copyright (C) 2009 Char Software Inc., DBA Localytics -// -// This code is provided under the Localytics Modified BSD License. -// A copy of this license has been distributed in a file called LICENSE -// with this source code. -// -// Please visit www.localytics.com for more information. - -#import "LocalyticsSession.h" -#import "WebserviceConstants.h" -#import "LocalyticsUploader.h" -#import "LocalyticsDatabase.h" - -#include -#include -#include -#include -#include -#include -#include - -#pragma mark Constants -#define PREFERENCES_KEY @"_localytics_install_id" // The randomly generated ID for each install of the app -#define CLIENT_VERSION @"iOS_2.6" // The version of this library -#define LOCALYTICS_DIR @".localytics" // The directory in which the Localytics database is stored -#define IFT_ETHER 0x6 // Ethernet CSMACD -#define PATH_TO_APT @"/private/var/lib/apt/" - -#define DEFAULT_BACKGROUND_SESSION_TIMEOUT 15 // Default value for how many seconds a session persists when App shifts to the background. - -// The singleton session object. -static LocalyticsSession *_sharedLocalyticsSession = nil; - -@interface LocalyticsSession() - -@property (nonatomic, retain) NSString *sessionUUID; -@property (nonatomic, retain) NSString *applicationKey; -@property (nonatomic, assign) NSTimeInterval lastSessionStartTimestamp; -@property (nonatomic, retain) NSDate *sessionResumeTime; -@property (nonatomic, retain) NSDate *sessionCloseTime; -@property (nonatomic, retain) NSMutableString *unstagedFlowEvents; -@property (nonatomic, retain) NSMutableString *stagedFlowEvents; -@property (nonatomic, retain) NSMutableString *screens; -@property (nonatomic, assign) NSTimeInterval sessionActiveDuration; -@property (nonatomic, assign) BOOL sessionHasBeenOpen; - -// Private methods. -- (void)ll_open; -- (void)reopenPreviousSession; -- (void)addFlowEventWithName:(NSString *)name type:(NSString *)eventType; -- (void)addScreenWithName:(NSString *)name; -- (NSString *)blobHeaderStringWithSequenceNumber:(int)nextSequenceNumber; -- (BOOL)ll_isOptedIn; -- (BOOL)createOptEvent:(BOOL)optState; -- (BOOL)saveApplicationFlowAndRemoveOnResume:(BOOL)removeOnResume; -- (NSString *)formatAttributeWithName:(NSString *)paramName value:(NSString *)paramValue; -- (NSString *)formatAttributeWithName:(NSString *)paramName value:(NSString *)paramValue first:(BOOL)firstAttribute; -- (void)logMessage:(NSString *)message; - -// Datapoint methods. -- (NSString *)customDimensions; -- (NSString *)macAddress; -- (NSString *)hashString:(NSString *)input; -- (NSString *)randomUUID; -- (NSString *)escapeString:(NSString *)input; -- (NSString *)installationId; -- (NSString *)uniqueDeviceIdentifier; -- (NSString *)appVersion; -- (NSTimeInterval)currentTimestamp; -- (BOOL)isDeviceJailbroken; -- (NSString *)deviceModel; -- (NSString *)modelSizeString; -- (double)availableMemory; - -@end - -@implementation LocalyticsSession - -@synthesize queue = _queue; -@synthesize criticalGroup = _criticalGroup; -@synthesize sessionUUID = _sessionUUID; -@synthesize applicationKey = _applicationKey; -@synthesize lastSessionStartTimestamp = _lastSessionStartTimestamp; -@synthesize sessionResumeTime = _sessionResumeTime; -@synthesize sessionCloseTime = _sessionCloseTime; -@synthesize isSessionOpen = _isSessionOpen; -@synthesize hasInitialized = _hasInitialized; -@synthesize backgroundSessionTimeout = _backgroundSessionTimeout; -@synthesize unstagedFlowEvents = _unstagedFlowEvents; -@synthesize stagedFlowEvents = _stagedFlowEvents; -@synthesize screens = _screens; -@synthesize sessionActiveDuration = _sessionActiveDuration; -@synthesize sessionHasBeenOpen = _sessionHasBeenOpen; - -#pragma mark Singleton - -+ (LocalyticsSession *)sharedLocalyticsSession { - @synchronized(self) { - if (_sharedLocalyticsSession == nil) { - _sharedLocalyticsSession = [[self alloc] init]; - } - } - return _sharedLocalyticsSession; -} - -- (LocalyticsSession *)init { - if((self = [super init])) { - _isSessionOpen = NO; - _hasInitialized = NO; - _backgroundSessionTimeout = DEFAULT_BACKGROUND_SESSION_TIMEOUT; - _sessionHasBeenOpen = NO; - _queue = dispatch_queue_create("com.Localytics.operations", DISPATCH_QUEUE_SERIAL); - _criticalGroup = dispatch_group_create(); - - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil]; - - [LocalyticsDatabase sharedLocalyticsDatabase]; - } - - return self; -} - -#pragma mark Public Methods - -- (void)LocalyticsSession:(NSString *)appKey { - // If the session has already initialized, don't bother doing it again. - if(self.hasInitialized) - { - [self logMessage:@"Object has already been initialized."]; - return; - } - - @try { - - if(appKey == (id)[NSNull null] || appKey.length == 0) { - [self logMessage:@"App key is null or empty."]; - self.hasInitialized = NO; - return; - } - - // App key should only be alphanumeric chars and dashes. - NSString *trimmedAppKey = [appKey stringByReplacingOccurrencesOfString:@"-" withString:@""]; - if([[trimmedAppKey stringByTrimmingCharactersInSet:[NSCharacterSet alphanumericCharacterSet]] isEqualToString:@""] == false) { - [self logMessage:@"App key may only contain dashes and alphanumeric characters."]; - self.hasInitialized = NO; - return; - } - - if ([LocalyticsDatabase sharedLocalyticsDatabase]) { - // Check if the app key has changed. - NSString *lastAppKey = [[LocalyticsDatabase sharedLocalyticsDatabase] appKey]; - if (![lastAppKey isEqualToString:appKey]) { - if (lastAppKey) { - // Clear previous events and dimensions to guarantee that new data isn't associated with the old app key. - [[LocalyticsDatabase sharedLocalyticsDatabase] resetAnalyticsData]; - - // Vacuum to improve the odds of opening a new session following bulk delete. - [[LocalyticsDatabase sharedLocalyticsDatabase] vacuumIfRequired]; - } - // Record the key for future checks. - [[LocalyticsDatabase sharedLocalyticsDatabase] updateAppKey:appKey]; - } - - self.applicationKey = appKey; - self.hasInitialized = YES; - [self logMessage:[@"Object Initialized. Application's key is: " stringByAppendingString:self.applicationKey]]; - } - } - @catch (NSException * e) {} -} - -- (void)startSession:(NSString *)appKey { - [self LocalyticsSession:appKey]; - [self open]; - [self upload]; -} - -// Public interface to ll_open. -- (void)open { - dispatch_async(_queue, ^{ - [self ll_open]; - }); -} - -- (void)resume { - dispatch_async(_queue, ^{ - // Do nothing if session is already open - if(self.isSessionOpen == YES) - return; - - if([self ll_isOptedIn] == false) { - [self logMessage:@"Can't resume session because user is opted out."]; - return; - } - - // conditions for resuming previous session - if(self.sessionHasBeenOpen && - (!self.sessionCloseTime || - [self.sessionCloseTime timeIntervalSinceNow]*-1 <= self.backgroundSessionTimeout)) { - // Note that we allow the session to be resumed even if the database size exceeds the - // maximum. This is because we don't want to create incomplete sessions. If the DB was large - // enough that the previous session could not be opened, there will be nothing to resume. But - // if this session caused it to go over it is better to let it complete and stop the next one - // from being created. - [self logMessage:@"Resume called - Resuming previous session."]; - [self reopenPreviousSession]; - } else { - // otherwise open new session and upload - [self logMessage:@"Resume called - Opening a new session."]; - [self ll_open]; - } - self.sessionCloseTime = nil; - }); -} - -- (void)close { - dispatch_group_async(_criticalGroup, _queue, ^{ - // Do nothing if the session is not open - if (self.isSessionOpen == NO) { - [self logMessage:@"Unable to close session"]; - return; - } - - // Save time of close - self.sessionCloseTime = [NSDate date]; - - // Update active session duration. - self.sessionActiveDuration += [self.sessionCloseTime timeIntervalSinceDate:self.sessionResumeTime]; - - int sessionLength = (int)[[NSDate date] timeIntervalSince1970] - self.lastSessionStartTimestamp; - - @try { - // Create the JSON representing the close blob - NSMutableString *closeEventString = [NSMutableString string]; - [closeEventString appendString:@"{"]; - [closeEventString appendString:[self formatAttributeWithName:PARAM_DATA_TYPE value:@"c" first:YES]]; - [closeEventString appendString:[self formatAttributeWithName:PARAM_SESSION_UUID value:self.sessionUUID]]; - [closeEventString appendString:[self formatAttributeWithName:PARAM_UUID value:[self randomUUID] ]]; - [closeEventString appendFormat:@",\"%@\":%u", PARAM_SESSION_START, (long)self.lastSessionStartTimestamp]; - [closeEventString appendFormat:@",\"%@\":%u", PARAM_SESSION_ACTIVE, (long)self.sessionActiveDuration]; - [closeEventString appendFormat:@",\"%@\":%u", PARAM_CLIENT_TIME, (long)[self currentTimestamp]]; - - // Avoid recording session lengths of users with unreasonable client times (usually caused by developers testing clock change attacks) - if(sessionLength > 0 && sessionLength < 400000) { - [closeEventString appendFormat:@",\"%@\":%u", PARAM_SESSION_TOTAL, sessionLength]; - } - - // Open second level - screen flow - [closeEventString appendFormat:@",\"%@\":[", PARAM_SESSION_SCREENFLOW]; - [closeEventString appendString:self.screens]; - - // Close second level - screen flow - [closeEventString appendString:@"]"]; - - // Append the custom dimensions - [closeEventString appendString:[self customDimensions]]; - - // Close first level - close blob - [closeEventString appendString:@"}\n"]; - - BOOL success = [[LocalyticsDatabase sharedLocalyticsDatabase] addCloseEventWithBlobString:[[closeEventString copy] autorelease]]; - - self.isSessionOpen = NO; // Session is no longer open. - - if (success) { - // Record final session flow, opting to remove it from the database if the session happens to resume. - // This is safe now that the session has closed because no new events can be added. - success = [self saveApplicationFlowAndRemoveOnResume:YES]; - } - - if (success) { - [self logMessage:@"Session succesfully closed."]; - } else { - [self logMessage:@"Failed to record session close."]; - } - } - @catch (NSException * e) {} - }); -} - -- (void)setOptIn:(BOOL)optedIn { - dispatch_async(_queue, ^{ - @try { - LocalyticsDatabase *db = [LocalyticsDatabase sharedLocalyticsDatabase]; - NSString *t = @"set_opt"; - BOOL success = [db beginTransaction:t]; - - // Write out opt event. - if (success) { - success = [self createOptEvent:optedIn]; - } - - // Update database with the option (stored internally as an opt-out). - if (success) { - [db setOptedOut:optedIn == NO]; - } - - if (success && optedIn == NO) { - // Disable all further Localytics calls for this and future sessions - // This should not be flipped when the session is opted back in because that - // would create an incomplete session. - self.isSessionOpen = NO; - } - - if (success) { - [db releaseTransaction:t]; - [self logMessage:[NSString stringWithFormat:@"Application opted %@", optedIn ? @"in" : @"out"]]; - } else { - [db rollbackTransaction:t]; - [self logMessage:@"Failed to update opt state."]; - } - } - @catch (NSException * e) {} - }); -} - -// Public interface to ll_isOptedIn. -- (BOOL)isOptedIn { - __block BOOL optedIn = YES; - dispatch_sync(_queue, ^{ - optedIn = [self ll_isOptedIn]; - }); - return optedIn; -} - -// A convenience function for users who don't wish to add attributes. -- (void)tagEvent:(NSString *)event { - [self tagEvent:event attributes:nil reportAttributes:nil]; -} - -// Most users should use this tagEvent call. -- (void)tagEvent:(NSString *)event attributes:(NSDictionary *)attributes { - [self tagEvent:event attributes:attributes reportAttributes:nil]; -} - -- (void)tagEvent:(NSString *)event attributes:(NSDictionary *)attributes reportAttributes:(NSDictionary *)reportAttributes { - dispatch_async(_queue, ^{ - @try { - // Do nothing if the session is not open. - if (self.isSessionOpen == NO) - { - [self logMessage:@"Cannot tag an event because the session is not open."]; - return; - } - - if(event == (id)[NSNull null] || event.length == 0) - { - [self logMessage:@"Event tagged without a name. Skipping."]; - return; - } - - // Create the JSON for the event - NSMutableString *eventString = [[[NSMutableString alloc] init] autorelease]; - [eventString appendString:@"{"]; - [eventString appendString:[self formatAttributeWithName:PARAM_DATA_TYPE value:@"e" first:YES] ]; - [eventString appendString:[self formatAttributeWithName:PARAM_UUID value:[self randomUUID] ]]; - [eventString appendString:[self formatAttributeWithName:PARAM_APP_KEY value:self.applicationKey ]]; - [eventString appendString:[self formatAttributeWithName:PARAM_SESSION_UUID value:self.sessionUUID ]]; - [eventString appendString:[self formatAttributeWithName:PARAM_EVENT_NAME value:[self escapeString:event] ]]; - [eventString appendFormat:@",\"%@\":%u", PARAM_CLIENT_TIME, (long)[self currentTimestamp]]; - - // Append the custom dimensions - [eventString appendString:[self customDimensions]]; - - // If there are any attributes for this event, add them as a hash - int attrIndex = 0; - if(attributes != nil) - { - // Open second level - attributes - [eventString appendString:[NSString stringWithFormat:@",\"%@\":{", PARAM_ATTRIBUTES]]; - for (id key in [attributes allKeys]) - { - // Have to escape paramName and paramValue because they user-defined. - [eventString appendString: - [self formatAttributeWithName:[self escapeString:[key description]] - value:[self escapeString:[[attributes valueForKey:key] description]] - first:(attrIndex == 0)]]; - attrIndex++; - } - - // Close second level - attributes - [eventString appendString:@"}"]; - } - - // If there are any report attributes for this event, add them as above - attrIndex = 0; - if(reportAttributes != nil) - { - [eventString appendString:[NSString stringWithFormat:@",\"%@\":{", PARAM_REPORT_ATTRIBUTES]]; - for(id key in [reportAttributes allKeys]) { - [eventString appendString: - [self formatAttributeWithName:[self escapeString:[key description]] - value:[self escapeString:[[reportAttributes valueForKey:key] description]] - first:(attrIndex == 0)]]; - attrIndex++; - } - [eventString appendString:@"}"]; - } - - // Close first level - Event information - [eventString appendString:@"}\n"]; - - BOOL success = [[LocalyticsDatabase sharedLocalyticsDatabase] addEventWithBlobString:[[eventString copy] autorelease]]; - if (success) { - // User-originated events should be tracked as application flow. - [self addFlowEventWithName:event type:@"e"]; // "e" for Event. - - [self logMessage:[@"Tagged event: " stringByAppendingString:event]]; - } else { - [self logMessage:@"Failed to tag event."]; - } - } - @catch (NSException * e) {} - }); -} - -- (void)tagScreen:(NSString *)screen { - dispatch_async(_queue, ^{ - // Do nothing if the session is not open. - if (self.isSessionOpen == NO) - { - [self logMessage:@"Cannot tag a screen because the session is not open."]; - return; - } - - // Tag screen with description to enforce string type and avoid retaining objects passed by clients in lieu of a - // screen name. - NSString *screenName = [screen description]; - [self addFlowEventWithName:screenName type:@"s"]; // "s" for Screen. - - // Maintain a parallel list of only screen names. This is submitted in the session close event. - // This may be removed in a future version of the client library. - [self addScreenWithName:screenName]; - - [self logMessage:[@"Tagged screen: " stringByAppendingString:screenName]]; - }); -} - -- (void)setCustomDimension:(int)dimension value:(NSString *)value { - dispatch_async(_queue, ^{ - if(dimension < 0 || dimension > 3) { - [self logMessage:@"Only valid dimensions are 0 - 3"]; - return; - } - - if(false == [[LocalyticsDatabase sharedLocalyticsDatabase] setCustomDimension:dimension value:value]) { - [self logMessage:@"Unable to set custom dimensions."]; - } - }); -} - -- (void)upload { - dispatch_group_async(_criticalGroup, _queue, ^{ - @try { - if ([[LocalyticsUploader sharedLocalyticsUploader] isUploading]) { - [self logMessage:@"An upload is already in progress. Aborting."]; - return; - } - - NSString *t = @"stage_upload"; - LocalyticsDatabase *db = [LocalyticsDatabase sharedLocalyticsDatabase]; - BOOL success = [db beginTransaction:t]; - - // - The event list for the current session is not modified - // New flow events are only transitioned to the "old" list if the upload is staged successfully. The queue - // ensures that the list of events are not modified while a call to upload is in progress. - if (success) { - // Write flow blob to database. This is for a session in progress and should not be removed upon resume. - success = [self saveApplicationFlowAndRemoveOnResume:NO]; - } - - if (success && [db unstagedEventCount] > 0) { - // Increment upload sequence number. - int sequenceNumber = 0; - success = [db incrementLastUploadNumber:&sequenceNumber]; - - // Write out header to database. - sqlite3_int64 headerRowId = 0; - if (success) { - NSString *headerBlob = [self blobHeaderStringWithSequenceNumber:sequenceNumber]; - success = [db addHeaderWithSequenceNumber:sequenceNumber blobString:headerBlob rowId:&headerRowId]; - } - - // Associate unstaged events. - if (success) { - success = [db stageEventsForUpload:headerRowId]; - } - } - - if (success) { - // Complete transaction - [db releaseTransaction:t]; - - // Move new flow events to the old flow event array. - if (self.unstagedFlowEvents.length) { - if (self.stagedFlowEvents.length) { - [self.stagedFlowEvents appendFormat:@",%@", self.unstagedFlowEvents]; - } else { - self.stagedFlowEvents = [[self.unstagedFlowEvents mutableCopy] autorelease]; - } - self.unstagedFlowEvents = [NSMutableString string]; - } - - // Begin upload. - [[LocalyticsUploader sharedLocalyticsUploader] uploaderWithApplicationKey:self.applicationKey]; - } else { - [db rollbackTransaction:t]; - [self logMessage:@"Failed to start upload."]; - } - } - @catch (NSException * e) { } - }); -} - -#pragma mark Private Methods - -- (void)ll_open { - // There are a number of conditions in which nothing should be done: - if (self.hasInitialized == NO || // the session object has not yet initialized - self.isSessionOpen == YES) // session has already been opened - { - [self logMessage:@"Unable to open session."]; - return; - } - - if([self ll_isOptedIn] == false) { - [self logMessage:@"Can't open session because user is opted out."]; - return; - } - - @try { - // If there is too much data on the disk, don't bother collecting any more. - LocalyticsDatabase *db = [LocalyticsDatabase sharedLocalyticsDatabase]; - if([db databaseSize] > MAX_DATABASE_SIZE) { - [self logMessage:@"Database has exceeded the maximum size. Session not opened."]; - self.isSessionOpen = NO; - return; - } - - self.sessionActiveDuration = 0; - self.sessionResumeTime = [NSDate date]; - self.unstagedFlowEvents = [NSMutableString string]; - self.stagedFlowEvents = [NSMutableString string]; - self.screens = [NSMutableString string]; - - // Begin transaction for session open. - NSString *t = @"open_session"; - BOOL success = [db beginTransaction:t]; - - // Save session start time. - self.lastSessionStartTimestamp = [self.sessionResumeTime timeIntervalSince1970]; - if (success) { - success = [db setLastsessionStartTimestamp:self.lastSessionStartTimestamp]; - } - - // Retrieve next session number. - int sessionNumber = 0; - if (success) { - success = [db incrementLastSessionNumber:&sessionNumber]; - } - - if (success) { - // Prepare session open event. - self.sessionUUID = [self randomUUID]; - - // Store event. - NSMutableString *openEventString = [NSMutableString string]; - [openEventString appendString:@"{"]; - [openEventString appendString:[self formatAttributeWithName:PARAM_DATA_TYPE value:@"s" first:YES]]; - [openEventString appendString:[self formatAttributeWithName:PARAM_NEW_SESSION_UUID value:self.sessionUUID]]; - [openEventString appendFormat:@",\"%@\":%u", PARAM_CLIENT_TIME, (long)self.lastSessionStartTimestamp]; - [openEventString appendFormat:@",\"%@\":%d", PARAM_SESSION_NUMBER, sessionNumber]; - - [openEventString appendString:[self customDimensions]]; - - [openEventString appendString:@"}\n"]; - - [self customDimensions]; - - success = [db addEventWithBlobString:[[openEventString copy] autorelease]]; - } - - if (success) { - [db releaseTransaction:t]; - self.isSessionOpen = YES; - self.sessionHasBeenOpen = YES; - [self logMessage:[@"Succesfully opened session. UUID is: " stringByAppendingString:self.sessionUUID]]; - } else { - [db rollbackTransaction:t]; - self.isSessionOpen = NO; - [self logMessage:@"Failed to open session."]; - } - } - @catch (NSException * e) {} -} - -/*! - @method reopenPreviousSession - @abstract Reopens the previous session, using previous session variables. If there was no previous session, do nothing. -*/ -- (void)reopenPreviousSession { - if(self.sessionHasBeenOpen == NO){ - [self logMessage:@"Unable to reopen previous session, because a previous session was never opened."]; - return; - } - - // Record session resume time. - self.sessionResumeTime = [NSDate date]; - - //Remove close and flow events if they exist. - [[LocalyticsDatabase sharedLocalyticsDatabase] removeLastCloseAndFlowEvents]; - - self.isSessionOpen = YES; -} - -/*! - @method addFlowEventWithName:type: - @abstract Adds a simple key-value pair to the list of events tagged during this session. - @param name The name of the tagged event. - @param eventType A key representing the type of the tagged event. Either "s" for Screen or "e" for Event. - */ -- (void)addFlowEventWithName:(NSString *)name type:(NSString *)eventType { - if (!name || !eventType) - return; - - // Format new event as simple key-value dictionary. - NSString *eventString = [self formatAttributeWithName:eventType value:[self escapeString:name] first:YES]; - - // Flow events are uploaded as a sequence of key-value pairs. Wrap the above in braces and append to the list. - BOOL previousFlowEvents = self.unstagedFlowEvents.length > 0; - if (previousFlowEvents) { - [self.unstagedFlowEvents appendString:@","]; - } - [self.unstagedFlowEvents appendFormat:@"{%@}", eventString]; -} - -/*! - @method addScreenWithName: - @abstract Adds a name to list of screens encountered during this session. - @discussion The complete list of names is sent with the session close event. Screen names are stored in parallel to the - screen flow events list and may be removed in future versions of this library. - @param name The name of the tagged screen. - */ -- (void)addScreenWithName:(NSString *)name { - if (self.screens.length > 0) { - [self.screens appendString:@","]; - } - [self.screens appendFormat:@"\"%@\"", [self escapeString:name]]; -} - -/*! - @method blobHeaderStringWithSequenceNumber: - @abstract Creates the JSON string for the upload blob header, substituting in the given upload sequence number. - @param nextSequenceNumber The sequence number for the current upload attempt. - @return The upload header JSON blob. - */ -- (NSString *)blobHeaderStringWithSequenceNumber:(int)nextSequenceNumber { - - NSMutableString *headerString = [[[NSMutableString alloc] init] autorelease]; - - // Common header information. - UIDevice *thisDevice = [UIDevice currentDevice]; - NSLocale *locale = [NSLocale currentLocale]; - NSLocale *english = [[[NSLocale alloc] initWithLocaleIdentifier: @"en_US"] autorelease]; - NSLocale *device_locale = [[NSLocale preferredLanguages] objectAtIndex:0]; - NSString *device_language = [english displayNameForKey:NSLocaleIdentifier value:device_locale]; - NSString *locale_country = [english displayNameForKey:NSLocaleCountryCode value:[locale objectForKey:NSLocaleCountryCode]]; - NSString *uuid = [self randomUUID]; - NSString *device_uuid = [self uniqueDeviceIdentifier]; - - // Open first level - blob information - [headerString appendString:@"{"]; - [headerString appendFormat:@"\"%@\":%d", PARAM_SEQUENCE_NUMBER, nextSequenceNumber]; - [headerString appendFormat:@",\"%@\":%u", PARAM_PERSISTED_AT, (long)[[LocalyticsDatabase sharedLocalyticsDatabase] createdTimestamp]]; - [headerString appendString:[self formatAttributeWithName:PARAM_DATA_TYPE value:@"h" ]]; - [headerString appendString:[self formatAttributeWithName:PARAM_UUID value:uuid ]]; - - // Open second level - blob header attributes - [headerString appendString:[NSString stringWithFormat:@",\"%@\":{", PARAM_ATTRIBUTES]]; - [headerString appendString:[self formatAttributeWithName:PARAM_DATA_TYPE value:@"a" first:YES]]; - - // >> Application and session information - [headerString appendString:[self formatAttributeWithName:PARAM_INSTALL_ID value:[self installationId] ]]; - [headerString appendString:[self formatAttributeWithName:PARAM_APP_KEY value:self.applicationKey ]]; - [headerString appendString:[self formatAttributeWithName:PARAM_APP_VERSION value:[self appVersion] ]]; - [headerString appendString:[self formatAttributeWithName:PARAM_LIBRARY_VERSION value:CLIENT_VERSION ]]; - - // >> Device Information -// [headerString appendString:[self formatAttributeWithName:PARAM_DEVICE_UUID value:device_uuid ]]; - [headerString appendString:[self formatAttributeWithName:PARAM_DEVICE_UUID_HASHED value:[self hashString:device_uuid] ]]; - [headerString appendString:[self formatAttributeWithName:PARAM_DEVICE_PLATFORM value:[thisDevice model] ]]; - [headerString appendString:[self formatAttributeWithName:PARAM_DEVICE_OS_VERSION value:[thisDevice systemVersion] ]]; - [headerString appendString:[self formatAttributeWithName:PARAM_DEVICE_MODEL value:[self deviceModel] ]]; - -// MAC Address collection. Uncomment the following line to add Mac address to the mix of collected identifiers -// [headerString appendString:[self formatAttributeWithName:PARAM_DEVICE_MAC value:[self hashString:[self macAddress]] ]]; - [headerString appendString:[NSString stringWithFormat:@",\"%@\":%d", PARAM_DEVICE_MEMORY, (long)[self availableMemory] ]]; - [headerString appendString:[self formatAttributeWithName:PARAM_LOCALE_LANGUAGE value:device_language]]; - [headerString appendString:[self formatAttributeWithName:PARAM_LOCALE_COUNTRY value:locale_country]]; - [headerString appendString:[self formatAttributeWithName:PARAM_DEVICE_COUNTRY value:[locale objectForKey:NSLocaleCountryCode]]]; - [headerString appendString:[NSString stringWithFormat:@",\"%@\":%@", PARAM_JAILBROKEN, [self isDeviceJailbroken] ? @"true" : @"false"]]; - - // Close second level - attributes - [headerString appendString:@"}"]; - - // Close first level - blob information - [headerString appendString:@"}\n"]; - - return [[headerString copy] autorelease]; -} - -- (BOOL)ll_isOptedIn { - return [[LocalyticsDatabase sharedLocalyticsDatabase] isOptedOut] == NO; -} - -/*! - @method createOptEvent: - @abstract Generates the JSON for an opt event (user opting in or out) and writes it to the database. - @return YES if the event was written to the database, NO otherwise - */ -- (BOOL)createOptEvent:(BOOL)optState { - NSMutableString *optEventString = [NSMutableString string]; - [optEventString appendString:@"{"]; - [optEventString appendString:[self formatAttributeWithName:PARAM_DATA_TYPE value:@"o" first:YES]]; - [optEventString appendString:[self formatAttributeWithName:PARAM_APP_KEY value:self.applicationKey first:NO]]; - [optEventString appendString:[NSString stringWithFormat:@",\"%@\":%@", PARAM_OPT_VALUE, (optState ? @"true" : @"false") ]]; - [optEventString appendFormat:@",\"%@\":%u", PARAM_CLIENT_TIME, (long)[self currentTimestamp]]; - [optEventString appendString:@"}\n"]; - - BOOL success = [[LocalyticsDatabase sharedLocalyticsDatabase] addEventWithBlobString:[[optEventString copy] autorelease]]; - return success; -} - -/* - @method saveApplicationFlowAndRemoveOnResume: - @abstract Constructs an application flow blob string and writes it to the database, optionally flagging it for deletion - if the session is resumed. - @param removeOnResume YES if the application flow blob should be deleted if the session is resumed. - @return YES if the application flow event was written to the database successfully. - */ -- (BOOL)saveApplicationFlowAndRemoveOnResume:(BOOL)removeOnResume { - BOOL success = YES; - - // If there are no new events, then there is nothing additional to save. - if (self.unstagedFlowEvents.length) { - // Flows are uploaded as a distinct blob type containing arrays of new and previously-uploaded event and - // screen names. Write a flow event to the database. - NSMutableString *flowEventString = [[[NSMutableString alloc] init] autorelease]; - - // Open first level - flow blob event - [flowEventString appendString:@"{"]; - [flowEventString appendString:[self formatAttributeWithName:PARAM_DATA_TYPE value:@"f" first:YES]]; - [flowEventString appendString:[self formatAttributeWithName:PARAM_UUID value:[self randomUUID] ]]; - [flowEventString appendFormat:@",\"%@\":%u", PARAM_SESSION_START, (long)self.lastSessionStartTimestamp]; - - // Open second level - new flow events - [flowEventString appendFormat:@",\"%@\":[", PARAM_NEW_FLOW_EVENTS]; - [flowEventString appendString:self.unstagedFlowEvents]; // Flow events are escaped in |-addFlowEventWithName:| - // Close second level - new flow events - [flowEventString appendString:@"]"]; - - // Open second level - old flow events - [flowEventString appendFormat:@",\"%@\":[", PARAM_OLD_FLOW_EVENTS]; - [flowEventString appendString:self.stagedFlowEvents]; - // Close second level - old flow events - [flowEventString appendString:@"]"]; - - // Close first level - flow blob event - [flowEventString appendString:@"}\n"]; - - success = [[LocalyticsDatabase sharedLocalyticsDatabase] addFlowEventWithBlobString:[[flowEventString copy] autorelease]]; - } - return success; -} - -// Convenience method for formatAttributeWithName which sets firstAttribute to NO since -// this is the most common way to call it. -- (NSString *)formatAttributeWithName:(NSString *)paramName value:(NSString *)paramValue { - return [self formatAttributeWithName:paramName value:paramValue first:NO]; -} - -/*! - @method formatAttributeWithName:value:firstAttribute: - @abstract Returns the given string key/value pair as a JSON string. - @param paramName The name of the parameter - @param paramValue The value of the parameter - @param firstAttribute YES if this attribute is first in an attribute list - @return a JSON string which can be dumped to the JSON file - */ -- (NSString *)formatAttributeWithName:(NSString *)paramName value:(NSString *)paramValue first:(BOOL)firstAttribute { - // The expected result is one of: - // "paramname":"paramvalue" - // "paramname":null - NSMutableString *formattedString = [NSMutableString string]; - if (!firstAttribute) { - [formattedString appendString:@","]; - } - - NSString *quotedString = @"\"%@\""; - paramName = [NSString stringWithFormat:quotedString, paramName]; - paramValue = paramValue ? [NSString stringWithFormat:quotedString, paramValue] : @"null"; - [formattedString appendFormat:@"%@:%@", paramName, paramValue]; - return [[formattedString copy] autorelease]; -} - -/*! - @method escapeString - @abstract Formats the input string so it fits nicely in a JSON document. This includes - escaping double quote and slash characters. - @return The escaped version of the input string - */ -- (NSString *)escapeString:(NSString *)input -{ - NSString *output = [input stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"]; - output = [output stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""]; - output = [output stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"]; - return output; -} - -- (void)applicationDidEnterBackground:(NSNotification *)notification -{ - [self logMessage:@"Application entered the background."]; - - // Continue executing until critical blocks finish executing or background time runs out, whichever comes first. - UIApplication *application = (UIApplication *)[notification object]; - __block UIBackgroundTaskIdentifier taskID = [application beginBackgroundTaskWithExpirationHandler:^{ - // Synchronize with the main queue in case the the tasks finish at the same time as the expiration handler. - dispatch_async(dispatch_get_main_queue(), ^{ - if (taskID != UIBackgroundTaskInvalid) { - [self logMessage:@"Failed to finish executing critical tasks. Cleaning up."]; - [application endBackgroundTask:taskID]; - taskID = UIBackgroundTaskInvalid; - } - }); - }]; - - // Critical tasks have finished. Expire the background task. - dispatch_group_notify(_criticalGroup, dispatch_get_main_queue(), ^{ - [self logMessage:@"Finished executing critical tasks."]; - if (taskID != UIBackgroundTaskInvalid) { - [application endBackgroundTask:taskID]; - taskID = UIBackgroundTaskInvalid; - } - }); -} - -/*! - @method logMessage - @abstract Logs a message with (localytics) prepended to it. - @param message The message to log - */ -- (void)logMessage:(NSString *)message -{ - if(DO_LOCALYTICS_LOGGING) { - NSLog(@"(localytics) %s\n", [message UTF8String]); - } -} - -#pragma mark Datapoint Functions -/*! - @method customDimensions - @abstract Returns the json blob containing the custom dimensions. Assumes this will be appended - to an existing blob and as a result prepends the results with a comma. - */ -- (NSString *)customDimensions -{ - NSMutableString *dimensions = [[[NSMutableString alloc] init] autorelease]; - - for(int i=0; i <4; i++) { - NSString *dimension = [[LocalyticsDatabase sharedLocalyticsDatabase] customDimension:i]; - if(dimension) { - [dimensions appendFormat:@",\"c%i\":\"%@\"", i, dimension]; - } - } - - return [[dimensions copy] autorelease]; -} - -/*! - @method macAddress - @abstract Returns the macAddress of this device. - */ -- (NSString *)macAddress -{ - NSMutableString* result = [NSMutableString string]; - - BOOL success; - struct ifaddrs* addrs; - const struct ifaddrs* cursor; - const struct sockaddr_dl* dlAddr; - const uint8_t * base; - int i; - - success = (getifaddrs(&addrs) == 0); - if(success) - { - cursor = addrs; - while(cursor != NULL) - { - if((cursor->ifa_addr->sa_family == AF_LINK) && (((const struct sockaddr_dl *) cursor->ifa_addr)->sdl_type == IFT_ETHER)) - { - dlAddr = (const struct sockaddr_dl *) cursor->ifa_addr; - base = (const uint8_t *) &dlAddr->sdl_data[dlAddr->sdl_nlen]; - - for(i=0; isdl_alen; i++) - { - if(i != 0) { - [result appendString:@":"]; - } - [result appendFormat:@"%02x", base[i]]; - } - break; - } - cursor = cursor->ifa_next; - } - freeifaddrs(addrs); - } - - return result; -} - -/*! - @method hashString - @abstract SHA1 Hashes a string - */ -- (NSString *)hashString:(NSString *)input -{ - NSData *stringBytes = [input dataUsingEncoding: NSUTF8StringEncoding]; - unsigned char digest[CC_SHA1_DIGEST_LENGTH]; - - if (CC_SHA1([stringBytes bytes], [stringBytes length], digest)) { - NSMutableString* hashedUUID = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2]; - for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) { - [hashedUUID appendFormat:@"%02x", digest[i]]; - } - return hashedUUID; - } - - return nil; -} - -/*! - @method randomUUID - @abstract Generates a random UUID - @return NSString containing the new UUID - */ -- (NSString *)randomUUID { - CFUUIDRef theUUID = CFUUIDCreate(NULL); - CFStringRef stringUUID = CFUUIDCreateString(NULL, theUUID); - CFRelease(theUUID); - return [(NSString *)stringUUID autorelease]; -} - -/*! - @method installationId - @abstract Looks in user preferences for an ID unique to this installation. If one is not - found it checks if one happens to be in the database (carroyover from older version of the db) - if not, it generates one. - @return A string uniquely identifying this installation of this app - */ -- (NSString *) installationId { - NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; - NSString *installId = [prefs stringForKey:PREFERENCES_KEY]; - - if(installId == nil) - { - [self logMessage:@"Install ID not found in preferences, checking DB"]; - installId = [[LocalyticsDatabase sharedLocalyticsDatabase] installId]; - } - - // If it hasn't been found yet, generate a new one. - if(installId == nil) - { - [self logMessage:@"Install ID not find one in database, generating a new one."]; - installId = [self randomUUID]; - } - - // Store the newly generated installId - [prefs setObject:installId forKey:PREFERENCES_KEY]; - [[NSUserDefaults standardUserDefaults] synchronize]; - - return installId; -} - -/*! - @method uniqueDeviceIdentifier - @abstract A unique device identifier is a hash value composed from various hardware identifiers such - as the device’s serial number. It is guaranteed to be unique for every device but cannot - be tied to a user account. [UIDevice Class Reference] - @return An 1-way hashed identifier unique to this device. - */ -- (NSString *)uniqueDeviceIdentifier { - -// Supress the warning for uniqueIdentifier being deprecated. -// We collect it as long as it is available along with a randomly generated ID. -// This way, when this becomes unavailable we can map existing users so the -// new vs returning counts do not break. This will be removed before it causes grief. -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - NSString *systemId = [[UIDevice currentDevice] uniqueIdentifier]; -#pragma clang diagnostic pop - - return systemId; -} - -/*! - @method appVersion - @abstract Gets the pretty string for this application's version. - @return The application's version as a pretty string - */ -- (NSString *)appVersion { - return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]; -} - -/*! - @method currentTimestamp - @abstract Gets the current time as seconds since Unix epoch. - @return an NSTimeInterval time. - */ -- (NSTimeInterval)currentTimestamp { - return [[NSDate date] timeIntervalSince1970]; -} - -/*! - @method isDeviceJailbroken - @abstract checks for the existance of apt to determine whether the user is running any - of the jailbroken app sources. - @return whether or not the device is jailbroken. - */ -- (BOOL) isDeviceJailbroken { - NSFileManager *sessionFileManager = [NSFileManager defaultManager]; - return [sessionFileManager fileExistsAtPath:PATH_TO_APT]; -} - -/*! - @method deviceModel - @abstract Gets the device model string. - @return a platform string identifying the device - */ -- (NSString *)deviceModel { - char *buffer[256] = { 0 }; - size_t size = sizeof(buffer); - sysctlbyname("hw.machine", buffer, &size, NULL, 0); - NSString *platform = [NSString stringWithCString:(const char*)buffer - encoding:NSUTF8StringEncoding]; - return platform; -} - -/*! - @method modelSizeString - @abstract Checks how much disk space is reported and uses that to determine the model - @return A string identifying the model, e.g. 8GB, 16GB, etc - */ -- (NSString *) modelSizeString { - -#if TARGET_IPHONE_SIMULATOR - return @"simulator"; -#endif - - // User partition - NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); - NSDictionary *stats = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[path lastObject] error:nil]; - uint64_t user = [[stats objectForKey:NSFileSystemSize] longLongValue]; - - // System partition - path = NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSSystemDomainMask, YES); - stats = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[path lastObject] error:nil]; - uint64_t system = [[stats objectForKey:NSFileSystemSize] longLongValue]; - - // Add up and convert to gigabytes - // TODO: seem to be missing a system partiton or two... - NSInteger size = (user + system) >> 30; - - // Find nearest power of 2 (eg, 1,2,4,8,16,32,etc). Over 64 and we return 0 - for (NSInteger gig = 1; gig < 257; gig = gig << 1) { - if (size < gig) - return [NSString stringWithFormat:@"%dGB", gig]; - } - return nil; -} - -/*! - @method availableMemory - @abstract Reports how much memory is available - @return A double containing the available free memory - */ -- (double)availableMemory { - double result = NSNotFound; - vm_statistics_data_t stats; - mach_msg_type_number_t count = HOST_VM_INFO_COUNT; - if (!host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&stats, &count)) - result = vm_page_size * stats.free_count; - - return result; -} - - -#pragma mark System Functions -+ (id)allocWithZone:(NSZone *)zone { - @synchronized(self) { - if (_sharedLocalyticsSession == nil) { - _sharedLocalyticsSession = [super allocWithZone:zone]; - return _sharedLocalyticsSession; - } - } - // returns nil on subsequent allocations - return nil; -} - -- (id)copyWithZone:(NSZone *)zone { - return self; -} - -- (id)retain { - return self; -} - -- (unsigned)retainCount { - // maximum value of an unsigned int - prevents additional retains for the class - return UINT_MAX; -} - -- (oneway void)release { - // ignore release commands -} - -- (id)autorelease { - return self; -} - -- (void)dealloc { - [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil]; - - dispatch_release(_criticalGroup); - dispatch_release(_queue); - [_sessionUUID release]; - [_applicationKey release]; - [_sessionCloseTime release]; - [_unstagedFlowEvents release]; - [_stagedFlowEvents release]; - [_screens release]; - [_sharedLocalyticsSession release]; - - [super dealloc]; -} - -@end +// LocalyticsSession.m +// Copyright (C) 2012 Char Software Inc., DBA Localytics +// +// This code is provided under the Localytics Modified BSD License. +// A copy of this license has been distributed in a file called LICENSE +// with this source code. +// +// Please visit www.localytics.com for more information. + +#import "LocalyticsSession.h" +#import "WebserviceConstants.h" +#import "LocalyticsUploader.h" +#import "LocalyticsDatabase.h" + +#include +#include +#include +#include +#include +#include +#include + +#pragma mark Constants +#define PREFERENCES_KEY @"_localytics_install_id" // The randomly generated ID for each install of the app +#define CLIENT_VERSION @"iOS_2.12" // The version of this library +#define LOCALYTICS_DIR @".localytics" // The directory in which the Localytics database is stored +#define IFT_ETHER 0x6 // Ethernet CSMACD +#define PATH_TO_APT @"/private/var/lib/apt/" + +#define DEFAULT_BACKGROUND_SESSION_TIMEOUT 15 // Default value for how many seconds a session persists when App shifts to the background. + +// The singleton session object. +static LocalyticsSession *_sharedLocalyticsSession = nil; + +@interface LocalyticsSession() + +@property (nonatomic, retain) NSString *sessionUUID; +@property (nonatomic, retain) NSString *applicationKey; +@property (nonatomic, assign) NSTimeInterval lastSessionStartTimestamp; +@property (nonatomic, retain) NSDate *sessionResumeTime; +@property (nonatomic, retain) NSDate *sessionCloseTime; +@property (nonatomic, retain) NSMutableString *unstagedFlowEvents; +@property (nonatomic, retain) NSMutableString *stagedFlowEvents; +@property (nonatomic, retain) NSMutableString *screens; +@property (nonatomic, assign) NSTimeInterval sessionActiveDuration; +@property (nonatomic, assign) BOOL sessionHasBeenOpen; +@property (nonatomic, assign) NSInteger sessionNumber; + +// Private methods. +- (void)ll_open; +- (void)reopenPreviousSession; +- (void)addFlowEventWithName:(NSString *)name type:(NSString *)eventType; +- (void)addScreenWithName:(NSString *)name; +- (NSString *)blobHeaderStringWithSequenceNumber:(int)nextSequenceNumber; +- (BOOL)ll_isOptedIn; +- (BOOL)createOptEvent:(BOOL)optState; +- (BOOL)saveApplicationFlowAndRemoveOnResume:(BOOL)removeOnResume; +- (NSString *)formatAttributeWithName:(NSString *)paramName value:(NSString *)paramValue; +- (NSString *)formatAttributeWithName:(NSString *)paramName value:(NSString *)paramValue first:(BOOL)firstAttribute; +-(void) uploadCallback:(NSDictionary*)info; + +// Datapoint methods. +- (NSString *)customDimensions; +- (NSString *)locationDimensions; +- (NSString *)hashString:(NSString *)input; +- (NSString *)randomUUID; +- (NSString *)escapeString:(NSString *)input; +- (NSString *)installationId; +- (NSString *)appVersion; +- (NSTimeInterval)currentTimestamp; +- (BOOL)isDeviceJailbroken; +- (NSString *)deviceModel; +- (NSString *)modelSizeString; +- (double)availableMemory; +- (NSString *)advertisingIdentifier; +- (NSString *)uniqueDeviceIdentifier; + +@end + +@implementation LocalyticsSession + +@synthesize queue = _queue; +@synthesize criticalGroup = _criticalGroup; +@synthesize sessionUUID = _sessionUUID; +@synthesize applicationKey = _applicationKey; +@synthesize lastSessionStartTimestamp = _lastSessionStartTimestamp; +@synthesize sessionResumeTime = _sessionResumeTime; +@synthesize sessionCloseTime = _sessionCloseTime; +@synthesize isSessionOpen = _isSessionOpen; +@synthesize hasInitialized = _hasInitialized; +@synthesize backgroundSessionTimeout = _backgroundSessionTimeout; +@synthesize unstagedFlowEvents = _unstagedFlowEvents; +@synthesize stagedFlowEvents = _stagedFlowEvents; +@synthesize screens = _screens; +@synthesize sessionActiveDuration = _sessionActiveDuration; +@synthesize sessionHasBeenOpen = _sessionHasBeenOpen; +@synthesize sessionNumber = _sessionNumber; +@synthesize enableHTTPS = _enableHTTPS; + +// Stores the last location passed in to the app. +CLLocationCoordinate2D lastDeviceLocation = {0}; + +#pragma mark Singleton + ++ (LocalyticsSession *)sharedLocalyticsSession { + @synchronized(self) { + if (_sharedLocalyticsSession == nil) { + _sharedLocalyticsSession = [[self alloc] init]; + } + } + return _sharedLocalyticsSession; +} + +- (LocalyticsSession *)init { + if((self = [super init])) { + _isSessionOpen = NO; + _hasInitialized = NO; + _backgroundSessionTimeout = DEFAULT_BACKGROUND_SESSION_TIMEOUT; + _sessionHasBeenOpen = NO; + _queue = dispatch_queue_create("com.Localytics.operations", DISPATCH_QUEUE_SERIAL); + _criticalGroup = dispatch_group_create(); + _enableHTTPS = NO; + + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil]; + + [LocalyticsDatabase sharedLocalyticsDatabase]; + } + + return self; +} + +#pragma mark Public Methods + +- (void)LocalyticsSession:(NSString *)appKey { + // If the session has already initialized, don't bother doing it again. + if(self.hasInitialized) + { + [self logMessage:@"Object has already been initialized."]; + return; + } + + @try { + + if(appKey == (id)[NSNull null] || appKey.length == 0) { + [self logMessage:@"App key is null or empty."]; + self.hasInitialized = NO; + return; + } + + // App key should only be alphanumeric chars and dashes. + NSString *trimmedAppKey = [appKey stringByReplacingOccurrencesOfString:@"-" withString:@""]; + if([[trimmedAppKey stringByTrimmingCharactersInSet:[NSCharacterSet alphanumericCharacterSet]] isEqualToString:@""] == false) { + [self logMessage:@"App key may only contain dashes and alphanumeric characters."]; + self.hasInitialized = NO; + return; + } + + if ([LocalyticsDatabase sharedLocalyticsDatabase]) { + // Check if the app key has changed. + NSString *lastAppKey = [[LocalyticsDatabase sharedLocalyticsDatabase] appKey]; + if (![lastAppKey isEqualToString:appKey]) { + if (lastAppKey) { + // Clear previous events and dimensions to guarantee that new data isn't associated with the old app key. + [[LocalyticsDatabase sharedLocalyticsDatabase] resetAnalyticsData]; + + // Vacuum to improve the odds of opening a new session following bulk delete. + [[LocalyticsDatabase sharedLocalyticsDatabase] vacuumIfRequired]; + } + // Record the key for future checks. + [[LocalyticsDatabase sharedLocalyticsDatabase] updateAppKey:appKey]; + } + + self.applicationKey = appKey; + self.hasInitialized = YES; + [self logMessage:[@"Object Initialized. Application's key is: " stringByAppendingString:self.applicationKey]]; + } + } + @catch (NSException * e) {} +} + +- (void)startSession:(NSString *)appKey { + //check app key + NSPredicate *matchPred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"[A-Fa-f0-9-]+"]; + BOOL matches = [matchPred evaluateWithObject:appKey]; + if (matches == NO) { + //generate exception + NSException *exception = [NSException exceptionWithName:@"Invalid Localytics App Key" reason:@"Application key is not valid. Please look at the iOS integration guidlines at http://www.localytics.com/docs/iphone-integration/" userInfo:nil]; + [exception raise]; + } + + [self LocalyticsSession:appKey]; + [self open]; + [self upload]; +} + +// Public interface to ll_open. +- (void)open { + dispatch_async(_queue, ^{ + [self ll_open]; + }); +} + + +- (BOOL)resume { + __block BOOL resumed = NO; + + dispatch_sync(_queue,^{ + @try { + // Do nothing if session is already open + if(self.isSessionOpen == YES) { + resumed = YES; + return; + } + + if([self ll_isOptedIn] == false) { + [self logMessage:@"Can't resume session because user is opted out."]; + resumed = NO; + return; + } + + // conditions for resuming previous session + if(self.sessionHasBeenOpen && + (!self.sessionCloseTime || + [self.sessionCloseTime timeIntervalSinceNow]*-1 <= self.backgroundSessionTimeout)) { + // Note that we allow the session to be resumed even if the database size exceeds the + // maximum. This is because we don't want to create incomplete sessions. If the DB was large + // enough that the previous session could not be opened, there will be nothing to resume. But + // if this session caused it to go over it is better to let it complete and stop the next one + // from being created. + [self logMessage:@"Resume called - Resuming previous session."]; + [self reopenPreviousSession]; + + resumed = YES; + } else { + // otherwise open new session and upload + [self logMessage:@"Resume called - Opening a new session."]; + [self ll_open]; + + resumed = NO; + } + self.sessionCloseTime = nil; + } @catch (NSException *e) {} + }); + return resumed; +} + +- (void)close { + dispatch_group_async(_criticalGroup, _queue, ^{ + // Do nothing if the session is not open + if (self.isSessionOpen == NO) { + [self logMessage:@"Unable to close session"]; + return; + } + + // Save time of close + self.sessionCloseTime = [NSDate date]; + + // Update active session duration. + self.sessionActiveDuration += [self.sessionCloseTime timeIntervalSinceDate:self.sessionResumeTime]; + + int sessionLength = (int)[[NSDate date] timeIntervalSince1970] - self.lastSessionStartTimestamp; + + @try { + // Create the JSON representing the close blob + NSMutableString *closeEventString = [NSMutableString string]; + [closeEventString appendString:@"{"]; + [closeEventString appendString:[self formatAttributeWithName:PARAM_DATA_TYPE value:@"c" first:YES]]; + [closeEventString appendString:[self formatAttributeWithName:PARAM_SESSION_UUID value:self.sessionUUID]]; + [closeEventString appendString:[self formatAttributeWithName:PARAM_UUID value:[self randomUUID] ]]; + [closeEventString appendFormat:@",\"%@\":%ld", PARAM_SESSION_START, (long)self.lastSessionStartTimestamp]; + [closeEventString appendFormat:@",\"%@\":%ld", PARAM_SESSION_ACTIVE, (long)self.sessionActiveDuration]; + [closeEventString appendFormat:@",\"%@\":%ld", PARAM_CLIENT_TIME, (long)[self currentTimestamp]]; + + // Avoid recording session lengths of users with unreasonable client times (usually caused by developers testing clock change attacks) + if(sessionLength > 0 && sessionLength < 400000) { + [closeEventString appendFormat:@",\"%@\":%d", PARAM_SESSION_TOTAL, sessionLength]; + } + + // Open second level - screen flow + [closeEventString appendFormat:@",\"%@\":[", PARAM_SESSION_SCREENFLOW]; + [closeEventString appendString:self.screens]; + + // Close second level - screen flow + [closeEventString appendString:@"]"]; + + // Append the custom dimensions + [closeEventString appendString:[self customDimensions]]; + + // Append the location + [closeEventString appendString:[self locationDimensions]]; + + // Close first level - close blob + [closeEventString appendString:@"}\n"]; + + BOOL success = [[LocalyticsDatabase sharedLocalyticsDatabase] queueCloseEventWithBlobString:[[closeEventString copy] autorelease]]; + + self.isSessionOpen = NO; // Session is no longer open. + + if (success) { + [self logMessage:@"Session succesfully closed."]; + } else { + [self logMessage:@"Failed to record session close."]; + } + } + @catch (NSException * e) {} + }); +} + +- (void)setOptIn:(BOOL)optedIn { + dispatch_async(_queue, ^{ + @try { + LocalyticsDatabase *db = [LocalyticsDatabase sharedLocalyticsDatabase]; + NSString *t = @"set_opt"; + BOOL success = [db beginTransaction:t]; + + // Write out opt event. + if (success) { + success = [self createOptEvent:optedIn]; + } + + // Update database with the option (stored internally as an opt-out). + if (success) { + [db setOptedOut:optedIn == NO]; + } + + if (success && optedIn == NO) { + // Disable all further Localytics calls for this and future sessions + // This should not be flipped when the session is opted back in because that + // would create an incomplete session. + self.isSessionOpen = NO; + } + + if (success) { + [db releaseTransaction:t]; + [self logMessage:[NSString stringWithFormat:@"Application opted %@", optedIn ? @"in" : @"out"]]; + } else { + [db rollbackTransaction:t]; + [self logMessage:@"Failed to update opt state."]; + } + } + @catch (NSException * e) {} + }); +} + +// Public interface to ll_isOptedIn. +- (BOOL)isOptedIn { + __block BOOL optedIn = YES; + dispatch_sync(_queue, ^{ + optedIn = [self ll_isOptedIn]; + }); + return optedIn; +} + +// A convenience function for users who don't wish to add attributes. +- (void)tagEvent:(NSString *)event { + [self tagEvent:event attributes:nil reportAttributes:nil]; +} + +// Most users should use this tagEvent call. +- (void)tagEvent:(NSString *)event attributes:(NSDictionary *)attributes { + [self tagEvent:event attributes:attributes reportAttributes:nil]; +} + +- (void)tagEvent:(NSString *)event attributes:(NSDictionary *)attributes reportAttributes:(NSDictionary *)reportAttributes { + dispatch_async(_queue, ^{ + @try { + // Do nothing if the session is not open. + if (self.isSessionOpen == NO) + { + [self logMessage:@"Cannot tag an event because the session is not open."]; + return; + } + + if(event == (id)[NSNull null] || event.length == 0) + { + [self logMessage:@"Event tagged without a name. Skipping."]; + return; + } + + // Create the JSON for the event + NSMutableString *eventString = [[[NSMutableString alloc] init] autorelease]; + [eventString appendString:@"{"]; + [eventString appendString:[self formatAttributeWithName:PARAM_DATA_TYPE value:@"e" first:YES] ]; + [eventString appendString:[self formatAttributeWithName:PARAM_UUID value:[self randomUUID] ]]; + [eventString appendString:[self formatAttributeWithName:PARAM_APP_KEY value:self.applicationKey ]]; + [eventString appendString:[self formatAttributeWithName:PARAM_SESSION_UUID value:self.sessionUUID ]]; + [eventString appendString:[self formatAttributeWithName:PARAM_EVENT_NAME value:[self escapeString:event] ]]; + [eventString appendFormat:@",\"%@\":%ld", PARAM_CLIENT_TIME, (long)[self currentTimestamp]]; + + // Append the custom dimensions + [eventString appendString:[self customDimensions]]; + + // Append the location + [eventString appendString:[self locationDimensions]]; + + // If there are any attributes for this event, add them as a hash + int attrIndex = 0; + if(attributes != nil) + { + // Open second level - attributes + [eventString appendString:[NSString stringWithFormat:@",\"%@\":{", PARAM_ATTRIBUTES]]; + for (id key in [attributes allKeys]) + { + // Have to escape paramName and paramValue because they user-defined. + [eventString appendString: + [self formatAttributeWithName:[self escapeString:[key description]] + value:[self escapeString:[[attributes valueForKey:key] description]] + first:(attrIndex == 0)]]; + attrIndex++; + } + + // Close second level - attributes + [eventString appendString:@"}"]; + } + + // If there are any report attributes for this event, add them as above + attrIndex = 0; + if(reportAttributes != nil) + { + [eventString appendString:[NSString stringWithFormat:@",\"%@\":{", PARAM_REPORT_ATTRIBUTES]]; + for(id key in [reportAttributes allKeys]) { + [eventString appendString: + [self formatAttributeWithName:[self escapeString:[key description]] + value:[self escapeString:[[reportAttributes valueForKey:key] description]] + first:(attrIndex == 0)]]; + attrIndex++; + } + [eventString appendString:@"}"]; + } + + // Close first level - Event information + [eventString appendString:@"}\n"]; + + BOOL success = [[LocalyticsDatabase sharedLocalyticsDatabase] addEventWithBlobString:[[eventString copy] autorelease]]; + if (success) { + // User-originated events should be tracked as application flow. + [self addFlowEventWithName:event type:@"e"]; // "e" for Event. + + [self ampTrigger:event]; + + [self logMessage:[@"Tagged event: " stringByAppendingString:event]]; + } else { + [self logMessage:@"Failed to tag event."]; + } + } + @catch (NSException * e) {} + }); +} + +- (void)tagScreen:(NSString *)screen { + dispatch_async(_queue, ^{ + // Do nothing if the session is not open. + if (self.isSessionOpen == NO) + { + [self logMessage:@"Cannot tag a screen because the session is not open."]; + return; + } + + // Tag screen with description to enforce string type and avoid retaining objects passed by clients in lieu of a + // screen name. + NSString *screenName = [screen description]; + [self addFlowEventWithName:screenName type:@"s"]; // "s" for Screen. + + // Maintain a parallel list of only screen names. This is submitted in the session close event. + // This may be removed in a future version of the client library. + [self addScreenWithName:screenName]; + + [self logMessage:[@"Tagged screen: " stringByAppendingString:screenName]]; + }); +} + +- (void)setLocation:(CLLocationCoordinate2D)deviceLocation { + lastDeviceLocation = deviceLocation; + [self logMessage:@"Setting Location"]; +} + +- (void)setCustomDimension:(int)dimension value:(NSString *)value { + dispatch_async(_queue, ^{ + if(dimension < 0 || dimension > 3) { + [self logMessage:@"Only valid dimensions are 0 - 3"]; + return; + } + + if(false == [[LocalyticsDatabase sharedLocalyticsDatabase] setCustomDimension:dimension value:value]) { + [self logMessage:@"Unable to set custom dimensions."]; + } + }); +} + +- (void)upload { + dispatch_group_async(_criticalGroup, _queue, ^{ + @try { + if ([[LocalyticsUploader sharedLocalyticsUploader] isUploading]) { + [self logMessage:@"An upload is already in progress. Aborting."]; + return; + } + + NSString *t = @"stage_upload"; + LocalyticsDatabase *db = [LocalyticsDatabase sharedLocalyticsDatabase]; + BOOL success = [db beginTransaction:t]; + + // - The event list for the current session is not modified + // New flow events are only transitioned to the "old" list if the upload is staged successfully. The queue + // ensures that the list of events are not modified while a call to upload is in progress. + if (success) { + // Write flow blob to database. This is for a session in progress and should not be removed upon resume. + success = [self saveApplicationFlowAndRemoveOnResume:NO]; + } + + if (success && [db unstagedEventCount] > 0) { + // Increment upload sequence number. + int sequenceNumber = 0; + success = [db incrementLastUploadNumber:&sequenceNumber]; + + // Write out header to database. + sqlite3_int64 headerRowId = 0; + if (success) { + NSString *headerBlob = [self blobHeaderStringWithSequenceNumber:sequenceNumber]; + success = [db addHeaderWithSequenceNumber:sequenceNumber blobString:headerBlob rowId:&headerRowId]; + } + + // Associate unstaged events. + if (success) { + success = [db stageEventsForUpload:headerRowId]; + } + } + + if (success) { + // Complete transaction + [db releaseTransaction:t]; + + // Move new flow events to the old flow event array. + if (self.unstagedFlowEvents.length) { + if (self.stagedFlowEvents.length) { + [self.stagedFlowEvents appendFormat:@",%@", self.unstagedFlowEvents]; + } else { + self.stagedFlowEvents = [[self.unstagedFlowEvents mutableCopy] autorelease]; + } + self.unstagedFlowEvents = [NSMutableString string]; + } + + // Begin upload. + [[LocalyticsUploader sharedLocalyticsUploader] uploaderWithApplicationKey:self.applicationKey useHTTPS:[self enableHTTPS] installId:[self installationId] resultTarget:self callback:@selector(uploadCallback:)]; + } else { + [db rollbackTransaction:t]; + [self logMessage:@"Failed to start upload."]; + } + } + @catch (NSException * e) { } + }); +} + +#pragma mark Private Methods + +-(NSString*)libraryVersion { + return CLIENT_VERSION; +} + +-(void) uploadCallback:(NSDictionary*)info{ +} + +- (void)dequeueCloseEventBlobString +{ + LocalyticsDatabase *db = [LocalyticsDatabase sharedLocalyticsDatabase]; + NSString *closeEventString = [db dequeueCloseEventBlobString]; + if (closeEventString) { + BOOL success = [db addCloseEventWithBlobString:closeEventString]; + if (!success) { + // Re-queue the close event. + [db queueCloseEventWithBlobString:closeEventString]; + } + } +} + +- (void)ll_open { + // There are a number of conditions in which nothing should be done: + if (self.hasInitialized == NO || // the session object has not yet initialized + self.isSessionOpen == YES) // session has already been opened + { + [self logMessage:@"Unable to open session."]; + return; + } + + if([self ll_isOptedIn] == false) { + [self logMessage:@"Can't open session because user is opted out."]; + return; + } + + @try { + // If there is too much data on the disk, don't bother collecting any more. + LocalyticsDatabase *db = [LocalyticsDatabase sharedLocalyticsDatabase]; + if([db databaseSize] > MAX_DATABASE_SIZE) { + [self logMessage:@"Database has exceeded the maximum size. Session not opened."]; + self.isSessionOpen = NO; + return; + } + + [self dequeueCloseEventBlobString]; + + self.sessionActiveDuration = 0; + self.sessionResumeTime = [NSDate date]; + self.unstagedFlowEvents = [NSMutableString string]; + self.stagedFlowEvents = [NSMutableString string]; + self.screens = [NSMutableString string]; + + // Begin transaction for session open. + NSString *t = @"open_session"; + BOOL success = [db beginTransaction:t]; + + // lastSessionStartTimestamp isn't really the last session start time. + // It's the sessionResumeTime which is [NSDate date] or now. Therefore, + // save the current lastSessionTimestamp value from the database so it + // can be used to calculate the elapsed time between session start times. + NSTimeInterval previousSessionStartTimeInterval = [db lastSessionStartTimestamp]; + + // Save session start time. + self.lastSessionStartTimestamp = [self.sessionResumeTime timeIntervalSince1970]; + if (success) { + success = [db setLastsessionStartTimestamp:self.lastSessionStartTimestamp]; + } + + // Retrieve next session number. + int sessionNumber = 0; + if (success) { + success = [db incrementLastSessionNumber:&sessionNumber]; + } + [self setSessionNumber:sessionNumber]; + + if (success) { + // Prepare session open event. + self.sessionUUID = [self randomUUID]; + + // Store event. + NSMutableString *openEventString = [NSMutableString string]; + [openEventString appendString:@"{"]; + [openEventString appendString:[self formatAttributeWithName:PARAM_DATA_TYPE value:@"s" first:YES]]; + [openEventString appendString:[self formatAttributeWithName:PARAM_NEW_SESSION_UUID value:self.sessionUUID]]; + [openEventString appendFormat:@",\"%@\":%ld", PARAM_CLIENT_TIME, (long)self.lastSessionStartTimestamp]; + [openEventString appendFormat:@",\"%@\":%d", PARAM_SESSION_NUMBER, sessionNumber]; + + double elapsedTime = 0.0; + if (previousSessionStartTimeInterval > 0) { + elapsedTime = [self lastSessionStartTimestamp] - previousSessionStartTimeInterval; + } + NSString *elapsedTimeString = [NSString stringWithFormat:@"%.0f", elapsedTime]; + [openEventString appendString:[self formatAttributeWithName:PARAM_SESSION_ELAPSE_TIME value:elapsedTimeString]]; + + [openEventString appendString:[self customDimensions]]; + [openEventString appendString:[self locationDimensions]]; + + [openEventString appendString:@"}\n"]; + + [self customDimensions]; + + success = [db addEventWithBlobString:[[openEventString copy] autorelease]]; + } + + if (success) { + [db releaseTransaction:t]; + self.isSessionOpen = YES; + self.sessionHasBeenOpen = YES; + [self logMessage:[@"Succesfully opened session. UUID is: " stringByAppendingString:self.sessionUUID]]; + } else { + [db rollbackTransaction:t]; + self.isSessionOpen = NO; + [self logMessage:@"Failed to open session."]; + } + } + @catch (NSException * e) {} +} + +/*! + @method reopenPreviousSession + @abstract Reopens the previous session, using previous session variables. If there was no previous session, do nothing. +*/ +- (void)reopenPreviousSession { + if(self.sessionHasBeenOpen == NO){ + [self logMessage:@"Unable to reopen previous session, because a previous session was never opened."]; + return; + } + + // Record session resume time. + self.sessionResumeTime = [NSDate date]; + + //Remove close and flow events if they exist. + [[LocalyticsDatabase sharedLocalyticsDatabase] removeLastCloseAndFlowEvents]; + + self.isSessionOpen = YES; +} + +/*! + @method addFlowEventWithName:type: + @abstract Adds a simple key-value pair to the list of events tagged during this session. + @param name The name of the tagged event. + @param eventType A key representing the type of the tagged event. Either "s" for Screen or "e" for Event. + */ +- (void)addFlowEventWithName:(NSString *)name type:(NSString *)eventType { + if (!name || !eventType) + return; + + // Format new event as simple key-value dictionary. + NSString *eventString = [self formatAttributeWithName:eventType value:[self escapeString:name] first:YES]; + + // Flow events are uploaded as a sequence of key-value pairs. Wrap the above in braces and append to the list. + BOOL previousFlowEvents = self.unstagedFlowEvents.length > 0; + if (previousFlowEvents) { + [self.unstagedFlowEvents appendString:@","]; + } + [self.unstagedFlowEvents appendFormat:@"{%@}", eventString]; +} + +/*! + @method addScreenWithName: + @abstract Adds a name to list of screens encountered during this session. + @discussion The complete list of names is sent with the session close event. Screen names are stored in parallel to the + screen flow events list and may be removed in future versions of this library. + @param name The name of the tagged screen. + */ +- (void)addScreenWithName:(NSString *)name { + if (self.screens.length > 0) { + [self.screens appendString:@","]; + } + [self.screens appendFormat:@"\"%@\"", [self escapeString:name]]; +} + +/*! + @method blobHeaderStringWithSequenceNumber: + @abstract Creates the JSON string for the upload blob header, substituting in the given upload sequence number. + @param nextSequenceNumber The sequence number for the current upload attempt. + @return The upload header JSON blob. + */ +- (NSString *)blobHeaderStringWithSequenceNumber:(int)nextSequenceNumber { + + NSMutableString *headerString = [[[NSMutableString alloc] init] autorelease]; + + // Common header information. + UIDevice *thisDevice = [UIDevice currentDevice]; + NSLocale *locale = [NSLocale currentLocale]; + NSLocale *english = [[[NSLocale alloc] initWithLocaleIdentifier: @"en_US"] autorelease]; + NSLocale *device_locale = [[NSLocale preferredLanguages] objectAtIndex:0]; + NSString *device_language = [english displayNameForKey:NSLocaleIdentifier value:device_locale]; + NSString *locale_country = [english displayNameForKey:NSLocaleCountryCode value:[locale objectForKey:NSLocaleCountryCode]]; + NSString *uuid = [self randomUUID]; + NSString *device_uuid = [self uniqueDeviceIdentifier]; + NSString *device_adid = [self advertisingIdentifier]; + + // Open first level - blob information + [headerString appendString:@"{"]; + [headerString appendFormat:@"\"%@\":%d", PARAM_SEQUENCE_NUMBER, nextSequenceNumber]; + [headerString appendFormat:@",\"%@\":%ld", PARAM_PERSISTED_AT, (long)[[LocalyticsDatabase sharedLocalyticsDatabase] createdTimestamp]]; + [headerString appendString:[self formatAttributeWithName:PARAM_DATA_TYPE value:@"h" ]]; + [headerString appendString:[self formatAttributeWithName:PARAM_UUID value:uuid ]]; + + // Open second level - blob header attributes + [headerString appendString:[NSString stringWithFormat:@",\"%@\":{", PARAM_ATTRIBUTES]]; + [headerString appendString:[self formatAttributeWithName:PARAM_DATA_TYPE value:@"a" first:YES]]; + + // >> Application and session information + [headerString appendString:[self formatAttributeWithName:PARAM_INSTALL_ID value:[self installationId] ]]; + [headerString appendString:[self formatAttributeWithName:PARAM_APP_KEY value:self.applicationKey ]]; + [headerString appendString:[self formatAttributeWithName:PARAM_APP_VERSION value:[self appVersion] ]]; + [headerString appendString:[self formatAttributeWithName:PARAM_LIBRARY_VERSION value:[self libraryVersion] ]]; + + // >> Device Information + if (device_uuid) { + [headerString appendString:[self formatAttributeWithName:PARAM_DEVICE_UUID_HASHED value:[self hashString:device_uuid] ]]; + } + if (device_adid) { + [headerString appendString:[self formatAttributeWithName:PARAM_DEVICE_ADID value:device_adid]]; + } + [headerString appendString:[self formatAttributeWithName:PARAM_DEVICE_PLATFORM value:[thisDevice model] ]]; + [headerString appendString:[self formatAttributeWithName:PARAM_DEVICE_OS_VERSION value:[thisDevice systemVersion] ]]; + [headerString appendString:[self formatAttributeWithName:PARAM_DEVICE_MODEL value:[self deviceModel] ]]; + +// MAC Address collection. Uncomment the following line to add Mac address to the mix of collected identifiers +// [headerString appendString:[self formatAttributeWithName:PARAM_DEVICE_MAC value:[self hashString:[self macAddress]] ]]; + [headerString appendString:[NSString stringWithFormat:@",\"%@\":%ld", PARAM_DEVICE_MEMORY, (long)[self availableMemory] ]]; + [headerString appendString:[self formatAttributeWithName:PARAM_LOCALE_LANGUAGE value:device_language]]; + [headerString appendString:[self formatAttributeWithName:PARAM_LOCALE_COUNTRY value:locale_country]]; + [headerString appendString:[self formatAttributeWithName:PARAM_DEVICE_COUNTRY value:[locale objectForKey:NSLocaleCountryCode]]]; + [headerString appendString:[NSString stringWithFormat:@",\"%@\":%@", PARAM_JAILBROKEN, [self isDeviceJailbroken] ? @"true" : @"false"]]; + + // Close second level - attributes + [headerString appendString:@"}"]; + + // Close first level - blob information + [headerString appendString:@"}\n"]; + + return [[headerString copy] autorelease]; +} + +- (BOOL)ll_isOptedIn { + return [[LocalyticsDatabase sharedLocalyticsDatabase] isOptedOut] == NO; +} + +/*! + @method createOptEvent: + @abstract Generates the JSON for an opt event (user opting in or out) and writes it to the database. + @return YES if the event was written to the database, NO otherwise + */ +- (BOOL)createOptEvent:(BOOL)optState { + NSMutableString *optEventString = [NSMutableString string]; + [optEventString appendString:@"{"]; + [optEventString appendString:[self formatAttributeWithName:PARAM_DATA_TYPE value:@"o" first:YES]]; + [optEventString appendString:[self formatAttributeWithName:PARAM_UUID value:[self randomUUID] first:NO ]]; + [optEventString appendString:[NSString stringWithFormat:@",\"%@\":%@", PARAM_OPT_VALUE, (optState ? @"false" : @"true") ]]; //this actually transmits the opposite of the opt state. The JSON contains whether the user is opted out, not whether the user is opted in. + [optEventString appendFormat:@",\"%@\":%ld", PARAM_CLIENT_TIME, (long)[self currentTimestamp]]; + [optEventString appendString:@"}\n"]; + + BOOL success = [[LocalyticsDatabase sharedLocalyticsDatabase] addEventWithBlobString:[[optEventString copy] autorelease]]; + return success; +} + +/* + @method saveApplicationFlowAndRemoveOnResume: + @abstract Constructs an application flow blob string and writes it to the database, optionally flagging it for deletion + if the session is resumed. + @param removeOnResume YES if the application flow blob should be deleted if the session is resumed. + @return YES if the application flow event was written to the database successfully. + */ +- (BOOL)saveApplicationFlowAndRemoveOnResume:(BOOL)removeOnResume { + BOOL success = YES; + + // If there are no new events, then there is nothing additional to save. + if (self.unstagedFlowEvents.length) { + // Flows are uploaded as a distinct blob type containing arrays of new and previously-uploaded event and + // screen names. Write a flow event to the database. + NSMutableString *flowEventString = [[[NSMutableString alloc] init] autorelease]; + + // Open first level - flow blob event + [flowEventString appendString:@"{"]; + [flowEventString appendString:[self formatAttributeWithName:PARAM_DATA_TYPE value:@"f" first:YES]]; + [flowEventString appendString:[self formatAttributeWithName:PARAM_UUID value:[self randomUUID] ]]; + [flowEventString appendFormat:@",\"%@\":%ld", PARAM_SESSION_START, (long)self.lastSessionStartTimestamp]; + + // Open second level - new flow events + [flowEventString appendFormat:@",\"%@\":[", PARAM_NEW_FLOW_EVENTS]; + [flowEventString appendString:self.unstagedFlowEvents]; // Flow events are escaped in |-addFlowEventWithName:| + // Close second level - new flow events + [flowEventString appendString:@"]"]; + + // Open second level - old flow events + [flowEventString appendFormat:@",\"%@\":[", PARAM_OLD_FLOW_EVENTS]; + [flowEventString appendString:self.stagedFlowEvents]; + // Close second level - old flow events + [flowEventString appendString:@"]"]; + + // Close first level - flow blob event + [flowEventString appendString:@"}\n"]; + + success = [[LocalyticsDatabase sharedLocalyticsDatabase] addFlowEventWithBlobString:[[flowEventString copy] autorelease]]; + } + return success; +} + +// Convenience method for formatAttributeWithName which sets firstAttribute to NO since +// this is the most common way to call it. +- (NSString *)formatAttributeWithName:(NSString *)paramName value:(NSString *)paramValue { + return [self formatAttributeWithName:paramName value:paramValue first:NO]; +} + +/*! + @method formatAttributeWithName:value:firstAttribute: + @abstract Returns the given string key/value pair as a JSON string. + @param paramName The name of the parameter + @param paramValue The value of the parameter + @param firstAttribute YES if this attribute is first in an attribute list + @return a JSON string which can be dumped to the JSON file + */ +- (NSString *)formatAttributeWithName:(NSString *)paramName value:(NSString *)paramValue first:(BOOL)firstAttribute { + // The expected result is one of: + // "paramname":"paramvalue" + // "paramname":null + NSMutableString *formattedString = [NSMutableString string]; + if (!firstAttribute) { + [formattedString appendString:@","]; + } + + NSString *quotedString = @"\"%@\""; + paramName = [NSString stringWithFormat:quotedString, paramName]; + paramValue = paramValue ? [NSString stringWithFormat:quotedString, paramValue] : @"null"; + [formattedString appendFormat:@"%@:%@", paramName, paramValue]; + return [[formattedString copy] autorelease]; +} + +/*! + @method escapeString + @abstract Formats the input string so it fits nicely in a JSON document. This includes + escaping double quote and slash characters. + @return The escaped version of the input string + */ +- (NSString *)escapeString:(NSString *)input +{ + NSString *output = [input stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"]; + output = [output stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""]; + output = [output stringByReplacingOccurrencesOfString:@"\'" withString:@"\\\'"]; + output = [output stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"]; + output = [output stringByReplacingOccurrencesOfString:@"\t" withString:@"\\t"]; + output = [output stringByReplacingOccurrencesOfString:@"\b" withString:@"\\b"]; + output = [output stringByReplacingOccurrencesOfString:@"\r" withString:@"\\r"]; + output = [output stringByReplacingOccurrencesOfString:@"\f" withString:@"\\f"]; + output = [output stringByReplacingOccurrencesOfString:@"\v" withString:@"\\v"]; + return output; +} + +- (void)applicationDidEnterBackground:(NSNotification *)notification +{ + [self logMessage:@"Application entered the background."]; + + // Continue executing until critical blocks finish executing or background time runs out, whichever comes first. + UIApplication *application = (UIApplication *)[notification object]; + __block UIBackgroundTaskIdentifier taskID = [application beginBackgroundTaskWithExpirationHandler:^{ + // Synchronize with the main queue in case the the tasks finish at the same time as the expiration handler. + dispatch_async(dispatch_get_main_queue(), ^{ + if (taskID != UIBackgroundTaskInvalid) { + [self logMessage:@"Failed to finish executing critical tasks. Cleaning up."]; + [application endBackgroundTask:taskID]; + taskID = UIBackgroundTaskInvalid; + } + }); + }]; + + // Critical tasks have finished. Expire the background task. + dispatch_group_notify(_criticalGroup, dispatch_get_main_queue(), ^{ + [self logMessage:@"Finished executing critical tasks."]; + if (taskID != UIBackgroundTaskInvalid) { + [application endBackgroundTask:taskID]; + taskID = UIBackgroundTaskInvalid; + } + }); +} + +/*! + @method logMessage + @abstract Logs a message with (localytics) prepended to it. + @param message The message to log + */ +- (void)logMessage:(NSString *)message +{ + if(DO_LOCALYTICS_LOGGING) { + NSLog(@"(localytics) %s\n", [message UTF8String]); + } +} + +#pragma mark Datapoint Functions +/*! + @method customDimensions + @abstract Returns the json blob containing the custom dimensions. Assumes this will be appended + to an existing blob and as a result prepends the results with a comma. + */ +- (NSString *)customDimensions +{ + NSMutableString *dimensions = [[[NSMutableString alloc] init] autorelease]; + + for(int i=0; i <4; i++) { + NSString *dimension = [[LocalyticsDatabase sharedLocalyticsDatabase] customDimension:i]; + if(dimension) { + [dimensions appendFormat:@",\"c%i\":\"%@\"", i, dimension]; + } + } + + return [[dimensions copy] autorelease]; +} + +/*! + @method locationDimensions + @abstract Returns the json blob containing the current location if available or nil if no location is available. + */ +- (NSString *)locationDimensions +{ + if(lastDeviceLocation.latitude == 0 || lastDeviceLocation.longitude == 0) { + return @""; + } + + return [NSString stringWithFormat:@",\"lat\":%f,\"lng\":%f", + lastDeviceLocation.latitude, + lastDeviceLocation.longitude]; + + + return [NSString stringWithFormat:@"%lf", lastDeviceLocation.latitude]; +} + +/*! + @method macAddress + @abstract Returns the macAddress of this device. + */ +- (NSString *)macAddress +{ + NSMutableString* result = [NSMutableString string]; + + BOOL success; + struct ifaddrs* addrs; + const struct ifaddrs* cursor; + const struct sockaddr_dl* dlAddr; + const uint8_t * base; + int i; + + success = (getifaddrs(&addrs) == 0); + if(success) + { + cursor = addrs; + while(cursor != NULL) + { + if((cursor->ifa_addr->sa_family == AF_LINK) && (((const struct sockaddr_dl *) cursor->ifa_addr)->sdl_type == IFT_ETHER)) + { + dlAddr = (const struct sockaddr_dl *) cursor->ifa_addr; + base = (const uint8_t *) &dlAddr->sdl_data[dlAddr->sdl_nlen]; + + for(i=0; isdl_alen; i++) + { + if(i != 0) { + [result appendString:@":"]; + } + [result appendFormat:@"%02x", base[i]]; + } + break; + } + cursor = cursor->ifa_next; + } + freeifaddrs(addrs); + } + + return result; +} + +/*! + @method hashString + @abstract SHA1 Hashes a string + */ +- (NSString *)hashString:(NSString *)input +{ + NSData *stringBytes = [input dataUsingEncoding: NSUTF8StringEncoding]; + unsigned char digest[CC_SHA1_DIGEST_LENGTH]; + + if (CC_SHA1([stringBytes bytes], [stringBytes length], digest)) { + NSMutableString* hashedUUID = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2]; + for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) { + [hashedUUID appendFormat:@"%02x", digest[i]]; + } + return hashedUUID; + } + + return nil; +} + +/*! + @method randomUUID + @abstract Generates a random UUID + @return NSString containing the new UUID + */ +- (NSString *)randomUUID { + CFUUIDRef theUUID = CFUUIDCreate(NULL); + CFStringRef stringUUID = CFUUIDCreateString(NULL, theUUID); + CFRelease(theUUID); + return [(NSString *)stringUUID autorelease]; +} + +/*! + @method installationId + @abstract Looks in user preferences for an ID unique to this installation. If one is not + found it checks if one happens to be in the database (carroyover from older version of the db) + if not, it generates one. + @return A string uniquely identifying this installation of this app + */ +- (NSString *) installationId { + NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; + NSString *installId = [prefs stringForKey:PREFERENCES_KEY]; + + if(installId == nil) + { + [self logMessage:@"Install ID not found in preferences, checking DB"]; + installId = [[LocalyticsDatabase sharedLocalyticsDatabase] installId]; + } + + // If it hasn't been found yet, generate a new one. + if(installId == nil) + { + [self logMessage:@"Install ID not find one in database, generating a new one."]; + installId = [self randomUUID]; + } + + // Store the newly generated installId + [prefs setObject:installId forKey:PREFERENCES_KEY]; + [[NSUserDefaults standardUserDefaults] synchronize]; + + return installId; +} + + +/*! + @method uniqueDeviceIdentifier + @abstract A unique device identifier is a hash value composed from various hardware identifiers such + as the device’s serial number. It is guaranteed to be unique for every device but cannot + be tied to a user account. [UIDevice Class Reference] + @return An 1-way hashed identifier unique to this device. + */ +- (NSString *)uniqueDeviceIdentifier { + + NSString *systemId = nil; + // We collect it as long as it is available along with a randomly generated ID. + // This way, when this becomes unavailable we can map existing users so the + // new vs returning counts do not break. + //only do this if the OS is less than 6.0 + if (([[[UIDevice currentDevice] systemVersion] floatValue] < 6.0f)) { + SEL udidSelector = NSSelectorFromString(@"uniqueIdentifier"); + if ([[UIDevice currentDevice] respondsToSelector:udidSelector]) { + systemId = [[UIDevice currentDevice] performSelector:udidSelector]; + } + } + return systemId; +} + + +/*! + @method advertisingIdentifier + @abstract An alphanumeric string unique to each device, used for advertising only. + From UIDevice documentation. + + @return An identifier unique to this device. + */ +- (NSString *)advertisingIdentifier { + NSString *adId = nil; + SEL adidSelector = NSSelectorFromString(@"identifierForAdvertising"); + if ([[UIDevice currentDevice] respondsToSelector:adidSelector]) { + adId = [[[UIDevice currentDevice] performSelector:adidSelector] performSelector:NSSelectorFromString(@"UUIDString")]; + } + return adId; +} + + +/*! + @method appVersion + @abstract Gets the pretty string for this application's version. + @return The application's version as a pretty string + */ +- (NSString *)appVersion { + return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]; +} + +/*! + @method currentTimestamp + @abstract Gets the current time as seconds since Unix epoch. + @return an NSTimeInterval time. + */ +- (NSTimeInterval)currentTimestamp { + return [[NSDate date] timeIntervalSince1970]; +} + +/*! + @method isDeviceJailbroken + @abstract checks for the existance of apt to determine whether the user is running any + of the jailbroken app sources. + @return whether or not the device is jailbroken. + */ +- (BOOL) isDeviceJailbroken { + NSFileManager *sessionFileManager = [NSFileManager defaultManager]; + return [sessionFileManager fileExistsAtPath:PATH_TO_APT]; +} + +/*! + @method deviceModel + @abstract Gets the device model string. + @return a platform string identifying the device + */ +- (NSString *)deviceModel { + char *buffer[256] = { 0 }; + size_t size = sizeof(buffer); + sysctlbyname("hw.machine", buffer, &size, NULL, 0); + NSString *platform = [NSString stringWithCString:(const char*)buffer + encoding:NSUTF8StringEncoding]; + return platform; +} + +/*! + @method modelSizeString + @abstract Checks how much disk space is reported and uses that to determine the model + @return A string identifying the model, e.g. 8GB, 16GB, etc + */ +- (NSString *) modelSizeString { + +#if TARGET_IPHONE_SIMULATOR + return @"simulator"; +#endif + + // User partition + NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSDictionary *stats = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[path lastObject] error:nil]; + uint64_t user = [[stats objectForKey:NSFileSystemSize] longLongValue]; + + // System partition + path = NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSSystemDomainMask, YES); + stats = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[path lastObject] error:nil]; + uint64_t system = [[stats objectForKey:NSFileSystemSize] longLongValue]; + + // Add up and convert to gigabytes + // TODO: seem to be missing a system partiton or two... + NSInteger size = (user + system) >> 30; + + // Find nearest power of 2 (eg, 1,2,4,8,16,32,etc). Over 64 and we return 0 + for (NSInteger gig = 1; gig < 257; gig = gig << 1) { + if (size < gig) + return [NSString stringWithFormat:@"%dGB", gig]; + } + return nil; +} + +/*! + @method availableMemory + @abstract Reports how much memory is available + @return A double containing the available free memory + */ +- (double)availableMemory { + double result = NSNotFound; + vm_statistics_data_t stats; + mach_msg_type_number_t count = HOST_VM_INFO_COUNT; + if (!host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&stats, &count)) + result = vm_page_size * stats.free_count; + + return result; +} + + +#pragma mark System Functions ++ (id)allocWithZone:(NSZone *)zone { + @synchronized(self) { + if (_sharedLocalyticsSession == nil) { + _sharedLocalyticsSession = [super allocWithZone:zone]; + return _sharedLocalyticsSession; + } + } + // returns nil on subsequent allocations + return nil; +} + +- (id)copyWithZone:(NSZone *)zone { + return self; +} + +- (id)retain { + return self; +} + +- (unsigned)retainCount { + // maximum value of an unsigned int - prevents additional retains for the class + return UINT_MAX; +} + +- (oneway void)release { + // ignore release commands +} + +- (id)autorelease { + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil]; + + dispatch_release(_criticalGroup); + dispatch_release(_queue); + [_sessionUUID release]; + [_applicationKey release]; + [_sessionCloseTime release]; + [_unstagedFlowEvents release]; + [_stagedFlowEvents release]; + [_screens release]; + [_sharedLocalyticsSession release]; + + [super dealloc]; +} + +#pragma mark - AMP stub +- (void)ampTrigger:(NSString *)event { + //do nothing +} + + +@end diff --git a/Localytics/LocalyticsUploader.h b/Localytics/LocalyticsUploader.h index 2d6b867e..260241a3 100644 --- a/Localytics/LocalyticsUploader.h +++ b/Localytics/LocalyticsUploader.h @@ -1,5 +1,5 @@ // LocalyticsUploader.h -// Copyright (C) 2009 Char Software Inc., DBA Localytics +// Copyright (C) 2012 Char Software Inc., DBA Localytics // // This code is provided under the Localytics Modified BSD License. // A copy of this license has been distributed in a file called LICENSE @@ -9,6 +9,8 @@ #import +extern NSString * const kLocalyticsKeyResponseBody; + /*! @class LocalyticsUploader @discussion Singleton class to handle data uploads @@ -35,8 +37,28 @@ writing data regardless of whether or not the upload succeeds. Files which have been renamed still count towards the total number of Localytics files which can be stored on the disk. + + This version of the method now just calls the second version of it with a nil target and NULL callback method. @param localyticsApplicationKey the Localytics application ID + @param useHTTPS Flag determining whether HTTP or HTTPS is used for the post URL. + @param installId Install id passed to the server in the x-install-id header field. */ -- (void)uploaderWithApplicationKey:(NSString *)localyticsApplicationKey; +- (void)uploaderWithApplicationKey:(NSString *)localyticsApplicationKey useHTTPS:(BOOL)useHTTPS installId:(NSString *)installId; + +/*! + @method LocalyticsUploader + @abstract Creates a thread which uploads all queued header and event data. + All files starting with sessionFilePrefix are renamed, + uploaded and deleted on upload. This way the sessions can continue + writing data regardless of whether or not the upload succeeds. Files + which have been renamed still count towards the total number of Localytics + files which can be stored on the disk. + @param localyticsApplicationKey the Localytics application ID + @param useHTTPS Flag determining whether HTTP or HTTPS is used for the post URL. + @param installId Install id passed to the server in the x-install-id header field. + @param resultTarget Result target is the target for the callback method that knows how to handle response data + @param callback Callback is the method of the target class that is to be called with the data begin returned by an upload + */ +- (void)uploaderWithApplicationKey:(NSString *)localyticsApplicationKey useHTTPS:(BOOL)useHTTPS installId:(NSString *)installId resultTarget:(id)target callback:(SEL)callbackMethod; @end \ No newline at end of file diff --git a/Localytics/LocalyticsUploader.m b/Localytics/LocalyticsUploader.m index 251c8f97..0b2f6127 100644 --- a/Localytics/LocalyticsUploader.m +++ b/Localytics/LocalyticsUploader.m @@ -1,5 +1,5 @@ // LocalyticsUploader.m -// Copyright (C) 2009 Char Software Inc., DBA Localytics +// Copyright (C) 2012 Char Software Inc., DBA Localytics // // This code is provided under the Localytics Modified BSD License. // A copy of this license has been distributed in a file called LICENSE @@ -10,16 +10,25 @@ #import "LocalyticsUploader.h" #import "LocalyticsSession.h" #import "LocalyticsDatabase.h" +#import "WebserviceConstants.h" #import -#define LOCALYTICS_URL @"http://analytics.localytics.com/api/v2/applications/%@/uploads" +#ifndef LOCALYTICS_URL +#define LOCALYTICS_URL @"http://analytics.localytics.com/api/v2/applications/%@/uploads" +#endif +#ifndef LOCALYTICS_URL_SECURED +#define LOCALYTICS_URL_SECURED @"https://analytics.localytics.com/api/v2/applications/%@/uploads" +#endif static LocalyticsUploader *_sharedUploader = nil; +NSString * const kLocalyticsKeyResponseBody = @"localytics.key.responseBody"; + @interface LocalyticsUploader () - (void)finishUpload; - (NSData *)gzipDeflatedDataWithData:(NSData *)data; - (void)logMessage:(NSString *)message; +- (NSString *)uploadTimeStamp; @property (readwrite) BOOL isUploading; @@ -40,7 +49,13 @@ static LocalyticsUploader *_sharedUploader = nil; #pragma mark - Class Methods -- (void)uploaderWithApplicationKey:(NSString *)localyticsApplicationKey { +- (void)uploaderWithApplicationKey:(NSString *)localyticsApplicationKey useHTTPS:(BOOL)useHTTPS installId:(NSString *)installId +{ + [self uploaderWithApplicationKey:localyticsApplicationKey useHTTPS:useHTTPS installId:installId resultTarget:nil callback:NULL]; +} + +- (void)uploaderWithApplicationKey:(NSString *)localyticsApplicationKey useHTTPS:(BOOL)useHTTPS installId:(NSString *)installId resultTarget:(id)target callback:(SEL)callbackMethod; +{ // Do nothing if already uploading. if (self.isUploading == true) @@ -77,17 +92,26 @@ static LocalyticsUploader *_sharedUploader = nil; NSData *requestData = [blobString dataUsingEncoding:NSUTF8StringEncoding]; NSString *myString = [[[NSString alloc] initWithData:requestData encoding:NSUTF8StringEncoding] autorelease]; [self logMessage:[NSString stringWithFormat:@"Uploading data (length: %u)", [myString length]]]; + [self logMessage:myString]; // Step 2 NSData *deflatedRequestData = [[self gzipDeflatedDataWithData:requestData] retain]; [pool drain]; - NSString *apiUrlString = [NSString stringWithFormat:LOCALYTICS_URL, [localyticsApplicationKey stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; + NSString *urlStringFormat; + if (useHTTPS) { + urlStringFormat = LOCALYTICS_URL_SECURED; + } else { + urlStringFormat = LOCALYTICS_URL; + } + NSString *apiUrlString = [NSString stringWithFormat:urlStringFormat, [localyticsApplicationKey stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; NSMutableURLRequest *submitRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:apiUrlString] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0]; [submitRequest setHTTPMethod:@"POST"]; + [submitRequest setValue:[self uploadTimeStamp] forHTTPHeaderField:HEADER_CLIENT_TIME]; + [submitRequest setValue:installId forHTTPHeaderField:HEADER_INSTALL_ID]; [submitRequest setValue:@"application/x-gzip" forHTTPHeaderField:@"Content-Type"]; [submitRequest setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"]; [submitRequest setValue:[NSString stringWithFormat:@"%d", [deflatedRequestData length]] forHTTPHeaderField:@"Content-Length"]; @@ -100,7 +124,7 @@ static LocalyticsUploader *_sharedUploader = nil; @try { NSURLResponse *response = nil; NSError *responseError = nil; - [NSURLConnection sendSynchronousRequest:submitRequest returningResponse:&response error:&responseError]; + NSData *responseData = [NSURLConnection sendSynchronousRequest:submitRequest returningResponse:&response error:&responseError]; NSInteger responseStatusCode = [(NSHTTPURLResponse *)response statusCode]; if (responseError) { @@ -123,6 +147,18 @@ static LocalyticsUploader *_sharedUploader = nil; [[LocalyticsDatabase sharedLocalyticsDatabase] deleteUploadedData]; } } + + if ([responseData length] > 0) { + if (DO_LOCALYTICS_LOGGING) { + NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; + [self logMessage:[NSString stringWithFormat:@"Response body: %@", responseString]]; + [responseString release]; + } + NSDictionary *userInfo = [NSDictionary dictionaryWithObject:responseData forKey:kLocalyticsKeyResponseBody]; + if (target) { + [target performSelector:callbackMethod withObject:userInfo]; + } + } } @catch (NSException * e) {} @@ -195,6 +231,15 @@ static LocalyticsUploader *_sharedUploader = nil; } } +/*! + @method uploadTimeStamp + @abstract Gets the current time, along with local timezone, formatted as a DateTime for the webservice. + @return a DateTime of the current local time and timezone. + */ +- (NSString *)uploadTimeStamp { + return [ NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970] ]; +} + #pragma mark - System Functions + (id)allocWithZone:(NSZone *)zone { @synchronized(self) { diff --git a/Localytics/UploaderThread.h b/Localytics/UploaderThread.h deleted file mode 100644 index 0b59c5a4..00000000 --- a/Localytics/UploaderThread.h +++ /dev/null @@ -1,48 +0,0 @@ -// UploaderThread.h -// Copyright (C) 2009 Char Software Inc., DBA Localytics -// -// This code is provided under the Localytics Modified BSD License. -// A copy of this license has been distributed in a file called LICENSE -// with this source code. -// -// Please visit www.localytics.com for more information. - -#import - -/*! - @class UploaderThread - @discussion Singleton class to handle data uploads - */ - -@interface UploaderThread : NSObject { - NSURLConnection *_uploadConnection; // The connection which uploads the bits - NSInteger _responseStatusCode; // The HTTP response status code for the current connection - - BOOL _isUploading; // A flag to gaurantee only one uploader instance can happen at once -} - -@property (nonatomic, retain) NSURLConnection *uploadConnection; - -@property BOOL isUploading; - -/*! - @method sharedUploaderThread - @abstract Establishes this as a Singleton Class allowing for data persistence. - The class is accessed within the code using the following syntax: - [[UploaderThread sharedUploaderThread] functionHere] - */ -+ (UploaderThread *)sharedUploaderThread; - -/*! - @method UploaderThread - @abstract Creates a thread which uploads all queued header and event data. - All files starting with sessionFilePrefix are renamed, - uploaded and deleted on upload. This way the sessions can continue - writing data regardless of whether or not the upload succeeds. Files - which have been renamed still count towards the total number of Localytics - files which can be stored on the disk. - @param localyticsApplicationKey the Localytics application ID - */ -- (void)uploaderThreadwithApplicationKey:(NSString *)localyticsApplicationKey; - -@end \ No newline at end of file diff --git a/Localytics/UploaderThread.m b/Localytics/UploaderThread.m deleted file mode 100644 index 3c04c127..00000000 --- a/Localytics/UploaderThread.m +++ /dev/null @@ -1,260 +0,0 @@ -// UploaderThread.m -// Copyright (C) 2009 Char Software Inc., DBA Localytics -// -// This code is provided under the Localytics Modified BSD License. -// A copy of this license has been distributed in a file called LICENSE -// with this source code. -// -// Please visit www.localytics.com for more information. - -#import "UploaderThread.h" -#import "LocalyticsSession.h" -#import "LocalyticsDatabase.h" -#import - -#define LOCALYTICS_URL @"http://analytics.localytics.com/api/v2/applications/%@/uploads" // url to send the - -static UploaderThread *_sharedUploaderThread = nil; - -@interface UploaderThread () -- (void)complete; -- (NSData *)gzipDeflatedDataWithData:(NSData *)data; -- (void)logMessage:(NSString *)message; -@end - -@implementation UploaderThread - -@synthesize uploadConnection = _uploadConnection; -@synthesize isUploading = _isUploading; - -#pragma mark Singleton Class -+ (UploaderThread *)sharedUploaderThread { - @synchronized(self) { - if (_sharedUploaderThread == nil) - { - _sharedUploaderThread = [[self alloc] init]; - } - } - return _sharedUploaderThread; -} - -#pragma mark Class Methods -- (void)uploaderThreadwithApplicationKey:(NSString *)localyticsApplicationKey { - - // Do nothing if already uploading. - if (self.uploadConnection != nil || self.isUploading == true) - { - [self logMessage:@"Upload already in progress. Aborting."]; - return; - } - - [self logMessage:@"Beginning upload process"]; - self.isUploading = true; - - // Prepare the data for upload. The upload could take a long time, so some effort has to be made to be sure that events - // which get written while the upload is taking place don't get lost or duplicated. To achieve this, the logic is: - // 1) Append every header row blob string and and those of its associated events to the upload string. - // 2) Deflate and upload the data. - // 3) On success, delete all blob headers and staged events. Events added while an upload is in process are not - // deleted because they are not associated a header (and cannot be until the upload completes). - - // Step 1 - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - - LocalyticsDatabase *db = [LocalyticsDatabase sharedLocalyticsDatabase]; - NSString *blobString = [db uploadBlobString]; - - if ([blobString length] == 0) { - // There is nothing outstanding to upload. - [self logMessage:@"Abandoning upload. There are no new events."]; - - [pool drain]; - [self complete]; - return; - } - - NSData *requestData = [blobString dataUsingEncoding:NSUTF8StringEncoding]; - NSString *myString = [[[NSString alloc] initWithData:requestData encoding:NSUTF8StringEncoding] autorelease]; - [self logMessage:@"Upload data:"]; - [self logMessage:myString]; - - // Step 2 - NSData *deflatedRequestData = [[self gzipDeflatedDataWithData:requestData] retain]; - - [pool drain]; - - NSString *apiUrlString = [NSString stringWithFormat:LOCALYTICS_URL, [localyticsApplicationKey stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; - NSMutableURLRequest *submitRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:apiUrlString] - cachePolicy:NSURLRequestReloadIgnoringCacheData - timeoutInterval:60.0]; - [submitRequest setHTTPMethod:@"POST"]; - [submitRequest setValue:@"application/x-gzip" forHTTPHeaderField:@"Content-Type"]; - [submitRequest setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"]; - [submitRequest setValue:[NSString stringWithFormat:@"%d", [deflatedRequestData length]] forHTTPHeaderField:@"Content-Length"]; - [submitRequest setHTTPBody:deflatedRequestData]; - [deflatedRequestData release]; - - // The NSURLConnection Object automatically spawns its own thread as a default behavior. - @try - { - [self logMessage:@"Spawning new thread for upload"]; - self.uploadConnection = [NSURLConnection connectionWithRequest:submitRequest delegate:self]; - - // Step 3 is handled by connectionDidFinishLoading. - } - @catch (NSException * e) - { - [self complete]; - } -} - -#pragma mark **** NSURLConnection FUNCTIONS **** - -- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { - // Used to gather response data from server - Not utilized in this version -} - -- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { - // Could receive multiple response callbacks, likely due to redirection. - // Record status and act only when connection completes load. - _responseStatusCode = [(NSHTTPURLResponse *)response statusCode]; -} - -- (void)connectionDidFinishLoading:(NSURLConnection *)connection { - // If the connection finished loading, the files should be deleted. While response status codes in the 5xx range - // leave upload rows intact, the default case is to delete. - if (_responseStatusCode >= 500 && _responseStatusCode < 600) - { - [self logMessage:[NSString stringWithFormat:@"Upload failed with response status code %d", _responseStatusCode]]; - } else - { - // The connection finished loading and uploaded data should be deleted. Because only one instance of the - // uploader can be running at a time it should not be possible for new upload rows to appear so there is no - // fear of deleting data which has not yet been uploaded. - [self logMessage:[NSString stringWithFormat:@"Upload completed successfully. Response code %d", _responseStatusCode]]; - [[LocalyticsDatabase sharedLocalyticsDatabase] deleteUploadData]; - } - - // Close upload session - [self complete]; -} - -- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { - // On error, simply print the error and close the uploader. We have to assume the data was not transmited - // so it is not deleted. In the event that we accidently store data which was succesfully uploaded, the - // duplicate data will be ignored by the server when it is next uploaded. - [self logMessage:[NSString stringWithFormat: - @"Error Uploading. Code: %d, Description: %s", - [error code], - [error localizedDescription]]]; - - [self complete]; -} - -/*! - @method complete - @abstract closes the upload connection and reports back to the session that the upload is complete - */ -- (void)complete { - _responseStatusCode = 0; - self.uploadConnection = nil; - self.isUploading = false; -} - -/*! - @method gzipDeflatedDataWithData - @abstract Deflates the provided data using gzip at the default compression level (6). Complete NSData gzip category available on CocoaDev. http://www.cocoadev.com/index.pl?NSDataCategory. - @return the deflated data - */ -- (NSData *)gzipDeflatedDataWithData:(NSData *)data -{ - if ([data length] == 0) return data; - - z_stream strm; - - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; - strm.total_out = 0; - strm.next_in=(Bytef *)[data bytes]; - strm.avail_in = [data length]; - - // Compresssion Levels: - // Z_NO_COMPRESSION - // Z_BEST_SPEED - // Z_BEST_COMPRESSION - // Z_DEFAULT_COMPRESSION - - if (deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, (15+16), 8, Z_DEFAULT_STRATEGY) != Z_OK) return nil; - - NSMutableData *compressed = [NSMutableData dataWithLength:16384]; // 16K chunks for expansion - - do { - - if (strm.total_out >= [compressed length]) - [compressed increaseLengthBy: 16384]; - - strm.next_out = [compressed mutableBytes] + strm.total_out; - strm.avail_out = [compressed length] - strm.total_out; - - deflate(&strm, Z_FINISH); - - } while (strm.avail_out == 0); - - deflateEnd(&strm); - - [compressed setLength: strm.total_out]; - return [NSData dataWithData:compressed]; -} - -/*! - @method logMessage - @abstract Logs a message with (localytics uploader) prepended to it - @param message The message to log -*/ -- (void) logMessage:(NSString *)message { - if(DO_LOCALYTICS_LOGGING) { - NSLog(@"(localytics uploader) %s\n", [message UTF8String]); - } -} - -#pragma mark System Functions -+ (id)allocWithZone:(NSZone *)zone { - @synchronized(self) { - if (_sharedUploaderThread == nil) { - _sharedUploaderThread = [super allocWithZone:zone]; - return _sharedUploaderThread; - } - } - // returns nil on subsequent allocations - return nil; -} - -- (id)copyWithZone:(NSZone *)zone { - return self; -} - -- (id)retain { - return self; -} - -- (unsigned)retainCount { - // maximum value of an unsigned int - prevents additional retains for the class - return UINT_MAX; -} - -- (oneway void)release { - // ignore release commands -} - -- (id)autorelease { - return self; -} - -- (void)dealloc { - [_uploadConnection release]; - [_sharedUploaderThread release]; - [super dealloc]; -} - -@end diff --git a/Localytics/WebserviceConstants.h b/Localytics/WebserviceConstants.h index fafdf88f..5f53f9fa 100644 --- a/Localytics/WebserviceConstants.h +++ b/Localytics/WebserviceConstants.h @@ -1,5 +1,5 @@ // WebserviceConstants.h -// Copyright (C) 2009 Char Software Inc., DBA Localytics +// Copyright (C) 2012 Char Software Inc., DBA Localytics // // This code is provided under the Localytics Modified BSD License. // A copy of this license has been distributed in a file called LICENSE @@ -11,6 +11,12 @@ // To save disk space and network bandwidth all the keywords have been // abbreviated and are exploded by the server. +/***************** + * Upload Header * + *****************/ +#define HEADER_CLIENT_TIME @"x-upload-time" +#define HEADER_INSTALL_ID @"x-install-id" + /********************* * Shared Attributes * *********************/ @@ -22,6 +28,7 @@ #define PARAM_SESSION_UUID @"su" // UUID for an existing session #define PARAM_NEW_SESSION_UUID @"u" // UUID for a new session #define PARAM_ATTRIBUTES @"attrs" // Attributes (dictionary) +#define PARAM_SESSION_ELAPSE_TIME @"sl" // Number of seconds since the previous session start /*************** * Blob Header * @@ -42,9 +49,8 @@ // PARAM_DATA_TYPE #define PARAM_APP_KEY @"au" // Localytics Application ID -#define PARAM_DEVICE_UUID @"du" // Device UUID #define PARAM_DEVICE_UUID_HASHED @"udid" // Hashed version of the UUID -#define PARAM_DEVICE_MAC @"wmac" // Hashed version of the device Mac +#define PARAM_DEVICE_ADID @"adid" // Advertising Identifier #define PARAM_INSTALL_ID @"iu" // Install ID #define PARAM_JAILBROKEN @"j" // Jailbroken (boolean) #define PARAM_LIBRARY_VERSION @"lv" // Client Version @@ -52,14 +58,11 @@ #define PARAM_DEVICE_PLATFORM @"dp" // Device Platform #define PARAM_LOCALE_LANGUAGE @"dll" // Locale Language #define PARAM_LOCALE_COUNTRY @"dlc" // Locale Country -#define PARAM_NETWORK_COUNTRY @"nc" // Network Country (iso code) // ???: Never used on iPhone. #define PARAM_DEVICE_COUNTRY @"dc" // Device Country (iso code) -#define PARAM_DEVICE_MANUFACTURER @"dma" // Device Manufacturer // ???: Never used on iPhone. Used to be "Device Make". #define PARAM_DEVICE_MODEL @"dmo" // Device Model #define PARAM_DEVICE_OS_VERSION @"dov" // Device OS Version #define PARAM_NETWORK_CARRIER @"nca" // Network Carrier -#define PARAM_DATA_CONNECTION @"dac" // Data Connection Type // ???: Never used on iPhone. -#define PARAM_OPT_VALUE @"optin" // Opt In (boolean) +#define PARAM_OPT_VALUE @"out" // Opt Out (boolean) #define PARAM_DEVICE_MEMORY @"dmem" // Device Memory /***************** diff --git a/MasterPassword/MPAppDelegate_Store.m b/MasterPassword/MPAppDelegate_Store.m index 060bb31d..abe33de5 100644 --- a/MasterPassword/MPAppDelegate_Store.m +++ b/MasterPassword/MPAppDelegate_Store.m @@ -46,11 +46,7 @@ }]; } - if (![managedObjectContext.persistentStoreCoordinator.persistentStores count]) - [managedObjectContext performBlockAndWait:^{ - managedObjectContext.persistentStoreCoordinator = [self storeManager].persistentStoreCoordinator; - }]; - + [[self storeManager] persistentStoreCoordinator]; if (![self storeManager].isReady) return nil; diff --git a/MasterPassword/iOS/MPAppDelegate.m b/MasterPassword/iOS/MPAppDelegate.m index 0524debb..3cf80efc 100644 --- a/MasterPassword/iOS/MPAppDelegate.m +++ b/MasterPassword/iOS/MPAppDelegate.m @@ -116,6 +116,7 @@ NSString *localyticsKey = [self localyticsKey]; if ([localyticsKey length]) { inf(@"Initializing Localytics"); + [LocalyticsSession sharedLocalyticsSession].enableHTTPS = YES; [[LocalyticsSession sharedLocalyticsSession] startSession:localyticsKey]; [[PearlLogger get] registerListener:^BOOL(PearlLogMessage *message) { if (message.level >= PearlLogLevelWarn) @@ -321,23 +322,11 @@ - (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { - wrn(@"Received memory warning."); + inf(@"Received memory warning."); [super applicationDidReceiveMemoryWarning:application]; } -- (void)applicationDidBecomeActive:(UIApplication *)application { - - inf(@"Re-activated"); - [[MPAppDelegate get] checkConfig]; - - if (FBSession.activeSession.state == FBSessionStateCreatedOpening) - // An old Facebook Login session that wasn't finished. Clean it up. - [FBSession.activeSession close]; - - [super applicationDidBecomeActive:application]; -} - - (void)applicationDidEnterBackground:(UIApplication *)application { [[LocalyticsSession sharedLocalyticsSession] close]; @@ -369,10 +358,31 @@ - (void)applicationWillResignActive:(UIApplication *)application { inf(@"Will deactivate"); + [self saveContext]; if (![[MPiOSConfig get].rememberLogin boolValue]) [self signOutAnimated:NO]; + + [[LocalyticsSession sharedLocalyticsSession] close]; + [[LocalyticsSession sharedLocalyticsSession] upload]; + + [super applicationWillResignActive:application]; +} + +- (void)applicationDidBecomeActive:(UIApplication *)application { + + inf(@"Re-activated"); + [[MPAppDelegate get] checkConfig]; + + if (FBSession.activeSession.state == FBSessionStateCreatedOpening) + // An old Facebook Login session that wasn't finished. Clean it up. + [FBSession.activeSession close]; + + [[LocalyticsSession sharedLocalyticsSession] resume]; + [[LocalyticsSession sharedLocalyticsSession] upload]; + + [super applicationDidBecomeActive:application]; } #pragma mark - Behavior diff --git a/MasterPassword/iOS/MPAppsViewController.m b/MasterPassword/iOS/MPAppsViewController.m index 5345bc59..28277ea7 100644 --- a/MasterPassword/iOS/MPAppsViewController.m +++ b/MasterPassword/iOS/MPAppsViewController.m @@ -77,6 +77,13 @@ [super viewWillAppear:animated]; } +- (void)viewDidAppear:(BOOL)animated { + + [[LocalyticsSession sharedLocalyticsSession] tagScreen:@"Apps"]; + + [super viewDidAppear:animated]; +} + - (void)viewWillDisappear:(BOOL)animated { [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide]; diff --git a/MasterPassword/iOS/MPGuideViewController.m b/MasterPassword/iOS/MPGuideViewController.m index 6f10409e..5e348b83 100644 --- a/MasterPassword/iOS/MPGuideViewController.m +++ b/MasterPassword/iOS/MPGuideViewController.m @@ -7,6 +7,7 @@ // #import "MPGuideViewController.h" +#import "LocalyticsSession.h" @implementation MPGuideViewController @@ -35,6 +36,8 @@ - (void)viewDidAppear:(BOOL)animated { + [[LocalyticsSession sharedLocalyticsSession] tagScreen:@"Guide"]; + [super viewDidAppear:animated]; } diff --git a/MasterPassword/iOS/MPMainViewController.m b/MasterPassword/iOS/MPMainViewController.m index 2d8138a4..32a7fc04 100644 --- a/MasterPassword/iOS/MPMainViewController.m +++ b/MasterPassword/iOS/MPMainViewController.m @@ -149,7 +149,7 @@ inf(@"Main will appear"); // Sometimes, the search bar gets stuck in some sort of first-responder mode that it can't get out of... - [self.searchDisplayController.searchBar resignFirstResponder]; + [[self.view.window findFirstResponderInHierarchy] resignFirstResponder]; // Needed for when we appear after a modal VC dismisses: // We can't present until the other modal VC has been fully dismissed and presenting in viewDidAppear will fail. @@ -204,6 +204,8 @@ }]; + [[LocalyticsSession sharedLocalyticsSession] tagScreen:@"Main"]; + [super viewDidAppear:animated]; } @@ -676,7 +678,7 @@ - (IBAction)action:(id)sender { - [PearlSheet showSheetWithTitle:nil message:nil viewStyle:UIActionSheetStyleAutomatic + [PearlSheet showSheetWithTitle:nil viewStyle:UIActionSheetStyleAutomatic initSheet:nil tappedButtonBlock:^(UIActionSheet *sheet, NSInteger buttonIndex) { if (buttonIndex == [sheet cancelButtonIndex]) diff --git a/MasterPassword/iOS/MPPreferencesViewController.m b/MasterPassword/iOS/MPPreferencesViewController.m index df30826e..1954728e 100644 --- a/MasterPassword/iOS/MPPreferencesViewController.m +++ b/MasterPassword/iOS/MPPreferencesViewController.m @@ -11,6 +11,7 @@ #import "MPAppDelegate.h" #import "MPAppDelegate_Key.h" #import "MPAppDelegate_Store.h" +#import "LocalyticsSession.h" @interface MPPreferencesViewController () @@ -80,6 +81,13 @@ [super viewWillAppear:animated]; } +- (void)viewDidAppear:(BOOL)animated { + + [[LocalyticsSession sharedLocalyticsSession] tagScreen:@"Preferences"]; + + [super viewDidAppear:animated]; +} + - (void)viewWillDisappear:(BOOL)animated { inf(@"Preferences will disappear"); @@ -152,6 +160,7 @@ vc.showDoneButton = NO; [self.navigationController pushViewController:vc animated:YES]; + [[LocalyticsSession sharedLocalyticsSession] tagScreen:@"Settings"]; } @end diff --git a/MasterPassword/iOS/MPTypeViewController.m b/MasterPassword/iOS/MPTypeViewController.m index 4357d025..6a02a91d 100644 --- a/MasterPassword/iOS/MPTypeViewController.m +++ b/MasterPassword/iOS/MPTypeViewController.m @@ -7,6 +7,7 @@ // #import "MPTypeViewController.h" +#import "LocalyticsSession.h" @interface MPTypeViewController () @@ -44,6 +45,8 @@ } }]; + [[LocalyticsSession sharedLocalyticsSession] tagScreen:@"Type Selection"]; + [super viewDidAppear:animated]; } diff --git a/MasterPassword/iOS/MPUnlockViewController.m b/MasterPassword/iOS/MPUnlockViewController.m index fe9f5d1f..94008290 100644 --- a/MasterPassword/iOS/MPUnlockViewController.m +++ b/MasterPassword/iOS/MPUnlockViewController.m @@ -16,6 +16,7 @@ #import "MPAppDelegate.h" #import "MPAppDelegate_Key.h" #import "MPAppDelegate_Store.h" +#import "LocalyticsSession.h" @interface MPUnlockViewController () @@ -193,6 +194,8 @@ self.uiContainer.alpha = 1; }]; + [[LocalyticsSession sharedLocalyticsSession] tagScreen:@"Unlock"]; + [super viewDidAppear:animated]; } @@ -749,7 +752,7 @@ return; [PearlSheet showSheetWithTitle:targetedUser.name - message:nil viewStyle:UIActionSheetStyleBlackTranslucent + viewStyle:UIActionSheetStyleBlackTranslucent initSheet:nil tappedButtonBlock:^(UIActionSheet *sheet, NSInteger buttonIndex) { if (buttonIndex == [sheet cancelButtonIndex]) return; @@ -823,7 +826,7 @@ - (IBAction)add:(UIButton *)sender { - [PearlSheet showSheetWithTitle:@"Follow Master Password" message:nil viewStyle:UIActionSheetStyleBlackTranslucent + [PearlSheet showSheetWithTitle:@"Follow Master Password" viewStyle:UIActionSheetStyleBlackTranslucent initSheet:nil tappedButtonBlock:^(UIActionSheet *sheet, NSInteger buttonIndex) { if (buttonIndex == [sheet cancelButtonIndex]) return;