Merge branch 'peristanceBDD' of https://codefirst.iut.uca.fr/git/BOB_PARTEAM/BOB_PARTY into peristanceBDD
continuous-integration/drone/push Build is passing Details

peristanceBDD
Alban GUILHOT 2 years ago
commit 7c2b14f1c5

@ -36,7 +36,7 @@ steps:
dockerfile: ./api-rest/Dockerfile
context: .
registry: hub.codefirst.iut.uca.fr
repo: hub.codefirst.iut.uca.fr/bob_parteam/bob_party
repo: hub.codefirst.iut.uca.fr/bob_parteam/bob_party/api
username:
from_secret: SECRET_REGISTRY_USERNAME
password:
@ -48,7 +48,7 @@ steps:
- name: deploy-api-containers
image: hub.codefirst.iut.uca.fr/thomas.bellembois/codefirst-dockerproxy-clientdrone:latest
environment:
IMAGENAME: hub.codefirst.iut.uca.fr/bob_parteam/bob_party:latest
IMAGENAME: hub.codefirst.iut.uca.fr/bob_parteam/bob_party/api:latest
CONTAINERNAME: api-bobParty
COMMAND: create
OVERWRITE: true
@ -66,6 +66,33 @@ steps:
ADMINS: thomaschazot2,mathildejean3,lilianbreton,luciebedouret,albanguilhot,cedricbouhours
depends_on: [ deploy-container-mysql, container-api ]
# docker image build
- name: container-server
image: plugins/docker
settings:
dockerfile: ./bob_party/Dockerfile
context: .
registry: hub.codefirst.iut.uca.fr
repo: hub.codefirst.iut.uca.fr/bob_parteam/bob_party/server
username:
from_secret: SECRET_REGISTRY_USERNAME
password:
from_secret: SECRET_REGISTRY_PASSWORD
#container deployment
- name: deploy-server-containers
image: hub.codefirst.iut.uca.fr/thomas.bellembois/codefirst-dockerproxy-clientdrone:latest
environment:
IMAGENAME: hub.codefirst.iut.uca.fr/bob_parteam/bob_party/server:latest
CONTAINERNAME: server-bobParty
COMMAND: create
OVERWRITE: true
#PRIVATE: true
ADMINS: thomaschazot2,mathildejean3,lilianbreton,luciebedouret,albanguilhot,cedricbouhours
depends_on: [ container-server ]

@ -155,8 +155,12 @@ public function deleteUserFromConversation(int $idConv, int $idUser){
public function deleteConversation(int $id):void{
$deleteConv = "DELETE FROM T_H_CONVERSATION_COV
WHERE PK_ID=:idConv";
$deleteMessages="DELETE FROM T_H_MESSAGE_MSG WHERE PK_ID = (SELECT FK_MESSAGE
FROM T_J_CONTAIN_MESSAGE_CMG
WHERE FK_CONVERSATION=:id)";
$argIdConv = array('idConv'=>array($id,PDO::PARAM_INT));
$this->connection->execQuery($deleteConv,$argIdConv);
$this->connection->execQuery($deleteMessages,$argIdConv);
}
}

@ -59,7 +59,7 @@ class UserGateway{
$tabSkin=null;
$skinsOfUserQuery="SELECT s.*
FROM T_H_SKIN_SKI s, T_J_OWN_SKIN_OWN o
WHERE o.FK_USER=:id AND S.PK_ID=o.FK_SKIN";
WHERE o.FK_USER=:id AND s.PK_ID=o.FK_SKIN";
$argIdUser=array('id'=>array($id,PDO::PARAM_INT));
$this->connection->execQuery($skinsOfUserQuery,$argIdUser);
$resSkin=$this->connection->getRes();
@ -110,12 +110,15 @@ class UserGateway{
public function getUserForConnection(string $username,string $password):?User{
$userQuery = "SELECT *
FROM T_S_USER_USR
WHERE USR_USERNAME=:username
AND USR_PASSWORD=:password";
$argUsernamePassword=(array('username'=>array($username,PDO::PARAM_STR),
'password'=>array($password,PDO::PARAM_STR)));
WHERE USR_USERNAME=:username";
$argUsernamePassword=(array('username'=>array($username,PDO::PARAM_STR)));
$this->connection->execQuery($userQuery,$argUsernamePassword);
$res=$this->connection->getRes();
foreach($res as $row){
if(!password_verify($password,$row["USR_PASSWORD"])){
return null;
}
}
$usr=$this->convertResToUser($res);
if ($usr != null){
$usr->tabSkin=$this->getSkinList($usr->id);
@ -127,19 +130,27 @@ class UserGateway{
/// Parameters : * $u (User): user we want to insert in database
/// Returning TRUE if the user has been added succesfully, FALSE otherwise
public function postUser(string $username, string $password, string $nationality, string $sex, string $dateOfBirth) {
$password=password_hash($password,PASSWORD_DEFAULT);
$insertUserQuery = "INSERT INTO T_S_USER_USR VALUES (NULL, :username, :password, :nationality, :sex, :dateOfBirth, 0, 0, 0, 1)";
$getLastIdQuery = "SELECT max(PK_ID) id FROM T_S_USER_USR";
$argUser=array('username' => array($username, PDO::PARAM_STR),
'password' => array($password, PDO::PARAM_STR),
'nationality' => array($nationality, PDO::PARAM_STR),
'sex' => array($sex, PDO::PARAM_STR),
'dateOfBirth' => array($dateOfBirth, PDO::PARAM_STR));
$this->connection->execQuery($insertUserQuery, $argUser);
$this->connection->execQuery($getLastIdQuery, array());
$res=$this->connection->getRes();
foreach($res as $row){
$this->putSkinList($row['id'], 1);
}
}
/// Brief : Modifying an EXISTING user in database
/// Parameters : * $u (User): user we want to update in database
/// Returning TRUE if the modifications has been done succesfully, FALSE otherwise
public function putUser(int $id,string $username, string $password, string $sex, string $nationality, int $currentBobCoins,int $totalBobCoins,int $nbGamesPlayed, int $currentSkin){
$password=password_hash($password,PASSWORD_DEFAULT);
$updateUserQuery="UPDATE T_S_USER_USR
SET USR_USERNAME = :username,
USR_PASSWORD=:password,

@ -12,7 +12,7 @@
exit;
*/
//require_once("initBdd.php");
require_once("initBdd.php");
@ -76,11 +76,15 @@
$url = explode('/', $url);
$i=0;
while ($url[$i]!=="index.php"){
while ($url[$i]!=="index.php" && count($url)>0){
unset($url[$i]);
$i++;
}
if (empty($url)){
exit;
}
//echo json_encode($url);
$method_name = !empty($url[2]) ? (string)$url[2] : null;
@ -230,15 +234,15 @@
//header("HTTP/1.0 400 Invalid number of arguments");
http_response_code(400);
}
$id = !empty($url[4]) ? (int) $url[4] : null;
$username = !empty($url[5]) ? (string) $url[5] : null;
$password = !empty($url[6]) ? (string) $url[6] : null;
$sexe = !empty($url[7]) ? (string) $url[7] : null;
$nationality = !empty($url[8]) ? (string) $url[8] : null;
$nbCurrentCoins = (int) $url[9];
$totalnbCoins = (int) $url[10];
$nbGames = (int) $url[11];
$currentSkin = !empty($url[12]) ? (int) $url[12] : null;
$id = !empty($url[3]) ? (int) $url[3] : null;
$username = !empty($url[4]) ? (string) $url[4] : null;
$password = !empty($url[5]) ? (string) $url[5] : null;
$sexe = !empty($url[6]) ? (string) $url[6] : null;
$nationality = !empty($url[7]) ? (string) $url[7] : null;
$nbCurrentCoins = (int) $url[8];
$totalnbCoins = (int) $url[9];
$nbGames = (int) $url[10];
$currentSkin = !empty($url[11]) ? (int) $url[11] : null;
$usergw->putUser($id,$username,$password,$sexe, $nationality, $nbCurrentCoins,$totalnbCoins,$nbGames,$currentSkin);
http_response_code(200);
}

@ -27,9 +27,6 @@ $conn->query("CREATE TABLE `T_H_CONVERSATION_COV` (
`COV_NAME` varchar(20) DEFAULT NULL
) ;");
$conn->query("CREATE TRIGGER `before_delete_conversation` BEFORE DELETE ON `T_H_CONVERSATION_COV` FOR EACH ROW DELETE FROM T_H_MESSAGE_MSG WHERE PK_ID = (SELECT FK_MESSAGE
FROM T_J_CONTAIN_MESSAGE_CMG
WHERE FK_CONVERSATION=OLD.PK_ID);");
$conn->query("CREATE TABLE `T_H_MESSAGE_MSG` (
`PK_ID` int(11) NOT NULL,
@ -73,7 +70,7 @@ $conn->query("CREATE TABLE `T_J_PLAY_MATCH_PLM` (
$conn->query("CREATE TABLE `T_S_USER_USR` (
`PK_ID` int(11) NOT NULL,
`USR_USERNAME` varchar(50) NOT NULL,
`USR_PASSWORD` varchar(50) NOT NULL,
`USR_PASSWORD` varchar(200) NOT NULL,
`USR_NATIONALITY` varchar(20) NOT NULL,
`USR_SEX` varchar(30) NOT NULL,
`USR_DATE_OF_BIRTH` date DEFAULT NULL,
@ -84,9 +81,6 @@ $conn->query("CREATE TABLE `T_S_USER_USR` (
);");
$conn->query("CREATE TRIGGER `after_insert_user` AFTER INSERT ON `T_S_USER_USR` FOR EACH ROW INSERT INTO T_J_OWN_SKIN_OWN VALUES(NEW.PK_ID,1);");
$conn->query("ALTER TABLE `T_E_GAME_GAM`
ADD PRIMARY KEY (`PK_ID`),
ADD UNIQUE KEY `GAM_NAME` (`GAM_NAME`);");
@ -205,6 +199,14 @@ $conn->query("INSERT INTO `T_E_GAME_GAM` (`PK_ID`, `GAM_NAME`, `GAM_IMAGE`, `GAM
$conn->query("INSERT INTO `T_S_USER_USR` (`PK_ID`, `USR_USERNAME`, `USR_PASSWORD`, `USR_NATIONALITY`, `USR_SEX`, `USR_DATE_OF_BIRTH`, `USR_CURRENT_NB_COINS`, `USR_TOTAL_NB_COINS`, `USR_NB_GAMES_PLAYED`, `FK_CURRENT_SKIN`) VALUES
(1, 'to', 't', 'Anglais(e)', 'M', '2003-07-01', 105, 230, 12, 2);");
$conn->query("INSERT INTO `T_S_USER_USR` (`PK_ID`, `USR_USERNAME`, `USR_PASSWORD`, `USR_NATIONALITY`, `USR_SEX`, `USR_DATE_OF_BIRTH`, `USR_CURRENT_NB_COINS`, `USR_TOTAL_NB_COINS`, `USR_NB_GAMES_PLAYED`, `FK_CURRENT_SKIN`) VALUES
(1, 'to', 't', 'Anglais(e)', 'M', '2003-07-01', 105, 230, 12, 1);");
$conn->query("INSERT INTO `T_J_OWN_SKIN_OWN` (`FK_USER`, `FK_SKIN`) VALUES
(1, 1),
(1, 2);");
?>

@ -0,0 +1,19 @@
FROM node:latest
# Create app directory
# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY bob_party/package*.json ./
RUN yarn
# If you are building your code for production
# RUN npm ci --only=production
# Bundle app source
COPY bob_party/server.js .
EXPOSE 3000
CMD [ "node", "server.js" ]
CMD [ "cat", "server.js" ]

@ -7,7 +7,7 @@ const { Server } = require("socket.io");
const io = new Server(server);
io.on('connection', (socket) => {
console.log(socket.id)
console.log(socket.id);
socket.on('signIn', (id) => {
socket.join("U"+id);
@ -26,23 +26,28 @@ io.on('connection', (socket) => {
console.log("Message envoyé");
});
socket.on("createConversation", (tabId) =>{
socket.on("createConversation", (tabId, conv) =>{
tabId.forEach(id => {
socket.to("U"+id).emit("messageReceived");
socket.to("U"+id).emit("addedToConv", conv);
});
});
socket.on('joinMatch', (match) => {
socket.join("M" + match);
socket.join("M" + match.code);
socket.to("M"+ match.code).emit("matchUsersChanged");
});
socket.on('launchMatch', (match) => {
socket.to("M"+ match.code).emit("matchLaunched");
});
socket.on('quitMatch', (match) => {
socket.off("M" + match);
socket.to("M"+ match.code).emit("matchUsersChanged")
});
socket.on("playTicTacToe", (match, rowIndex, columnIndex, turn) =>{
socket.to("M"+match).emit("oppPlayTicTacToe", rowIndex, columnIndex, turn);
socket.to("M"+match.code).emit("oppPlayTicTacToe", rowIndex, columnIndex, turn);
});
});

@ -7,11 +7,15 @@ import { ScreenIndicator } from "../../components/ScreenIndicator";
import { TopBar } from "../../components/TopBar";
import { socket } from "../../../socketConfig";
import { MANAGER_MATCH, MANAGER_USER } from "../../../appManagers";
import { useUserStore } from "../../context/userContext";
export default function TicTacToeOnline(props: { navigation: any }){
const [init, setInit]=useState(0);
const [initTic, setInitTic]=useState(0);
const setUser = useUserStore((state) => state.setUser);
setUpTicTacToeOnline();
@ -29,7 +33,7 @@ export default function TicTacToeOnline(props: { navigation: any }){
const [currentTurn,setCurrentTurn] = useState("x");
const onPressCell = (rowIndex:number,columnIndex:number) => {
const onPressCell = async (rowIndex:number,columnIndex:number) => {
if (turnUser!==currentTurn){
Alert.alert("ce n'est pas à votre tour de jouer");
return;
@ -40,9 +44,9 @@ export default function TicTacToeOnline(props: { navigation: any }){
updateMap[rowIndex][columnIndex]=currentTurn;
return updateMap;
});
socket.emit("playTicTacToe", 1, rowIndex, columnIndex, currentTurn);
socket.emit("playTicTacToe", MANAGER_MATCH.getCurrentMatch(), rowIndex, columnIndex, currentTurn);
setCurrentTurn(currentTurn === "x"? "o" : "x");
const retour=checkWinning();
const retour= await checkWinning();
if(retour!=true){
checkComplete();
}
@ -54,9 +58,8 @@ export default function TicTacToeOnline(props: { navigation: any }){
};
function setUpTicTacToeOnline() {
if (init===0){
setInit(1);
socket.emit("inMatch", 1);
if (initTic===0){
setInitTic(1);
socket.on("oppPlayTicTacToe", (rowIndex, columnIndex, turn) =>{
setMap((existingMap) =>{
@ -80,36 +83,42 @@ export default function TicTacToeOnline(props: { navigation: any }){
}
}
const checkWinning = () =>{
async function endGame(win: number){
socket.off("oppPlayTicTacToe");
navigation.goBack();
const tmp=MANAGER_USER.getCurrentUser();
if (tmp!==null){
await MANAGER_MATCH.getCurrentMatch()?.updatePostMatch(tmp, win);
MANAGER_USER.setCurrentUser(tmp);
setUser(tmp);
}
}
const checkWinning = async () =>{
const tmp=MANAGER_USER.getCurrentUser()
// Checks rows
for (let i=0; i<3; i++){
const isRowXWinning = map[i].every((cell)=> cell==="x");
const isRowOWinning = map[i] .every((cell)=>cell==="o");
if(isRowXWinning==true){
if (tmp!==null){
Alert.alert("X won !");
if (turnUser==="x"){
MANAGER_MATCH.getCurrentMatch()?.updatePostMatch(tmp, 2);
await endGame(2);
}
else{
MANAGER_MATCH.getCurrentMatch()?.updatePostMatch(tmp, 0);
}
await endGame(0);
}
Alert.alert("X won !");
navigation.goBack();
return true;
}
else if(isRowOWinning==true){
if (tmp!==null){
Alert.alert("O won !");
if (turnUser==="x"){
MANAGER_MATCH.getCurrentMatch()?.updatePostMatch(tmp, 0);
await endGame(0);
}
else{
MANAGER_MATCH.getCurrentMatch()?.updatePostMatch(tmp, 2);
}
await endGame(2);
}
Alert.alert("O won !");
navigation.goBack();
return true;
}
}
@ -127,29 +136,23 @@ export default function TicTacToeOnline(props: { navigation: any }){
}
}
if (isColumnXWinning == true){
if (tmp!==null){
Alert.alert("X won !");
if (turnUser==="x"){
MANAGER_MATCH.getCurrentMatch()?.updatePostMatch(tmp, 2);
await endGame(2);
}
else{
MANAGER_MATCH.getCurrentMatch()?.updatePostMatch(tmp, 0);
}
await endGame(0);
}
Alert.alert("X won !");
navigation.goBack();
return true;
}
if(isColumnOWinning==true){
if (tmp!==null){
Alert.alert("O won !");
if (turnUser==="x"){
MANAGER_MATCH.getCurrentMatch()?.updatePostMatch(tmp, 0);
await endGame(0);
}
else{
MANAGER_MATCH.getCurrentMatch()?.updatePostMatch(tmp, 2);
}
await endGame(2);
}
Alert.alert("O won !");
navigation.goBack();
return true;
}
@ -174,44 +177,34 @@ export default function TicTacToeOnline(props: { navigation: any }){
}
}
if(isDiag1OWinning==true || isDiag2OWinning==true){
if (tmp!==null){
Alert.alert("O won !");
if (turnUser==="x"){
MANAGER_MATCH.getCurrentMatch()?.updatePostMatch(tmp, 0);
await endGame(0);
}
else{
MANAGER_MATCH.getCurrentMatch()?.updatePostMatch(tmp, 2);
await endGame(2);
}
}
Alert.alert("O won !");
navigation.goBack();
return true;
}
if(isDiag1XWinning==true || isDiag2XWinning==true){
if (tmp!==null){
Alert.alert("X won !");
if (turnUser==="x"){
MANAGER_MATCH.getCurrentMatch()?.updatePostMatch(tmp, 2);
await endGame(2);
}
else{
MANAGER_MATCH.getCurrentMatch()?.updatePostMatch(tmp, 0);
await endGame(0);
}
}
Alert.alert("X won !");
navigation.goBack();
return true;
}
};
const checkComplete = () =>{
const checkComplete = async () =>{
const isRow0Full = map[0].every((cell)=> cell!=="");
const isRow1Full = map[1] .every((cell)=>cell!=="");
const isRow2Full = map[2] .every((cell)=>cell!=="");
if(isRow0Full==true && isRow1Full==true && isRow2Full==true){
const tmp=MANAGER_USER.getCurrentUser();
if (tmp!==null){
MANAGER_MATCH.getCurrentMatch()?.updatePostMatch(tmp, 1);
}
Alert.alert("Draw !");
navigation.goBack();
await endGame(1);
return false;
}
};

@ -1,4 +1,4 @@
import { FC, ReactNode } from "react"
import { FC, ReactNode, useState } from "react"
import { Pressable, Image, ImageStyle, Text, View, Alert, ImageSourcePropType, TextStyle } from "react-native"
import React from "react"
import { Skin } from "../core/skin"
@ -22,24 +22,33 @@ FC<{conv: Conversation, navigation: any}> =
{
const setCurrentConv = useConversationStore((state) => state.setCurrentConv);
const [user,setUser]=useState(MANAGER_USER.getCurrentUser());
const [initVar,setInitVar]=useState(0);
const user1 = MANAGER_USER.getCurrentUser();
let tmp;
if (conv.getTabMessage().length<2){
tmp=conv.getTabUser()[0];
}
else if (user1?.isEqual(conv.getTabUser()[0])) tmp = conv.getTabUser()[1];
else tmp = conv.getTabUser()[0];
const user2 = tmp;
init();
function init(){
if (initVar===0){
setInitVar(1);
if (conv.getTabUser().length<2){
setUser(MANAGER_USER.getCurrentUser());
}
else if (MANAGER_USER.getCurrentUser()?.isEqual(conv.getLastMessage().getMessageSender())){
setUser(conv.getLastMessage().getMessageSender());
}
else{
setUser(conv.getTabUser()[1]);
}
}
}
return(
<Pressable onPress={() => {MANAGER_CONVERSATION.setCurrentConv(conv); setCurrentConv(conv); navigation.navigate(Conversation)}}>
<View style={styles.conv}>
<View>
<SkinComponent skin={user2.getCurrentSkin()} state='icon' nav={navigation}/>
<SkinComponent skin={user?.getCurrentSkin()} state='icon' nav={navigation}/>
</View>
<View style={{marginLeft: '5%', justifyContent: 'space-evenly'}}>
<Text style={styles.textNom}>{conv.getName()}</Text>

@ -43,6 +43,7 @@ FC<{game: Game, nav: any}> =
}, []);
return (
<View>
<Pressable onPress={() => createNewMatch(game, nav)}>

@ -17,6 +17,7 @@ import { useMatchStore } from '../context/matchContext';
import { MANAGER_MATCH } from '../../appManagers';
import { ScreenIndicator } from '../components/ScreenIndicator';
import { UserPreview } from "./UserPreview"
import { socket } from "../../socketConfig"
export const LobbyComponent :
@ -24,8 +25,12 @@ FC<{nav: any}> =
({nav}) =>
{
const setTabUser = useMatchStore((state) => state.setTabUser);
const setMatch = useMatchStore((state) => state.setMatch);
const [initUsers, setInitUsers] = useState(0);
const [init, setInit] = useState(0);
function getUsers(){
if (initUsers===0){
@ -45,6 +50,36 @@ FC<{nav: any}> =
}
async function launchMatch(){
}
function initMatchSocket(){
if (init===0){
setInit(1);
socket.on("matchUsersChanged", async () =>{
const match=MANAGER_MATCH.getCurrentMatch();
if (match !==null){
await MANAGER_MATCH.getLoaderMatch().loadByID(match.code).then((res) =>{
MANAGER_MATCH.setCurrentMatch(res);
setMatch(res);
setInitUsers(0);
getUsers();
});
}
});
socket.on("matchLaunched", async () =>{
nav.navigate(MANAGER_MATCH.getCurrentMatch()?.getGame().getName().replace(/\s/g, ''));
});
}
}
initMatchSocket();
if(MANAGER_MATCH.getCurrentMatch()?.getGame().getNbPlayerMax()==1){
return (
<View style={stylesScreen.bodyStartCenter}>
@ -66,7 +101,7 @@ FC<{nav: any}> =
getUsers();
return(
<View style={stylesScreen.bodyStartCenter}>
<Text style={style.text}>Match ID : {MANAGER_MATCH.getCurrentMatch()?.getCode()}</Text>
<Text style={style.text}>Match ID : {useMatchStore().match?.getCode()}</Text>
<FlatList
data={useMatchStore().tabUser}
keyExtractor={usr =>usr?.getUsername() || usr}
@ -75,7 +110,7 @@ FC<{nav: any}> =
/>
<Pressable
style={style.pressable}
onPress={() => nav.navigate(MANAGER_MATCH.getCurrentMatch()?.getGame().getName().replace(/\s/g, ''))}
onPress={() => {socket.emit("launchMatch", MANAGER_MATCH.getCurrentMatch()); nav.navigate(MANAGER_MATCH.getCurrentMatch()?.getGame().getName().replace(/\s/g, ''))}}
>
<Text style={style.text}>Lancer la partie</Text>
</Pressable>

@ -52,7 +52,7 @@ FC<{nav: any, state?: string}> =
await MANAGER_CONVERSATION.getsaverConversation().deleteUserToConversation(tmpConv, tmp);
const trouveIndex = (element: Conversation) => element.getId()===tmpConv.getId();
const index=MANAGER_CONVERSATION.getTabConv().findIndex(trouveIndex);
MANAGER_CONVERSATION.getTabConv().splice(index);
MANAGER_CONVERSATION.getTabConv().splice(index, 1);
if (tmpConv.getTabUser().length===1){
await MANAGER_CONVERSATION.getsaverConversation().deleteConversation(tmpConv);
}
@ -70,6 +70,7 @@ FC<{nav: any, state?: string}> =
const m=new MatchModifier();
if (tmp!==null && tmpMatch!==null){
socket.emit("quitMatch", tmpMatch);
socket.off("M" + tmpMatch.code);
await m.quitMatch(tmp, tmpMatch);
resetMatch();
resetTabUserMatch();
@ -111,7 +112,7 @@ FC<{nav: any, state?: string}> =
case 'conversation':
return (
<View style={styles.header}>
<Pressable onPress={() => { resetCurrentConv; MANAGER_CONVERSATION.setCurrentConv(null); nav.goBack()}}>
<Pressable onPress={() => { resetCurrentConv(); MANAGER_CONVERSATION.setCurrentConv(null); nav.goBack()}}>
<Image source={cross} style={styles.icon}/>
</Pressable>
<Text style={styles.titre}>{useConversationStore().currentConv?.getName()}</Text>

@ -19,7 +19,6 @@ export const UserPreview :
FC<{user: User | null}> =
({user}) =>
{
console.log(user);
if(user !== null){
return (
<View style= {styles.view}>

@ -67,6 +67,6 @@ export abstract class Match{
}
abstract updatePostMatch(user:User, points:number):void;
abstract updatePostMatch(user:User, points:number):Promise<void>;
}

@ -10,9 +10,9 @@ export default class MatchCasino extends Match{
super(code, inGame, tabUser, game);
}
updatePostMatch(user:User, points: number): void {
async updatePostMatch(user:User, points: number): Promise<void> {
const manage= new UserCoinsModifier();
manage.addCoins(user, this.getGame().coinsCalculator(points));
await manage.addCoins(user, this.getGame().coinsCalculator(points));
}
}

@ -10,8 +10,8 @@ export default class MatchMulti extends Match{
super(code, inGame, tabUser, game);
}
updatePostMatch(user:User, points: number): void {
async updatePostMatch(user:User, points: number): Promise<void> {
const manage= new UserCoinsModifier();
manage.addCoins(user, this.getGame().coinsCalculator(points));
await manage.addCoins(user, this.getGame().coinsCalculator(points));
}
}

@ -10,8 +10,8 @@ export default class MatchSolo extends Match{
super(code, inGame, tabUser, game);
}
updatePostMatch(user:User, points: number): void {
async updatePostMatch(user:User, points: number): Promise<void> {
const manage= new UserCoinsModifier();
manage.addCoins(user, this.getGame().coinsCalculator(points));
await manage.addCoins(user, this.getGame().coinsCalculator(points));
}
}

@ -66,7 +66,8 @@ export default function AddConversation(props: {navigation:any}){
(objA, objB) => objB.getLastMessage().getMessageDate().getTime() - objA.getLastMessage().getMessageDate().getTime(),
);
setTabConv(MANAGER_CONVERSATION.getTabConv());
socket.emit("createConversation", tabId);
socket.emit("createConversation", tabId, res);
socket.emit("inConv", res);
navigation.goBack();
}
});

@ -26,7 +26,7 @@ function ConversationScreen(props: { navigation: any; }) {
await MANAGER_CONVERSATION.getsaverConversation().addMessage(tmpConv.getId(), e.nativeEvent.text, new Date(), tmpUs).then((res) => {
if (res!==null){
const trouveIndex = (element: Conversation) => element.getId()===tmpConv.getId();
MANAGER_CONVERSATION.getCurrentConv()?.getTabMessage().push(res);
MANAGER_CONVERSATION.getCurrentConv()?.ajouterMessage(res);
const index=MANAGER_CONVERSATION.getTabConv().findIndex(trouveIndex);
const tmp=MANAGER_CONVERSATION.getCurrentConv();
if (tmp!==null){

@ -1,5 +1,5 @@
import { StatusBar } from 'expo-status-bar'
import {View, FlatList, Text} from 'react-native'
import {View, FlatList, Text, Alert, NativeSyntheticEvent, TextInputSubmitEditingEventData} from 'react-native'
import React, { useState } from 'react';
import { TopBar } from '../components/TopBar';
import { BotBar } from '../components/BotBar';
@ -8,14 +8,38 @@ import { ScreenIndicator } from '../components/ScreenIndicator';
import { TextInput } from 'react-native-gesture-handler';
import stylesScreen from './style/screens.style'
import styles from './style/GameChoice.style'
import { MANAGER_GAME } from '../../appManagers';
import { MANAGER_GAME, MANAGER_MATCH, MANAGER_USER } from '../../appManagers';
import { GameList } from '../components/GameList';
import { useMatchStore } from '../context/matchContext';
import { socket } from '../../socketConfig';
function GameChoice(props: { navigation: any}) {
const { navigation} = props
const [matchId, setMatchId] = useState('');
const setMatch = useMatchStore((state) => state.setMatch);
async function joinMatch(id:NativeSyntheticEvent<TextInputSubmitEditingEventData>){
const newId = parseInt(id.nativeEvent.text);
const tmp=MANAGER_USER.getCurrentUser();
if (tmp !== null){
await MANAGER_MATCH.getsaverMatch().joinMatch(tmp, newId).then((res) =>{
if (res===null){
Alert.alert("L'id du match n'existe pas ou un jeu est déjà lancé ou il y a trop de joueurs");//changer ça avec d'autre codes de retour
}
else{
MANAGER_MATCH.setCurrentMatch(res);
setMatch(res);
socket.emit("joinMatch", res);
navigation.navigate("GameSolo");
}
});
}
}
if(MANAGER_GAME.currentGameType === "solo" ){
return (
<View style={stylesScreen.container}>
@ -48,7 +72,7 @@ function GameChoice(props: { navigation: any}) {
/>
<View style={{backgroundColor: '#2D2C33', flexDirection: 'row', alignContent: 'flex-start', margin: '2%', borderRadius: 15}}>
<Text style={styles.text}>Rejoindre un match</Text>
<TextInput style={styles.textInput} placeholder='Id' onChangeText={(val) => setMatchId(val)} autoCapitalize='none' />
<TextInput style={styles.textInput} placeholder='Id' onChangeText={(val) => setMatchId(val)} onSubmitEditing={(val) => {joinMatch(val)}} autoCapitalize='none' />
</View>
</View>
<BotBar

@ -32,6 +32,8 @@ function SignIn(props: { navigation: any; }) {
const setTabSkin = useSkinStore((state) => state.setTabSkin);
const [waitConnect, setWaitConnect] = useState(0);
const errorList = useSelector((state: RootState) => state.credentialErrors.loginErrorList);
@ -44,12 +46,11 @@ function SignIn(props: { navigation: any; }) {
dispatch(updateIncorrectCredentials(true));
}
let waitConnect=0;
async function handleUserConnect(username: string, password: string){
if (waitConnect==0){
waitConnect=1;
setWaitConnect(-1);
await MANAGER_USER.getLoaderUser().loadByUsernamePassword(username, password).then(async (res) => {
if (res!=null){
@ -67,10 +68,10 @@ function SignIn(props: { navigation: any; }) {
}
else{
Alert.alert("Incorrect Username or Password");
setWaitConnect(0);
}
});
waitConnect=0;
}
return;
}
@ -83,6 +84,10 @@ function SignIn(props: { navigation: any; }) {
socket.on("messageReceived", async () =>{
await handleConversationLoad();
});
socket.on("addedToConv", async (conv) =>{
socket.emit("inConv", conv);
await handleConversationLoad();
});
}
async function handleConversationLoad(){
@ -96,9 +101,6 @@ function SignIn(props: { navigation: any; }) {
if (tmpConv!==null){
const trouveIndex = (element: Conversation) => element.getId()===tmpConv.getId();
const index=MANAGER_CONVERSATION.getTabConv().findIndex(trouveIndex);
MANAGER_CONVERSATION.getTabConv()?.sort(
(objA, objB) => objB.getLastMessage().getMessageDate().getTime() - objA.getLastMessage().getMessageDate().getTime(),
);
MANAGER_CONVERSATION.setCurrentConv(MANAGER_CONVERSATION.getTabConv()[index]);
setCurrentConv(MANAGER_CONVERSATION.getCurrentConv());
}

@ -14,11 +14,15 @@ import { updateImpossibleBirthDate, updateInvalidPassword, updateInvalidPseudo,
import { getSystemErrorMap } from 'util';
import DateTimePicker from '@react-native-community/datetimepicker';
import DatePicker from '@dietime/react-native-date-picker';
import { MANAGER_USER } from '../../appManagers';
import { MANAGER_CONVERSATION, MANAGER_GAME, MANAGER_SKIN, MANAGER_USER } from '../../appManagers';
import { Dispatch, AnyAction } from '@reduxjs/toolkit';
import { User } from '../core/User/user';
import { useUserStore } from '../context/userContext';
import { socket } from '../../socketConfig';
import { useConversationStore } from '../context/conversationContext';
import { useGameStore } from '../context/gameContext';
import { Conversation } from '../core/conversation';
import { useSkinStore } from '../context/storeContext'
function SignUp(props: { navigation: any; }) {
const { navigation } = props
@ -31,6 +35,17 @@ function SignUp(props: { navigation: any; }) {
const setUser = useUserStore((state) => state.setUser);
const setTabConv = useConversationStore((state) => state.setTabConv);
const setCurrentConv = useConversationStore((state) => state.setCurrentConv);
const setTabGame = useGameStore((state) => state.setTabGame);
const setTabGameSolo = useGameStore((state) => state.setTabGameSolo);
const setTabGameMulti = useGameStore((state) => state.setTabGameMulti);
const setTabSkin = useSkinStore((state) => state.setTabSkin);
function onDateSelected(event : DateTimePickerEvent, value : Date | undefined) {
if (value != undefined) {
setDate(value);
@ -165,14 +180,72 @@ function SignUp(props: { navigation: any; }) {
if (tmp!=null){
Alert.alert("Ce pseudo existe déjà");
}
await MANAGER_USER.getsaverUser().saveUser(pseudo, password, selectedNationality, selectedSex, date).then((res)=>{
await MANAGER_USER.getsaverUser().saveUser(pseudo, password, selectedNationality, selectedSex, date).then(async (res)=>{
MANAGER_USER.setCurrentUser(res);
setUser(MANAGER_USER.getCurrentUser());
socket.emit("signIn", res);
initSocket();
await handleSkinLoad();
await handleGameLoad();
navigation.navigate('HomeTab');
})
}
}
function initSocket(){
socket.emit("signIn", MANAGER_USER.getCurrentUser()?.id);
MANAGER_CONVERSATION.getTabConv()?.forEach( conv =>{
socket.emit("inConv", conv);
});
socket.on("messageReceived", async () =>{
await handleConversationLoad();
});
socket.on("addedToConv", async (conv) =>{
socket.emit("inConv", conv);
await handleConversationLoad();
});
}
async function handleSkinLoad(){
MANAGER_SKIN.setTabSkin(await MANAGER_SKIN.getLoaderSkin().loadAllSkin());
setTabSkin(MANAGER_SKIN.getTabSkin());
}
async function handleGameLoad(){
MANAGER_GAME.setTabGame(await MANAGER_GAME.getLoaderGame().loadAllGames());
MANAGER_GAME.getTabGame().forEach(game => {
if (game.getNbPlayerMin()>1){
MANAGER_GAME.getTabGameMulti().push(game);
}
else{
MANAGER_GAME.getTabGameSolo().push(game);
}
});
setTabGame(MANAGER_GAME.getTabGame());
setTabGameMulti(MANAGER_GAME.getTabGameMulti())
setTabGameSolo(MANAGER_GAME.getTabGameSolo());
}
async function handleConversationLoad(){
const tmp = MANAGER_USER.getCurrentUser();
if (tmp !== null) {
await MANAGER_CONVERSATION.getLoaderConversation().loadByUser(tmp).then((res) => {
const tmp=MANAGER_USER.getCurrentUser()
MANAGER_CONVERSATION.setTabConv(res);
if (tmp!==null){
const tmpConv=MANAGER_CONVERSATION.getCurrentConv();
if (tmpConv!==null){
const trouveIndex = (element: Conversation) => element.getId()===tmpConv.getId();
const index=MANAGER_CONVERSATION.getTabConv().findIndex(trouveIndex);
MANAGER_CONVERSATION.setCurrentConv(MANAGER_CONVERSATION.getTabConv()[index]);
setCurrentConv(MANAGER_CONVERSATION.getCurrentConv());
}
setTabConv(MANAGER_CONVERSATION.getTabConv());
}
});
}
}
}
export default SignUp

@ -26,7 +26,7 @@ export class LoaderConversationApi implements ILoaderConversation{
url: url,
})
.then(async function (response: any) {
if (response.data != null || response.data != undefined){
if (response.data != null && response.data != undefined){
tabConv=await jsonToConversation(response);
}
});
@ -63,7 +63,10 @@ async function jsonToConversation(response:any) {
const sender:User | null= await MANAGER_USER.getLoaderUser().loadByID(message.idSender);
if (sender!=null){
tabMessage.push(new Message(message.id, message.content, sender, new Date(message.dateEnvoie)));
const tab=message.dateEnvoie.split(' ');
const tabDate=tab[0].split('-');
const tabPrecis=tab[1].split(":");
tabMessage.push(new Message(message.id, message.content, sender, new Date(tabDate[0],parseInt(tabDate[1])-1,tabDate[2],tabPrecis[0], tabPrecis[1], tabPrecis[2])));
}
if(conv.tabMessages.length===tabMessage.length){
resolve();

@ -12,15 +12,14 @@ export default class LoaderGameApi implements ILoaderGame{
async loadAllGames(): Promise<Game[]> {
let tab: Game[]=[];
const url=this.baseUrl+"http://localhost:8888/api-rest/index.php/getGames";
const url=this.baseUrl+"getGames";
await this.axios({
method: 'get',
url: url,
})
.then(function (response: any) {
if (response.data != null || response.data != undefined){
if (response.data != null && response.data != undefined){
response.data.forEach(game => {
switch(game.type){
case "GameSolo":
@ -54,7 +53,7 @@ export default class LoaderGameApi implements ILoaderGame{
method: 'get',
url: url,
}).then(function (response: any){
if (response.data!=undefined || response.data!==null){
if (response.data!=undefined && response.data!==null){
switch(response.data.type){
case "GameSolo":
let mapSolo = new Map();
@ -62,14 +61,17 @@ export default class LoaderGameApi implements ILoaderGame{
mapSolo.set(new Number(response.data.keys[i]), new Number(response.data.values[i]))
}
game = new GameSolo(response.data.id, response.data.name, response.data.image, response.data.nbPlayerMin, response.data.nbPlayerMax, mapSolo);
break;
case "GameMulti":
const mapMulti = new Map();
for (let i=0; i<response.data.keys.length; i++){
mapMulti.set(new Number(response.data.keys[i]), new Number(response.data.values[i]));
}
game = new GameMulti(response.data.id, response.data.name, response.data.image, response.data.nbPlayerMin, response.data.nbPlayerMax, mapMulti);
break;
case "GameCasino":
game = new GameCasino(response.data.id, response.data.name, response.data.image, response.data.nbPlayerMin, response.data.nbPlayerMax);
break;
}
}
});

@ -44,7 +44,7 @@ export default class SaverMatchApi implements ISaverMatch{
}
async deleteUserFromMatch(u: User): Promise<void> {
let url=this.baseUrl + 'deleteUserFromMatch.php/' + u.id;
let url=this.baseUrl + 'deleteUserFromMatch/' + u.id;
await this.axios({
method: 'put',
url: url,
@ -61,7 +61,8 @@ export default class SaverMatchApi implements ISaverMatch{
await MANAGER_MATCH.getLoaderMatch().loadByID(id).then(async (response)=>{
if (response!==undefined && response !== null){
if (response.getTabUsers().length<response.getGame().getNbPlayerMax() || response.getInGame()===false){
console.log(response.getTabUsers().length + " : " + response.getGame().getNbPlayerMax());
if (response.getTabUsers().length<response.getGame().getNbPlayerMax() && response.getInGame()===false){
response.getTabUsers().push(u);
match=response;
await this.axios({

@ -27,6 +27,7 @@ export default class SaverUserApi implements ISaverUser{
async updateUser(u: User): Promise<void> {
let us:User|null=null;
const url=this.baseUrl + 'putUser/'+ u.getId() + "/" + u.getUsername() + "/" + u.getPassword() + "/" + u.getSexe() + "/" + u.getNationality() + "/" + u.getCurrentCoins() + "/" + u.getTotalCoins() + "/" + u.getGamesPlayed() + "/" + u.getCurrentSkin().getSkinId();
console.log(url);
await this.axios({
method: 'put',
url: url,

Loading…
Cancel
Save