peer-at-code-backend/src/be/jeffcheasey88/peeratcode/routes/groups/GroupJoin.java

78 lines
2.9 KiB
Java

package be.jeffcheasey88.peeratcode.routes.groups;
import static be.jeffcheasey88.peeratcode.framework.RequestType.POST;
import java.time.LocalDateTime;
import java.util.regex.Matcher;
import be.jeffcheasey88.peeratcode.bonus.extract.RouteDoc;
import be.jeffcheasey88.peeratcode.framework.HttpReader;
import be.jeffcheasey88.peeratcode.framework.HttpWriter;
import be.jeffcheasey88.peeratcode.framework.Locker;
import be.jeffcheasey88.peeratcode.framework.Response;
import be.jeffcheasey88.peeratcode.framework.Route;
import be.jeffcheasey88.peeratcode.framework.User;
import be.jeffcheasey88.peeratcode.model.Chapter;
import be.jeffcheasey88.peeratcode.model.Completion;
import be.jeffcheasey88.peeratcode.model.Group;
import be.jeffcheasey88.peeratcode.model.PeerAtUser;
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
public class GroupJoin implements Response{
private DatabaseRepository repo;
private int groupDelay;
private String waitTime;
private final Locker<Completion> leaderboard;
public GroupJoin(DatabaseRepository repo, int groupDelay, String waitTime, Locker<Completion> locker){
this.repo = repo;
this.groupDelay = groupDelay;
this.waitTime = waitTime;
this.leaderboard = locker;
}
@RouteDoc(path = "/groupJoin", responseCode = 200, responseDescription = "L'utilisateur a rejoint le groupe")
@RouteDoc(responseCode = 403, responseDescription = "L'utilisateur est déjà dedans / ne peux pas le rejoindre")
@RouteDoc(responseCode = 423, responseDescription = "L'utilisateur essaye de rejoindre un groupe après le délai maximum de création de l'event")
@RouteDoc(responseCode = 409, responseDescription = "L'utilisateur est un peu débile... ou pas ?")
@Route(path = "^\\/groupJoin$", type = POST, needLogin = true)
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception{
Group group = new Group(reader.readJson());
PeerAtUser peerat = (PeerAtUser)user;
Group userGroup = this.repo.getPlayerGroup(peerat.getId(), group.getLinkToChapter());
if(group.equals(userGroup)){
writer.response(403, "Access-Control-Allow-Origin: *");
return;
}
if(group.getLinkToChapter() == null){
writer.response(409, "Access-Control-Allow-Origin: *");
writer.write(waitTime);
return;
}
if(group.getLinkToChapter() != null){
Chapter chapter = this.repo.getChapter(group.getLinkToChapter());
if(chapter.getStartDate() != null){
LocalDateTime start = chapter.getStartDate().toLocalDateTime().plusMinutes(this.groupDelay);
if(LocalDateTime.now().isAfter(start)){
writer.response(423, "Access-Control-Allow-Origin: *");
return;
}
}
}
if (this.repo.insertUserInGroup(group, peerat)) {
writer.response(200, "Access-Control-Allow-Origin: *");
leaderboard.setValue(new Completion(0, 0, 0, null, 0));
} else {
writer.response(403, "Access-Control-Allow-Origin: *");
}
}
}