Skip to content

Commit

Permalink
Migrate to unique names instead of snowflake
Browse files Browse the repository at this point in the history
  • Loading branch information
nelifs committed Dec 9, 2024
1 parent 39791c5 commit 849d563
Show file tree
Hide file tree
Showing 26 changed files with 118 additions and 120 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,59 +44,59 @@ public ChannelDTO createChannel(@RequestAttribute(value = AttributesConstants.US
}

@Operation(summary = "Get channel")
@GetMapping("/{id}")
@GetMapping("/{name}")
public ChannelDTO getChannel(@RequestAttribute(value = AttributesConstants.CHANNEL) Channel channel) {
return new ChannelDTO(channel);
}

@Operation(summary = "Edit channel")
@PatchMapping("/{id}")
@PatchMapping("/{name}")
public ChannelDTO editChannel(@RequestAttribute(value = AttributesConstants.MEMBER) Member member, @RequestAttribute(value = AttributesConstants.CHANNEL) Channel channel, @Valid @RequestBody ChannelEditDTO body) throws MissingPermissionsException {
channel = channelsService.editChannel(member, channel, body);

return new ChannelDTO(channel);
}

@Operation(summary = "Delete channel")
@DeleteMapping("/{id}")
@DeleteMapping("/{name}")
public OkDTO deleteChannel(@RequestAttribute(value = AttributesConstants.USER) User user, @RequestAttribute(value = AttributesConstants.CHANNEL) Channel channel) throws MissingPermissionsException {
channelsService.deleteChannel(channel, user);

return new OkDTO(true);
}

@Operation(summary = "Join channel")
@PutMapping("/{id}/members/@me")
public MemberDTO joinChannel(@RequestAttribute(value = AttributesConstants.USER) User user, @RequestAttribute(value = AttributesConstants.CHANNEL) Channel channel, @PathVariable long id) throws MemberAlreadyInChannelException {
@PutMapping("/{name}/members/@me")
public MemberDTO joinChannel(@RequestAttribute(value = AttributesConstants.USER) User user, @RequestAttribute(value = AttributesConstants.CHANNEL) Channel channel) throws MemberAlreadyInChannelException {
Member member = channelsService.joinUser(channel, user);

return new MemberDTO(member);
}

@Operation(summary = "Leave channel")
@DeleteMapping("/{id}/members/@me")
@DeleteMapping("/{name}/members/@me")
public OkDTO leaveChannel(@RequestAttribute(value = AttributesConstants.USER) User user, @RequestAttribute(value = AttributesConstants.CHANNEL) Channel channel) throws MemberInChannelNotFoundException {
channelsService.leaveUser(channel, user);

return new OkDTO(true);
}

@Operation(summary = "Get member")
@GetMapping("/{id}/members/{memberId}")
public MemberDTO getMember(@RequestAttribute(value = AttributesConstants.USER) User user, @RequestAttribute(value = AttributesConstants.CHANNEL) Channel channel, @PathVariable String memberId) throws MemberInChannelNotFoundException {
if (Objects.equals(memberId, "@me")) {
memberId = user.getId();
@GetMapping("/{name}/members/{memberUsername}")
public MemberDTO getMember(@RequestAttribute(value = AttributesConstants.USER) User user, @RequestAttribute(value = AttributesConstants.CHANNEL) Channel channel, @PathVariable String memberUsername) throws MemberInChannelNotFoundException {
if (Objects.equals(memberUsername, "@me")) {
memberUsername = user.getUsername();
}

Member member = channelsService.getMember(channel, memberId);
Member member = channelsService.getMember(channel, memberUsername);

if (member == null) throw new MemberInChannelNotFoundException();

return new MemberDTO(member);
}

@Operation(summary = "Get members")
@GetMapping("/{id}/members")
@GetMapping("/{name}/members")
public List<MemberDTO> getMembers(@RequestAttribute(value = AttributesConstants.CHANNEL) Channel channel) {
return channelsService.getMembers(channel);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,16 @@ public MessagesController(MessagesService messagesService) {
}

@Operation(summary = "Get messages")
@GetMapping("/channel/{channelId}")
@GetMapping("/channel/{name}")
public List<MessageDTO> getMessages(@RequestAttribute(value = AttributesConstants.USER) User user, @RequestAttribute(value = AttributesConstants.CHANNEL) Channel channel, @RequestParam(required = false, defaultValue = "0") long before, @RequestParam(required = false, defaultValue = "0") int limit) {
log.info("MESSAGES ({}, {}) from CHANNEL ({}) by USER ({}, {}) requested", before, limit, channel.getId(), user.getId(), user.getEmail());

return messagesService.getMessages(before, limit, channel);
}

@Operation(summary = "Get message")
@GetMapping("/channel/{channelId}/{id}")
public MessagesDTO getMessage(@RequestAttribute(value = AttributesConstants.USER) User user, @RequestAttribute(value = AttributesConstants.CHANNEL) Channel channel, @PathVariable String id) throws MessageNotFoundException {
@GetMapping("/channel/{name}/{id}")
public MessagesDTO getMessage(@RequestAttribute(value = AttributesConstants.USER) User user, @RequestAttribute(value = AttributesConstants.CHANNEL) Channel channel, @PathVariable long id) throws MessageNotFoundException {
log.info("MESSAGE ({}) from CHANNEL ({}) by USER ({}, {}) requested", id, channel.getId(), user.getId(), user.getEmail());

List<Message> message = List.of(messagesService.getMessage(id, channel));
Expand All @@ -54,7 +54,7 @@ public MessagesDTO getMessage(@RequestAttribute(value = AttributesConstants.USER
}

@Operation(summary = "Create message")
@PostMapping("/channel/{channelId}")
@PostMapping("/channel/{name}")
public OkDTO createMessage(@RequestAttribute(value = AttributesConstants.USER) User user, @RequestAttribute(value = AttributesConstants.CHANNEL) Channel channel, @Valid @RequestBody MessageCreateDTO body) {
log.info("MESSAGE post to CHANNEL ({}) by USER ({}, {}) requested", channel.getId(), user.getId(), user.getEmail());

Expand All @@ -64,8 +64,8 @@ public OkDTO createMessage(@RequestAttribute(value = AttributesConstants.USER) U
}

@Operation(summary = "Delete message")
@DeleteMapping("/channel/{channelId}/{id}")
public OkDTO deleteMessage(@RequestAttribute(value = AttributesConstants.USER) User user, @RequestAttribute(value = AttributesConstants.MEMBER) Member member, @RequestAttribute(value = AttributesConstants.CHANNEL) Channel channel, @PathVariable String id) throws MessageNotFoundException, MissingPermissionsException {
@DeleteMapping("/channel/{name}/{id}")
public OkDTO deleteMessage(@RequestAttribute(value = AttributesConstants.USER) User user, @RequestAttribute(value = AttributesConstants.MEMBER) Member member, @RequestAttribute(value = AttributesConstants.CHANNEL) Channel channel, @PathVariable long id) throws MessageNotFoundException, MissingPermissionsException {
log.info("MESSAGE ({}) delete from CHANNEL ({}) by USER ({}, {}) requested", id, channel.getId(), user.getId(), user.getEmail());

messagesService.deleteMessage(id, member, channel);
Expand All @@ -74,8 +74,8 @@ public OkDTO deleteMessage(@RequestAttribute(value = AttributesConstants.USER) U
}

@Operation(summary = "Edit message")
@PatchMapping("/channel/{channelId}/{id}")
public MessagesDTO editMessage(@RequestAttribute(value = AttributesConstants.USER) User user, @RequestAttribute(value = AttributesConstants.MEMBER) Member member, @RequestAttribute(value = AttributesConstants.CHANNEL) Channel channel, @Valid @RequestBody MessageCreateDTO body, @PathVariable String id) throws MessageNotFoundException, MissingPermissionsException {
@PatchMapping("/channel/{name}/{id}")
public MessagesDTO editMessage(@RequestAttribute(value = AttributesConstants.USER) User user, @RequestAttribute(value = AttributesConstants.MEMBER) Member member, @RequestAttribute(value = AttributesConstants.CHANNEL) Channel channel, @Valid @RequestBody MessageCreateDTO body, @PathVariable long id) throws MessageNotFoundException, MissingPermissionsException {
log.info("MESSAGE ({}) patch in CHANNEL ({}) by USER ({}, {}) requested", id, channel.getId(), user.getId(), user.getEmail());

List<Message> message = List.of(messagesService.editMessage(id, channel, member, body));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,13 @@ public UsersController(UsersService usersService) {
}

@Operation(summary = "Get user")
@GetMapping("/{userKey}")
public UserDTO getUser(@RequestAttribute(value = AttributesConstants.USER) User authenticatedUser, @PathVariable String userKey) throws UserNotFoundException {
if (Objects.equals(userKey, "@me")) {
@GetMapping("/{username}")
public UserDTO getUser(@RequestAttribute(value = AttributesConstants.USER) User authenticatedUser, @PathVariable String username) throws UserNotFoundException {
if (Objects.equals(username, "@me")) {
return new UserDTO(authenticatedUser, true);
}

return new UserDTO(usersService.getUser(userKey), false);
return new UserDTO(usersService.getUser(username), false);
}

@Operation(summary = "Edit user")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
import su.foxogram.models.Message;
import su.foxogram.models.User;
import su.foxogram.repositories.MessageRepository;
import su.foxogram.structures.Snowflake;

import java.util.List;
import java.util.Objects;
Expand All @@ -37,16 +36,15 @@ public List<MessageDTO> getMessages(long before, int limit, Channel channel) {

return messagesArray.stream()
.map(message -> new MessageDTO(
message.getId(),
message.getContent(),
message.getAuthor().getUserId(),
message.getChannel().getId(),
message.getAuthor().getUser().getUsername(),
message.getChannel().getName(),
message.getAttachments()
))
.collect(Collectors.toList());
}

public Message getMessage(String id, Channel channel) throws MessageNotFoundException {
public Message getMessage(long id, Channel channel) throws MessageNotFoundException {
Message message = messageRepository.findByChannelAndId(channel, id);

if (message == null) throw new MessageNotFoundException();
Expand All @@ -57,35 +55,34 @@ public Message getMessage(String id, Channel channel) throws MessageNotFoundExce
}

public void addMessage(Channel channel, User user, MessageCreateDTO body) {
String id = Snowflake.create();
String authorId = user.getId();
long authorId = user.getId();
long timestamp = System.currentTimeMillis();
List<String> attachments = body.getAttachments();
String content = body.getContent();

Message message = new Message(id, channel, content, authorId, timestamp, attachments);
Message message = new Message(0, channel, content, authorId, timestamp, attachments);

messageRepository.save(message);
log.info("MESSAGE ({}) to CHANNEL ({}) saved to database successfully", id, channel.getId());
log.info("MESSAGE ({}) to CHANNEL ({}) saved to database successfully", message.getId(), channel.getId());
}

public void deleteMessage(String id, Member member, Channel channel) throws MessageNotFoundException, MissingPermissionsException {
public void deleteMessage(long id, Member member, Channel channel) throws MessageNotFoundException, MissingPermissionsException {
Message message = messageRepository.findByChannelAndId(channel, id);

if (message == null) throw new MessageNotFoundException();
if (!Objects.equals(message.getAuthor().getUserId(), member.getUserId()) || member.hasAnyPermission(MemberConstants.Permissions.ADMIN, MemberConstants.Permissions.MANAGE_MESSAGES))
if (!Objects.equals(message.getAuthor().getUsername(), member.getUsername()) || member.hasAnyPermission(MemberConstants.Permissions.ADMIN, MemberConstants.Permissions.MANAGE_MESSAGES))
throw new MissingPermissionsException();

messageRepository.delete(message);
log.info("MESSAGE ({}) in CHANNEL ({}) deleted successfully", id, channel.getId());
}

public Message editMessage(String id, Channel channel, Member member, MessageCreateDTO body) throws MessageNotFoundException, MissingPermissionsException {
public Message editMessage(long id, Channel channel, Member member, MessageCreateDTO body) throws MessageNotFoundException, MissingPermissionsException {
Message message = messageRepository.findByChannelAndId(channel, id);
String content = body.getContent();

if (message == null) throw new MessageNotFoundException();
if (!Objects.equals(message.getAuthor().getUserId(), member.getUserId()))
if (!Objects.equals(message.getAuthor().getUsername(), member.getUsername()))
throw new MissingPermissionsException();

message.setContent(content);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@
import su.foxogram.util.CodeGenerator;
import su.foxogram.util.Encryptor;

import java.util.Optional;

@Slf4j
@Service
public class UsersService {
Expand All @@ -34,12 +32,12 @@ public UsersService(UserRepository userRepository, EmailService emailService, Co
this.codeRepository = codeRepository;
}

public User getUser(String key) throws UserNotFoundException {
Optional<User> optionalUser = userRepository.findByIdOrUsername(key, key);
public User getUser(String username) throws UserNotFoundException {
User user = userRepository.findByUsername(username);

if (optionalUser.isEmpty()) throw new UserNotFoundException();
if (user == null) throw new UserNotFoundException();

return optionalUser.get();
return user;
}

public User editUser(User user, UserEditDTO body) throws UserCredentialsDuplicateException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,16 @@
@Getter
@Setter
public class ChannelDTO {
private String id;

private String name;

private int type;

private String ownerId;
private String owner;

public ChannelDTO(Channel channel) {
this.id = channel.getId();
this.name = channel.getName();
this.type = channel.getType();
this.ownerId = channel.getOwnerId();
this.owner = channel.getOwner();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,12 @@
@Getter
@Setter
public class MemberDTO {
private String userId;

private String channelId;
private String channelName;

private long permissions;

public MemberDTO(Member member) {
this.userId = member.getUserId();
this.channelId = member.getChannel().getId();
this.channelName = member.getChannel().getName();
this.permissions = member.getPermissions();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,19 @@
@Getter
@Setter
public class MessageDTO {
private String id;

private String content;

private String authorId;
private String authorUsername;

private String channelId;
private String channelName;

private List<String> attachments;

public MessageDTO(String id, String content, String authorId, String channelId, List<String> attachments) {
this.id = id;
public MessageDTO(String content, String authorUsername, String channelName, List<String> attachments) {
this.content = content;
this.authorId = authorId;
this.channelId = channelId;
this.authorUsername = authorUsername;
this.channelName = channelName;
this.attachments = attachments;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class MessagesDTO {

public MessagesDTO(List<Message> messages) {
for (Message message : messages) {
this.messages.add(new MessageDTO(message.getId(), message.getContent(), message.getAuthor().getUserId(), message.getChannel().getId(), message.getAttachments()));
this.messages.add(new MessageDTO(message.getContent(), message.getAuthor().getUser().getUsername(), message.getChannel().getName(), message.getAttachments()));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
@Getter
@Setter
public class UserDTO {
private String id;

private String avatar;

Expand All @@ -24,7 +23,6 @@ public class UserDTO {
private long type;

public UserDTO(User user, boolean includeEmail) {
this.id = user.getId();
this.avatar = user.getAvatar();
this.displayName = user.getDisplayName();
this.username = user.getUsername();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ public ChannelInterceptor(ChannelsService channelsService) {
public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws ChannelNotFoundException {
Map<String, String> uriVariables = (Map<String, String>) getUriVariables(request);

String channelId = getChannelId(uriVariables).orElseThrow(ChannelNotFoundException::new);
String channelName = getChannelName(uriVariables).orElseThrow(ChannelNotFoundException::new);

request.setAttribute(AttributesConstants.CHANNEL, channelsService.getChannel(channelId));
request.setAttribute(AttributesConstants.CHANNEL, channelsService.getChannel(channelName));

return true;
}
Expand All @@ -43,11 +43,11 @@ public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServl
.orElseGet(Collections::emptyMap);
}

private Optional<String> getChannelId(Map<String, String> uriVariables) {
String channelIdString = uriVariables.get("id");
private Optional<String> getChannelName(Map<String, String> uriVariables) {
String channelName = uriVariables.get("name");

try {
return Optional.ofNullable(channelIdString);
return Optional.ofNullable(channelName);
} catch (NumberFormatException e) {
return Optional.empty();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,7 @@ public boolean preHandle(HttpServletRequest request, @NotNull HttpServletRespons
User user = (User) request.getAttribute(AttributesConstants.USER);
Channel channel = (Channel) request.getAttribute(AttributesConstants.CHANNEL);

Member member = channelsService.getMember(channel, user.getId());

if (member == null) throw new ChannelNotFoundException();
Member member = channelsService.getMember(channel, user.getUsername());

request.setAttribute("member", member);
return true;
Expand Down
9 changes: 5 additions & 4 deletions foxogram-common/src/main/java/su/foxogram/models/Channel.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
})
public class Channel {
@Id
public String id;
@GeneratedValue(strategy = GenerationType.IDENTITY)
public long id;

@Column()
public String name;
Expand All @@ -24,7 +25,7 @@ public class Channel {
public int type;

@Column()
public String ownerId;
public String owner;

@OneToMany(mappedBy = "channel", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Member> members;
Expand All @@ -35,10 +36,10 @@ public class Channel {
public Channel() {
}

public Channel(String id, String name, int type, String ownerId) {
public Channel(long id, String name, int type, String owner) {
this.id = id;
this.name = name;
this.type = type;
this.ownerId = ownerId;
this.owner = owner;
}
}
Loading

0 comments on commit 849d563

Please sign in to comment.