Compare commits
11 commits
Author | SHA1 | Date | |
---|---|---|---|
27a15a7ff0 | |||
03e64abf9c | |||
4a499e3540 | |||
4df8f2a37b | |||
24dc025507 | |||
9e2a4735d3 | |||
e3b18ace64 | |||
ebabcf4d2c | |||
14b12634f8 | |||
5fde1c1747 | |||
c720d1e542 |
121 changed files with 3243 additions and 4814 deletions
14
.classpath
14
.classpath
|
@ -1,13 +1,13 @@
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<classpath>
|
<classpath>
|
||||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
|
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
|
||||||
<attributes>
|
|
||||||
<attribute name="module" value="true"/>
|
|
||||||
</attributes>
|
|
||||||
</classpathentry>
|
|
||||||
<classpathentry kind="src" path="src"/>
|
<classpathentry kind="src" path="src"/>
|
||||||
<classpathentry kind="src" path="test"/>
|
<classpathentry kind="src" path="test"/>
|
||||||
|
<classpathentry exported="true" kind="lib" path="json-simple-1.1.1.jar"/>
|
||||||
<classpathentry exported="true" kind="lib" path="mysql-connector-java-8.0.28.jar"/>
|
<classpathentry exported="true" kind="lib" path="mysql-connector-java-8.0.28.jar"/>
|
||||||
|
<classpathentry exported="true" kind="lib" path="password4j-1.6.3.jar"/>
|
||||||
|
<classpathentry exported="true" kind="lib" path="slf4j-api-2.0.6.jar"/>
|
||||||
|
<classpathentry exported="true" kind="lib" path="jose4j-0.9.3.jar"/>
|
||||||
<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/5"/>
|
<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/5"/>
|
||||||
<classpathentry kind="src" path=".apt_generated">
|
<classpathentry kind="src" path=".apt_generated">
|
||||||
<attributes>
|
<attributes>
|
||||||
|
@ -16,9 +16,5 @@
|
||||||
</classpathentry>
|
</classpathentry>
|
||||||
<classpathentry kind="lib" path="Treasure.jar"/>
|
<classpathentry kind="lib" path="Treasure.jar"/>
|
||||||
<classpathentry exported="true" kind="lib" path="JDA-5.0.0-beta.8-withDependencies.jar"/>
|
<classpathentry exported="true" kind="lib" path="JDA-5.0.0-beta.8-withDependencies.jar"/>
|
||||||
<classpathentry exported="true" kind="lib" path="PeerAtCodeFramework.jar"/>
|
|
||||||
<classpathentry exported="true" kind="lib" path="angus-activation-2.0.2.jar"/>
|
|
||||||
<classpathentry exported="true" kind="lib" path="jakarta.activation-api-2.1.3.jar"/>
|
|
||||||
<classpathentry exported="true" kind="lib" path="jakarta.mail-2.0.3.jar"/>
|
|
||||||
<classpathentry kind="output" path="bin"/>
|
<classpathentry kind="output" path="bin"/>
|
||||||
</classpath>
|
</classpath>
|
||||||
|
|
Binary file not shown.
1
.gitignore
vendored
1
.gitignore
vendored
|
@ -6,4 +6,3 @@ config-test.txt
|
||||||
dist/
|
dist/
|
||||||
testApi/
|
testApi/
|
||||||
.apt_generated/*
|
.apt_generated/*
|
||||||
/.apt_generated/
|
|
||||||
|
|
Binary file not shown.
BIN
Treasure.jar
BIN
Treasure.jar
Binary file not shown.
Binary file not shown.
|
@ -123,5 +123,4 @@ CREATE TABLE `containsTags` (
|
||||||
CONSTRAINT `containsTags_ibfk_2` FOREIGN KEY (`fk_puzzle`) REFERENCES `puzzles` (`id_puzzle`)
|
CONSTRAINT `containsTags_ibfk_2` FOREIGN KEY (`fk_puzzle`) REFERENCES `puzzles` (`id_puzzle`)
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||||
|
|
||||||
INSERT INTO chapters (id_chapter, name) VALUES (1, 'chapter 1');
|
|
||||||
INSERT INTO players (pseudo, email, passwd,firstname,lastname) VALUES ('userTest', 'test@peerat.dev', '$argon2id$v=19$m=15360,t=2,p=1$$cAQwfs30Bf2rQGj86bpz7i59TlsuOFPiXeNpLlVu4AY', 'a','b')
|
|
||||||
|
|
Binary file not shown.
Binary file not shown.
BIN
jose4j-0.9.3.jar
Normal file
BIN
jose4j-0.9.3.jar
Normal file
Binary file not shown.
BIN
json-simple-1.1.1.jar
Normal file
BIN
json-simple-1.1.1.jar
Normal file
Binary file not shown.
BIN
password4j-1.6.3.jar
Normal file
BIN
password4j-1.6.3.jar
Normal file
Binary file not shown.
|
@ -1,6 +0,0 @@
|
||||||
/chapter/0
|
|
||||||
GET
|
|
||||||
Authorization: Bearer <token:test@peerat.dev>
|
|
||||||
|
|
||||||
|
|
||||||
400
|
|
|
@ -1,8 +0,0 @@
|
||||||
/chapters
|
|
||||||
GET
|
|
||||||
Authorization: Bearer <token:test@peerat.dev>
|
|
||||||
|
|
||||||
|
|
||||||
200
|
|
||||||
|
|
||||||
[]
|
|
|
@ -1,8 +0,0 @@
|
||||||
/leaderboard/
|
|
||||||
GET
|
|
||||||
Authorization: Bearer <token:test@peerat.dev>
|
|
||||||
|
|
||||||
|
|
||||||
200
|
|
||||||
|
|
||||||
[]
|
|
|
@ -1,6 +0,0 @@
|
||||||
/puzzle/0
|
|
||||||
GET
|
|
||||||
Authorization: Bearer <token:test@peerat.dev>
|
|
||||||
|
|
||||||
|
|
||||||
400
|
|
|
@ -1,6 +0,0 @@
|
||||||
/admin/chapter/0
|
|
||||||
GET
|
|
||||||
Authorization: Bearer <token:test@peerat.dev>
|
|
||||||
|
|
||||||
|
|
||||||
401
|
|
BIN
slf4j-api-2.0.6.jar
Normal file
BIN
slf4j-api-2.0.6.jar
Normal file
Binary file not shown.
|
@ -1,4 +1,4 @@
|
||||||
package dev.peerat.backend;
|
package be.jeffcheasey88.peeratcode;
|
||||||
|
|
||||||
import java.io.BufferedReader;
|
import java.io.BufferedReader;
|
||||||
import java.io.BufferedWriter;
|
import java.io.BufferedWriter;
|
||||||
|
@ -7,11 +7,7 @@ import java.io.FileReader;
|
||||||
import java.io.FileWriter;
|
import java.io.FileWriter;
|
||||||
import java.lang.reflect.Field;
|
import java.lang.reflect.Field;
|
||||||
|
|
||||||
import dev.peerat.backend.utils.Mail;
|
public class Configuration{
|
||||||
|
|
||||||
public class Configuration {
|
|
||||||
|
|
||||||
private boolean prod;
|
|
||||||
|
|
||||||
private String db_host;
|
private String db_host;
|
||||||
private int db_port;
|
private int db_port;
|
||||||
|
@ -33,57 +29,33 @@ public class Configuration {
|
||||||
|
|
||||||
private int groupJoinMinutes;
|
private int groupJoinMinutes;
|
||||||
private String groupQuitMinutes;
|
private String groupQuitMinutes;
|
||||||
private int groupMaxPlayers;
|
|
||||||
|
|
||||||
private String mailUsername;
|
|
||||||
private String mailPassword;
|
|
||||||
private String mailSmtpHost;
|
|
||||||
private int mailSmtpPort;
|
|
||||||
private String mailFromAddress;
|
|
||||||
|
|
||||||
private String git_token;
|
private String git_token;
|
||||||
|
|
||||||
private String jwt_key;
|
|
||||||
|
|
||||||
private String sql_folder;
|
|
||||||
|
|
||||||
private int event_chapter;
|
|
||||||
|
|
||||||
private File _file;
|
private File _file;
|
||||||
|
|
||||||
public Configuration(String path) {
|
public Configuration(String path){
|
||||||
this._file = new File(path);
|
this._file = new File(path);
|
||||||
System.out.println("Config on " + _file.getAbsolutePath());
|
System.out.println("Config on " + _file.getAbsolutePath());
|
||||||
}
|
}
|
||||||
|
|
||||||
public <T> Configuration addDefaultValue(String name, T value) throws Exception{
|
public void load() throws Exception{
|
||||||
if(value == null) throw new IllegalArgumentException("Value cannot be null");
|
if(!this._file.exists()) return;
|
||||||
Field field = getClass().getDeclaredField(name);
|
|
||||||
field.setAccessible(true);
|
|
||||||
field.set(this, value);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Configuration load() throws Exception{
|
|
||||||
if(!this._file.exists()) return this;
|
|
||||||
BufferedReader reader = new BufferedReader(new FileReader(this._file));
|
BufferedReader reader = new BufferedReader(new FileReader(this._file));
|
||||||
String line;
|
String line;
|
||||||
while((line = reader.readLine()) != null){
|
while((line = reader.readLine()) != null){
|
||||||
int index = line.indexOf('=');
|
String[] split = line.split("=");
|
||||||
String key = line.substring(0, index);
|
Field field = getClass().getDeclaredField(split[0]);
|
||||||
String value = line.substring(index+1);
|
|
||||||
Field field = getClass().getDeclaredField(key);
|
|
||||||
if(field == null) continue;
|
if(field == null) continue;
|
||||||
field.setAccessible(true);
|
field.setAccessible(true);
|
||||||
injectValue(field, value);
|
injectValue(field, split[1]);
|
||||||
}
|
}
|
||||||
reader.close();
|
reader.close();
|
||||||
return this;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void injectValue(Field field, String value) throws IllegalAccessException {
|
private void injectValue(Field field, String value) throws IllegalAccessException{
|
||||||
if (field.getType().isPrimitive()) {
|
if(field.getType().isPrimitive()){
|
||||||
switch (field.getType().getName()) {
|
switch(field.getType().getName()){
|
||||||
case "boolean":
|
case "boolean":
|
||||||
field.setBoolean(this, Boolean.parseBoolean(value));
|
field.setBoolean(this, Boolean.parseBoolean(value));
|
||||||
break;
|
break;
|
||||||
|
@ -113,15 +85,15 @@ public class Configuration {
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (field.getType().equals(String.class)) {
|
if(field.getType().equals(String.class)){
|
||||||
field.set(this, value);
|
field.set(this, value);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
throw new IllegalArgumentException(value);
|
throw new IllegalArgumentException(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void save() throws Exception {
|
public void save() throws Exception{
|
||||||
if (!_file.exists()) {
|
if(!_file.exists()){
|
||||||
File parent = _file.getParentFile();
|
File parent = _file.getParentFile();
|
||||||
if(!parent.exists()) parent.mkdirs();
|
if(!parent.exists()) parent.mkdirs();
|
||||||
_file.createNewFile();
|
_file.createNewFile();
|
||||||
|
@ -132,16 +104,12 @@ public class Configuration {
|
||||||
field.setAccessible(true);
|
field.setAccessible(true);
|
||||||
if(field.getName().startsWith("_")) continue;
|
if(field.getName().startsWith("_")) continue;
|
||||||
Object value = field.get(this);
|
Object value = field.get(this);
|
||||||
writer.write(field.getName() + "=" + value+"\n");
|
writer.write(field.getName() + "=" + value);
|
||||||
}
|
}
|
||||||
writer.flush();
|
writer.flush();
|
||||||
writer.close();
|
writer.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isProduction(){
|
|
||||||
return this.prod;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDbHost(){
|
public String getDbHost(){
|
||||||
return this.db_host;
|
return this.db_host;
|
||||||
}
|
}
|
||||||
|
@ -187,6 +155,7 @@ public class Configuration {
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getUsersFiles(){
|
public String getUsersFiles(){
|
||||||
|
if(users_files == null || users_files.trim().isEmpty()) users_files = "/tmp/users_files";
|
||||||
return users_files;
|
return users_files;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -202,36 +171,7 @@ public class Configuration {
|
||||||
return this.groupQuitMinutes;
|
return this.groupQuitMinutes;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getGroupMaxPlayers(){
|
|
||||||
return this.groupMaxPlayers;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Mail getMail(){
|
|
||||||
return new Mail(
|
|
||||||
this.mailUsername,
|
|
||||||
this.mailPassword,
|
|
||||||
this.mailSmtpHost,
|
|
||||||
this.mailSmtpPort,
|
|
||||||
this.mailFromAddress);
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getGitToken(){
|
public String getGitToken(){
|
||||||
return this.git_token;
|
return this.git_token;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getJwtKey(){
|
|
||||||
return this.jwt_key;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setJwtKey(String key){
|
|
||||||
this.jwt_key = key;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSqlFolder(){
|
|
||||||
return this.sql_folder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getEventChapter(){
|
|
||||||
return this.event_chapter;
|
|
||||||
}
|
|
||||||
}
|
}
|
143
src/be/jeffcheasey88/peeratcode/Main.java
Normal file
143
src/be/jeffcheasey88/peeratcode/Main.java
Normal file
|
@ -0,0 +1,143 @@
|
||||||
|
package be.jeffcheasey88.peeratcode;
|
||||||
|
|
||||||
|
import static be.jeffcheasey88.peeratcode.framework.RequestType.OPTIONS;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.ServerSocket;
|
||||||
|
import java.net.Socket;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
|
||||||
|
import javax.net.ssl.SSLServerSocket;
|
||||||
|
import javax.net.ssl.SSLServerSocketFactory;
|
||||||
|
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.Client;
|
||||||
|
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.Router;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.User;
|
||||||
|
import be.jeffcheasey88.peeratcode.model.Completion;
|
||||||
|
import be.jeffcheasey88.peeratcode.model.Group;
|
||||||
|
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
|
||||||
|
import be.jeffcheasey88.peeratcode.routes.BadgeDetails;
|
||||||
|
import be.jeffcheasey88.peeratcode.routes.ChapterElement;
|
||||||
|
import be.jeffcheasey88.peeratcode.routes.ChapterList;
|
||||||
|
import be.jeffcheasey88.peeratcode.routes.DynamicLeaderboard;
|
||||||
|
import be.jeffcheasey88.peeratcode.routes.Leaderboard;
|
||||||
|
import be.jeffcheasey88.peeratcode.routes.PlayerDetails;
|
||||||
|
import be.jeffcheasey88.peeratcode.routes.PuzzleElement;
|
||||||
|
import be.jeffcheasey88.peeratcode.routes.PuzzleResponse;
|
||||||
|
import be.jeffcheasey88.peeratcode.routes.Result;
|
||||||
|
import be.jeffcheasey88.peeratcode.routes.admins.DynamicLogs;
|
||||||
|
import be.jeffcheasey88.peeratcode.routes.groups.GroupCreate;
|
||||||
|
import be.jeffcheasey88.peeratcode.routes.groups.GroupJoin;
|
||||||
|
import be.jeffcheasey88.peeratcode.routes.groups.GroupList;
|
||||||
|
import be.jeffcheasey88.peeratcode.routes.groups.GroupQuit;
|
||||||
|
import be.jeffcheasey88.peeratcode.routes.users.ChangePassword;
|
||||||
|
import be.jeffcheasey88.peeratcode.routes.users.ForgotPassword;
|
||||||
|
import be.jeffcheasey88.peeratcode.routes.users.Login;
|
||||||
|
import be.jeffcheasey88.peeratcode.routes.users.ProfileSettings;
|
||||||
|
import be.jeffcheasey88.peeratcode.routes.users.Register;
|
||||||
|
|
||||||
|
public class Main{
|
||||||
|
public static void main(String[] args) throws Exception{
|
||||||
|
Configuration config = new Configuration("config.txt");
|
||||||
|
config.load();
|
||||||
|
|
||||||
|
Class.forName("com.mysql.cj.jdbc.Driver");
|
||||||
|
|
||||||
|
Router router = new Router(new DatabaseRepository(config), config.getTokenIssuer(),
|
||||||
|
config.getTokenExpiration());
|
||||||
|
|
||||||
|
router.setDefault((matcher, user, reader, writer) -> {
|
||||||
|
writer.response(404, "Access-Control-Allow-Origin: *");
|
||||||
|
writer.write("404 not Found.\n");
|
||||||
|
});
|
||||||
|
|
||||||
|
router.register(new Response(){
|
||||||
|
@Route(path = "^(.*)$", type = OPTIONS)
|
||||||
|
@Override
|
||||||
|
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
|
||||||
|
writer.response(200, "Access-Control-Allow-Origin: *",
|
||||||
|
"Access-Control-Allow-Methods: *", "Access-Control-Allow-Headers: *");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
initRoutes(router, config);
|
||||||
|
|
||||||
|
// RouteExtracter extracter = new RouteExtracter(router);
|
||||||
|
// extracter.extract();
|
||||||
|
|
||||||
|
startWebServer(config, router);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void initRoutes(Router router, Configuration config){
|
||||||
|
DatabaseRepository repo = router.getDataBase();
|
||||||
|
router.register(new Register(repo, router, config.getUsersFiles(), config.getGitToken()));
|
||||||
|
router.register(new Login(repo, router));
|
||||||
|
router.register(new ProfileSettings(repo));
|
||||||
|
router.register(new ChangePassword(repo));
|
||||||
|
router.register(new ForgotPassword());
|
||||||
|
|
||||||
|
router.register(new DynamicLogs(repo, new Locker<>())); //to change
|
||||||
|
|
||||||
|
router.register(new ChapterElement(repo));
|
||||||
|
router.register(new ChapterList(repo));
|
||||||
|
router.register(new PuzzleElement(repo));
|
||||||
|
router.register(new Result(repo));
|
||||||
|
router.register(new Leaderboard(repo));
|
||||||
|
router.register(new PlayerDetails(repo));
|
||||||
|
router.register(new BadgeDetails(repo));
|
||||||
|
|
||||||
|
Locker<Group> groupLock = new Locker<>();
|
||||||
|
Locker<Completion> leaderboard = new Locker<>();
|
||||||
|
|
||||||
|
router.register(new DynamicLeaderboard(repo, leaderboard));
|
||||||
|
router.register(new PuzzleResponse(repo, config.getUsersFiles(), leaderboard));
|
||||||
|
|
||||||
|
router.register(new GroupCreate(repo, groupLock, config.getGroupJoinMinutes()));
|
||||||
|
router.register(new GroupList(repo));
|
||||||
|
router.register(new GroupJoin(repo, config.getGroupJoinMinutes(), config.getGroupQuitMinutes(), leaderboard));
|
||||||
|
router.register(new GroupQuit(repo, config.getGroupJoinMinutes(), leaderboard));
|
||||||
|
|
||||||
|
// Bot bot = new Bot(config, repo, groupLock);
|
||||||
|
// bot.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void startWebServer(Configuration config, Router router) throws IOException {
|
||||||
|
if (config.useSsl()) { // Not needed with the use of a proxy
|
||||||
|
SSLServerSocket server = null;
|
||||||
|
try {
|
||||||
|
System.setProperty("javax.net.ssl.keyStore", config.getSslKeystore());
|
||||||
|
System.setProperty("javax.net.ssl.keyStorePassword", config.getSslKeystorePasswd());
|
||||||
|
|
||||||
|
SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
|
||||||
|
server = (SSLServerSocket) ssf.createServerSocket(config.getTcpPort());
|
||||||
|
|
||||||
|
while (!server.isClosed()) {
|
||||||
|
Socket socket = server.accept();
|
||||||
|
Client client = new Client(socket, router);
|
||||||
|
client.start();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
} finally {
|
||||||
|
if (server != null) {
|
||||||
|
server.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
try (ServerSocket server = new ServerSocket(config.getTcpPort())) {
|
||||||
|
while (!server.isClosed()) {
|
||||||
|
Socket socket = server.accept();
|
||||||
|
Client client = new Client(socket, router);
|
||||||
|
client.start();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,12 +1,12 @@
|
||||||
package dev.peerat.backend.bonus.discord;
|
package be.jeffcheasey88.peeratcode.bonus.discord;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import dev.peerat.backend.Configuration;
|
import be.jeffcheasey88.peeratcode.Configuration;
|
||||||
import dev.peerat.backend.model.Group;
|
import be.jeffcheasey88.peeratcode.framework.Locker;
|
||||||
import dev.peerat.backend.repository.DatabaseRepository;
|
import be.jeffcheasey88.peeratcode.framework.Locker.Key;
|
||||||
import dev.peerat.framework.Locker;
|
import be.jeffcheasey88.peeratcode.model.Group;
|
||||||
import dev.peerat.framework.Locker.Key;
|
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
|
||||||
import net.dv8tion.jda.api.JDA;
|
import net.dv8tion.jda.api.JDA;
|
||||||
import net.dv8tion.jda.api.JDABuilder;
|
import net.dv8tion.jda.api.JDABuilder;
|
||||||
import net.dv8tion.jda.api.entities.Guild;
|
import net.dv8tion.jda.api.entities.Guild;
|
||||||
|
@ -38,7 +38,7 @@ public class Bot extends Thread{
|
||||||
|
|
||||||
locker.init(key);
|
locker.init(key);
|
||||||
|
|
||||||
List<Group> groups = this.repo.getGroupRepository().getAllGroups();
|
List<Group> groups = this.repo.getAllGroups();
|
||||||
for(Group group : groups){
|
for(Group group : groups){
|
||||||
Integer chapter = group.getLinkToChapter();
|
Integer chapter = group.getLinkToChapter();
|
||||||
// Integer puzzle = group.getLinkToPuzzle();
|
// Integer puzzle = group.getLinkToPuzzle();
|
|
@ -1,4 +1,4 @@
|
||||||
package dev.peerat.backend.bonus.extract;
|
package be.jeffcheasey88.peeratcode.bonus.extract;
|
||||||
|
|
||||||
import java.lang.annotation.ElementType;
|
import java.lang.annotation.ElementType;
|
||||||
import java.lang.annotation.Repeatable;
|
import java.lang.annotation.Repeatable;
|
|
@ -1,4 +1,4 @@
|
||||||
package dev.peerat.backend.bonus.extract;
|
package be.jeffcheasey88.peeratcode.bonus.extract;
|
||||||
|
|
||||||
import java.lang.annotation.ElementType;
|
import java.lang.annotation.ElementType;
|
||||||
import java.lang.annotation.Retention;
|
import java.lang.annotation.Retention;
|
|
@ -0,0 +1,49 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.bonus.extract;
|
||||||
|
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Map.Entry;
|
||||||
|
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.RequestType;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.Response;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.Route;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.Router;
|
||||||
|
|
||||||
|
//A noter que le but est d'extraire des informations sans modifier le code source,
|
||||||
|
//comme les tests unitaire, ici je veux générer un élément textuel qui me donnera l'état des routes,
|
||||||
|
//je ne vais donc pas modifier la classe router pour donner un accès au route.
|
||||||
|
public class RouteExtracter {
|
||||||
|
|
||||||
|
private Router router;
|
||||||
|
|
||||||
|
public RouteExtracter(Router router){
|
||||||
|
this.router = router;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void extract() throws Exception{
|
||||||
|
Field field = Router.class.getDeclaredField("responses");
|
||||||
|
field.setAccessible(true);
|
||||||
|
Map<RequestType, Map<Response, Route>> responses = (Map<RequestType, Map<Response, Route>>) field.get(this.router);
|
||||||
|
for(Entry<RequestType, Map<Response, Route>> types : responses.entrySet()){
|
||||||
|
for(Entry<Response, Route> routes : types.getValue().entrySet()){
|
||||||
|
System.out.println("["+types.getKey()+"] ("+routes.getValue().needLogin()+") "+routes.getValue().path());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void extractDoc() throws Exception{
|
||||||
|
Field field = Router.class.getDeclaredField("responses");
|
||||||
|
field.setAccessible(true);
|
||||||
|
Map<RequestType, Map<Response, Route>> responses = (Map<RequestType, Map<Response, Route>>) field.get(this.router);
|
||||||
|
for(Map<Response, Route> route : responses.values()){
|
||||||
|
for(Response response : route.keySet()){
|
||||||
|
Method method = response.getClass().getDeclaredMethod("exec",
|
||||||
|
Response.class.getDeclaredMethods()[0].getParameterTypes());
|
||||||
|
for(RouteDoc doc : method.getDeclaredAnnotationsByType(RouteDoc.class)){
|
||||||
|
System.out.println(doc.path()+((doc.path().isEmpty() ? "":"\n"))+" ["+doc.responseCode()+"] "+doc.responseDescription());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
60
src/be/jeffcheasey88/peeratcode/framework/Client.java
Normal file
60
src/be/jeffcheasey88/peeratcode/framework/Client.java
Normal file
|
@ -0,0 +1,60 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.framework;
|
||||||
|
|
||||||
|
import java.net.Socket;
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
import org.jose4j.jwa.AlgorithmConstraints.ConstraintType;
|
||||||
|
import org.jose4j.jws.AlgorithmIdentifiers;
|
||||||
|
import org.jose4j.jwt.JwtClaims;
|
||||||
|
import org.jose4j.jwt.consumer.JwtConsumer;
|
||||||
|
import org.jose4j.jwt.consumer.JwtConsumerBuilder;
|
||||||
|
|
||||||
|
public class Client extends Thread{
|
||||||
|
|
||||||
|
private HttpReader reader;
|
||||||
|
private HttpWriter writer;
|
||||||
|
private Router router;
|
||||||
|
|
||||||
|
public Client(Socket socket, Router router) throws Exception{
|
||||||
|
this.reader = new HttpReader(socket);
|
||||||
|
this.writer = new HttpWriter(socket);
|
||||||
|
this.router = router;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run(){
|
||||||
|
try{
|
||||||
|
String[] headers = reader.readLine().split("\\s");
|
||||||
|
System.out.println(Arrays.toString(headers));
|
||||||
|
reader.readHeaders();
|
||||||
|
|
||||||
|
router.exec(RequestType.valueOf(headers[0]), headers[1], isLogin(reader), reader, writer);
|
||||||
|
writer.flush();
|
||||||
|
writer.close();
|
||||||
|
}catch(Exception e){
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private User isLogin(HttpReader reader) throws Exception{
|
||||||
|
String auth = reader.getHeader("Authorization");
|
||||||
|
if(auth == null) return null;
|
||||||
|
auth = auth.substring(7);
|
||||||
|
try{
|
||||||
|
JwtConsumer jwtConsumer = new JwtConsumerBuilder()
|
||||||
|
.setRequireExpirationTime()
|
||||||
|
.setAllowedClockSkewInSeconds(30)
|
||||||
|
.setExpectedIssuer(this.router.getTokenIssuer())
|
||||||
|
.setVerificationKey(this.router.getWebKey().getKey())
|
||||||
|
.setJwsAlgorithmConstraints(ConstraintType.PERMIT, AlgorithmIdentifiers.RSA_USING_SHA256).build();
|
||||||
|
|
||||||
|
JwtClaims jwtClaims = jwtConsumer.processToClaims(auth);
|
||||||
|
return new User(jwtClaims);
|
||||||
|
}catch(Exception e){
|
||||||
|
writer.response(401, "Access-Control-Allow-Origin: *");
|
||||||
|
writer.flush();
|
||||||
|
writer.close();
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
138
src/be/jeffcheasey88/peeratcode/framework/HttpReader.java
Normal file
138
src/be/jeffcheasey88/peeratcode/framework/HttpReader.java
Normal file
|
@ -0,0 +1,138 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.framework;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.net.Socket;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import org.json.simple.parser.JSONParser;
|
||||||
|
|
||||||
|
public class HttpReader{
|
||||||
|
|
||||||
|
private static Pattern HEADER_PATTERN = Pattern.compile("^([^:]*):\\s+(.*)$");
|
||||||
|
|
||||||
|
private Socket socket;
|
||||||
|
private InputStream in;
|
||||||
|
private BufferedReader reader;
|
||||||
|
|
||||||
|
private Map<String, String> headers;
|
||||||
|
|
||||||
|
public HttpReader(Socket socket) throws Exception{
|
||||||
|
this.socket = socket;
|
||||||
|
this.in = socket.getInputStream();
|
||||||
|
this.reader = new BufferedReader(new InputStreamReader(in));
|
||||||
|
this.headers = new HashMap<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public HttpReader(HttpReader origin) throws Exception{
|
||||||
|
this.socket = origin.socket;
|
||||||
|
this.in = origin.in;
|
||||||
|
this.reader = origin.reader;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isClosed(){
|
||||||
|
return this.socket.isClosed();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void readHeaders() throws Exception{
|
||||||
|
String line;
|
||||||
|
while(((line = reader.readLine()) != null) && (line.length() > 0)){
|
||||||
|
Matcher matcher = HEADER_PATTERN.matcher(line);
|
||||||
|
matcher.matches();
|
||||||
|
this.headers.put(matcher.group(1).toLowerCase(), matcher.group(2));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getHeader(String key){
|
||||||
|
return this.headers.get(key.toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
public int read(byte[] buffer) throws IOException{
|
||||||
|
return this.in.read(buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int read(char[] buffer) throws IOException{
|
||||||
|
return this.reader.read(buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String readLine() throws IOException{
|
||||||
|
return this.reader.readLine();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean ready() throws IOException{
|
||||||
|
return this.reader.ready();
|
||||||
|
}
|
||||||
|
|
||||||
|
public int readInt() throws Exception{
|
||||||
|
int result = 0;
|
||||||
|
result += this.in.read() << 24;
|
||||||
|
result += this.in.read() << 16;
|
||||||
|
result += this.in.read() << 8;
|
||||||
|
result += this.in.read();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public <T> T readJson() throws Exception{
|
||||||
|
String line = "";
|
||||||
|
while (ready()){
|
||||||
|
char[] c = new char[1];
|
||||||
|
read(c);
|
||||||
|
line += c[0];
|
||||||
|
if (c[0] == '}'){
|
||||||
|
Object parse;
|
||||||
|
try {
|
||||||
|
parse = new JSONParser().parse(line);
|
||||||
|
if (parse != null)
|
||||||
|
return (T) parse;
|
||||||
|
}catch(Exception e){}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
*
|
||||||
|
------WebKitFormBoundaryNUjiLBAMuX2dhxU7
|
||||||
|
Content-Disposition: form-data; name="answer"
|
||||||
|
|
||||||
|
12
|
||||||
|
------WebKitFormBoundaryNUjiLBAMuX2dhxU7
|
||||||
|
Content-Disposition: form-data; name="filename"
|
||||||
|
|
||||||
|
webpack.js
|
||||||
|
------WebKitFormBoundaryNUjiLBAMuX2dhxU7
|
||||||
|
Content-Disposition: form-data; name="code_file"; filename="webpack.js"
|
||||||
|
Content-Type: text/javascript
|
||||||
|
|
||||||
|
|
||||||
|
------WebKitFormBoundaryNUjiLBAMuX2dhxU7--
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
public List<String> readMultiPartData() throws Exception{
|
||||||
|
List<String> list = new ArrayList<>();
|
||||||
|
String boundary = getHeader("content-type");
|
||||||
|
if(boundary == null) return list;
|
||||||
|
boundary = boundary.split(";")[1].split("=")[1];
|
||||||
|
readLine();
|
||||||
|
|
||||||
|
while(ready()){
|
||||||
|
String line;
|
||||||
|
while (((line = readLine()) != null) && (line.length() > 0));
|
||||||
|
String buffer = "";
|
||||||
|
while (((line = readLine()) != null) && (!line.startsWith("--"+boundary))){
|
||||||
|
buffer += line;
|
||||||
|
}
|
||||||
|
list.add(buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
}
|
101
src/be/jeffcheasey88/peeratcode/framework/HttpWriter.java
Normal file
101
src/be/jeffcheasey88/peeratcode/framework/HttpWriter.java
Normal file
|
@ -0,0 +1,101 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.framework;
|
||||||
|
|
||||||
|
import java.io.BufferedWriter;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.io.OutputStreamWriter;
|
||||||
|
import java.net.Socket;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
|
||||||
|
public class HttpWriter{
|
||||||
|
|
||||||
|
private OutputStream out;
|
||||||
|
private BufferedWriter writer;
|
||||||
|
|
||||||
|
public HttpWriter(Socket socket) throws Exception{
|
||||||
|
this.out = socket.getOutputStream();
|
||||||
|
this.writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
|
||||||
|
public HttpWriter(HttpWriter origin) throws Exception{
|
||||||
|
this.out = origin.out;
|
||||||
|
this.writer = origin.writer;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void write(byte[] buffer) throws IOException{
|
||||||
|
this.out.write(buffer);
|
||||||
|
this.out.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void write(String message) throws IOException{
|
||||||
|
this.writer.write(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void flush() throws IOException{
|
||||||
|
this.writer.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void close() throws IOException{
|
||||||
|
this.writer.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void response(int code, String... headers) throws Exception{
|
||||||
|
write("HTTP/1.1 "+code+codeMessage(code)+"\n");
|
||||||
|
for(String header : headers) write(header+"\n");
|
||||||
|
write("\n");
|
||||||
|
flush();
|
||||||
|
StackTraceElement[] e = Thread.currentThread().getStackTrace();
|
||||||
|
System.out.println(e[2]+" -> response "+code);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String[] HEIGHTBITS = new String[7];
|
||||||
|
private static String[] NINEBITS = new String[206];
|
||||||
|
|
||||||
|
static {
|
||||||
|
HEIGHTBITS[0] = " OK";
|
||||||
|
HEIGHTBITS[1] = " Created";
|
||||||
|
HEIGHTBITS[2] = " Accepted";
|
||||||
|
HEIGHTBITS[3] = " Non-Authoritative Information";
|
||||||
|
HEIGHTBITS[4] = " No Content";
|
||||||
|
HEIGHTBITS[5] = " Reset Content";
|
||||||
|
HEIGHTBITS[6] = " Partial Content";
|
||||||
|
|
||||||
|
NINEBITS[0] = " Multiple Choices";
|
||||||
|
NINEBITS[1] = " Moved Permanently";
|
||||||
|
NINEBITS[2] = " Temporary Redirect";
|
||||||
|
NINEBITS[3] = " See Other";
|
||||||
|
NINEBITS[4] = " Not Modified";
|
||||||
|
NINEBITS[5] = " Use Proxy";
|
||||||
|
|
||||||
|
NINEBITS[100] = " Bad Request";
|
||||||
|
NINEBITS[101] = " Unauthorized";
|
||||||
|
NINEBITS[102] = " Payment Required";
|
||||||
|
NINEBITS[103] = " Forbidden";
|
||||||
|
NINEBITS[104] = " Not Found";
|
||||||
|
NINEBITS[105] = " Method Not Allowed";
|
||||||
|
NINEBITS[106] = " Not Acceptable";
|
||||||
|
NINEBITS[107] = " Proxy Authentication Required";
|
||||||
|
NINEBITS[108] = " Request Time-Out";
|
||||||
|
NINEBITS[109] = " Conflict";
|
||||||
|
NINEBITS[110] = " Gone";
|
||||||
|
NINEBITS[111] = " Length Required";
|
||||||
|
NINEBITS[112] = " Precondition Failed";
|
||||||
|
NINEBITS[113] = " Request Entity Too Large";
|
||||||
|
NINEBITS[114] = " Request-URI Too Large";
|
||||||
|
NINEBITS[115] = " Unsupported Media Type";
|
||||||
|
|
||||||
|
NINEBITS[200] = " Internal Server Error";
|
||||||
|
NINEBITS[201] = " Not Implemented";
|
||||||
|
NINEBITS[202] = " Bad Gateway";
|
||||||
|
NINEBITS[203] = " Service Unavailable";
|
||||||
|
NINEBITS[204] = " Gateway Timeout";
|
||||||
|
NINEBITS[205] = " HTTP Version Not Supported";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String codeMessage(int code){
|
||||||
|
if(code == 100) return " Continue";
|
||||||
|
if(code >> 8 == 0) return HEIGHTBITS[code-200];
|
||||||
|
return NINEBITS[code-300];
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
59
src/be/jeffcheasey88/peeratcode/framework/Locker.java
Normal file
59
src/be/jeffcheasey88/peeratcode/framework/Locker.java
Normal file
|
@ -0,0 +1,59 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.framework;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Map.Entry;
|
||||||
|
import java.util.concurrent.BlockingQueue;
|
||||||
|
import java.util.concurrent.LinkedBlockingQueue;
|
||||||
|
|
||||||
|
public class Locker<V>{
|
||||||
|
|
||||||
|
private Map<Key, BlockingQueue<V>> map;
|
||||||
|
|
||||||
|
public Locker(){
|
||||||
|
this.map = new HashMap<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void init(Key key){
|
||||||
|
this.map.put(key, new LinkedBlockingQueue<>());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void remove(Key key){
|
||||||
|
this.map.remove(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
private BlockingQueue<V> get(Key key){
|
||||||
|
return this.map.get(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setValue(V value){
|
||||||
|
for(Entry<Key, BlockingQueue<V>> entry : this.map.entrySet()){
|
||||||
|
entry.getValue().add(value);
|
||||||
|
this.unlock(entry.getKey());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public V getValue(Key key){
|
||||||
|
BlockingQueue<V> queue = get(key);
|
||||||
|
if(queue.isEmpty()) return null;
|
||||||
|
return queue.poll();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void lock(Key key) throws InterruptedException{
|
||||||
|
BlockingQueue<V> queue = get(key);
|
||||||
|
if(queue.isEmpty()){
|
||||||
|
synchronized(queue){
|
||||||
|
queue.wait();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void unlock(Key key){
|
||||||
|
BlockingQueue<V> queue = get(key);
|
||||||
|
synchronized(queue){
|
||||||
|
queue.notify();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class Key{ public Key(){} }
|
||||||
|
}
|
|
@ -0,0 +1,7 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.framework;
|
||||||
|
|
||||||
|
public enum RequestType{
|
||||||
|
|
||||||
|
GET, POST, OPTIONS;
|
||||||
|
|
||||||
|
}
|
9
src/be/jeffcheasey88/peeratcode/framework/Response.java
Normal file
9
src/be/jeffcheasey88/peeratcode/framework/Response.java
Normal file
|
@ -0,0 +1,9 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.framework;
|
||||||
|
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
|
||||||
|
public interface Response{
|
||||||
|
|
||||||
|
void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception;
|
||||||
|
|
||||||
|
}
|
19
src/be/jeffcheasey88/peeratcode/framework/Route.java
Normal file
19
src/be/jeffcheasey88/peeratcode/framework/Route.java
Normal file
|
@ -0,0 +1,19 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.framework;
|
||||||
|
|
||||||
|
import java.lang.annotation.ElementType;
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
@Target(ElementType.METHOD)
|
||||||
|
public @interface Route{
|
||||||
|
|
||||||
|
String path() default "^.*$";
|
||||||
|
|
||||||
|
RequestType type() default RequestType.GET;
|
||||||
|
|
||||||
|
boolean needLogin() default false;
|
||||||
|
|
||||||
|
boolean websocket() default false;
|
||||||
|
}
|
178
src/be/jeffcheasey88/peeratcode/framework/Router.java
Normal file
178
src/be/jeffcheasey88/peeratcode/framework/Router.java
Normal file
|
@ -0,0 +1,178 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.framework;
|
||||||
|
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Map.Entry;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import org.jose4j.jwk.RsaJsonWebKey;
|
||||||
|
import org.jose4j.jwk.RsaJwkGenerator;
|
||||||
|
import org.jose4j.jws.AlgorithmIdentifiers;
|
||||||
|
import org.jose4j.jws.JsonWebSignature;
|
||||||
|
import org.jose4j.jwt.JwtClaims;
|
||||||
|
import org.jose4j.lang.JoseException;
|
||||||
|
|
||||||
|
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
|
||||||
|
|
||||||
|
public class Router{
|
||||||
|
|
||||||
|
private Map<RequestType, Map<Response, Route>> responses;
|
||||||
|
private Map<Response, Pattern> patterns;
|
||||||
|
private Response noFileFound;
|
||||||
|
private RsaJsonWebKey rsaJsonWebKey;
|
||||||
|
private DatabaseRepository repo;
|
||||||
|
private String token_issuer;
|
||||||
|
private int token_expiration;
|
||||||
|
|
||||||
|
public Router(DatabaseRepository repo, String token_issuer, int token_expiration) throws Exception{
|
||||||
|
this.repo = repo;
|
||||||
|
this.token_issuer = token_issuer;
|
||||||
|
this.token_expiration = token_expiration;
|
||||||
|
this.responses = new HashMap<>();
|
||||||
|
for(RequestType type : RequestType.values()) this.responses.put(type, new HashMap<>());
|
||||||
|
this.patterns = new HashMap<>();
|
||||||
|
this.rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);
|
||||||
|
}
|
||||||
|
|
||||||
|
public DatabaseRepository getDataBase(){
|
||||||
|
return this.repo;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void register(Response response){
|
||||||
|
try{
|
||||||
|
Method method = response.getClass().getDeclaredMethod("exec",
|
||||||
|
Response.class.getDeclaredMethods()[0].getParameterTypes());
|
||||||
|
Route route = method.getAnnotation(Route.class);
|
||||||
|
|
||||||
|
this.responses.get(route.type()).put(response, route);
|
||||||
|
this.patterns.put(response, Pattern.compile(route.path()));
|
||||||
|
}catch(Exception e){
|
||||||
|
throw new IllegalArgumentException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDefault(Response response){
|
||||||
|
this.noFileFound = response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void exec(RequestType type, String path, User user, HttpReader reader, HttpWriter writer) throws Exception{
|
||||||
|
if(type == null) return;
|
||||||
|
for(Entry<Response, Route> routes : this.responses.get(type).entrySet()){
|
||||||
|
Matcher matcher = this.patterns.get(routes.getKey()).matcher(path);
|
||||||
|
if(matcher.matches()){
|
||||||
|
if(user == null && routes.getValue().needLogin()){
|
||||||
|
writer.response(401, "Access-Control-Allow-Origin: *");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(routes.getValue().websocket()){
|
||||||
|
switchToWebSocket(reader, writer);
|
||||||
|
reader = new WebSocketReader(reader);
|
||||||
|
writer = new WebSocketWriter(writer);
|
||||||
|
}
|
||||||
|
routes.getKey().exec(matcher, user, reader, writer);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(noFileFound != null) noFileFound.exec(null, user, reader, writer);
|
||||||
|
}
|
||||||
|
|
||||||
|
public RsaJsonWebKey getWebKey(){
|
||||||
|
return this.rsaJsonWebKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTokenIssuer(){
|
||||||
|
return this.token_issuer;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String createAuthUser(int id) throws JoseException{
|
||||||
|
JwtClaims claims = new JwtClaims();
|
||||||
|
claims.setIssuer(token_issuer); // who creates the token and signs it
|
||||||
|
claims.setExpirationTimeMinutesInTheFuture(token_expiration);
|
||||||
|
claims.setGeneratedJwtId(); // a unique identifier for the token
|
||||||
|
claims.setIssuedAtToNow(); // when the token was issued/created (now)
|
||||||
|
claims.setNotBeforeMinutesInThePast(2); // time before which the token is not yet valid (2 minutes ago)
|
||||||
|
|
||||||
|
claims.setClaim("id", id);
|
||||||
|
|
||||||
|
JsonWebSignature jws = new JsonWebSignature();
|
||||||
|
jws.setPayload(claims.toJson());
|
||||||
|
jws.setKey(rsaJsonWebKey.getPrivateKey());
|
||||||
|
jws.setKeyIdHeaderValue(rsaJsonWebKey.getKeyId());
|
||||||
|
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
|
||||||
|
return jws.getCompactSerialization();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void switchToWebSocket(HttpReader reader, HttpWriter writer) throws Exception{
|
||||||
|
String key = reader.getHeader("Sec-WebSocket-Key");
|
||||||
|
if (key == null) throw new IllegalArgumentException();
|
||||||
|
|
||||||
|
writer.write("HTTP/1.1 101 Switching Protocols\n");
|
||||||
|
writer.write("Connection: Upgrade\n");
|
||||||
|
writer.write("Upgrade: websocket\n");
|
||||||
|
writer.write("Sec-WebSocket-Accept: " + printBase64Binary(MessageDigest.getInstance("SHA-1")
|
||||||
|
.digest((key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes("UTF-8"))) + "\n");
|
||||||
|
writer.write("\n");
|
||||||
|
writer.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// From javax.xml.bind.DatatypeConverter
|
||||||
|
private String printBase64Binary(byte[] array){
|
||||||
|
char[] arrayOfChar = new char[(array.length + 2) / 3 * 4];
|
||||||
|
int i = _printBase64Binary(array, 0, array.length, arrayOfChar, 0);
|
||||||
|
assert i == arrayOfChar.length;
|
||||||
|
return new String(arrayOfChar);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int _printBase64Binary(byte[] paramArrayOfbyte, int paramInt1, int paramInt2,
|
||||||
|
char[] paramArrayOfchar, int paramInt3){
|
||||||
|
int i = paramInt2;
|
||||||
|
int j;
|
||||||
|
for (j = paramInt1; i >= 3; j += 3){
|
||||||
|
paramArrayOfchar[paramInt3++] = encode(paramArrayOfbyte[j] >> 2);
|
||||||
|
paramArrayOfchar[paramInt3++] = encode(
|
||||||
|
(paramArrayOfbyte[j] & 0x3) << 4 | paramArrayOfbyte[j + 1] >> 4 & 0xF);
|
||||||
|
paramArrayOfchar[paramInt3++] = encode(
|
||||||
|
(paramArrayOfbyte[j + 1] & 0xF) << 2 | paramArrayOfbyte[j + 2] >> 6 & 0x3);
|
||||||
|
paramArrayOfchar[paramInt3++] = encode(paramArrayOfbyte[j + 2] & 0x3F);
|
||||||
|
i -= 3;
|
||||||
|
}
|
||||||
|
if (i == 1){
|
||||||
|
paramArrayOfchar[paramInt3++] = encode(paramArrayOfbyte[j] >> 2);
|
||||||
|
paramArrayOfchar[paramInt3++] = encode((paramArrayOfbyte[j] & 0x3) << 4);
|
||||||
|
paramArrayOfchar[paramInt3++] = '=';
|
||||||
|
paramArrayOfchar[paramInt3++] = '=';
|
||||||
|
}
|
||||||
|
if (i == 2){
|
||||||
|
paramArrayOfchar[paramInt3++] = encode(paramArrayOfbyte[j] >> 2);
|
||||||
|
paramArrayOfchar[paramInt3++] = encode(
|
||||||
|
(paramArrayOfbyte[j] & 0x3) << 4 | paramArrayOfbyte[j + 1] >> 4 & 0xF);
|
||||||
|
paramArrayOfchar[paramInt3++] = encode((paramArrayOfbyte[j + 1] & 0xF) << 2);
|
||||||
|
paramArrayOfchar[paramInt3++] = '=';
|
||||||
|
}
|
||||||
|
return paramInt3;
|
||||||
|
}
|
||||||
|
|
||||||
|
private char encode(int paramInt){
|
||||||
|
return encodeMap[paramInt & 0x3F];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final char[] encodeMap = initEncodeMap();
|
||||||
|
|
||||||
|
private static char[] initEncodeMap(){
|
||||||
|
char[] arrayOfChar = new char[64];
|
||||||
|
byte b;
|
||||||
|
for (b = 0; b < 26; b++)
|
||||||
|
arrayOfChar[b] = (char) (65 + b);
|
||||||
|
for (b = 26; b < 52; b++)
|
||||||
|
arrayOfChar[b] = (char) (97 + b - 26);
|
||||||
|
for (b = 52; b < 62; b++)
|
||||||
|
arrayOfChar[b] = (char) (48 + b - 52);
|
||||||
|
arrayOfChar[62] = '+';
|
||||||
|
arrayOfChar[63] = '/';
|
||||||
|
return arrayOfChar;
|
||||||
|
}
|
||||||
|
}
|
27
src/be/jeffcheasey88/peeratcode/framework/User.java
Normal file
27
src/be/jeffcheasey88/peeratcode/framework/User.java
Normal file
|
@ -0,0 +1,27 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.framework;
|
||||||
|
|
||||||
|
import org.jose4j.jwt.JwtClaims;
|
||||||
|
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.Locker.Key;
|
||||||
|
|
||||||
|
public class User{
|
||||||
|
|
||||||
|
private int id;
|
||||||
|
private Key key;
|
||||||
|
|
||||||
|
public User(JwtClaims jwtClaims){
|
||||||
|
this.id = ((Long) jwtClaims.getClaimValue("id")).intValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setKey(Key key){
|
||||||
|
this.key = key;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Key getKey(){
|
||||||
|
return this.key;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getId(){
|
||||||
|
return this.id;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,62 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.framework;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class WebSocketReader extends HttpReader{
|
||||||
|
|
||||||
|
public WebSocketReader(HttpReader origin) throws Exception{
|
||||||
|
super(origin);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String readLine() throws IOException{
|
||||||
|
//read websocket found on StackOverFlow
|
||||||
|
int buffLenth = 1024;
|
||||||
|
int len = 0;
|
||||||
|
byte[] b = new byte[buffLenth];
|
||||||
|
// rawIn is a Socket.getInputStream();
|
||||||
|
while (true){
|
||||||
|
len = read(b);
|
||||||
|
if (len != -1){
|
||||||
|
byte rLength = 0;
|
||||||
|
int rMaskIndex = 2;
|
||||||
|
int rDataStart = 0;
|
||||||
|
// b[0] is always text in my case so no need to check;
|
||||||
|
byte data = b[1];
|
||||||
|
byte op = (byte) 127;
|
||||||
|
rLength = (byte) (data & op);
|
||||||
|
|
||||||
|
if (rLength == (byte) 126)
|
||||||
|
rMaskIndex = 4;
|
||||||
|
if (rLength == (byte) 127)
|
||||||
|
rMaskIndex = 10;
|
||||||
|
|
||||||
|
byte[] masks = new byte[4];
|
||||||
|
|
||||||
|
int j = 0;
|
||||||
|
int i = 0;
|
||||||
|
for (i = rMaskIndex; i < (rMaskIndex + 4); i++){
|
||||||
|
masks[j] = b[i];
|
||||||
|
j++;
|
||||||
|
}
|
||||||
|
|
||||||
|
rDataStart = rMaskIndex + 4;
|
||||||
|
|
||||||
|
int messLen = len - rDataStart;
|
||||||
|
|
||||||
|
byte[] message = new byte[messLen];
|
||||||
|
|
||||||
|
for (i = rDataStart, j = 0; i < len; i++, j++){
|
||||||
|
message[j] = (byte) (b[i] ^ masks[j % 4]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new String(message);
|
||||||
|
|
||||||
|
} else
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,61 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.framework;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class WebSocketWriter extends HttpWriter{
|
||||||
|
|
||||||
|
public WebSocketWriter(HttpWriter origin) throws Exception{
|
||||||
|
super(origin);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void write(String message) throws IOException{
|
||||||
|
//write websocket found on StackOverFlow
|
||||||
|
byte[] rawData = message.getBytes();
|
||||||
|
|
||||||
|
int frameCount = 0;
|
||||||
|
byte[] frame = new byte[10];
|
||||||
|
|
||||||
|
frame[0] = (byte) 129;
|
||||||
|
|
||||||
|
if (rawData.length <= 125){
|
||||||
|
frame[1] = (byte) rawData.length;
|
||||||
|
frameCount = 2;
|
||||||
|
} else if (rawData.length >= 126 && rawData.length <= 65535){
|
||||||
|
frame[1] = (byte) 126;
|
||||||
|
int len = rawData.length;
|
||||||
|
frame[2] = (byte) ((len >> 8) & (byte) 255);
|
||||||
|
frame[3] = (byte) (len & (byte) 255);
|
||||||
|
frameCount = 4;
|
||||||
|
} else {
|
||||||
|
frame[1] = (byte) 127;
|
||||||
|
int len = rawData.length;
|
||||||
|
frame[2] = (byte) ((len >> 56) & (byte) 255);
|
||||||
|
frame[3] = (byte) ((len >> 48) & (byte) 255);
|
||||||
|
frame[4] = (byte) ((len >> 40) & (byte) 255);
|
||||||
|
frame[5] = (byte) ((len >> 32) & (byte) 255);
|
||||||
|
frame[6] = (byte) ((len >> 24) & (byte) 255);
|
||||||
|
frame[7] = (byte) ((len >> 16) & (byte) 255);
|
||||||
|
frame[8] = (byte) ((len >> 8) & (byte) 255);
|
||||||
|
frame[9] = (byte) (len & (byte) 255);
|
||||||
|
frameCount = 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
int bLength = frameCount + rawData.length;
|
||||||
|
|
||||||
|
byte[] reply = new byte[bLength];
|
||||||
|
|
||||||
|
int bLim = 0;
|
||||||
|
for (int i = 0; i < frameCount; i++){
|
||||||
|
reply[bLim] = frame[i];
|
||||||
|
bLim++;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < rawData.length; i++){
|
||||||
|
reply[bLim] = rawData[i];
|
||||||
|
bLim++;
|
||||||
|
}
|
||||||
|
|
||||||
|
write(reply);
|
||||||
|
flush();
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,5 +1,8 @@
|
||||||
package dev.peerat.backend.model;
|
package be.jeffcheasey88.peeratcode.model;
|
||||||
|
|
||||||
|
import be.jeffcheasey88.peeratcode.mapping.Treasure;
|
||||||
|
|
||||||
|
@Treasure
|
||||||
public class Badge {
|
public class Badge {
|
||||||
|
|
||||||
private String name;
|
private String name;
|
|
@ -1,4 +1,4 @@
|
||||||
package dev.peerat.backend.model;
|
package be.jeffcheasey88.peeratcode.model;
|
||||||
|
|
||||||
import java.sql.Timestamp;
|
import java.sql.Timestamp;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
@ -35,10 +35,11 @@ public class Chapter {
|
||||||
this.puzzles = puzzles;
|
this.puzzles = puzzles;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean hasStarted(){
|
public boolean isInCurrentTime(){
|
||||||
LocalDateTime now = LocalDateTime.now();
|
LocalDateTime now = LocalDateTime.now();
|
||||||
boolean show = true;
|
boolean show = true;
|
||||||
if(startDate != null) show &= now.isAfter(startDate.toLocalDateTime());
|
if(startDate != null) show &= now.isAfter(startDate.toLocalDateTime());
|
||||||
|
if(endDate != null) show &= now.isBefore(endDate.toLocalDateTime());
|
||||||
return show;
|
return show;
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package dev.peerat.backend.model;
|
package be.jeffcheasey88.peeratcode.model;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
@ -11,7 +11,7 @@ public class Completion{
|
||||||
private int score;
|
private int score;
|
||||||
private String puzzleName;
|
private String puzzleName;
|
||||||
|
|
||||||
public Completion(int playerId, int puzzleId, int tries, String fileName, int score){
|
public Completion(int playerId, int puzzleId, int tries, String fileName, int score) {
|
||||||
this(playerId, puzzleId, tries, score, fileName, null, null, null, null);
|
this(playerId, puzzleId, tries, score, fileName, null, null, null, null);
|
||||||
}
|
}
|
||||||
public Completion(int playerId, int puzzleId, int tries, String fileName, int score, String puzzleName) {
|
public Completion(int playerId, int puzzleId, int tries, String fileName, int score, String puzzleName) {
|
||||||
|
@ -22,13 +22,13 @@ public class Completion{
|
||||||
this(playerId, puzzleId, 0, 0, fileName, file, response, currentPuzzle, null);
|
this(playerId, puzzleId, 0, 0, fileName, file, response, currentPuzzle, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Completion(int initTries, int initScore){
|
public Completion(int initTries, int initScore) {
|
||||||
// For group leaderboard
|
// For group leaderboard
|
||||||
this(-1, -1, initTries, initScore, null, null, null, null, null);
|
this(-1, -1, initTries, initScore, null, null, null, null, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Completion(int playerId, int puzzleId, int tries, int score, String fileName, byte[] file, byte[] response,
|
public Completion(int playerId, int puzzleId, int tries, int score, String fileName, byte[] file, byte[] response,
|
||||||
Puzzle currentPuzzle, String initPuzzleName){
|
Puzzle currentPuzzle, String initPuzzleName) {
|
||||||
this.playerId = playerId;
|
this.playerId = playerId;
|
||||||
this.puzzleId = puzzleId;
|
this.puzzleId = puzzleId;
|
||||||
this.fileName = fileName;
|
this.fileName = fileName;
|
||||||
|
@ -40,7 +40,7 @@ public class Completion{
|
||||||
this.score = score;
|
this.score = score;
|
||||||
|
|
||||||
if (currentPuzzle != null)
|
if (currentPuzzle != null)
|
||||||
addTry(currentPuzzle, response, 0);
|
addTry(currentPuzzle, response);
|
||||||
|
|
||||||
puzzleName = initPuzzleName;
|
puzzleName = initPuzzleName;
|
||||||
}
|
}
|
||||||
|
@ -62,17 +62,12 @@ public class Completion{
|
||||||
return tries;
|
return tries;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addTry(Puzzle currentPuzzle, byte[] response, int chapter){
|
public void addTry(Puzzle currentPuzzle, byte[] response) {
|
||||||
if (score <= 0){
|
if (score <= 0){
|
||||||
tries++;
|
tries++;
|
||||||
if (response != null && Arrays.equals(currentPuzzle.getSoluce(), response)){
|
if (response != null && Arrays.equals(currentPuzzle.getSoluce(), response)) {
|
||||||
if (tries > 1) { // Loose 5% each try with a minimum of 1 for score
|
if (tries > 1) { // Loose 5% each try with a minimum of 1 for score
|
||||||
if(chapter < 4){
|
|
||||||
score = currentPuzzle.getScoreMax();
|
|
||||||
}else{
|
|
||||||
score = (int) Math.ceil(currentPuzzle.getScoreMax() * (1 - ((tries - 1) / 20.)));
|
score = (int) Math.ceil(currentPuzzle.getScoreMax() * (1 - ((tries - 1) / 20.)));
|
||||||
}
|
|
||||||
// score = currentPuzzle.getScoreMax();
|
|
||||||
if (score < 1)
|
if (score < 1)
|
||||||
score = 1;
|
score = 1;
|
||||||
} else
|
} else
|
|
@ -1,49 +1,35 @@
|
||||||
package dev.peerat.backend.model;
|
package be.jeffcheasey88.peeratcode.model;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
||||||
import org.jose4j.json.internal.json_simple.JSONArray;
|
import org.json.simple.JSONArray;
|
||||||
import org.jose4j.json.internal.json_simple.JSONObject;
|
import org.json.simple.JSONObject;
|
||||||
|
|
||||||
import be.jeffcheasey88.peeratcode.mapping.SeaBottle;
|
|
||||||
import dev.peerat.framework.utils.json.JsonMap;
|
|
||||||
|
|
||||||
public class Group implements Comparable<Group> {
|
public class Group implements Comparable<Group> {
|
||||||
private String name;
|
private String name;
|
||||||
private Integer linkToChapter;
|
private Integer linkToChapter;
|
||||||
// private Integer linkToPuzzle;
|
// private Integer linkToPuzzle;
|
||||||
private List<Player> players;
|
private List<Player> players;
|
||||||
private int playerCount;
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString(){
|
public String toString(){
|
||||||
return "Group[name="+name+", chapter="+linkToChapter+"]";
|
return "Group[name="+name+", chapter="+linkToChapter+"]";
|
||||||
}
|
}
|
||||||
|
|
||||||
public Group(JsonMap json){
|
public Group(JSONObject json) {
|
||||||
this.name = (String) json.get("name");
|
this.name = (String) json.get("name");
|
||||||
if (json.has("chapter"))
|
if (json.containsKey("chapter"))
|
||||||
this.linkToChapter = ((Number) json.get("chapter")).intValue();
|
this.linkToChapter = ((Number) json.get("chapter")).intValue();
|
||||||
// if (json.has("puzzle"))
|
// if (json.containsKey("puzzle"))
|
||||||
// this.linkToPuzzle = ((Number) json.get("puzzle")).intValue();
|
// this.linkToPuzzle = ((Number) json.get("puzzle")).intValue();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Group(String name, Integer initChap, Integer initPuzz, int playerCount) {
|
public Group(String name, Integer initChap, Integer initPuzz) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
this.linkToChapter = initChap;
|
this.linkToChapter = initChap;
|
||||||
// this.linkToPuzzle = initPuzz;
|
// this.linkToPuzzle = initPuzz;
|
||||||
this.playerCount = playerCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getPlayerCount(){
|
|
||||||
return this.playerCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
@SeaBottle
|
|
||||||
public static Group getGroup(int player){
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addPlayer(Player newPlayer) {
|
public void addPlayer(Player newPlayer) {
|
||||||
|
@ -119,7 +105,6 @@ public class Group implements Comparable<Group> {
|
||||||
}
|
}
|
||||||
groupJSON.put("players", groupsPlayerJSON);
|
groupJSON.put("players", groupsPlayerJSON);
|
||||||
}
|
}
|
||||||
groupJSON.put("playerCount", this.playerCount);
|
|
||||||
return groupJSON;
|
return groupJSON;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -139,7 +124,7 @@ public class Group implements Comparable<Group> {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode(){
|
public int hashCode() {
|
||||||
return Objects.hash(name);
|
return Objects.hash(name);
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,14 +1,14 @@
|
||||||
package dev.peerat.backend.model;
|
package be.jeffcheasey88.peeratcode.model;
|
||||||
|
|
||||||
import java.util.Base64;
|
import java.util.Base64;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
import dev.peerat.framework.utils.json.JsonArray;
|
import org.json.simple.JSONArray;
|
||||||
import dev.peerat.framework.utils.json.JsonMap;
|
import org.json.simple.JSONObject;
|
||||||
|
|
||||||
public class Player implements Comparable<Player> {
|
public class Player implements Comparable<Player>{
|
||||||
private String pseudo;
|
private String pseudo;
|
||||||
private String email;
|
private String email;
|
||||||
private String firstname;
|
private String firstname;
|
||||||
|
@ -22,12 +22,12 @@ public class Player implements Comparable<Player> {
|
||||||
|
|
||||||
private Set<Badge> badges;
|
private Set<Badge> badges;
|
||||||
|
|
||||||
public Player(String pseudo, String email, String firstname, String lastname) {
|
public Player(String pseudo, String email, String firstname, String lastname, String description) {
|
||||||
this.pseudo = pseudo;
|
this.pseudo = pseudo;
|
||||||
this.email = email;
|
this.email = email;
|
||||||
this.firstname = firstname;
|
this.firstname = firstname;
|
||||||
this.lastname = lastname;
|
this.lastname = lastname;
|
||||||
this.description = "";
|
this.description = description;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Player(String pseudo, int score, int tries) {
|
public Player(String pseudo, int score, int tries) {
|
||||||
|
@ -37,11 +37,6 @@ public class Player implements Comparable<Player> {
|
||||||
email = ""; // TO make compareTo and equals works as usual
|
email = ""; // TO make compareTo and equals works as usual
|
||||||
}
|
}
|
||||||
|
|
||||||
public Player(String email) {
|
|
||||||
// For player find in Map during register process
|
|
||||||
this.email = email;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPseudo(String pseudo){
|
public void setPseudo(String pseudo){
|
||||||
this.pseudo = pseudo;
|
this.pseudo = pseudo;
|
||||||
}
|
}
|
||||||
|
@ -70,9 +65,9 @@ public class Player implements Comparable<Player> {
|
||||||
return groups;
|
return groups;
|
||||||
}
|
}
|
||||||
|
|
||||||
public JsonArray getJsonGroups() {
|
public JSONArray getJsonGroups() {
|
||||||
if (groups != null) {
|
if (groups != null) {
|
||||||
JsonArray groupsJSON = new JsonArray();
|
JSONArray groupsJSON = new JSONArray();
|
||||||
for (Group group : groups) {
|
for (Group group : groups) {
|
||||||
groupsJSON.add(group.toJson());
|
groupsJSON.add(group.toJson());
|
||||||
}
|
}
|
||||||
|
@ -121,13 +116,13 @@ public class Player implements Comparable<Player> {
|
||||||
return completions.size();
|
return completions.size();
|
||||||
}
|
}
|
||||||
|
|
||||||
public JsonArray getJsonCompletions() {
|
public JSONArray getJsonCompletions() {
|
||||||
JsonArray completionsJSON = new JsonArray();
|
JSONArray completionsJSON = new JSONArray();
|
||||||
for (Completion completion : completions) {
|
for (Completion completion : completions) {
|
||||||
JsonMap completionJSON = new JsonMap();
|
JSONObject completionJSON = new JSONObject();
|
||||||
completionJSON.set("puzzleName", completion.getPuzzleName());
|
completionJSON.put("puzzleName", completion.getPuzzleName());
|
||||||
completionJSON.set("tries", completion.getTries());
|
completionJSON.put("tries", completion.getTries());
|
||||||
completionJSON.set("score", completion.getScore());
|
completionJSON.put("score", completion.getScore());
|
||||||
completionsJSON.add(completionJSON);
|
completionsJSON.add(completionJSON);
|
||||||
}
|
}
|
||||||
return completionsJSON;
|
return completionsJSON;
|
||||||
|
@ -145,17 +140,17 @@ public class Player implements Comparable<Player> {
|
||||||
return badges;
|
return badges;
|
||||||
}
|
}
|
||||||
|
|
||||||
public JsonArray getJsonBadges() {
|
public JSONArray getJsonBadges() {
|
||||||
if (badges == null)
|
if (badges == null)
|
||||||
return null;
|
return null;
|
||||||
JsonArray badgesJSON = new JsonArray();
|
JSONArray badgesJSON = new JSONArray();
|
||||||
for (Badge badge : badges) {
|
for (Badge badge : badges) {
|
||||||
JsonMap badgeJSON = new JsonMap();
|
JSONObject badgeJSON = new JSONObject();
|
||||||
badgeJSON.set("name", badge.getName());
|
badgeJSON.put("name", badge.getName());
|
||||||
byte[] logo = badge.getLogo();
|
byte[] logo = badge.getLogo();
|
||||||
if (logo != null)
|
if (logo != null)
|
||||||
badgeJSON.set("logo", Base64.getEncoder().encodeToString(logo));
|
badgeJSON.put("logo", Base64.getEncoder().encodeToString(logo));
|
||||||
badgeJSON.set("level", badge.getLevel());
|
badgeJSON.put("level", badge.getLevel());
|
||||||
badgesJSON.add(badgeJSON);
|
badgesJSON.add(badgeJSON);
|
||||||
}
|
}
|
||||||
return badgesJSON;
|
return badgesJSON;
|
||||||
|
@ -190,7 +185,7 @@ public class Player implements Comparable<Player> {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode(){
|
public int hashCode(){
|
||||||
return Objects.hash(email, pseudo);
|
return Objects.hash(email);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -202,6 +197,6 @@ public class Player implements Comparable<Player> {
|
||||||
if (getClass() != obj.getClass())
|
if (getClass() != obj.getClass())
|
||||||
return false;
|
return false;
|
||||||
Player other = (Player) obj;
|
Player other = (Player) obj;
|
||||||
return Objects.equals(email, other.email) && Objects.equals(pseudo, other.pseudo);
|
return Objects.equals(email, other.email);
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -1,13 +1,11 @@
|
||||||
package dev.peerat.backend.model;
|
package be.jeffcheasey88.peeratcode.model;
|
||||||
|
|
||||||
import java.sql.Timestamp;
|
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
import dev.peerat.framework.utils.json.JsonArray;
|
import org.json.simple.JSONArray;
|
||||||
import dev.peerat.framework.utils.json.JsonMap;
|
import org.json.simple.JSONObject;
|
||||||
|
|
||||||
public class Puzzle {
|
public class Puzzle {
|
||||||
|
|
||||||
|
@ -19,10 +17,9 @@ public class Puzzle {
|
||||||
private int scoreMax;
|
private int scoreMax;
|
||||||
private Set<String> tags;
|
private Set<String> tags;
|
||||||
private int depend;
|
private int depend;
|
||||||
private Timestamp startDate;
|
|
||||||
|
|
||||||
public Puzzle(int id, String name, String content, byte[] soluce, String verify, int scoreMax, String tags,
|
public Puzzle(int id, String name, String content, byte[] soluce, String verify, int scoreMax, String tags,
|
||||||
int depend, Timestamp startDate) {
|
int depend) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
this.name = name;
|
this.name = name;
|
||||||
this.content = content;
|
this.content = content;
|
||||||
|
@ -31,7 +28,6 @@ public class Puzzle {
|
||||||
this.scoreMax = scoreMax;
|
this.scoreMax = scoreMax;
|
||||||
setTags(tags);
|
setTags(tags);
|
||||||
this.depend = depend;
|
this.depend = depend;
|
||||||
this.startDate = startDate;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getId() {
|
public int getId() {
|
||||||
|
@ -63,13 +59,13 @@ public class Puzzle {
|
||||||
*
|
*
|
||||||
* @return DEATH
|
* @return DEATH
|
||||||
*/
|
*/
|
||||||
public JsonArray getJsonTags() {
|
public JSONArray getJsonTags() {
|
||||||
if (tags == null)
|
if (tags == null)
|
||||||
return null;
|
return null;
|
||||||
JsonArray tagsJSON = new JsonArray();
|
JSONArray tagsJSON = new JSONArray();
|
||||||
for (String tag : tags) {
|
for (String tag : tags) {
|
||||||
JsonMap tagJSON = new JsonMap();
|
JSONObject tagJSON = new JSONObject();
|
||||||
tagJSON.set("name", tag);
|
tagJSON.put("name", tag);
|
||||||
tagsJSON.add(tagJSON);
|
tagsJSON.add(tagJSON);
|
||||||
}
|
}
|
||||||
return tagsJSON;
|
return tagsJSON;
|
||||||
|
@ -86,13 +82,6 @@ public class Puzzle {
|
||||||
return this.depend;
|
return this.depend;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean hasStarted(){
|
|
||||||
LocalDateTime now = LocalDateTime.now();
|
|
||||||
boolean show = true;
|
|
||||||
if(startDate != null) show &= now.isAfter(startDate.toLocalDateTime());
|
|
||||||
return show;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object object) {
|
public boolean equals(Object object) {
|
||||||
if (this == object)
|
if (this == object)
|
263
src/be/jeffcheasey88/peeratcode/repository/DatabaseQuery.java
Normal file
263
src/be/jeffcheasey88/peeratcode/repository/DatabaseQuery.java
Normal file
|
@ -0,0 +1,263 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.repository;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
|
||||||
|
public enum DatabaseQuery {
|
||||||
|
// PUZZLES
|
||||||
|
SPECIFIC_PUZZLE_QUERY(
|
||||||
|
"SELECT p.*, np.origin, GROUP_CONCAT(t.name) AS tags FROM puzzles p LEFT JOIN nextPart np ON p.id_puzzle = np.next LEFT JOIN containsTags ct ON ct.fk_puzzle = p.id_puzzle LEFT JOIN tags t ON t.id_tag = ct.fk_tag WHERE p.id_puzzle = ? GROUP BY p.id_puzzle"),
|
||||||
|
PUZZLES_IN_CHAPTER_QUERY(
|
||||||
|
"SELECT p.*, GROUP_CONCAT(t.name) AS tags FROM puzzles p LEFT JOIN containsTags ct ON ct.fk_puzzle = p.id_puzzle LEFT JOIN tags t ON t.id_tag = ct.fk_tag WHERE fk_chapter = ? GROUP BY p.id_puzzle"),
|
||||||
|
|
||||||
|
// CHAPTERS
|
||||||
|
SPECIFIC_CHAPTER_QUERY("SELECT * FROM chapters WHERE id_chapter = ?"),
|
||||||
|
CHAPTER_FROM_PUZZLE("SELECT c.*\r\n"
|
||||||
|
+ "FROM chapters c\r\n"
|
||||||
|
+ "JOIN puzzles p ON p.fk_chapter = c.id_chapter\r\n"
|
||||||
|
+ "WHERE p.id_puzzle = ?"),
|
||||||
|
ALL_CHAPTERS_QUERY("SELECT * FROM chapters WHERE id_chapter > 0"),
|
||||||
|
|
||||||
|
// GROUPS
|
||||||
|
ALL_GROUPS("SELECT * FROM groups"),
|
||||||
|
GET_GROUP_FOR_PLAYER("SELECT g.* FROM groups g JOIN containsGroups cg ON cg.fk_group = g.id_group WHERE cg.fk_player = ? AND g.fk_chapter = ?"), // AND g.fk_puzzle = ?
|
||||||
|
GET_GROUP_ID_BY_DATA("SELECT id_group FROM groups WHERE name = ? AND (fk_chapter = ?)"), // OR fk_puzzle = ?
|
||||||
|
INSERT_GROUP("INSERT INTO groups (name, fk_chapter) VALUES (?,?)"),
|
||||||
|
INSERT_PLAYER_IN_GROUP("INSERT INTO containsGroups (fk_player, fk_group) VALUES (?,?)"),
|
||||||
|
LEAVE_GROUP("DELETE FROM containsGroups WHERE fk_player = ? AND fk_group = ?"),
|
||||||
|
|
||||||
|
// LEADERBOARD
|
||||||
|
ALL_PLAYERS_FOR_LEADERBOARD(
|
||||||
|
"select p.*, scores.*, g.* from players p ,(SELECT fk_player, SUM(c.score) AS score, COUNT(c.id_completion) AS completions, SUM(c.tries) AS tries, rank() over(ORDER BY score DESC) AS rank FROM completions c GROUP BY c.fk_player) AS scores LEFT JOIN containsGroups cg ON scores.fk_player = cg.fk_player LEFT JOIN groups g ON cg.fk_group = g.id_group WHERE p.id_player = scores.fk_player ORDER BY g.fk_chapter"),
|
||||||
|
ALL_GROUP_FOR_CHAPTER_LEADERBOARD(
|
||||||
|
"SELECT g.*, pl.pseudo, co.score, co.tries FROM groups g LEFT JOIN containsGroups cg ON g.id_group = cg.fk_group LEFT JOIN players pl ON cg.fk_player = pl.id_player LEFT JOIN completions co ON pl.id_player = co.fk_player WHERE cg.fk_player IS NOT NULL AND fk_chapter = ? AND (co.fk_puzzle IN (SELECT id_puzzle FROM puzzles puz WHERE puz.fk_chapter = g.fk_chapter) OR co.score IS NULL);"),
|
||||||
|
|
||||||
|
// REGISTER
|
||||||
|
CHECK_PSEUDO_AVAILABLE_QUERY("SELECT * FROM players WHERE pseudo = ?"),
|
||||||
|
CHECK_EMAIL_AVAILABLE_QUERY("SELECT * FROM players WHERE email = ?"),
|
||||||
|
REGISTER_QUERY(
|
||||||
|
"INSERT INTO players (pseudo, email, passwd, firstname, lastname, description, avatar) VALUES (?, ?, ?, ?, ?, ?, ?)"),
|
||||||
|
REGISTER_PLAYER_IN_EXISTING_GROUP(
|
||||||
|
"INSERT INTO containsGroups (fk_player, fk_group) VALUES (?, (SELECT id_group FROM groups WHERE name = ?));"),
|
||||||
|
|
||||||
|
// LOGIN
|
||||||
|
CHECK_PASSWORD("SELECT id_player, passwd FROM players WHERE pseudo=?"),
|
||||||
|
|
||||||
|
// COMPLETIONS
|
||||||
|
GET_COMPLETION(
|
||||||
|
"SELECT * FROM completions WHERE fk_puzzle = ? AND fk_player = ?"),
|
||||||
|
GET_COMPLETION_GROUP("SELECT c.*\r\n"
|
||||||
|
+ "FROM completions c\r\n"
|
||||||
|
+ "JOIN containsGroups cG on c.fk_player = cG.fk_player\r\n"
|
||||||
|
+ "JOIN containsGroups cGs on cGs.fk_group = cG.fk_group\r\n"
|
||||||
|
+ "JOIN groups g on cG.fk_group = g.id_group\r\n"
|
||||||
|
+ "JOIN puzzles p on p.id_puzzle = c.fk_puzzle\r\n"
|
||||||
|
+ "WHERE cGs.fk_player = ? AND p.id_puzzle = ?"),
|
||||||
|
INSERT_COMPLETION(
|
||||||
|
"INSERT INTO completions (fk_puzzle, fk_player, tries, code, fileName, score) values (?, ?, ?, ?, ?, ?)"),
|
||||||
|
UPDATE_COMPLETION(
|
||||||
|
"UPDATE completions SET tries = ?, score = ?, fk_player = ? WHERE fk_puzzle = ? AND fk_player = ?"),
|
||||||
|
SCORE("SELECT score FROM completions WHERE fk_player = ? AND fk_puzzle = ?"),
|
||||||
|
SCORE_GROUP("SELECT c.score\r\n"
|
||||||
|
+ "FROM completions c\r\n"
|
||||||
|
+ "JOIN containsGroups cG on c.fk_player = cG.fk_player\r\n"
|
||||||
|
+ "JOIN containsGroups cGs on cGs.fk_group = cG.fk_group\r\n"
|
||||||
|
+ "JOIN groups g on cG.fk_group = g.id_group\r\n"
|
||||||
|
+ "JOIN puzzles p on p.id_puzzle = c.fk_puzzle\r\n"
|
||||||
|
+ "WHERE cGs.fk_player = ? AND p.id_puzzle = ?"),
|
||||||
|
|
||||||
|
// PLAYERS
|
||||||
|
GET_PLAYER_SIMPLE("SELECT pseudo, email, firstname, lastname, description FROM players WHERE id_player = ?"),
|
||||||
|
GET_PLAYER_PSEUDO("SELECT * FROM players WHERE pseudo = ?"),
|
||||||
|
GET_PLAYER_DETAILS("SELECT p.*, g.*\r\n"
|
||||||
|
+ "FROM players p\r\n"
|
||||||
|
+ "LEFT OUTER JOIN containsGroups cg ON p.id_player = cg.fk_player\r\n"
|
||||||
|
+ "LEFT OUTER JOIN groups g ON cg.fk_group = g.id_group\r\n"
|
||||||
|
+ "LEFT OUTER JOIN completions c on p.id_player = c.fk_player\r\n"
|
||||||
|
+ "WHERE "),
|
||||||
|
GET_PLAYER_DETAILS_BY_ID(GET_PLAYER_DETAILS, " p.id_player = ? GROUP BY g.name ORDER BY g.fk_chapter, g.fk_puzzle;"),
|
||||||
|
GET_PLAYER_DETAILS_BY_PSEUDO(GET_PLAYER_DETAILS, "p.pseudo = ? GROUP BY g.name ORDER BY g.fk_chapter, g.fk_puzzle;"),
|
||||||
|
GET_PLAYER_COMPLETIONS("select c.*, p.name from completions c left join puzzles p on c.fk_puzzle = p.id_puzzle where fk_player = ?;"),
|
||||||
|
GET_PLAYER_RANK("SELECT * FROM (SELECT fk_player, RANK() OVER(ORDER BY SUM(score) DESC) rank FROM completions c LEFT JOIN players p ON p.id_player = c.fk_player GROUP BY fk_player ORDER BY rank) AS ranks WHERE ranks.fk_player = ?;"),
|
||||||
|
|
||||||
|
UPDATE_PLAYER_INFO("UPDATE players SET pseudo = ?, email = ?, first_name = ?, last_name = ? WHERE id_player = ?"),
|
||||||
|
UPDATE_PLAYER_PASSWORD("UPDATE players SET passwd = ? WHERE id_player = ?"),
|
||||||
|
|
||||||
|
// BADGES
|
||||||
|
GET_BADGE("SELECT * FROM badges WHERE id_badge = ?"), GET_BADGES_OF_PLAYER(
|
||||||
|
"SELECT * FROM badges b LEFT JOIN containsBadges cb ON cb.fk_badge = b.id_badge WHERE cb.fk_player = ?"),
|
||||||
|
|
||||||
|
//TRIGGER
|
||||||
|
FIRST_TRY("CREATE OR REPLACE TRIGGER FirstTry\r\n"
|
||||||
|
+ "AFTER INSERT\r\n"
|
||||||
|
+ " ON completions FOR EACH ROW\r\n"
|
||||||
|
+ "BEGIN\r\n"
|
||||||
|
+ " DECLARE badge INT;\r\n"
|
||||||
|
+ " DECLARE contain INT;\r\n"
|
||||||
|
+ " \r\n"
|
||||||
|
+ " SELECT id_badge\r\n"
|
||||||
|
+ " INTO @badge\r\n"
|
||||||
|
+ " FROM badges\r\n"
|
||||||
|
+ " WHERE name = 'FirstTry';\r\n"
|
||||||
|
+ " \r\n"
|
||||||
|
+ " IF @badge is not null THEN\r\n"
|
||||||
|
+ " \r\n"
|
||||||
|
+ " SELECT count(*)\r\n"
|
||||||
|
+ " INTO @contain\r\n"
|
||||||
|
+ " FROM containsBadges\r\n"
|
||||||
|
+ " WHERE fk_badge = @badge AND fk_player = NEW.fk_player;\r\n"
|
||||||
|
+ " \r\n"
|
||||||
|
+ " IF (@contain = 0) THEN\r\n"
|
||||||
|
+ " INSERT INTO containsBadges(fk_player, fk_badge) VALUES (NEW.fk_player, @badge);\r\n"
|
||||||
|
+ " END IF;\r\n"
|
||||||
|
+ " END IF;\r\n"
|
||||||
|
+ "END;"),
|
||||||
|
EventParticipation("CREATE OR REPLACE TRIGGER EventParticipation\r\n"
|
||||||
|
+ "AFTER INSERT\r\n"
|
||||||
|
+ " ON completions FOR EACH ROW\r\n"
|
||||||
|
+ "BEGIN\r\n"
|
||||||
|
+ " DECLARE badge INT;\r\n"
|
||||||
|
+ " DECLARE endDate datetime;\r\n"
|
||||||
|
+ " DECLARE player INT;\r\n"
|
||||||
|
+ " DECLARE contain INT;\r\n"
|
||||||
|
+ "\r\n"
|
||||||
|
+ " SELECT id_badge\r\n"
|
||||||
|
+ " INTO badge\r\n"
|
||||||
|
+ " FROM badges\r\n"
|
||||||
|
+ " WHERE name = 'EventParticipation';\r\n"
|
||||||
|
+ "\r\n"
|
||||||
|
+ " IF @badge is not null THEN\r\n"
|
||||||
|
+ "\r\n"
|
||||||
|
+ " SELECT c.end_date, i.fk_player\r\n"
|
||||||
|
+ " INTO endDate, player\r\n"
|
||||||
|
+ " FROM inserted i\r\n"
|
||||||
|
+ " JOIN puzzles p ON i.fk_puzzle = p.id_puzzle\r\n"
|
||||||
|
+ " JOIN chapters c on p.fk_chapter = c.id_chapter;\r\n"
|
||||||
|
+ "\r\n"
|
||||||
|
+ " IF @endDate is not null THEN\r\n"
|
||||||
|
+ "\r\n"
|
||||||
|
+ " SELECT count(*)\r\n"
|
||||||
|
+ " INTO contain\r\n"
|
||||||
|
+ " FROM containsBadges\r\n"
|
||||||
|
+ " WHERE fk_badge = badge AND fk_player = player;\r\n"
|
||||||
|
+ "\r\n"
|
||||||
|
+ " IF (@contain = 0) THEN\r\n"
|
||||||
|
+ " INSERT INTO containsBadges(fk_player, fk_badge) VALUES (@player, @badge);\r\n"
|
||||||
|
+ " END IF;\r\n"
|
||||||
|
+ " END IF;\r\n"
|
||||||
|
+ " END IF;\r\n"
|
||||||
|
+ "END;");
|
||||||
|
|
||||||
|
private String request;
|
||||||
|
|
||||||
|
DatabaseQuery(DatabaseQuery parent, String request) {
|
||||||
|
this.request = parent.request + request;
|
||||||
|
}
|
||||||
|
|
||||||
|
DatabaseQuery(String request) {
|
||||||
|
this.request = request;
|
||||||
|
}
|
||||||
|
|
||||||
|
public PreparedStatement prepare(Connection con) throws SQLException {
|
||||||
|
return con.prepareStatement(this.request);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return this.request;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
*
|
||||||
|
|
||||||
|
SELECT p.*, scores.score, scores.completions, scores.tries, scores.rank, g.*
|
||||||
|
FROM players p,
|
||||||
|
(SELECT fk_player, SUM(c.score) AS score,
|
||||||
|
COUNT(c.id_completion) AS completions,
|
||||||
|
SUM(c.tries) AS tries,
|
||||||
|
rank() over(ORDER BY score DESC) AS rank
|
||||||
|
FROM completions c GROUP BY c.fk_player)
|
||||||
|
AS scores
|
||||||
|
LEFT OUTER JOIN containsGroups cg ON scores.fk_player = cg.fk_player
|
||||||
|
LEFT OUTER JOIN groups g ON cg.fk_group = g.id_group
|
||||||
|
WHERE p.id_player = scores.fk_player AND "),
|
||||||
|
|
||||||
|
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* TRIGGER PLACE
|
||||||
|
*
|
||||||
|
|
||||||
|
CREATE OR REPLACE TRIGGER FirstTry
|
||||||
|
AFTER INSERT
|
||||||
|
ON completions FOR EACH ROW
|
||||||
|
BEGIN
|
||||||
|
DECLARE badge INT;
|
||||||
|
DECLARE contain INT;
|
||||||
|
|
||||||
|
SELECT id_badge
|
||||||
|
INTO @badge
|
||||||
|
FROM badges
|
||||||
|
WHERE name = 'FirstTry';
|
||||||
|
|
||||||
|
IF @badge is not null THEN
|
||||||
|
|
||||||
|
SELECT count(*)
|
||||||
|
INTO @contain
|
||||||
|
FROM containsBadges
|
||||||
|
WHERE fk_badge = @badge AND fk_player = NEW.fk_player;
|
||||||
|
|
||||||
|
IF (@contain = 0) THEN
|
||||||
|
|
||||||
|
IF (NEW.score >= 0 AND NEW.tries < 2) THEN
|
||||||
|
INSERT INTO containsBadges(fk_player, fk_badge) VALUES (NEW.fk_player, @badge);
|
||||||
|
END IF;
|
||||||
|
END IF;
|
||||||
|
END IF;
|
||||||
|
END;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
CREATE OR REPLACE TRIGGER EventParticipation
|
||||||
|
AFTER INSERT
|
||||||
|
ON completions FOR EACH ROW
|
||||||
|
BEGIN
|
||||||
|
DECLARE badge INT;
|
||||||
|
DECLARE endDate datetime;
|
||||||
|
DECLARE player INT;
|
||||||
|
DECLARE contain INT;
|
||||||
|
|
||||||
|
SELECT id_badge
|
||||||
|
INTO badge
|
||||||
|
FROM badges
|
||||||
|
WHERE name = 'EventParticipation';
|
||||||
|
|
||||||
|
IF @badge is not null THEN
|
||||||
|
|
||||||
|
SELECT c.end_date, i.fk_player
|
||||||
|
INTO endDate, player
|
||||||
|
FROM inserted i
|
||||||
|
JOIN puzzles p ON i.fk_puzzle = p.id_puzzle
|
||||||
|
JOIN chapters c on p.fk_chapter = c.id_chapter;
|
||||||
|
|
||||||
|
IF @endDate is not null THEN
|
||||||
|
|
||||||
|
SELECT count(*)
|
||||||
|
INTO contain
|
||||||
|
FROM containsBadges
|
||||||
|
WHERE fk_badge = badge AND fk_player = player;
|
||||||
|
|
||||||
|
IF (@contain = 0) THEN
|
||||||
|
INSERT INTO containsBadges(fk_player, fk_badge) VALUES (@player, @badge);
|
||||||
|
END IF;
|
||||||
|
END IF;
|
||||||
|
END IF;
|
||||||
|
END;
|
||||||
|
|
||||||
|
|
||||||
|
*
|
||||||
|
*/
|
|
@ -0,0 +1,681 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.repository;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.DriverManager;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.ResultSetMetaData;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.sql.Statement;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.SortedSet;
|
||||||
|
import java.util.TreeSet;
|
||||||
|
|
||||||
|
import com.password4j.Hash;
|
||||||
|
import com.password4j.Password;
|
||||||
|
|
||||||
|
import be.jeffcheasey88.peeratcode.Configuration;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.User;
|
||||||
|
import be.jeffcheasey88.peeratcode.model.Badge;
|
||||||
|
import be.jeffcheasey88.peeratcode.model.Chapter;
|
||||||
|
import be.jeffcheasey88.peeratcode.model.Completion;
|
||||||
|
import be.jeffcheasey88.peeratcode.model.Group;
|
||||||
|
import be.jeffcheasey88.peeratcode.model.Player;
|
||||||
|
import be.jeffcheasey88.peeratcode.model.Puzzle;
|
||||||
|
|
||||||
|
public class DatabaseRepository {
|
||||||
|
|
||||||
|
private Connection con;
|
||||||
|
private Configuration config;
|
||||||
|
|
||||||
|
public DatabaseRepository(Configuration config) {
|
||||||
|
this.config = config;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ensureConnection() throws SQLException {
|
||||||
|
if (con == null || (!con.isValid(5))){
|
||||||
|
System.out.println("connecting "+config.getDbHost()+" on "+config.getDbDatabase());
|
||||||
|
this.con = DriverManager.getConnection(
|
||||||
|
"jdbc:mysql://" + config.getDbHost() + ":" + config.getDbPort() + "/" + config.getDbDatabase() + "",
|
||||||
|
config.getDbUser(), config.getDbPassword());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Puzzle makePuzzle(ResultSet puzzleResult) throws SQLException {
|
||||||
|
return new Puzzle(puzzleResult.getInt("id_puzzle"), puzzleResult.getString("name"),
|
||||||
|
puzzleResult.getString("content"), puzzleResult.getBytes("soluce"), puzzleResult.getString("verify"),
|
||||||
|
puzzleResult.getInt("score_max"), puzzleResult.getString("tags"),
|
||||||
|
hasColumn(puzzleResult, "origin") ? puzzleResult.getInt("origin") : -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Chapter makeChapter(ResultSet chapterResult) throws SQLException {
|
||||||
|
return new Chapter(chapterResult.getInt("id_chapter"), chapterResult.getString("name"),
|
||||||
|
chapterResult.getTimestamp("start_date"), chapterResult.getTimestamp("end_date"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Completion makeCompletion(ResultSet completionResult) throws SQLException {
|
||||||
|
String fileName = null;
|
||||||
|
if (hasColumn(completionResult, "fileName"))
|
||||||
|
fileName = completionResult.getString("fileName");
|
||||||
|
String puzzleName = null;
|
||||||
|
if (hasColumn(completionResult, "name"))
|
||||||
|
puzzleName = completionResult.getString("name");
|
||||||
|
|
||||||
|
return new Completion(completionResult.getInt("fk_player"), completionResult.getInt("fk_puzzle"), completionResult.getInt("tries"),
|
||||||
|
fileName, completionResult.getInt("score"), puzzleName);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Player makePlayer(ResultSet playerResult, int id) throws SQLException {
|
||||||
|
Player p = new Player(playerResult.getString("pseudo"), playerResult.getString("email"),
|
||||||
|
playerResult.getString("firstName"), playerResult.getString("lastName"),
|
||||||
|
playerResult.getString("description"));
|
||||||
|
if (hasColumn(playerResult, "avatar")) {
|
||||||
|
p.setAvatar(playerResult.getBytes("avatar"));
|
||||||
|
}
|
||||||
|
if (hasColumn(playerResult, "score")) {
|
||||||
|
p.addCompletion(new Completion(playerResult.getInt("tries"), playerResult.getInt("score")));
|
||||||
|
for (int ct = 1; ct < playerResult.getInt("completions"); ct++)
|
||||||
|
{ // TODO refactor for V3
|
||||||
|
p.addCompletion(new Completion(0, 0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Manage groups
|
||||||
|
String groupName = playerResult.getString("name");
|
||||||
|
if (groupName != null) {
|
||||||
|
p.addGroup(makeGroup(playerResult));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ADD rank
|
||||||
|
PreparedStatement completionsStmt = DatabaseQuery.GET_PLAYER_RANK.prepare(con);
|
||||||
|
completionsStmt.setInt(1, id);
|
||||||
|
ResultSet result = completionsStmt.executeQuery();
|
||||||
|
while (result.next()) {
|
||||||
|
p.setRank(result.getInt("rank"));
|
||||||
|
}
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Group makeGroup(ResultSet result) throws SQLException {
|
||||||
|
return new Group(result.getString("name"), result.getInt("fk_chapter"), result.getInt("fk_puzzle"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Player makeGroupPlayer(ResultSet result) throws SQLException {
|
||||||
|
return new Player(result.getString("pseudo"), result.getInt("score"), result.getInt("tries"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Badge makeBadge(ResultSet rs) throws SQLException {
|
||||||
|
return new Badge(rs.getString("name"), rs.getBytes("logo"), rs.getInt("level"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean hasColumn(ResultSet rs, String columnName) throws SQLException {
|
||||||
|
// Found on StackOverflow
|
||||||
|
ResultSetMetaData rsmd = rs.getMetaData();
|
||||||
|
int columns = rsmd.getColumnCount();
|
||||||
|
for (int x = 1; x <= columns; x++) {
|
||||||
|
if (columnName.equals(rsmd.getColumnName(x)))
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Puzzle> getPuzzlesInChapter(int id) throws SQLException {
|
||||||
|
List<Puzzle> puzzles = new ArrayList<>();
|
||||||
|
ensureConnection();
|
||||||
|
PreparedStatement puzzleStmt = DatabaseQuery.PUZZLES_IN_CHAPTER_QUERY.prepare(this.con);
|
||||||
|
puzzleStmt.setInt(1, id);
|
||||||
|
ResultSet puzzleResult = puzzleStmt.executeQuery();
|
||||||
|
while (puzzleResult.next()) {
|
||||||
|
puzzles.add(makePuzzle(puzzleResult));
|
||||||
|
}
|
||||||
|
return puzzles;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a specific puzzle
|
||||||
|
*
|
||||||
|
* @param id The id of the puzzle
|
||||||
|
* @return The puzzle or null if an error occurred
|
||||||
|
*/
|
||||||
|
public Puzzle getPuzzle(int id) {
|
||||||
|
try {
|
||||||
|
ensureConnection();
|
||||||
|
PreparedStatement puzzleStmt = DatabaseQuery.SPECIFIC_PUZZLE_QUERY.prepare(this.con);
|
||||||
|
puzzleStmt.setInt(1, id);
|
||||||
|
ResultSet puzzleResult = puzzleStmt.executeQuery();
|
||||||
|
if (puzzleResult.next()) {
|
||||||
|
return makePuzzle(puzzleResult);
|
||||||
|
}
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getScore(int user, int puzzle) {
|
||||||
|
try {
|
||||||
|
ensureConnection();
|
||||||
|
PreparedStatement stmt = DatabaseQuery.SCORE_GROUP.prepare(this.con);
|
||||||
|
stmt.setInt(1, user);
|
||||||
|
stmt.setInt(2, puzzle);
|
||||||
|
ResultSet result = stmt.executeQuery();
|
||||||
|
if (result.next())
|
||||||
|
return result.getInt("score");
|
||||||
|
|
||||||
|
stmt = DatabaseQuery.SCORE.prepare(this.con);
|
||||||
|
stmt.setInt(1, user);
|
||||||
|
stmt.setInt(2, puzzle);
|
||||||
|
|
||||||
|
result = stmt.executeQuery();
|
||||||
|
if (result.next())
|
||||||
|
return result.getInt("score");
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Completion getCompletionGroup(int user, int puzzle) {
|
||||||
|
try {
|
||||||
|
PreparedStatement stmt = DatabaseQuery.GET_COMPLETION_GROUP.prepare(this.con);
|
||||||
|
stmt.setInt(1, user);
|
||||||
|
stmt.setInt(2, puzzle);
|
||||||
|
ResultSet result = stmt.executeQuery();
|
||||||
|
if (result.next())
|
||||||
|
return makeCompletion(result);
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return getCompletion(user, puzzle);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Completion getCompletion(int playerId, int puzzleId) {
|
||||||
|
try {
|
||||||
|
PreparedStatement completionsStmt = DatabaseQuery.GET_COMPLETION.prepare(this.con);
|
||||||
|
completionsStmt.setInt(1, puzzleId);
|
||||||
|
completionsStmt.setInt(2, playerId);
|
||||||
|
ResultSet result = completionsStmt.executeQuery();
|
||||||
|
if (result.next()) {
|
||||||
|
return makeCompletion(result);
|
||||||
|
}
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Player getPlayer(int idPlayer) {
|
||||||
|
try {
|
||||||
|
PreparedStatement completionsStmt = DatabaseQuery.GET_PLAYER_SIMPLE.prepare(this.con);
|
||||||
|
completionsStmt.setInt(1, idPlayer);
|
||||||
|
ResultSet result = completionsStmt.executeQuery();
|
||||||
|
if (result.next()) {
|
||||||
|
return makePlayer(result, idPlayer);
|
||||||
|
}
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean updatePseudo(int id, Player player, String pseudo){
|
||||||
|
try{
|
||||||
|
PreparedStatement statment = DatabaseQuery.GET_PLAYER_PSEUDO.prepare(this.con);
|
||||||
|
statment.setString(1, pseudo);
|
||||||
|
ResultSet result = statment.executeQuery();
|
||||||
|
if(result.next()) return false;
|
||||||
|
statment = DatabaseQuery.UPDATE_PLAYER_INFO.prepare(this.con);
|
||||||
|
statment.setString(1, player.getPseudo());
|
||||||
|
statment.setString(2, player.getEmail());
|
||||||
|
statment.setString(3, player.getFirstname());
|
||||||
|
statment.setString(4, player.getLastname());
|
||||||
|
statment.setInt(5, id);
|
||||||
|
return statment.executeUpdate() > 0;
|
||||||
|
}catch(Exception e){
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void updateProfile(int id, Player player, String lastname, String firstname){
|
||||||
|
try{
|
||||||
|
PreparedStatement statment = DatabaseQuery.UPDATE_PLAYER_INFO.prepare(this.con);
|
||||||
|
statment.setString(1, player.getPseudo());
|
||||||
|
statment.setString(2, player.getEmail());
|
||||||
|
statment.setString(3, firstname);
|
||||||
|
statment.setString(4, lastname);
|
||||||
|
statment.setInt(5, id);
|
||||||
|
statment.executeUpdate();
|
||||||
|
}catch(Exception e){
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void updatePassword(int id, String password){
|
||||||
|
try{
|
||||||
|
PreparedStatement statment = DatabaseQuery.UPDATE_PLAYER_PASSWORD.prepare(this.con);
|
||||||
|
statment.setString(1, Password.hash(password).withArgon2().getResult());
|
||||||
|
statment.setInt(2, id);
|
||||||
|
statment.executeUpdate();
|
||||||
|
}catch(Exception e){
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Player getPlayerDetails(int idPlayer) {
|
||||||
|
return getPlayerDetails(idPlayer, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Player getPlayerDetails(String pseudoPlayer) {
|
||||||
|
return getPlayerDetails(-1, pseudoPlayer);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Player getPlayerDetails(int id, String pseudo) {
|
||||||
|
try {
|
||||||
|
ensureConnection();
|
||||||
|
PreparedStatement completionsStmt;
|
||||||
|
if (pseudo != null) {
|
||||||
|
completionsStmt = DatabaseQuery.GET_PLAYER_DETAILS_BY_PSEUDO.prepare(this.con);
|
||||||
|
completionsStmt.setString(1, pseudo);
|
||||||
|
} else {
|
||||||
|
completionsStmt = DatabaseQuery.GET_PLAYER_DETAILS_BY_ID.prepare(this.con);
|
||||||
|
completionsStmt.setInt(1, id);
|
||||||
|
}
|
||||||
|
ResultSet result = completionsStmt.executeQuery();
|
||||||
|
Player player = null;
|
||||||
|
while (result.next()) {
|
||||||
|
if (player == null) {
|
||||||
|
id = result.getInt("id_player");
|
||||||
|
player = makePlayer(result, id);
|
||||||
|
completionsStmt = DatabaseQuery.GET_BADGES_OF_PLAYER.prepare(this.con);
|
||||||
|
completionsStmt.setInt(1, id);
|
||||||
|
ResultSet resultBadges = completionsStmt.executeQuery();
|
||||||
|
while (resultBadges.next()) {
|
||||||
|
player.addBadge(makeBadge(resultBadges));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
player.addGroup(makeGroup(result));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// ADD completions
|
||||||
|
completionsStmt = DatabaseQuery.GET_PLAYER_COMPLETIONS.prepare(con);
|
||||||
|
completionsStmt.setInt(1, id);
|
||||||
|
result = completionsStmt.executeQuery();
|
||||||
|
while (result.next()) {
|
||||||
|
player.addCompletion(makeCompletion(result));
|
||||||
|
}
|
||||||
|
|
||||||
|
return player;
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public SortedSet<Player> getAllPlayerForLeaderboard() {
|
||||||
|
try {
|
||||||
|
ensureConnection();
|
||||||
|
PreparedStatement playersStmt = DatabaseQuery.ALL_PLAYERS_FOR_LEADERBOARD.prepare(this.con);
|
||||||
|
ResultSet result = playersStmt.executeQuery();
|
||||||
|
ArrayList<Player> players = new ArrayList<Player>();
|
||||||
|
Player tmpPlayer;
|
||||||
|
while (result.next()) {
|
||||||
|
tmpPlayer = makePlayer(result, result.getInt("id_player"));
|
||||||
|
if (!players.contains(tmpPlayer)) {
|
||||||
|
players.add(tmpPlayer);
|
||||||
|
} else {
|
||||||
|
players.get(players.indexOf(tmpPlayer)).addGroup(makeGroup(result));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new TreeSet<Player>(players);
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public SortedSet<Group> getAllGroupForChapterLeaderboard(int chapterId){
|
||||||
|
try{
|
||||||
|
ensureConnection();
|
||||||
|
PreparedStatement groupsStmt = DatabaseQuery.ALL_GROUP_FOR_CHAPTER_LEADERBOARD.prepare(this.con);
|
||||||
|
groupsStmt.setInt(1, chapterId);
|
||||||
|
ResultSet result = groupsStmt.executeQuery();
|
||||||
|
List<Group> groups = new ArrayList<Group>();
|
||||||
|
Group tmpGroup;
|
||||||
|
while (result.next()) {
|
||||||
|
tmpGroup = makeGroup(result);
|
||||||
|
if (tmpGroup != null) {
|
||||||
|
int gPosition = groups.indexOf(tmpGroup);
|
||||||
|
if (gPosition < 0) {
|
||||||
|
tmpGroup.addPlayer(makeGroupPlayer(result));
|
||||||
|
groups.add(tmpGroup);
|
||||||
|
} else {
|
||||||
|
groups.get(gPosition).addPlayer(makeGroupPlayer(result));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new TreeSet<Group>(groups);
|
||||||
|
}catch(SQLException e){
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Badge getBadge(int badgeId) {
|
||||||
|
try {
|
||||||
|
ensureConnection();
|
||||||
|
PreparedStatement completionsStmt = DatabaseQuery.GET_BADGE.prepare(this.con);
|
||||||
|
completionsStmt.setInt(1, badgeId);
|
||||||
|
ResultSet result = completionsStmt.executeQuery();
|
||||||
|
if (result.next()) {
|
||||||
|
return makeBadge(result);
|
||||||
|
}
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a specific chapter
|
||||||
|
*
|
||||||
|
* @param id The id of the chapter
|
||||||
|
* @return The chapter or null if an error occurred
|
||||||
|
*/
|
||||||
|
public Chapter getChapter(int id) {
|
||||||
|
try {
|
||||||
|
ensureConnection();
|
||||||
|
PreparedStatement chapterStmt = DatabaseQuery.SPECIFIC_CHAPTER_QUERY.prepare(this.con);
|
||||||
|
chapterStmt.setInt(1, id);
|
||||||
|
ResultSet chapterResult = chapterStmt.executeQuery();
|
||||||
|
if (chapterResult.next()) {
|
||||||
|
Chapter chapter = makeChapter(chapterResult);
|
||||||
|
List<Puzzle> puzzles = getPuzzlesInChapter(id);
|
||||||
|
chapter.setPuzzles(puzzles);
|
||||||
|
return chapter;
|
||||||
|
}
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Chapter getChapter(Puzzle puzzle){
|
||||||
|
try {
|
||||||
|
ensureConnection();
|
||||||
|
PreparedStatement chapterStmt = DatabaseQuery.CHAPTER_FROM_PUZZLE.prepare(this.con);
|
||||||
|
chapterStmt.setInt(1, puzzle.getId());
|
||||||
|
ResultSet chapterResult = chapterStmt.executeQuery();
|
||||||
|
if (chapterResult.next()) {
|
||||||
|
Chapter chapter = makeChapter(chapterResult);
|
||||||
|
List<Puzzle> puzzles = getPuzzlesInChapter(chapter.getId());
|
||||||
|
chapter.setPuzzles(puzzles);
|
||||||
|
return chapter;
|
||||||
|
}
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all chapters in the database
|
||||||
|
*
|
||||||
|
* @return List of all chapters or null if an error occurred
|
||||||
|
*/
|
||||||
|
public List<Chapter> getAllChapters() {
|
||||||
|
try {
|
||||||
|
List<Chapter> chapterList = new ArrayList<>();
|
||||||
|
ensureConnection();
|
||||||
|
PreparedStatement chapterStmt = DatabaseQuery.ALL_CHAPTERS_QUERY.prepare(this.con);
|
||||||
|
ResultSet chapterResult = chapterStmt.executeQuery();
|
||||||
|
while (chapterResult.next()) {
|
||||||
|
Chapter chapter = makeChapter(chapterResult);
|
||||||
|
chapter.setPuzzles(getPuzzlesInChapter(chapter.getId()));
|
||||||
|
chapterList.add(chapter);
|
||||||
|
}
|
||||||
|
return chapterList;
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Group> getAllGroups() {
|
||||||
|
try {
|
||||||
|
ensureConnection();
|
||||||
|
List<Group> list = new ArrayList<>();
|
||||||
|
PreparedStatement stmt = DatabaseQuery.ALL_GROUPS.prepare(this.con);
|
||||||
|
ResultSet groupResult = stmt.executeQuery();
|
||||||
|
while (groupResult.next())
|
||||||
|
list.add(makeGroup(groupResult));
|
||||||
|
return list;
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a pseudo is available
|
||||||
|
*
|
||||||
|
* @param pseudo The pseudo to check
|
||||||
|
* @return True if the pseudo is available, false if it's already taken
|
||||||
|
*/
|
||||||
|
public boolean checkPseudoAvailability(String pseudo) {
|
||||||
|
return checkAvailability(pseudo, DatabaseQuery.CHECK_PSEUDO_AVAILABLE_QUERY.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if an email is available
|
||||||
|
*
|
||||||
|
* @param email The email to check
|
||||||
|
* @return True if the email is available, false if it's already taken
|
||||||
|
*/
|
||||||
|
public boolean checkEmailAvailability(String email) {
|
||||||
|
return checkAvailability(email, DatabaseQuery.CHECK_EMAIL_AVAILABLE_QUERY.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean checkAvailability(String queriedString, String correspondingQuery) {
|
||||||
|
try {
|
||||||
|
ensureConnection();
|
||||||
|
PreparedStatement statement = con.prepareStatement(correspondingQuery);
|
||||||
|
statement.setString(1, queriedString);
|
||||||
|
ResultSet result = statement.executeQuery();
|
||||||
|
return !result.next();
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register a new user
|
||||||
|
*
|
||||||
|
* @param pseudo The pseudo of the user
|
||||||
|
* @param email The email of the user
|
||||||
|
* @param password The password of the user
|
||||||
|
* @param firstname The firstname of the user
|
||||||
|
* @param lastname The lastname of the user
|
||||||
|
* @param description The description of the user
|
||||||
|
* @param sgroup The group of the user
|
||||||
|
* @param avatar The avatar of the user
|
||||||
|
* @return True if the user was registered, false if an error occurred
|
||||||
|
*/
|
||||||
|
public int register(String pseudo, String email, String password, String firstname, String lastname,
|
||||||
|
String description, String sgroup, String avatar) {
|
||||||
|
try {
|
||||||
|
ensureConnection();
|
||||||
|
con.setAutoCommit(false);
|
||||||
|
try (PreparedStatement playerStatement = con.prepareStatement(DatabaseQuery.REGISTER_QUERY.toString(),
|
||||||
|
Statement.RETURN_GENERATED_KEYS)) {
|
||||||
|
playerStatement.setString(1, pseudo);
|
||||||
|
playerStatement.setString(2, email);
|
||||||
|
playerStatement.setString(3, Password.hash(password).withArgon2().getResult());
|
||||||
|
playerStatement.setString(4, firstname);
|
||||||
|
playerStatement.setString(5, lastname);
|
||||||
|
playerStatement.setString(6, description);
|
||||||
|
playerStatement.setString(7, avatar);
|
||||||
|
if (playerStatement.executeUpdate() == 1) {
|
||||||
|
ResultSet inserted = playerStatement.getGeneratedKeys();
|
||||||
|
if (inserted.next()) {
|
||||||
|
int newPlayerId = inserted.getInt(1);
|
||||||
|
if (!sgroup.isEmpty()) {
|
||||||
|
try (PreparedStatement containsGroupsStatement = con
|
||||||
|
.prepareStatement(DatabaseQuery.REGISTER_PLAYER_IN_EXISTING_GROUP.toString())) {
|
||||||
|
containsGroupsStatement.setInt(1, newPlayerId);
|
||||||
|
containsGroupsStatement.setString(2, sgroup);
|
||||||
|
containsGroupsStatement.executeUpdate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
con.commit();
|
||||||
|
con.setAutoCommit(true);
|
||||||
|
return newPlayerId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (SQLException e) {
|
||||||
|
con.rollback();
|
||||||
|
con.setAutoCommit(true);
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Login a user
|
||||||
|
*
|
||||||
|
* @param username The username of the user
|
||||||
|
* @param password The password of the user
|
||||||
|
* @return id the id of the user, -1 if not login successefuly
|
||||||
|
*/
|
||||||
|
public int login(String username, String password){
|
||||||
|
try {
|
||||||
|
ensureConnection();
|
||||||
|
PreparedStatement statement = con.prepareStatement(DatabaseQuery.CHECK_PASSWORD.toString());
|
||||||
|
DatabaseQuery.PUZZLES_IN_CHAPTER_QUERY.prepare(this.con);
|
||||||
|
statement.setString(1, username);
|
||||||
|
ResultSet result = statement.executeQuery();
|
||||||
|
if (result.next()) {
|
||||||
|
String hashedPassword = result.getString("passwd");
|
||||||
|
if (Password.check(password, hashedPassword).withArgon2())
|
||||||
|
return result.getInt("id_player");
|
||||||
|
}
|
||||||
|
} catch (SQLException e) {
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Completion insertOrUpdatePuzzleResponse(int puzzleId, int userId, String fileName, byte[] code,
|
||||||
|
byte[] response, Puzzle currentPuzzle){
|
||||||
|
try {
|
||||||
|
ensureConnection();
|
||||||
|
Completion completion = getCompletionGroup(userId, puzzleId);
|
||||||
|
if (completion == null){
|
||||||
|
System.out.println("Completion is null");
|
||||||
|
completion = new Completion(userId, puzzleId, fileName, code, response, currentPuzzle);
|
||||||
|
insertCompletion(completion);
|
||||||
|
} else {
|
||||||
|
System.out.println(completion);
|
||||||
|
completion.addTry(currentPuzzle, response);
|
||||||
|
int lastUserId = completion.getPlayerId();
|
||||||
|
completion.updatePlayer(userId);
|
||||||
|
updateCompletion(completion, lastUserId);
|
||||||
|
}
|
||||||
|
return completion;
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void insertCompletion(Completion newCompletion) throws SQLException {
|
||||||
|
PreparedStatement statement = DatabaseQuery.INSERT_COMPLETION.prepare(this.con);
|
||||||
|
statement.setInt(1, newCompletion.getPuzzleId());
|
||||||
|
statement.setInt(2, newCompletion.getPlayerId());
|
||||||
|
statement.setInt(3, newCompletion.getTries());
|
||||||
|
statement.setBytes(4, newCompletion.getCode());
|
||||||
|
statement.setString(5, newCompletion.getFileName());
|
||||||
|
statement.setInt(6, newCompletion.getScore());
|
||||||
|
statement.executeUpdate();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean insertGroup(Group group, User creator) throws SQLException {
|
||||||
|
Integer groupId = getGroupId(group);
|
||||||
|
if (groupId == null)
|
||||||
|
ensureConnection();
|
||||||
|
PreparedStatement statement = DatabaseQuery.INSERT_GROUP.prepare(this.con);
|
||||||
|
statement.setString(1, group.getName());
|
||||||
|
statement.setObject(2, group.getLinkToChapter());
|
||||||
|
// statement.setObject(3, group.getLinkToPuzzle());
|
||||||
|
if (statement.executeUpdate() >= 0)
|
||||||
|
return insertUserInGroup(group, creator);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Group getPlayerGroup(int user, Integer chapter) throws SQLException {
|
||||||
|
ensureConnection();
|
||||||
|
PreparedStatement stmt = DatabaseQuery.GET_GROUP_FOR_PLAYER.prepare(this.con);
|
||||||
|
stmt.setInt(1, user);
|
||||||
|
stmt.setObject(2, chapter);
|
||||||
|
// stmt.setObject(3, puzzle);
|
||||||
|
|
||||||
|
ResultSet result = stmt.executeQuery();
|
||||||
|
if (result.next())
|
||||||
|
return makeGroup(result);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getGroupId(Group group) throws SQLException {
|
||||||
|
ensureConnection();
|
||||||
|
PreparedStatement stmt = DatabaseQuery.GET_GROUP_ID_BY_DATA.prepare(this.con);
|
||||||
|
stmt.setString(1, group.getName());
|
||||||
|
stmt.setObject(2, group.getLinkToChapter());
|
||||||
|
// stmt.setObject(3, group.getLinkToPuzzle());
|
||||||
|
|
||||||
|
ResultSet result = stmt.executeQuery();
|
||||||
|
if (result.next())
|
||||||
|
return result.getInt("id_group");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean insertUserInGroup(Group group, User user) throws SQLException {
|
||||||
|
Integer id = getGroupId(group);
|
||||||
|
Group alreadyInGroup = getPlayerGroup(user.getId(), group.getLinkToChapter());
|
||||||
|
if (id != null && alreadyInGroup == null) {
|
||||||
|
PreparedStatement stmt = DatabaseQuery.INSERT_PLAYER_IN_GROUP.prepare(this.con);
|
||||||
|
|
||||||
|
stmt.setInt(1, user.getId());
|
||||||
|
stmt.setInt(2, id);
|
||||||
|
|
||||||
|
return stmt.executeUpdate() >= 0;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean leaveGroup(Group group, User user) throws SQLException {
|
||||||
|
Integer id = getGroupId(group);
|
||||||
|
if (id != null) {
|
||||||
|
PreparedStatement stmt = DatabaseQuery.LEAVE_GROUP.prepare(this.con);
|
||||||
|
|
||||||
|
stmt.setInt(1, user.getId());
|
||||||
|
stmt.setInt(2, id);
|
||||||
|
|
||||||
|
return stmt.executeUpdate() >= 0;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void updateCompletion(Completion completionToUpdate, int user) throws SQLException{
|
||||||
|
System.out.println("update "+completionToUpdate);
|
||||||
|
PreparedStatement statement = DatabaseQuery.UPDATE_COMPLETION.prepare(this.con);
|
||||||
|
statement.setInt(1, completionToUpdate.getTries());
|
||||||
|
statement.setInt(2, completionToUpdate.getScore());
|
||||||
|
statement.setInt(3, completionToUpdate.getPlayerId());
|
||||||
|
statement.setInt(4, completionToUpdate.getPuzzleId());
|
||||||
|
statement.setInt(5, user);
|
||||||
|
statement.executeUpdate();
|
||||||
|
}
|
||||||
|
}
|
47
src/be/jeffcheasey88/peeratcode/routes/BadgeDetails.java
Normal file
47
src/be/jeffcheasey88/peeratcode/routes/BadgeDetails.java
Normal file
|
@ -0,0 +1,47 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.routes;
|
||||||
|
|
||||||
|
import java.util.Base64;
|
||||||
|
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.HttpWriter;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.Response;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.Route;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.User;
|
||||||
|
import be.jeffcheasey88.peeratcode.model.Badge;
|
||||||
|
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
|
||||||
|
|
||||||
|
public class BadgeDetails implements Response {
|
||||||
|
|
||||||
|
private final DatabaseRepository databaseRepo;
|
||||||
|
|
||||||
|
public BadgeDetails(DatabaseRepository databaseRepo) {
|
||||||
|
this.databaseRepo = databaseRepo;
|
||||||
|
}
|
||||||
|
|
||||||
|
@RouteDoc(path = "/badge/<id>", responseCode = 200, responseDescription = "JSON contenant les informations du badge")
|
||||||
|
@RouteDoc(responseCode = 400, responseDescription = "Aucun id donner")
|
||||||
|
|
||||||
|
@Route(path = "^\\/badge\\/([0-9]+)$", needLogin = true)
|
||||||
|
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
|
||||||
|
if (matcher.groupCount() > 0) {
|
||||||
|
int badgeId = Integer.parseInt(matcher.group(1));
|
||||||
|
Badge badge = databaseRepo.getBadge(badgeId);
|
||||||
|
JSONObject badgeJSON = new JSONObject();
|
||||||
|
if (badge != null) {
|
||||||
|
badgeJSON.put("name", badge.getName());
|
||||||
|
if (badge.getLogo() != null)
|
||||||
|
badgeJSON.put("logo", Base64.getEncoder().encodeToString(badge.getLogo()));
|
||||||
|
badgeJSON.put("level", badge.getLevel());
|
||||||
|
}
|
||||||
|
writer.response(200, "Access-Control-Allow-Origin: *");
|
||||||
|
writer.write(badgeJSON.toJSONString().replace("\\", ""));
|
||||||
|
} else {
|
||||||
|
writer.response(400, "Access-Control-Allow-Origin: *");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
61
src/be/jeffcheasey88/peeratcode/routes/ChapterElement.java
Normal file
61
src/be/jeffcheasey88/peeratcode/routes/ChapterElement.java
Normal file
|
@ -0,0 +1,61 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.routes;
|
||||||
|
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
|
||||||
|
import org.json.simple.JSONArray;
|
||||||
|
import org.json.simple.JSONObject;
|
||||||
|
|
||||||
|
import be.jeffcheasey88.peeratcode.bonus.extract.RouteDoc;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.HttpReader;
|
||||||
|
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.Puzzle;
|
||||||
|
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
|
||||||
|
|
||||||
|
public class ChapterElement implements Response {
|
||||||
|
|
||||||
|
private final DatabaseRepository databaseRepo;
|
||||||
|
|
||||||
|
public ChapterElement(DatabaseRepository databaseRepo) {
|
||||||
|
this.databaseRepo = databaseRepo;
|
||||||
|
}
|
||||||
|
|
||||||
|
@RouteDoc(path = "/chapter/<id>", responseCode = 200, responseDescription = "JSON contenant les informations du chapitre demander")
|
||||||
|
@RouteDoc(responseCode = 400, responseDescription = "Aucun id donner")
|
||||||
|
|
||||||
|
@Route(path = "^\\/chapter\\/([0-9]+)$", needLogin = true)
|
||||||
|
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception{
|
||||||
|
Chapter chapter = databaseRepo.getChapter(Integer.parseInt(matcher.group(1)));
|
||||||
|
if (chapter != null){
|
||||||
|
JSONObject chapterJSON = new JSONObject();
|
||||||
|
chapterJSON.put("id", chapter.getId());
|
||||||
|
chapterJSON.put("name", chapter.getName());
|
||||||
|
boolean show = chapter.isInCurrentTime();
|
||||||
|
chapterJSON.put("show", show);
|
||||||
|
|
||||||
|
if(show){
|
||||||
|
JSONArray puzzles = new JSONArray();
|
||||||
|
for (Puzzle puzzle : chapter.getPuzzles()){
|
||||||
|
JSONObject puzzleJSON = new JSONObject();
|
||||||
|
puzzleJSON.put("id", puzzle.getId());
|
||||||
|
puzzleJSON.put("name", puzzle.getName());
|
||||||
|
puzzleJSON.put("scoreMax", puzzle.getScoreMax());
|
||||||
|
if (puzzle.getTags() != null) puzzleJSON.put("tags", puzzle.getJsonTags());
|
||||||
|
int score = this.databaseRepo.getScore(user.getId(), puzzle.getId());
|
||||||
|
if(score >= 0) puzzleJSON.put("score", score);
|
||||||
|
puzzles.add(puzzleJSON);
|
||||||
|
}
|
||||||
|
chapterJSON.put("puzzles", puzzles);
|
||||||
|
}
|
||||||
|
|
||||||
|
writer.response(200, "Access-Control-Allow-Origin: *");
|
||||||
|
writer.write(chapterJSON.toJSONString());
|
||||||
|
} else {
|
||||||
|
writer.response(400, "Access-Control-Allow-Origin: *");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
48
src/be/jeffcheasey88/peeratcode/routes/ChapterList.java
Normal file
48
src/be/jeffcheasey88/peeratcode/routes/ChapterList.java
Normal file
|
@ -0,0 +1,48 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.routes;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
|
||||||
|
import org.json.simple.JSONArray;
|
||||||
|
import org.json.simple.JSONObject;
|
||||||
|
|
||||||
|
import be.jeffcheasey88.peeratcode.bonus.extract.RouteDoc;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.HttpReader;
|
||||||
|
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.repository.DatabaseRepository;
|
||||||
|
|
||||||
|
public class ChapterList implements Response {
|
||||||
|
|
||||||
|
private final DatabaseRepository databaseRepo;
|
||||||
|
|
||||||
|
public ChapterList(DatabaseRepository databaseRepo) {
|
||||||
|
this.databaseRepo = databaseRepo;
|
||||||
|
}
|
||||||
|
|
||||||
|
@RouteDoc(path = "/chapters", responseCode = 200, responseDescription = "JSON contenant les informations des chapitres")
|
||||||
|
@RouteDoc(responseCode = 400, responseDescription = "Aucun chapitre trouver")
|
||||||
|
|
||||||
|
@Route(path = "^\\/chapters$", needLogin = true)
|
||||||
|
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception{
|
||||||
|
List<Chapter> allChapters = databaseRepo.getAllChapters();
|
||||||
|
if(allChapters != null){
|
||||||
|
JSONArray chaptersJSON = new JSONArray();
|
||||||
|
for (Chapter chapter : allChapters) {
|
||||||
|
JSONObject chapterJSON = new JSONObject();
|
||||||
|
chapterJSON.put("id", chapter.getId());
|
||||||
|
chapterJSON.put("name", chapter.getName());
|
||||||
|
chapterJSON.put("show", chapter.isInCurrentTime());
|
||||||
|
chaptersJSON.add(chapterJSON);
|
||||||
|
}
|
||||||
|
writer.response(200, "Access-Control-Allow-Origin: *");
|
||||||
|
writer.write(chaptersJSON.toJSONString());
|
||||||
|
}else{
|
||||||
|
writer.response(400, "Access-Control-Allow-Origin: *");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,46 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.routes;
|
||||||
|
|
||||||
|
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.Locker.Key;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.Route;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.User;
|
||||||
|
import be.jeffcheasey88.peeratcode.model.Completion;
|
||||||
|
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
|
||||||
|
|
||||||
|
public class DynamicLeaderboard extends Leaderboard{
|
||||||
|
|
||||||
|
private Locker<Completion> locker;
|
||||||
|
|
||||||
|
public DynamicLeaderboard(DatabaseRepository databaseRepo, Locker<Completion> locker){
|
||||||
|
super(databaseRepo);
|
||||||
|
this.locker = locker;
|
||||||
|
}
|
||||||
|
|
||||||
|
@RouteDoc(path = "/rleaderboard/{id}", responseCode = 101, responseDescription = "WebSocket")
|
||||||
|
|
||||||
|
@Route(path = "^\\/rleaderboard\\/?(\\d+)?$", websocket = true)
|
||||||
|
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception{
|
||||||
|
Key key = new Key();
|
||||||
|
|
||||||
|
locker.init(key);
|
||||||
|
try {
|
||||||
|
while(!reader.isClosed()){
|
||||||
|
locker.getValue(key);
|
||||||
|
if(matcher.group(1) != null){
|
||||||
|
groupsLeaderboard(Integer.parseInt(matcher.group(1)), writer);
|
||||||
|
}else{
|
||||||
|
playersLeaderboard(writer);
|
||||||
|
}
|
||||||
|
locker.lock(key);
|
||||||
|
}
|
||||||
|
}catch(Exception e){
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
locker.remove(key);
|
||||||
|
}
|
||||||
|
}
|
92
src/be/jeffcheasey88/peeratcode/routes/Leaderboard.java
Normal file
92
src/be/jeffcheasey88/peeratcode/routes/Leaderboard.java
Normal file
|
@ -0,0 +1,92 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.routes;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.SortedSet;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
|
||||||
|
import org.json.simple.JSONArray;
|
||||||
|
import org.json.simple.JSONObject;
|
||||||
|
|
||||||
|
import be.jeffcheasey88.peeratcode.bonus.extract.RouteDoc;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.HttpReader;
|
||||||
|
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.model.Player;
|
||||||
|
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
|
||||||
|
|
||||||
|
public class Leaderboard implements Response {
|
||||||
|
|
||||||
|
private final DatabaseRepository databaseRepo;
|
||||||
|
|
||||||
|
public Leaderboard(DatabaseRepository databaseRepo) {
|
||||||
|
this.databaseRepo = databaseRepo;
|
||||||
|
}
|
||||||
|
|
||||||
|
@RouteDoc(path = "/leaderboard/{id}", responseCode = 200, responseDescription = "JSON contenant le leaderboard")
|
||||||
|
|
||||||
|
@Route(path = "^\\/leaderboard\\/?(\\d+)?$")
|
||||||
|
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
|
||||||
|
writer.response(200, "Access-Control-Allow-Origin: *");
|
||||||
|
if (matcher.group(1) != null) {
|
||||||
|
groupsLeaderboard(Integer.parseInt(matcher.group(1)), writer);
|
||||||
|
} else {
|
||||||
|
playersLeaderboard(writer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public final void groupsLeaderboard(int chapterId, HttpWriter writer) throws IOException {
|
||||||
|
Chapter chInfo = databaseRepo.getChapter(chapterId);
|
||||||
|
|
||||||
|
SortedSet<Group> allGroupsForChapter = databaseRepo.getAllGroupForChapterLeaderboard(chapterId);
|
||||||
|
JSONObject leaderboardJSON = new JSONObject();
|
||||||
|
if (chInfo.getStartDate() != null)
|
||||||
|
leaderboardJSON.put("start_date", chInfo.getStartDate().toString());
|
||||||
|
if (chInfo.getEndDate() != null)
|
||||||
|
leaderboardJSON.put("end_date", chInfo.getEndDate().toString());
|
||||||
|
JSONArray groupsJSON = new JSONArray();
|
||||||
|
if (allGroupsForChapter != null) {
|
||||||
|
int rank = 1;
|
||||||
|
int sameRankCount = 1;
|
||||||
|
Group previousGroup = null;
|
||||||
|
for (Group g : allGroupsForChapter) {
|
||||||
|
if (previousGroup != null) {
|
||||||
|
if (g.compareTo(previousGroup) == 0) {
|
||||||
|
sameRankCount++;
|
||||||
|
} else {
|
||||||
|
rank = rank + sameRankCount;
|
||||||
|
sameRankCount = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
groupsJSON.add(g.toJson(rank));
|
||||||
|
previousGroup = g;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
leaderboardJSON.put("groups", groupsJSON);
|
||||||
|
writer.write(leaderboardJSON.toJSONString().replace("\\", ""));
|
||||||
|
}
|
||||||
|
|
||||||
|
public final void playersLeaderboard(HttpWriter writer) throws IOException {
|
||||||
|
SortedSet<Player> allPlayers = databaseRepo.getAllPlayerForLeaderboard();
|
||||||
|
JSONArray playersJSON = new JSONArray();
|
||||||
|
if (allPlayers != null) {
|
||||||
|
for (Player player : allPlayers) {
|
||||||
|
JSONObject playerJSON = new JSONObject();
|
||||||
|
playerJSON.put("pseudo", player.getPseudo());
|
||||||
|
if (player.getGroups() != null)
|
||||||
|
playerJSON.put("groups", player.getJsonGroups());
|
||||||
|
// if (player.getAvatar() != null)
|
||||||
|
// playerJSON.put("avatar", Base64.getEncoder().encodeToString(player.getAvatar()));
|
||||||
|
playerJSON.put("rank", player.getRank());
|
||||||
|
playerJSON.put("score", player.getTotalScore());
|
||||||
|
playerJSON.put("completions", player.getTotalCompletion());
|
||||||
|
playerJSON.put("tries", player.getTotalTries());
|
||||||
|
playersJSON.add(playerJSON);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
writer.write(playersJSON.toJSONString().replace("\\", ""));
|
||||||
|
}
|
||||||
|
}
|
61
src/be/jeffcheasey88/peeratcode/routes/PlayerDetails.java
Normal file
61
src/be/jeffcheasey88/peeratcode/routes/PlayerDetails.java
Normal file
|
@ -0,0 +1,61 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.routes;
|
||||||
|
|
||||||
|
import java.util.Base64;
|
||||||
|
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.HttpWriter;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.Response;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.Route;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.User;
|
||||||
|
import be.jeffcheasey88.peeratcode.model.Player;
|
||||||
|
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
|
||||||
|
|
||||||
|
public class PlayerDetails implements Response {
|
||||||
|
|
||||||
|
private final DatabaseRepository databaseRepo;
|
||||||
|
|
||||||
|
public PlayerDetails(DatabaseRepository databaseRepo) {
|
||||||
|
this.databaseRepo = databaseRepo;
|
||||||
|
}
|
||||||
|
|
||||||
|
@RouteDoc(path = "/player/{id}", responseCode = 200, responseDescription = "JSON contenant les informations de l'utilisateur")
|
||||||
|
@RouteDoc(responseCode = 400, responseDescription = "Utilisateur introuvable dans la base de donnée")
|
||||||
|
|
||||||
|
@Route(path = "^\\/player\\/?(.+)?$", needLogin = true)
|
||||||
|
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
|
||||||
|
Player player;
|
||||||
|
if (matcher.group(1) != null) {
|
||||||
|
player = databaseRepo.getPlayerDetails(matcher.group(1));
|
||||||
|
} else {
|
||||||
|
player = databaseRepo.getPlayerDetails(user.getId());
|
||||||
|
}
|
||||||
|
JSONObject playerJSON = new JSONObject();
|
||||||
|
if (player != null) {
|
||||||
|
playerJSON.put("pseudo", player.getPseudo());
|
||||||
|
playerJSON.put("email", player.getEmail());
|
||||||
|
playerJSON.put("firstname", player.getFirstname());
|
||||||
|
playerJSON.put("lastname", player.getLastname());
|
||||||
|
playerJSON.put("description", player.getDescription());
|
||||||
|
if (player.getGroups() != null)
|
||||||
|
playerJSON.put("groups", player.getJsonGroups());
|
||||||
|
playerJSON.put("rank", player.getRank());
|
||||||
|
playerJSON.put("score", player.getTotalScore());
|
||||||
|
playerJSON.put("completions", player.getTotalCompletion());
|
||||||
|
playerJSON.put("completionsList", player.getJsonCompletions());
|
||||||
|
playerJSON.put("tries", player.getTotalTries());
|
||||||
|
if (player.getBadges() != null)
|
||||||
|
playerJSON.put("badges", player.getJsonBadges());
|
||||||
|
if (player.getAvatar() != null)
|
||||||
|
playerJSON.put("avatar", Base64.getEncoder().encodeToString(player.getAvatar()));
|
||||||
|
writer.response(200, "Access-Control-Allow-Origin: *");
|
||||||
|
writer.write(playerJSON.toJSONString().replace("\\", ""));
|
||||||
|
} else {
|
||||||
|
writer.response(400, "Access-Control-Allow-Origin: *");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
72
src/be/jeffcheasey88/peeratcode/routes/PuzzleElement.java
Normal file
72
src/be/jeffcheasey88/peeratcode/routes/PuzzleElement.java
Normal file
|
@ -0,0 +1,72 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.routes;
|
||||||
|
|
||||||
|
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.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.Completion;
|
||||||
|
import be.jeffcheasey88.peeratcode.model.Puzzle;
|
||||||
|
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
|
||||||
|
|
||||||
|
public class PuzzleElement implements Response {
|
||||||
|
|
||||||
|
private final DatabaseRepository databaseRepo;
|
||||||
|
|
||||||
|
public PuzzleElement(DatabaseRepository databaseRepo) {
|
||||||
|
this.databaseRepo = databaseRepo;
|
||||||
|
}
|
||||||
|
|
||||||
|
@RouteDoc(path = "/puzzle/<id>", responseCode = 200, responseDescription = "JSON contenant les informations du puzzle")
|
||||||
|
@RouteDoc(responseCode = 400, responseDescription = "puzzle introuvable dans la base de donnée")
|
||||||
|
@RouteDoc(responseCode = 423, responseDescription = "L'utilisateur essaye de voir le puzzle en dehors de l'event")
|
||||||
|
|
||||||
|
@Route(path = "^\\/puzzle\\/([0-9]+)$", needLogin = true)
|
||||||
|
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
|
||||||
|
Puzzle puzzle = databaseRepo.getPuzzle(extractId(matcher));
|
||||||
|
if (puzzle != null){
|
||||||
|
Chapter chapter = this.databaseRepo.getChapter(puzzle);
|
||||||
|
if(chapter.getStartDate() != null){
|
||||||
|
if(LocalDateTime.now().isBefore(chapter.getStartDate().toLocalDateTime())){
|
||||||
|
writer.response(423, "Access-Control-Allow-Origin: *");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// if(chapter.getEndDate() != null){
|
||||||
|
// if(LocalDateTime.now().isAfter(chapter.getEndDate().toLocalDateTime())){
|
||||||
|
// writer.response(423, "Access-Control-Allow-Origin: *");
|
||||||
|
// return;
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
JSONObject puzzleJSON = new JSONObject();
|
||||||
|
puzzleJSON.put("id", puzzle.getId());
|
||||||
|
puzzleJSON.put("name", puzzle.getName());
|
||||||
|
puzzleJSON.put("content", puzzle.getContent());
|
||||||
|
puzzleJSON.put("scoreMax", puzzle.getScoreMax());
|
||||||
|
if(puzzle.getTags() != null) puzzleJSON.put("tags", puzzle.getJsonTags());
|
||||||
|
Completion completion = this.databaseRepo.getCompletionGroup(user.getId(), puzzle.getId());
|
||||||
|
if(completion != null && completion.getScore() >= 0){
|
||||||
|
puzzleJSON.put("score", completion.getScore());
|
||||||
|
puzzleJSON.put("tries", completion.getTries());
|
||||||
|
}
|
||||||
|
if(puzzle.getDepend() > 0) puzzleJSON.put("depend", puzzle.getDepend());
|
||||||
|
writer.response(200, "Access-Control-Allow-Origin: *", "Content-Type: application/json");
|
||||||
|
writer.write(puzzleJSON.toJSONString());
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
writer.response(400, "Access-Control-Allow-Origin: *");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private int extractId(Matcher matcher) {
|
||||||
|
return Integer.parseInt(matcher.group(1));
|
||||||
|
}
|
||||||
|
}
|
159
src/be/jeffcheasey88/peeratcode/routes/PuzzleResponse.java
Normal file
159
src/be/jeffcheasey88/peeratcode/routes/PuzzleResponse.java
Normal file
|
@ -0,0 +1,159 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.routes;
|
||||||
|
|
||||||
|
import static be.jeffcheasey88.peeratcode.framework.RequestType.POST;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
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.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.Player;
|
||||||
|
import be.jeffcheasey88.peeratcode.model.Puzzle;
|
||||||
|
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
|
||||||
|
|
||||||
|
public class PuzzleResponse implements Response {
|
||||||
|
private final DatabaseRepository databaseRepo;
|
||||||
|
private final String usersFilesPath;
|
||||||
|
|
||||||
|
private final Locker<Completion> leaderboard;
|
||||||
|
|
||||||
|
public PuzzleResponse(DatabaseRepository databaseRepo, String initUsersFilesPath, Locker<Completion> locker){
|
||||||
|
this.databaseRepo = databaseRepo;
|
||||||
|
usersFilesPath = initUsersFilesPath;
|
||||||
|
this.leaderboard = locker;
|
||||||
|
}
|
||||||
|
|
||||||
|
@RouteDoc(path = "/puzzleResponse/<id>", responseCode = 200, responseDescription = "Bonne réponse, json contenant les points + tries")
|
||||||
|
@RouteDoc(responseCode = 400, responseDescription = "Pas de réponse")
|
||||||
|
@RouteDoc(responseCode = 403, responseDescription = "Déjà répondu")
|
||||||
|
@RouteDoc(responseCode = 406, responseDescription = "Mauvaise réponse")
|
||||||
|
@RouteDoc(responseCode = 423, responseDescription = "L'utilisateur essaye de répondre en dehors de l'event")
|
||||||
|
|
||||||
|
@Route(path = "^\\/puzzleResponse\\/([0-9]+)$", type = POST, needLogin = true)
|
||||||
|
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception{
|
||||||
|
ReceivedResponse received = new ReceivedResponse(matcher, reader);
|
||||||
|
if (received.getResponse() == null){
|
||||||
|
writer.response(400, "Access-Control-Allow-Origin: *");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
//saveSourceCode(received, databaseRepo.getPlayer(user.getId()));
|
||||||
|
JSONObject responseJSON = new JSONObject();
|
||||||
|
if(this.databaseRepo.getScore(user.getId(), received.getPuzzleId()) > 0){
|
||||||
|
writer.response(403, "Access-Control-Allow-Origin: *");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Puzzle currentPuzzle = databaseRepo.getPuzzle(received.getPuzzleId());
|
||||||
|
Chapter chapter = this.databaseRepo.getChapter(currentPuzzle);
|
||||||
|
if(chapter.getStartDate() != null){
|
||||||
|
if(LocalDateTime.now().isBefore(chapter.getStartDate().toLocalDateTime())){
|
||||||
|
writer.response(423, "Access-Control-Allow-Origin: *");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(chapter.getEndDate() != null){
|
||||||
|
if(LocalDateTime.now().isAfter(chapter.getEndDate().toLocalDateTime())){
|
||||||
|
if(Arrays.equals(currentPuzzle.getSoluce(), received.getResponse())){
|
||||||
|
writer.response(200, "Access-Control-Allow-Origin: *", "Content-Type: application/json");
|
||||||
|
JSONObject theoSaisPasJusteRecevoir200 = new JSONObject();
|
||||||
|
theoSaisPasJusteRecevoir200.put("success", true);
|
||||||
|
writer.write(theoSaisPasJusteRecevoir200.toJSONString());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
writer.response(423, "Access-Control-Allow-Origin: *");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Group group = this.databaseRepo.getPlayerGroup(user.getId(), chapter.getId());
|
||||||
|
if(group == null){
|
||||||
|
writer.response(423, "Access-Control-Allow-Origin: *");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Completion completion = databaseRepo.insertOrUpdatePuzzleResponse(received.getPuzzleId(), user.getId(),
|
||||||
|
received.getFileName(), received.getSourceCode(), received.getResponse(), currentPuzzle);
|
||||||
|
if(completion == null){
|
||||||
|
writer.response(400, "Access-Control-Allow-Origin: *");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(completion.getScore() > 0){
|
||||||
|
writer.response(200, "Access-Control-Allow-Origin: *", "Content-Type: application/json");
|
||||||
|
responseJSON.put("score", completion.getScore());
|
||||||
|
responseJSON.put("tries", completion.getTries());
|
||||||
|
|
||||||
|
}else{
|
||||||
|
writer.response(406, "Access-Control-Allow-Origin: *", "Content-Type: application/json");
|
||||||
|
responseJSON.put("tries", completion.getTries());
|
||||||
|
}
|
||||||
|
writer.write(responseJSON.toJSONString());
|
||||||
|
writer.flush();
|
||||||
|
|
||||||
|
leaderboard.setValue(completion);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void saveSourceCode(ReceivedResponse received, Player player){
|
||||||
|
try{
|
||||||
|
Path path = Paths.get(String.format("%s/%s/puz%04d-%s", usersFilesPath, player.getPseudo(),
|
||||||
|
received.getPuzzleId(), received.getFileName()));
|
||||||
|
Files.write(path, received.getSourceCode());
|
||||||
|
}catch (IOException e){
|
||||||
|
System.err.println("ERREUR D'ENREGISTREMENT DU CODE POUR PUZZLE_RESPONSE : " + e.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
class ReceivedResponse {
|
||||||
|
|
||||||
|
private int puzzleId;
|
||||||
|
private byte[] response;
|
||||||
|
private String fileName;
|
||||||
|
private byte[] sourceCode;
|
||||||
|
|
||||||
|
public ReceivedResponse(Matcher matcher, HttpReader reader) throws Exception {
|
||||||
|
puzzleId = Integer.parseInt(matcher.group(1));
|
||||||
|
|
||||||
|
List<String> multiPartData = reader.readMultiPartData();
|
||||||
|
if (multiPartData != null && multiPartData.size() > 0) {
|
||||||
|
this.response = multiPartData.get(0).getBytes();
|
||||||
|
if (multiPartData.size() == 3) {
|
||||||
|
this.fileName = multiPartData.get(1);
|
||||||
|
this.sourceCode = multiPartData.get(2).getBytes();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getPuzzleId() {
|
||||||
|
return puzzleId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] getResponse() {
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFileName() {
|
||||||
|
return fileName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] getSourceCode() {
|
||||||
|
return sourceCode;
|
||||||
|
}
|
||||||
|
}
|
37
src/be/jeffcheasey88/peeratcode/routes/Result.java
Normal file
37
src/be/jeffcheasey88/peeratcode/routes/Result.java
Normal file
|
@ -0,0 +1,37 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.routes;
|
||||||
|
|
||||||
|
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.Response;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.Route;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.User;
|
||||||
|
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
|
||||||
|
|
||||||
|
public class Result implements Response {
|
||||||
|
|
||||||
|
private DatabaseRepository repo;
|
||||||
|
|
||||||
|
public Result(DatabaseRepository repo) {
|
||||||
|
this.repo = repo;
|
||||||
|
}
|
||||||
|
|
||||||
|
@RouteDoc(path = "/result/<id>", responseCode = 200, responseDescription = "Le score")
|
||||||
|
@RouteDoc(responseCode = 425, responseDescription = "Puzzle pas compléter")
|
||||||
|
|
||||||
|
@Route(path = "^\\/result\\/(\\d+)$", needLogin = true)
|
||||||
|
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
|
||||||
|
int puzzle = Integer.parseInt(matcher.group(1));
|
||||||
|
|
||||||
|
int score = this.repo.getScore(user.getId(), puzzle);
|
||||||
|
if (score < 0) {
|
||||||
|
writer.response(425, "Access-Control-Allow-Origin: *");
|
||||||
|
} else {
|
||||||
|
writer.response(200, "Access-Control-Allow-Origin: *");
|
||||||
|
writer.write(score + "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,49 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.routes.admins;
|
||||||
|
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
|
||||||
|
import org.json.simple.JSONObject;
|
||||||
|
|
||||||
|
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.framework.Locker.Key;
|
||||||
|
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
|
||||||
|
|
||||||
|
public class DynamicLogs implements Response{
|
||||||
|
|
||||||
|
private Locker<Object> locker; //Context
|
||||||
|
private DatabaseRepository repo;
|
||||||
|
|
||||||
|
public DynamicLogs(DatabaseRepository repo, Locker<Object> locker){
|
||||||
|
this.repo = repo;
|
||||||
|
this.locker = locker;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Route(path = "^/admin/logs$", needLogin = true, websocket = true)
|
||||||
|
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
|
||||||
|
//check if admin
|
||||||
|
|
||||||
|
Key key = new Key();
|
||||||
|
|
||||||
|
locker.init(key);
|
||||||
|
try {
|
||||||
|
while(!reader.isClosed()){
|
||||||
|
Object instance = locker.getValue(key);
|
||||||
|
JSONObject json = new JSONObject();
|
||||||
|
writer.write(json.toJSONString());
|
||||||
|
writer.flush();
|
||||||
|
locker.lock(key);
|
||||||
|
}
|
||||||
|
}catch(Exception e){
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
locker.remove(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,67 @@
|
||||||
|
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.Group;
|
||||||
|
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
|
||||||
|
|
||||||
|
public class GroupCreate implements Response {
|
||||||
|
|
||||||
|
private Locker<Group> locker;
|
||||||
|
private DatabaseRepository repo;
|
||||||
|
private int groupDelay;
|
||||||
|
|
||||||
|
public GroupCreate(DatabaseRepository repo, Locker<Group> locker, int groupDelay){
|
||||||
|
this.repo = repo;
|
||||||
|
this.locker = locker;
|
||||||
|
this.groupDelay = groupDelay;
|
||||||
|
}
|
||||||
|
|
||||||
|
@RouteDoc(path = "/groupCreate", responseCode = 200, responseDescription = "Le groupe a été créé")
|
||||||
|
@RouteDoc(responseCode = 403, responseDescription = "L'utilisateur est déjà dans le groupe / ne peux pas le rejoindre")
|
||||||
|
@RouteDoc(responseCode = 423, responseDescription = "L'utilisateur essaye de crée un groupe après le délai maximum de création de l'event")
|
||||||
|
|
||||||
|
@Route(path = "^\\/groupCreate$", type = POST, needLogin = true)
|
||||||
|
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception{
|
||||||
|
Group newGroup = new Group(reader.readJson());
|
||||||
|
|
||||||
|
if (this.repo.getPlayerGroup(user.getId(), newGroup.getLinkToChapter()) == null) {
|
||||||
|
try {
|
||||||
|
if(this.repo.getGroupId(newGroup) == null) throw new NullPointerException();
|
||||||
|
writer.response(403, "Access-Control-Allow-Origin: *");
|
||||||
|
return;
|
||||||
|
}catch(NullPointerException e){
|
||||||
|
if(newGroup.getLinkToChapter() != null){
|
||||||
|
Chapter chapter = this.repo.getChapter(newGroup.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.insertGroup(newGroup, user)) {
|
||||||
|
writer.response(200, "Access-Control-Allow-Origin: *");
|
||||||
|
|
||||||
|
locker.setValue(newGroup);
|
||||||
|
} else {
|
||||||
|
writer.response(403, "Access-Control-Allow-Origin: *");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}else {
|
||||||
|
writer.response(403, "Access-Control-Allow-Origin: *");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
76
src/be/jeffcheasey88/peeratcode/routes/groups/GroupJoin.java
Normal file
76
src/be/jeffcheasey88/peeratcode/routes/groups/GroupJoin.java
Normal file
|
@ -0,0 +1,76 @@
|
||||||
|
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.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());
|
||||||
|
|
||||||
|
Group userGroup = this.repo.getPlayerGroup(user.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, user)) {
|
||||||
|
writer.response(200, "Access-Control-Allow-Origin: *");
|
||||||
|
|
||||||
|
leaderboard.setValue(new Completion(0, 0, 0, null, 0));
|
||||||
|
} else {
|
||||||
|
writer.response(403, "Access-Control-Allow-Origin: *");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
34
src/be/jeffcheasey88/peeratcode/routes/groups/GroupList.java
Normal file
34
src/be/jeffcheasey88/peeratcode/routes/groups/GroupList.java
Normal file
|
@ -0,0 +1,34 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.routes.groups;
|
||||||
|
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
|
||||||
|
import org.json.simple.JSONArray;
|
||||||
|
|
||||||
|
import be.jeffcheasey88.peeratcode.bonus.extract.RouteDoc;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.HttpReader;
|
||||||
|
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.Group;
|
||||||
|
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
|
||||||
|
|
||||||
|
public class GroupList implements Response {
|
||||||
|
|
||||||
|
private DatabaseRepository repo;
|
||||||
|
|
||||||
|
public GroupList(DatabaseRepository repo) {
|
||||||
|
this.repo = repo;
|
||||||
|
}
|
||||||
|
|
||||||
|
@RouteDoc(path = "/groups", responseCode = 200, responseDescription = "JSON avec la liste des groups")
|
||||||
|
|
||||||
|
@Route(path = "^\\/groups$", needLogin = true)
|
||||||
|
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
|
||||||
|
writer.response(200, "Access-Control-Allow-Origin: *");
|
||||||
|
JSONArray result = new JSONArray();
|
||||||
|
for(Group group : this.repo.getAllGroups()) result.add(group.toJson());
|
||||||
|
writer.write(result.toJSONString());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
68
src/be/jeffcheasey88/peeratcode/routes/groups/GroupQuit.java
Normal file
68
src/be/jeffcheasey88/peeratcode/routes/groups/GroupQuit.java
Normal file
|
@ -0,0 +1,68 @@
|
||||||
|
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.repository.DatabaseRepository;
|
||||||
|
|
||||||
|
public class GroupQuit implements Response{
|
||||||
|
|
||||||
|
private DatabaseRepository repo;
|
||||||
|
private int groupDelay;
|
||||||
|
|
||||||
|
private final Locker<Completion> leaderboard;
|
||||||
|
|
||||||
|
public GroupQuit(DatabaseRepository repo, int groupDelay, Locker<Completion> locker){
|
||||||
|
this.repo = repo;
|
||||||
|
this.groupDelay = groupDelay;
|
||||||
|
|
||||||
|
this.leaderboard = locker;
|
||||||
|
}
|
||||||
|
|
||||||
|
@RouteDoc(path = "/groupQuit", responseCode = 200, responseDescription = "L'utilisateur à quitter le groupe")
|
||||||
|
@RouteDoc(responseCode = 403, responseDescription = "L'utilisateur n'est pas dans le groupe / n'a pas pu le quittez")
|
||||||
|
@RouteDoc(responseCode = 423, responseDescription = "L'utilisateur essaye de quitter un groupe après le délai maximum de création de l'event")
|
||||||
|
|
||||||
|
@Route(path = "^\\/groupQuit$", type = POST, needLogin = true)
|
||||||
|
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception{
|
||||||
|
Group group = new Group(reader.readJson());
|
||||||
|
|
||||||
|
Group userGroup = this.repo.getPlayerGroup(user.getId(), group.getLinkToChapter());
|
||||||
|
if(!group.equals(userGroup)){
|
||||||
|
writer.response(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(LocalDateTime.now().isAfter(start)){
|
||||||
|
writer.response(423, "Access-Control-Allow-Origin: *");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.repo.leaveGroup(group, user)) {
|
||||||
|
writer.response(200, "Access-Control-Allow-Origin: *");
|
||||||
|
|
||||||
|
leaderboard.setValue(new Completion(0, 0, 0, null, 0));
|
||||||
|
} else {
|
||||||
|
writer.response(403, "Access-Control-Allow-Origin: *");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,35 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.routes.users;
|
||||||
|
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
|
||||||
|
import org.jose4j.json.internal.json_simple.JSONObject;
|
||||||
|
|
||||||
|
import be.jeffcheasey88.peeratcode.bonus.extract.RouteDoc;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.HttpReader;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.HttpWriter;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.RequestType;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.Response;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.Route;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.User;
|
||||||
|
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
|
||||||
|
|
||||||
|
public class ChangePassword implements Response{
|
||||||
|
|
||||||
|
private DatabaseRepository repo;
|
||||||
|
|
||||||
|
public ChangePassword(DatabaseRepository repo){
|
||||||
|
this.repo = repo;
|
||||||
|
}
|
||||||
|
|
||||||
|
@RouteDoc(path = "/user/cpw", responseCode = 200, responseDescription = "L'utilisateur a mis à jours sont mots de passe")
|
||||||
|
@RouteDoc(responseCode = 400, responseDescription = "L'utilisateur a envoyer un mots de passe invalide")
|
||||||
|
|
||||||
|
@Route(path = "^/user/cpw$", type = RequestType.POST, needLogin = true)
|
||||||
|
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
|
||||||
|
String password = (String) reader.<JSONObject>readJson().get("password");
|
||||||
|
|
||||||
|
repo.updatePassword(user.getId(), password);
|
||||||
|
writer.response(200, "Access-Control-Allow-Origin: *");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,25 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.routes.users;
|
||||||
|
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.HttpReader;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.HttpWriter;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.Response;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.Route;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.User;
|
||||||
|
|
||||||
|
public class ForgotPassword implements Response{
|
||||||
|
|
||||||
|
@Route(path = "^/user/fpw$")
|
||||||
|
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
|
||||||
|
if(user != null){
|
||||||
|
writer.response(403, "Access-Control-Allow-Origin: *");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
}
|
55
src/be/jeffcheasey88/peeratcode/routes/users/Login.java
Normal file
55
src/be/jeffcheasey88/peeratcode/routes/users/Login.java
Normal file
|
@ -0,0 +1,55 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.routes.users;
|
||||||
|
|
||||||
|
import static be.jeffcheasey88.peeratcode.framework.RequestType.POST;
|
||||||
|
|
||||||
|
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.HttpWriter;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.Response;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.Route;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.Router;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.User;
|
||||||
|
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
|
||||||
|
import be.jeffcheasey88.peeratcode.utils.FormResponse;
|
||||||
|
|
||||||
|
public class Login extends FormResponse{
|
||||||
|
|
||||||
|
private DatabaseRepository databaseRepo;
|
||||||
|
private Router router;
|
||||||
|
|
||||||
|
public Login(DatabaseRepository databaseRepo, Router router){
|
||||||
|
this.databaseRepo = databaseRepo;
|
||||||
|
this.router = router;
|
||||||
|
}
|
||||||
|
|
||||||
|
@RouteDoc(path = "/login", responseCode = 200, responseDescription = "L'utilisateur est inscrit")
|
||||||
|
@RouteDoc(responseCode = 403, responseDescription = "L'utilisateur est connecté")
|
||||||
|
@RouteDoc(responseCode = 400, responseDescription = "Aucune données fournie / données invalide")
|
||||||
|
|
||||||
|
@Route(path = "^\\/login$", type = POST)
|
||||||
|
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
|
||||||
|
if(user != null){
|
||||||
|
writer.response(403, "Access-Control-Allow-Origin: *");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
JSONObject json = json(reader);
|
||||||
|
if(!areValids("pseudo", "passwd")){
|
||||||
|
writer.response(400, "Access-Control-Allow-Origin: *");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
int id;
|
||||||
|
if((id = databaseRepo.login((String)json.get("pseudo"), (String)json.get("passwd"))) >= 0){
|
||||||
|
writer.response(200,
|
||||||
|
"Access-Control-Allow-Origin: *",
|
||||||
|
"Access-Control-Expose-Headers: Authorization",
|
||||||
|
"Authorization: Bearer " + this.router.createAuthUser(id));
|
||||||
|
}else{
|
||||||
|
writer.response(400,"Access-Control-Allow-Origin: *");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,57 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.routes.users;
|
||||||
|
|
||||||
|
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.HttpWriter;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.RequestType;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.Response;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.Route;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.User;
|
||||||
|
import be.jeffcheasey88.peeratcode.model.Player;
|
||||||
|
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
|
||||||
|
|
||||||
|
public class ProfileSettings implements Response{
|
||||||
|
|
||||||
|
private DatabaseRepository repo;
|
||||||
|
|
||||||
|
public ProfileSettings(DatabaseRepository repo){
|
||||||
|
this.repo = repo;
|
||||||
|
}
|
||||||
|
|
||||||
|
@RouteDoc(path = "/user/settings", responseCode = 200, responseDescription = "L'utilisateur a mis à jours sont profile")
|
||||||
|
@RouteDoc(responseCode = 400, responseDescription = "L'utilisateur a envoyer une donnée unique, déjà utilisée")
|
||||||
|
|
||||||
|
@Route(path = "^/user/settings$", type = RequestType.POST, needLogin = true)
|
||||||
|
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception {
|
||||||
|
JSONObject json = reader.readJson();
|
||||||
|
|
||||||
|
String pseudo = (String) json.get("pseudo");
|
||||||
|
String email = (String) json.get("email");
|
||||||
|
String firstname = (String) json.get("firstname");
|
||||||
|
String lastname = (String) json.get("lastname");
|
||||||
|
Player player = repo.getPlayer(user.getId());
|
||||||
|
|
||||||
|
if(!player.getPseudo().equals(pseudo)){
|
||||||
|
if(!repo.updatePseudo(user.getId(), player, pseudo)){
|
||||||
|
writer.response(400, "Access-Control-Allow-Origin: *");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
player.setPseudo(pseudo);
|
||||||
|
}
|
||||||
|
|
||||||
|
if(!player.getEmail().equals(email)){
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
if((!player.getFirstname().equals(firstname)) || (!player.getLastname().equals(lastname))){
|
||||||
|
repo.updateProfile(user.getId(), player, lastname, firstname);
|
||||||
|
}
|
||||||
|
|
||||||
|
writer.response(200, "Access-Control-Allow-Origin: *");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
143
src/be/jeffcheasey88/peeratcode/routes/users/Register.java
Normal file
143
src/be/jeffcheasey88/peeratcode/routes/users/Register.java
Normal file
|
@ -0,0 +1,143 @@
|
||||||
|
package be.jeffcheasey88.peeratcode.routes.users;
|
||||||
|
|
||||||
|
import static be.jeffcheasey88.peeratcode.framework.RequestType.POST;
|
||||||
|
|
||||||
|
import java.io.BufferedWriter;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.OutputStreamWriter;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.security.KeyPair;
|
||||||
|
import java.security.KeyPairGenerator;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.Base64.Encoder;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
|
||||||
|
import javax.net.ssl.HttpsURLConnection;
|
||||||
|
|
||||||
|
import org.json.simple.JSONAware;
|
||||||
|
import org.json.simple.JSONObject;
|
||||||
|
|
||||||
|
import be.jeffcheasey88.peeratcode.bonus.extract.RouteDoc;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.HttpReader;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.HttpWriter;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.Route;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.Router;
|
||||||
|
import be.jeffcheasey88.peeratcode.framework.User;
|
||||||
|
import be.jeffcheasey88.peeratcode.repository.DatabaseRepository;
|
||||||
|
import be.jeffcheasey88.peeratcode.utils.FormResponse;
|
||||||
|
|
||||||
|
public class Register extends FormResponse {
|
||||||
|
|
||||||
|
private DatabaseRepository databaseRepo;
|
||||||
|
private Router router;
|
||||||
|
private String usersFilesPath;
|
||||||
|
private KeyPairGenerator generator;
|
||||||
|
private Encoder encoder;
|
||||||
|
private String gitToken;
|
||||||
|
|
||||||
|
public Register(DatabaseRepository databaseRepo, Router router, String initUsersFilesPath, String gitToken){
|
||||||
|
this.databaseRepo = databaseRepo;
|
||||||
|
this.router = router;
|
||||||
|
this.usersFilesPath = initUsersFilesPath;
|
||||||
|
this.gitToken = gitToken;
|
||||||
|
try {
|
||||||
|
generator = KeyPairGenerator.getInstance("RSA");
|
||||||
|
generator.initialize(2048); //a changer ?
|
||||||
|
} catch (NoSuchAlgorithmException e){
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
encoder = Base64.getEncoder();
|
||||||
|
}
|
||||||
|
|
||||||
|
@RouteDoc(path = "/register", responseCode = 200, responseDescription = "L'utilisateur est inscrit")
|
||||||
|
@RouteDoc(responseCode = 403, responseDescription = "L'utilisateur est connecté")
|
||||||
|
@RouteDoc(responseCode = 400, responseDescription = "Aucune données fournie / données invalide")
|
||||||
|
|
||||||
|
@Route(path = "^\\/register$", type = POST)
|
||||||
|
public void exec(Matcher matcher, User user, HttpReader reader, HttpWriter writer) throws Exception{
|
||||||
|
if (user != null){
|
||||||
|
writer.response(403, "Access-Control-Allow-Origin: *");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
JSONObject json = json(reader);
|
||||||
|
if(!areValids("pseudo","email","passwd","firstname","lastname")){
|
||||||
|
writer.response(400, "Access-Control-Allow-Origin: *");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String pseudo = (String) json.get("pseudo");
|
||||||
|
String email = (String) json.get("email");
|
||||||
|
String password = (String) json.get("passwd");
|
||||||
|
String firstname = (String) json.get("firstname");
|
||||||
|
String lastname = (String) json.get("lastname");
|
||||||
|
String description = (String) json.get("description");
|
||||||
|
String group = (String) json.get("sgroup");
|
||||||
|
String avatar = (String) json.get("avatar");
|
||||||
|
|
||||||
|
boolean pseudoAvailable = databaseRepo.checkPseudoAvailability(pseudo);
|
||||||
|
boolean emailAvailable = databaseRepo.checkEmailAvailability(email);
|
||||||
|
if(pseudoAvailable && emailAvailable){
|
||||||
|
int id;
|
||||||
|
if((id = databaseRepo.register(pseudo, email, password, firstname, lastname, description, group,
|
||||||
|
avatar)) >= 0) {
|
||||||
|
writer.response(200,
|
||||||
|
"Access-Control-Allow-Origin: *",
|
||||||
|
"Access-Control-Expose-Headers: Authorization",
|
||||||
|
"Authorization: Bearer " + this.router.createAuthUser(id));
|
||||||
|
createFolderToSaveSourceCode(pseudo);
|
||||||
|
}else{
|
||||||
|
writer.response(400, "Access-Control-Allow-Origin: *");
|
||||||
|
}
|
||||||
|
}else{
|
||||||
|
writer.response(400, "Access-Control-Allow-Origin: *");
|
||||||
|
JSONObject error = new JSONObject();
|
||||||
|
error.put("username_valid", pseudoAvailable);
|
||||||
|
error.put("email_valid", emailAvailable);
|
||||||
|
writer.write(error.toJSONString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String generateGitKey(String email, String pseudo, String password) throws Exception{
|
||||||
|
KeyPair pair = generator.generateKeyPair(); //doit être unique ???
|
||||||
|
|
||||||
|
JSONObject createUser = new JSONObject();
|
||||||
|
createUser.put("email", email);
|
||||||
|
createUser.put("username", pseudo);
|
||||||
|
createUser.put("password", password);
|
||||||
|
post("https://git-users.peerat.dev/api/v1/admin/users/", createUser);
|
||||||
|
|
||||||
|
JSONObject sendKey = new JSONObject();
|
||||||
|
sendKey.put("key", new String(encoder.encode(pair.getPrivate().getEncoded()))); //add ssh-rsa au début ?
|
||||||
|
sendKey.put("read_only", false);
|
||||||
|
sendKey.put("title", "peer_at_code_auto_push_key_"+pseudo);
|
||||||
|
post("https://git-users.peerat.dev/api/v1/admin/users/"+pseudo+"/keys", sendKey);
|
||||||
|
|
||||||
|
return new String(encoder.encode(pair.getPrivate().getEncoded()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void post(String url, JSONAware json) throws Exception{
|
||||||
|
HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
|
||||||
|
connection.setRequestMethod("POST");
|
||||||
|
connection.setRequestProperty("Content-Type","application/json");
|
||||||
|
connection.setRequestProperty("Authorization","Bearer "+this.gitToken);
|
||||||
|
connection.setDoInput(true);
|
||||||
|
connection.setDoOutput(true);
|
||||||
|
|
||||||
|
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
|
||||||
|
writer.write(json.toJSONString());
|
||||||
|
writer.flush();
|
||||||
|
writer.close();
|
||||||
|
|
||||||
|
int response = connection.getResponseCode();
|
||||||
|
if(response != 201) throw new Exception("Call to "+url+" failed with response code "+response);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createFolderToSaveSourceCode(String pseudo) throws IOException {
|
||||||
|
|
||||||
|
Files.createDirectories(Paths.get(String.format("%s/%s", usersFilesPath, pseudo)));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -1,41 +1,41 @@
|
||||||
package dev.peerat.backend.utils;
|
package be.jeffcheasey88.peeratcode.utils;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
import dev.peerat.framework.HttpReader;
|
import org.json.simple.JSONAware;
|
||||||
import dev.peerat.framework.Response;
|
|
||||||
import dev.peerat.framework.utils.json.Json;
|
import be.jeffcheasey88.peeratcode.framework.HttpReader;
|
||||||
import dev.peerat.framework.utils.json.JsonMap;
|
import be.jeffcheasey88.peeratcode.framework.Response;
|
||||||
|
|
||||||
public abstract class FormResponse implements Response{
|
public abstract class FormResponse implements Response{
|
||||||
|
|
||||||
private Json json;
|
private JSONAware json;
|
||||||
private Map<String, Pattern> checker;
|
private Map<String, Pattern> checker;
|
||||||
|
|
||||||
public FormResponse(){
|
public FormResponse(){
|
||||||
this.checker = new HashMap<>();
|
this.checker = new HashMap<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void validator(String key, String regex){
|
public void validator(String key, Pattern regex){
|
||||||
this.checker.put(key, Pattern.compile(regex, Pattern.CASE_INSENSITIVE));
|
this.checker.put(key, regex);
|
||||||
}
|
}
|
||||||
|
|
||||||
public <T extends Json> T json(HttpReader reader) throws Exception{
|
public <T extends JSONAware> T json(HttpReader reader) throws Exception{
|
||||||
return (T) (this.json = reader.readJson());
|
return (T) (this.json = reader.readJson());
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean hasFields(String... fields){
|
public boolean hasFields(String... fields){
|
||||||
JsonMap map = (JsonMap)json;
|
Map<?,?> map = (Map<?,?>)json;
|
||||||
for(String field : fields){
|
for(String field : fields){
|
||||||
if(!map.has(field)) return false;
|
if(!map.containsKey(field)) return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean areValids(String... fields){
|
public boolean areValids(String... fields){
|
||||||
JsonMap map = (JsonMap)json;
|
Map<?,?> map = (Map<?,?>)json;
|
||||||
for(String field : fields){
|
for(String field : fields){
|
||||||
String value = (String) map.get(field);
|
String value = (String) map.get(field);
|
||||||
if(value == null) return false;
|
if(value == null) return false;
|
|
@ -1,184 +0,0 @@
|
||||||
package dev.peerat.backend;
|
|
||||||
|
|
||||||
import static dev.peerat.framework.RequestType.OPTIONS;
|
|
||||||
|
|
||||||
import java.lang.reflect.Method;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Map.Entry;
|
|
||||||
import java.util.function.Predicate;
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
|
|
||||||
import dev.peerat.backend.bonus.extract.RouteExtracter;
|
|
||||||
import dev.peerat.backend.model.Group;
|
|
||||||
import dev.peerat.backend.model.PeerAtUser;
|
|
||||||
import dev.peerat.backend.repository.ConnectionManager;
|
|
||||||
import dev.peerat.backend.repository.DatabaseRepository;
|
|
||||||
import dev.peerat.framework.Context;
|
|
||||||
import dev.peerat.framework.DependencyInjector;
|
|
||||||
import dev.peerat.framework.HttpReader;
|
|
||||||
import dev.peerat.framework.HttpWriter;
|
|
||||||
import dev.peerat.framework.Locker;
|
|
||||||
import dev.peerat.framework.Locker.Key;
|
|
||||||
import dev.peerat.framework.RequestType;
|
|
||||||
import dev.peerat.framework.Response;
|
|
||||||
import dev.peerat.framework.Route;
|
|
||||||
import dev.peerat.framework.RouteInterceptor;
|
|
||||||
import dev.peerat.framework.Router;
|
|
||||||
import dev.peerat.framework.auth.Authenticator;
|
|
||||||
import dev.peerat.framework.auth.JwtAuthenticator;
|
|
||||||
import dev.peerat.framework.utils.json.JsonMap;
|
|
||||||
import dev.peerat.framework.utils.json.JsonParser;
|
|
||||||
|
|
||||||
public class Main{
|
|
||||||
|
|
||||||
private static Router<PeerAtUser> ACCESS_ROUTER;
|
|
||||||
|
|
||||||
public static void main(String[] args) throws Exception{
|
|
||||||
Configuration config = new Configuration("config.txt").addDefaultValue("users_files", "/tmp/users_files");
|
|
||||||
config.load();
|
|
||||||
|
|
||||||
Class.forName("com.mysql.cj.jdbc.Driver");
|
|
||||||
|
|
||||||
DatabaseRepository repo = new DatabaseRepository(new ConnectionManager(config), config);
|
|
||||||
Router<PeerAtUser> router = new Router<PeerAtUser>()
|
|
||||||
.activeReOrdering().
|
|
||||||
addDefaultHeaders(RequestType.GET, "Access-Control-Allow-Origin: *").
|
|
||||||
addDefaultHeaders(RequestType.POST, "Access-Control-Allow-Origin: *").
|
|
||||||
addDefaultHeaders(RequestType.OPTIONS,
|
|
||||||
"Access-Control-Allow-Origin: *",
|
|
||||||
"Access-Control-Allow-Methods: *",
|
|
||||||
"Access-Control-Allow-Headers: *");
|
|
||||||
ACCESS_ROUTER = router;
|
|
||||||
|
|
||||||
Authenticator<PeerAtUser> auth;
|
|
||||||
if(config.getJwtKey() != null){
|
|
||||||
JsonParser parser = new JsonParser();
|
|
||||||
JsonMap json = parser.parse(config.getJwtKey());
|
|
||||||
Map<String, Object> params = new HashMap<>();
|
|
||||||
for(Entry<String, Object> entry : json.entries()) params.put(entry.getKey(), entry.getValue());
|
|
||||||
auth = new JwtAuthenticator<PeerAtUser>().configure(
|
|
||||||
(builder) -> builder.setExpectedIssuer(config.getTokenIssuer()),
|
|
||||||
(claims) -> {
|
|
||||||
claims.setIssuer(config.getTokenIssuer());
|
|
||||||
claims.setExpirationTimeMinutesInTheFuture(config.getTokenExpiration());
|
|
||||||
},
|
|
||||||
(claims) -> new PeerAtUser(claims),
|
|
||||||
params);
|
|
||||||
}else{
|
|
||||||
auth = new JwtAuthenticator<PeerAtUser>().configure(
|
|
||||||
(builder) -> builder.setExpectedIssuer(config.getTokenIssuer()),
|
|
||||||
(claims) -> {
|
|
||||||
claims.setIssuer(config.getTokenIssuer());
|
|
||||||
claims.setExpirationTimeMinutesInTheFuture(config.getTokenExpiration());
|
|
||||||
},
|
|
||||||
(claims) -> new PeerAtUser(claims));
|
|
||||||
JsonMap json = new JsonMap();
|
|
||||||
for(Entry<String, Object> entry : ((JwtAuthenticator<PeerAtUser>)auth).exportKey().entrySet()){
|
|
||||||
json.set(entry.getKey(), entry.getValue());
|
|
||||||
}
|
|
||||||
config.setJwtKey(json.toString());
|
|
||||||
config.save();
|
|
||||||
}
|
|
||||||
router.setAuthenticator(auth);
|
|
||||||
|
|
||||||
router.setDefault((matcher, context, reader, writer) -> {
|
|
||||||
context.response(404);
|
|
||||||
writer.write("404 not Found.\n");
|
|
||||||
});
|
|
||||||
|
|
||||||
router.register(new Response(){
|
|
||||||
@Route(path = "^(.*)$", type = OPTIONS)
|
|
||||||
public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception {
|
|
||||||
context.response(200);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
initRoutes(router, repo, config);
|
|
||||||
|
|
||||||
router.addInterceptor(new RouteInterceptor(){
|
|
||||||
@Override
|
|
||||||
public boolean intercept(Matcher matcher, Context context, HttpReader reader, HttpWriter writer, Method method){
|
|
||||||
if(method.getDeclaringClass().getPackage().getName().contains(".admins")){
|
|
||||||
try {
|
|
||||||
Group group = repo.getGroupRepository().getPlayerGroup(context.<PeerAtUser>getUser().getId(), 1);
|
|
||||||
if(!group.getName().equalsIgnoreCase("Quarter-Master - Battles PAC x CEI")){
|
|
||||||
context.response(401);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}catch(Exception ex){
|
|
||||||
ex.printStackTrace();
|
|
||||||
try{
|
|
||||||
context.response(401);
|
|
||||||
}catch(Exception e){}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
new Thread(new Runnable(){
|
|
||||||
public void run(){
|
|
||||||
Key key = new Key();
|
|
||||||
|
|
||||||
Locker<Context> locker = router.getLogger();
|
|
||||||
|
|
||||||
locker.init(key);
|
|
||||||
try {
|
|
||||||
while(true){
|
|
||||||
locker.lock(key);
|
|
||||||
Context instance = locker.getValue(key);
|
|
||||||
if(instance == null) continue;
|
|
||||||
System.out.println("["+((instance.isLogged()) ? repo.getPlayerRepository().getPlayer(instance.<PeerAtUser>getUser().getId()).getPseudo() : "?")+"] "+instance.getType()+" "+instance.getPath()+" -> "+instance.getResponseCode());
|
|
||||||
}
|
|
||||||
}catch(Exception e){
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
locker.remove(key);
|
|
||||||
}
|
|
||||||
}).start();
|
|
||||||
|
|
||||||
new Thread(new Runnable(){
|
|
||||||
public void run(){
|
|
||||||
Key key = new Key();
|
|
||||||
|
|
||||||
Locker<Throwable> locker = router.getExceptionLogger();
|
|
||||||
|
|
||||||
locker.init(key);
|
|
||||||
try {
|
|
||||||
while(true){
|
|
||||||
locker.lock(key);
|
|
||||||
locker.getValue(key).printStackTrace();
|
|
||||||
}
|
|
||||||
}catch(Exception e){
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
locker.remove(key);
|
|
||||||
}
|
|
||||||
}).start();
|
|
||||||
|
|
||||||
if(config.useSsl()) router.configureSSL(config.getSslKeystore(), config.getSslKeystorePasswd());
|
|
||||||
router.listen(config.getTcpPort(), config.useSsl());
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void initRoutes(Router<PeerAtUser> router, DatabaseRepository repo, Configuration config) throws Exception{
|
|
||||||
Predicate<PeerAtUser> isAdmin = (user) -> {
|
|
||||||
try {
|
|
||||||
Group group = repo.getGroupRepository().getPlayerGroup(user.getId(), 1);
|
|
||||||
return group.getName().equalsIgnoreCase("Quarter-Master - Battles PAC x CEI");
|
|
||||||
}catch(Exception ex){}
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
|
|
||||||
router.registerPackages("dev.peerat.backend.routes",new DependencyInjector()
|
|
||||||
.of(repo, router, config, new RouteExtracter(router), config.getMail(), isAdmin)
|
|
||||||
.of("waitting", new HashMap<>())
|
|
||||||
.of("leaderboard", new Locker<>())
|
|
||||||
.of("groups", new Locker<>())
|
|
||||||
.of("groupMessages", new Locker<>()));
|
|
||||||
|
|
||||||
// Bot bot = new Bot(config, repo, groupLock);
|
|
||||||
// bot.start();
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,131 +0,0 @@
|
||||||
package dev.peerat.backend.bonus.extract;
|
|
||||||
|
|
||||||
import java.lang.reflect.Field;
|
|
||||||
import java.lang.reflect.Method;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
import dev.peerat.backend.model.PeerAtUser;
|
|
||||||
import dev.peerat.framework.RequestType;
|
|
||||||
import dev.peerat.framework.Response;
|
|
||||||
import dev.peerat.framework.Route;
|
|
||||||
import dev.peerat.framework.RouteMapper;
|
|
||||||
import dev.peerat.framework.Router;
|
|
||||||
import dev.peerat.framework.utils.json.JsonArray;
|
|
||||||
import dev.peerat.framework.utils.json.JsonMap;
|
|
||||||
|
|
||||||
public class RouteExtracter {
|
|
||||||
|
|
||||||
private Router<PeerAtUser> router;
|
|
||||||
|
|
||||||
public RouteExtracter(Router<PeerAtUser> router){
|
|
||||||
this.router = router;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void extract() throws Exception{
|
|
||||||
RouteMapper[] mappers = getField(Router.class, router, "mappers");
|
|
||||||
for(RequestType type : RequestType.values()){
|
|
||||||
RouteMapper mapper = mappers[type.ordinal()];
|
|
||||||
Response[] responses = getField(RouteMapper.class, mapper, "responses");
|
|
||||||
Route[] routes = getField(RouteMapper.class, mapper, "routes");
|
|
||||||
synchronized (responses){
|
|
||||||
for(int i = 0; i < responses.length; i++){
|
|
||||||
Route route = routes[i];
|
|
||||||
System.out.println("["+type+"] ("+route.needLogin()+") "+route.path());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void extractDoc() throws Exception{
|
|
||||||
RouteMapper[] mappers = getField(Router.class, router, "mappers");
|
|
||||||
for(RequestType type : RequestType.values()){
|
|
||||||
RouteMapper mapper = mappers[type.ordinal()];
|
|
||||||
Response[] responses = getField(RouteMapper.class, mapper, "responses");
|
|
||||||
synchronized (responses){
|
|
||||||
for(int i = 0; i < responses.length; i++){
|
|
||||||
Response response = responses[i];
|
|
||||||
Method method = response.getClass().getDeclaredMethod("exec",
|
|
||||||
Response.class.getDeclaredMethods()[0].getParameterTypes());
|
|
||||||
for(RouteDoc doc : method.getDeclaredAnnotationsByType(RouteDoc.class)){
|
|
||||||
System.out.println(doc.path()+((doc.path().isEmpty() ? "":"\n"))+" ["+doc.responseCode()+"] "+doc.responseDescription());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public JsonMap swagger(String host) throws Exception{
|
|
||||||
JsonMap result = new JsonMap();
|
|
||||||
result.set("swagger","2.0");
|
|
||||||
JsonMap info = new JsonMap();
|
|
||||||
info.set("title", "Peer-at-code backend api routes");
|
|
||||||
info.set("description", "Using Peer-at Code Framework");
|
|
||||||
result.set("info", info);
|
|
||||||
result.set("host", host);
|
|
||||||
result.set("basePath","/");
|
|
||||||
|
|
||||||
List<Response> routes = new ArrayList<>();
|
|
||||||
RouteMapper[] mappers = getField(Router.class, router, "mappers");
|
|
||||||
for(RequestType type : RequestType.values()){
|
|
||||||
RouteMapper mapper = mappers[type.ordinal()];
|
|
||||||
Response[] responses = getField(RouteMapper.class, mapper, "responses");
|
|
||||||
synchronized (responses){
|
|
||||||
routes.addAll(Arrays.asList(responses));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Set<String> packages = new HashSet<>();
|
|
||||||
for(Response response : routes){
|
|
||||||
String name = response.getClass().getPackage().getName();
|
|
||||||
name = name.substring(name.lastIndexOf('.')+1, name.length());
|
|
||||||
packages.add(name);
|
|
||||||
}
|
|
||||||
JsonArray tags = new JsonArray();
|
|
||||||
for(String tag : packages){
|
|
||||||
JsonMap current = new JsonMap();
|
|
||||||
current.set("name", tag);
|
|
||||||
tags.add(current);
|
|
||||||
}
|
|
||||||
result.set("tags", tags);
|
|
||||||
JsonArray schemes = new JsonArray();
|
|
||||||
schemes.add("https");
|
|
||||||
result.set("schemes", schemes);
|
|
||||||
|
|
||||||
JsonMap paths = new JsonMap();
|
|
||||||
|
|
||||||
for(Response response : routes){
|
|
||||||
Method method = response.getClass().getDeclaredMethod("exec",
|
|
||||||
Response.class.getDeclaredMethods()[0].getParameterTypes());
|
|
||||||
Route route = method.getDeclaredAnnotation(Route.class);
|
|
||||||
RouteDoc[] docs = method.getDeclaredAnnotationsByType(RouteDoc.class);
|
|
||||||
if(docs.length < 1) continue;
|
|
||||||
RouteDoc base = docs[0];
|
|
||||||
JsonMap current = new JsonMap();
|
|
||||||
JsonMap data = new JsonMap();
|
|
||||||
JsonArray tag = new JsonArray();
|
|
||||||
String pack = response.getClass().getPackage().getName();
|
|
||||||
pack = pack.substring(pack.lastIndexOf('.')+1, pack.length());
|
|
||||||
tag.add(pack);
|
|
||||||
data.set("tags", tag);
|
|
||||||
|
|
||||||
|
|
||||||
current.set(route.type().toString().toLowerCase(), data);
|
|
||||||
|
|
||||||
paths.set(base.path(), current);
|
|
||||||
}
|
|
||||||
|
|
||||||
result.set("paths", paths);
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
private <E> E getField(Class<?> clazz, Object instance, String name) throws Exception{
|
|
||||||
Field field = clazz.getDeclaredField(name);
|
|
||||||
field.setAccessible(true);
|
|
||||||
return (E) field.get(instance);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,28 +0,0 @@
|
||||||
package dev.peerat.backend.model;
|
|
||||||
|
|
||||||
import org.jose4j.jwt.JwtClaims;
|
|
||||||
|
|
||||||
public class PeerAtUser extends dev.peerat.framework.User{
|
|
||||||
|
|
||||||
private int id;
|
|
||||||
|
|
||||||
public PeerAtUser(int id){
|
|
||||||
this.id = id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public PeerAtUser(JwtClaims claims){
|
|
||||||
this.id = ((Long) claims.getClaimValue("id")).intValue();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void write(JwtClaims claims){
|
|
||||||
claims.setClaim("id", this.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getId(){
|
|
||||||
return this.id;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,30 +0,0 @@
|
||||||
package dev.peerat.backend.model;
|
|
||||||
|
|
||||||
import dev.peerat.framework.utils.json.JsonMap;
|
|
||||||
|
|
||||||
public class Tag{
|
|
||||||
|
|
||||||
private int id;
|
|
||||||
private String name;
|
|
||||||
|
|
||||||
public Tag(int id, String name){
|
|
||||||
this.id = id;
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getId(){
|
|
||||||
return this.id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getName(){
|
|
||||||
return this.name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public JsonMap toJson(){
|
|
||||||
JsonMap result = new JsonMap();
|
|
||||||
result.set("id", id);
|
|
||||||
result.set("name", name);
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,114 +0,0 @@
|
||||||
package dev.peerat.backend.repository;
|
|
||||||
|
|
||||||
import java.sql.Connection;
|
|
||||||
import java.sql.PreparedStatement;
|
|
||||||
import java.sql.ResultSet;
|
|
||||||
import java.sql.ResultSetMetaData;
|
|
||||||
import java.sql.SQLException;
|
|
||||||
|
|
||||||
import dev.peerat.backend.Configuration;
|
|
||||||
import dev.peerat.backend.model.Badge;
|
|
||||||
import dev.peerat.backend.model.Chapter;
|
|
||||||
import dev.peerat.backend.model.Completion;
|
|
||||||
import dev.peerat.backend.model.Group;
|
|
||||||
import dev.peerat.backend.model.Player;
|
|
||||||
import dev.peerat.backend.model.Puzzle;
|
|
||||||
|
|
||||||
public class BaseDatabaseQuery{
|
|
||||||
|
|
||||||
private ConnectionManager con;
|
|
||||||
private Configuration config;
|
|
||||||
|
|
||||||
public BaseDatabaseQuery(ConnectionManager con){
|
|
||||||
this.con = con;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Connection ensureConnection() throws SQLException{
|
|
||||||
return this.con.ensureConnection();
|
|
||||||
}
|
|
||||||
|
|
||||||
public PreparedStatement prepare(String request) throws SQLException{
|
|
||||||
return this.con.ensureConnection().prepareStatement(request);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Puzzle makePuzzle(ResultSet puzzleResult) throws SQLException {
|
|
||||||
return new Puzzle(puzzleResult.getInt("id_puzzle"), puzzleResult.getString("name"),
|
|
||||||
puzzleResult.getString("content"), puzzleResult.getBytes("soluce"), puzzleResult.getString("verify"),
|
|
||||||
puzzleResult.getInt("score_max"), puzzleResult.getString("tags"),
|
|
||||||
hasColumn(puzzleResult, "origin") ? puzzleResult.getInt("origin") : -1,
|
|
||||||
puzzleResult.getTimestamp("start_date"));
|
|
||||||
}
|
|
||||||
|
|
||||||
public Chapter makeChapter(ResultSet chapterResult) throws SQLException {
|
|
||||||
return new Chapter(chapterResult.getInt("id_chapter"), chapterResult.getString("name"),
|
|
||||||
chapterResult.getTimestamp("start_date"), chapterResult.getTimestamp("end_date"));
|
|
||||||
}
|
|
||||||
|
|
||||||
public Completion makeCompletion(ResultSet completionResult) throws SQLException {
|
|
||||||
String fileName = null;
|
|
||||||
if (hasColumn(completionResult, "fileName"))
|
|
||||||
fileName = completionResult.getString("fileName");
|
|
||||||
String puzzleName = null;
|
|
||||||
if (hasColumn(completionResult, "name"))
|
|
||||||
puzzleName = completionResult.getString("name");
|
|
||||||
|
|
||||||
return new Completion(completionResult.getInt("fk_player"), completionResult.getInt("fk_puzzle"), completionResult.getInt("tries"),
|
|
||||||
fileName, completionResult.getInt("score"), puzzleName);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Player makePlayer(ResultSet playerResult, int id) throws SQLException {
|
|
||||||
Player p = new Player(playerResult.getString("pseudo"), playerResult.getString("email"),
|
|
||||||
playerResult.getString("firstName"), playerResult.getString("lastName"));
|
|
||||||
if (hasColumn(playerResult, "avatar")) {
|
|
||||||
p.setAvatar(playerResult.getBytes("avatar"));
|
|
||||||
}
|
|
||||||
if (hasColumn(playerResult, "score")) {
|
|
||||||
p.addCompletion(new Completion(playerResult.getInt("tries"), playerResult.getInt("score")));
|
|
||||||
for (int ct = 1; ct < playerResult.getInt("completions"); ct++)
|
|
||||||
{ // TODO refactor for V3
|
|
||||||
p.addCompletion(new Completion(0, 0));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (hasColumn(playerResult, "name")) {
|
|
||||||
// Manage groups
|
|
||||||
String groupName = playerResult.getString("name");
|
|
||||||
if (groupName != null) {
|
|
||||||
p.addGroup(makeGroup(playerResult));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ADD rank
|
|
||||||
PreparedStatement completionsStmt = con.ensureConnection().prepareStatement(DatabasePlayerRepository.GET_PLAYER_RANK());
|
|
||||||
completionsStmt.setInt(1, id);
|
|
||||||
ResultSet result = completionsStmt.executeQuery();
|
|
||||||
while (result.next()) {
|
|
||||||
p.setRank(result.getInt("rank"));
|
|
||||||
}
|
|
||||||
return p;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Group makeGroup(ResultSet result) throws SQLException {
|
|
||||||
return new Group(result.getString("name"), result.getInt("fk_chapter"), result.getInt("fk_puzzle"), ((hasColumn(result, "countPlayer")) ? result.getInt("countPlayer") : 0));
|
|
||||||
}
|
|
||||||
|
|
||||||
public Player makeGroupPlayer(ResultSet result) throws SQLException {
|
|
||||||
return new Player(result.getString("pseudo"), result.getInt("score"), result.getInt("tries"));
|
|
||||||
}
|
|
||||||
|
|
||||||
public Badge makeBadge(ResultSet rs) throws SQLException {
|
|
||||||
return new Badge(rs.getString("name"), rs.getBytes("logo"), rs.getInt("level"));
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean hasColumn(ResultSet rs, String columnName) throws SQLException {
|
|
||||||
// Found on StackOverflow
|
|
||||||
ResultSetMetaData rsmd = rs.getMetaData();
|
|
||||||
int columns = rsmd.getColumnCount();
|
|
||||||
for (int x = 1; x <= columns; x++) {
|
|
||||||
if (columnName.equals(rsmd.getColumnName(x)))
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,26 +0,0 @@
|
||||||
package dev.peerat.backend.repository;
|
|
||||||
|
|
||||||
import java.sql.Connection;
|
|
||||||
import java.sql.DriverManager;
|
|
||||||
import java.sql.SQLException;
|
|
||||||
|
|
||||||
import dev.peerat.backend.Configuration;
|
|
||||||
|
|
||||||
public class ConnectionManager {
|
|
||||||
|
|
||||||
private Connection con;
|
|
||||||
private Configuration config;
|
|
||||||
|
|
||||||
public ConnectionManager(Configuration config){
|
|
||||||
this.config = config;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Connection ensureConnection() throws SQLException {
|
|
||||||
if (con == null || (!con.isValid(5))) {
|
|
||||||
this.con = DriverManager.getConnection(
|
|
||||||
"jdbc:mysql://" + config.getDbHost() + ":" + config.getDbPort() + "/" + config.getDbDatabase() + "",
|
|
||||||
config.getDbUser(), config.getDbPassword());
|
|
||||||
}
|
|
||||||
return this.con;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,194 +0,0 @@
|
||||||
package dev.peerat.backend.repository;
|
|
||||||
|
|
||||||
import java.sql.PreparedStatement;
|
|
||||||
import java.sql.ResultSet;
|
|
||||||
import java.sql.SQLException;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import dev.peerat.backend.Configuration;
|
|
||||||
import dev.peerat.backend.model.Chapter;
|
|
||||||
import dev.peerat.backend.model.Puzzle;
|
|
||||||
import dev.peerat.backend.model.Tag;
|
|
||||||
|
|
||||||
public class DatabaseAdminRepository extends BaseDatabaseQuery{
|
|
||||||
|
|
||||||
private static enum Query{
|
|
||||||
|
|
||||||
//ADMIN
|
|
||||||
ADD_CHAPTER("INSERT INTO chapters (name, start_date, end_date) VALUES (?,?,?)"),
|
|
||||||
DELETE_CHAPTER("DELETE FROM chapters WHERE id_chapter = ?"),
|
|
||||||
EDIT_CHAPTER("UPDATE chapters SET name = ?, start_date = ?, end_date = ? WHERE id_chapter = ?"),
|
|
||||||
GET_CHAPTER("SELECT * FROM chapters WHERE id_chapter = ?"),
|
|
||||||
|
|
||||||
ADD_PUZZLE("INSERT INTO puzzles (name, content, soluce, verify, score_max, fk_chapter) VALUES (?,?,?,?,?,?)"),
|
|
||||||
DELETE_PUZZLE("DELETE FROM puzzles WHERE id_puzzle = ?"),
|
|
||||||
EDIT_PUZZLE("UPDATE puzzles SET name = ?, content = ?, soluce = ?, verify = ?, score_max = ?, fk_chapter = ? WHERE id_puzzle = ?"),
|
|
||||||
GET_PUZZLE("SELECT p.*, GROUP_CONCAT(t.name) AS tags FROM puzzles p LEFT JOIN containsTags ct ON ct.fk_puzzle = p.id_puzzle LEFT JOIN tags t ON t.id_tag = ct.fk_tag WHERE p.id_puzzle = ? GROUP BY p.id_puzzle"),
|
|
||||||
GET_PUZZLES("SELECT p.*, GROUP_CONCAT(t.name) AS tags FROM puzzles p LEFT JOIN containsTags ct ON ct.fk_puzzle = p.id_puzzle LEFT JOIN tags t ON t.id_tag = ct.fk_tag GROUP BY p.id_puzzle"),
|
|
||||||
|
|
||||||
ADD_TAG("INSERT INTO tags (name) VALUES (?)"),
|
|
||||||
DELETE_TAG("DELETE FROM tags WHERE id_tag = ?"),
|
|
||||||
EDIT_TAG("UPDATE tags SET name = ? WHERE id_tag = ?"),
|
|
||||||
GET_TAGS("SELECT * FROM tags");
|
|
||||||
|
|
||||||
private String request;
|
|
||||||
|
|
||||||
Query(Query parent, String request) {
|
|
||||||
this.request = parent.request + request;
|
|
||||||
}
|
|
||||||
|
|
||||||
Query(String request) {
|
|
||||||
this.request = request;
|
|
||||||
}
|
|
||||||
|
|
||||||
public PreparedStatement prepare(BaseDatabaseQuery base) throws SQLException {
|
|
||||||
return base.prepare(this.request);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return this.request;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private Configuration config;
|
|
||||||
|
|
||||||
public DatabaseAdminRepository(ConnectionManager con, Configuration config){
|
|
||||||
super(con);
|
|
||||||
this.config = config;
|
|
||||||
}
|
|
||||||
|
|
||||||
//ADMIN
|
|
||||||
public Chapter getAdminChapter(int id){
|
|
||||||
try {
|
|
||||||
PreparedStatement chapterStmt = Query.GET_CHAPTER.prepare(this);
|
|
||||||
chapterStmt.setInt(1, id);
|
|
||||||
ResultSet chapterResult = chapterStmt.executeQuery();
|
|
||||||
if (chapterResult.next()) {
|
|
||||||
Chapter chapter = makeChapter(chapterResult);
|
|
||||||
return chapter;
|
|
||||||
}
|
|
||||||
} catch (SQLException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Puzzle getAdminPuzzle(int id){
|
|
||||||
try {
|
|
||||||
PreparedStatement chapterStmt = Query.GET_PUZZLE.prepare(this);
|
|
||||||
chapterStmt.setInt(1, id);
|
|
||||||
ResultSet chapterResult = chapterStmt.executeQuery();
|
|
||||||
if (chapterResult.next()) {
|
|
||||||
return makePuzzle(chapterResult);
|
|
||||||
}
|
|
||||||
} catch (SQLException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<Puzzle> getAdminPuzzles(){
|
|
||||||
try {
|
|
||||||
PreparedStatement chapterStmt = Query.GET_PUZZLES.prepare(this);
|
|
||||||
ResultSet chapterResult = chapterStmt.executeQuery();
|
|
||||||
List<Puzzle> list = new ArrayList<>();
|
|
||||||
while(chapterResult.next()){
|
|
||||||
list.add(makePuzzle(chapterResult));
|
|
||||||
}
|
|
||||||
return list;
|
|
||||||
} catch (SQLException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<Tag> getAdminTags(){
|
|
||||||
try {
|
|
||||||
PreparedStatement chapterStmt = Query.GET_TAGS.prepare(this);
|
|
||||||
ResultSet chapterResult = chapterStmt.executeQuery();
|
|
||||||
List<Tag> list = new ArrayList<>();
|
|
||||||
while(chapterResult.next()){
|
|
||||||
list.add(new Tag(chapterResult.getInt("id_tag"), chapterResult.getString("name")));
|
|
||||||
}
|
|
||||||
return list;
|
|
||||||
} catch (SQLException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean adminAddChapter(Chapter chapter) throws SQLException {
|
|
||||||
PreparedStatement statement = Query.ADD_CHAPTER.prepare(this);
|
|
||||||
statement.setString(1, chapter.getName());
|
|
||||||
statement.setTimestamp(2, chapter.getStartDate());
|
|
||||||
statement.setTimestamp(3, chapter.getEndDate());
|
|
||||||
return (statement.executeUpdate() >= 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean adminAddPuzzle(Puzzle puzzle, int chapter) throws SQLException {
|
|
||||||
PreparedStatement statement = Query.ADD_PUZZLE.prepare(this);
|
|
||||||
statement.setString(1, puzzle.getName());
|
|
||||||
statement.setString(2, puzzle.getContent());
|
|
||||||
statement.setBytes(3, puzzle.getSoluce());
|
|
||||||
statement.setString(4, "");
|
|
||||||
statement.setInt(5, puzzle.getScoreMax());
|
|
||||||
statement.setInt(6, chapter);
|
|
||||||
return (statement.executeUpdate() >= 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean adminAddTag(String name) throws SQLException {
|
|
||||||
PreparedStatement statement = Query.ADD_TAG.prepare(this);
|
|
||||||
statement.setString(1, name);
|
|
||||||
return (statement.executeUpdate() >= 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean adminUpdateChapter(int id, Chapter chapter) throws SQLException {
|
|
||||||
PreparedStatement statement = Query.EDIT_CHAPTER.prepare(this);
|
|
||||||
statement.setString(1, chapter.getName());
|
|
||||||
statement.setTimestamp(2, chapter.getStartDate());
|
|
||||||
statement.setTimestamp(3, chapter.getEndDate());
|
|
||||||
statement.setInt(4, id);
|
|
||||||
return (statement.executeUpdate() >= 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean adminUpdatePuzzle(int id, Puzzle puzzle, int chapter) throws SQLException {
|
|
||||||
PreparedStatement statement = Query.EDIT_PUZZLE.prepare(this);
|
|
||||||
statement.setString(1, puzzle.getName());
|
|
||||||
statement.setString(2, puzzle.getContent());
|
|
||||||
statement.setBytes(3, puzzle.getSoluce());
|
|
||||||
statement.setString(4, "");
|
|
||||||
statement.setInt(5, puzzle.getScoreMax());
|
|
||||||
statement.setInt(6, chapter);
|
|
||||||
statement.setInt(7, id);
|
|
||||||
return (statement.executeUpdate() >= 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean adminUpdateTag(Tag tag) throws SQLException {
|
|
||||||
PreparedStatement statement = Query.EDIT_TAG.prepare(this);
|
|
||||||
statement.setString(1, tag.getName());
|
|
||||||
statement.setInt(2, tag.getId());
|
|
||||||
return (statement.executeUpdate() >= 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean adminDeleteChapter(int id) throws SQLException {
|
|
||||||
PreparedStatement statement = Query.DELETE_CHAPTER.prepare(this);
|
|
||||||
statement.setInt(1, id);
|
|
||||||
return (statement.executeUpdate() >= 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean adminDeletePuzzle(int id) throws SQLException {
|
|
||||||
PreparedStatement statement = Query.DELETE_PUZZLE.prepare(this);
|
|
||||||
statement.setInt(1, id);
|
|
||||||
return (statement.executeUpdate() >= 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean adminDeleteTag(int id) throws SQLException {
|
|
||||||
PreparedStatement statement = Query.DELETE_TAG.prepare(this);
|
|
||||||
statement.setInt(1, id);
|
|
||||||
return (statement.executeUpdate() >= 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,167 +0,0 @@
|
||||||
package dev.peerat.backend.repository;
|
|
||||||
|
|
||||||
import java.sql.Connection;
|
|
||||||
import java.sql.PreparedStatement;
|
|
||||||
import java.sql.ResultSet;
|
|
||||||
import java.sql.SQLException;
|
|
||||||
import java.sql.Statement;
|
|
||||||
|
|
||||||
import com.password4j.Password;
|
|
||||||
|
|
||||||
import dev.peerat.backend.Configuration;
|
|
||||||
|
|
||||||
public class DatabaseAuthRepository extends BaseDatabaseQuery{
|
|
||||||
|
|
||||||
private static enum Query{
|
|
||||||
|
|
||||||
// REGISTER
|
|
||||||
CHECK_PSEUDO_AVAILABLE_QUERY("SELECT * FROM players WHERE pseudo = ?"),
|
|
||||||
CHECK_EMAIL_AVAILABLE_QUERY("SELECT * FROM players WHERE email = ?"),
|
|
||||||
REGISTER_QUERY(
|
|
||||||
"INSERT INTO players (pseudo, email, passwd, firstname, lastname, description, avatar) VALUES (?, ?, ?, ?, ?, ?, ?)"),
|
|
||||||
REGISTER_PLAYER_IN_EXISTING_GROUP(
|
|
||||||
"INSERT INTO containsGroups (fk_player, fk_group) VALUES (?, (SELECT id_group FROM groups WHERE name = ?));"),
|
|
||||||
|
|
||||||
// LOGIN
|
|
||||||
CHECK_PASSWORD("SELECT id_player, passwd FROM players WHERE pseudo=?");
|
|
||||||
|
|
||||||
private String request;
|
|
||||||
|
|
||||||
Query(Query parent, String request) {
|
|
||||||
this.request = parent.request + request;
|
|
||||||
}
|
|
||||||
|
|
||||||
Query(String request) {
|
|
||||||
this.request = request;
|
|
||||||
}
|
|
||||||
|
|
||||||
public PreparedStatement prepare(BaseDatabaseQuery base) throws SQLException {
|
|
||||||
return base.prepare(this.request);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return this.request;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private Configuration config;
|
|
||||||
|
|
||||||
public DatabaseAuthRepository(ConnectionManager con, Configuration config){
|
|
||||||
super(con);
|
|
||||||
this.config = config;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if a pseudo is available
|
|
||||||
*
|
|
||||||
* @param pseudo The pseudo to check
|
|
||||||
* @return True if the pseudo is available, false if it's already taken
|
|
||||||
*/
|
|
||||||
public boolean checkPseudoAvailability(String pseudo) {
|
|
||||||
return checkAvailability(pseudo, Query.CHECK_PSEUDO_AVAILABLE_QUERY.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if an email is available
|
|
||||||
*
|
|
||||||
* @param email The email to check
|
|
||||||
* @return True if the email is available, false if it's already taken
|
|
||||||
*/
|
|
||||||
public boolean checkEmailAvailability(String email) {
|
|
||||||
return checkAvailability(email, Query.CHECK_EMAIL_AVAILABLE_QUERY.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean checkAvailability(String queriedString, String correspondingQuery) {
|
|
||||||
try {
|
|
||||||
PreparedStatement statement = prepare(correspondingQuery);
|
|
||||||
statement.setString(1, queriedString);
|
|
||||||
ResultSet result = statement.executeQuery();
|
|
||||||
return !result.next();
|
|
||||||
} catch (SQLException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Register a new user
|
|
||||||
*
|
|
||||||
* @param pseudo The pseudo of the user
|
|
||||||
* @param email The email of the user
|
|
||||||
* @param password The password of the user
|
|
||||||
* @param firstname The firstname of the user
|
|
||||||
* @param lastname The lastname of the user
|
|
||||||
* @param description The description of the user
|
|
||||||
* @param sgroup The group of the user
|
|
||||||
* @param avatar The avatar of the user
|
|
||||||
* @return True if the user was registered, false if an error occurred
|
|
||||||
*/
|
|
||||||
public int register(String pseudo, String email, String password, String firstname, String lastname,
|
|
||||||
String description, String sgroup, String avatar) {
|
|
||||||
try {
|
|
||||||
String pass = Password.hash(password).withArgon2().getResult();
|
|
||||||
System.out.println("pass("+pass.length()+") "+pass);
|
|
||||||
Connection con = ensureConnection();
|
|
||||||
con.setAutoCommit(false);
|
|
||||||
try (PreparedStatement playerStatement = con.prepareStatement(Query.REGISTER_QUERY.toString(),
|
|
||||||
Statement.RETURN_GENERATED_KEYS)) {
|
|
||||||
playerStatement.setString(1, pseudo);
|
|
||||||
playerStatement.setString(2, email);
|
|
||||||
playerStatement.setString(3, Password.hash(password).withArgon2().getResult());
|
|
||||||
playerStatement.setString(4, firstname);
|
|
||||||
playerStatement.setString(5, lastname);
|
|
||||||
playerStatement.setString(6, description);
|
|
||||||
playerStatement.setString(7, avatar);
|
|
||||||
if (playerStatement.executeUpdate() == 1) {
|
|
||||||
ResultSet inserted = playerStatement.getGeneratedKeys();
|
|
||||||
if (inserted.next()) {
|
|
||||||
int newPlayerId = inserted.getInt(1);
|
|
||||||
if (!sgroup.isEmpty()) {
|
|
||||||
try (PreparedStatement containsGroupsStatement = con
|
|
||||||
.prepareStatement(Query.REGISTER_PLAYER_IN_EXISTING_GROUP.toString())) {
|
|
||||||
containsGroupsStatement.setInt(1, newPlayerId);
|
|
||||||
containsGroupsStatement.setString(2, sgroup);
|
|
||||||
containsGroupsStatement.executeUpdate();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
con.commit();
|
|
||||||
con.setAutoCommit(true);
|
|
||||||
return newPlayerId;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (SQLException e) {
|
|
||||||
con.rollback();
|
|
||||||
con.setAutoCommit(true);
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
} catch (SQLException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Login a user
|
|
||||||
*
|
|
||||||
* @param username The username of the user
|
|
||||||
* @param password The password of the user
|
|
||||||
* @return id the id of the user, -1 if not login successefuly
|
|
||||||
*/
|
|
||||||
public int login(String username, String password) {
|
|
||||||
try {
|
|
||||||
ensureConnection();
|
|
||||||
PreparedStatement statement = prepare(Query.CHECK_PASSWORD.toString());
|
|
||||||
statement.setString(1, username);
|
|
||||||
ResultSet result = statement.executeQuery();
|
|
||||||
if (result.next()) {
|
|
||||||
String hashedPassword = result.getString("passwd");
|
|
||||||
if (Password.check(password, hashedPassword).withArgon2())
|
|
||||||
return result.getInt("id_player");
|
|
||||||
}
|
|
||||||
} catch (SQLException e) {
|
|
||||||
}
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,69 +0,0 @@
|
||||||
package dev.peerat.backend.repository;
|
|
||||||
|
|
||||||
import java.sql.Connection;
|
|
||||||
import java.sql.PreparedStatement;
|
|
||||||
import java.sql.ResultSet;
|
|
||||||
import java.sql.SQLException;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import dev.peerat.backend.Configuration;
|
|
||||||
import dev.peerat.backend.model.Badge;
|
|
||||||
import dev.peerat.backend.model.Puzzle;
|
|
||||||
|
|
||||||
public class DatabaseBadgeRepository extends BaseDatabaseQuery{
|
|
||||||
|
|
||||||
public static String GET_BADGES_OF_PLAYER(){
|
|
||||||
return Query.GET_BADGES_OF_PLAYER.request;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static enum Query{
|
|
||||||
|
|
||||||
// BADGES
|
|
||||||
GET_BADGE("SELECT * FROM badges WHERE id_badge = ?"),
|
|
||||||
GET_BADGES_OF_PLAYER(
|
|
||||||
"SELECT * FROM badges b LEFT JOIN containsBadges cb ON cb.fk_badge = b.id_badge WHERE cb.fk_player = ?");
|
|
||||||
|
|
||||||
|
|
||||||
private String request;
|
|
||||||
|
|
||||||
Query(Query parent, String request) {
|
|
||||||
this.request = parent.request + request;
|
|
||||||
}
|
|
||||||
|
|
||||||
Query(String request) {
|
|
||||||
this.request = request;
|
|
||||||
}
|
|
||||||
|
|
||||||
public PreparedStatement prepare(BaseDatabaseQuery base) throws SQLException {
|
|
||||||
return base.prepare(this.request);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return this.request;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private Configuration config;
|
|
||||||
|
|
||||||
public DatabaseBadgeRepository(ConnectionManager con, Configuration config){
|
|
||||||
super(con);
|
|
||||||
this.config = config;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Badge getBadge(int badgeId) {
|
|
||||||
try {
|
|
||||||
ensureConnection();
|
|
||||||
PreparedStatement completionsStmt = Query.GET_BADGE.prepare(this);
|
|
||||||
completionsStmt.setInt(1, badgeId);
|
|
||||||
ResultSet result = completionsStmt.executeQuery();
|
|
||||||
if (result.next()) {
|
|
||||||
return makeBadge(result);
|
|
||||||
}
|
|
||||||
} catch (SQLException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,122 +0,0 @@
|
||||||
package dev.peerat.backend.repository;
|
|
||||||
|
|
||||||
import java.sql.Connection;
|
|
||||||
import java.sql.PreparedStatement;
|
|
||||||
import java.sql.ResultSet;
|
|
||||||
import java.sql.SQLException;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import dev.peerat.backend.Configuration;
|
|
||||||
import dev.peerat.backend.model.Chapter;
|
|
||||||
import dev.peerat.backend.model.Puzzle;
|
|
||||||
|
|
||||||
public class DatabaseChapterRepository extends BaseDatabaseQuery{
|
|
||||||
|
|
||||||
private static enum Query{
|
|
||||||
|
|
||||||
// CHAPTERS
|
|
||||||
SPECIFIC_CHAPTER_QUERY("SELECT * FROM chapters WHERE id_chapter = ?"),
|
|
||||||
CHAPTER_FROM_PUZZLE("SELECT c.*\r\n"
|
|
||||||
+ "FROM chapters c\r\n"
|
|
||||||
+ "JOIN puzzles p ON p.fk_chapter = c.id_chapter\r\n"
|
|
||||||
+ "WHERE p.id_puzzle = ?"),
|
|
||||||
ALL_CHAPTERS_QUERY("SELECT * FROM chapters WHERE id_chapter > 0");
|
|
||||||
|
|
||||||
|
|
||||||
private String request;
|
|
||||||
|
|
||||||
Query(Query parent, String request) {
|
|
||||||
this.request = parent.request + request;
|
|
||||||
}
|
|
||||||
|
|
||||||
Query(String request) {
|
|
||||||
this.request = request;
|
|
||||||
}
|
|
||||||
|
|
||||||
public PreparedStatement prepare(BaseDatabaseQuery base) throws SQLException {
|
|
||||||
return base.prepare(this.request);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return this.request;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private Configuration config;
|
|
||||||
private DatabasePuzzleRepository puzzleRepo;
|
|
||||||
|
|
||||||
public DatabaseChapterRepository(ConnectionManager con, Configuration config, DatabasePuzzleRepository puzzleRepo){
|
|
||||||
super(con);
|
|
||||||
this.config = config;
|
|
||||||
this.puzzleRepo = puzzleRepo;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get a specific chapter
|
|
||||||
*
|
|
||||||
* @param id The id of the chapter
|
|
||||||
* @return The chapter or null if an error occurred
|
|
||||||
*/
|
|
||||||
public Chapter getChapter(int id) {
|
|
||||||
try {
|
|
||||||
ensureConnection();
|
|
||||||
PreparedStatement chapterStmt = Query.SPECIFIC_CHAPTER_QUERY.prepare(this);
|
|
||||||
chapterStmt.setInt(1, id);
|
|
||||||
ResultSet chapterResult = chapterStmt.executeQuery();
|
|
||||||
if (chapterResult.next()) {
|
|
||||||
Chapter chapter = makeChapter(chapterResult);
|
|
||||||
List<Puzzle> puzzles = puzzleRepo.getPuzzlesInChapter(id);
|
|
||||||
chapter.setPuzzles(puzzles);
|
|
||||||
return chapter;
|
|
||||||
}
|
|
||||||
} catch (SQLException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Chapter getChapter(Puzzle puzzle){
|
|
||||||
try {
|
|
||||||
ensureConnection();
|
|
||||||
PreparedStatement chapterStmt = Query.CHAPTER_FROM_PUZZLE.prepare(this);
|
|
||||||
chapterStmt.setInt(1, puzzle.getId());
|
|
||||||
ResultSet chapterResult = chapterStmt.executeQuery();
|
|
||||||
if (chapterResult.next()) {
|
|
||||||
Chapter chapter = makeChapter(chapterResult);
|
|
||||||
List<Puzzle> puzzles = puzzleRepo.getPuzzlesInChapter(chapter.getId());
|
|
||||||
chapter.setPuzzles(puzzles);
|
|
||||||
return chapter;
|
|
||||||
}
|
|
||||||
} catch (SQLException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get all chapters in the database
|
|
||||||
*
|
|
||||||
* @return List of all chapters or null if an error occurred
|
|
||||||
*/
|
|
||||||
public List<Chapter> getAllChapters() {
|
|
||||||
try {
|
|
||||||
List<Chapter> chapterList = new ArrayList<>();
|
|
||||||
ensureConnection();
|
|
||||||
PreparedStatement chapterStmt = Query.ALL_CHAPTERS_QUERY.prepare(this);
|
|
||||||
ResultSet chapterResult = chapterStmt.executeQuery();
|
|
||||||
while (chapterResult.next()) {
|
|
||||||
Chapter chapter = makeChapter(chapterResult);
|
|
||||||
chapter.setPuzzles(puzzleRepo.getPuzzlesInChapter(chapter.getId()));
|
|
||||||
chapterList.add(chapter);
|
|
||||||
}
|
|
||||||
return chapterList;
|
|
||||||
} catch (SQLException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,162 +0,0 @@
|
||||||
package dev.peerat.backend.repository;
|
|
||||||
|
|
||||||
import java.sql.Connection;
|
|
||||||
import java.sql.PreparedStatement;
|
|
||||||
import java.sql.ResultSet;
|
|
||||||
import java.sql.SQLException;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import dev.peerat.backend.Configuration;
|
|
||||||
import dev.peerat.backend.model.Completion;
|
|
||||||
import dev.peerat.backend.model.Puzzle;
|
|
||||||
|
|
||||||
public class DatabaseCompletionRepository extends BaseDatabaseQuery{
|
|
||||||
|
|
||||||
private static enum Query{
|
|
||||||
|
|
||||||
// COMPLETIONS
|
|
||||||
GET_COMPLETION(
|
|
||||||
"SELECT * FROM completions WHERE fk_puzzle = ? AND fk_player = ?"),
|
|
||||||
GET_COMPLETION_GROUP("SELECT c.*\r\n"
|
|
||||||
+ "FROM completions c\r\n"
|
|
||||||
+ "WHERE c.fk_puzzle = ? AND c.fk_player IN\r\n"
|
|
||||||
+ "(select f.fk_player FROM containsGroups cgs JOIN containsGroups f ON f.fk_group = cgs.fk_group JOIN groups g ON g.id_group = cgs.fk_group WHERE g.fk_chapter = 12 AND cgs.fk_player = ?)"),
|
|
||||||
INSERT_COMPLETION(
|
|
||||||
"INSERT INTO completions (fk_puzzle, fk_player, tries, code, fileName, score) values (?, ?, ?, ?, ?, ?)"),
|
|
||||||
UPDATE_COMPLETION(
|
|
||||||
"UPDATE completions SET tries = ?, score = ?, fk_player = ? WHERE fk_puzzle = ? AND fk_player = ?"),
|
|
||||||
SCORE("SELECT score FROM completions WHERE fk_player = ? AND fk_puzzle = ?"),
|
|
||||||
SCORE_GROUP("SELECT c.score\r\n"
|
|
||||||
+ "FROM completions c\r\n"
|
|
||||||
+ "WHERE c.fk_puzzle = ? AND c.fk_player IN\r\n"
|
|
||||||
+ "(select f.fk_player FROM containsGroups cgs JOIN containsGroups f ON f.fk_group = cgs.fk_group JOIN groups g ON g.id_group = cgs.fk_group WHERE g.fk_chapter = 12 AND cgs.fk_player = ?)");
|
|
||||||
|
|
||||||
private String request;
|
|
||||||
|
|
||||||
Query(Query parent, String request) {
|
|
||||||
this.request = parent.request + request;
|
|
||||||
}
|
|
||||||
|
|
||||||
Query(String request) {
|
|
||||||
this.request = request;
|
|
||||||
}
|
|
||||||
|
|
||||||
public PreparedStatement prepare(BaseDatabaseQuery base) throws SQLException {
|
|
||||||
return base.prepare(this.request);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return this.request;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private Configuration config;
|
|
||||||
private DatabaseChapterRepository chapterRepo;
|
|
||||||
|
|
||||||
public DatabaseCompletionRepository(ConnectionManager con, Configuration config, DatabaseChapterRepository chapterRepo){
|
|
||||||
super(con);
|
|
||||||
this.config = config;
|
|
||||||
this.chapterRepo = chapterRepo;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Completion getCompletionGroup(int user, int puzzle) {
|
|
||||||
try {
|
|
||||||
PreparedStatement stmt = Query.GET_COMPLETION_GROUP.prepare(this);
|
|
||||||
stmt.setInt(1, puzzle);
|
|
||||||
stmt.setInt(2, user);
|
|
||||||
ResultSet result = stmt.executeQuery();
|
|
||||||
if (result.next())
|
|
||||||
return makeCompletion(result);
|
|
||||||
} catch (SQLException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return getCompletion(user, puzzle);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Completion getCompletion(int playerId, int puzzleId) {
|
|
||||||
try {
|
|
||||||
PreparedStatement completionsStmt = Query.GET_COMPLETION.prepare(this);
|
|
||||||
completionsStmt.setInt(1, puzzleId);
|
|
||||||
completionsStmt.setInt(2, playerId);
|
|
||||||
ResultSet result = completionsStmt.executeQuery();
|
|
||||||
if (result.next()) {
|
|
||||||
return makeCompletion(result);
|
|
||||||
}
|
|
||||||
} catch (SQLException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Completion insertOrUpdatePuzzleResponse(int puzzleId, int userId, String fileName, byte[] code,
|
|
||||||
byte[] response, Puzzle currentPuzzle){
|
|
||||||
try {
|
|
||||||
ensureConnection();
|
|
||||||
Completion completion = getCompletionGroup(userId, puzzleId);
|
|
||||||
if (completion == null){
|
|
||||||
System.out.println("Completion is null");
|
|
||||||
completion = new Completion(userId, puzzleId, fileName, code, response, currentPuzzle);
|
|
||||||
insertCompletion(completion);
|
|
||||||
} else {
|
|
||||||
System.out.println(completion);
|
|
||||||
completion.addTry(currentPuzzle, response, chapterRepo.getChapter(currentPuzzle).getId());
|
|
||||||
int lastUserId = completion.getPlayerId();
|
|
||||||
completion.updatePlayer(userId);
|
|
||||||
updateCompletion(completion, lastUserId);
|
|
||||||
}
|
|
||||||
return completion;
|
|
||||||
} catch (SQLException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void insertCompletion(Completion newCompletion) throws SQLException {
|
|
||||||
PreparedStatement statement = Query.INSERT_COMPLETION.prepare(this);
|
|
||||||
statement.setInt(1, newCompletion.getPuzzleId());
|
|
||||||
statement.setInt(2, newCompletion.getPlayerId());
|
|
||||||
statement.setInt(3, newCompletion.getTries());
|
|
||||||
statement.setBytes(4, newCompletion.getCode());
|
|
||||||
statement.setString(5, newCompletion.getFileName());
|
|
||||||
statement.setInt(6, newCompletion.getScore());
|
|
||||||
statement.executeUpdate();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private void updateCompletion(Completion completionToUpdate, int user) throws SQLException{
|
|
||||||
System.out.println("update "+completionToUpdate);
|
|
||||||
PreparedStatement statement = Query.UPDATE_COMPLETION.prepare(this);
|
|
||||||
statement.setInt(1, completionToUpdate.getTries());
|
|
||||||
statement.setInt(2, completionToUpdate.getScore());
|
|
||||||
statement.setInt(3, completionToUpdate.getPlayerId());
|
|
||||||
statement.setInt(4, completionToUpdate.getPuzzleId());
|
|
||||||
statement.setInt(5, user);
|
|
||||||
statement.executeUpdate();
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getScore(int user, int puzzle) {
|
|
||||||
try {
|
|
||||||
ensureConnection();
|
|
||||||
PreparedStatement stmt = Query.SCORE_GROUP.prepare(this);
|
|
||||||
stmt.setInt(1, puzzle);
|
|
||||||
stmt.setInt(2, user);
|
|
||||||
ResultSet result = stmt.executeQuery();
|
|
||||||
if (result.next())
|
|
||||||
return result.getInt("score");
|
|
||||||
|
|
||||||
stmt = Query.SCORE.prepare(this);
|
|
||||||
stmt.setInt(1, user);
|
|
||||||
stmt.setInt(2, puzzle);
|
|
||||||
|
|
||||||
result = stmt.executeQuery();
|
|
||||||
if (result.next())
|
|
||||||
return result.getInt("score");
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,166 +0,0 @@
|
||||||
package dev.peerat.backend.repository;
|
|
||||||
|
|
||||||
import java.sql.Connection;
|
|
||||||
import java.sql.PreparedStatement;
|
|
||||||
import java.sql.ResultSet;
|
|
||||||
import java.sql.SQLException;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import dev.peerat.backend.Configuration;
|
|
||||||
import dev.peerat.backend.model.Group;
|
|
||||||
import dev.peerat.backend.model.PeerAtUser;
|
|
||||||
|
|
||||||
public class DatabaseGroupRepository extends BaseDatabaseQuery{
|
|
||||||
|
|
||||||
private static enum Query{
|
|
||||||
|
|
||||||
// GROUPS
|
|
||||||
ALL_GROUPS("SELECT * FROM groups"),
|
|
||||||
ALL_GROUPS_BY_CHAPTER("select g.*, count(cg.fk_player) as countPlayer from groups g left join containsGroups cg on cg.fk_group = g.id_group where g.fk_chapter = ? group by g.id_group"),
|
|
||||||
GET_GROUP_FOR_PLAYER("SELECT g.* FROM groups g JOIN containsGroups cg ON cg.fk_group = g.id_group WHERE cg.fk_player = ? AND g.fk_chapter = ?"), // AND g.fk_puzzle = ?
|
|
||||||
GET_GROUP_ID_BY_DATA("SELECT id_group FROM groups WHERE name = ? AND (fk_chapter = ?)"), // OR fk_puzzle = ?
|
|
||||||
GET_GROUP_USERS_COUNT("SELECT count(*) as howmany FROM containsGroups WHERE fk_group = ?"),
|
|
||||||
INSERT_GROUP("INSERT INTO groups (name, fk_chapter) VALUES (?,?)"),
|
|
||||||
INSERT_PLAYER_IN_GROUP("INSERT INTO containsGroups (fk_player, fk_group) VALUES (?,?)"),
|
|
||||||
LEAVE_GROUP("DELETE FROM containsGroups WHERE fk_player = ? AND fk_group = ?");
|
|
||||||
|
|
||||||
private String request;
|
|
||||||
|
|
||||||
Query(Query parent, String request) {
|
|
||||||
this.request = parent.request + request;
|
|
||||||
}
|
|
||||||
|
|
||||||
Query(String request) {
|
|
||||||
this.request = request;
|
|
||||||
}
|
|
||||||
|
|
||||||
public PreparedStatement prepare(BaseDatabaseQuery base) throws SQLException {
|
|
||||||
return base.prepare(this.request);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return this.request;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private Configuration config;
|
|
||||||
|
|
||||||
public DatabaseGroupRepository(ConnectionManager con, Configuration config){
|
|
||||||
super(con);
|
|
||||||
this.config = config;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<Group> getAllGroups() {
|
|
||||||
try {
|
|
||||||
ensureConnection();
|
|
||||||
List<Group> list = new ArrayList<>();
|
|
||||||
PreparedStatement stmt = Query.ALL_GROUPS.prepare(this);
|
|
||||||
ResultSet groupResult = stmt.executeQuery();
|
|
||||||
while (groupResult.next())
|
|
||||||
list.add(makeGroup(groupResult));
|
|
||||||
return list;
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<Group> getAllGroupsByChapter(int chapter){
|
|
||||||
try {
|
|
||||||
ensureConnection();
|
|
||||||
List<Group> list = new ArrayList<>();
|
|
||||||
PreparedStatement stmt = Query.ALL_GROUPS_BY_CHAPTER.prepare(this);
|
|
||||||
stmt.setInt(1, chapter);
|
|
||||||
ResultSet groupResult = stmt.executeQuery();
|
|
||||||
while (groupResult.next())
|
|
||||||
list.add(makeGroup(groupResult));
|
|
||||||
return list;
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean insertGroup(Group group, PeerAtUser creator) throws SQLException {
|
|
||||||
Integer groupId = getGroupId(group);
|
|
||||||
if (groupId == null)
|
|
||||||
ensureConnection();
|
|
||||||
PreparedStatement statement = Query.INSERT_GROUP.prepare(this);
|
|
||||||
statement.setString(1, group.getName());
|
|
||||||
statement.setObject(2, group.getLinkToChapter());
|
|
||||||
// statement.setObject(3, group.getLinkToPuzzle());
|
|
||||||
if (statement.executeUpdate() >= 0)
|
|
||||||
return insertUserInGroup(group, creator);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Group getPlayerGroup(int user, Integer chapter) throws SQLException {
|
|
||||||
ensureConnection();
|
|
||||||
PreparedStatement stmt = Query.GET_GROUP_FOR_PLAYER.prepare(this);
|
|
||||||
stmt.setInt(1, user);
|
|
||||||
stmt.setObject(2, chapter);
|
|
||||||
// stmt.setObject(3, puzzle);
|
|
||||||
|
|
||||||
ResultSet result = stmt.executeQuery();
|
|
||||||
if (result.next())
|
|
||||||
return makeGroup(result);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getGroupId(Group group) throws SQLException {
|
|
||||||
ensureConnection();
|
|
||||||
PreparedStatement stmt = Query.GET_GROUP_ID_BY_DATA.prepare(this);
|
|
||||||
stmt.setString(1, group.getName());
|
|
||||||
stmt.setObject(2, group.getLinkToChapter());
|
|
||||||
// stmt.setObject(3, group.getLinkToPuzzle());
|
|
||||||
|
|
||||||
ResultSet result = stmt.executeQuery();
|
|
||||||
if (result.next())
|
|
||||||
return result.getInt("id_group");
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean insertUserInGroup(Group group, PeerAtUser user) throws SQLException{
|
|
||||||
Integer id = getGroupId(group);
|
|
||||||
if(id != null){
|
|
||||||
int howmany = numberInGroup(id);
|
|
||||||
System.out.println("join group, already have "+howmany);
|
|
||||||
if(howmany > config.getGroupMaxPlayers()) return false;
|
|
||||||
}
|
|
||||||
Group alreadyInGroup = getPlayerGroup(user.getId(), group.getLinkToChapter());
|
|
||||||
if (id != null && alreadyInGroup == null) {
|
|
||||||
PreparedStatement stmt = Query.INSERT_PLAYER_IN_GROUP.prepare(this);
|
|
||||||
|
|
||||||
stmt.setInt(1, user.getId());
|
|
||||||
stmt.setInt(2, id);
|
|
||||||
|
|
||||||
return stmt.executeUpdate() >= 0;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int numberInGroup(int group) throws SQLException{
|
|
||||||
PreparedStatement stmt = Query.GET_GROUP_USERS_COUNT.prepare(this);
|
|
||||||
stmt.setInt(1, group);
|
|
||||||
|
|
||||||
ResultSet result = stmt.executeQuery();
|
|
||||||
if(result.next()) return result.getInt("howmany");
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean leaveGroup(Group group, PeerAtUser user) throws SQLException {
|
|
||||||
Integer id = getGroupId(group);
|
|
||||||
if (id != null) {
|
|
||||||
PreparedStatement stmt = Query.LEAVE_GROUP.prepare(this);
|
|
||||||
|
|
||||||
stmt.setInt(1, user.getId());
|
|
||||||
stmt.setInt(2, id);
|
|
||||||
|
|
||||||
return stmt.executeUpdate() >= 0;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,102 +0,0 @@
|
||||||
package dev.peerat.backend.repository;
|
|
||||||
|
|
||||||
import java.sql.Connection;
|
|
||||||
import java.sql.PreparedStatement;
|
|
||||||
import java.sql.ResultSet;
|
|
||||||
import java.sql.SQLException;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.SortedSet;
|
|
||||||
import java.util.TreeSet;
|
|
||||||
|
|
||||||
import dev.peerat.backend.Configuration;
|
|
||||||
import dev.peerat.backend.model.Group;
|
|
||||||
import dev.peerat.backend.model.Player;
|
|
||||||
|
|
||||||
public class DatabaseLeaderboardRepository extends BaseDatabaseQuery{
|
|
||||||
|
|
||||||
private static enum Query{
|
|
||||||
|
|
||||||
// LEADERBOARD
|
|
||||||
ALL_PLAYERS_FOR_LEADERBOARD(
|
|
||||||
"select p.*, scores.*, g.* from players p ,(SELECT fk_player, SUM(c.score) AS score, COUNT(c.id_completion) AS completions, SUM(c.tries) AS tries, rank() over(ORDER BY score DESC) AS rank FROM completions c LEFT JOIN puzzles puzz on puzz.id_puzzle = c.fk_puzzle LEFT JOIN chapters chap on chap.id_chapter = puzz.fk_chapter WHERE chap.id_chapter > 1 GROUP BY c.fk_player) AS scores LEFT JOIN containsGroups cg ON scores.fk_player = cg.fk_player LEFT JOIN groups g ON cg.fk_group = g.id_group WHERE p.id_player = scores.fk_player ORDER BY g.fk_chapter"),
|
|
||||||
ALL_GROUP_FOR_CHAPTER_LEADERBOARD(
|
|
||||||
"SELECT g.*, pl.pseudo, co.score, co.tries FROM groups g LEFT JOIN containsGroups cg ON g.id_group = cg.fk_group LEFT JOIN players pl ON cg.fk_player = pl.id_player LEFT JOIN completions co ON pl.id_player = co.fk_player WHERE cg.fk_player IS NOT NULL AND fk_chapter = ? AND (co.fk_puzzle IN (SELECT id_puzzle FROM puzzles puz WHERE puz.fk_chapter = g.fk_chapter) OR co.score IS NULL);");
|
|
||||||
|
|
||||||
private String request;
|
|
||||||
|
|
||||||
Query(Query parent, String request) {
|
|
||||||
this.request = parent.request + request;
|
|
||||||
}
|
|
||||||
|
|
||||||
Query(String request) {
|
|
||||||
this.request = request;
|
|
||||||
}
|
|
||||||
|
|
||||||
public PreparedStatement prepare(BaseDatabaseQuery base) throws SQLException {
|
|
||||||
return base.prepare(this.request);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return this.request;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private Configuration config;
|
|
||||||
|
|
||||||
public DatabaseLeaderboardRepository(ConnectionManager con, Configuration config){
|
|
||||||
super(con);
|
|
||||||
this.config = config;
|
|
||||||
}
|
|
||||||
|
|
||||||
public SortedSet<Player> getAllPlayerForLeaderboard() {
|
|
||||||
try {
|
|
||||||
ensureConnection();
|
|
||||||
PreparedStatement playersStmt = Query.ALL_PLAYERS_FOR_LEADERBOARD.prepare(this);
|
|
||||||
ResultSet result = playersStmt.executeQuery();
|
|
||||||
ArrayList<Player> players = new ArrayList<Player>();
|
|
||||||
Player tmpPlayer;
|
|
||||||
while (result.next()) {
|
|
||||||
tmpPlayer = makePlayer(result, result.getInt("id_player"));
|
|
||||||
if (!players.contains(tmpPlayer)) {
|
|
||||||
players.add(tmpPlayer);
|
|
||||||
} else {
|
|
||||||
players.get(players.indexOf(tmpPlayer)).addGroup(makeGroup(result));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return new TreeSet<Player>(players);
|
|
||||||
} catch (SQLException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public SortedSet<Group> getAllGroupForChapterLeaderboard(int chapterId){
|
|
||||||
try{
|
|
||||||
ensureConnection();
|
|
||||||
PreparedStatement groupsStmt = Query.ALL_GROUP_FOR_CHAPTER_LEADERBOARD.prepare(this);
|
|
||||||
groupsStmt.setInt(1, chapterId);
|
|
||||||
ResultSet result = groupsStmt.executeQuery();
|
|
||||||
List<Group> groups = new ArrayList<Group>();
|
|
||||||
Group tmpGroup;
|
|
||||||
while (result.next()) {
|
|
||||||
tmpGroup = makeGroup(result);
|
|
||||||
if (tmpGroup != null) {
|
|
||||||
int gPosition = groups.indexOf(tmpGroup);
|
|
||||||
if (gPosition < 0) {
|
|
||||||
tmpGroup.addPlayer(makeGroupPlayer(result));
|
|
||||||
groups.add(tmpGroup);
|
|
||||||
} else {
|
|
||||||
groups.get(gPosition).addPlayer(makeGroupPlayer(result));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return new TreeSet<Group>(groups);
|
|
||||||
}catch(SQLException e){
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,191 +0,0 @@
|
||||||
package dev.peerat.backend.repository;
|
|
||||||
|
|
||||||
import java.sql.Connection;
|
|
||||||
import java.sql.PreparedStatement;
|
|
||||||
import java.sql.ResultSet;
|
|
||||||
import java.sql.SQLException;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import com.password4j.Password;
|
|
||||||
|
|
||||||
import dev.peerat.backend.Configuration;
|
|
||||||
import dev.peerat.backend.model.Player;
|
|
||||||
import dev.peerat.backend.model.Puzzle;
|
|
||||||
|
|
||||||
public class DatabasePlayerRepository extends BaseDatabaseQuery{
|
|
||||||
|
|
||||||
public static String GET_PLAYER_RANK(){
|
|
||||||
return Query.GET_PLAYER_RANK.request;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static enum Query{
|
|
||||||
|
|
||||||
// PLAYERS
|
|
||||||
GET_PLAYER_SIMPLE("SELECT pseudo, email, firstname, lastname, description FROM players WHERE id_player = ?"),
|
|
||||||
GET_PLAYER_EMAIL("SELECT id_player FROM players WHERE email = ?"),
|
|
||||||
GET_PLAYER_PSEUDO("SELECT * FROM players WHERE pseudo = ?"),
|
|
||||||
GET_PLAYER_DETAILS("SELECT p.*, g.*\r\n"
|
|
||||||
+ "FROM players p\r\n"
|
|
||||||
+ "LEFT OUTER JOIN containsGroups cg ON p.id_player = cg.fk_player\r\n"
|
|
||||||
+ "LEFT OUTER JOIN groups g ON cg.fk_group = g.id_group\r\n"
|
|
||||||
+ "LEFT OUTER JOIN completions c on p.id_player = c.fk_player\r\n"
|
|
||||||
+ "WHERE "),
|
|
||||||
GET_PLAYER_DETAILS_BY_ID(GET_PLAYER_DETAILS, " p.id_player = ? GROUP BY g.name ORDER BY g.fk_chapter, g.fk_puzzle;"),
|
|
||||||
GET_PLAYER_DETAILS_BY_PSEUDO(GET_PLAYER_DETAILS, "p.pseudo = ? GROUP BY g.name ORDER BY g.fk_chapter, g.fk_puzzle;"),
|
|
||||||
GET_PLAYER_COMPLETIONS("select c.*, p.name from completions c left join puzzles p on c.fk_puzzle = p.id_puzzle where fk_player = ?;"),
|
|
||||||
GET_PLAYER_RANK("SELECT * FROM (SELECT fk_player, RANK() OVER(ORDER BY SUM(score) DESC) rank FROM completions c LEFT JOIN puzzles puzz on puzz.id_puzzle = c.fk_puzzle LEFT JOIN chapters chap on chap.id_chapter = puzz.fk_chapter LEFT JOIN players p ON p.id_player = c.fk_player WHERE chap.id_chapter > 1 GROUP BY fk_player ORDER BY rank) AS ranks WHERE ranks.fk_player = ?;"),
|
|
||||||
UPDATE_PLAYER_INFO("UPDATE players SET pseudo = ?, email = ?, firstname = ?, lastname = ? WHERE id_player = ?"),
|
|
||||||
UPDATE_PLAYER_PASSWORD("UPDATE players SET passwd = ? WHERE id_player = ?");
|
|
||||||
private String request;
|
|
||||||
|
|
||||||
Query(Query parent, String request) {
|
|
||||||
this.request = parent.request + request;
|
|
||||||
}
|
|
||||||
|
|
||||||
Query(String request) {
|
|
||||||
this.request = request;
|
|
||||||
}
|
|
||||||
|
|
||||||
public PreparedStatement prepare(BaseDatabaseQuery base) throws SQLException {
|
|
||||||
return base.prepare(this.request);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return this.request;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private Configuration config;
|
|
||||||
|
|
||||||
public DatabasePlayerRepository(ConnectionManager con, Configuration config){
|
|
||||||
super(con);
|
|
||||||
this.config = config;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Player getPlayer(int idPlayer) {
|
|
||||||
try {
|
|
||||||
PreparedStatement completionsStmt = Query.GET_PLAYER_SIMPLE.prepare(this);
|
|
||||||
completionsStmt.setInt(1, idPlayer);
|
|
||||||
ResultSet result = completionsStmt.executeQuery();
|
|
||||||
if (result.next()) {
|
|
||||||
return makePlayer(result, idPlayer);
|
|
||||||
}
|
|
||||||
} catch (SQLException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getPlayerId(String email){
|
|
||||||
try {
|
|
||||||
ensureConnection();
|
|
||||||
PreparedStatement completionsStmt = Query.GET_PLAYER_EMAIL.prepare(this);
|
|
||||||
completionsStmt.setString(1, email);
|
|
||||||
ResultSet result = completionsStmt.executeQuery();
|
|
||||||
if (result.next()) {
|
|
||||||
return result.getInt("id_player");
|
|
||||||
}
|
|
||||||
} catch (SQLException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean updatePseudo(int id, Player player, String pseudo){
|
|
||||||
try{
|
|
||||||
PreparedStatement statment = Query.GET_PLAYER_PSEUDO.prepare(this);
|
|
||||||
statment.setString(1, pseudo);
|
|
||||||
ResultSet result = statment.executeQuery();
|
|
||||||
if(result.next()) return false;
|
|
||||||
statment = Query.UPDATE_PLAYER_INFO.prepare(this);
|
|
||||||
statment.setString(1, pseudo);
|
|
||||||
statment.setString(2, player.getEmail());
|
|
||||||
statment.setString(3, player.getFirstname());
|
|
||||||
statment.setString(4, player.getLastname());
|
|
||||||
statment.setInt(5, id);
|
|
||||||
return statment.executeUpdate() > 0;
|
|
||||||
}catch(Exception e){
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void updateProfile(int id, Player player, String lastname, String firstname){
|
|
||||||
try{
|
|
||||||
PreparedStatement statment = Query.UPDATE_PLAYER_INFO.prepare(this);
|
|
||||||
statment.setString(1, player.getPseudo());
|
|
||||||
statment.setString(2, player.getEmail());
|
|
||||||
statment.setString(3, firstname);
|
|
||||||
statment.setString(4, lastname);
|
|
||||||
statment.setInt(5, id);
|
|
||||||
statment.executeUpdate();
|
|
||||||
}catch(Exception e){
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void updatePassword(int id, String password){
|
|
||||||
try{
|
|
||||||
PreparedStatement statment = Query.UPDATE_PLAYER_PASSWORD.prepare(this);
|
|
||||||
statment.setString(1, Password.hash(password).withArgon2().getResult());
|
|
||||||
statment.setInt(2, id);
|
|
||||||
statment.executeUpdate();
|
|
||||||
}catch(Exception e){
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public Player getPlayerDetails(int idPlayer) {
|
|
||||||
return getPlayerDetails(idPlayer, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Player getPlayerDetails(String pseudoPlayer) {
|
|
||||||
return getPlayerDetails(-1, pseudoPlayer);
|
|
||||||
}
|
|
||||||
|
|
||||||
private Player getPlayerDetails(int id, String pseudo) {
|
|
||||||
try {
|
|
||||||
ensureConnection();
|
|
||||||
PreparedStatement completionsStmt;
|
|
||||||
if (pseudo != null) {
|
|
||||||
completionsStmt = Query.GET_PLAYER_DETAILS_BY_PSEUDO.prepare(this);
|
|
||||||
completionsStmt.setString(1, pseudo);
|
|
||||||
} else {
|
|
||||||
completionsStmt = Query.GET_PLAYER_DETAILS_BY_ID.prepare(this);
|
|
||||||
completionsStmt.setInt(1, id);
|
|
||||||
}
|
|
||||||
ResultSet result = completionsStmt.executeQuery();
|
|
||||||
Player player = null;
|
|
||||||
while (result.next()) {
|
|
||||||
if (player == null) {
|
|
||||||
id = result.getInt("id_player");
|
|
||||||
player = makePlayer(result, id);
|
|
||||||
completionsStmt = prepare(DatabaseBadgeRepository.GET_BADGES_OF_PLAYER());
|
|
||||||
completionsStmt.setInt(1, id);
|
|
||||||
ResultSet resultBadges = completionsStmt.executeQuery();
|
|
||||||
while (resultBadges.next()) {
|
|
||||||
player.addBadge(makeBadge(resultBadges));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
player.addGroup(makeGroup(result));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// ADD completions
|
|
||||||
completionsStmt = Query.GET_PLAYER_COMPLETIONS.prepare(this);
|
|
||||||
completionsStmt.setInt(1, id);
|
|
||||||
result = completionsStmt.executeQuery();
|
|
||||||
while (result.next()) {
|
|
||||||
player.addCompletion(makeCompletion(result));
|
|
||||||
}
|
|
||||||
|
|
||||||
return player;
|
|
||||||
} catch (SQLException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,78 +0,0 @@
|
||||||
package dev.peerat.backend.repository;
|
|
||||||
|
|
||||||
import java.sql.Connection;
|
|
||||||
import java.sql.PreparedStatement;
|
|
||||||
import java.sql.ResultSet;
|
|
||||||
import java.sql.SQLException;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import dev.peerat.backend.Configuration;
|
|
||||||
import dev.peerat.backend.model.Puzzle;
|
|
||||||
|
|
||||||
public class DatabasePuzzleRepository extends BaseDatabaseQuery{
|
|
||||||
|
|
||||||
private static enum Query{
|
|
||||||
|
|
||||||
SPECIFIC_PUZZLE_QUERY(
|
|
||||||
"SELECT p.*, np.origin, GROUP_CONCAT(t.name) AS tags FROM puzzles p LEFT JOIN nextPart np ON p.id_puzzle = np.next LEFT JOIN containsTags ct ON ct.fk_puzzle = p.id_puzzle LEFT JOIN tags t ON t.id_tag = ct.fk_tag WHERE p.id_puzzle = ? GROUP BY p.id_puzzle"),
|
|
||||||
PUZZLES_IN_CHAPTER_QUERY(
|
|
||||||
"SELECT p.*, GROUP_CONCAT(t.name) AS tags FROM puzzles p LEFT JOIN containsTags ct ON ct.fk_puzzle = p.id_puzzle LEFT JOIN tags t ON t.id_tag = ct.fk_tag WHERE fk_chapter = ? GROUP BY p.id_puzzle");
|
|
||||||
|
|
||||||
private String request;
|
|
||||||
|
|
||||||
Query(Query parent, String request) {
|
|
||||||
this.request = parent.request + request;
|
|
||||||
}
|
|
||||||
|
|
||||||
Query(String request) {
|
|
||||||
this.request = request;
|
|
||||||
}
|
|
||||||
|
|
||||||
public PreparedStatement prepare(BaseDatabaseQuery base) throws SQLException {
|
|
||||||
return base.prepare(this.request);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return this.request;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private Configuration config;
|
|
||||||
|
|
||||||
public DatabasePuzzleRepository(ConnectionManager con, Configuration config){
|
|
||||||
super(con);
|
|
||||||
this.config = config;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<Puzzle> getPuzzlesInChapter(int id) throws SQLException {
|
|
||||||
List<Puzzle> puzzles = new ArrayList<>();
|
|
||||||
ensureConnection();
|
|
||||||
PreparedStatement puzzleStmt = Query.PUZZLES_IN_CHAPTER_QUERY.prepare(this);
|
|
||||||
puzzleStmt.setInt(1, id);
|
|
||||||
ResultSet puzzleResult = puzzleStmt.executeQuery();
|
|
||||||
while (puzzleResult.next()) {
|
|
||||||
puzzles.add(makePuzzle(puzzleResult));
|
|
||||||
}
|
|
||||||
return puzzles;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get a specific puzzle
|
|
||||||
*
|
|
||||||
* @param id The id of the puzzle
|
|
||||||
* @return The puzzle or null if an error occurred
|
|
||||||
*/
|
|
||||||
public Puzzle getPuzzle(int id) throws SQLException {
|
|
||||||
ensureConnection();
|
|
||||||
PreparedStatement puzzleStmt = Query.SPECIFIC_PUZZLE_QUERY.prepare(this);
|
|
||||||
puzzleStmt.setInt(1, id);
|
|
||||||
ResultSet puzzleResult = puzzleStmt.executeQuery();
|
|
||||||
if (puzzleResult.next()) {
|
|
||||||
return makePuzzle(puzzleResult);
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,181 +0,0 @@
|
||||||
package dev.peerat.backend.repository;
|
|
||||||
|
|
||||||
import java.sql.Connection;
|
|
||||||
import java.sql.PreparedStatement;
|
|
||||||
import java.sql.SQLException;
|
|
||||||
|
|
||||||
public enum DatabaseQuery {
|
|
||||||
|
|
||||||
//TRIGGER
|
|
||||||
FIRST_TRY("CREATE OR REPLACE TRIGGER FirstTry\r\n"
|
|
||||||
+ "AFTER INSERT\r\n"
|
|
||||||
+ " ON completions FOR EACH ROW\r\n"
|
|
||||||
+ "BEGIN\r\n"
|
|
||||||
+ " DECLARE badge INT;\r\n"
|
|
||||||
+ " DECLARE contain INT;\r\n"
|
|
||||||
+ " \r\n"
|
|
||||||
+ " SELECT id_badge\r\n"
|
|
||||||
+ " INTO @badge\r\n"
|
|
||||||
+ " FROM badges\r\n"
|
|
||||||
+ " WHERE name = 'FirstTry';\r\n"
|
|
||||||
+ " \r\n"
|
|
||||||
+ " IF @badge is not null THEN\r\n"
|
|
||||||
+ " \r\n"
|
|
||||||
+ " SELECT count(*)\r\n"
|
|
||||||
+ " INTO @contain\r\n"
|
|
||||||
+ " FROM containsBadges\r\n"
|
|
||||||
+ " WHERE fk_badge = @badge AND fk_player = NEW.fk_player;\r\n"
|
|
||||||
+ " \r\n"
|
|
||||||
+ " IF (@contain = 0) THEN\r\n"
|
|
||||||
+ " INSERT INTO containsBadges(fk_player, fk_badge) VALUES (NEW.fk_player, @badge);\r\n"
|
|
||||||
+ " END IF;\r\n"
|
|
||||||
+ " END IF;\r\n"
|
|
||||||
+ "END;"),
|
|
||||||
EventParticipation("CREATE OR REPLACE TRIGGER EventParticipation\r\n"
|
|
||||||
+ "AFTER INSERT\r\n"
|
|
||||||
+ " ON completions FOR EACH ROW\r\n"
|
|
||||||
+ "BEGIN\r\n"
|
|
||||||
+ " DECLARE badge INT;\r\n"
|
|
||||||
+ " DECLARE endDate datetime;\r\n"
|
|
||||||
+ " DECLARE player INT;\r\n"
|
|
||||||
+ " DECLARE contain INT;\r\n"
|
|
||||||
+ "\r\n"
|
|
||||||
+ " SELECT id_badge\r\n"
|
|
||||||
+ " INTO badge\r\n"
|
|
||||||
+ " FROM badges\r\n"
|
|
||||||
+ " WHERE name = 'EventParticipation';\r\n"
|
|
||||||
+ "\r\n"
|
|
||||||
+ " IF @badge is not null THEN\r\n"
|
|
||||||
+ "\r\n"
|
|
||||||
+ " SELECT c.end_date, i.fk_player\r\n"
|
|
||||||
+ " INTO endDate, player\r\n"
|
|
||||||
+ " FROM inserted i\r\n"
|
|
||||||
+ " JOIN puzzles p ON i.fk_puzzle = p.id_puzzle\r\n"
|
|
||||||
+ " JOIN chapters c on p.fk_chapter = c.id_chapter;\r\n"
|
|
||||||
+ "\r\n"
|
|
||||||
+ " IF @endDate is not null THEN\r\n"
|
|
||||||
+ "\r\n"
|
|
||||||
+ " SELECT count(*)\r\n"
|
|
||||||
+ " INTO contain\r\n"
|
|
||||||
+ " FROM containsBadges\r\n"
|
|
||||||
+ " WHERE fk_badge = badge AND fk_player = player;\r\n"
|
|
||||||
+ "\r\n"
|
|
||||||
+ " IF (@contain = 0) THEN\r\n"
|
|
||||||
+ " INSERT INTO containsBadges(fk_player, fk_badge) VALUES (@player, @badge);\r\n"
|
|
||||||
+ " END IF;\r\n"
|
|
||||||
+ " END IF;\r\n"
|
|
||||||
+ " END IF;\r\n"
|
|
||||||
+ "END;");
|
|
||||||
|
|
||||||
private String request;
|
|
||||||
|
|
||||||
DatabaseQuery(DatabaseQuery parent, String request) {
|
|
||||||
this.request = parent.request + request;
|
|
||||||
}
|
|
||||||
|
|
||||||
DatabaseQuery(String request) {
|
|
||||||
this.request = request;
|
|
||||||
}
|
|
||||||
|
|
||||||
public PreparedStatement prepare(Connection con) throws SQLException {
|
|
||||||
return con.prepareStatement(this.request);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return this.request;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/*
|
|
||||||
*
|
|
||||||
|
|
||||||
SELECT p.*, scores.score, scores.completions, scores.tries, scores.rank, g.*
|
|
||||||
FROM players p,
|
|
||||||
(SELECT fk_player, SUM(c.score) AS score,
|
|
||||||
COUNT(c.id_completion) AS completions,
|
|
||||||
SUM(c.tries) AS tries,
|
|
||||||
rank() over(ORDER BY score DESC) AS rank
|
|
||||||
FROM completions c GROUP BY c.fk_player)
|
|
||||||
AS scores
|
|
||||||
LEFT OUTER JOIN containsGroups cg ON scores.fk_player = cg.fk_player
|
|
||||||
LEFT OUTER JOIN groups g ON cg.fk_group = g.id_group
|
|
||||||
WHERE p.id_player = scores.fk_player AND "),
|
|
||||||
|
|
||||||
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
|
|
||||||
/* TRIGGER PLACE
|
|
||||||
*
|
|
||||||
|
|
||||||
CREATE OR REPLACE TRIGGER FirstTry
|
|
||||||
AFTER INSERT
|
|
||||||
ON completions FOR EACH ROW
|
|
||||||
BEGIN
|
|
||||||
DECLARE badge INT;
|
|
||||||
DECLARE contain INT;
|
|
||||||
|
|
||||||
SELECT id_badge
|
|
||||||
INTO @badge
|
|
||||||
FROM badges
|
|
||||||
WHERE name = 'FirstTry';
|
|
||||||
|
|
||||||
IF @badge is not null THEN
|
|
||||||
|
|
||||||
SELECT count(*)
|
|
||||||
INTO @contain
|
|
||||||
FROM containsBadges
|
|
||||||
WHERE fk_badge = @badge AND fk_player = NEW.fk_player;
|
|
||||||
|
|
||||||
IF (@contain = 0) THEN
|
|
||||||
|
|
||||||
IF (NEW.score >= 0 AND NEW.tries < 2) THEN
|
|
||||||
INSERT INTO containsBadges(fk_player, fk_badge) VALUES (NEW.fk_player, @badge);
|
|
||||||
END IF;
|
|
||||||
END IF;
|
|
||||||
END IF;
|
|
||||||
END;
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
CREATE OR REPLACE TRIGGER EventParticipation
|
|
||||||
AFTER INSERT
|
|
||||||
ON completions FOR EACH ROW
|
|
||||||
BEGIN
|
|
||||||
DECLARE badge INT;
|
|
||||||
DECLARE endDate datetime;
|
|
||||||
DECLARE player INT;
|
|
||||||
DECLARE contain INT;
|
|
||||||
|
|
||||||
SELECT id_badge
|
|
||||||
INTO badge
|
|
||||||
FROM badges
|
|
||||||
WHERE name = 'EventParticipation';
|
|
||||||
|
|
||||||
IF @badge is not null THEN
|
|
||||||
|
|
||||||
SELECT c.end_date, i.fk_player
|
|
||||||
INTO endDate, player
|
|
||||||
FROM inserted i
|
|
||||||
JOIN puzzles p ON i.fk_puzzle = p.id_puzzle
|
|
||||||
JOIN chapters c on p.fk_chapter = c.id_chapter;
|
|
||||||
|
|
||||||
IF @endDate is not null THEN
|
|
||||||
|
|
||||||
SELECT count(*)
|
|
||||||
INTO contain
|
|
||||||
FROM containsBadges
|
|
||||||
WHERE fk_badge = badge AND fk_player = player;
|
|
||||||
|
|
||||||
IF (@contain = 0) THEN
|
|
||||||
INSERT INTO containsBadges(fk_player, fk_badge) VALUES (@player, @badge);
|
|
||||||
END IF;
|
|
||||||
END IF;
|
|
||||||
END IF;
|
|
||||||
END;
|
|
||||||
|
|
||||||
|
|
||||||
*
|
|
||||||
*/
|
|
|
@ -1,239 +0,0 @@
|
||||||
package dev.peerat.backend.repository;
|
|
||||||
|
|
||||||
import java.io.BufferedReader;
|
|
||||||
import java.io.BufferedWriter;
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.FileReader;
|
|
||||||
import java.io.FileWriter;
|
|
||||||
import java.io.InputStream;
|
|
||||||
import java.io.InputStreamReader;
|
|
||||||
import java.lang.reflect.Field;
|
|
||||||
import java.nio.file.FileSystems;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.nio.file.StandardWatchEventKinds;
|
|
||||||
import java.nio.file.WatchEvent;
|
|
||||||
import java.nio.file.WatchKey;
|
|
||||||
import java.nio.file.WatchService;
|
|
||||||
import java.sql.Connection;
|
|
||||||
import java.sql.PreparedStatement;
|
|
||||||
import java.sql.ResultSet;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import dev.peerat.backend.Configuration;
|
|
||||||
|
|
||||||
public class DatabaseRepository extends BaseDatabaseQuery{
|
|
||||||
|
|
||||||
private Connection con; //refractor chain
|
|
||||||
private Configuration config;
|
|
||||||
|
|
||||||
private DatabasePuzzleRepository puzzleRepo;
|
|
||||||
private DatabaseChapterRepository chapterRepo;
|
|
||||||
private DatabaseAdminRepository adminRepo;
|
|
||||||
private DatabaseAuthRepository authRepo;
|
|
||||||
private DatabaseBadgeRepository badgeRepo;
|
|
||||||
private DatabaseCompletionRepository completionRepo;
|
|
||||||
private DatabaseGroupRepository groupRepo;
|
|
||||||
private DatabaseLeaderboardRepository leaderboardRepo;
|
|
||||||
private DatabasePlayerRepository playerRepo;
|
|
||||||
|
|
||||||
public DatabaseRepository(ConnectionManager con, Configuration config) throws Exception {
|
|
||||||
super(con);
|
|
||||||
this.config = config;
|
|
||||||
|
|
||||||
this.puzzleRepo = new DatabasePuzzleRepository(con, config);
|
|
||||||
this.chapterRepo = new DatabaseChapterRepository(con, config, puzzleRepo);
|
|
||||||
this.adminRepo = new DatabaseAdminRepository(con, config);
|
|
||||||
this.authRepo = new DatabaseAuthRepository(con, config);
|
|
||||||
this.badgeRepo = new DatabaseBadgeRepository(con, config);
|
|
||||||
this.completionRepo = new DatabaseCompletionRepository(con, config, chapterRepo);
|
|
||||||
this.groupRepo = new DatabaseGroupRepository(con, config);
|
|
||||||
this.leaderboardRepo = new DatabaseLeaderboardRepository(con, config);
|
|
||||||
this.playerRepo = new DatabasePlayerRepository(con, config);
|
|
||||||
|
|
||||||
loadConfig(config);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void loadConfig(Configuration config) throws Exception{
|
|
||||||
String name = DatabaseRepository.class.getPackage().getName();
|
|
||||||
InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream(name.replace(".", "/"));
|
|
||||||
File folder = new File(config.getSqlFolder());
|
|
||||||
try{
|
|
||||||
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
|
|
||||||
String line;
|
|
||||||
while((line = reader.readLine()) != null){
|
|
||||||
if(line.endsWith(".class")){
|
|
||||||
Class<?> clazz = Class.forName(name+"."+line.substring(0, line.length()-6));
|
|
||||||
if(BaseDatabaseQuery.class.isAssignableFrom(clazz)){
|
|
||||||
for(Class<?> subClazz : clazz.getDeclaredClasses()){
|
|
||||||
if(subClazz.isEnum()){
|
|
||||||
configure(subClazz, folder);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
reader.close();
|
|
||||||
}catch(Exception e){
|
|
||||||
System.err.println("Failed to read "+name);
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
new Thread(() -> {
|
|
||||||
try{
|
|
||||||
WatchService watchService = FileSystems.getDefault().newWatchService();
|
|
||||||
Path path = folder.toPath();
|
|
||||||
path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
|
|
||||||
while (true) {
|
|
||||||
WatchKey key = watchService.take();
|
|
||||||
for(WatchEvent<?> event : key.pollEvents()){
|
|
||||||
Path edited = (Path) event.context();
|
|
||||||
String targetClazz = edited.toFile().getName().split("\\.")[0];
|
|
||||||
Class<?> clazz = Class.forName(name+"."+targetClazz);
|
|
||||||
if(BaseDatabaseQuery.class.isAssignableFrom(clazz)){
|
|
||||||
for(Class<?> subClazz : clazz.getDeclaredClasses()){
|
|
||||||
if(subClazz.isEnum()){
|
|
||||||
bind(subClazz, new File(folder, edited.toFile().getName()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
key.reset();
|
|
||||||
}
|
|
||||||
}catch(Exception ex){
|
|
||||||
ex.printStackTrace();
|
|
||||||
}
|
|
||||||
}).start();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void configure(Class<?> clazz, File folder) throws Exception{
|
|
||||||
String name = clazz.getName().split("\\$")[0];
|
|
||||||
String[] split = name.split("\\.");
|
|
||||||
File file = new File(folder, split[split.length-1]+".txt");
|
|
||||||
if(file.exists()){
|
|
||||||
bind(clazz, file);
|
|
||||||
}else{
|
|
||||||
File parent = file.getParentFile();
|
|
||||||
if(!parent.exists()) parent.mkdirs();
|
|
||||||
file.createNewFile();
|
|
||||||
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
|
|
||||||
for(Object obj : clazz.getEnumConstants()){
|
|
||||||
Enum instance = (Enum) obj;
|
|
||||||
writer.write(instance.name()+"="+instance.toString().replace("\n", " ").replace("\r", " ")+"\n");
|
|
||||||
}
|
|
||||||
writer.flush();
|
|
||||||
writer.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void bind(Class<?> clazz, File file) throws Exception{
|
|
||||||
Map<String, String> map = new HashMap<>();
|
|
||||||
BufferedReader reader = new BufferedReader(new FileReader(file));
|
|
||||||
String line;
|
|
||||||
while((line = reader.readLine()) != null){
|
|
||||||
int index = line.indexOf('=');
|
|
||||||
String key = line.substring(0, index);
|
|
||||||
String value = line.substring(index+1);
|
|
||||||
map.put(key, value);
|
|
||||||
}
|
|
||||||
reader.close();
|
|
||||||
|
|
||||||
for(Object obj : clazz.getEnumConstants()){
|
|
||||||
Enum instance = (Enum) obj;
|
|
||||||
String value = map.get(instance.name());
|
|
||||||
Field field = obj.getClass().getDeclaredField("request");
|
|
||||||
field.setAccessible(true);
|
|
||||||
field.set(instance, value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public DatabasePuzzleRepository getPuzzleRepository(){
|
|
||||||
return this.puzzleRepo;
|
|
||||||
}
|
|
||||||
|
|
||||||
public DatabaseChapterRepository getChapterRepository(){
|
|
||||||
return this.chapterRepo;
|
|
||||||
}
|
|
||||||
|
|
||||||
public DatabaseAdminRepository getAdminRepository(){
|
|
||||||
return this.adminRepo;
|
|
||||||
}
|
|
||||||
|
|
||||||
public DatabaseAuthRepository getAuthRepository(){
|
|
||||||
return this.authRepo;
|
|
||||||
}
|
|
||||||
|
|
||||||
public DatabaseBadgeRepository getBadgeRepository(){
|
|
||||||
return this.badgeRepo;
|
|
||||||
}
|
|
||||||
|
|
||||||
public DatabaseCompletionRepository getCompletionRepository(){
|
|
||||||
return this.completionRepo;
|
|
||||||
}
|
|
||||||
|
|
||||||
public DatabaseGroupRepository getGroupRepository(){
|
|
||||||
return this.groupRepo;
|
|
||||||
}
|
|
||||||
|
|
||||||
public DatabaseLeaderboardRepository getLeaderboardRepository(){
|
|
||||||
return this.leaderboardRepo;
|
|
||||||
}
|
|
||||||
|
|
||||||
public DatabasePlayerRepository getPlayerRepository(){
|
|
||||||
return this.playerRepo;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
public void hotfix() throws Exception{
|
|
||||||
ensureConnection();
|
|
||||||
|
|
||||||
PreparedStatement stmt = con.prepareStatement("SELECT c.*, g.* FROM completions c JOIN puzzles p ON c.fk_puzzle = p.id_puzzle JOIN containsGroups cg ON cg.fk_player = c.fk_player JOIN groups g ON g.id_group = cg.fk_group WHERE g.fk_chapter = 12 AND p.fk_chapter = 12;");
|
|
||||||
ResultSet results = stmt.executeQuery();
|
|
||||||
List<Completionz> list = new ArrayList<>();
|
|
||||||
while(results.next()){
|
|
||||||
Completionz complete = new Completionz(results);
|
|
||||||
list.add(complete);
|
|
||||||
}
|
|
||||||
Map<Integer, Map<Integer, Completionz>> map = new HashMap<>();
|
|
||||||
for(Completionz comp : list){
|
|
||||||
Map<Integer,Completionz> puz = map.get(comp.puzzle);
|
|
||||||
if(puz == null){
|
|
||||||
puz = new HashMap<>();
|
|
||||||
map.put(comp.puzzle, puz);
|
|
||||||
}
|
|
||||||
Completionz c = puz.get(comp.groups);
|
|
||||||
if(c == null){
|
|
||||||
puz.put(comp.groups, comp);
|
|
||||||
}else{
|
|
||||||
if(comp.score >= c.score){
|
|
||||||
puz.put(comp.groups, comp);
|
|
||||||
System.out.println("remove compl "+c.id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static class Completionz{
|
|
||||||
|
|
||||||
public int id;
|
|
||||||
public int puzzle;
|
|
||||||
public int player;
|
|
||||||
public int tries;
|
|
||||||
public int score;
|
|
||||||
public int groups;
|
|
||||||
|
|
||||||
public Completionz(ResultSet result) throws Exception{
|
|
||||||
id = result.getInt("id_completion");
|
|
||||||
puzzle = result.getInt("fk_puzzle");
|
|
||||||
player = result.getInt("fk_player");
|
|
||||||
tries = result.getInt("tries");
|
|
||||||
score = result.getInt("score");
|
|
||||||
groups = result.getInt("id_group");
|
|
||||||
System.out.println(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,46 +0,0 @@
|
||||||
package dev.peerat.backend.routes;
|
|
||||||
|
|
||||||
import java.util.Base64;
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
|
|
||||||
import dev.peerat.backend.bonus.extract.RouteDoc;
|
|
||||||
import dev.peerat.backend.model.Badge;
|
|
||||||
import dev.peerat.backend.repository.DatabaseBadgeRepository;
|
|
||||||
import dev.peerat.backend.repository.DatabaseRepository;
|
|
||||||
import dev.peerat.framework.Context;
|
|
||||||
import dev.peerat.framework.HttpReader;
|
|
||||||
import dev.peerat.framework.HttpWriter;
|
|
||||||
import dev.peerat.framework.Response;
|
|
||||||
import dev.peerat.framework.Route;
|
|
||||||
import dev.peerat.framework.utils.json.JsonMap;
|
|
||||||
|
|
||||||
public class BadgeDetails implements Response {
|
|
||||||
|
|
||||||
private final DatabaseBadgeRepository databaseRepo;
|
|
||||||
|
|
||||||
public BadgeDetails(DatabaseRepository databaseRepo) {
|
|
||||||
this.databaseRepo = databaseRepo.getBadgeRepository();
|
|
||||||
}
|
|
||||||
|
|
||||||
@RouteDoc(path = "/badge/<id>", responseCode = 200, responseDescription = "JSON contenant les informations du badge")
|
|
||||||
@RouteDoc(responseCode = 400, responseDescription = "Aucun id donner")
|
|
||||||
|
|
||||||
@Route(path = "^\\/badge\\/([0-9]+)$", needLogin = true)
|
|
||||||
public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception {
|
|
||||||
if (matcher.groupCount() > 0) {
|
|
||||||
int badgeId = Integer.parseInt(matcher.group(1));
|
|
||||||
Badge badge = databaseRepo.getBadge(badgeId);
|
|
||||||
JsonMap badgeJSON = new JsonMap();
|
|
||||||
if(badge != null){
|
|
||||||
badgeJSON.set("name", badge.getName());
|
|
||||||
if(badge.getLogo() != null) badgeJSON.set("logo", Base64.getEncoder().encodeToString(badge.getLogo()));
|
|
||||||
badgeJSON.set("level", badge.getLevel());
|
|
||||||
}
|
|
||||||
context.response(200);
|
|
||||||
writer.write(badgeJSON.toString().replace("\\", ""));
|
|
||||||
} else {
|
|
||||||
context.response(400);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,68 +0,0 @@
|
||||||
package dev.peerat.backend.routes;
|
|
||||||
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
|
|
||||||
import dev.peerat.backend.bonus.extract.RouteDoc;
|
|
||||||
import dev.peerat.backend.model.Chapter;
|
|
||||||
import dev.peerat.backend.model.PeerAtUser;
|
|
||||||
import dev.peerat.backend.model.Puzzle;
|
|
||||||
import dev.peerat.backend.repository.DatabaseChapterRepository;
|
|
||||||
import dev.peerat.backend.repository.DatabaseCompletionRepository;
|
|
||||||
import dev.peerat.backend.repository.DatabaseGroupRepository;
|
|
||||||
import dev.peerat.backend.repository.DatabaseRepository;
|
|
||||||
import dev.peerat.framework.Context;
|
|
||||||
import dev.peerat.framework.HttpReader;
|
|
||||||
import dev.peerat.framework.HttpWriter;
|
|
||||||
import dev.peerat.framework.Response;
|
|
||||||
import dev.peerat.framework.Route;
|
|
||||||
import dev.peerat.framework.utils.json.JsonArray;
|
|
||||||
import dev.peerat.framework.utils.json.JsonMap;
|
|
||||||
|
|
||||||
public class ChapterElement implements Response {
|
|
||||||
|
|
||||||
private final DatabaseChapterRepository chapterRepo;
|
|
||||||
private final DatabaseCompletionRepository completionRepo;
|
|
||||||
|
|
||||||
public ChapterElement(DatabaseRepository repo) {
|
|
||||||
this.chapterRepo = repo.getChapterRepository();
|
|
||||||
this.completionRepo = repo.getCompletionRepository();
|
|
||||||
}
|
|
||||||
|
|
||||||
@RouteDoc(path = "/chapter/<id>", responseCode = 200, responseDescription = "JSON contenant les informations du chapitre demander")
|
|
||||||
@RouteDoc(responseCode = 400, responseDescription = "Aucun id donner")
|
|
||||||
|
|
||||||
@Route(path = "^\\/chapter\\/([0-9]+)$", needLogin = true)
|
|
||||||
public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
|
|
||||||
Chapter chapter = chapterRepo.getChapter(Integer.parseInt(matcher.group(1)));
|
|
||||||
if (chapter != null){
|
|
||||||
JsonMap chapterJSON = new JsonMap();
|
|
||||||
chapterJSON.set("id", chapter.getId());
|
|
||||||
chapterJSON.set("name", chapter.getName());
|
|
||||||
boolean show = chapter.hasStarted();
|
|
||||||
chapterJSON.set("show", show);
|
|
||||||
if(chapter.getStartDate() != null) chapterJSON.set("start", chapter.getStartDate().toString());
|
|
||||||
if(chapter.getEndDate() != null) chapterJSON.set("end", chapter.getEndDate().toString());
|
|
||||||
PeerAtUser user = context.getUser();
|
|
||||||
if(show){
|
|
||||||
JsonArray puzzles = new JsonArray();
|
|
||||||
for (Puzzle puzzle : chapter.getPuzzles()){
|
|
||||||
JsonMap puzzleJSON = new JsonMap();
|
|
||||||
puzzleJSON.set("id", puzzle.getId());
|
|
||||||
puzzleJSON.set("name", puzzle.getName());
|
|
||||||
puzzleJSON.set("scoreMax", puzzle.getScoreMax());
|
|
||||||
if (puzzle.getTags() != null) puzzleJSON.set("tags", puzzle.getJsonTags());
|
|
||||||
int score = this.completionRepo.getScore(user.getId(), puzzle.getId());
|
|
||||||
if(score >= 0) puzzleJSON.set("score", score);
|
|
||||||
puzzleJSON.set("show", puzzle.hasStarted());
|
|
||||||
puzzles.add(puzzleJSON);
|
|
||||||
}
|
|
||||||
chapterJSON.set("puzzles", puzzles);
|
|
||||||
}
|
|
||||||
context.response(200);
|
|
||||||
writer.write(chapterJSON.toString());
|
|
||||||
} else {
|
|
||||||
context.response(400);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,50 +0,0 @@
|
||||||
package dev.peerat.backend.routes;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
|
|
||||||
import dev.peerat.backend.bonus.extract.RouteDoc;
|
|
||||||
import dev.peerat.backend.model.Chapter;
|
|
||||||
import dev.peerat.backend.repository.DatabaseChapterRepository;
|
|
||||||
import dev.peerat.backend.repository.DatabaseRepository;
|
|
||||||
import dev.peerat.framework.Context;
|
|
||||||
import dev.peerat.framework.HttpReader;
|
|
||||||
import dev.peerat.framework.HttpWriter;
|
|
||||||
import dev.peerat.framework.Response;
|
|
||||||
import dev.peerat.framework.Route;
|
|
||||||
import dev.peerat.framework.utils.json.JsonArray;
|
|
||||||
import dev.peerat.framework.utils.json.JsonMap;
|
|
||||||
|
|
||||||
public class ChapterList implements Response {
|
|
||||||
|
|
||||||
private final DatabaseChapterRepository databaseRepo;
|
|
||||||
|
|
||||||
public ChapterList(DatabaseRepository databaseRepo) {
|
|
||||||
this.databaseRepo = databaseRepo.getChapterRepository();
|
|
||||||
}
|
|
||||||
|
|
||||||
@RouteDoc(path = "/chapters", responseCode = 200, responseDescription = "JSON contenant les informations des chapitres")
|
|
||||||
@RouteDoc(responseCode = 400, responseDescription = "Aucun chapitre trouver")
|
|
||||||
|
|
||||||
@Route(path = "^\\/chapters$", needLogin = true)
|
|
||||||
public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception {
|
|
||||||
List<Chapter> allChapters = databaseRepo.getAllChapters();
|
|
||||||
if (allChapters != null) {
|
|
||||||
JsonArray chaptersJSON = new JsonArray();
|
|
||||||
for (Chapter chapter : allChapters) {
|
|
||||||
JsonMap chapterJSON = new JsonMap();
|
|
||||||
chapterJSON.set("id", chapter.getId());
|
|
||||||
chapterJSON.set("name", chapter.getName());
|
|
||||||
chapterJSON.set("show", chapter.hasStarted());
|
|
||||||
if(chapter.getStartDate() != null) chapterJSON.set("start", chapter.getStartDate().toString());
|
|
||||||
if(chapter.getEndDate() != null) chapterJSON.set("end", chapter.getEndDate().toString());
|
|
||||||
chaptersJSON.add(chapterJSON);
|
|
||||||
}
|
|
||||||
context.response(200);
|
|
||||||
writer.write(chaptersJSON.toString());
|
|
||||||
} else {
|
|
||||||
context.response(400);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,51 +0,0 @@
|
||||||
package dev.peerat.backend.routes;
|
|
||||||
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
|
|
||||||
import dev.peerat.backend.bonus.extract.RouteDoc;
|
|
||||||
import dev.peerat.backend.model.Completion;
|
|
||||||
import dev.peerat.backend.repository.DatabaseRepository;
|
|
||||||
import dev.peerat.framework.Context;
|
|
||||||
import dev.peerat.framework.HttpReader;
|
|
||||||
import dev.peerat.framework.HttpWriter;
|
|
||||||
import dev.peerat.framework.Injection;
|
|
||||||
import dev.peerat.framework.Locker;
|
|
||||||
import dev.peerat.framework.Locker.Key;
|
|
||||||
import dev.peerat.framework.Route;
|
|
||||||
|
|
||||||
public class DynamicLeaderboard extends Leaderboard{
|
|
||||||
|
|
||||||
private Locker<Completion> locker;
|
|
||||||
|
|
||||||
public DynamicLeaderboard(DatabaseRepository databaseRepo, @Injection("leaderboard") Locker<Completion> locker){
|
|
||||||
super(databaseRepo);
|
|
||||||
this.locker = locker;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Locker<Completion> getLocker(){
|
|
||||||
return this.locker;
|
|
||||||
}
|
|
||||||
|
|
||||||
@RouteDoc(path = "/rleaderboard/{id}", responseCode = 101, responseDescription = "WebSocket")
|
|
||||||
|
|
||||||
@Route(path = "^\\/rleaderboard\\/?(\\d+)?$", websocket = true)
|
|
||||||
public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
|
|
||||||
Key key = new Key();
|
|
||||||
|
|
||||||
locker.init(key);
|
|
||||||
try {
|
|
||||||
while(!reader.isClosed()){
|
|
||||||
locker.getValue(key);
|
|
||||||
if(matcher.group(1) != null){
|
|
||||||
groupsLeaderboard(Integer.parseInt(matcher.group(1)), writer);
|
|
||||||
}else{
|
|
||||||
playersLeaderboard(writer);
|
|
||||||
}
|
|
||||||
locker.lock(key);
|
|
||||||
}
|
|
||||||
}catch(Exception e){
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
locker.remove(key);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,65 +0,0 @@
|
||||||
package dev.peerat.backend.routes;
|
|
||||||
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
|
|
||||||
import dev.peerat.framework.Context;
|
|
||||||
import dev.peerat.framework.HttpReader;
|
|
||||||
import dev.peerat.framework.HttpWriter;
|
|
||||||
import dev.peerat.framework.Injection;
|
|
||||||
import dev.peerat.framework.Locker;
|
|
||||||
import dev.peerat.framework.Locker.Key;
|
|
||||||
import dev.peerat.framework.Route;
|
|
||||||
import dev.peerat.framework.utils.json.JsonMap;
|
|
||||||
|
|
||||||
public class EventSSE{
|
|
||||||
|
|
||||||
private Locker<GroupMessage> locker;
|
|
||||||
|
|
||||||
public EventSSE(@Injection("groupMessages") Locker<GroupMessage> locker){
|
|
||||||
this.locker = locker;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Route(path = "^/group/event/$", websocket = true)
|
|
||||||
public void connect(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception {
|
|
||||||
String group = reader.<JsonMap>readJson().get("group");
|
|
||||||
|
|
||||||
Key key = new Key();
|
|
||||||
|
|
||||||
locker.init(key);
|
|
||||||
try {
|
|
||||||
while(true){
|
|
||||||
locker.lock(key);
|
|
||||||
GroupMessage message = locker.getValue(key);
|
|
||||||
if(message.getGroup() == null || message.getGroup().equals(group)){
|
|
||||||
JsonMap send = new JsonMap();
|
|
||||||
send.set("message", message.getMessage());
|
|
||||||
writer.write(send.toString()+"\n");
|
|
||||||
writer.flush();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}catch(Exception e){
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
locker.remove(key);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static class GroupMessage{
|
|
||||||
|
|
||||||
private String group;
|
|
||||||
private String message;
|
|
||||||
|
|
||||||
public GroupMessage(String group, String message){
|
|
||||||
this.group = group;
|
|
||||||
this.message = message;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getGroup(){
|
|
||||||
return this.group;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getMessage(){
|
|
||||||
return this.message;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,91 +0,0 @@
|
||||||
package dev.peerat.backend.routes;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.SortedSet;
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
|
|
||||||
import dev.peerat.backend.bonus.extract.RouteDoc;
|
|
||||||
import dev.peerat.backend.model.Chapter;
|
|
||||||
import dev.peerat.backend.model.Group;
|
|
||||||
import dev.peerat.backend.model.Player;
|
|
||||||
import dev.peerat.backend.repository.DatabaseRepository;
|
|
||||||
import dev.peerat.framework.Context;
|
|
||||||
import dev.peerat.framework.HttpReader;
|
|
||||||
import dev.peerat.framework.HttpWriter;
|
|
||||||
import dev.peerat.framework.Response;
|
|
||||||
import dev.peerat.framework.Route;
|
|
||||||
import dev.peerat.framework.utils.json.JsonArray;
|
|
||||||
import dev.peerat.framework.utils.json.JsonMap;
|
|
||||||
|
|
||||||
public class Leaderboard implements Response {
|
|
||||||
|
|
||||||
private final DatabaseRepository databaseRepo;
|
|
||||||
|
|
||||||
public Leaderboard(DatabaseRepository databaseRepo) {
|
|
||||||
this.databaseRepo = databaseRepo;
|
|
||||||
}
|
|
||||||
|
|
||||||
@RouteDoc(path = "/leaderboard/{id}", responseCode = 200, responseDescription = "JSON contenant le leaderboard")
|
|
||||||
|
|
||||||
@Route(path = "^\\/leaderboard\\/?(\\d+)?$")
|
|
||||||
public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception {
|
|
||||||
context.response(200);
|
|
||||||
if (matcher.group(1) != null) {
|
|
||||||
groupsLeaderboard(Integer.parseInt(matcher.group(1)), writer);
|
|
||||||
} else {
|
|
||||||
playersLeaderboard(writer);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public final void groupsLeaderboard(int chapterId, HttpWriter writer) throws IOException {
|
|
||||||
Chapter chInfo = databaseRepo.getChapterRepository().getChapter(chapterId);
|
|
||||||
|
|
||||||
SortedSet<Group> allGroupsForChapter = databaseRepo.getLeaderboardRepository().getAllGroupForChapterLeaderboard(chapterId);
|
|
||||||
JsonMap leaderboardJSON = new JsonMap();
|
|
||||||
if (chInfo.getStartDate() != null)
|
|
||||||
leaderboardJSON.set("start_date", chInfo.getStartDate().toString());
|
|
||||||
if (chInfo.getEndDate() != null)
|
|
||||||
leaderboardJSON.set("end_date", chInfo.getEndDate().toString());
|
|
||||||
JsonArray groupsJSON = new JsonArray();
|
|
||||||
if (allGroupsForChapter != null) {
|
|
||||||
int rank = 1;
|
|
||||||
int sameRankCount = 1;
|
|
||||||
Group previousGroup = null;
|
|
||||||
for (Group g : allGroupsForChapter) {
|
|
||||||
if (previousGroup != null) {
|
|
||||||
if (g.compareTo(previousGroup) == 0) {
|
|
||||||
sameRankCount++;
|
|
||||||
} else {
|
|
||||||
rank = rank + sameRankCount;
|
|
||||||
sameRankCount = 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
groupsJSON.add(g.toJson(rank));
|
|
||||||
previousGroup = g;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
leaderboardJSON.set("groups", groupsJSON);
|
|
||||||
writer.write(leaderboardJSON.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
public final void playersLeaderboard(HttpWriter writer) throws IOException {
|
|
||||||
SortedSet<Player> allPlayers = databaseRepo.getLeaderboardRepository().getAllPlayerForLeaderboard();
|
|
||||||
JsonArray playersJSON = new JsonArray();
|
|
||||||
if (allPlayers != null) {
|
|
||||||
for (Player player : allPlayers) {
|
|
||||||
JsonMap playerJSON = new JsonMap();
|
|
||||||
playerJSON.set("pseudo", player.getPseudo());
|
|
||||||
if (player.getGroups() != null)
|
|
||||||
playerJSON.set("groups", player.getJsonGroups());
|
|
||||||
// if (player.getAvatar() != null)
|
|
||||||
// playerJSON.put("avatar", Base64.getEncoder().encodeToString(player.getAvatar()));
|
|
||||||
playerJSON.set("rank", player.getRank());
|
|
||||||
playerJSON.set("score", player.getTotalScore());
|
|
||||||
playerJSON.set("completions", player.getTotalCompletion());
|
|
||||||
playerJSON.set("tries", player.getTotalTries());
|
|
||||||
playersJSON.add(playerJSON);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
writer.write(playersJSON.toString());
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,62 +0,0 @@
|
||||||
package dev.peerat.backend.routes;
|
|
||||||
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
|
|
||||||
import dev.peerat.backend.bonus.extract.RouteDoc;
|
|
||||||
import dev.peerat.backend.model.PeerAtUser;
|
|
||||||
import dev.peerat.backend.model.Player;
|
|
||||||
import dev.peerat.backend.repository.DatabasePlayerRepository;
|
|
||||||
import dev.peerat.backend.repository.DatabaseRepository;
|
|
||||||
import dev.peerat.framework.Context;
|
|
||||||
import dev.peerat.framework.HttpReader;
|
|
||||||
import dev.peerat.framework.HttpWriter;
|
|
||||||
import dev.peerat.framework.Response;
|
|
||||||
import dev.peerat.framework.Route;
|
|
||||||
import dev.peerat.framework.utils.json.JsonMap;
|
|
||||||
|
|
||||||
public class PlayerDetails implements Response {
|
|
||||||
|
|
||||||
private final DatabasePlayerRepository databaseRepo;
|
|
||||||
|
|
||||||
public PlayerDetails(DatabaseRepository databaseRepo) {
|
|
||||||
this.databaseRepo = databaseRepo.getPlayerRepository();
|
|
||||||
}
|
|
||||||
|
|
||||||
@RouteDoc(path = "/player/{id}", responseCode = 200, responseDescription = "JSON contenant les informations de l'utilisateur")
|
|
||||||
@RouteDoc(responseCode = 400, responseDescription = "Utilisateur introuvable dans la base de donnée")
|
|
||||||
|
|
||||||
@Route(path = "^\\/player\\/?(.+)?$", needLogin = true)
|
|
||||||
public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception {
|
|
||||||
Player player;
|
|
||||||
if (matcher.group(1) != null) {
|
|
||||||
player = databaseRepo.getPlayerDetails(matcher.group(1));
|
|
||||||
} else {
|
|
||||||
PeerAtUser user = context.getUser();
|
|
||||||
player = databaseRepo.getPlayerDetails(user.getId());
|
|
||||||
}
|
|
||||||
JsonMap playerJSON = new JsonMap();
|
|
||||||
if (player != null) {
|
|
||||||
playerJSON.set("pseudo", player.getPseudo());
|
|
||||||
playerJSON.set("email", player.getEmail());
|
|
||||||
playerJSON.set("firstname", player.getFirstname());
|
|
||||||
playerJSON.set("lastname", player.getLastname());
|
|
||||||
playerJSON.set("description", player.getDescription());
|
|
||||||
if (player.getGroups() != null)
|
|
||||||
playerJSON.set("groups", player.getJsonGroups());
|
|
||||||
playerJSON.set("rank", player.getRank());
|
|
||||||
playerJSON.set("score", player.getTotalScore());
|
|
||||||
playerJSON.set("completions", player.getTotalCompletion());
|
|
||||||
playerJSON.set("completionsList", player.getJsonCompletions());
|
|
||||||
playerJSON.set("tries", player.getTotalTries());
|
|
||||||
if (player.getBadges() != null)
|
|
||||||
playerJSON.set("badges", player.getJsonBadges());
|
|
||||||
// if (player.getAvatar() != null)
|
|
||||||
// playerJSON.set("avatar", Base64.getEncoder().encodeToString(player.getAvatar()));
|
|
||||||
context.response(200);
|
|
||||||
writer.write(playerJSON.toString());
|
|
||||||
} else {
|
|
||||||
context.response(400);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,77 +0,0 @@
|
||||||
package dev.peerat.backend.routes;
|
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.util.function.Predicate;
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
|
|
||||||
import dev.peerat.backend.bonus.extract.RouteDoc;
|
|
||||||
import dev.peerat.backend.model.Chapter;
|
|
||||||
import dev.peerat.backend.model.Completion;
|
|
||||||
import dev.peerat.backend.model.PeerAtUser;
|
|
||||||
import dev.peerat.backend.model.Puzzle;
|
|
||||||
import dev.peerat.backend.repository.DatabaseRepository;
|
|
||||||
import dev.peerat.framework.Context;
|
|
||||||
import dev.peerat.framework.HttpReader;
|
|
||||||
import dev.peerat.framework.HttpWriter;
|
|
||||||
import dev.peerat.framework.Response;
|
|
||||||
import dev.peerat.framework.Route;
|
|
||||||
import dev.peerat.framework.utils.json.JsonMap;
|
|
||||||
|
|
||||||
public class PuzzleElement implements Response {
|
|
||||||
|
|
||||||
private final DatabaseRepository databaseRepo;
|
|
||||||
private Predicate<PeerAtUser> isAdmin;
|
|
||||||
|
|
||||||
public PuzzleElement(DatabaseRepository databaseRepo, Predicate<PeerAtUser> isAdmin){
|
|
||||||
this.databaseRepo = databaseRepo;
|
|
||||||
this.isAdmin = isAdmin;
|
|
||||||
}
|
|
||||||
|
|
||||||
@RouteDoc(path = "/puzzle/<id>", responseCode = 200, responseDescription = "JSON contenant les informations du puzzle")
|
|
||||||
@RouteDoc(responseCode = 400, responseDescription = "puzzle introuvable dans la base de donnée")
|
|
||||||
@RouteDoc(responseCode = 423, responseDescription = "L'utilisateur essaye de voir le puzzle en dehors de l'event")
|
|
||||||
|
|
||||||
@Route(path = "^\\/puzzle\\/([0-9]+)$", needLogin = true)
|
|
||||||
public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception {
|
|
||||||
Puzzle puzzle = databaseRepo.getPuzzleRepository().getPuzzle(extractId(matcher));
|
|
||||||
if (puzzle != null){
|
|
||||||
Chapter chapter = this.databaseRepo.getChapterRepository().getChapter(puzzle);
|
|
||||||
if(chapter.getStartDate() != null && !isAdmin.test(context.getUser())){
|
|
||||||
if(LocalDateTime.now().isBefore(chapter.getStartDate().toLocalDateTime())){
|
|
||||||
context.response(423);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// if(chapter.getEndDate() != null){
|
|
||||||
// if(LocalDateTime.now().isAfter(chapter.getEndDate().toLocalDateTime())){
|
|
||||||
// writer.response(423, "Access-Control-Allow-Origin: *");
|
|
||||||
// return;
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
PeerAtUser user = context.getUser();
|
|
||||||
|
|
||||||
JsonMap puzzleJSON = new JsonMap();
|
|
||||||
puzzleJSON.set("id", puzzle.getId());
|
|
||||||
puzzleJSON.set("name", puzzle.getName());
|
|
||||||
puzzleJSON.set("content", puzzle.getContent());
|
|
||||||
puzzleJSON.set("scoreMax", puzzle.getScoreMax());
|
|
||||||
if(puzzle.getTags() != null) puzzleJSON.set("tags", puzzle.getJsonTags());
|
|
||||||
Completion completion = this.databaseRepo.getCompletionRepository().getCompletionGroup(user.getId(), puzzle.getId());
|
|
||||||
if(completion != null && completion.getScore() >= 0){
|
|
||||||
puzzleJSON.set("score", completion.getScore());
|
|
||||||
puzzleJSON.set("tries", completion.getTries());
|
|
||||||
}
|
|
||||||
if(puzzle.getDepend() > 0) puzzleJSON.set("depend", puzzle.getDepend());
|
|
||||||
context.response(200, "Content-Type: application/json");
|
|
||||||
writer.write(puzzleJSON.toString());
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
context.response(400);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private int extractId(Matcher matcher) {
|
|
||||||
return Integer.parseInt(matcher.group(1));
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,172 +0,0 @@
|
||||||
package dev.peerat.backend.routes;
|
|
||||||
|
|
||||||
import static dev.peerat.framework.RequestType.POST;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.nio.file.Paths;
|
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.function.Predicate;
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
|
|
||||||
import dev.peerat.backend.Configuration;
|
|
||||||
import dev.peerat.backend.bonus.extract.RouteDoc;
|
|
||||||
import dev.peerat.backend.model.Chapter;
|
|
||||||
import dev.peerat.backend.model.Completion;
|
|
||||||
import dev.peerat.backend.model.Group;
|
|
||||||
import dev.peerat.backend.model.PeerAtUser;
|
|
||||||
import dev.peerat.backend.model.Player;
|
|
||||||
import dev.peerat.backend.model.Puzzle;
|
|
||||||
import dev.peerat.backend.repository.DatabaseRepository;
|
|
||||||
import dev.peerat.framework.Context;
|
|
||||||
import dev.peerat.framework.HttpReader;
|
|
||||||
import dev.peerat.framework.HttpWriter;
|
|
||||||
import dev.peerat.framework.Injection;
|
|
||||||
import dev.peerat.framework.Locker;
|
|
||||||
import dev.peerat.framework.Response;
|
|
||||||
import dev.peerat.framework.Route;
|
|
||||||
import dev.peerat.framework.utils.json.JsonMap;
|
|
||||||
|
|
||||||
public class PuzzleResponse implements Response {
|
|
||||||
private final DatabaseRepository databaseRepo;
|
|
||||||
private final String usersFilesPath;
|
|
||||||
|
|
||||||
private final Locker<Completion> leaderboard;
|
|
||||||
private Predicate<PeerAtUser> isAdmin;
|
|
||||||
|
|
||||||
public PuzzleResponse(DatabaseRepository databaseRepo, Configuration config, @Injection("leaderboard") Locker<Completion> locker, Predicate<PeerAtUser> isAdmin){
|
|
||||||
this.databaseRepo = databaseRepo;
|
|
||||||
usersFilesPath = config.getUsersFiles();
|
|
||||||
this.leaderboard = locker;
|
|
||||||
this.isAdmin = isAdmin;
|
|
||||||
}
|
|
||||||
|
|
||||||
@RouteDoc(path = "/puzzleResponse/<id>", responseCode = 200, responseDescription = "Bonne réponse, json contenant les points + tries")
|
|
||||||
@RouteDoc(responseCode = 400, responseDescription = "Pas de réponse")
|
|
||||||
@RouteDoc(responseCode = 403, responseDescription = "Déjà répondu")
|
|
||||||
@RouteDoc(responseCode = 406, responseDescription = "Mauvaise réponse")
|
|
||||||
@RouteDoc(responseCode = 423, responseDescription = "L'utilisateur essaye de répondre en dehors de l'event")
|
|
||||||
|
|
||||||
@Route(path = "^\\/puzzleResponse\\/([0-9]+)$", type = POST, needLogin = true)
|
|
||||||
public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
|
|
||||||
ReceivedResponse received = new ReceivedResponse(matcher, reader);
|
|
||||||
if (received.getResponse() == null){
|
|
||||||
context.response(400);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
PeerAtUser user = context.getUser();
|
|
||||||
|
|
||||||
//saveSourceCode(received, databaseRepo.getPlayer(user.getId()));
|
|
||||||
JsonMap responseJSON = new JsonMap();
|
|
||||||
if(this.databaseRepo.getCompletionRepository().getScore(user.getId(), received.getPuzzleId()) > 0){
|
|
||||||
context.response(403);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
Puzzle currentPuzzle = databaseRepo.getPuzzleRepository().getPuzzle(received.getPuzzleId());
|
|
||||||
if(!currentPuzzle.hasStarted()){
|
|
||||||
context.response(423);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
Chapter chapter = this.databaseRepo.getChapterRepository().getChapter(currentPuzzle);
|
|
||||||
if(!chapter.hasStarted()){
|
|
||||||
context.response(423);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if(chapter.getEndDate() != null && !isAdmin.test(context.getUser())){
|
|
||||||
if(LocalDateTime.now().isAfter(chapter.getEndDate().toLocalDateTime())){
|
|
||||||
if(Arrays.equals(currentPuzzle.getSoluce(), received.getResponse())){
|
|
||||||
context.response(200, "Content-Type: application/json");
|
|
||||||
JsonMap theoSaisPasJusteRecevoir200 = new JsonMap();
|
|
||||||
theoSaisPasJusteRecevoir200.set("success", true);
|
|
||||||
writer.write(theoSaisPasJusteRecevoir200.toString());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
context.response(423);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Group group = this.databaseRepo.getGroupRepository().getPlayerGroup(user.getId(), chapter.getId());
|
|
||||||
if(group == null){
|
|
||||||
context.response(423);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
Completion completion = databaseRepo.getCompletionRepository().insertOrUpdatePuzzleResponse(received.getPuzzleId(), user.getId(),
|
|
||||||
received.getFileName(), received.getSourceCode(), received.getResponse(), currentPuzzle);
|
|
||||||
if(completion == null){
|
|
||||||
context.response(400);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if(completion.getScore() > 0){
|
|
||||||
context.response(200, "Content-Type: application/json");
|
|
||||||
responseJSON.set("score", completion.getScore());
|
|
||||||
responseJSON.set("tries", completion.getTries());
|
|
||||||
|
|
||||||
}else{
|
|
||||||
context.response(406, "Content-Type: application/json");
|
|
||||||
responseJSON.set("tries", completion.getTries());
|
|
||||||
}
|
|
||||||
writer.write(responseJSON.toString());
|
|
||||||
writer.flush();
|
|
||||||
|
|
||||||
leaderboard.setValue(completion);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void saveSourceCode(ReceivedResponse received, Player player){
|
|
||||||
try{
|
|
||||||
Path path = Paths.get(String.format("%s/%s/puz%04d-%s", usersFilesPath, player.getPseudo(),
|
|
||||||
received.getPuzzleId(), received.getFileName()));
|
|
||||||
Files.write(path, received.getSourceCode());
|
|
||||||
}catch (IOException e){
|
|
||||||
System.err.println("ERREUR D'ENREGISTREMENT DU CODE POUR PUZZLE_RESPONSE : " + e.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
class ReceivedResponse {
|
|
||||||
|
|
||||||
private int puzzleId;
|
|
||||||
private byte[] response;
|
|
||||||
private String fileName;
|
|
||||||
private byte[] sourceCode;
|
|
||||||
|
|
||||||
public ReceivedResponse(Matcher matcher, HttpReader reader) throws Exception {
|
|
||||||
puzzleId = Integer.parseInt(matcher.group(1));
|
|
||||||
|
|
||||||
List<String> multiPartData = reader.readMultiPartData();
|
|
||||||
if (multiPartData != null && multiPartData.size() > 0){
|
|
||||||
this.response = multiPartData.get(0).getBytes();
|
|
||||||
System.out.println("Puzzle response:");
|
|
||||||
System.out.println(Arrays.toString(response));
|
|
||||||
System.out.println(new String(response));
|
|
||||||
if (multiPartData.size() == 3) {
|
|
||||||
this.fileName = multiPartData.get(1);
|
|
||||||
this.sourceCode = multiPartData.get(2).getBytes();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getPuzzleId() {
|
|
||||||
return puzzleId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public byte[] getResponse() {
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getFileName() {
|
|
||||||
return fileName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public byte[] getSourceCode() {
|
|
||||||
return sourceCode;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,41 +0,0 @@
|
||||||
package dev.peerat.backend.routes;
|
|
||||||
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
|
|
||||||
import dev.peerat.backend.bonus.extract.RouteDoc;
|
|
||||||
import dev.peerat.backend.model.PeerAtUser;
|
|
||||||
import dev.peerat.backend.repository.DatabaseCompletionRepository;
|
|
||||||
import dev.peerat.backend.repository.DatabaseRepository;
|
|
||||||
import dev.peerat.framework.Context;
|
|
||||||
import dev.peerat.framework.HttpReader;
|
|
||||||
import dev.peerat.framework.HttpWriter;
|
|
||||||
import dev.peerat.framework.Response;
|
|
||||||
import dev.peerat.framework.Route;
|
|
||||||
|
|
||||||
public class Result implements Response {
|
|
||||||
|
|
||||||
private DatabaseCompletionRepository repo;
|
|
||||||
|
|
||||||
public Result(DatabaseRepository repo) {
|
|
||||||
this.repo = repo.getCompletionRepository();
|
|
||||||
}
|
|
||||||
|
|
||||||
@RouteDoc(path = "/result/<id>", responseCode = 200, responseDescription = "Le score")
|
|
||||||
@RouteDoc(responseCode = 425, responseDescription = "Puzzle pas compléter")
|
|
||||||
|
|
||||||
@Route(path = "^\\/result\\/(\\d+)$", needLogin = true)
|
|
||||||
public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception {
|
|
||||||
int puzzle = Integer.parseInt(matcher.group(1));
|
|
||||||
|
|
||||||
PeerAtUser user = context.getUser();
|
|
||||||
|
|
||||||
int score = this.repo.getScore(user.getId(), puzzle);
|
|
||||||
if (score < 0) {
|
|
||||||
context.response(425);
|
|
||||||
} else {
|
|
||||||
context.response(200);
|
|
||||||
writer.write(score + "");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,35 +0,0 @@
|
||||||
package dev.peerat.backend.routes;
|
|
||||||
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
|
|
||||||
import dev.peerat.backend.Configuration;
|
|
||||||
import dev.peerat.backend.bonus.extract.RouteExtracter;
|
|
||||||
import dev.peerat.framework.Context;
|
|
||||||
import dev.peerat.framework.HttpReader;
|
|
||||||
import dev.peerat.framework.HttpWriter;
|
|
||||||
import dev.peerat.framework.Injection;
|
|
||||||
import dev.peerat.framework.Response;
|
|
||||||
import dev.peerat.framework.Route;
|
|
||||||
|
|
||||||
public class Swagger implements Response{
|
|
||||||
|
|
||||||
private String json;
|
|
||||||
|
|
||||||
public Swagger(RouteExtracter extracter, Configuration config){
|
|
||||||
try{
|
|
||||||
// this.json = extracter.swagger(config.getTokenIssuer()).toString();
|
|
||||||
}catch(Exception e){
|
|
||||||
e.printStackTrace();
|
|
||||||
json = "{}";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Route(path = "^/swagger$")
|
|
||||||
public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception {
|
|
||||||
context.response(200);
|
|
||||||
writer.write(json);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,70 +0,0 @@
|
||||||
package dev.peerat.backend.routes.admins;
|
|
||||||
|
|
||||||
import static dev.peerat.framework.RequestType.DELETE;
|
|
||||||
import static dev.peerat.framework.RequestType.POST;
|
|
||||||
import static dev.peerat.framework.RequestType.PUT;
|
|
||||||
|
|
||||||
import java.sql.Timestamp;
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
|
|
||||||
import dev.peerat.backend.model.Chapter;
|
|
||||||
import dev.peerat.backend.repository.DatabaseAdminRepository;
|
|
||||||
import dev.peerat.backend.repository.DatabaseRepository;
|
|
||||||
import dev.peerat.framework.Context;
|
|
||||||
import dev.peerat.framework.HttpReader;
|
|
||||||
import dev.peerat.framework.HttpWriter;
|
|
||||||
import dev.peerat.framework.Route;
|
|
||||||
import dev.peerat.framework.utils.json.JsonMap;
|
|
||||||
|
|
||||||
public class ChapterController{
|
|
||||||
|
|
||||||
private DatabaseAdminRepository repo;
|
|
||||||
|
|
||||||
public ChapterController(DatabaseRepository repo){
|
|
||||||
this.repo = repo.getAdminRepository();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Route(path = "^/admin/chapter/$", type = POST, needLogin = true)
|
|
||||||
public void add(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
|
|
||||||
JsonMap json = reader.readJson();
|
|
||||||
Chapter chapter = new Chapter(-1, json.get("name"), Timestamp.valueOf(json.<String>get("start")), Timestamp.valueOf(json.<String>get("end")));
|
|
||||||
if(repo.adminAddChapter(chapter)){
|
|
||||||
context.response(200);
|
|
||||||
}else{
|
|
||||||
context.response(501);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Route(path = "^/admin/chapter/(\\d+)$", type = DELETE, needLogin = true)
|
|
||||||
public void delte(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
|
|
||||||
if(this.repo.adminDeleteChapter(Integer.parseInt(matcher.group(1)))){
|
|
||||||
context.response(200);
|
|
||||||
}else{
|
|
||||||
context.response(501);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Route(path = "^/admin/chapter/(\\d+)$", type = PUT, needLogin = true)
|
|
||||||
public void edit(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
|
|
||||||
JsonMap json = reader.readJson();
|
|
||||||
Chapter chapter = new Chapter(-1, json.get("name"), Timestamp.valueOf(json.<String>get("start")), Timestamp.valueOf(json.<String>get("end")));
|
|
||||||
if(repo.adminUpdateChapter(Integer.parseInt(matcher.group(1)), chapter)){
|
|
||||||
context.response(200);
|
|
||||||
}else{
|
|
||||||
context.response(501);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Route(path = "^/admin/chapter/(\\d+)$", needLogin = true)
|
|
||||||
public void get(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
|
|
||||||
Chapter chapter = this.repo.getAdminChapter(Integer.parseInt(matcher.group(1)));
|
|
||||||
JsonMap json = new JsonMap();
|
|
||||||
json.set("name", chapter.getName());
|
|
||||||
json.set("start", chapter.getStartDate());
|
|
||||||
json.set("end", chapter.getEndDate());
|
|
||||||
|
|
||||||
context.response(200);
|
|
||||||
writer.write(json.toString()+"\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,32 +0,0 @@
|
||||||
package dev.peerat.backend.routes.admins;
|
|
||||||
|
|
||||||
import dev.peerat.backend.routes.EventSSE.GroupMessage;
|
|
||||||
import dev.peerat.framework.Context;
|
|
||||||
import dev.peerat.framework.HttpReader;
|
|
||||||
import dev.peerat.framework.Injection;
|
|
||||||
import dev.peerat.framework.Locker;
|
|
||||||
import dev.peerat.framework.RequestType;
|
|
||||||
import dev.peerat.framework.Route;
|
|
||||||
import dev.peerat.framework.utils.json.JsonMap;
|
|
||||||
|
|
||||||
public class GroupController {
|
|
||||||
|
|
||||||
private Locker<GroupMessage> locker;
|
|
||||||
|
|
||||||
public GroupController(@Injection("groupMessages") Locker<GroupMessage> locker){
|
|
||||||
this.locker = locker;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Route(path = "^/admin/event/$", type = RequestType.POST ,needLogin = true)
|
|
||||||
public void send(Context context, HttpReader reader) throws Exception{
|
|
||||||
JsonMap json = reader.readJson();
|
|
||||||
if(!json.has("message")){
|
|
||||||
context.response(400);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
locker.setValue(new GroupMessage(json.get("group"), json.get("message")));
|
|
||||||
context.response(200);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,78 +0,0 @@
|
||||||
package dev.peerat.backend.routes.admins;
|
|
||||||
|
|
||||||
import java.util.function.BiConsumer;
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
|
|
||||||
import dev.peerat.backend.bonus.extract.RouteDoc;
|
|
||||||
import dev.peerat.backend.model.PeerAtUser;
|
|
||||||
import dev.peerat.backend.repository.DatabaseAdminRepository;
|
|
||||||
import dev.peerat.backend.repository.DatabasePlayerRepository;
|
|
||||||
import dev.peerat.backend.repository.DatabaseRepository;
|
|
||||||
import dev.peerat.framework.Context;
|
|
||||||
import dev.peerat.framework.HttpReader;
|
|
||||||
import dev.peerat.framework.HttpWriter;
|
|
||||||
import dev.peerat.framework.Locker;
|
|
||||||
import dev.peerat.framework.Locker.Key;
|
|
||||||
import dev.peerat.framework.Route;
|
|
||||||
import dev.peerat.framework.Router;
|
|
||||||
import dev.peerat.framework.utils.json.JsonArray;
|
|
||||||
import dev.peerat.framework.utils.json.JsonMap;
|
|
||||||
|
|
||||||
public class LogController {
|
|
||||||
|
|
||||||
private Locker<Context> contextLocker;
|
|
||||||
private Locker<Throwable> exceptionLocker;
|
|
||||||
private DatabaseAdminRepository repo;
|
|
||||||
private DatabasePlayerRepository playerRepo;
|
|
||||||
|
|
||||||
public LogController(Router<PeerAtUser> router, DatabaseRepository repo){
|
|
||||||
this.contextLocker = router.getLogger();
|
|
||||||
this.exceptionLocker = router.getExceptionLogger();
|
|
||||||
this.repo = repo.getAdminRepository();
|
|
||||||
this.playerRepo = repo.getPlayerRepository();
|
|
||||||
}
|
|
||||||
|
|
||||||
@RouteDoc(path = "/admin/logs", responseCode = 200, responseDescription = "L'utilisateur peux voir les logs en directe")
|
|
||||||
@RouteDoc(responseCode = 401, responseDescription = "L'utilisateur n'a pas accès à cette ressource")
|
|
||||||
|
|
||||||
@Route(path = "^/admin/logs$", needLogin = true, websocket = true)
|
|
||||||
public void logs(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
|
|
||||||
log(reader, writer, this.contextLocker, (json, instance) -> {
|
|
||||||
json.set("logged", instance.isLogged());
|
|
||||||
if(instance.isLogged()) json.set("pseudo", playerRepo.getPlayer(instance.<PeerAtUser>getUser().getId()).getPseudo());
|
|
||||||
json.set("path", instance.getPath());
|
|
||||||
json.set("type", instance.getType().toString());
|
|
||||||
json.set("code", instance.getResponseCode());
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@Route(path = "^/admin/exceptions$", needLogin = true, websocket = true)
|
|
||||||
public void exceptions(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
|
|
||||||
log(reader, writer, this.exceptionLocker, (json, exception) -> {
|
|
||||||
json.set("type", exception.getClass().getSimpleName());
|
|
||||||
json.set("message", exception.getMessage());
|
|
||||||
JsonArray trace = new JsonArray();
|
|
||||||
for(StackTraceElement element : exception.getStackTrace()) trace.add(element.toString());
|
|
||||||
json.set("trace", trace);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public <T> void log(HttpReader reader, HttpWriter writer, Locker<T> locker, BiConsumer<JsonMap, T> consumer){
|
|
||||||
Key key = new Key();
|
|
||||||
|
|
||||||
locker.init(key);
|
|
||||||
try {
|
|
||||||
while(!reader.isClosed()){
|
|
||||||
locker.lock(key);
|
|
||||||
T instance = locker.getValue(key);
|
|
||||||
JsonMap json = new JsonMap();
|
|
||||||
consumer.accept(json, instance);
|
|
||||||
|
|
||||||
writer.write(json.toString());
|
|
||||||
writer.flush();
|
|
||||||
}
|
|
||||||
}catch(Exception e){}
|
|
||||||
locker.remove(key);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,89 +0,0 @@
|
||||||
package dev.peerat.backend.routes.admins;
|
|
||||||
|
|
||||||
import static dev.peerat.framework.RequestType.DELETE;
|
|
||||||
import static dev.peerat.framework.RequestType.POST;
|
|
||||||
import static dev.peerat.framework.RequestType.PUT;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
|
|
||||||
import dev.peerat.backend.model.Puzzle;
|
|
||||||
import dev.peerat.backend.repository.DatabaseAdminRepository;
|
|
||||||
import dev.peerat.backend.repository.DatabaseRepository;
|
|
||||||
import dev.peerat.framework.Context;
|
|
||||||
import dev.peerat.framework.HttpReader;
|
|
||||||
import dev.peerat.framework.HttpWriter;
|
|
||||||
import dev.peerat.framework.Route;
|
|
||||||
import dev.peerat.framework.utils.json.JsonArray;
|
|
||||||
import dev.peerat.framework.utils.json.JsonMap;
|
|
||||||
|
|
||||||
public class PuzzleController {
|
|
||||||
|
|
||||||
private DatabaseAdminRepository repo;
|
|
||||||
|
|
||||||
public PuzzleController(DatabaseRepository repo){
|
|
||||||
this.repo = repo.getAdminRepository();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Route(path = "^/admin/puzzle/$", type = POST, needLogin = true)
|
|
||||||
public void add(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
|
|
||||||
JsonMap json = reader.readJson();
|
|
||||||
Puzzle puzzle = new Puzzle(-1, json.get("name"), json.get("content"), json.<String>get("soluce").getBytes(), null, json.<Long>get("scoreMax").intValue(), null, -1, null);
|
|
||||||
if(repo.adminAddPuzzle(puzzle, json.<Long>get("chapter").intValue())){
|
|
||||||
context.response(200);
|
|
||||||
}else{
|
|
||||||
context.response(501);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Route(path = "^/admin/puzzle/(\\d+)$", type = DELETE, needLogin = true)
|
|
||||||
public void delete(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
|
|
||||||
if(this.repo.adminDeletePuzzle(Integer.parseInt(matcher.group(1)))){
|
|
||||||
context.response(200);
|
|
||||||
}else{
|
|
||||||
context.response(501);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@Route(path = "^/admin/puzzle/(\\d+)$", type = PUT, needLogin = true)
|
|
||||||
public void edit(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
|
|
||||||
JsonMap json = reader.readJson();
|
|
||||||
Puzzle puzzle = new Puzzle(-1, json.get("name"), json.get("content"), json.<String>get("soluce").getBytes(), null, json.<Long>get("scoreMax").intValue(), null, -1, null);
|
|
||||||
if(repo.adminUpdatePuzzle(Integer.parseInt(matcher.group(1)), puzzle, json.<Long>get("chapter").intValue())){
|
|
||||||
context.response(200);
|
|
||||||
}else{
|
|
||||||
context.response(501);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Route(path = "^/admin/puzzle/(\\d+)$", needLogin = true)
|
|
||||||
public void get(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
|
|
||||||
Puzzle puzzle = this.repo.getAdminPuzzle(Integer.parseInt(matcher.group(1)));
|
|
||||||
JsonMap json = new JsonMap();
|
|
||||||
json.set("name", puzzle.getName());
|
|
||||||
json.set("content", puzzle.getContent());
|
|
||||||
json.set("soluce", new String(puzzle.getSoluce()));
|
|
||||||
json.set("score_max", puzzle.getScoreMax());
|
|
||||||
|
|
||||||
context.response(200);
|
|
||||||
writer.write(json.toString()+"\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Route(path = "^/admin/puzzles/$", needLogin = true)
|
|
||||||
public void getAll(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
|
|
||||||
List<Puzzle> puzzles = repo.getAdminPuzzles();
|
|
||||||
JsonArray array = new JsonArray();
|
|
||||||
for (Puzzle puzzle : puzzles){
|
|
||||||
JsonMap puzzleJSON = new JsonMap();
|
|
||||||
puzzleJSON.set("id", puzzle.getId());
|
|
||||||
puzzleJSON.set("name", puzzle.getName());
|
|
||||||
puzzleJSON.set("scoreMax", puzzle.getScoreMax());
|
|
||||||
if(puzzle.getTags() != null) puzzleJSON.set("tags", puzzle.getJsonTags());
|
|
||||||
puzzleJSON.set("show", puzzle.hasStarted());
|
|
||||||
array.add(puzzleJSON);
|
|
||||||
}
|
|
||||||
context.response(200);
|
|
||||||
writer.write(array.toString());
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,68 +0,0 @@
|
||||||
package dev.peerat.backend.routes.admins;
|
|
||||||
|
|
||||||
import static dev.peerat.framework.RequestType.DELETE;
|
|
||||||
import static dev.peerat.framework.RequestType.POST;
|
|
||||||
import static dev.peerat.framework.RequestType.PUT;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
|
|
||||||
import dev.peerat.backend.model.Tag;
|
|
||||||
import dev.peerat.backend.repository.DatabaseAdminRepository;
|
|
||||||
import dev.peerat.backend.repository.DatabaseRepository;
|
|
||||||
import dev.peerat.framework.Context;
|
|
||||||
import dev.peerat.framework.HttpReader;
|
|
||||||
import dev.peerat.framework.HttpWriter;
|
|
||||||
import dev.peerat.framework.Route;
|
|
||||||
import dev.peerat.framework.utils.json.JsonArray;
|
|
||||||
import dev.peerat.framework.utils.json.JsonMap;
|
|
||||||
|
|
||||||
public class TagController {
|
|
||||||
|
|
||||||
private DatabaseAdminRepository repo;
|
|
||||||
|
|
||||||
public TagController(DatabaseRepository repo){
|
|
||||||
this.repo = repo.getAdminRepository();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Route(path = "^/admin/tag/$", type = POST, needLogin = true)
|
|
||||||
public void add(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
|
|
||||||
JsonMap json = reader.readJson();
|
|
||||||
if(repo.adminAddTag(json.get("name"))){
|
|
||||||
context.response(200);
|
|
||||||
}else{
|
|
||||||
context.response(501);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Route(path = "^/admin/tag/(\\d+)$", type = DELETE, needLogin = true)
|
|
||||||
public void delete(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
|
|
||||||
if(this.repo.adminDeleteTag(Integer.parseInt(matcher.group(1)))){
|
|
||||||
context.response(200);
|
|
||||||
}else{
|
|
||||||
context.response(501);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Route(path = "^/admin/tag/(\\d+)$", type = PUT, needLogin = true)
|
|
||||||
public void edit(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
|
|
||||||
JsonMap json = reader.readJson();
|
|
||||||
if(repo.adminUpdateTag(new Tag(Integer.parseInt(matcher.group(1)), json.get("name")))){
|
|
||||||
context.response(200);
|
|
||||||
}else{
|
|
||||||
context.response(501);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Route(path = "^/admin/tag/$", needLogin = true)
|
|
||||||
public void get(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
|
|
||||||
List<Tag> list = repo.getAdminTags();
|
|
||||||
JsonArray json = new JsonArray();
|
|
||||||
for(Tag tag : list) json.add(tag.toJson());
|
|
||||||
context.response(200);
|
|
||||||
writer.write(json.toString());
|
|
||||||
writer.flush();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,28 +0,0 @@
|
||||||
package dev.peerat.backend.routes.admins;
|
|
||||||
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
|
|
||||||
import dev.peerat.backend.model.Completion;
|
|
||||||
import dev.peerat.framework.Context;
|
|
||||||
import dev.peerat.framework.HttpReader;
|
|
||||||
import dev.peerat.framework.HttpWriter;
|
|
||||||
import dev.peerat.framework.Injection;
|
|
||||||
import dev.peerat.framework.Locker;
|
|
||||||
import dev.peerat.framework.Response;
|
|
||||||
import dev.peerat.framework.Route;
|
|
||||||
|
|
||||||
public class WebHookLeaderboard implements Response{
|
|
||||||
|
|
||||||
private Locker<Completion> locker;
|
|
||||||
|
|
||||||
public WebHookLeaderboard(@Injection("leaderboard") Locker<Completion> locker){
|
|
||||||
this.locker = locker;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Route(path = "^/admin/webhook/leaderboard/$", needLogin = true)
|
|
||||||
public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
|
|
||||||
locker.setValue(new Completion(0, 0));
|
|
||||||
context.response(200);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,83 +0,0 @@
|
||||||
package dev.peerat.backend.routes.groups;
|
|
||||||
|
|
||||||
import static dev.peerat.framework.RequestType.POST;
|
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
|
|
||||||
import dev.peerat.backend.Configuration;
|
|
||||||
import dev.peerat.backend.bonus.extract.RouteDoc;
|
|
||||||
import dev.peerat.backend.model.Chapter;
|
|
||||||
import dev.peerat.backend.model.Group;
|
|
||||||
import dev.peerat.backend.model.PeerAtUser;
|
|
||||||
import dev.peerat.backend.repository.DatabaseChapterRepository;
|
|
||||||
import dev.peerat.backend.repository.DatabaseGroupRepository;
|
|
||||||
import dev.peerat.backend.repository.DatabaseRepository;
|
|
||||||
import dev.peerat.backend.utils.FormResponse;
|
|
||||||
import dev.peerat.framework.Context;
|
|
||||||
import dev.peerat.framework.HttpReader;
|
|
||||||
import dev.peerat.framework.HttpWriter;
|
|
||||||
import dev.peerat.framework.Injection;
|
|
||||||
import dev.peerat.framework.Locker;
|
|
||||||
import dev.peerat.framework.Route;
|
|
||||||
import dev.peerat.framework.utils.json.JsonMap;
|
|
||||||
|
|
||||||
public class GroupCreate extends FormResponse {
|
|
||||||
|
|
||||||
private Locker<Group> locker;
|
|
||||||
private DatabaseGroupRepository repo;
|
|
||||||
private DatabaseChapterRepository chapterRepo;
|
|
||||||
private int groupDelay;
|
|
||||||
|
|
||||||
public GroupCreate(DatabaseRepository repo, @Injection("groups") Locker<Group> locker, Configuration config){
|
|
||||||
this.repo = repo.getGroupRepository();
|
|
||||||
this.chapterRepo = repo.getChapterRepository();
|
|
||||||
this.locker = locker;
|
|
||||||
this.groupDelay = config.getGroupJoinMinutes();
|
|
||||||
|
|
||||||
validator("name", "[a-zA-Z0-9&|!?{}\\[\\]%/*\\-+=:;,_#@ ]{3,100}");
|
|
||||||
}
|
|
||||||
|
|
||||||
@RouteDoc(path = "/groupCreate", responseCode = 200, responseDescription = "Le groupe a été créé")
|
|
||||||
@RouteDoc(responseCode = 403, responseDescription = "L'utilisateur est déjà dans le groupe / ne peux pas le rejoindre")
|
|
||||||
@RouteDoc(responseCode = 423, responseDescription = "L'utilisateur essaye de crée un groupe après le délai maximum de création de l'event")
|
|
||||||
|
|
||||||
@Route(path = "^\\/groupCreate$", type = POST, needLogin = true)
|
|
||||||
public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
|
|
||||||
JsonMap json = json(reader);
|
|
||||||
if(!areValids("name")){
|
|
||||||
context.response(403);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Group newGroup = new Group(json);
|
|
||||||
PeerAtUser user = context.getUser();
|
|
||||||
|
|
||||||
if (this.repo.getPlayerGroup(user.getId(), newGroup.getLinkToChapter()) == null) {
|
|
||||||
try {
|
|
||||||
if(this.repo.getGroupId(newGroup) == null) throw new NullPointerException();
|
|
||||||
context.response(403);
|
|
||||||
return;
|
|
||||||
}catch(NullPointerException e){
|
|
||||||
if(newGroup.getLinkToChapter() != null){
|
|
||||||
Chapter chapter = this.chapterRepo.getChapter(newGroup.getLinkToChapter());
|
|
||||||
if(chapter.getStartDate() != null){
|
|
||||||
LocalDateTime start = chapter.getStartDate().toLocalDateTime().plusMinutes(this.groupDelay);
|
|
||||||
if(LocalDateTime.now().isAfter(start)){
|
|
||||||
context.response(423);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (this.repo.insertGroup(newGroup, user)) {
|
|
||||||
context.response(200);
|
|
||||||
|
|
||||||
locker.setValue(newGroup);
|
|
||||||
} else {
|
|
||||||
context.response(403);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}else {
|
|
||||||
context.response(403);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,84 +0,0 @@
|
||||||
package dev.peerat.backend.routes.groups;
|
|
||||||
|
|
||||||
import static dev.peerat.framework.RequestType.POST;
|
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
|
|
||||||
import dev.peerat.backend.Configuration;
|
|
||||||
import dev.peerat.backend.bonus.extract.RouteDoc;
|
|
||||||
import dev.peerat.backend.model.Chapter;
|
|
||||||
import dev.peerat.backend.model.Completion;
|
|
||||||
import dev.peerat.backend.model.Group;
|
|
||||||
import dev.peerat.backend.model.PeerAtUser;
|
|
||||||
import dev.peerat.backend.repository.DatabaseChapterRepository;
|
|
||||||
import dev.peerat.backend.repository.DatabaseGroupRepository;
|
|
||||||
import dev.peerat.backend.repository.DatabaseRepository;
|
|
||||||
import dev.peerat.framework.Context;
|
|
||||||
import dev.peerat.framework.HttpReader;
|
|
||||||
import dev.peerat.framework.HttpWriter;
|
|
||||||
import dev.peerat.framework.Injection;
|
|
||||||
import dev.peerat.framework.Locker;
|
|
||||||
import dev.peerat.framework.Response;
|
|
||||||
import dev.peerat.framework.Route;
|
|
||||||
|
|
||||||
public class GroupJoin implements Response{
|
|
||||||
|
|
||||||
private DatabaseChapterRepository chapterRepo;
|
|
||||||
private DatabaseGroupRepository groupRepo;
|
|
||||||
private int groupDelay;
|
|
||||||
private String waitTime;
|
|
||||||
|
|
||||||
private final Locker<Completion> leaderboard;
|
|
||||||
|
|
||||||
public GroupJoin(DatabaseRepository repo, Configuration config, @Injection("leaderboard") Locker<Completion> locker){
|
|
||||||
this.chapterRepo = repo.getChapterRepository();
|
|
||||||
this.groupRepo = repo.getGroupRepository();
|
|
||||||
this.groupDelay = config.getGroupJoinMinutes();
|
|
||||||
this.waitTime = config.getGroupQuitMinutes();
|
|
||||||
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, Context context, HttpReader reader, HttpWriter writer) throws Exception{
|
|
||||||
Group group = new Group(reader.readJson());
|
|
||||||
PeerAtUser user = context.getUser();
|
|
||||||
|
|
||||||
Group userGroup = this.groupRepo.getPlayerGroup(user.getId(), group.getLinkToChapter());
|
|
||||||
if(group.equals(userGroup)){
|
|
||||||
context.response(403);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if(group.getLinkToChapter() == null){
|
|
||||||
context.response(409);
|
|
||||||
writer.write(waitTime);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if(group.getLinkToChapter() != null){
|
|
||||||
Chapter chapter = this.chapterRepo.getChapter(group.getLinkToChapter());
|
|
||||||
if(chapter.getStartDate() != null){
|
|
||||||
LocalDateTime start = chapter.getStartDate().toLocalDateTime().plusMinutes(this.groupDelay);
|
|
||||||
if(LocalDateTime.now().isAfter(start)){
|
|
||||||
context.response(423);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.groupRepo.insertUserInGroup(group, user)) {
|
|
||||||
context.response(200);
|
|
||||||
|
|
||||||
leaderboard.setValue(new Completion(0, 0, 0, null, 0));
|
|
||||||
} else {
|
|
||||||
context.response(403);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,43 +0,0 @@
|
||||||
package dev.peerat.backend.routes.groups;
|
|
||||||
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
|
|
||||||
import dev.peerat.backend.bonus.extract.RouteDoc;
|
|
||||||
import dev.peerat.backend.model.Group;
|
|
||||||
import dev.peerat.backend.repository.DatabaseGroupRepository;
|
|
||||||
import dev.peerat.backend.repository.DatabaseRepository;
|
|
||||||
import dev.peerat.framework.Context;
|
|
||||||
import dev.peerat.framework.HttpReader;
|
|
||||||
import dev.peerat.framework.HttpWriter;
|
|
||||||
import dev.peerat.framework.Response;
|
|
||||||
import dev.peerat.framework.Route;
|
|
||||||
import dev.peerat.framework.utils.json.JsonArray;
|
|
||||||
|
|
||||||
public class GroupList implements Response {
|
|
||||||
|
|
||||||
private DatabaseGroupRepository repo;
|
|
||||||
|
|
||||||
public GroupList(DatabaseRepository repo){
|
|
||||||
this.repo = repo.getGroupRepository();
|
|
||||||
}
|
|
||||||
|
|
||||||
@RouteDoc(path = "/groups", responseCode = 200, responseDescription = "JSON avec la liste des groups")
|
|
||||||
|
|
||||||
@Route(path = "^\\/groups\\/?(\\d+)?$", needLogin = true)
|
|
||||||
public void exec(Matcher matcher, Context context, HttpReader reader, HttpWriter writer) throws Exception{
|
|
||||||
String param = matcher.group(1);
|
|
||||||
if(param == null){
|
|
||||||
JsonArray result = new JsonArray();
|
|
||||||
for(Group group : this.repo.getAllGroups()) result.add(group.toJson());
|
|
||||||
context.response(200);
|
|
||||||
writer.write(result.toString());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
int chapter = Integer.parseInt(param);
|
|
||||||
JsonArray result = new JsonArray();
|
|
||||||
for(Group group : this.repo.getAllGroupsByChapter(chapter)) result.add(group.toJson());
|
|
||||||
context.response(200);
|
|
||||||
writer.write(result.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue