Ejemplo n.º 1
0
        public static void Run()
        {
            GALogger.D("Starting GA thread");

            try
            {
                while (shouldThreadrun)
                {
                    TimedBlock timedBlock;

                    while ((timedBlock = GetNextBlock()) != null)
                    {
                        if (!timedBlock.ignore)
                        {
                            timedBlock.block();
                        }
                    }


#if WINDOWS_WSA || WINDOWS_UWP || WINDOWS_PHONE
                    Task.Delay(1000).Wait();
#else
                    Thread.Sleep(ThreadWaitTimeInMs);
#endif
                }
            }
            catch (Exception e)
            {
                GALogger.E("Error on GA thread");
                GALogger.E(e.ToString());
            }

            GALogger.D("Ending GA thread");
        }
Ejemplo n.º 2
0
        private static void FixMissingSessionEndEvents()
        {
            if (!GAState.IsEventSubmissionEnabled)
            {
                return;
            }

            // Get all sessions that are not current
            Dictionary <string, object> parameters = new Dictionary <string, object>();

            parameters.Add("$session_id", GAState.SessionId);


            string    sql      = "SELECT timestamp, event FROM ga_session WHERE session_id != $session_id;";
            JSONArray sessions = GAStore.ExecuteQuerySync(sql, parameters);

            if (sessions == null || sessions.Count == 0)
            {
                return;
            }

            GALogger.I(sessions.Count + " session(s) located with missing session_end event.");

            // Add missing session_end events
            for (int i = 0; i < sessions.Count; ++i)
            {
                JSONNode session         = sessions[i];
                JSONNode sessionEndEvent = null;

                try
                {
                    sessionEndEvent = JSONNode.LoadFromBinaryBase64(session["event"].Value);
                }
                catch (Exception)
                {
                    //GALogger.E("FixMissingSessionEndEvents: Error decoding json, " + e);
                }

                if (sessionEndEvent != null)
                {
                    long event_ts = sessionEndEvent["client_ts"].AsLong;
                    long start_ts = session["timestamp"].AsLong;

                    long length = event_ts - start_ts;
                    length = Math.Max(0, length);

                    GALogger.D("fixMissingSessionEndEvents length calculated: " + length);

                    sessionEndEvent["category"] = CategorySessionEnd;
                    sessionEndEvent.Add("length", new JSONNumber(length));

                    // Add to store
                    AddEventToStore(sessionEndEvent.AsObject);
                }
                else
                {
                    GALogger.I("Problem decoding session_end event. Skipping  this session_end event.");
                }
            }
        }
Ejemplo n.º 3
0
        public static void Run()
        {
            GALogger.D("Starting GA thread");

            try
            {
                while (!endThread && threadDeadline.CompareTo(DateTime.Now) > 0)
                {
                    RunBlocks();

#if WINDOWS_WSA || WINDOWS_UWP
                    Task.Delay(ThreadWaitTimeInMs).Wait();
#else
                    Thread.Sleep(ThreadWaitTimeInMs);
#endif
                }

                // run any last blocks added
                RunBlocks();

                if (!endThread)
                {
                    GALogger.D("Ending GA thread");
                }
            }
            catch (Exception)
            {
                //GALogger.E("Error on GA thread");
                //GALogger.E(e.ToString());
            }
        }
Ejemplo n.º 4
0
 public static void OnResume()
 {
     GALogger.D("OnResume() called");
     GAThreading.PerformTaskOnGAThread("onResume", () =>
     {
         GAState.ResumeSessionAndStartQueue();
     });
 }
Ejemplo n.º 5
0
        private static void PopulateConfigurations(JSONNode sdkConfig)
        {
            lock (Instance.configurationsLock)
            {
                JSONArray configurations = sdkConfig["configurations"].AsArray;

                if (configurations != null)
                {
                    for (int i = 0; i < configurations.Count; ++i)
                    {
                        JSONNode configuration = configurations[i];

                        if (configuration != null)
                        {
                            string key   = configuration["key"].Value;
                            object value = null;
                            if (configuration["value"].IsNumber)
                            {
                                value = configuration["value"].AsDouble;
                            }
                            else
                            {
                                value = configuration["value"].Value;
                            }
                            long start_ts = configuration["start"].IsNumber ? configuration["start"].AsLong : long.MinValue;
                            long end_ts   = configuration["end"].IsNumber ? configuration["end"].AsLong : long.MaxValue;

                            long client_ts_adjusted = GetClientTsAdjusted();

                            GALogger.D("PopulateConfigurations: key=" + key + ", value=" + value + ", start_ts=" + start_ts + ", end_ts=" + ", client_ts_adjusted=" + client_ts_adjusted);

                            if (key != null && value != null && client_ts_adjusted > start_ts && client_ts_adjusted < end_ts)
                            {
                                JSONObject json = new JSONObject();
                                if (configuration["value"].IsNumber)
                                {
                                    Instance.configurations.Add(key, new JSONNumber(configuration["value"].AsDouble));
                                }
                                else
                                {
                                    Instance.configurations.Add(key, configuration["value"].Value);
                                }

                                GALogger.D("configuration added: " + configuration);
                            }
                        }
                    }
                }
                Instance.commandCenterIsReady = true;
                foreach (ICommandCenterListener listener in Instance.commandCenterListeners)
                {
                    listener.OnCommandCenterUpdated();
                }
            }
        }
Ejemplo n.º 6
0
 public static void OnStop()
 {
     GALogger.D("OnStop() called");
     GAThreading.PerformTaskOnGAThread("onStop", () =>
     {
         try
         {
             GAState.EndSessionAndStopQueue();
         }
         catch (Exception)
         {
         }
     });
 }
Ejemplo n.º 7
0
        public static void StartThread()
#endif
        {
            GALogger.D("StartThread called");
            if (!shouldThreadrun)
            {
                shouldThreadrun = true;
#if WINDOWS_WSA || WINDOWS_UWP || WINDOWS_PHONE
                await ThreadPool.RunAsync(o => Run());
#else
                Thread thread = new Thread(new ThreadStart(Run));
                thread.Priority = ThreadPriority.Lowest;
                thread.Start();
#endif
            }
        }
Ejemplo n.º 8
0
        private byte[] CreatePayloadData(string payload, bool gzip)
        {
            byte[] payloadData;

            if (gzip)
            {
                payloadData = GAUtilities.GzipCompress(payload);
                GALogger.D("Gzip stats. Size: " + Encoding.UTF8.GetBytes(payload).Length + ", Compressed: " + payloadData.Length + ", Content: " + payload);
            }
            else
            {
                payloadData = Encoding.UTF8.GetBytes(payload);
            }

            return(payloadData);
        }
Ejemplo n.º 9
0
        public void SendSdkErrorEvent(EGASdkErrorType type)
        {
            if (!GAState.IsEventSubmissionEnabled)
            {
                return;
            }

            string gameKey   = GAState.GameKey;
            string secretKey = GAState.GameSecret;

            // Validate
            if (!GAValidator.ValidateSdkErrorEvent(gameKey, secretKey, type))
            {
                return;
            }

            // Generate URL
            string url = baseUrl + "/" + gameKey + "/" + eventsUrlPath;

            GALogger.D("Sending 'events' URL: " + url);

            string payloadJSONString = "";

            JSONObject json = GAState.GetSdkErrorEventAnnotations();

            string typeString = SdkErrorTypeToString(type);

            json.Add("type", typeString);

            List <JSONNode> eventArray = new List <JSONNode>();

            eventArray.Add(json);
            payloadJSONString = GAUtilities.ArrayOfObjectsToJsonString(eventArray);

            if (string.IsNullOrEmpty(payloadJSONString))
            {
                GALogger.W("sendSdkErrorEvent: JSON encoding failed.");
                return;
            }

            GALogger.D("sendSdkErrorEvent json: " + payloadJSONString);
            byte[]       payloadData  = Encoding.UTF8.GetBytes(payloadJSONString);
            SdkErrorTask sdkErrorTask = new SdkErrorTask(type, payloadData, secretKey);

            sdkErrorTask.Execute(url);
        }
Ejemplo n.º 10
0
        protected void OnPostExecute(HttpStatusCode responseCode, string responseDescription)
        {
            if (string.IsNullOrEmpty(this.body))
            {
                GALogger.D("sdk error failed. Might be no connection. Description: " + responseDescription + ", Status code: " + responseCode);
                return;
            }

            if (responseCode != HttpStatusCode.OK)
            {
                GALogger.W("sdk error failed. response code not 200. status code: " + responseCode + ", description: " + responseDescription + ", body: " + this.body);
                return;
            }
            else
            {
                countMap[this.type] = countMap[this.type] + 1;
            }
        }
Ejemplo n.º 11
0
        public static void OnSuspend()
        {
            if (_endThread)
            {
                return;
            }

            GALogger.D("OnSuspend() called");
            GAThreading.PerformTaskOnGAThread("onSuspend", () =>
            {
                try
                {
                    GAState.EndSessionAndStopQueue(false);
                }
                catch (Exception)
                {
                }
            });
        }
Ejemplo n.º 12
0
#pragma warning disable 0162
        public static void IncrementProgressionTries(string progression)
        {
            int tries = GetProgressionTries(progression) + 1;

            Instance.progressionTries[progression] = tries;

            if (GAStore.InMemory)
            {
                GALogger.D("Trying to IncrementProgressionTries with InMemory=true - cannot. Skipping.");
            }
            else
            {
                // Persist
                Dictionary <string, object> parms = new Dictionary <string, object>();
                parms.Add("$progression", progression);
                parms.Add("$tries", tries);
                GAStore.ExecuteQuerySync("INSERT OR REPLACE INTO ga_progression (progression, tries) VALUES($progression, $tries);", parms);
            }
        }
Ejemplo n.º 13
0
        public static void OnQuit()
        {
            if (_endThread)
            {
                return;
            }

            GALogger.D("OnQuit() called");
            GAThreading.PerformTaskOnGAThread("onQuit", () =>
            {
                try
                {
                    _endThread = true;
                    GAState.EndSessionAndStopQueue(true);
                }
                catch (Exception)
                {
                }
            });
        }
Ejemplo n.º 14
0
        private EGAHTTPApiResponse ProcessRequestResponse(HttpStatusCode responseCode, string responseMessage, string body, string requestId)
        {
            // if no result - often no connection
            if (string.IsNullOrEmpty(body))
            {
                GALogger.D(requestId + " request. failed. Might be no connection. Description: " + responseMessage + ", Status code: " + responseCode);
                return(EGAHTTPApiResponse.NoResponse);
            }

            // ok
            if (responseCode == HttpStatusCode.OK)
            {
                return(EGAHTTPApiResponse.Ok);
            }
            // ok
            if (responseCode == HttpStatusCode.Created)
            {
                return(EGAHTTPApiResponse.Created);
            }

            // 401 can return 0 status
            if (responseCode == (HttpStatusCode)0 || responseCode == HttpStatusCode.Unauthorized)
            {
                GALogger.D(requestId + " request. 401 - Unauthorized.");
                return(EGAHTTPApiResponse.Unauthorized);
            }

            if (responseCode == HttpStatusCode.BadRequest)
            {
                GALogger.D(requestId + " request. 400 - Bad Request.");
                return(EGAHTTPApiResponse.BadRequest);
            }

            if (responseCode == HttpStatusCode.InternalServerError)
            {
                GALogger.D(requestId + " request. 500 - Internal Server Error.");
                return(EGAHTTPApiResponse.InternalServerError);
            }

            return(EGAHTTPApiResponse.UnknownResponseCode);
        }
Ejemplo n.º 15
0
 private static void ValidateAndFixCurrentDimensions()
 {
     // validate that there are no current dimension01 not in list
     if (!GAValidator.ValidateDimension01(CurrentCustomDimension01))
     {
         GALogger.D("Invalid dimension01 found in variable. Setting to nil. Invalid dimension: " + CurrentCustomDimension01);
         SetCustomDimension01("");
     }
     // validate that there are no current dimension02 not in list
     if (!GAValidator.ValidateDimension02(CurrentCustomDimension02))
     {
         GALogger.D("Invalid dimension02 found in variable. Setting to nil. Invalid dimension: " + CurrentCustomDimension02);
         SetCustomDimension02("");
     }
     // validate that there are no current dimension03 not in list
     if (!GAValidator.ValidateDimension03(CurrentCustomDimension03))
     {
         GALogger.D("Invalid dimension03 found in variable. Setting to nil. Invalid dimension: " + CurrentCustomDimension03);
         SetCustomDimension03("");
     }
 }
Ejemplo n.º 16
0
#pragma warning disable 0162
        public static void ClearProgressionTries(string progression)
        {
            Dictionary <string, int> progressionTries = Instance.progressionTries;

            if (progressionTries.ContainsKey(progression))
            {
                progressionTries.Remove(progression);
            }

            if (GAStore.InMemory)
            {
                GALogger.D("Trying to ClearProgressionTries with InMemory=true - cannot. Skipping.");
            }
            else
            {
                // Delete
                Dictionary <string, object> parms = new Dictionary <string, object>();
                parms.Add("$progression", progression);
                GAStore.ExecuteQuerySync("DELETE FROM ga_progression WHERE progression = $progression;", parms);
            }
        }
Ejemplo n.º 17
0
        private static void FixMissingSessionEndEvents()
        {
            // Get all sessions that are not current
            Dictionary <string, object> parameters = new Dictionary <string, object>();

            parameters.Add("$session_id", GAState.SessionId);


            string    sql      = "SELECT timestamp, event FROM ga_session WHERE session_id != $session_id;";
            JSONArray sessions = GAStore.ExecuteQuerySync(sql, parameters);

            if (sessions == null)
            {
                return;
            }

            GALogger.I(sessions.Count + " session(s) located with missing session_end event.");

            // Add missing session_end events
            for (int i = 0; i < sessions.Count; ++i)
            {
                JSONNode session         = sessions[i];
                JSONNode sessionEndEvent = JSONNode.LoadFromBase64(session["event"].AsString);
                long     event_ts        = sessionEndEvent["client_ts"].AsLong;
                long     start_ts        = session["timestamp"].AsLong;

                long length = event_ts - start_ts;
                length = Math.Max(0, length);

                GALogger.D("fixMissingSessionEndEvents length calculated: " + length);

                sessionEndEvent["category"] = CategorySessionEnd;
                sessionEndEvent.Add("length", new JSONData(length));

                // Add to store
                AddEventToStore(sessionEndEvent.AsObject);
            }
        }
Ejemplo n.º 18
0
        private static void CacheIdentifier()
        {
            if (!string.IsNullOrEmpty(GAState.UserId))
            {
                GAState.Identifier = GAState.UserId;
            }
#if WINDOWS_UWP
            else if (!string.IsNullOrEmpty(GADevice.AdvertisingId))
            {
                GAState.Identifier = GADevice.AdvertisingId;
            }
            else if (!string.IsNullOrEmpty(GADevice.DeviceId))
            {
                GAState.Identifier = GADevice.DeviceId;
            }
#endif
            else if (!string.IsNullOrEmpty(Instance.DefaultUserId))
            {
                GAState.Identifier = Instance.DefaultUserId;
            }

            GALogger.D("identifier, {clean:" + GAState.Identifier + "}");
        }
Ejemplo n.º 19
0
        private static string GetOSVersionString()
        {
            string osVersion = SystemInfo.operatingSystem;

            GALogger.D("GetOSVersionString: " + osVersion);

            // Capture and process OS version information
            // For Windows
            Match regexResult = Regex.Match(osVersion, @"Windows.*?\((\d{0,5}\.\d{0,5}\.(\d{0,5}))\)");

            if (regexResult.Success)
            {
                string versionNumberString = regexResult.Groups[1].Value;
                string buildNumberString   = regexResult.Groups[2].Value;
                // Fix a bug in older versions of Unity where Windows 10 isn't recognised properly
                int buildNumber = 0;
                Int32.TryParse(buildNumberString, out buildNumber);
                if (buildNumber > 10000)
                {
                    versionNumberString = "10.0." + buildNumberString;
                }
                return("windows " + versionNumberString);
            }
            // For OS X
            regexResult = Regex.Match(osVersion, @"Mac OS X (\d{0,5}\.\d{0,5}\.\d{0,5})");
            if (regexResult.Success)
            {
                return("mac_osx " + regexResult.Captures[0].Value.Replace("Mac OS X ", ""));
            }
            regexResult = Regex.Match(osVersion, @"Mac OS X (\d{0,5}_\d{0,5}_\d{0,5})");
            if (regexResult.Success)
            {
                return("mac_osx " + regexResult.Captures[0].Value.Replace("Mac OS X ", "").Replace("_", "."));
            }
            // Not supporting other OS yet. The default version string won't be accepted by GameAnalytics
            return(UnityRuntimePlatformToString(Application.platform) + " 0.0.0");
        }
Ejemplo n.º 20
0
        public KeyValuePair <EGAHTTPApiResponse, JSONNode> SendEventsInArray(List <JSONNode> eventArray)
#endif
        {
            JSONNode json;

            if (eventArray.Count == 0)
            {
                GALogger.D("sendEventsInArray called with missing eventArray");
            }

            EGAHTTPApiResponse result  = EGAHTTPApiResponse.NoResponse;
            string             gameKey = GAState.GameKey;

            // Generate URL
            string url = baseUrl + "/" + gameKey + "/" + eventsUrlPath;

            GALogger.D("Sending 'events' URL: " + url);

            // make JSON string from data
            string JSONstring = GAUtilities.ArrayOfObjectsToJsonString(eventArray);

            if (JSONstring.Length == 0)
            {
                GALogger.D("sendEventsInArray JSON encoding failed of eventArray");
                json   = null;
                result = EGAHTTPApiResponse.JsonEncodeFailed;
                return(new KeyValuePair <EGAHTTPApiResponse, JSONNode>(result, json));
            }

            string         body                = "";
            HttpStatusCode responseCode        = (HttpStatusCode)0;
            string         responseDescription = "";
            string         authorization       = "";

            try
            {
                byte[]         payloadData = CreatePayloadData(JSONstring, useGzip);
                HttpWebRequest request     = CreateRequest(url, payloadData, useGzip);
                authorization = request.Headers[HttpRequestHeader.Authorization];
#if WINDOWS_UWP || WINDOWS_WSA
                using (Stream dataStream = await request.GetRequestStreamAsync())
#else
                using (Stream dataStream = request.GetRequestStream())
#endif
                {
                    dataStream.Write(payloadData, 0, payloadData.Length);
                }

#if WINDOWS_UWP || WINDOWS_WSA
                using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse)
#else
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
#endif
                {
                    using (Stream dataStream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(dataStream))
                        {
                            string responseString = reader.ReadToEnd();

                            responseCode        = response.StatusCode;
                            responseDescription = response.StatusDescription;

                            // print result
                            body = responseString;
                        }
                    }
                }
            }
            catch (WebException e)
            {
                if (e.Response != null)
                {
                    using (HttpWebResponse response = (HttpWebResponse)e.Response)
                    {
                        using (Stream streamResponse = response.GetResponseStream())
                        {
                            using (StreamReader streamRead = new StreamReader(streamResponse))
                            {
                                string responseString = streamRead.ReadToEnd();

                                responseCode        = response.StatusCode;
                                responseDescription = response.StatusDescription;

                                body = responseString;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                GALogger.E(e.ToString());
            }

            GALogger.D("events request content: " + body);

            EGAHTTPApiResponse requestResponseEnum = ProcessRequestResponse(responseCode, responseDescription, body, "Events");

            // if not 200 result
            if (requestResponseEnum != EGAHTTPApiResponse.Ok && requestResponseEnum != EGAHTTPApiResponse.BadRequest)
            {
                GALogger.D("Failed events Call. URL: " + url + ", Authorization: " + authorization + ", JSONString: " + JSONstring);
                json   = null;
                result = requestResponseEnum;
                return(new KeyValuePair <EGAHTTPApiResponse, JSONNode>(result, json));
            }

            // decode JSON
            JSONNode requestJsonDict = JSON.Parse(body);

            if (requestJsonDict == null)
            {
                json   = null;
                result = EGAHTTPApiResponse.JsonDecodeFailed;
                return(new KeyValuePair <EGAHTTPApiResponse, JSONNode>(result, json));
            }

            // print reason if bad request
            if (requestResponseEnum == EGAHTTPApiResponse.BadRequest)
            {
                GALogger.D("Failed Events Call. Bad request. Response: " + requestJsonDict.ToString());
            }

            // return response
            json   = requestJsonDict;
            result = requestResponseEnum;
            return(new KeyValuePair <EGAHTTPApiResponse, JSONNode>(result, json));
        }
Ejemplo n.º 21
0
        public KeyValuePair <EGAHTTPApiResponse, JSONClass> RequestInitReturningDict()
#endif
        {
            JSONClass          json;
            EGAHTTPApiResponse result  = EGAHTTPApiResponse.NoResponse;
            string             gameKey = GAState.GameKey;

            // Generate URL
            string url = baseUrl + "/" + gameKey + "/" + initializeUrlPath;

            GALogger.D("Sending 'init' URL: " + url);

            JSONClass initAnnotations = GAState.GetInitAnnotations();

            // make JSON string from data
            string JSONstring = initAnnotations.ToString();

            if (string.IsNullOrEmpty(JSONstring))
            {
                result = EGAHTTPApiResponse.JsonEncodeFailed;
                json   = null;
                return(new KeyValuePair <EGAHTTPApiResponse, JSONClass>(result, json));
            }

            string         body                = "";
            HttpStatusCode responseCode        = (HttpStatusCode)0;
            string         responseDescription = "";
            string         authorization       = "";

            try
            {
                byte[]         payloadData = CreatePayloadData(JSONstring, useGzip);
                HttpWebRequest request     = CreateRequest(url, payloadData, useGzip);
                authorization = request.Headers[HttpRequestHeader.Authorization];
#if WINDOWS_UWP || WINDOWS_WSA
                using (Stream dataStream = await request.GetRequestStreamAsync())
#else
                using (Stream dataStream = request.GetRequestStream())
#endif
                {
                    dataStream.Write(payloadData, 0, payloadData.Length);
                }

#if WINDOWS_UWP || WINDOWS_WSA
                using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse)
#else
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
#endif
                {
                    using (Stream dataStream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(dataStream))
                        {
                            string responseString = reader.ReadToEnd();

                            responseCode        = response.StatusCode;
                            responseDescription = response.StatusDescription;

                            // print result
                            body = responseString;
                        }
                    }
                }
            }
            catch (WebException e)
            {
                if (e.Response != null)
                {
                    using (HttpWebResponse response = (HttpWebResponse)e.Response)
                    {
                        using (Stream streamResponse = response.GetResponseStream())
                        {
                            using (StreamReader streamRead = new StreamReader(streamResponse))
                            {
                                string responseString = streamRead.ReadToEnd();

                                responseCode        = response.StatusCode;
                                responseDescription = response.StatusDescription;

                                body = responseString;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                GALogger.E(e.ToString());
            }

            // process the response
            GALogger.D("init request content : " + body);

            JSONNode           requestJsonDict     = JSON.Parse(body);
            EGAHTTPApiResponse requestResponseEnum = ProcessRequestResponse(responseCode, responseDescription, body, "Init");

            // if not 200 result
            if (requestResponseEnum != EGAHTTPApiResponse.Ok && requestResponseEnum != EGAHTTPApiResponse.BadRequest)
            {
                GALogger.D("Failed Init Call. URL: " + url + ", Authorization: " + authorization + ", JSONString: " + JSONstring);
                result = requestResponseEnum;
                json   = null;
                return(new KeyValuePair <EGAHTTPApiResponse, JSONClass>(result, json));
            }

            if (requestJsonDict == null)
            {
                GALogger.D("Failed Init Call. Json decoding failed");
                result = EGAHTTPApiResponse.JsonDecodeFailed;
                json   = null;
                return(new KeyValuePair <EGAHTTPApiResponse, JSONClass>(result, json));
            }

            // print reason if bad request
            if (requestResponseEnum == EGAHTTPApiResponse.BadRequest)
            {
                GALogger.D("Failed Init Call. Bad request. Response: " + requestJsonDict.AsObject.ToString());
                // return bad request result
                result = requestResponseEnum;
                json   = null;
                return(new KeyValuePair <EGAHTTPApiResponse, JSONClass>(result, json));
            }

            // validate Init call values
            JSONClass validatedInitValues = GAValidator.ValidateAndCleanInitRequestResponse(requestJsonDict);

            if (validatedInitValues == null)
            {
                result = EGAHTTPApiResponse.BadResponse;
                json   = null;
                return(new KeyValuePair <EGAHTTPApiResponse, JSONClass>(result, json));
            }

            // all ok
            result = EGAHTTPApiResponse.Ok;
            json   = validatedInitValues;
            return(new KeyValuePair <EGAHTTPApiResponse, JSONClass>(result, json));
        }
Ejemplo n.º 22
0
        public static bool EnsureDatabase(bool dropDatabase, string key)
        {
            // lazy creation of db path
            if (string.IsNullOrEmpty(Instance.dbPath))
            {
                // initialize db path
#pragma warning disable 0429
#if WINDOWS_UWP || WINDOWS_WSA
                Instance.dbPath = InMemory ? ":memory:" : Path.Combine(GADevice.WritablePath, "ga.sqlite3");
#else
                Instance.dbPath = InMemory ? ":memory:" : Path.Combine(Path.Combine(GADevice.WritablePath, key), "ga.sqlite3");

                if (!InMemory)
                {
                    string d = Path.Combine(GADevice.WritablePath, key);
                    if (!Directory.Exists(d))
                    {
                        Directory.CreateDirectory(d);
                    }
                }
#endif
#pragma warning restore 0429
                GALogger.D("Database path set to: " + Instance.dbPath);
            }

            // Open database
            try
            {
#if UNITY
                Instance.SqlDatabase = new SqliteConnection("URI=file:" + Instance.dbPath + ";Version=3");
#else
                Instance.SqlDatabase = new SqliteConnection(new SqliteConnectionStringBuilder
                {
                    DataSource = Instance.dbPath
                }.ConnectionString);
#endif

                Instance.SqlDatabase.Open();
                Instance.DbReady = true;
                GALogger.I("Database opened: " + Instance.dbPath);
            }
            catch (Exception e)
            {
                Instance.DbReady = false;
                GALogger.W("Could not open database: " + Instance.dbPath + " " + e);
                return(false);
            }

            if (dropDatabase)
            {
                GALogger.D("Drop tables");
                ExecuteQuerySync("DROP TABLE ga_events");
                ExecuteQuerySync("DROP TABLE ga_state");
                ExecuteQuerySync("DROP TABLE ga_session");
                ExecuteQuerySync("DROP TABLE ga_progression");
                ExecuteQuerySync("VACUUM");
            }

            // Create statements
            string sql_ga_events      = "CREATE TABLE IF NOT EXISTS ga_events(status CHAR(50) NOT NULL, category CHAR(50) NOT NULL, session_id CHAR(50) NOT NULL, client_ts CHAR(50) NOT NULL, event TEXT NOT NULL);";
            string sql_ga_session     = "CREATE TABLE IF NOT EXISTS ga_session(session_id CHAR(50) PRIMARY KEY NOT NULL, timestamp CHAR(50) NOT NULL, event TEXT NOT NULL);";
            string sql_ga_state       = "CREATE TABLE IF NOT EXISTS ga_state(key CHAR(255) PRIMARY KEY NOT NULL, value TEXT);";
            string sql_ga_progression = "CREATE TABLE IF NOT EXISTS ga_progression(progression CHAR(255) PRIMARY KEY NOT NULL, tries CHAR(255));";

            JSONArray results = ExecuteQuerySync(sql_ga_events);

            if (results == null)
            {
                return(false);
            }

            if (ExecuteQuerySync("SELECT status FROM ga_events LIMIT 0,1") == null)
            {
                GALogger.D("ga_events corrupt, recreating.");
                ExecuteQuerySync("DROP TABLE ga_events");
                results = ExecuteQuerySync(sql_ga_events);
                if (results == null)
                {
                    GALogger.W("ga_events corrupt, could not recreate it.");
                    return(false);
                }
            }

            results = ExecuteQuerySync(sql_ga_session);

            if (results == null)
            {
                return(false);
            }

            if (ExecuteQuerySync("SELECT session_id FROM ga_session LIMIT 0,1") == null)
            {
                GALogger.D("ga_session corrupt, recreating.");
                ExecuteQuerySync("DROP TABLE ga_session");
                results = ExecuteQuerySync(sql_ga_session);
                if (results == null)
                {
                    GALogger.W("ga_session corrupt, could not recreate it.");
                    return(false);
                }
            }

            results = ExecuteQuerySync(sql_ga_state);

            if (results == null)
            {
                return(false);
            }

            if (ExecuteQuerySync("SELECT key FROM ga_state LIMIT 0,1") == null)
            {
                GALogger.D("ga_state corrupt, recreating.");
                ExecuteQuerySync("DROP TABLE ga_state");
                results = ExecuteQuerySync(sql_ga_state);
                if (results == null)
                {
                    GALogger.W("ga_state corrupt, could not recreate it.");
                    return(false);
                }
            }

            results = ExecuteQuerySync(sql_ga_progression);

            if (results == null)
            {
                return(false);
            }

            if (ExecuteQuerySync("SELECT progression FROM ga_progression LIMIT 0,1") == null)
            {
                GALogger.D("ga_progression corrupt, recreating.");
                ExecuteQuerySync("DROP TABLE ga_progression");
                results = ExecuteQuerySync(sql_ga_progression);
                if (results == null)
                {
                    GALogger.W("ga_progression corrupt, could not recreate it.");
                    return(false);
                }
            }

            // All good
            TrimEventTable();

            IsTableReady = true;
            GALogger.D("Database tables ensured present");

            return(true);
        }
Ejemplo n.º 23
0
        private GAThreading()
        {
            GALogger.D("Initializing GA thread...");

            StartThread();
        }
Ejemplo n.º 24
0
#pragma warning disable 0162
        private static void EnsurePersistedStates()
        {
            if (GAStore.InMemory)
            {
#if UNITY
                GALogger.D("retrieving persisted states from local PlayerPrefs");

                GAState instance = GAState.Instance;

                instance.DefaultUserId = UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + SessionNumKey, Guid.NewGuid().ToString());
                {
                    int tmp;
                    int.TryParse(UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + SessionNumKey, "0"), out tmp);
                    SessionNum = tmp;
                }
                {
                    int tmp;
                    int.TryParse(UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + TransactionNumKey, "0"), out tmp);
                    TransactionNum = tmp;
                }
                if (!string.IsNullOrEmpty(instance.FacebookId))
                {
                    UnityEngine.PlayerPrefs.SetString(InMemoryPrefix + FacebookIdKey, instance.FacebookId);
                }
                else
                {
                    instance.FacebookId = UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + FacebookIdKey, "");
                }
                if (!string.IsNullOrEmpty(instance.Gender))
                {
                    UnityEngine.PlayerPrefs.SetString(InMemoryPrefix + GenderKey, instance.Gender);
                }
                else
                {
                    instance.Gender = UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + GenderKey, "");
                }
                if (instance.BirthYear != 0)
                {
                    UnityEngine.PlayerPrefs.SetString(InMemoryPrefix + BirthYearKey, instance.BirthYear.ToString());
                }
                else
                {
                    int tmp;
                    int.TryParse(UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + BirthYearKey, "0"), out tmp);
                    instance.BirthYear = tmp;
                }
                if (!string.IsNullOrEmpty(CurrentCustomDimension01))
                {
                    UnityEngine.PlayerPrefs.SetString(InMemoryPrefix + Dimension01Key, CurrentCustomDimension01);
                }
                else
                {
                    CurrentCustomDimension01 = UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + Dimension01Key, "");
                }
                if (!string.IsNullOrEmpty(CurrentCustomDimension02))
                {
                    UnityEngine.PlayerPrefs.SetString(InMemoryPrefix + Dimension02Key, CurrentCustomDimension02);
                }
                else
                {
                    CurrentCustomDimension02 = UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + Dimension02Key, "");
                }
                if (!string.IsNullOrEmpty(CurrentCustomDimension03))
                {
                    UnityEngine.PlayerPrefs.SetString(InMemoryPrefix + Dimension03Key, CurrentCustomDimension03);
                }
                else
                {
                    CurrentCustomDimension03 = UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + Dimension03Key, "");
                }

                string sdkConfigCachedString = UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + SdkConfigCachedKey, "");
                if (!string.IsNullOrEmpty(sdkConfigCachedString))
                {
                    // decode JSON
                    JSONNode sdkConfigCached = null;
                    try
                    {
                        sdkConfigCached = JSONNode.LoadFromBinaryBase64(sdkConfigCachedString);
                    }
                    catch (Exception)
                    {
                        //GALogger.E("EnsurePersistedStates: Error decoding json, " + e);
                    }

                    if (sdkConfigCached != null && sdkConfigCached.Count != 0)
                    {
                        instance.SdkConfigCached = sdkConfigCached;
                    }
                }
#else
                GALogger.W("EnsurePersistedStates: No implementation yet for InMemory=true");
#endif
            }
            else
            {
                // get and extract stored states
                JSONObject state_dict       = new JSONObject();
                JSONArray  results_ga_state = GAStore.ExecuteQuerySync("SELECT * FROM ga_state;");

                if (results_ga_state != null && results_ga_state.Count != 0)
                {
                    for (int i = 0; i < results_ga_state.Count; ++i)
                    {
                        JSONNode result = results_ga_state[i];
                        state_dict.Add(result["key"], result["value"]);
                    }
                }

                // insert into GAState instance
                GAState instance = GAState.Instance;

                instance.DefaultUserId = state_dict[DefaultUserIdKey] != null ? state_dict[DefaultUserIdKey].Value : Guid.NewGuid().ToString();

                SessionNum = state_dict[SessionNumKey] != null ? state_dict[SessionNumKey].AsInt : 0;

                TransactionNum = state_dict[TransactionNumKey] != null ? state_dict[TransactionNumKey].AsInt : 0;

                // restore cross session user values
                if (!string.IsNullOrEmpty(instance.FacebookId))
                {
                    GAStore.SetState(FacebookIdKey, instance.FacebookId);
                }
                else
                {
                    instance.FacebookId = state_dict[FacebookIdKey] != null ? state_dict[FacebookIdKey].Value : "";
                    if (!string.IsNullOrEmpty(instance.FacebookId))
                    {
                        GALogger.D("facebookid found in DB: " + instance.FacebookId);
                    }
                }

                if (!string.IsNullOrEmpty(instance.Gender))
                {
                    GAStore.SetState(GenderKey, instance.Gender);
                }
                else
                {
                    instance.Gender = state_dict[GenderKey] != null ? state_dict[GenderKey].Value : "";
                    if (!string.IsNullOrEmpty(instance.Gender))
                    {
                        GALogger.D("gender found in DB: " + instance.Gender);
                    }
                }

                if (instance.BirthYear != 0)
                {
                    GAStore.SetState(BirthYearKey, instance.BirthYear.ToString());
                }
                else
                {
                    instance.BirthYear = state_dict[BirthYearKey] != null ? state_dict[BirthYearKey].AsInt : 0;
                    if (instance.BirthYear != 0)
                    {
                        GALogger.D("birthYear found in DB: " + instance.BirthYear);
                    }
                }

                // restore dimension settings
                if (!string.IsNullOrEmpty(CurrentCustomDimension01))
                {
                    GAStore.SetState(Dimension01Key, CurrentCustomDimension01);
                }
                else
                {
                    CurrentCustomDimension01 = state_dict[Dimension01Key] != null ? state_dict[Dimension01Key].Value : "";
                    if (!string.IsNullOrEmpty(CurrentCustomDimension01))
                    {
                        GALogger.D("Dimension01 found in cache: " + CurrentCustomDimension01);
                    }
                }

                if (!string.IsNullOrEmpty(CurrentCustomDimension02))
                {
                    GAStore.SetState(Dimension02Key, CurrentCustomDimension02);
                }
                else
                {
                    CurrentCustomDimension02 = state_dict[Dimension02Key] != null ? state_dict[Dimension02Key].Value : "";
                    if (!string.IsNullOrEmpty(CurrentCustomDimension02))
                    {
                        GALogger.D("Dimension02 found in cache: " + CurrentCustomDimension02);
                    }
                }

                if (!string.IsNullOrEmpty(CurrentCustomDimension03))
                {
                    GAStore.SetState(Dimension03Key, CurrentCustomDimension03);
                }
                else
                {
                    CurrentCustomDimension03 = state_dict[Dimension03Key] != null ? state_dict[Dimension03Key].Value : "";
                    if (!string.IsNullOrEmpty(CurrentCustomDimension03))
                    {
                        GALogger.D("Dimension03 found in cache: " + CurrentCustomDimension03);
                    }
                }

                // get cached init call values
                string sdkConfigCachedString = state_dict[SdkConfigCachedKey] != null ? state_dict[SdkConfigCachedKey].Value : "";
                if (!string.IsNullOrEmpty(sdkConfigCachedString))
                {
                    // decode JSON
                    JSONNode sdkConfigCached = null;

                    try
                    {
                        sdkConfigCached = JSONNode.LoadFromBinaryBase64(sdkConfigCachedString);
                    }
                    catch (Exception)
                    {
                        //GALogger.E("EnsurePersistedStates: Error decoding json, " + e);
                    }

                    if (sdkConfigCached != null && sdkConfigCached.Count != 0)
                    {
                        instance.SdkConfigCached = sdkConfigCached;
                    }
                }

                JSONArray results_ga_progression = GAStore.ExecuteQuerySync("SELECT * FROM ga_progression;");

                if (results_ga_progression != null && results_ga_progression.Count != 0)
                {
                    for (int i = 0; i < results_ga_progression.Count; ++i)
                    {
                        JSONNode result = results_ga_progression[i];
                        if (result != null && result.Count != 0)
                        {
                            instance.progressionTries[result["progression"].Value] = result["tries"].AsInt;
                        }
                    }
                }
            }
        }
Ejemplo n.º 25
0
        protected void DoInBackground(string url)
#endif
        {
            if (!countMap.ContainsKey(this.type))
            {
                countMap.Add(this.type, 0);
            }

            if (countMap[this.type] >= MaxCount)
            {
                return;
            }

            HttpStatusCode responseCode        = (HttpStatusCode)0;
            string         responseDescription = "";

            try
            {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "POST";
#if WINDOWS_UWP || WINDOWS_WSA || WINDOWS_PHONE
                request.Headers[HttpRequestHeader.ContentLength] = this.payloadData.Length.ToString();
#else
                request.ContentLength = payloadData.Length;
#endif
                request.Headers[HttpRequestHeader.Authorization] = this.hashHmac;
                request.ContentType = "application/json";

#if WINDOWS_UWP || WINDOWS_WSA
                using (Stream dataStream = await request.GetRequestStreamAsync())
#elif WINDOWS_PHONE
                using (Stream dataStream = await Task.Factory.FromAsync <Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null))
#else
                using (Stream dataStream = request.GetRequestStream())
#endif
                {
                    dataStream.Write(this.payloadData, 0, payloadData.Length);
                }

#if WINDOWS_UWP || WINDOWS_WSA
                using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse)
#elif WINDOWS_PHONE
                using (WebResponse response = await Task.Factory.FromAsync <WebResponse>(request.BeginGetResponse, request.EndGetResponse, null))
#else
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
#endif
                {
                    using (Stream dataStream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(dataStream))
                        {
                            string responseString = reader.ReadToEnd();
                            body = responseString;
                        }
                    }
                }
            }
            catch (WebException e)
            {
                if (e.Response != null)
                {
                    using (HttpWebResponse response = (HttpWebResponse)e.Response)
                    {
                        using (Stream streamResponse = response.GetResponseStream())
                        {
                            using (StreamReader streamRead = new StreamReader(streamResponse))
                            {
                                string responseString = streamRead.ReadToEnd();

                                responseCode        = response.StatusCode;
                                responseDescription = response.StatusDescription;

                                body = responseString;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                GALogger.E(e.ToString());
            }

            // process the response
            GALogger.D("sdk error request content : " + body);

            OnPostExecute(responseCode, responseDescription);
        }
Ejemplo n.º 26
0
 public static void StopThread()
 {
     GALogger.D("StopThread called");
     shouldThreadrun = false;
 }