Exemplo n.º 1
0
        public async Task <IActionResult> CreateChannel(Guid appId, [FromBody] ChannelUpdate channel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var app = await _applicationRepository.Get(appId);

            if (app == null)
            {
                return(NotFound());
            }

            var newChannel = new Channel
            {
                Id         = Guid.NewGuid(),
                Name       = channel.Name,
                CustomData = channel.CustomData
            };

            app.Channels.Add(newChannel);

            await _applicationRepository.Upsert(app);

            return(CreatedAtAction(nameof(GetChannel), new { appId, channelId = newChannel.Id }, newChannel));
        }
Exemplo n.º 2
0
        public async Task <IActionResult> UpdateChannel(Guid appId, Guid channelId, [FromBody] ChannelUpdate channel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var app = await _applicationRepository.Get(appId);

            if (app == null)
            {
                return(NotFound());
            }

            var channelToUpdate = app.Channels.FirstOrDefault(ch => ch.Id == channelId);

            if (channelToUpdate == null)
            {
                return(NotFound());
            }

            channelToUpdate.Name       = channel.Name;
            channelToUpdate.CustomData = channel.CustomData;

            await _applicationRepository.Upsert(app);

            return(Ok(channelToUpdate));
        }
Exemplo n.º 3
0
        public async Task RunAsync(Guid channelId, string blobName, Stream myBlob)
        {
            try
            {
                var feedPath   = this.pathGenerator.GetChannelDownloadPath(channelId, blobName);
                var feedString = await this.blobContainer.ReadBlobAsStringAsync("rss", feedPath, IBlobContainer.UploadStringCompression.GZip);

                //var feedString = await this.reader.ReadAllAsTextAsync(myBlob);
                var feed          = this.feedReader.GetFeed(feedString);
                var feedItems     = feed.Items;
                var channelUpdate = new ChannelUpdate
                {
                    Title       = feed.Title,
                    Description = feed.Description ?? string.Empty,
                    Id          = channelId
                };

                await this.queue.AddAsync(channelUpdate, QueuesName.ChannelUpdate);

                foreach (var item in feedItems)
                {
                    var itemJson       = this.serializer.Serialize(item);
                    var itemUploadPath = this.pathGenerator.GetPathUpload(channelId, item.Id);
                    await this.blobContainer.UploadStringAsync("rss", itemUploadPath, itemJson, IBlobContainer.UploadStringCompression.GZip);

                    var hash = this.hasher.GetHash(
                        item.Content?.Trim()
                        + item.Description?.Trim()
                        + item.Title?.Trim()
                        + item.Link?.Trim());

                    if (string.IsNullOrWhiteSpace(item.Content?.Trim()) &&
                        string.IsNullOrWhiteSpace(item.Description?.Trim()) &&
                        string.IsNullOrWhiteSpace(item.Title?.Trim()) &&
                        string.IsNullOrWhiteSpace(item.Link?.Trim()))
                    {
                        throw new Exception("Crap - how to calculate sha for item?");
                    }

                    try
                    {
                        await this.newsWriter.InsertNewsLinkAsync(channelId, item.Title, item.Id, item.PublishingDate, item.Link, hash);
                    }
                    catch (NewsWriterInsertNewsLinkException e)
                    {
                        this.logger.LogCritical(e.ToString());
                        await this.blobContainer.DeleteAsync("rss", itemUploadPath);
                    }
                }
            }
            catch (FeedReaderWrapperParseStringException e)
            {
                this.logger.LogCritical($"Xml rss/raw/{channelId.ToString()}/{blobName} is broken.Finishing and returning");
                this.logger.LogCritical(e.ToString());
            }
        }
Exemplo n.º 4
0
 public void UpdateChannels(bool force)
 {
     //TODO: Should update RSS channels in background!
     foreach (IRSSChannel channel in Channels)
     {
         if (force || channel.Expired())
         {
             ChannelUpdate update = new ChannelUpdate(channel.Update);
             update.BeginInvoke(new AsyncCallback(ChannelUpdated), update);
         }
     }
 }
Exemplo n.º 5
0
        public void Update(IReadOnlyCollection <ITag> tags, ulong userId, ulong channelId, DateTimeOffset messageTime, bool updateChannelTimestamp, DateTimeOffset offset)
        {
            var emojis = tags.Where(x => x.Type == TagType.Emoji).Select(x => x.Value as Emote).ToList();

            if (emojis.Any())
            {
                var emoteUses = _database.GetCollection <EmoteUse>(TABLE_EMOTE_USES);

                // Check if emoji is already present in the database, if not
                // add it.
                foreach (var emoji in emojis)
                {
                    if (twiceCord.Emotes.Any(emote => emote.Id == emoji.Id))
                    {
                        // Get the emote from the database whose data has to be updated
                        EmoteUse emoteUse = new EmoteUse
                        {
                            EmoteId   = emoji.Id,
                            EmoteName = emoji.Name,
                            Animated  = emoji.Animated,
                            ChannelId = channelId,
                            UserId    = userId,
                            Timestamp = messageTime.UtcDateTime
                        };

                        emoteUses.Insert(emoteUse);
                    }
                }

                if (updateChannelTimestamp)
                {
                    var channelUpdateCollection = _database.GetCollection <ChannelUpdate>(TABLE_CHANNEL_UPDATES);
                    var channelUpdate           = channelUpdateCollection.FindOne(x => x.ChannelId == channelId);

                    if (channelUpdate == null)
                    {
                        channelUpdate = new ChannelUpdate
                        {
                            ChannelId  = channelId,
                            LastUpdate = DateTime.UnixEpoch
                        };
                    }

                    channelUpdate.LastUpdate = offset.UtcDateTime;
                    channelUpdateCollection.Upsert(channelUpdate);
                }
            }
        }
Exemplo n.º 6
0
        void ChannelUpdated(IAsyncResult ar)
        {
            ChannelUpdate update = ar.AsyncState as ChannelUpdate;

            if (update != null)
            {
                update.EndInvoke(ar);
                try
                {
                    ChannelUpdated(update.Target as IRSSChannel);
                }
                catch (Exception e)
                {
                    //ignore
                }
            }
        }
Exemplo n.º 7
0
        public DateTimeOffset LastChannelUpdate(ulong channelId)
        {
            var channelUpdateCollection = _database.GetCollection <ChannelUpdate>(TABLE_CHANNEL_UPDATES);
            var channelUpdate           = channelUpdateCollection.FindOne(x => x.ChannelId == channelId);

            if (channelUpdate == null)
            {
                channelUpdate = new ChannelUpdate
                {
                    ChannelId  = channelId,
                    LastUpdate = DateTime.UnixEpoch
                };

                channelUpdateCollection.Insert(channelUpdate);
            }

            return(channelUpdate.LastUpdate);
        }
Exemplo n.º 8
0
        public async Task <ActionResult <ChannelUrlRedirect> > Update(string id, ChannelUpdate channelUpdate)
        {
            Channel channel = _channelRepository.GetChannelByIdOrDefault(id);

            if (channel == null)
            {
                return(NotFound());
            }

            if (channel.OwnerId != CurrentUserId())
            {
                return(Unauthorized());
            }

            if (channel.IsEditing)
            {
                return(BadRequest("Channel is already being modified."));
            }

            if (!ValidateDeleteTrackIds(channelUpdate.DeleteTrackIds, channel))
            {
                return(BadRequest(ModelState));
            }

            if (!await TestNewMediaUrls(channelUpdate.NewMediaUrls))
            {
                return(BadRequest(ModelState));
            }

            string oldName = channel.Name;

            channel.Name        = channelUpdate.Name;
            channel.Description = channelUpdate.Description;
            channel.IsEditing   = true;
            await _channelRepository.UpdateChannel(oldName, channel);

            await _channelTrackRepository.DeleteTracks(channel, channelUpdate.DeleteTrackIds);

            await _radioHubProxy.RedirectUsersToNewUrl(id, channel.Name, channel.Discriminator);

            _channelTaskLoader.Enqueue(new ChannelUpdateTask(id, channelUpdate.NewMediaUrls));

            return(Ok(new ChannelUrlRedirect(channel.Name, channel.Discriminator)));
        }
Exemplo n.º 9
0
        public async Task Update(ChannelUpdate message)
        {
            var query = "UPDATE Channels SET Title = @title, Description = @description, ModifiedOn = @modified WHERE Id = @id";

            var queryData = new
            {
                title       = message.Title,
                description = message.Description,
                modified    = DateTime.UtcNow,
                id          = message.Id
            };

            try
            {
                await using var sqlConnection = new SqlConnection(this.connectionString);
                await sqlConnection.ExecuteAsync(query, queryData);
            }
            catch (Exception e)
            {
                this.loger.LogCritical(e.ToString());
            }
        }
Exemplo n.º 10
0
 public override void ChannelUpdated(TwilioChatClient client, Channel channel, ChannelUpdate updated)
 {
     Logger.Info($"ChatClient: {client}", $"ChannelUpdated: {channel.Sid}, reason: {updated}");
 }
Exemplo n.º 11
0
 public override void ChannelUpdated(TwilioChatClient client, Channel channel, ChannelUpdate updated)
 {
     Logger.Info($"ChatClient: {client}", $"ChannelUpdated: {channel.Sid}, reason: {updated}");
     Logger.Info($"ChatClient: {client}", $"Channel attributes: {channel.Attributes.ToDebugLog()}");
 }
Exemplo n.º 12
0
 internal void OnChannelUpdate(object sender, ChannelEventArgs e)
 {
     ChannelUpdate?.Invoke(sender, e.Convert <IServerChannel>());
 }
Exemplo n.º 13
0
        //TODO: Typing Start
        //TODO: Integrations
        //TODO: User Updates
        //TODO: Voice Chat

        private void GatewayMessageHandler(string eventName, string payload)
        {
            _Logger?.Debug($"{eventName} - {payload}");

            var eventValue = (Events)Enum.Parse(typeof(Events), eventName);

            var eventPayload = JObject.Parse(payload);

            switch (eventValue)
            {
            case Events.READY:
            {
                var guilds = eventPayload["guilds"] as JArray;

                foreach (var guild in guilds)
                {
                    var g = new Guild {
                        Id = guild["id"].ToString(), Unavailable = guild["unavailable"].ToObject <bool>()
                    };

                    Guilds.Add(g.Id, g);
                }

                break;
            }

            case Events.GUILD_CREATE:
            {
                Guild g = null;
                if (Guilds.ContainsKey(eventPayload["id"].ToString()))
                {
                    g = Guilds[eventPayload["id"].ToString()];
                }
                else
                {
                    g = new Guild()
                    {
                        Id = eventPayload["id"].ToString()
                    };
                    Guilds.Add(g.Id, g);
                }

                JsonConvert.PopulateObject(payload, g);

                foreach (var channel in g.Channels)
                {
                    if (!Channels.ContainsKey(channel.Key))
                    {
                        Channels.Add(channel.Key, channel.Value);
                    }

                    channel.Value.Guild_Id = g.Id;
                    channel.Value.Guild    = g;
                }

                foreach (var member in g.Members)
                {
                    if (!Users.ContainsKey(member.Key))
                    {
                        Users.Add(member.Key, member.Value.User);
                    }
                    else if (member.Value.User != Users[member.Key])
                    {
                        member.Value.User = Users[member.Key];
                    }

                    member.Value.Guild = g;
                }

                foreach (var presence in g.Presences.Values)
                {
                    presence.User = Users[presence.User.Id];
                }

                g.UpdateAllUserPermissions();

                GuildCreated?.Invoke(g);
                break;
            }

            case Events.GUILD_UPDATE:
            {
                var g = Guilds[eventPayload["id"].ToString()];

                // TODO: Double check that this is the correct behavior.
                JsonConvert.PopulateObject(payload, g);

                GuildUpdated?.Invoke(g);
                break;
            }

            case Events.GUILD_DELETE:
            {
                var g = Guilds[eventPayload["id"].ToString()];
                Guilds.Remove(eventPayload["id"].ToString());

                GuildDeleted?.Invoke(g);
                break;
            }

            case Events.CHANNEL_CREATE:
            {
                var c = eventPayload.ToObject <GuildChannel>();
                var g = Guilds[c.Guild_Id];

                c.Guild = g;
                g.Channels.Add(c.Id, c);
                Channels.Add(c.Id, c);

                ChannelCreate?.Invoke(g, c);
                break;
            }

            case Events.CHANNEL_UPDATE:
            {
                var g = Guilds[eventPayload["guild_id"].ToString()];
                var c = g.Channels[eventPayload["id"].ToString()];

                JsonConvert.PopulateObject(payload, c);

                ChannelUpdate?.Invoke(g, c);
                break;
            }

            case Events.CHANNEL_DELETE:
            {
                var g = Guilds[eventPayload["guild_id"].ToString()];
                var c = g.Channels[eventPayload["id"].ToString()];

                g.Channels.Remove(c.Id);
                Channels.Remove(c.Id);

                ChannelDelete?.Invoke(g, c);
                break;
            }

            case Events.GUILD_BAN_ADD:
            {
                // TODO: User knows about bans
                var g = Guilds[eventPayload["guild_id"].ToString()];
                var m = g.Members[eventPayload["id"].ToString()];

                Users[m.User.Id].Guilds.Remove(g);
                g.Members.Remove(m.User.Id);

                BanAdd?.Invoke(g, m.User);
                break;
            }

            case Events.GUILD_BAN_REMOVE:
            {
                var g = Guilds[eventPayload["guild_id"].ToString()];

                BanRemove?.Invoke(g, eventPayload.ToObject <DiscordUser>());
                break;
            }

            case Events.GUILD_EMOJIS_UPDATE:
            {
                var g = Guilds[eventPayload["guild_id"].ToString()];

                g.Emojis.Clear();

                JsonConvert.PopulateObject(payload, g);

                EmojiUpdate?.Invoke(g, eventPayload["emojis"].ToObject <List <Guild.Emoji> >());
                break;
            }

            case Events.GUILD_MEMBER_ADD:
            {
                var g = Guilds[eventPayload["guild_id"].ToString()];
                var m = eventPayload.ToObject <GuildMember>();

                if (!Users.ContainsKey(m.User.Id))
                {
                    Users.Add(m.User.Id, m.User);
                }
                else
                {
                    m.User = Users[m.User.Id];
                }

                g.Members.Add(m.User.Id, m);
                m.User.Guilds.Add(g);

                m.Guild = g;
                g.UpdateUserPermission(m);

                MemberAdd?.Invoke(g, m);
                break;
            }

            case Events.GUILD_MEMBER_REMOVE:
            {
                var g = Guilds[eventPayload["guild_id"].ToString()];
                var m = g.Members[eventPayload["user"]["id"].ToString()];

                g.Members.Remove(m.User.Id);
                m.User.Guilds.Remove(g);

                MemberRemove?.Invoke(g, m);
                break;
            }

            case Events.GUILD_MEMBER_UPDATE:
            {
                var g = Guilds[eventPayload["guild_id"].ToString()];
                var m = g.Members[eventPayload["user"]["id"].ToString()];

                JsonConvert.PopulateObject(payload, m);

                g.UpdateUserPermission(m);

                MemberUpdate?.Invoke(g, m);
                break;
            }

            case Events.GUILD_MEMBERS_CHUNK:
            {
                var g       = Guilds[eventPayload["guild_id"].ToString()];
                var members = eventPayload["members"].ToObject <List <GuildMember> >();

                foreach (var member in members)
                {
                    if (Users.ContainsKey(member.User.Id))
                    {
                        member.User = Users[member.User.Id];
                    }
                    else
                    {
                        Users.Add(member.User.Id, member.User);
                    }

                    g.Members.Remove(member.User.Id);
                    g.Members.Add(member.User.Id, member);
                }

                MemberChunkUpdate?.Invoke(g, members);
                break;
            }

            case Events.GUILD_ROLE_CREATE:
            {
                var g = Guilds[eventPayload["guild_id"].ToString()];
                var r = eventPayload["role"].ToObject <Guild.Role>();

                g.Roles.Add(r.Id, r);

                RoleCreate?.Invoke(g, r);
                break;
            }

            case Events.GUILD_ROLE_UPDATE:
            {
                var g = Guilds[eventPayload["guild_id"].ToString()];
                var r = g.Roles[eventPayload["role"]["id"].ToString()];

                JsonConvert.PopulateObject(eventPayload["role"].ToString(), r);

                RoleUpdate?.Invoke(g, r);
                break;
            }

            case Events.GUILD_ROLE_DELETE:
            {
                var g = Guilds[eventPayload["guild_id"].ToString()];
                var r = g.Roles[eventPayload["role_id"].ToString()];

                g.Roles.Remove(r.Id);

                RoleDelete?.Invoke(g, r);
                break;
            }

            case Events.MESSAGE_CREATE:
            {
                var message = eventPayload.ToObject <Message>();
                var c       = Channels[message.Channel_Id];

                message.Channel = c;

                if (string.IsNullOrEmpty(message.Webhook_Id))
                {
                    if (Users.ContainsKey(message.Author.Id))
                    {
                        message.Author = Users[message.Author.Id];
                    }
                }

                MessageCreate?.Invoke(c, message);
                break;
            }

            case Events.MESSAGE_UPDATE:
            {
                var message = eventPayload.ToObject <Message>();
                var c       = Channels[message.Channel_Id];

                MessageUpdate?.Invoke(c, message);
                break;
            }

            case Events.MESSAGE_DELETE:
            {
                var message = eventPayload.ToObject <Message>();
                var c       = Channels[message.Channel_Id];

                MessageDelete?.Invoke(c, message);
                break;
            }

            case Events.MESSAGE_DELETE_BULK:
            {
                var messages = eventPayload.ToObject <List <Message> >();
                var c        = Channels[eventPayload["channel_id"].ToString()];

                MessagesBulkDelete?.Invoke(c, messages);
                break;
            }

            case Events.PRESENCE_UPDATE:
            {
                var presense = eventPayload.ToObject <Guild.Presence>();
                var g        = Guilds[eventPayload["guild_id"].ToString()];

                if (g.Presences.ContainsKey(presense.User.Id))
                {
                    var p = g.Presences[presense.User.Id];

                    p.Game   = presense.Game;
                    p.Status = presense.Status;

                    presense = p;
                }
                else
                {
                    presense.User = Users[presense.User.Id];
                    g.Presences.Add(presense.User.Id, presense);
                }

                PresenceUpdate?.Invoke(g, presense);
                break;
            }
            }
        }
Exemplo n.º 14
0
        private void HandleDispatchEvent(GatewayPayload evnt, TaskCompletionSource <bool> readySignal)
        {
            switch (evnt.DispatchType)
            {
            case GatewayDispatchType.Ready:
                var readyEvent = evnt.Data as ReadyEvent;
                SetSession(readyEvent.SessionId);
                readySignal.TrySetResult(true);
                Ready?.Invoke(readyEvent);
                break;

            case GatewayDispatchType.Resumed:
                readySignal.TrySetResult(true);
                Resumed?.Invoke();
                break;

            case GatewayDispatchType.GuildCreate: GuildCreate?.Invoke(evnt.Data as GatewayGuild); break;

            case GatewayDispatchType.GuildUpdate: GuildUpdate?.Invoke(evnt.Data as Guild); break;

            case GatewayDispatchType.GuildDelete: GuildDelete?.Invoke(evnt.Data as UnavailableGuild); break;

            case GatewayDispatchType.ChannelCreate: ChannelCreate?.Invoke(evnt.Data as Channel); break;

            case GatewayDispatchType.ChannelUpdate: ChannelUpdate?.Invoke(evnt.Data as Channel); break;

            case GatewayDispatchType.ChannelDelete: ChannelDelete?.Invoke(evnt.Data as Channel); break;

            case GatewayDispatchType.ChannelPinsUpdate: ChannelPinsUpdate?.Invoke(evnt.Data as ChannelPinsUpdateEvent); break;

            case GatewayDispatchType.GuildMemberAdd: GuildMemberAdd?.Invoke(evnt.Data as GuildMemberAddEvent); break;

            case GatewayDispatchType.GuildMemberUpdate: GuildMemberUpdate?.Invoke(evnt.Data as GuildMemberUpdateEvent); break;

            case GatewayDispatchType.GuildMemberRemove: GuildMemberRemove?.Invoke(evnt.Data as GuildMemberRemoveEvent); break;

            case GatewayDispatchType.GuildMembersChunk: GuildMembersChunk?.Invoke(evnt.Data as GuildMembersChunkEvent); break;

            case GatewayDispatchType.GuildRoleCreate: GuildRoleCreate?.Invoke(evnt.Data as GuildRoleCreateEvent); break;

            case GatewayDispatchType.GuildRoleUpdate: GuildRoleUpdate?.Invoke(evnt.Data as GuildRoleUpdateEvent); break;

            case GatewayDispatchType.GuildRoleDelete: GuildRoleDelete?.Invoke(evnt.Data as GuildRoleDeleteEvent); break;

            case GatewayDispatchType.GuildBanAdd: GuildBanAdd?.Invoke(evnt.Data as GuildBanAddEvent); break;

            case GatewayDispatchType.GuildBanRemove: GuildBanRemove?.Invoke(evnt.Data as GuildBanRemoveEvent); break;

            case GatewayDispatchType.GuildEmojisUpdate: GuildEmojisUpdate?.Invoke(evnt.Data as GuildEmojiUpdateEvent); break;

            case GatewayDispatchType.GuildIntegrationsUpdate: GuildIntegrationsUpdate?.Invoke(evnt.Data as GuildIntegrationsUpdateEvent); break;

            case GatewayDispatchType.MessageCreate: MessageCreate?.Invoke(evnt.Data as Message); break;

            case GatewayDispatchType.MessageUpdate: MessageUpdate?.Invoke(evnt.Data as Message); break;

            case GatewayDispatchType.MessageDelete: MessageDelete?.Invoke(evnt.Data as MessageDeleteEvent); break;

            case GatewayDispatchType.MessageDeleteBulk: MessageDeleteBulk?.Invoke(evnt.Data as MessageDeleteBulkEvent); break;

            case GatewayDispatchType.MessageReactionAdd: MessageReactionAdd?.Invoke(evnt.Data as MessageReactionAddEvent); break;

            case GatewayDispatchType.MessageReactionRemove: MessageReactionRemove?.Invoke(evnt.Data as MessageReactionRemoveEvent); break;

            case GatewayDispatchType.MessageReactionRemoveAll: MessageReactionRemoveAll?.Invoke(evnt.Data as MessageReactionRemoveAllEvent); break;

            case GatewayDispatchType.PresenceUpdate: PresenceUpdate?.Invoke(evnt.Data as Presence); break;

            case GatewayDispatchType.UserUpdate: UserUpdate?.Invoke(evnt.Data as User); break;

            case GatewayDispatchType.TypingStart: TypingStart?.Invoke(evnt.Data as TypingStartEvent); break;

            case GatewayDispatchType.VoiceStateUpdate: VoiceStateUpdate?.Invoke(evnt.Data as VoiceState); break;

            case GatewayDispatchType.VoiceServerUpdate: VoiceServerUpdate?.Invoke(evnt.Data as VoiceServerUpdateEvent); break;

            case GatewayDispatchType.WebhooksUpdate: WebhooksUpdate?.Invoke(evnt.Data as WebhooksUpdateEvent); break;
            }
        }