示例#1
0
        /// <summary>
        /// SwrveProfileManager is a class that is reponsable to load from cache and manage any info related with a SwrveUser.
        /// </summary>
        public SwrveProfileManager(SwrveInitMode initMode)
        {
            // Get User UUID from PlayerPrefs
            userId = PlayerPrefs.GetString(SwrveUserIdKey, null);
            if (initMode == SwrveInitMode.AUTO && string.IsNullOrEmpty(userId))
            {
                PrepareAndSetUserId(userId);
            }

            if (string.IsNullOrEmpty(userId))
            {
                SwrveLog.Log("The userId is not currently set");
            }
            else
            {
                SwrveLog.Log("Your current user id is: " + userId);
            }
        }
示例#2
0
 public void UserUpdate(string userUpdate)
 {
     try
     {
         Dictionary <string, object>             dictionary  = (Dictionary <string, object>)Json.Deserialize(userUpdate);
         Dictionary <string, string>             dictionary2 = new Dictionary <string, string>();
         Dictionary <string, object> .Enumerator enumerator  = dictionary.GetEnumerator();
         while (enumerator.MoveNext())
         {
             dictionary2[enumerator.Current.Key] = $"{enumerator.Current.Value}";
         }
         SDK.UserUpdate(dictionary2);
     }
     catch (Exception ex)
     {
         SwrveLog.LogError(ex.ToString(), "userUpdate");
     }
 }
        /// <summary>
        /// Notify that the message was shown to the user. This function
        /// has to be called only once when the message is displayed to
        /// the user.
        /// This is automatically called by the SDK and will only need
        /// to be manually called if you are implementing your own
        /// in-app message rendering code.
        /// </summary>
        public void MessageWasShownToUser(SwrveMessageFormat messageFormat)
        {
            base.WasShownToUser();

            if (Messages.Count > 0)
            {
                if (!RandomOrder)
                {
                    int nextMessage = (Next + 1) % Messages.Count;
                    Next = nextMessage;
                    SwrveLog.Log("Round Robin: Next message in campaign " + Id + " is " + nextMessage);
                }
                else
                {
                    SwrveLog.Log("Next message in campaign " + Id + " is random");
                }
            }
        }
示例#4
0
 public static IEnumerable <SwrveTrigger> LoadFromJson(List <object> triggers)
 {
     try
     {
         if (SwrveTrigger.< > f__mg$cache0 == null)
         {
             SwrveTrigger.< > f__mg$cache0 = new Func <object, SwrveTrigger>(SwrveTrigger.LoadFromJson);
         }
         return(from dict in triggers.Select(SwrveTrigger.< > f__mg$cache0)
                where dict != null
                select dict);
     }
     catch (Exception arg)
     {
         SwrveLog.LogError(string.Format("Error creating a list of SwrveTriggers, ex: {0}", arg));
     }
     return(null);
 }
示例#5
0
        public void TriggerFailure(string eventName, string globalReason)
        {
            try {
                if (CanMakeTriggerRequest())
                {
                    string endpoint = getEndpoint("talk/game/" + swrve.ApiKey + "/user/" + swrve.UserId + "/trigger");
                    Dictionary <string, object> triggerJson = new Dictionary <string, object> ();
                    triggerJson.Add("trigger_name", eventName);
                    triggerJson.Add("displayed", false);
                    triggerJson.Add("reason", globalReason);
                    triggerJson.Add("campaigns", new List <object> ());

                    MakeRequest(endpoint, triggerJson);
                }
            } catch (Exception exp) {
                SwrveLog.LogError("QA request talk session failed: " + exp.ToString());
            }
        }
        public virtual void Save(string tag, string data, string userId = null)
        {
            bool saved = false;

            try {
                string prefPath = tag + ((userId == null) ? string.Empty : userId);
                SwrveLog.Log("Setting " + prefPath + " in PlayerPrefs", "storage");
                PlayerPrefs.SetString(prefPath, data);
                saved = true;
            } catch (PlayerPrefsException ppe) {
                SwrveLog.LogError(ppe.ToString(), "storage");
            }

            if (!saved)
            {
                SwrveLog.LogWarning(tag + " not saved!", "storage");
            }
        }
示例#7
0
        /// <summary>
        /// Search for a message related to the given trigger event at the given
        /// time. This function will return null if too many messages were dismissed,
        /// the campaign start is in the future, the campaign end is in the past or
        /// the given event is not contained in the trigger set.
        /// </summary>
        /// <param name="triggerEvent">
        /// Event triggered. Must be a trigger for the campaign.
        /// </param>
        /// <param name="campaignReasons">
        /// At the exit of the function will include the reasons why a campaign the campaigns
        /// in memory were not shown or chosen.
        /// </param>
        /// <returns>
        /// In-app message that contains the given event in its trigger list and satisfies all the
        /// rules.
        /// </returns>
        public SwrveMessage GetMessageForEvent(string triggerEvent, IDictionary <string, string> payload, SwrveQAUser qaUser)
        {
            int messagesCount = Messages.Count;

            if (messagesCount == 0)
            {
                LogAndAddReason("No messages in campaign " + Id, qaUser);
                return(null);
            }

            if (checkCampaignLimits(triggerEvent, payload, qaUser))
            {
                SwrveLog.Log(string.Format("[{0}] {1} matches a trigger in {2}", this, triggerEvent, Id));

                return(GetNextMessage(messagesCount, qaUser));
            }
            return(null);
        }
 public SwrveConversation GetConversationForEvent(string triggerEvent, IDictionary <string, string> payload, SwrveQAUser qaUser)
 {
     if (null == Conversation)
     {
         LogAndAddReason("No conversation in campaign " + Id, qaUser);
         return(null);
     }
     if (CheckCampaignLimits(triggerEvent, payload, qaUser))
     {
         SwrveLog.Log($"[{this}] {triggerEvent} matches a trigger in {Id}");
         if (AreAssetsReady())
         {
             return(Conversation);
         }
         LogAndAddReason("Assets not downloaded to show conversation in campaign " + Id, qaUser);
     }
     return(null);
 }
示例#9
0
    private void setNativeInfo(Dictionary <string, string> deviceInfo)
    {
        if (!string.IsNullOrEmpty(iOSdeviceToken))
        {
            deviceInfo["swrve.ios_token"] = iOSdeviceToken;
        }

        try {
            deviceInfo ["swrve.timezone_name"] = _swrveiOSGetTimeZone();
        } catch (Exception e) {
            SwrveLog.LogWarning("Couldn't get device timezone on iOS, make sure you have the plugin inside your project and you are running on a device: " + e.ToString());
        }

        try {
            deviceInfo ["swrve.device_region"] = _swrveiOSLocaleCountry();
        } catch (Exception e) {
            SwrveLog.LogWarning("Couldn't get device region on iOS, make sure you have the plugin inside your project and you are running on a device: " + e.ToString());
        }

        if (config.LogAppleIDFV)
        {
            try {
                String idfv = _swrveiOSIDFV();
                if (!string.IsNullOrEmpty(idfv))
                {
                    deviceInfo ["swrve.IDFV"] = idfv;
                }
            } catch (Exception e) {
                SwrveLog.LogWarning("Couldn't get device IDFV, make sure you have the plugin inside your project and you are running on a device: " + e.ToString());
            }
        }
        if (config.LogAppleIDFA)
        {
            try {
                String idfa = _swrveiOSIDFA();
                if (!string.IsNullOrEmpty(idfa))
                {
                    deviceInfo ["swrve.IDFA"] = idfa;
                }
            } catch (Exception e) {
                SwrveLog.LogWarning("Couldn't get device IDFA, make sure you have the plugin inside your project and you are running on a device: " + e.ToString());
            }
        }
    }
示例#10
0
    public static void SetPlotConfigKey(string platform, string writePath = null)
    {
        platform = platform.ToLower();

        string readPath = null;

        if ("android" == platform)
        {
            readPath = "Assets/Plugins/Android/SwrveLocationSDK/assets";
        }
        else if ("ios" == platform)
        {
            readPath = "Assets/Plugins/iOS/SwrveLocationSDK";
        }
        else
        {
            SwrveLog.Log(string.Format("{0} is an unknown platform, returning", platform));
            return;
        }
        if (!Directory.Exists(readPath))
        {
            return;
        }
        readPath = Path.Combine(readPath, "plotconfig.json");

        string plotToken = SwrveBuildComponent.GetPostProcessString(SwrveBuildComponent.PLOT_TOKEN_KEY);

        if (string.IsNullOrEmpty(plotToken))
        {
            SwrveLog.Log(string.Format("No plot token set in postprocess file, not adding plotconfig.json for {0}", platform));
            return;
        }

        if (string.IsNullOrEmpty(writePath))
        {
            writePath = readPath;
        }

        Dictionary <string, object> plotconfig =
            (Dictionary <string, object>)Json.Deserialize(File.ReadAllText(readPath));

        plotconfig[PLOT_PUBLIC_TOKEN_KEY] = plotToken;
        File.WriteAllText(writePath, Json.Serialize(plotconfig));
    }
示例#11
0
 public static WwwDeducedError DeduceWwwError(UnityWebRequest request)
 {
     if (request.isNetworkError)
     {
         SwrveLog.LogError("Request network error: " + request.error + " in " + request.url);
         return(WwwDeducedError.NetworkError);
     }
     if (request.GetResponseHeaders() != null)
     {
         string value = null;
         Dictionary <string, string> .Enumerator enumerator = request.GetResponseHeaders().GetEnumerator();
         while (enumerator.MoveNext())
         {
             string key = enumerator.Current.Key;
             if (string.Equals(key, "X-Swrve-Error", StringComparison.OrdinalIgnoreCase))
             {
                 request.GetResponseHeaders().TryGetValue(key, out value);
                 break;
             }
         }
         if (value != null)
         {
             SwrveLog.LogError("Request response headers [\"X-Swrve-Error\"]: " + value + " at " + request.url);
             try
             {
                 if (!string.IsNullOrEmpty(request.downloadHandler.text))
                 {
                     SwrveLog.LogError("Request response headers [\"X-Swrve-Error\"]: " + ((IDictionary <string, object>)Json.Deserialize(request.downloadHandler.text))["message"]);
                 }
             }
             catch (Exception ex)
             {
                 SwrveLog.LogError(ex.Message);
             }
             return(WwwDeducedError.ApplicationErrorHeader);
         }
     }
     if (!string.IsNullOrEmpty(request.error))
     {
         SwrveLog.LogError("Request network error: " + request.error + " in " + request.url);
         return(WwwDeducedError.NetworkError);
     }
     return(WwwDeducedError.NoError);
 }
        /// <summary>
        /// Search for a message related to the given trigger event at the given
        /// time. This function will return null if too many messages were dismissed,
        /// the campaign start is in the future, the campaign end is in the past or
        /// the given event is not contained in the trigger set.
        /// </summary>
        /// <param name="triggerEvent">
        /// Event triggered. Must be a trigger for the campaign.
        /// </param>
        /// <param name="campaignReasons">
        /// At the exit of the function will include the reasons why a campaign the campaigns
        /// in memory were not shown or chosen.
        /// </param>
        /// <returns>
        /// In-app message that contains the given event in its trigger list and satisfies all the
        /// rules.
        /// </returns>
        public SwrveMessage GetMessageForEvent(string triggerEvent, IDictionary <string, string> payload, List <SwrveQaUserCampaignInfo> qaCampaignInfoList)
        {
            int messagesCount = Messages.Count;

            if (messagesCount == 0)
            {
                string reason = "No messages in campaign " + Id;
                LogAndAddReason(reason, false, qaCampaignInfoList);
                return(null);
            }

            if (CheckCampaignLimits(triggerEvent, payload, qaCampaignInfoList))
            {
                SwrveLog.Log(string.Format("[{0}] {1} matches a trigger in {2}", this, triggerEvent, Id));

                return(GetNextMessage(messagesCount, qaCampaignInfoList));
            }
            return(null);
        }
示例#13
0
        public virtual string Load(string tag, string userId = null)
        {
            string result = null;

            try
            {
                string key = tag + ((userId != null) ? userId : string.Empty);
                if (PlayerPrefs.HasKey(key))
                {
                    SwrveLog.Log("Got " + tag + " from PlayerPrefs", "storage");
                    result = PlayerPrefs.GetString(key);
                }
            }
            catch (PlayerPrefsException ex)
            {
                SwrveLog.LogError(ex.ToString(), "storage");
            }
            return(result);
        }
    private void setNativeInfo(Dictionary <string, string> deviceInfo)
    {
        if (!string.IsNullOrEmpty(gcmDeviceToken))
        {
            deviceInfo["swrve.gcm_token"] = gcmDeviceToken;
        }

        if (!string.IsNullOrEmpty(admDeviceToken))
        {
            deviceInfo["swrve.adm_token"] = admDeviceToken;
        }

        string timezone = AndroidGetTimezone();

        if (!string.IsNullOrEmpty(timezone))
        {
            deviceInfo ["swrve.timezone_name"] = timezone;
        }

        string deviceRegion = AndroidGetRegion();

        if (!string.IsNullOrEmpty(deviceRegion))
        {
            deviceInfo ["swrve.device_region"] = deviceRegion;
        }

        if (config.LogAndroidId)
        {
            try {
                deviceInfo ["swrve.android_id"] = AndroidGetAndroidId();
            } catch (Exception e) {
                SwrveLog.LogWarning("Couldn't get device IDFA, make sure you have the plugin inside your project and you are running on a device: " + e.ToString());
            }
        }

        if (config.LogGoogleAdvertisingId)
        {
            if (!string.IsNullOrEmpty(googlePlayAdvertisingId))
            {
                deviceInfo ["swrve.GAID"] = googlePlayAdvertisingId;
            }
        }
    }
    private string AndroidGetAppVersion()
    {
        if (SwrveHelper.IsOnDevice())
        {
            try {
                using (AndroidJavaClass unityPlayerClass = new AndroidJavaClass(UnityPlayerName)) {
                    AndroidJavaObject context     = unityPlayerClass.GetStatic <AndroidJavaObject> (UnityCurrentActivityName);
                    string            packageName = context.Call <string> ("getPackageName");
                    string            versionName = context.Call <AndroidJavaObject> ("getPackageManager")
                                                    .Call <AndroidJavaObject> ("getPackageInfo", packageName, 0).Get <string> ("versionName");
                    return(versionName);
                }
            } catch (Exception exp) {
                SwrveLog.LogWarning("Couldn't get the device app version, make sure you are running on an Android device: " + exp.ToString());
            }
        }

        return(null);
    }
示例#16
0
 protected bool _CheckArguments(string name, long quantity, string type)
 {
     if (string.IsNullOrEmpty(name))
     {
         SwrveLog.LogError("IapRewards illegal argument: reward name cannot be empty");
         return(false);
     }
     if (quantity <= 0)
     {
         SwrveLog.LogError("IapRewards illegal argument: reward amount must be greater than zero");
         return(false);
     }
     if (string.IsNullOrEmpty(type))
     {
         SwrveLog.LogError("IapRewards illegal argument: type cannot be empty");
         return(false);
     }
     return(true);
 }
示例#17
0
        public IEnumerator DownloadAnyMissingAssets(Action callBack)
        {
            if (MissingAssetsQueue.Count > 0)
            {
                // Make a copy of the current MissingAssetsQueue so it can processed in the coroutine safely
                HashSet <SwrveAssetsQueueItem> currentMissingQueue = new HashSet <SwrveAssetsQueueItem>();
                currentMissingQueue.UnionWith(MissingAssetsQueue);
                MissingAssetsQueue.Clear();
                SwrveLog.Log("There were " + currentMissingQueue.Count + " Assets not yet downloaded. Retrieving them now...");
                yield return(StartTask("SwrveAssetsManager.DownloadAssetQueue", DownloadAssetQueue(currentMissingQueue)));

                if (callBack != null)
                {
                    callBack.Invoke();
                }
            }

            TaskFinished("SwrveAssetsManager.DownloadMissingAssets");
        }
示例#18
0
 public void UpdateDeviceInfo()
 {
     try {
         if (CanMakeRequest())
         {
             String endpoint = getEndpoint("talk/game/" + swrve.ApiKey + "/user/" + swrve.UserId + "/device_info");
             Dictionary <string, object>             deviceJson     = new Dictionary <string, object> ();
             Dictionary <string, string>             deviceData     = swrve.GetDeviceInfo();
             Dictionary <string, string> .Enumerator deviceDataEnum = deviceData.GetEnumerator();
             while (deviceDataEnum.MoveNext())
             {
                 deviceJson.Add(deviceDataEnum.Current.Key, deviceDataEnum.Current.Value);
             }
             MakeRequest(endpoint, deviceJson);
         }
     } catch (Exception exp) {
         SwrveLog.LogError("QA request talk device info update failed: " + exp.ToString());
     }
 }
示例#19
0
        public static string GetRandomUUID()
        {
#if UNITY_IPHONE
            string randomUUID = getNativeRandomUUID();
            if (!string.IsNullOrEmpty(randomUUID))
            {
                return(randomUUID);
            }
#endif
            try {
                Type type = System.Type.GetType("System.Guid");
                if (type != null)
                {
                    MethodInfo methodInfo = type.GetMethod("NewGuid");
                    if (methodInfo != null)
                    {
                        object result = methodInfo.Invoke(null, null);
                        if (result != null)
                        {
                            string stringResult = result.ToString();
                            if (!string.IsNullOrEmpty(stringResult))
                            {
                                return(stringResult);
                            }
                        }
                    }
                }
            } catch (Exception exp) {
                SwrveLog.LogWarning("Couldn't get random UUID: " + exp.ToString());
            }

            // Generate random string if all fails
            string chars        = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            string randomString = string.Empty;
            for (int i = 0; i < 128; i++)
            {
                System.Random rnd    = new System.Random();
                int           rndInt = rnd.Next(chars.Length);
                randomString += chars[rndInt];
            }
            return(randomString);
        }
示例#20
0
        protected void ProcessResponse(UnityWebRequest www, long wwwTime, string url, Action <RESTResponse> listener)
        {
#if SWRVE_SUPPORTED_PLATFORM
            try {
                if (!www.isNetworkError)
                {
                    // - made it there and it was ok
                    string responseBody = null;
                    bool   success      = ResponseBodyTester.TestUTF8(www.downloadHandler.data, out responseBody);
                    Dictionary <string, string> headers = new Dictionary <string, string> ();

                    if (www.GetResponseHeaders() != null)
                    {
                        Dictionary <string, string> .Enumerator headersEnum = www.GetResponseHeaders().GetEnumerator();
                        while (headersEnum.MoveNext())
                        {
                            KeyValuePair <string, string> header = headersEnum.Current;
                            headers.Add(header.Key.ToUpper(), header.Value);
                        }
                    }

                    if (success)
                    {
                        AddMetrics(url, wwwTime, false);
                        listener.Invoke(new RESTResponse(error: UnityWwwHelper.DeduceWwwError(www), responseCode: www.responseCode, responseBody: responseBody, headers: headers));
                    }
                    else
                    {
                        AddMetrics(url, wwwTime, true);
                        listener.Invoke(new RESTResponse(error: WwwDeducedError.ApplicationErrorBody, responseCode: www.responseCode, responseBody: responseBody, headers: headers));
                    }
                }
                else
                {
                    AddMetrics(url, wwwTime, true);
                    listener.Invoke(new RESTResponse(error: UnityWwwHelper.DeduceWwwError(www)));
                }
            } catch (Exception exp) {
                SwrveLog.LogError(exp);
            }
#endif
        }
示例#21
0
        public virtual void Save(string tag, string data, string userId = null)
        {
            bool flag = false;

            try
            {
                string text = tag + ((userId != null) ? userId : string.Empty);
                SwrveLog.Log("Setting " + text + " in PlayerPrefs", "storage");
                PlayerPrefs.SetString(text, data);
                flag = true;
            }
            catch (PlayerPrefsException ex)
            {
                SwrveLog.LogError(ex.ToString(), "storage");
            }
            if (!flag)
            {
                SwrveLog.LogWarning(tag + " not saved!", "storage");
            }
        }
示例#22
0
        private void MakeRequest(string qaEventsStringJson)
        {
            if (qaEventsStringJson == null)
            {
                return;
            }

            byte[] qaPostEncodedData = null;
            qaPostEncodedData = PostBodyBuilder.BuildQaEvent(apiKey, appId, userId, this.deviceUUID, appVersion, SwrveHelper.GetMilliseconds(), qaEventsStringJson);

            Dictionary <string, string> requestHeaders = new Dictionary <string, string> {
                { @"Content-Type", @"application/json; charset=utf-8" }
            };

            if (qaPostEncodedData != null)
            {
                container.StartCoroutine(restClient.Post(endPoint, qaPostEncodedData, requestHeaders, RestListener));
                SwrveLog.LogInfo("Swrve: SwrveQa Json Event sent:" + qaEventsStringJson);
            }
        }
示例#23
0
    public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
    {
        try {
            if (target == BuildTarget.iOS)
            {
                SwrveLog.Log("SwrveIOSPostProcess");
                CorrectXCodeProject(pathToBuiltProject, true);
                SilentPushNotifications(pathToBuiltProject);
                PermissionsDelegateSupport(pathToBuiltProject);
            }
        } catch (Exception exp) {
            UnityEngine.Debug.LogError("Swrve could not post process the iOS build: " + exp);
#if UNITY_2018_2_OR_NEWER
            if (Application.isBatchMode)
            {
                EditorApplication.Exit(1);
            }
#endif
        }
    }
示例#24
0
        protected static void AssignCampaignTriggers(SwrveBaseCampaign campaign, Dictionary <string, object> campaignData)
        {
            IList <object> list  = (IList <object>)campaignData["triggers"];
            int            i     = 0;
            int            count = list.Count;

            while (i < count)
            {
                object obj = list[i];
                if (obj.GetType() == typeof(string))
                {
                    obj = new Dictionary <string, object>
                    {
                        {
                            "event_name",
                            obj
                        },
                        {
                            "conditions",
                            new Dictionary <string, object>()
                        }
                    };
                }
                try
                {
                    SwrveTrigger item = SwrveTrigger.LoadFromJson((IDictionary <string, object>)obj);
                    campaign.GetTriggers().Add(item);
                }
                catch (Exception ex)
                {
                    SwrveLog.LogError(string.Concat(new object[]
                    {
                        "Unable to parse SwrveTrigger from json ",
                        Json.Serialize(obj),
                        ", ",
                        ex
                    }));
                }
                i++;
            }
        }
示例#25
0
        public static void CampaignButtonClicked(int campaignId, int variantId, string buttonName, string actionType, string actionValue)
        {
            if (!CanLog())
            {
                return;
            }

            try {
                Dictionary <string, object> logDetails = new Dictionary <string, object>();
                logDetails.Add("campaign_id", campaignId);
                logDetails.Add("variant_id", variantId);
                logDetails.Add("button_name", buttonName);
                logDetails.Add("action_type", actionType);
                logDetails.Add("action_value", actionValue);

                SwrveQaUser qaUser = SwrveQaUser.Instance;
                qaUser.QueueQaLogEvent("campaign-button-clicked", logDetails);
            } catch (Exception ex) {
                SwrveLog.LogError("SwrveQaUser: CampaignButtonClicked exception:" + ex.ToString());
            }
        }
示例#26
0
 /// <summary>
 /// Buffer the event of a purchase using real currency, where any in-app
 /// currencies were purchased, or where multiple items were purchased as part of a bundle.
 /// The receipt provided will be validated against the iTunes Store.
 /// </summary>
 /// <remarks>
 /// See the REST API documentation for the "iap" event.
 /// Note that this method is currently only supported for the Apple App Store,
 /// and a valid receipt needs to be provided for verification.
 /// </remarks>
 /// <param name="quantity">
 /// Quantity purchased.
 /// </param>
 /// <param name="productId">
 /// Unique product identifier for the item bought. This should match the Swrve resource name.
 /// </param>
 /// <param name="productPrice">
 /// Price of the product purchased in real money. Note that this is the price
 /// per product, not the total price of the transaction (when quantity > 1).
 /// </param>
 /// <param name="currency">
 /// Real world currency used for this transaction. This must be an ISO currency code.
 /// </param>
 /// <param name="rewards">
 /// SwrveIAPRewards object containing any in-app currency and/or additional items
 /// included in this purchase that need to be recorded.
 /// This parameter is optional.
 /// </param>
 /// <param name="receipt">
 /// The receipt sent back from the iTunes Store upon successful purchase - this receipt will be verified by Swrve.
 /// Use either Base64EncodedReceipt or RawReceipt depending on what is offered by your plugin.
 /// </param>
 /// <param name="transactionId">
 /// The transaction id identifying the purchase iOS7+ (see SKPaymentTransaction::transactionIdentifier).
 /// </param>
 public void IapApple(int quantity, string productId, double productPrice, string currency, IapRewards rewards, IapReceipt receipt, string transactionId)
 {
     if (config.AppStore != "apple")
     {
         throw new Exception("This function can only be called to validate IAP events from Apple");
     }
     else
     {
         string encodedReceipt = null;
         if (receipt != null)
         {
             encodedReceipt = receipt.GetBase64EncodedReceipt();
         }
         if (String.IsNullOrEmpty(encodedReceipt))
         {
             SwrveLog.LogError("IAP event not sent: receipt cannot be empty for Apple Store verification");
             return;
         }
         _Iap(quantity, productId, productPrice, currency, rewards, encodedReceipt, string.Empty, transactionId, config.AppStore);
     }
 }
        public virtual string Load(string tag, string userId = null)
        {
            string result = null;

            try {
                // Read from file
                string loadFileName = GetFileName(tag, userId);
                if (CrossPlatformFile.Exists(loadFileName))
                {
                    result = CrossPlatformFile.LoadText(loadFileName);
                }
                else
                {
                    // Skipping file load, doesn't exist
                }
            } catch (Exception e) {
                SwrveLog.LogError(e.ToString(), "storage");
            }

            return(result);
        }
示例#28
0
 public virtual void Remove(string tag, string userId = null)
 {
     try
     {
         string fileName = GetFileName(tag, userId);
         if (CrossPlatformFile.Exists(fileName))
         {
             SwrveLog.Log("Removing: " + fileName, "storage");
             CrossPlatformFile.Delete(fileName);
         }
         string path = fileName + "_SGT";
         if (CrossPlatformFile.Exists(path))
         {
             CrossPlatformFile.Delete(path);
         }
     }
     catch (Exception ex)
     {
         SwrveLog.LogError(ex.ToString(), "storage");
     }
 }
        public static void ShowConversation(ISwrveCommon sdk, object conversationJson)
        {
            if (conversationJson is string)
            {
                conversationJson = JsonObject.Parse((string)conversationJson);
            }
            else if (!(conversationJson is JsonObject))
            {
                SwrveLog.e(string.Format("Unable to handle object of type {0} for ShowConversation", (conversationJson == null ? "null" : "" + conversationJson.GetType())));
                return;
            }

            string os = AnalyticsInfo.VersionInfo.DeviceFamily.ToLower();
            SwrveConversationUI conversationUI = new SwrveConversationUI(sdk, os.Contains("desktop"));

            SwrveConversation conversation = new SwrveConversation(new SwrveConversationCampaign(), (JsonObject)conversationJson);

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            conversationUI.PresentConversation(sdk, conversation);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
        }
示例#30
0
        /// <summary>
        /// Load an in-app campaign from a JSON response.
        /// </summary>
        /// <param name="campaignData">
        /// JSON object with the individual campaign data.
        /// </param>
        /// <param name="initialisedTime">
        /// Time that the SDK was initialised. Used for rules checking.
        /// </param>
        /// <param name="assetPath">
        /// Path to the folder that will store all the assets.
        /// </param>
        /// <returns>
        /// Parsed in-app campaign.
        /// </returns>
        public static SwrveBaseCampaign LoadFromJSON(SwrveSDK sdk, Dictionary <string, object> campaignData, DateTime initialisedTime, SwrveQAUser qaUser)
        {
            int id = MiniJsonHelper.GetInt(campaignData, ID_KEY);
            SwrveBaseCampaign campaign = null;

            if (campaignData.ContainsKey(CONVERSATION_KEY))
            {
                campaign = SwrveConversationCampaign.LoadFromJSON(sdk, campaignData, id, initialisedTime);
            }
            else if (campaignData.ContainsKey(MESSAGES_KEY))
            {
                campaign = SwrveMessagesCampaign.LoadFromJSON(sdk, campaignData, id, initialisedTime, qaUser);
            }

            if (campaign == null)
            {
                return(null);
            }
            campaign.Id = id;

            AssignCampaignTriggers(campaign, campaignData);
            campaign.MessageCenter = campaignData.ContainsKey(MESSAGE_CENTER_KEY) && (bool)campaignData[MESSAGE_CENTER_KEY];

            if ((!campaign.MessageCenter) && (campaign.GetTriggers().Count == 0))
            {
                campaign.LogAndAddReason("Campaign [" + campaign.Id + "], has no triggers. Skipping this campaign.", qaUser);
                return(null);
            }

            AssignCampaignRules(campaign, campaignData);
            AssignCampaignDates(campaign, campaignData);
            campaign.Subject = campaignData.ContainsKey(SUBJECT_KEY) ? (string)campaignData[SUBJECT_KEY] : "";

            if (campaign.MessageCenter)
            {
                SwrveLog.Log(string.Format("message center campaign: {0}, {1}", campaign.GetType(), campaign.subject));
            }

            return(campaign);
        }