Search in sources :

Example 1 with RegularServerChannel

use of org.javacord.api.entity.channel.RegularServerChannel in project Javacord by BtoBastian.

the class ChannelUpdateHandler method handleRegularServerChannel.

private void handleRegularServerChannel(JsonNode jsonChannel) {
    long channelId = jsonChannel.get("id").asLong();
    Optional<RegularServerChannel> optionalChannel = api.getRegularServerChannelById(channelId);
    if (!optionalChannel.isPresent()) {
        LoggerUtil.logMissingChannel(logger, channelId);
        return;
    }
    RegularServerChannelImpl channel = (RegularServerChannelImpl) optionalChannel.get();
    ServerImpl server = (ServerImpl) channel.getServer();
    final AtomicBoolean areYouAffected = new AtomicBoolean(false);
    ChannelCategory oldCategory = channel.asCategorizable().flatMap(Categorizable::getCategory).orElse(null);
    ChannelCategory newCategory = jsonChannel.hasNonNull("parent_id") ? channel.getServer().getChannelCategoryById(jsonChannel.get("parent_id").asLong(-1)).orElse(null) : null;
    final RegularServerChannelImpl regularServerChannel = (RegularServerChannelImpl) channel;
    final int oldRawPosition = regularServerChannel.getRawPosition();
    final int newRawPosition = jsonChannel.get("position").asInt();
    if (oldRawPosition != newRawPosition || !Objects.deepEquals(oldCategory, newCategory)) {
        final int oldPosition = regularServerChannel.getPosition();
        if (regularServerChannel instanceof ServerTextChannelImpl) {
            ((ServerTextChannelImpl) regularServerChannel).setParentId(newCategory == null ? -1 : newCategory.getId());
        } else if (regularServerChannel instanceof ServerVoiceChannelImpl) {
            ((ServerVoiceChannelImpl) regularServerChannel).setParentId(newCategory == null ? -1 : newCategory.getId());
        }
        regularServerChannel.setRawPosition(newRawPosition);
        final int newPosition = regularServerChannel.getPosition();
        final ServerChannelChangePositionEvent event = new ServerChannelChangePositionEventImpl(regularServerChannel, newPosition, oldPosition, newRawPosition, oldRawPosition, newCategory, oldCategory);
        if (server.isReady()) {
            api.getEventDispatcher().dispatchServerChannelChangePositionEvent((DispatchQueueSelector) regularServerChannel.getServer(), regularServerChannel.getServer(), regularServerChannel, event);
        }
    }
    Collection<Long> rolesWithOverwrittenPermissions = new HashSet<>();
    Collection<Long> usersWithOverwrittenPermissions = new HashSet<>();
    if (jsonChannel.has("permission_overwrites") && !jsonChannel.get("permission_overwrites").isNull()) {
        for (JsonNode permissionOverwriteJson : jsonChannel.get("permission_overwrites")) {
            Permissions oldOverwrittenPermissions;
            ConcurrentHashMap<Long, Permissions> overwrittenPermissions;
            long entityId = permissionOverwriteJson.get("id").asLong();
            Optional<DiscordEntity> entity;
            switch(permissionOverwriteJson.get("type").asInt()) {
                case 0:
                    Role role = server.getRoleById(entityId).orElseThrow(() -> new IllegalStateException("Received channel update event with unknown role!"));
                    entity = Optional.of(role);
                    oldOverwrittenPermissions = regularServerChannel.getOverwrittenPermissions(role);
                    overwrittenPermissions = regularServerChannel.getInternalOverwrittenRolePermissions();
                    rolesWithOverwrittenPermissions.add(entityId);
                    break;
                case 1:
                    oldOverwrittenPermissions = regularServerChannel.getOverwrittenUserPermissions().getOrDefault(entityId, PermissionsImpl.EMPTY_PERMISSIONS);
                    entity = api.getCachedUserById(entityId).map(DiscordEntity.class::cast);
                    overwrittenPermissions = regularServerChannel.getInternalOverwrittenUserPermissions();
                    usersWithOverwrittenPermissions.add(entityId);
                    break;
                default:
                    throw new IllegalStateException("Permission overwrite object with unknown type: " + permissionOverwriteJson);
            }
            long allow = permissionOverwriteJson.get("allow").asLong(0);
            long deny = permissionOverwriteJson.get("deny").asLong(0);
            Permissions newOverwrittenPermissions = new PermissionsImpl(allow, deny);
            if (!newOverwrittenPermissions.equals(oldOverwrittenPermissions)) {
                overwrittenPermissions.put(entityId, newOverwrittenPermissions);
                if (server.isReady()) {
                    dispatchServerChannelChangeOverwrittenPermissionsEvent(channel, newOverwrittenPermissions, oldOverwrittenPermissions, entityId, entity.orElse(null));
                    areYouAffected.compareAndSet(false, entityId == api.getYourself().getId());
                    entity.filter(e -> e instanceof Role).map(Role.class::cast).ifPresent(role -> areYouAffected.compareAndSet(false, role.getUsers().stream().anyMatch(User::isYourself)));
                }
            }
        }
    }
    ConcurrentHashMap<Long, Permissions> overwrittenRolePermissions;
    ConcurrentHashMap<Long, Permissions> overwrittenUserPermissions;
    overwrittenRolePermissions = regularServerChannel.getInternalOverwrittenRolePermissions();
    overwrittenUserPermissions = regularServerChannel.getInternalOverwrittenUserPermissions();
    Iterator<Map.Entry<Long, Permissions>> userIt = overwrittenUserPermissions.entrySet().iterator();
    while (userIt.hasNext()) {
        Map.Entry<Long, Permissions> entry = userIt.next();
        if (usersWithOverwrittenPermissions.contains(entry.getKey())) {
            continue;
        }
        Permissions oldPermissions = entry.getValue();
        userIt.remove();
        if (server.isReady()) {
            dispatchServerChannelChangeOverwrittenPermissionsEvent(channel, PermissionsImpl.EMPTY_PERMISSIONS, oldPermissions, entry.getKey(), api.getCachedUserById(entry.getKey()).orElse(null));
            areYouAffected.compareAndSet(false, entry.getKey() == api.getYourself().getId());
        }
    }
    Iterator<Map.Entry<Long, Permissions>> roleIt = overwrittenRolePermissions.entrySet().iterator();
    while (roleIt.hasNext()) {
        Map.Entry<Long, Permissions> entry = roleIt.next();
        if (rolesWithOverwrittenPermissions.contains(entry.getKey())) {
            continue;
        }
        api.getRoleById(entry.getKey()).ifPresent(role -> {
            Permissions oldPermissions = entry.getValue();
            roleIt.remove();
            if (server.isReady()) {
                dispatchServerChannelChangeOverwrittenPermissionsEvent(channel, PermissionsImpl.EMPTY_PERMISSIONS, oldPermissions, role.getId(), role);
                areYouAffected.compareAndSet(false, role.getUsers().stream().anyMatch(User::isYourself));
            }
        });
    }
    if (areYouAffected.get() && !channel.canYouSee()) {
        api.forEachCachedMessageWhere(msg -> msg.getChannel().getId() == channelId, msg -> {
            api.removeMessageFromCache(msg.getId());
            ((MessageCacheImpl) ((TextChannel) channel).getMessageCache()).removeMessage(msg);
        });
    }
}
Also used : User(org.javacord.api.entity.user.User) RegularServerChannel(org.javacord.api.entity.channel.RegularServerChannel) RegularServerChannelImpl(org.javacord.core.entity.channel.RegularServerChannelImpl) JsonNode(com.fasterxml.jackson.databind.JsonNode) ServerChannelChangePositionEvent(org.javacord.api.event.channel.server.ServerChannelChangePositionEvent) ServerImpl(org.javacord.core.entity.server.ServerImpl) PermissionsImpl(org.javacord.core.entity.permission.PermissionsImpl) Permissions(org.javacord.api.entity.permission.Permissions) ServerTextChannelImpl(org.javacord.core.entity.channel.ServerTextChannelImpl) HashSet(java.util.HashSet) ServerVoiceChannelImpl(org.javacord.core.entity.channel.ServerVoiceChannelImpl) Role(org.javacord.api.entity.permission.Role) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MessageCacheImpl(org.javacord.core.util.cache.MessageCacheImpl) ServerChannelChangePositionEventImpl(org.javacord.core.event.channel.server.ServerChannelChangePositionEventImpl) ChannelCategory(org.javacord.api.entity.channel.ChannelCategory) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) DiscordEntity(org.javacord.api.entity.DiscordEntity)

Example 2 with RegularServerChannel

use of org.javacord.api.entity.channel.RegularServerChannel in project Javacord by BtoBastian.

the class ServerImpl method getChannels.

@Override
public List<ServerChannel> getChannels() {
    final List<ServerChannel> channels = getUnorderedChannels().stream().filter(channel -> channel.asCategorizable().map(categorizable -> !categorizable.getCategory().isPresent()).orElse(false)).map(Channel::asRegularServerChannel).filter(Optional::isPresent).map(Optional::get).sorted(Comparator.<RegularServerChannel>comparingInt(channel -> channel.getType().getId()).thenComparing(RegularServerChannelImpl.COMPARE_BY_RAW_POSITION)).collect(Collectors.toList());
    getChannelCategories().forEach(category -> {
        channels.add(category);
        channels.addAll(category.getChannels());
    });
    final Map<ServerTextChannel, List<ServerThreadChannel>> serverTextChannelThreads = new HashMap<>();
    getThreadChannels().forEach(serverThreadChannel -> {
        final ServerTextChannel serverTextChannel = serverThreadChannel.getParent();
        serverTextChannelThreads.merge(serverTextChannel, new ArrayList<>(Collections.singletonList(serverThreadChannel)), (serverThreadChannels, serverThreadChannels2) -> {
            serverThreadChannels.addAll(serverThreadChannels2);
            return new ArrayList<>(serverThreadChannels);
        });
    });
    serverTextChannelThreads.forEach((serverTextChannel, serverThreadChannels) -> channels.addAll(channels.indexOf(serverTextChannel) + 1, serverThreadChannels));
    return Collections.unmodifiableList(channels);
}
Also used : AudioConnection(org.javacord.api.audio.AudioConnection) RegularServerChannelImpl(org.javacord.core.entity.channel.RegularServerChannelImpl) ServerChannel(org.javacord.api.entity.channel.ServerChannel) ServerVoiceChannelImpl(org.javacord.core.entity.channel.ServerVoiceChannelImpl) IconImpl(org.javacord.core.entity.IconImpl) Member(org.javacord.core.entity.user.Member) ServerThreadChannel(org.javacord.api.entity.channel.ServerThreadChannel) URL(java.net.URL) AuditLogImpl(org.javacord.core.entity.auditlog.AuditLogImpl) RestMethod(org.javacord.core.util.rest.RestMethod) ServerStageVoiceChannelImpl(org.javacord.core.entity.channel.ServerStageVoiceChannelImpl) StickerImpl(org.javacord.core.entity.sticker.StickerImpl) Ban(org.javacord.api.entity.server.Ban) BoostLevel(org.javacord.api.entity.server.BoostLevel) RoleImpl(org.javacord.core.entity.permission.RoleImpl) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ServerTextChannelImpl(org.javacord.core.entity.channel.ServerTextChannelImpl) Locale(java.util.Locale) Map(java.util.Map) RestRequest(org.javacord.core.util.rest.RestRequest) JsonNode(com.fasterxml.jackson.databind.JsonNode) VanityUrlCodeImpl(org.javacord.core.entity.VanityUrlCodeImpl) AuditLog(org.javacord.api.entity.auditlog.AuditLog) Webhook(org.javacord.api.entity.webhook.Webhook) NsfwLevel(org.javacord.api.entity.server.NsfwLevel) Activity(org.javacord.api.entity.activity.Activity) InternalServerAttachableListenerManager(org.javacord.core.listener.server.InternalServerAttachableListenerManager) InviteImpl(org.javacord.core.entity.server.invite.InviteImpl) UserImpl(org.javacord.core.entity.user.UserImpl) Collection(java.util.Collection) ChannelCategoryImpl(org.javacord.core.entity.channel.ChannelCategoryImpl) WebhookImpl(org.javacord.core.entity.webhook.WebhookImpl) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) SlashCommand(org.javacord.api.interaction.SlashCommand) MultiFactorAuthenticationLevel(org.javacord.api.entity.server.MultiFactorAuthenticationLevel) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) VanityUrlCode(org.javacord.api.entity.VanityUrlCode) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) ServerVoiceChannel(org.javacord.api.entity.channel.ServerVoiceChannel) Objects(java.util.Objects) ExplicitContentFilterLevel(org.javacord.api.entity.server.ExplicitContentFilterLevel) RestEndpoint(org.javacord.core.util.rest.RestEndpoint) Sticker(org.javacord.api.entity.sticker.Sticker) List(java.util.List) Logger(org.apache.logging.log4j.Logger) AudioConnectionImpl(org.javacord.core.audio.AudioConnectionImpl) JsonNodeFactory(com.fasterxml.jackson.databind.node.JsonNodeFactory) Role(org.javacord.api.entity.permission.Role) Optional(java.util.Optional) IncomingWebhookImpl(org.javacord.core.entity.webhook.IncomingWebhookImpl) AuditLogActionType(org.javacord.api.entity.auditlog.AuditLogActionType) ActiveThreads(org.javacord.api.entity.server.ActiveThreads) RichInvite(org.javacord.api.entity.server.invite.RichInvite) DispatchQueueSelector(org.javacord.core.util.event.DispatchQueueSelector) ChannelType(org.javacord.api.entity.channel.ChannelType) KnownCustomEmoji(org.javacord.api.entity.emoji.KnownCustomEmoji) ActivityImpl(org.javacord.core.entity.activity.ActivityImpl) ServerThreadChannelImpl(org.javacord.core.entity.channel.ServerThreadChannelImpl) Channel(org.javacord.api.entity.channel.Channel) DiscordClient(org.javacord.api.entity.DiscordClient) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) IncomingWebhook(org.javacord.api.entity.webhook.IncomingWebhook) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) DiscordEntity(org.javacord.api.entity.DiscordEntity) Region(org.javacord.api.entity.Region) Icon(org.javacord.api.entity.Icon) ServerTextChannel(org.javacord.api.entity.channel.ServerTextChannel) Cleanupable(org.javacord.core.util.Cleanupable) DefaultMessageNotificationLevel(org.javacord.api.entity.server.DefaultMessageNotificationLevel) ReentrantLock(java.util.concurrent.locks.ReentrantLock) MalformedURLException(java.net.MalformedURLException) MemberImpl(org.javacord.core.entity.user.MemberImpl) DiscordApiImpl(org.javacord.core.DiscordApiImpl) AuditLogEntry(org.javacord.api.entity.auditlog.AuditLogEntry) Javacord(org.javacord.api.Javacord) Consumer(java.util.function.Consumer) LoggerUtil(org.javacord.core.util.logging.LoggerUtil) ServerFeature(org.javacord.api.entity.server.ServerFeature) ChannelCategory(org.javacord.api.entity.channel.ChannelCategory) ConcurrentSkipListSet(java.util.concurrent.ConcurrentSkipListSet) ServerStageVoiceChannel(org.javacord.api.entity.channel.ServerStageVoiceChannel) Intent(org.javacord.api.entity.intent.Intent) User(org.javacord.api.entity.user.User) RestRequestResult(org.javacord.core.util.rest.RestRequestResult) VerificationLevel(org.javacord.api.entity.server.VerificationLevel) UserStatus(org.javacord.api.entity.user.UserStatus) DiscordApi(org.javacord.api.DiscordApi) Server(org.javacord.api.entity.server.Server) Comparator(java.util.Comparator) Collections(java.util.Collections) RegularServerChannel(org.javacord.api.entity.channel.RegularServerChannel) ServerTextChannel(org.javacord.api.entity.channel.ServerTextChannel) Optional(java.util.Optional) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ServerChannel(org.javacord.api.entity.channel.ServerChannel) ServerThreadChannel(org.javacord.api.entity.channel.ServerThreadChannel) ServerVoiceChannel(org.javacord.api.entity.channel.ServerVoiceChannel) Channel(org.javacord.api.entity.channel.Channel) ServerTextChannel(org.javacord.api.entity.channel.ServerTextChannel) ServerStageVoiceChannel(org.javacord.api.entity.channel.ServerStageVoiceChannel) RegularServerChannel(org.javacord.api.entity.channel.RegularServerChannel) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) ServerChannel(org.javacord.api.entity.channel.ServerChannel) RegularServerChannel(org.javacord.api.entity.channel.RegularServerChannel)

Aggregations

JsonNode (com.fasterxml.jackson.databind.JsonNode)2 HashSet (java.util.HashSet)2 Map (java.util.Map)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 DiscordEntity (org.javacord.api.entity.DiscordEntity)2 ChannelCategory (org.javacord.api.entity.channel.ChannelCategory)2 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)1 JsonNodeFactory (com.fasterxml.jackson.databind.node.JsonNodeFactory)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 Instant (java.time.Instant)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 Comparator (java.util.Comparator)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Locale (java.util.Locale)1 Objects (java.util.Objects)1 Optional (java.util.Optional)1