package be.jeffcheasey88.peeratcode.routes.groups; import static be.jeffcheasey88.peeratcode.framework.RequestType.POST; import java.time.LocalDateTime; import java.util.regex.Matcher; import org.json.simple.JSONObject; import be.jeffcheasey88.peeratcode.bonus.extract.RouteDoc; import be.jeffcheasey88.peeratcode.framework.HttpReader; import be.jeffcheasey88.peeratcode.framework.HttpUtil; import be.jeffcheasey88.peeratcode.framework.HttpWriter; 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.Group; import be.jeffcheasey88.peeratcode.repository.DatabaseRepository; public class GroupJoin implements Response{ private DatabaseRepository repo; private int groupDelay; public GroupJoin(DatabaseRepository repo, int groupDelay){ this.repo = repo; this.groupDelay = groupDelay; } @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") @Route(path = "^\\/groupJoin$", type = POST, needLogin = true) public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception{ Group group = new Group((JSONObject) HttpUtil.readJson(reader)); Group userGroup = this.repo.getPlayerGroup(user.getId(), group.getLinkToChapter(), group.getLinkToPuzzle()); if(group.equals(userGroup)){ HttpUtil.responseHeaders(writer, 403, "Access-Control-Allow-Origin: *"); 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(start.isBefore(LocalDateTime.now())){ HttpUtil.responseHeaders(writer, 423, "Access-Control-Allow-Origin: *"); return; } } } if (this.repo.insertUserInGroup(group, user)) { HttpUtil.responseHeaders(writer, 200, "Access-Control-Allow-Origin: *"); } else { HttpUtil.responseHeaders(writer, 403, "Access-Control-Allow-Origin: *"); } } }