示例#1
0
        void UpdatedCallback()
        {
            InboxMessageBox box = this.Inbox.GetMessageBox();

            currentVersion  = box.Version;
            this.currentBox = box;
        }
        protected override async Task MainLoopImplAsync(CancellationToken cancel)
        {
            cancel.ThrowIfCancellationRequested();

            GoogleApi.GmailProfile profile;

            try
            {
                profile = await Api !.GmailGetProfileAsync(cancel);

                ClearLastError();
            }
            catch (Exception ex)
            {
                SetLastError(ex);
                throw;
            }

            currentProfile = profile;

            currentAccountInfoStr = profile.emailAddress;

            while (true)
            {
                cancel.ThrowIfCancellationRequested();

                try
                {
                    InboxMessageBox box = await ReloadInternalAsync(cancel);

                    this.InitialLoading = false;

                    ClearLastError();

                    MessageBoxUpdatedCallback(box);
                }
                catch (Exception ex)
                {
                    SetLastError(ex);
                    throw;
                }

                await TaskUtil.WaitObjectsAsync(
                    cancels : cancel._SingleArray(),
                    timeout : Util.GenRandInterval(CoresConfig.InboxGmailAdapterSettings.ReloadInterval));
            }
        }
示例#3
0
    async Task <InboxMessageBox> ReloadInternalAsync(bool all, IEnumerable <string>?targetChannelIDs, CancellationToken cancel)
    {
        List <InboxMessage> msgList = new List <InboxMessage>();

        // Team info
        this.TeamInfo = await Api !.GetTeamInfoAsync(cancel);

        currentAccountInfoStr = this.TeamInfo.name;

        if (all)
        {
            // Enum users
            this.UserList = await Api.GetUsersListAsync(cancel);

            // Clear cache
            this.MessageListPerConversation.Clear();

            // Muted channels list
            this.MutedChannelList = await Api.GetMutedChannels(cancel);
        }

        // Enum conversations
        this.ConversationList = await Api.GetConversationsListAsync(cancel);

        if (LastSnapshotDay != DateTime.Now.Day)
        {
            LastSnapshotDay = DateTime.Now.Day;

            SlackSnapshot snapshot = new SlackSnapshot
            {
                TeamInfo         = this.TeamInfo,
                UserList         = this.UserList,
                ConversationList = this.ConversationList,
                MutedChannelList = this.MutedChannelList,
            };

            snapshot._PostData("slack_snapshot");
        }

        // Enum messages
        foreach (var conv in ConversationList)
        {
            if (conv.id._IsFilled())
            {
                bool reload = false;

                if (conv.IsTarget())
                {
                    if (all)
                    {
                        reload = true;
                    }
                    else
                    {
                        if (targetChannelIDs !.Contains(conv.id, StrComparer.IgnoreCaseComparer))
                        {
                            reload = true;
                        }
                    }

                    if (MutedChannelList != null && MutedChannelList.Where(x => x._IsSamei(conv.id)).Any())
                    {
                        reload = false;
                    }
                }

                if (reload)
                {
                    // Get the conversation info
                    SlackApi.Channel convInfo = await Api.GetConversationInfoAsync(conv.id, cancel);

                    // Get unread messages
                    SlackApi.Message[] messages = await Api.GetConversationHistoryAsync(conv.id, convInfo.last_read, this.Inbox.Options.MaxMessagesPerAdapter, cancel : cancel);

                    MessageListPerConversation[conv.id] = messages;
                }

                if (conv.IsTarget())
                {
                    if (MessageListPerConversation.TryGetValue(conv.id, out SlackApi.Message[]? messages))
                    {
                        foreach (SlackApi.Message message in messages)
                        {
                            var user = GetUser(message.user);

                            string group_name = "";

                            if (conv.is_channel)
                            {
                                group_name = "#" + conv.name_normalized;
                            }
                            else if (conv.is_im)
                            {
                                group_name = "@" + GetUser(conv.user)?.profile?.real_name ?? "unknown";
                            }
                            else
                            {
                                group_name = "@" + conv.name_normalized;
                            }

                            InboxMessage m = new InboxMessage
                            {
                                Id = this.Guid + "_" + message.ts.ToString(),

                                Service   = TeamInfo.name._DecodeHtml(),
                                FromImage = TeamInfo.icon?.image_132 ?? "",

                                From         = (user?.profile?.real_name ?? "Unknown User")._DecodeHtml(),
                                ServiceImage = user?.profile?.image_512 ?? "",

                                Group = group_name._DecodeHtml(),

                                Body      = message.text._DecodeHtml(),
                                Timestamp = message.ts._ToDateTimeOfSlack(),
                            };

                            m.Subject = this.TeamInfo.name._DecodeHtml();

                            m.Body = m.Body._SlackExpandBodyUsername(this.UserList);

                            if (message.upload)
                            {
                                m.Body += $"Filename: '{message.files!.FirstOrDefault()?.name ?? "Unknown Filename"}'";
                            }

                            msgList.Add(m);
                        }
                    }
                }
            }
        }

        InboxMessageBox ret = new InboxMessageBox(false)
        {
            MessageList = msgList.OrderByDescending(x => x.Timestamp).Take(this.Inbox.Options.MaxMessagesPerAdapter).ToArray(),
        };

        int numUnread = ret.MessageList.Length;

        if (this.LastUnread != numUnread)
        {
            this.LastUnread = numUnread;

            SlackStatus st = new SlackStatus
            {
                NumUnreadMessages = numUnread,
                TeamInfo          = this.TeamInfo,
            };

            st._PostData("slack_status");
        }

        ClearLastError();

        if (numReload == 0)
        {
            ret.IsFirst = true;
        }

        numReload++;

        return(ret);
    }
示例#4
0
    protected override async Task MainLoopImplAsync(CancellationToken cancel)
    {
        MessageListPerConversation.Clear();

        cancel.ThrowIfCancellationRequested();

        CancellationTokenSource realTimeTaskCancel = new CancellationTokenSource();

        Task realTimeTask = RealtimeRecvLoopAsync(realTimeTaskCancel.Token);

        try
        {
            bool all = true;
            string[]? targetChannelIdList = null;

            while (true)
            {
                cancel.ThrowIfCancellationRequested();

                ExceptionWhen reason;

                try
                {
                    InboxMessageBox box = await ReloadInternalAsync(all, targetChannelIdList, cancel);

                    ClearLastError();

                    this.InitialLoading = false;

                    MessageBoxUpdatedCallback(box);

                    if (this.UpdateChannelsList.Count == 0)
                    {
                        reason = await TaskUtil.WaitObjectsAsync(
                            cancels : cancel._SingleArray(),
                            events : this.UpdateChannelsEvent._SingleArray(),
                            timeout : Util.GenRandInterval(CoresConfig.InboxSlackAdapterSettings.RefreshAllInterval));
                    }
                    else
                    {
                        reason = ExceptionWhen.None;
                    }
                }
                catch (Exception ex)
                {
                    SetLastError(ex._GetSingleException());

                    ex._Debug();

                    reason = ExceptionWhen.TimeoutException;

                    await cancel._WaitUntilCanceledAsync(15000);
                }

                if (reason == ExceptionWhen.TimeoutException)
                {
                    all = true;
                    targetChannelIdList = null;
                    lock (this.UpdateChannelsListLock)
                    {
                        this.UpdateChannelsList.Clear();
                    }
                }
                else
                {
                    all = false;
                    lock (this.UpdateChannelsListLock)
                    {
                        targetChannelIdList = this.UpdateChannelsList.ToArray();
                        this.UpdateChannelsList.Clear();
                    }
                }
            }
        }
        finally
        {
            realTimeTaskCancel._TryCancel();

            await realTimeTask._TryWaitAsync(true);
        }
    }
        async Task <InboxMessageBox> ReloadInternalAsync(CancellationToken cancel)
        {
            GoogleApi.MessageList[] list = await Api !.GmailListMessagesAsync("is:unread label:inbox", this.Inbox.Options.MaxMessagesPerAdapter, cancel);

            List <GoogleApi.Message> msgList = new List <GoogleApi.Message>();

            foreach (GoogleApi.MessageList message in list)
            {
                if (message.id._IsFilled())
                {
                    try
                    {
                        if (MessageCache.TryGetValue(message.id, out GoogleApi.Message? m) == false)
                        {
                            m = await Api.GmailGetMessageAsync(message.id, cancel);

                            MessageCache[message.id] = m;
                        }

                        m._MarkNotNull();

                        msgList.Add(m);
                    }
                    catch (Exception ex)
                    {
                        ex._Debug();
                    }
                }
            }

            // delete old cache
            List <string> deleteList = new List <string>();

            foreach (string id in MessageCache.Keys)
            {
                if (list.Where(x => x.id._IsSamei(id)).Any() == false)
                {
                    deleteList.Add(id);
                }
            }
            foreach (string id in deleteList)
            {
                MessageCache.Remove(id);
            }

            InboxMessageBox box = new InboxMessageBox(false);

            List <InboxMessage> msgList2 = new List <InboxMessage>();

            foreach (var msg in msgList.OrderByDescending(x => x.internalDate).Take(this.Inbox.Options.MaxMessagesPerAdapter))
            {
                var m = new InboxMessage
                {
                    From         = msg.GetFrom()._DecodeHtml(),
                    FromImage    = Consts.CdnUrls.GmailIcon,
                    Group        = "",
                    Id           = this.Guid + "_" + msg.id,
                    Service      = currentProfile !.emailAddress,
                    ServiceImage = Consts.CdnUrls.GmailIcon,
                    Subject      = msg.GetSubject()._DecodeHtml(),
                    Body         = msg.snippet._DecodeHtml(),
                    Timestamp    = msg.internalDate._ToDateTimeOfGoogle(),
                };

                msgList2.Add(m);
            }

            box.MessageList = msgList2.ToArray();

            if (numReload == 0)
            {
                box.IsFirst = true;
            }

            numReload++;

            return(box);
        }
示例#6
0
        public IActionResult GetData()
        {
            InboxMessageBox box = this.Reader.GetCurrentBox();

            return(box._AspNetJsonResult());
        }