use of org.javacord.api.entity.permission.Role in project Javacord by BtoBastian.
the class Server method canBanUser.
/**
* Checks if the given user can ban the other user.
* This method also considers the position of the user roles and the owner.
*
* @param user The user which "want" to ban the other user.
* @param userToBan The user which should be banned.
* @return Whether the given user can ban the other user or not.
*/
default boolean canBanUser(User user, User userToBan) {
// owner can always ban, regardless of role for example
if (isOwner(user)) {
return true;
}
// user cannot ban at all
if (!canBanUsers(user)) {
return false;
}
// only returns empty optional if user is not member of server
// but then canBanUsers should already have kicked in
Role ownRole = getHighestRole(user).orElseThrow(AssertionError::new);
Optional<Role> otherRole = getHighestRole(userToBan);
// otherRole empty => userToBan is not on the server => ban is allowed
boolean userToBanOnServer = otherRole.isPresent();
return !userToBanOnServer || (ownRole.compareTo(otherRole.get()) > 0);
}
use of org.javacord.api.entity.permission.Role in project Javacord by BtoBastian.
the class GuildMemberUpdateHandler method handle.
@Override
public void handle(JsonNode packet) {
api.getPossiblyUnreadyServerById(packet.get("guild_id").asLong()).map(server -> (ServerImpl) server).ifPresent(server -> {
MemberImpl newMember = new MemberImpl(api, server, packet, null);
Member oldMember = server.getRealMemberById(newMember.getId()).orElse(null);
api.addMemberToCacheOrReplaceExisting(newMember);
if (oldMember == null) {
// Should only happen shortly after startup and is unproblematic
return;
}
if (!newMember.getNickname().equals(oldMember.getNickname())) {
UserChangeNicknameEvent event = new UserChangeNicknameEventImpl(newMember, oldMember);
api.getEventDispatcher().dispatchUserChangeNicknameEvent(server, server, newMember.getUser(), event);
}
if (!newMember.getServerAvatarHash().equals(oldMember.getServerAvatarHash())) {
UserChangeServerAvatarEvent event = new UserChangeServerAvatarEventImpl(newMember, oldMember);
api.getEventDispatcher().dispatchUserChangeServerAvatarEvent(server, server, newMember.getUser(), event);
}
if (newMember.isPending() != oldMember.isPending()) {
UserChangePendingEvent event = new UserChangePendingEventImpl(oldMember, newMember);
api.getEventDispatcher().dispatchUserChangePendingEvent(server, server, newMember.getUser(), event);
}
if (packet.has("roles")) {
JsonNode jsonRoles = packet.get("roles");
Collection<Role> newRoles = new HashSet<>();
Collection<Role> oldRoles = oldMember.getRoles();
Collection<Role> intersection = new HashSet<>();
for (JsonNode roleIdJson : jsonRoles) {
api.getRoleById(roleIdJson.asText()).map(role -> {
newRoles.add(role);
return role;
}).filter(oldRoles::contains).ifPresent(intersection::add);
}
// Added roles
Collection<Role> addedRoles = new ArrayList<>(newRoles);
addedRoles.removeAll(intersection);
for (Role role : addedRoles) {
if (role.isEveryoneRole()) {
continue;
}
UserRoleAddEvent event = new UserRoleAddEventImpl(role, newMember);
api.getEventDispatcher().dispatchUserRoleAddEvent((DispatchQueueSelector) role.getServer(), role, role.getServer(), newMember.getId(), event);
}
// Removed roles
Collection<Role> removedRoles = new ArrayList<>(oldRoles);
removedRoles.removeAll(intersection);
for (Role role : removedRoles) {
if (role.isEveryoneRole()) {
continue;
}
UserRoleRemoveEvent event = new UserRoleRemoveEventImpl(role, newMember);
api.getEventDispatcher().dispatchUserRoleRemoveEvent((DispatchQueueSelector) role.getServer(), role, role.getServer(), newMember.getId(), event);
}
}
if (newMember.getUser().isYourself()) {
Set<Long> unreadableChannels = server.getTextChannels().stream().filter(((Predicate<ServerTextChannel>) ServerTextChannel::canYouSee).negate()).map(ServerTextChannel::getId).collect(Collectors.toSet());
api.forEachCachedMessageWhere(msg -> unreadableChannels.contains(msg.getChannel().getId()), msg -> {
api.removeMessageFromCache(msg.getId());
((MessageCacheImpl) msg.getChannel().getMessageCache()).removeMessage(msg);
});
}
// https://github.com/discord/discord-api-docs/pull/1307#issuecomment-581561519
if (oldMember.getUser() != null) {
UserImpl oldUser = (UserImpl) oldMember.getUser();
boolean userChanged = false;
UserImpl updatedUser = oldUser.replacePartialUserData(packet.get("user"));
if (packet.get("user").has("username")) {
String newName = packet.get("user").get("username").asText();
String oldName = oldUser.getName();
if (!oldName.equals(newName)) {
dispatchUserChangeNameEvent(updatedUser, newName, oldName);
userChanged = true;
}
}
if (packet.get("user").has("discriminator")) {
String newDiscriminator = packet.get("user").get("discriminator").asText();
String oldDiscriminator = oldUser.getDiscriminator();
if (!oldDiscriminator.equals(newDiscriminator)) {
dispatchUserChangeDiscriminatorEvent(updatedUser, newDiscriminator, oldDiscriminator);
userChanged = true;
}
}
if (packet.get("user").has("avatar")) {
String newAvatarHash = packet.get("user").get("avatar").asText(null);
String oldAvatarHash = oldUser.getAvatarHash().orElse(null);
if (!Objects.deepEquals(newAvatarHash, oldAvatarHash)) {
dispatchUserChangeAvatarEvent(updatedUser, newAvatarHash, oldAvatarHash);
userChanged = true;
}
}
if (userChanged) {
api.updateUserOfAllMembers(updatedUser);
}
}
});
}
use of org.javacord.api.entity.permission.Role in project Javacord by BtoBastian.
the class GuildRoleCreateHandler method handle.
@Override
public void handle(JsonNode packet) {
long serverId = Long.parseLong(packet.get("guild_id").asText());
api.getPossiblyUnreadyServerById(serverId).ifPresent(server -> {
Role role = ((ServerImpl) server).getOrCreateRole(packet.get("role"));
RoleCreateEvent event = new RoleCreateEventImpl(role);
api.getEventDispatcher().dispatchRoleCreateEvent((DispatchQueueSelector) server, server, event);
});
}
use of org.javacord.api.entity.permission.Role 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);
});
}
}
use of org.javacord.api.entity.permission.Role in project Javacord by BtoBastian.
the class ChannelUpdateHandler method dispatchServerChannelChangeOverwrittenPermissionsEvent.
/**
* Dispatches a ServerChannelChangeOverwrittenPermissionsEvent.
*
* @param channel The channel of the event.
* @param newPermissions The new overwritten permissions.
* @param oldPermissions The old overwritten permissions.
* @param entityId The id of the entity.
* @param entity The entity of the event.
*/
private void dispatchServerChannelChangeOverwrittenPermissionsEvent(ServerChannel channel, Permissions newPermissions, Permissions oldPermissions, long entityId, DiscordEntity entity) {
if (newPermissions.equals(oldPermissions)) {
// any of its values. We don't need to dispatch an event for this.
return;
}
ServerChannelChangeOverwrittenPermissionsEvent event = new ServerChannelChangeOverwrittenPermissionsEventImpl(channel, newPermissions, oldPermissions, entityId, entity);
api.getEventDispatcher().dispatchServerChannelChangeOverwrittenPermissionsEvent((DispatchQueueSelector) channel.getServer(), (entity instanceof Role) ? (Role) entity : null, channel.getServer(), channel, (entity instanceof User) ? (User) entity : null, event);
}
Aggregations