示例#1
0
 private void OnMessage(LCIMConversation conv, LCIMMessage msg)
 {
     if (conv.Id == WordConversationId)
     {
         AddMessage(msg);
     }
 }
示例#2
0
        public async Task CreateConversation()
        {
            TaskCompletionSource <object> tcs = new TaskCompletionSource <object>();

            string     clientId = Guid.NewGuid().ToString();
            LCIMClient client   = new LCIMClient(clientId);

            await client.Open();

            client.OnInvited = (conv, initBy) => {
                WriteLine($"on invited: {initBy}");
                WriteLine(conv.CreatorId);
            };

            client.OnMembersJoined = (conv, memberList, initBy) => {
                WriteLine($"on members joined: {initBy}");
                foreach (string memberId in conv.MemberIds)
                {
                    WriteLine(memberId);
                }
                tcs.SetResult(null);
            };

            string           name         = Guid.NewGuid().ToString();
            LCIMConversation conversation = await client.CreateConversation(new string[] { "world" }, name : name, unique : false);

            await tcs.Task;
        }
示例#3
0
        public async Task Unread()
        {
            TaskCompletionSource <object> tcs = new TaskCompletionSource <object>();
            string           clientId         = Guid.NewGuid().ToString();
            LCIMClient       client           = new LCIMClient(clientId);
            LCIMConversation conversation     = await m1.CreateConversation(new string[] { clientId });

            LCIMTextMessage textMessage = new LCIMTextMessage("hello");
            await conversation.Send(textMessage);

            client.OnUnreadMessagesCountUpdated = (convs) => {
                foreach (LCIMConversation conv in convs)
                {
                    WriteLine($"unread count: {conv.Unread}");
                    //Assert.AreEqual(conv.Unread, 1);
                    //Assert.True(conv.LastMessage is LCIMTextMessage);
                    //LCIMTextMessage textMsg = conv.LastMessage as LCIMTextMessage;
                    //Assert.AreEqual(textMsg.Text, "hello");
                }
            };
            await client.Open();

            client.OnMessage = (conv, msg) => {
                WriteLine($"unread count: {conv.Unread}");
                Assert.AreEqual(conv.Unread, 2);
                Assert.True(conv.LastMessage is LCIMTextMessage);
                LCIMTextMessage textMsg = conv.LastMessage as LCIMTextMessage;
                Assert.AreEqual(textMsg.Text, "world");
                tcs.SetResult(true);
            };
            textMessage = new LCIMTextMessage("world");
            await conversation.Send(textMessage);

            await tcs.Task;
        }
        private async Task OnMessageReceipt(GenericCommand notification)
        {
            RcpCommand       rcp          = notification.RcpMessage;
            string           convId       = rcp.Cid;
            string           msgId        = rcp.Id;
            long             timestamp    = rcp.T;
            bool             isRead       = rcp.Read;
            string           fromId       = rcp.From;
            LCIMConversation conversation = await Client.GetOrQueryConversation(convId);

            if (isRead)
            {
                Client.OnMessageRead?.Invoke(conversation, msgId);
                if (timestamp > conversation.LastReadTimestamp)
                {
                    conversation.LastReadTimestamp = timestamp;
                    Client.OnLastReadAtUpdated?.Invoke(conversation);
                }
            }
            else
            {
                Client.OnMessageDelivered?.Invoke(conversation, msgId);
                if (timestamp > conversation.LastDeliveredTimestamp)
                {
                    conversation.LastDeliveredTimestamp = timestamp;
                    Client.OnLastDeliveredAtUpdated?.Invoke(conversation);
                }
            }
        }
示例#5
0
        private async Task OnLeft(ConvCommand convMessage)
        {
            LCIMConversation conversation = await Client.GetOrQueryConversation(convMessage.Cid);

            // 从内存中清除对话
            Client.ConversationDict.Remove(conversation.Id);
            Client.OnKicked?.Invoke(conversation, convMessage.InitBy);
        }
示例#6
0
        private async Task OnMemberInfoChanged(ConvCommand conv)
        {
            LCIMConversation conversation = await Client.GetOrQueryConversation(conv.Cid);

            ConvMemberInfo memberInfo = conv.Info;

            Client.OnMemberInfoUpdated?.Invoke(conversation, memberInfo.Pid, memberInfo.Role, conv.InitBy);
        }
示例#7
0
 private void OnMessage(LCIMConversation conv, LCIMMessage msg)
 {
     if (conv.Id == conversation.Id &&
         msg is LCIMTextMessage textMsg)
     {
         AddMessage(textMsg);
     }
 }
示例#8
0
        private async Task OnMembersUnblocked(ConvCommand convMessage)
        {
            LCIMConversation conversation = await Client.GetOrQueryConversation(convMessage.Cid);

            ReadOnlyCollection <string> unblockedMemberIds = convMessage.M.ToList().AsReadOnly();

            Client.OnMembersUnblocked?.Invoke(conversation, unblockedMemberIds, convMessage.InitBy);
        }
示例#9
0
        private async Task OnMembersMuted(ConvCommand convMessage)
        {
            LCIMConversation conversation = await Client.GetOrQueryConversation(convMessage.Cid);

            ReadOnlyCollection <string> mutedMemberIds = new ReadOnlyCollection <string>(convMessage.M);

            conversation.mutedIds.UnionWith(mutedMemberIds);
            Client.OnMembersMuted?.Invoke(conversation, mutedMemberIds, convMessage.InitBy);
        }
示例#10
0
        private async Task OnMemberLeft(ConvCommand convMessage)
        {
            LCIMConversation conversation = await Client.GetOrQueryConversation(convMessage.Cid);

            ReadOnlyCollection <string> leftIdList = new ReadOnlyCollection <string>(convMessage.M);

            conversation.ids.RemoveWhere(item => leftIdList.Contains(item));
            Client.OnMembersLeft?.Invoke(conversation, leftIdList, convMessage.InitBy);
        }
示例#11
0
        private async Task OnMembersUnmuted(ConvCommand convMessage)
        {
            LCIMConversation conversation = await Client.GetOrQueryConversation(convMessage.Cid);

            ReadOnlyCollection <string> unmutedMemberIds = new ReadOnlyCollection <string>(convMessage.M);

            conversation.mutedIds.RemoveWhere(id => unmutedMemberIds.Contains(id));
            Client.OnMembersUnmuted?.Invoke(conversation, unmutedMemberIds, convMessage.InitBy);
        }
示例#12
0
        public async Task SetUp()
        {
            Utils.SetUp();
            m1 = new LCIMClient("m1");
            m2 = new LCIMClient("m2");
            await m1.Open();

            await m2.Open();

            conversation = await m1.CreateConversation(new string[] { "m2" });
        }
示例#13
0
        public async Task SetUp()
        {
            Utils.SetUp();
            c1 = new LCIMClient(Guid.NewGuid().ToString());
            c2 = new LCIMClient(Guid.NewGuid().ToString());
            await c1.Open();

            await c2.Open();

            conversation = await c1.CreateConversation(new string[] { Guid.NewGuid().ToString() });
        }
示例#14
0
        private async Task OnPropertiesUpdated(ConvCommand conv)
        {
            LCIMConversation conversation = await Client.GetOrQueryConversation(conv.Cid);

            Dictionary <string, object> updatedAttr = JsonConvert.DeserializeObject <Dictionary <string, object> >(conv.AttrModified.Data,
                                                                                                                   LCJsonConverter.Default);

            // 更新内存数据
            conversation.MergeInfo(updatedAttr);
            Client.OnConversationInfoUpdated?.Invoke(conversation,
                                                     new ReadOnlyDictionary <string, object>(updatedAttr),
                                                     conv.InitBy);
        }
示例#15
0
        public async Task SetUp()
        {
            Utils.SetUp();
            c1 = new LCIMClient(Guid.NewGuid().ToString());
            await c1.Open();

            c2 = new LCIMClient(Guid.NewGuid().ToString());
            await c2.Open();

            lean = new LCIMClient("lean");
            await lean.Open();

            conversation = await c1.CreateConversation(new string[] { "lean", "cloud" });
        }
示例#16
0
        internal async Task FetchReciptTimestamp(string convId)
        {
            ConvCommand convCommand = new ConvCommand {
                Cid = convId
            };
            GenericCommand request = NewCommand(CommandType.Conv, OpType.MaxRead);

            request.ConvMessage = convCommand;
            GenericCommand response = await Connection.SendRequest(request);

            convCommand = response.ConvMessage;
            LCIMConversation conversation = await Client.GetOrQueryConversation(convCommand.Cid);

            conversation.LastDeliveredTimestamp = convCommand.MaxAckTimestamp;
            conversation.LastReadTimestamp      = convCommand.MaxReadTimestamp;
        }
示例#17
0
    private async void Reload()
    {
        scrollRect.ClearItemData();

        nameText.text = target.GetNickname();

        client            = LCManager.Instance.IMClient;
        client.OnMessage += OnMessage;
        conversation      = await client.CreateConversation(new string[] { target.ObjectId });

        // 拉取历史消息
        ReadOnlyCollection <LCIMMessage> messages = await conversation.QueryMessages();

        foreach (LCIMMessage message in messages)
        {
            AddMessage(message);
        }
    }
示例#18
0
    private async Task <string> GetConversationName(LCIMConversation conv)
    {
        if (conv.Name != null)
        {
            return(conv.Name);
        }

        LCIMClient client = LCManager.Instance.IMClient;

        if (conv.MemberIds.Count == 2)
        {
            // 私聊
            string targetId = conv.MemberIds[0] == client.Id ? conv.MemberIds[1] : conv.MemberIds[0];
            target = await LCManager.Instance.GetUser(targetId);

            return(target.GetNickname());
        }
        return("Group");
    }
示例#19
0
    public async void Send()
    {
        string content = inputField.text;

        if (string.IsNullOrEmpty(content))
        {
            return;
        }

        try {
            LCIMTextMessage  message      = new LCIMTextMessage(content);
            LCIMConversation conversation = await LCManager.Instance.IMClient.GetConversation(WordConversationId);

            await conversation.Send(message);

            AddMessage(message);
        } catch (LCException e) {
            LCUtils.LogException(e);
        }
    }
        private async Task OnMessaage(GenericCommand notification)
        {
            DirectCommand direct = notification.DirectMessage;
            // 反序列化消息
            LCIMMessage message;

            if (direct.HasBinaryMsg)
            {
                // 二进制消息
                byte[] bytes = direct.BinaryMsg.ToByteArray();
                message = LCIMBinaryMessage.Deserialize(bytes);
            }
            else
            {
                // 类型消息
                message = LCIMTypedMessage.Deserialize(direct.Msg);
            }
            // 填充消息数据
            message.ConversationId = direct.Cid;
            message.Id             = direct.Id;
            message.FromClientId   = direct.FromPeerId;
            message.SentTimestamp  = direct.Timestamp;
            message.MentionAll     = direct.MentionAll;
            message.MentionIdList  = direct.MentionPids.ToList();
            message.Mentioned      = message.MentionAll ||
                                     message.MentionIdList.Contains(Client.Id);
            message.PatchedTimestamp = direct.PatchTimestamp;
            message.IsTransient      = direct.Transient;
            // 获取对话
            LCIMConversation conversation = await Client.GetOrQueryConversation(direct.Cid);

            conversation.Unread++;
            conversation.LastMessage = message;
            // 通知服务端已接收
            if (!(conversation is LCIMChatRoom) && !message.IsTransient)
            {
                // 只有非暂态消息才需要发送 ack
                _ = Ack(message.ConversationId, message.Id);
            }
            Client.OnMessage?.Invoke(conversation, message);
        }
示例#21
0
        public async Task CreateChatRoom()
        {
            string     clientId = Guid.NewGuid().ToString();
            LCIMClient client   = new LCIMClient(clientId);

            await client.Open();

            client.OnInvited = (conv, initBy) => {
                WriteLine($"on invited: {initBy}");
            };

            string           name         = Guid.NewGuid().ToString();
            LCIMConversation conversation = await client.CreateChatRoom(name);

            string     visitorId = Guid.NewGuid().ToString();
            LCIMClient visitor   = new LCIMClient(visitorId);

            await visitor.Open();

            LCIMChatRoom chatRoom = await visitor.GetConversation(conversation.Id) as LCIMChatRoom;

            await chatRoom.Join();

            LCIMTextMessage textMessage = new LCIMTextMessage("hello, world");
            await conversation.Send(textMessage);

            int count = await chatRoom.GetMembersCount();

            ReadOnlyCollection <string> onlineMembers = await chatRoom.GetOnlineMembers();

            Assert.GreaterOrEqual(onlineMembers.Count, 1);
            foreach (string memberId in onlineMembers)
            {
                WriteLine($"{memberId} online");
            }

            await client.Close();

            await visitor.Close();
        }
示例#22
0
        private async Task OnUnread(GenericCommand notification)
        {
            UnreadCommand unread = notification.UnreadMessage;

            IEnumerable <string> convIds = unread.Convs
                                           .Select(conv => conv.Cid);
            Dictionary <string, LCIMConversation> conversationDict = (await Client.GetConversationList(convIds))
                                                                     .ToDictionary(item => item.Id);
            ReadOnlyCollection <LCIMConversation> conversations = unread.Convs.Select(conv => {
                // 设置对话中的未读数据
                LCIMConversation conversation = conversationDict[conv.Cid];
                conversation.Unread           = conv.Unread;
                if (conv.HasData || conv.HasBinaryMsg)
                {
                    // 如果有消息,则反序列化
                    LCIMMessage message = null;
                    if (conv.HasBinaryMsg)
                    {
                        // 二进制消息
                        byte[] bytes = conv.BinaryMsg.ToByteArray();
                        message      = LCIMBinaryMessage.Deserialize(bytes);
                    }
                    else
                    {
                        // 类型消息
                        message = LCIMTypedMessage.Deserialize(conv.Data);
                    }
                    // 填充消息数据
                    message.ConversationId   = conv.Cid;
                    message.Id               = conv.Mid;
                    message.FromClientId     = conv.From;
                    message.SentTimestamp    = conv.Timestamp;
                    message.Mentioned        = conv.Mentioned;
                    conversation.LastMessage = message;
                }
                return(conversation);
            }).ToList().AsReadOnly();

            Client.OnUnreadMessagesCountUpdated?.Invoke(conversations);
        }
        private async Task OnMessagePatched(GenericCommand notification)
        {
            PatchCommand patchMessage = notification.PatchMessage;

            foreach (PatchItem patch in patchMessage.Patches)
            {
                // 获取对话
                LCIMConversation conversation = await Client.GetOrQueryConversation(patch.Cid);

                LCIMMessage message;
                if (patch.HasBinaryMsg)
                {
                    byte[] bytes = patch.BinaryMsg.ToByteArray();
                    message = LCIMBinaryMessage.Deserialize(bytes);
                }
                else
                {
                    message = LCIMTypedMessage.Deserialize(patch.Data);
                }
                message.ConversationId   = patch.Cid;
                message.Id               = patch.Mid;
                message.FromClientId     = patch.From;
                message.SentTimestamp    = patch.Timestamp;
                message.PatchedTimestamp = patch.PatchTimestamp;
                if (message is LCIMRecalledMessage recalledMessage)
                {
                    // 消息撤回
                    Client.OnMessageRecalled?.Invoke(conversation, recalledMessage);
                }
                else
                {
                    // 消息修改
                    Client.OnMessageUpdated?.Invoke(conversation, message);
                }
            }
        }
示例#24
0
        internal async Task <LCIMConversation> CreateConv(
            IEnumerable <string> members = null,
            string name      = null,
            bool transient   = false,
            bool unique      = true,
            bool temporary   = false,
            int temporaryTtl = 86400,
            Dictionary <string, object> properties = null)
        {
            GenericCommand request = NewCommand(CommandType.Conv, OpType.Start);
            ConvCommand    conv    = new ConvCommand {
                Transient = transient,
                Unique    = unique,
            };

            if (members != null)
            {
                conv.M.AddRange(members);
            }
            if (temporary)
            {
                conv.TempConv    = temporary;
                conv.TempConvTTL = temporaryTtl;
            }
            Dictionary <string, object> attrs = new Dictionary <string, object>();

            if (!string.IsNullOrEmpty(name))
            {
                attrs["name"] = name;
            }
            if (properties != null)
            {
                attrs = properties.Union(attrs.Where(kv => !properties.ContainsKey(kv.Key)))
                        .ToDictionary(k => k.Key, v => v.Value);
            }
            conv.Attr = new JsonObjectMessage {
                Data = JsonConvert.SerializeObject(LCEncoder.Encode(attrs))
            };
            if (Client.SignatureFactory != null)
            {
                LCIMSignature signature = await Client.SignatureFactory.CreateStartConversationSignature(Client.Id, members);

                conv.S = signature.Signature;
                conv.T = signature.Timestamp;
                conv.N = signature.Nonce;
            }
            request.ConvMessage = conv;
            GenericCommand response = await Connection.SendRequest(request);

            string convId = response.ConvMessage.Cid;

            if (!Client.ConversationDict.TryGetValue(convId, out LCIMConversation conversation))
            {
                if (transient)
                {
                    conversation = new LCIMChatRoom(Client);
                }
                else if (temporary)
                {
                    conversation = new LCIMTemporaryConversation(Client);
                }
                else if (properties != null && properties.ContainsKey("system"))
                {
                    conversation = new LCIMServiceConversation(Client);
                }
                else
                {
                    conversation = new LCIMConversation(Client);
                }
                Client.ConversationDict[convId] = conversation;
            }
            // 合并请求数据
            conversation.Id        = convId;
            conversation.Unique    = unique;
            conversation.UniqueId  = response.ConvMessage.UniqueId;
            conversation.Name      = name;
            conversation.CreatorId = Client.Id;
            conversation.ids       = members != null ?
                                     new HashSet <string>(members) : new HashSet <string>();
            // 将自己加入
            conversation.ids.Add(Client.Id);
            conversation.CreatedAt = DateTime.Parse(response.ConvMessage.Cdate);
            conversation.UpdatedAt = conversation.CreatedAt;
            return(conversation);
        }
示例#25
0
        internal async Task <ReadOnlyCollection <LCIMConversation> > Find(LCIMConversationQuery query)
        {
            GenericCommand command = new GenericCommand {
                Cmd    = CommandType.Conv,
                Op     = OpType.Query,
                AppId  = LCCore.AppId,
                PeerId = Client.Id,
            };
            ConvCommand convMessage = new ConvCommand();

            string where = query.Condition.BuildWhere();
            if (!string.IsNullOrEmpty(where))
            {
                try {
                    convMessage.Where = new JsonObjectMessage {
                        Data = where
                    };
                } catch (Exception e) {
                    LCLogger.Error(e);
                }
            }
            int flag = 0;

            if (query.Compact)
            {
                flag += LCIMConversationQuery.CompactFlag;
            }
            if (query.WithLastMessageRefreshed)
            {
                flag += LCIMConversationQuery.WithLastMessageFlag;
            }
            if (flag > 0)
            {
                convMessage.Flag = flag;
            }
            convMessage.Skip  = query.Condition.Skip;
            convMessage.Limit = query.Condition.Limit;
            string orders = query.Condition.BuildOrders();

            if (!string.IsNullOrEmpty(orders))
            {
                convMessage.Sort = orders;
            }
            command.ConvMessage = convMessage;
            GenericCommand response = await Connection.SendRequest(command);

            JsonObjectMessage results = response.ConvMessage.Results;
            List <object>     convs   = JsonConvert.DeserializeObject <List <object> >(results.Data,
                                                                                       LCJsonConverter.Default);

            return(convs.Select(item => {
                Dictionary <string, object> conv = item as Dictionary <string, object>;
                string convId = conv["objectId"] as string;
                if (!Client.ConversationDict.TryGetValue(convId, out LCIMConversation conversation))
                {
                    // 解析是哪种类型的对话
                    if (conv.TryGetValue("tr", out object transient) && (bool)transient == true)
                    {
                        conversation = new LCIMChatRoom(Client);
                    }
                    else if (conv.ContainsKey("tempConv") && conv.ContainsKey("tempConvTTL"))
                    {
                        conversation = new LCIMTemporaryConversation(Client);
                    }
                    else if (conv.TryGetValue("sys", out object sys) && (bool)sys == true)
                    {
                        conversation = new LCIMServiceConversation(Client);
                    }
                    else
                    {
                        conversation = new LCIMConversation(Client);
                    }
                    Client.ConversationDict[convId] = conversation;
                }
                conversation.MergeFrom(conv);
                return conversation;
            }).ToList().AsReadOnly());
        }
示例#26
0
        private async Task OnUnblocked(ConvCommand convMessage)
        {
            LCIMConversation conversation = await Client.GetOrQueryConversation(convMessage.Cid);

            Client.OnUnblocked?.Invoke(conversation, convMessage.InitBy);
        }