using DidabuCloud.Unity.Core; using DidabuCloud.Unity.Core.NetWorking; using Mogafa.App.LogEvents; using Mogafa.Common.HttpClients; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading.Tasks; namespace DidabuCloud.Unity.LogEvents { public class DidabuLogEventReporter : EventReporterAbstract { private readonly string url = "https://api.didabu.com/"; private readonly string sandboxUrl = "https://ll4tscl8ad.execute-api.cn-northwest-1.amazonaws.com.cn/Prod/"; private List waitingList = new List(); private readonly string logEventWaitingListKey = "DidabuLogEventWaitingListKey"; private readonly string cachedEventStorageKey = "DidabuCachedEvents"; private readonly Didabu didabu; private readonly List requiredParameters = new List(); private readonly List addedParameters = new List(); private readonly int waitingTime; private bool allParametersAdded = false; private List cachedEvents = new List(); private bool theFirstEvent = true; public DidabuLogEventReporter(Didabu didabu, List requiredParameters = null, int waitingTime = 30000) { this.didabu = didabu; this.requiredParameters = requiredParameters; this.waitingTime = waitingTime; if (this.requiredParameters == null) { this.requiredParameters = new List(); } if (!this.requiredParameters.Contains("isOrganic")) { this.requiredParameters.Add("isOrganic"); } if (!this.requiredParameters.Contains("mediaSource")) { this.requiredParameters.Add("mediaSource"); } if (!this.requiredParameters.Contains("adCampaign")) { this.requiredParameters.Add("adCampaign"); } if (!this.requiredParameters.Contains("adSet")) { this.requiredParameters.Add("adSet"); } didabu.OnInitialSuccessed += DidabuOnInitialSuccessed; didabu.OnGetConfigurationSuccessed += OnGetConfigurationSuccessed; GetCachedEvents().Wait(); } private void OnGetConfigurationSuccessed(DidabuCoreConfig config) { if (config != null && !string.IsNullOrEmpty(config.CountryCode)) { AddCommonEventParameter("countryCode", config.CountryCode); } } private void DidabuOnInitialSuccessed(string obj) { AddCommonEventParameter("deviceId", didabu.DeviceId); foreach (var eventDto in waitingList.Where(wl => string.IsNullOrEmpty(wl.AccountId))) { eventDto.AccountId = obj; } } public override string Name => "Didabu"; protected string BaseUrl { get { if (Didabu.Application.IsSandbox) { return sandboxUrl; } return url; } } protected string LogEventUrl { get { return BaseUrl + "logEvent/logEvent"; } } private async Task SaveWaitingList() { await LocalStorage.Set(logEventWaitingListKey, waitingList); } private async Task SaveCachedEvents() { await LocalStorage.Set(cachedEventStorageKey, cachedEvents); } private async Task GetCachedEvents() { cachedEvents = await LocalStorage.Get>(cachedEventStorageKey); if(cachedEvents == null) { cachedEvents = new List(); } } private async Task GetWaitingList() { waitingList = await LocalStorage.Get>(logEventWaitingListKey); if (waitingList == null) { waitingList = new List(); } } protected override void AfterAddCommonEventParameter(string eventParameterName, string value) { Logger.LogDebug($"After add common event parameter, parameter name:{eventParameterName}"); var mapName = MapName(eventParameterName, eventParameterNameMap); foreach (var cachedEvent in cachedEvents) { if (!cachedEvent.Parameters.ContainsKey(mapName)) { cachedEvent.Parameters.Add(mapName, value); } else { cachedEvent.Parameters[mapName] = value; } } if (allParametersAdded) { return; } if (requiredParameters.Contains(eventParameterName) && !addedParameters.Contains(eventParameterName)) { addedParameters.Add(eventParameterName); Logger.LogDebug($"Add required parameter, parameter name:{eventParameterName}"); } allParametersAdded = requiredParameters.Count == addedParameters.Count; if (allParametersAdded) { CachedEventsToWaitingList().Wait(); } } protected override async void AfterInitialize(List enabledEventNames, Dictionary eventNameMap, Dictionary eventParameterNameMap) { var devicePlatform = "Other"; if (UnityEngine.Application.platform == UnityEngine.RuntimePlatform.IPhonePlayer) { devicePlatform = "iOS"; } else if (UnityEngine.Application.platform == UnityEngine.RuntimePlatform.Android) { devicePlatform = "Android"; } AddCommonEventParameter("deviceModel", UnityEngine.SystemInfo.deviceModel); AddCommonEventParameter("deviceName", UnityEngine.SystemInfo.deviceName); AddCommonEventParameter("deviceType", UnityEngine.SystemInfo.deviceType.ToString()); AddCommonEventParameter("devicePlatform", devicePlatform); AddCommonEventParameter("batteryLevel", UnityEngine.SystemInfo.batteryLevel.ToString()); AddCommonEventParameter("batteryStatus", UnityEngine.SystemInfo.batteryStatus.ToString()); AddCommonEventParameter("systemMemorySize", UnityEngine.SystemInfo.systemMemorySize.ToString()); AddCommonEventParameter("graphicsMemorySize", UnityEngine.SystemInfo.graphicsMemorySize.ToString()); AddCommonEventParameter("deviceOs", UnityEngine.SystemInfo.operatingSystem); AddCommonEventParameter("bundleId", UnityEngine.Application.identifier); AddCommonEventParameter("wifi", UnityEngine.Application.internetReachability == UnityEngine.NetworkReachability.ReachableViaCarrierDataNetwork ? "true" : "false"); if (!string.IsNullOrEmpty(didabu.DeviceId)) { AddCommonEventParameter("deviceId", didabu.DeviceId); } if (didabu.Config != null && !string.IsNullOrEmpty(didabu.Config.CountryCode)) { AddCommonEventParameter("countryCode", didabu.Config.CountryCode); } //AddCommonEventParameter("osVersion", UnityEngine.SystemInfo); //AddCommonEventParameter("carrier", ""); AddCommonEventParameter("appVersion", UnityEngine.Application.version); AddCommonEventParameter("sdkVersion", didabu.Version); AddCommonEventParameter("language", UnityEngine.Application.systemLanguage.ToString()); AddCommonEventParameter("region", RegionInfo.CurrentRegion.EnglishName); await GetWaitingList(); Didabu.Application.AddTask(0, 15000, 0, ReportWaitingList); } private async Task CachedEventsToWaitingList() { foreach (var cachedEvent in cachedEvents) { var cachedLogEvent = new LogEventDto { AppId = Didabu.Application.AppId, AccountId = Didabu.Application.User.DidabuId, EventName = cachedEvent.EventName, ParametersJson = JsonConvert.SerializeObject(cachedEvent.Parameters), EventTime = cachedEvent.EventTime, LocalTime = cachedEvent.LocalTime, Id = Guid.NewGuid().ToString() }; waitingList.Add(cachedLogEvent); Logger.LogInformation($"Add cached event to waiting list, event name:{cachedEvent.EventName}"); } await SaveWaitingList(); if (cachedEvents.Count != 0) { cachedEvents.Clear(); await SaveCachedEvents(); } allParametersAdded = true; } protected override async Task LogEventInternal(string name, Dictionary eventParameters) { if (eventParameters == null) { eventParameters = new Dictionary(); } if (theFirstEvent) { Didabu.Application.AddTask(waitingTime, waitingTime, 1, CachedEventsToWaitingList); theFirstEvent = false; } if (!allParametersAdded) { Logger.LogInformation($"Add event to cached, event name:{name}"); cachedEvents.Add(new CachedEvent { EventName = name, Parameters = eventParameters, EventTime = Didabu.Application.RemoteUtcTimestamp, LocalTime = Didabu.Application.LocalTimestamp }); await SaveCachedEvents(); return; } await CachedEventsToWaitingList(); var parametersJson = JsonConvert.SerializeObject(eventParameters); var logEvent = new LogEventDto { AppId = Didabu.Application.AppId, AccountId = Didabu.Application.User.DidabuId, EventName = name, ParametersJson = parametersJson, EventTime = Didabu.Application.RemoteUtcTimestamp, LocalTime = Didabu.Application.LocalTimestamp, Id = Guid.NewGuid().ToString() }; waitingList.Add(logEvent); await SaveWaitingList(); } internal async Task ReportWaitingList() { if (waitingList != null && waitingList.Count > 0) { Logger.LogInformation($"Have new events, retry to report."); if (!string.IsNullOrEmpty(Didabu.Application.User.DidabuId)) { foreach (var eventDto in waitingList.Where(wl => string.IsNullOrEmpty(wl.AccountId))) { eventDto.AccountId = Didabu.Application.User.DidabuId; } } var cloneWaitingList = new List(waitingList.Where(wl => !string.IsNullOrEmpty(wl.AccountId))); if (cloneWaitingList.Count == 0) { return; } try { Logger.LogDebug($"Log event to Didabu, events:{JsonConvert.SerializeObject(cloneWaitingList)}"); var result = await HttpUtility.Post>(LogEventUrl, JsonConvert.SerializeObject(cloneWaitingList)); if (result.Code == HttpStatusCodes.OK && result.IsSuccessful) { foreach (var dto in cloneWaitingList) { if (!result.Data.Contains(dto.Id)) { waitingList.Remove(dto); } else { Logger.LogError($"Log event to Didabu failed, event name:{dto.EventName}"); } } await SaveWaitingList(); } else { Logger.LogError($"Log event error, code:{result.Code}, message:{result.Message}"); } } catch (Exception ex) { Logger.LogError($"Log event error:{ex.Message}"); } } } } public class EventParameterNames { public const string IsOrganic = "isOrganic"; public const string MediaSource = "mediaSource"; public const string AdCampaign = "adCampaign"; public const string AdSet = "adSet"; public const string AbGroups = "abGroups"; } }