public void Open(string userId, long curServerTS, IFizzAuthRestClient client)
        {
            IfClosed(() =>
            {
                if (_userId != null)
                {
                    FizzLogger.W("Please close instance before re-opening");
                    return;
                }

                if (userId == null)
                {
                    throw FizzException.ERROR_INVALID_USER_ID;
                }
                if (client == null)
                {
                    throw ERROR_INVALID_CLIENT;
                }

                _client     = client;
                _userId     = userId;
                _timeOffset = FizzUtils.Now() - curServerTS;
                _startTime  = FizzUtils.Now() + _timeOffset;
                _sessionId  = Guid.NewGuid().ToString();

                ClosePreviousSession();
                SessionStarted();

                _interval.Enable();
                _onLogEmpty = () => { };
            });
        }
Example #2
0
        private void SendChatMessage(string messageStr)
        {
            if (_data == null)
            {
                return;
            }

            long now = FizzUtils.Now();
            Dictionary <string, string> data = new Dictionary <string, string>();

            data.Add(FizzUIMessage.KEY_CLIENT_ID, now + "");

            FizzChannelMessage message = new FizzChannelMessage(
                now,
                FizzService.Instance.UserId,
                FizzService.Instance.UserName,
                _data.Id,
                messageStr,
                data,
                null,
                now);

            UIChatCellModel model = GetChatCellModelFromAction(message);

            AddNewAction(model, false, true);

            FizzService.Instance.PublishMessage(message.To, message.Nick, message.Body, message.Data, FizzService.Instance.IsTranslationEnabled, true, ex => {
                if (ex == null)
                {
                    model.Action.PublishState = UIChannelMessageState.Sent;
                    AddNewAction(model);
                }
            });
        }
        private void HandleSendData(Dictionary <string, string> data)
        {
            if (data == null)
            {
                return;
            }

            if (ChannelsView.CurrentSelectedChannel == null)
            {
                return;
            }

            FizzChannel channel = ChannelsView.CurrentSelectedChannel;

            try
            {
                long now = FizzUtils.Now();
                data.Add(FizzMessageCellModel.KEY_CLIENT_ID, now + "");

                FizzMessageCellModel model = new FizzMessageCellModel(
                    now,
                    FizzService.Instance.UserId,
                    FizzService.Instance.UserName,
                    channel.Id,
                    string.Empty,
                    data,
                    null,
                    now)
                {
                    DeliveryState = FizzChatCellDeliveryState.Pending
                };

                MessagesView.AddMessage(model);

                FizzService.Instance.Client.Chat.PublishMessage(
                    channel.Id,
                    FizzService.Instance.UserName,
                    string.Empty,
                    data,
                    FizzService.Instance.IsTranslationEnabled,
                    channel.Meta.FilterContent,
                    channel.Meta.PersistMessages,
                    exception =>
                {
                    if (exception == null)
                    {
                        model.DeliveryState = FizzChatCellDeliveryState.Sent;
                        MessagesView.AddMessage(model);


                        string dataStr = Utils.GetDictionaryToString(data, FizzMessageCellModel.KEY_CLIENT_ID);
                        FizzService.Instance.Client.Ingestion.TextMessageSent(channel.Id, dataStr, FizzService.Instance.UserName);
                    }
                });
            }
            catch
            {
                FizzLogger.E("Something went wrong while calling PublishMessage of FizzService.");
            }
        }
Example #4
0
 private FizzEvent BuildEvent(string userId, string sessionId)
 {
     return(new FizzEvent(
                userId,
                FizzEventType.session_started,
                1, sessionId, FizzUtils.Now(), "ios", "b1", null, null, null, null));
 }
Example #5
0
        public void Process()
        {
            long          now              = FizzUtils.Now();
            int           fired            = 0;
            List <Action> timersToDispatch = new List <Action>();

            lock (synclock)
            {
                foreach (var timer in timers)
                {
                    if (timer.Key <= now)
                    {
                        timersToDispatch.Add(timer.Value);
                        fired++;
                    }
                    else
                    {
                        break;
                    }
                }

                while (fired-- > 0)
                {
                    timers.RemoveAt(0);
                }
            }

            foreach (var timer in timersToDispatch)
            {
                SafeInvoke(timer);
            }
        }
        private FizzEvent BuildEvent(string sessionId, FizzEventType type, long timestamp, JSONNode fields)
        {
            try
            {
                UnityEngine.PlayerPrefs.SetString(KEY_SESSION_UPDATE_TS, (FizzUtils.Now() + _timeOffset).ToString());
                UnityEngine.PlayerPrefs.Save();

                return(new FizzEvent(
                           _userId,
                           type,
                           EVENT_VER,
                           sessionId,
                           timestamp,
                           PLATFORM,
                           BuildVer,
                           CustomDimesion01, CustomDimesion02, CustomDimesion03,
                           fields
                           ));
            }
            catch (Exception ex)
            {
                FizzLogger.E("Invalid event encountered: " + ex.Message);
                return(null);
            }
        }
        public void InvalidCreationTest()
        {
            var ex = Assert.Throws <FizzException>(() => new FizzChannelMessage(
                                                       1,
                                                       null,
                                                       "nick",
                                                       "to",
                                                       "body",
                                                       "data",
                                                       null,
                                                       FizzUtils.Now()
                                                       ));

            Assert.AreEqual(ex.Message, "invalid_message_from");

            ex = Assert.Throws <FizzException>(() => new FizzChannelMessage(
                                                   1,
                                                   "from",
                                                   "nick",
                                                   null,
                                                   "body",
                                                   "data",
                                                   null,
                                                   FizzUtils.Now()
                                                   ));
            Assert.AreEqual(ex.Message, "invalid_message_to");
        }
Example #8
0
 public void Delay(int delayMS, Action action)
 {
     if (action == null || delayMS < 0)
     {
         FizzLogger.W("Invalid timer scheduled");
         return;
     }
     lock (synclock)
     {
         timers.Add(FizzUtils.Now() + delayMS, action);
     }
 }
        public void TimerTest()
        {
            var  dispatcher = new FizzActionDispatcher();
            bool fired1     = false;
            bool fired2     = false;
            bool fired3     = false;

            long scheduledAt1 = FizzUtils.Now();

            dispatcher.Delay(10, () =>
            {
                long now = FizzUtils.Now();
                Assert.IsTrue(now >= scheduledAt1 + 10);
                Assert.IsFalse(fired2);
                Assert.IsFalse(fired3);
                fired1 = true;
            });

            long scheduledAt2 = FizzUtils.Now();

            dispatcher.Delay(1000, () =>
            {
                long now = FizzUtils.Now();
                Assert.IsTrue(now >= scheduledAt2 + 1000);
                Assert.IsTrue(fired1);
                Assert.IsTrue(fired3);
                fired2 = true;
            });

            long scheduledAt3 = FizzUtils.Now();

            dispatcher.Delay(100, () =>
            {
                long now = FizzUtils.Now();
                Assert.IsTrue(now >= scheduledAt3 + 100);
                Assert.IsTrue(fired1);
                Assert.IsFalse(fired2);
                fired3 = true;
            });

            while (!fired1 || !fired2 || !fired3)
            {
                dispatcher.Process();
            }
        }
        private void ClosePreviousSession()
        {
            string lastSessionId = UnityEngine.PlayerPrefs.GetString(KEY_SESSION, string.Empty);

            if (!string.IsNullOrEmpty(lastSessionId))
            {
                long sessionStartTs  = FizzUtils.Now() + _timeOffset;
                long sessionUpdateTs = FizzUtils.Now() + _timeOffset;
                long.TryParse(UnityEngine.PlayerPrefs.GetString(KEY_SESSION_START_TS), out sessionStartTs);
                long.TryParse(UnityEngine.PlayerPrefs.GetString(KEY_SESSION_UPDATE_TS), out sessionUpdateTs);

                SessionEnded(lastSessionId, sessionStartTs, sessionUpdateTs);

                UnityEngine.PlayerPrefs.DeleteKey(KEY_SESSION);
                UnityEngine.PlayerPrefs.DeleteKey(KEY_SESSION_START_TS);
                UnityEngine.PlayerPrefs.DeleteKey(KEY_SESSION_UPDATE_TS);
                UnityEngine.PlayerPrefs.Save();
            }
        }
Example #11
0
        public void IntegrityTest()
        {
            JSONClass json    = new JSONClass();
            long      id      = FizzUtils.Now();
            long      created = FizzUtils.Now();

            json[FizzTopicMessage.KEY_ID].AsDouble      = (double)id;
            json[FizzTopicMessage.KEY_TYPE]             = "test";
            json[FizzTopicMessage.KEY_FROM]             = "from";
            json[FizzTopicMessage.KEY_DATA]             = "data";
            json[FizzTopicMessage.KEY_CREATED].AsDouble = (double)created;

            var m = new FizzTopicMessage(json.ToString());

            Assert.AreEqual(m.Id, id);
            Assert.AreEqual(m.Type, "test");
            Assert.AreEqual(m.From, "from");
            Assert.AreEqual(m.Data, "data");
            Assert.AreEqual(m.Created, created);
        }
        public void InvalidInputTest()
        {
            var ex = Assert.Throws <FizzException>(() => new FizzIngestionClient(null, new FizzMockActionDispatcher()));

            Assert.AreEqual(ex.Message, "invalid_event_log");

            ex = Assert.Throws <FizzException>(() => new FizzIngestionClient(new FizzInMemoryEventLog(), null));
            Assert.AreEqual(ex.Message, "invalid_dispatcher");


            var ingestion = new FizzIngestionClient(
                new FizzInMemoryEventLog(),
                new FizzMockActionDispatcher()
                );

            ex = Assert.Throws <FizzException>(() => ingestion.Open(null, FizzUtils.Now(), new FizzMockAuthRestClient()));
            Assert.AreEqual(ex.Message, "invalid_user_id");

            ex = Assert.Throws <FizzException>(() => ingestion.Open("userA", FizzUtils.Now(), null));
            Assert.AreEqual(ex.Message, "invalid_client");
        }
        public void IntegrityTest()
        {
            var now = FizzUtils.Now();
            var m   = new FizzChannelMessage(
                1,
                "from",
                "nick",
                "to",
                "body",
                "data",
                null,
                now
                );

            Assert.AreEqual(m.Id, 1);
            Assert.AreEqual(m.From, "from");
            Assert.AreEqual(m.Nick, "nick");
            Assert.AreEqual(m.To, "to");
            Assert.AreEqual(m.Body, "body");
            Assert.AreEqual(m.Data, "data");
            Assert.AreEqual(m.Created, now);
        }
        public void TextMessageSent(string channelId, string content, string senderNick)
        {
            IfOpened(() =>
            {
                FizzLogger.D("Text Message Sent => channel:" + channelId + " content:" + content + " nick:" + senderNick);

                JSONClass fields = new JSONClass();

                if (channelId != null)
                {
                    fields["channel_id"] = channelId;
                }
                if (content != null)
                {
                    fields["content"] = content;
                }
                if (senderNick != null)
                {
                    fields["nick"] = senderNick;
                }

                _eventLog.Put(BuildEvent(_sessionId, FizzEventType.text_msg_sent, FizzUtils.Now() + _timeOffset, fields));
            });
        }
        public void Process()
        {
            long now = FizzUtils.Now();

            if (timers.Count <= 0 || timers.Keys[0] > now)
            {
                return;
            }
            List <Action> timersToDispatch = new List <Action>();

            lock (synclock)
            {
                while (timers.Count > 0 && timers.Keys[0] <= now)
                {
                    timersToDispatch.Add(timers.Values[0]);
                    timers.RemoveAt(0);
                }
            }

            foreach (var timer in timersToDispatch)
            {
                SafeInvoke(timer);
            }
        }
Example #16
0
        private void HandleSendMessage(string message)
        {
            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            FizzChannelModel channel = ChannelsView.CurrentSelectedChannel;

            if (channel == null)
            {
                return;
            }

            try
            {
                long now = FizzUtils.Now();
                Dictionary <string, string> data = new Dictionary <string, string>
                {
                    { FizzMessageCellModel.KEY_CLIENT_ID, now + "" }
                };

                FizzMessageCellModel model = new FizzMessageCellModel(
                    now,
                    FizzService.Instance.UserId,
                    FizzService.Instance.UserName,
                    channel.Id,
                    message,
                    data,
                    null,
                    now)
                {
                    DeliveryState = FizzChatCellDeliveryState.Pending
                };

                MessagesView.AddMessage(model);

                channel.PublishMessage(
                    FizzService.Instance.UserName,
                    message,
                    GetLanguageCode(),
                    data,
                    FizzService.Instance.IsTranslationEnabled,
                    exception =>
                {
                    if (exception == null)
                    {
                        if (model.DeliveryState != FizzChatCellDeliveryState.Published)
                        {
                            model.DeliveryState = FizzChatCellDeliveryState.Sent;
                        }
                        MessagesView.AddMessage(model);

                        FizzService.Instance.Client.Ingestion.TextMessageSent(channel.Id, message, FizzService.Instance.UserName);
                    }
                });
            }
            catch
            {
                FizzLogger.E("Something went wrong while calling PublishMessage of FizzService.");
            }
        }
        public void ProductPurchased(string productId, double amount, string currency, string receipt)
        {
            IfOpened(() =>
            {
                FizzLogger.D("Product Purchased => id:" + productId + " amount:" + amount + " currency:" + currency + " receipt:" + receipt);

                JSONClass fields = new JSONClass();

                if (productId != null)
                {
                    fields["product_id"] = productId;
                }
                if (currency != null)
                {
                    fields["currency"] = currency;
                }
                if (receipt != null)
                {
                    fields["receipt"] = receipt;
                }
                fields["amount"].AsDouble = amount;

                _eventLog.Put(BuildEvent(_sessionId, FizzEventType.product_purchased, FizzUtils.Now() + _timeOffset, fields));
            });
        }
Example #18
0
        public void ReportMessage(string channelId, string message, string messageId, IFizzLanguageCode lang, string userId, string offense, string description, Action <string, FizzException> callback)
        {
            IfOpened(() =>
            {
                if (string.IsNullOrEmpty(channelId))
                {
                    FizzUtils.DoCallback <string> (null, ERROR_INVALID_CHANNEL_ID, callback);
                    return;
                }
                if (string.IsNullOrEmpty(message))
                {
                    FizzUtils.DoCallback <string> (null, ERROR_INVALID_MESSAGE, callback);
                    return;
                }
                if (string.IsNullOrEmpty(messageId))
                {
                    FizzUtils.DoCallback <string> (null, ERROR_INVALID_MESSAGE_ID, callback);
                    return;
                }
                if (lang == null)
                {
                    FizzUtils.DoCallback <string> (null, ERROR_INVALID_LANGUAGE, callback);
                    return;
                }
                if (string.IsNullOrEmpty(userId))
                {
                    FizzUtils.DoCallback <string> (null, ERROR_INVALID_USER_ID, callback);
                    return;
                }
                if (string.IsNullOrEmpty(offense))
                {
                    FizzUtils.DoCallback <string> (null, ERROR_INVALID_OFFENCE, callback);
                    return;
                }

                try
                {
                    JSONClass json     = new JSONClass();
                    json["channel_id"] = channelId;
                    json["message"]    = message;
                    json["message_id"] = messageId;
                    json["language"]   = lang.Code;
                    json["user_id"]    = userId;
                    json["offense"]    = offense.ToString();
                    json.Add("time", new JSONData(FizzUtils.Now() / 1000));

                    if (!string.IsNullOrEmpty(description))
                    {
                        json["description"] = description;
                    }

                    _restClient.Post(FizzConfig.API_BASE_URL, FizzConfig.API_PATH_REPORTS, json.ToString(), (response, ex) =>
                    {
                        if (ex != null)
                        {
                            FizzUtils.DoCallback <string> (null, ex, callback);
                        }
                        else
                        {
                            try
                            {
                                JSONNode responseJson    = JSONNode.Parse(response);
                                string reportedMessageId = responseJson["id"];

                                FizzUtils.DoCallback <string> (reportedMessageId, null, callback);
                            }
                            catch
                            {
                                FizzUtils.DoCallback <string> (null, ERROR_INVALID_RESPONSE_FORMAT, callback);
                            }
                        }
                    });
                }
                catch (FizzException ex)
                {
                    FizzUtils.DoCallback <string> (null, ex, callback);
                }
            });
        }
 private void UpdateSessionTimestamp()
 {
     UnityEngine.PlayerPrefs.SetString(KEY_SESSION_UPDATE_TS, (FizzUtils.Now() + _timeOffset).ToString());
     UnityEngine.PlayerPrefs.Save();
 }