Ajoue d'un lien avec une base de donnée sur le localhost (mamp) grace à l'api, fin de tous les savers et les loaders a part ceux des matchs, fin de la partie reseaux lorsque l'utilisateur envoie et reçoit un message
continuous-integration/drone/push Build is passing Details

peristanceBDD
Thomas Chazot 2 years ago
parent ace46ab432
commit 0f97baac5d

@ -1,19 +1,22 @@
# Rederection if URL not found
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILEANME} !-f
RewriteCond %{REQUEST_FILEANME} !-d
RewriteRule (.+) index.php?p=$1 [QSA,L]
</IfModule>
# # Rederection if URL not found
# Redirecting 403 errors to index.php (does not work)
ErrorDocument 403 http://localhost:8888/api-rest/index.php
# <IfModule mod_rewrite.c>
# RewriteEngine on
# RewriteCond %{REQUEST_FILEANME} !-f
# RewriteCond %{REQUEST_FILEANME} !-d
# RewriteRule (.+) index.php?p=$1 [QSA,L]
# </IfModule>
# Refusing access to all files ending with php
Require all denied
# # Redirecting 403 errors to index.php (does not work)
# #ErrorDocument 403 http://localhost:8888/api-rest/index.php
# Allowing access to index.php
<Files index.php>
Require all granted
</Files>
# # Refusing access to all files ending with php
# # Allowing access to index.php
# <Files index.php>
# Require all granted
# </Files>
# Require all denied

@ -28,14 +28,14 @@ class ConversationGateway{
/// Parameters : * $idUser (string): identifier of the user we want to get the conversations
public function getConversations(string $_idUser):?array{
// Declaration of arrays (NULL) and queries
$tabConversations=NULL;
$tabUsers=NULL;
$tabMessages=NULL;
$tabConversations=[];
$tabUsers=[];
$tabMessages=[];
$conversationQuery = "SELECT c.PK_ID, c.COV_NAME
FROM T_H_CONVERSATION_COV c, T_J_DISCUSS_DIS d
WHERE c.PK_ID=d.FK_CONVERSATION
AND d.FK_USER=:idUser";
$messagesQuery = "SELECT m.PK_ID, m.MSG_MESSAGE, m.FK_SENDER
$messagesQuery = "SELECT m.PK_ID, m.MSG_MESSAGE, m.FK_SENDER, m.MSG_DATEENVOIE
FROM T_H_MESSAGE_MSG m, T_J_CONTAIN_MESSAGE_CMG c
WHERE m.PK_ID=c.FK_MESSAGE
AND c.FK_CONVERSATION=:idConv";
@ -53,9 +53,10 @@ class ConversationGateway{
$this->connection->execQuery($messagesQuery,$argIdConv);
$resMessages=$this->connection->getRes();
foreach($resMessages as $rowMessages){
$tabUsers[] = new Message($rowMessages['PK_ID'],
$tabMessages[] = new Message($rowMessages['PK_ID'],
$rowMessages['MSG_MESSAGE'],
$rowMessages['FK_SENDER']);
$rowMessages['FK_SENDER'],
$rowMessages['MSG_DATEENVOIE']);
}
// Find all the users in the conversation
$this->connection->execQuery($usersQuery,$argIdConv);
@ -76,7 +77,7 @@ class ConversationGateway{
}
/// Brief : Adding a new conversation in database
public function postConversation(string $name, int $idUser): void{
public function postConversation(string $name, array $idUsers): int{
// Declare queries
$convCreationQuery = "INSERT INTO T_H_CONVERSATION_COV VALUES(NULL,:name)";
$addUserInConvQuery = "INSERT INTO T_J_DISCUSS_DIS VALUES(:idUser,:idConv)";
@ -92,10 +93,13 @@ class ConversationGateway{
foreach($res as $row){
$id=$row['PK_ID'];
}
$argUserInConvQuery = array('idUser'=>array($idUser, PDO::PARAM_INT),
'idConv'=>array($id, PDO::PARAM_INT));
$this->connection->execQuery($addUserInConvQuery,$argUserInConvQuery);
foreach ($idUsers as $idUs){
$argUserInConvQuery = array('idUser'=>array($idUs, PDO::PARAM_INT),
'idConv'=>array($id, PDO::PARAM_INT));
$this->connection->execQuery($addUserInConvQuery,$argUserInConvQuery);
}
return $id;
}
/// Brief : Modifying an EXISTING conversation in database
@ -125,12 +129,13 @@ public function deleteUserFromConversation(int $idConv, int $idUser){
}
/// Brief : adding a new message into a conversation
public function addMessageToConversation(string $message, int $idSender, int $idConv){
$insertMessageQuery = "INSERT INTO T_H_MESSAGE_MSG VALUES(NULL,:message,:idSender)";
public function addMessageToConversation(string $message, int $idSender, int $idConv, string $date): int{
$insertMessageQuery = "INSERT INTO T_H_MESSAGE_MSG VALUES(NULL,:message,:idSender, :date)";
$insertMsgInConvQuery = "INSERT INTO T_J_CONTAIN_MESSAGE_CMG VALUES(:idConv,:idMessage)";
$argInsertMessage= array('message'=>array($message,PDO::PARAM_STR),
'idSender'=>array($idSender,PDO::PARAM_INT));
'idSender'=>array($idSender,PDO::PARAM_INT),
'date'=>array($date,PDO::PARAM_STR));
$this->connection->execQuery($insertMessageQuery,$argInsertMessage);
$this->connection->execQuery("SELECT PK_ID
FROM T_H_MESSAGE_MSG
@ -143,6 +148,7 @@ public function deleteUserFromConversation(int $idConv, int $idUser){
$argMsgInConv = array('idConv'=>array($idConv,PDO::PARAM_INT),
'idMessage'=>array($idMsg,PDO::PARAM_INT));
$this->connection->execQuery($insertMsgInConvQuery,$argMsgInConv);
return $idMsg;
}
/// Brief : Deleting a conversation and its messages from database

@ -29,6 +29,20 @@ class SkinGateway{
}
return $tabSkins;
}
public function getSkinById(int $id):?Skin{
$skin=null;
$skinQuery="SELECT * FROM T_H_SKIN_SKI WHERE PK_ID=:id";
$this->connection->execQuery($skinQuery,array('id'=>array($id, PDO::PARAM_INT)));
$res = $this->connection->getRes();
foreach($res as $row){
$skin= new Skin($row['PK_ID'],
$row['SKI_NAME'],
$row['SKI_IMAGE'],
$row['SKI_PRICE']);
}
return $skin;
}
}
?>

@ -1,6 +1,8 @@
<?php
require_once('model/user.php');
require_once('model/skin.php');
class UserGateway{
@ -33,6 +35,9 @@ class UserGateway{
public function convertResToUser($res):?User{
$usr=null;
foreach($res as $row){
$skinGateway=new SkinGateway($this->connection);
$skinId=$row['FK_CURRENT_SKIN'];
$skin=$skinGateway->getSkinById($skinId);
$usr= new User($row['PK_ID'],
$row['USR_USERNAME'],
$row['USR_PASSWORD'],
@ -42,7 +47,7 @@ class UserGateway{
$row['USR_CURRENT_NB_COINS'],
$row['USR_TOTAL_NB_COINS'],
$row['USR_NB_GAMES_PLAYED'],
$row['FK_CURRENT_SKIN'],
$skin,
null);
}
return $usr;
@ -54,8 +59,8 @@ class UserGateway{
$tabSkin=null;
$skinsOfUserQuery="SELECT s.*
FROM T_H_SKIN_SKI s, T_J_OWN_SKIN_OWN o
WHERE o.FK_USER=:id";
$argIdUser=array('id'=>array($id,PDO::PARAM_STR));
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();
foreach($resSkin as $row){
@ -76,7 +81,7 @@ class UserGateway{
$res=$this->connection->getRes();
$usr=$this->convertResToUser($res);
if ($usr != null){
$usr->listSkin=$this->getSkinList($usr->id);
$usr->tabSkin=$this->getSkinList($usr->id);
}
return $usr;
}
@ -92,7 +97,7 @@ class UserGateway{
$res=$this->connection->getRes();
$usr=$this->convertResToUser($res);
if ($usr != null){
$usr->listSkin=$this->getSkinList($usr->id);
$usr->tabSkin=$this->getSkinList($usr->id);
}
return $usr;
}
@ -113,7 +118,7 @@ class UserGateway{
$res=$this->connection->getRes();
$usr=$this->convertResToUser($res);
if ($usr != null){
$usr->listSkin=$this->getSkinList($usr->id);
$usr->tabSkin=$this->getSkinList($usr->id);
}
return $usr;
}
@ -134,10 +139,12 @@ class UserGateway{
/// 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, int $currentBobCoins,int $totalBobCoins,int $nbGamesPlayed, int $currentSkin){
public function putUser(int $id,string $username, string $password, string $sex, string $nationality, int $currentBobCoins,int $totalBobCoins,int $nbGamesPlayed, int $currentSkin){
$updateUserQuery="UPDATE T_S_USER_USR
SET USR_USERNAME = :username,
USR_PASSWORD=:password,
USR_SEX=:sex,
USR_NATIONALITY=:nationality,
USR_CURRENT_NB_COINS=:currentBobCoins,
USR_TOTAL_NB_COINS=:totalBobCoins,
USR_NB_GAMES_PLAYED=:nbGamesPlayed,
@ -145,6 +152,8 @@ class UserGateway{
WHERE PK_ID=:id";
$argUser=array('username' => array($username, PDO::PARAM_STR),
'password' => array($password, PDO::PARAM_STR),
'sex' => array($sex, PDO::PARAM_STR),
'nationality' => array($nationality, PDO::PARAM_STR),
'currentBobCoins' => array($currentBobCoins, PDO::PARAM_INT),
'totalBobCoins' => array($totalBobCoins, PDO::PARAM_INT),
'nbGamesPlayed' => array($nbGamesPlayed, PDO::PARAM_INT),

@ -1,6 +1,5 @@
<?php
echo "hey you ";
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST,GET,DELETE,PUT');
/// Good to know :
@ -10,7 +9,7 @@
include ('dbConnection.php');
include ('gateways/userGateway.php');
include ('gateways/matchGateway.php');
include ('gateways/conversationGataway.php');
include ('gateways/conversationGateway.php');
include ('gateways/gameGateway.php');
include ('gateways/skinGateway.php');
@ -145,6 +144,7 @@
header("HTTP/1.0 401 UNAUTHORIZED REQUEST");
http_response_code(401);
}
break;
case 'POST':
if($method_name === "postUser"){ // test : OK
if (count($url)<8){
@ -153,7 +153,7 @@
}
$username = !empty($url[4]) ? (string) $url[4] : null;
$password = !empty($url[5]) ? (string) $url[5] : null;
$nationality = !empty($url[5]) ? (string) $url[5] : null;
$nationality = !empty($url[6]) ? (string) $url[6] : null;
$sex = !empty($url[7]) ? (string) $url[7] : null;
$dateOfBirth = !empty($url[8]) ? (string) $url[8] : null;
$usergw->postUser($username,$password,$nationality,$sex,$dateOfBirth);
@ -172,9 +172,11 @@
}
elseif($method_name === "postConversation"){ // test : OK
$name = !empty($url[4]) ? (string) $url[4] : null;
$idCreator = !empty($url[5]) ? (int) $url[5] : null;
if ($name != null || $idCreator != null){
$conversationgw->postConversation($name,$idCreator);
$idList = !empty($url[5]) ? (array) explode(",",$url[5]) : null;
$name=urldecode($name);
if ($name != null || $idList != null){
$id=$conversationgw->postConversation($name,$idList);
echo json_encode($id, JSON_PRETTY_PRINT);
http_response_code(200);
} else{
header("HTTP/1.0 400 name or creator not given");
@ -188,18 +190,20 @@
break;
case 'PUT':
if($method_name === "putUser"){ // test : OK
if (count($url)<10){
if (count($url)<12){
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;
$nbCurrentCoins = !empty($url[7]) ? (int) $url[7] : null;
$totalnbCoins = !empty($url[8]) ? (int) $url[8] : null;
$nbGames = !empty($url[9]) ? (int) $url[9] : null;
$currentSkin = !empty($url[10]) ? (int) $url[10] : null;
$usergw->putUser($id,$username,$password,$nbCurrentCoins,$totalnbCoins,$nbGames,$currentSkin);
$sexe = !empty($url[7]) ? (string) $url[7] : null;
$nationality = !empty($url[8]) ? (string) $url[8] : null;
$nbCurrentCoins = !empty($url[9]) ? (int) $url[9] : null;
$totalnbCoins = !empty($url[10]) ? (int) $url[10] : null;
$nbGames = !empty($url[11]) ? (int) $url[11] : null;
$currentSkin = !empty($url[12]) ? (int) $url[12] : null;
$usergw->putUser($id,$username,$password,$sexe, $nationality, $nbCurrentCoins,$totalnbCoins,$nbGames,$currentSkin);
http_response_code(200);
}
elseif($method_name === "putSkinList"){ // test : OK
@ -247,6 +251,8 @@
elseif($method_name === "putConversation"){ // test : OK
$id = !empty($url[4]) ? (int) $url[4] : null;
$newName = !empty($url[5]) ? (string) $url[5] : null;
$newName=urldecode($newName);
if ($id != null && $newName != null){
$conversationgw->putConversation($id,$newName);
http_response_code(200);
@ -281,8 +287,13 @@
$msg=!empty($url[4]) ? (string) $url[4] : null;
$idSender=!empty($url[5]) ? (int) $url[5] : null;
$idConv=!empty($url[6]) ? (int) $url[6] : null;
if ($msg != null && $idSender != null && $idConv != null){
$conversationgw->addMessageToConversation($msg,$idSender,$idConv);
$date=!empty($url[7]) ? (string) $url[7] : null;
$date=urldecode($date);
$msg=urldecode($msg);
if ($msg != null && $idSender != null && $idConv != null && $date!=null){
$id=$conversationgw->addMessageToConversation($msg,$idSender,$idConv, $date);
echo json_encode($id, JSON_PRETTY_PRINT);
http_response_code(200);
} else{
header("HTTP/1.0 400 id conv or message or sender not given");

@ -5,13 +5,13 @@ class Conversation{
// Object attributes
public string $id;
public string $name;
public $listMessages;
public $tabMessages;
public $listIdUsers;
public function __construct($_id,$_name,$_listMessages,$_listIdUsers){
public function __construct($_id,$_name,$_tabMessages,$_listIdUsers){
$this->id=$_id;
$this->name=$_name;
$this->listMessages=$_listMessages;
$this->tabMessages=$_tabMessages;
$this->listIdUsers=$_listIdUsers;
}
}

@ -3,14 +3,16 @@
class Message {
// Object attributes
public String $id;
public String $message;
public String $idSender;
public string $id;
public string $content;
public string $idSender;
public string $dateEnvoie;
public function __construct(String $_id, String $_message, String $_idSender){
public function __construct(string $_id, string $_content, string $_idSender, string $_dateEnvoie){
$this->id=$_id;
$this->message=$_message;
$this->content=$_content;
$this->idSender=$_idSender;
$this->dateEnvoie=$_dateEnvoie;
}
}

@ -4,14 +4,14 @@ class Skin{
public int $id;
public string $name;
public string $image;
public int $price;
public string $source;
public int $cost;
public function __construct(int $_id, string $_name, string $_image, int $_price){
public function __construct(int $_id, string $_name, string $_source, int $_cost){
$this->id=$_id;
$this->name=$_name;
$this->image=$_image;
$this->price=$_price;
$this->source=$_source;
$this->cost=$_cost;
}
}

@ -7,26 +7,26 @@ class User {
public string $username;
public string $password;
public string $nationality;
public string $sex;
public string $sexe;
public string $dateOfBirth;
public int $currentBobCoins;
public int $totalBobCoins;
public int $currentCoins;
public int $totalCoins;
public int $nbGamesPlayed;
public int $currentSkin;
public ?array $listSkin;
public Skin $currentSkin;
public ?array $tabSkin;
public function __construct(int $_id,string $_username,string $_password, string $_nationality,string $_sex, string $_dateOfBirth, int $_currentBobCoins, int $_totalBobCoins, int $_nbGamesPlayed, int $_currentSkin,?array $_listSkin){
public function __construct(int $_id,string $_username,string $_password, string $_nationality,string $_sexe, string $_dateOfBirth, int $_currentCoins, int $_totalCoins, int $_nbGamesPlayed, Skin $_currentSkin,?array $_tabSkin){
$this->id=$_id;
$this->username=$_username;
$this->password=$_password;
$this->nationality=$_nationality;
$this->sex=$_sex;
$this->sexe=$_sexe;
$this->dateOfBirth=$_dateOfBirth;
$this->currentBobCoins=$_currentBobCoins;
$this->totalBobCoins=$_totalBobCoins;
$this->currentCoins=$_currentCoins;
$this->totalCoins=$_totalCoins;
$this->nbGamesPlayed=$_nbGamesPlayed;
$this->currentSkin=$_currentSkin;
$this->listSkin=$_listSkin;
$this->tabSkin=$_tabSkin;
}
}

@ -0,0 +1,430 @@
-- phpMyAdmin SQL Dump
-- version 5.1.1
-- https://www.phpmyadmin.net/
--
-- Hôte : localhost:8889
-- Généré le : ven. 30 déc. 2022 à 14:14
-- Version du serveur : 5.7.34
-- Version de PHP : 7.4.21
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de données : `bobParty`
--
-- --------------------------------------------------------
--
-- Structure de la table `T_E_GAME_GAM`
--
CREATE TABLE `T_E_GAME_GAM` (
`PK_ID` int(11) NOT NULL,
`GAM_NAME` varchar(50) DEFAULT NULL,
`GAM_IMAGE` varchar(50) DEFAULT NULL,
`GAM_NB_PLAYER_MIN` int(11) DEFAULT NULL,
`GAM_NB_PLAYER_MAX` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Structure de la table `T_E_MATCH_MTC`
--
CREATE TABLE `T_E_MATCH_MTC` (
`PK_ID` int(11) NOT NULL,
`MTC_IN_GAME` tinyint(1) DEFAULT NULL,
`FK_GAME` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Structure de la table `T_H_CONVERSATION_COV`
--
CREATE TABLE `T_H_CONVERSATION_COV` (
`PK_ID` int(11) NOT NULL,
`COV_NAME` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Déchargement des données de la table `T_H_CONVERSATION_COV`
--
INSERT INTO `T_H_CONVERSATION_COV` (`PK_ID`, `COV_NAME`) VALUES
(32, 'Wesh la conv');
--
-- Déclencheurs `T_H_CONVERSATION_COV`
--
DELIMITER $$
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)
$$
DELIMITER ;
-- --------------------------------------------------------
--
-- Structure de la table `T_H_MESSAGE_MSG`
--
CREATE TABLE `T_H_MESSAGE_MSG` (
`PK_ID` int(11) NOT NULL,
`MSG_MESSAGE` text,
`FK_SENDER` int(11) DEFAULT NULL,
`MSG_DATEENVOIE` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Déchargement des données de la table `T_H_MESSAGE_MSG`
--
INSERT INTO `T_H_MESSAGE_MSG` (`PK_ID`, `MSG_MESSAGE`, `FK_SENDER`, `MSG_DATEENVOIE`) VALUES
(21, 'tom a créé une conversation', 1, '2022-12-29 00:00:00'),
(25, 'Salut test', 1, '2022-12-30 09:39:15'),
(57, 'Salut by', 1, '2022-12-30 11:01:17'),
(58, 'Wesh', 1, '2022-12-30 11:12:04'),
(59, 'Salut', 1, '2022-12-30 11:15:44'),
(60, 'Bonjour', 1, '2022-12-30 11:15:52'),
(61, 'Wesh', 1, '2022-12-30 11:16:25'),
(62, 'Bite', 1, '2022-12-30 11:17:38'),
(63, 'Cc', 2, '2022-12-30 11:21:04'),
(64, 'Cc', 2, '2022-12-30 11:21:06'),
(65, 'Bonjour', 2, '2022-12-30 11:24:58'),
(66, 'Hé ho', 2, '2022-12-30 11:25:02'),
(68, 'Salut ça va marcher', 1, '2022-12-30 11:55:21');
-- --------------------------------------------------------
--
-- Structure de la table `T_H_SKIN_SKI`
--
CREATE TABLE `T_H_SKIN_SKI` (
`PK_ID` int(11) NOT NULL,
`SKI_NAME` varchar(50) NOT NULL,
`SKI_IMAGE` varchar(200) NOT NULL,
`SKI_PRICE` varchar(30) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Déchargement des données de la table `T_H_SKIN_SKI`
--
INSERT INTO `T_H_SKIN_SKI` (`PK_ID`, `SKI_NAME`, `SKI_IMAGE`, `SKI_PRICE`) VALUES
(1, 'Bob', 'https://codefirst.iut.uca.fr/git/BOB_PARTEAM/BOB_PARTY/raw/branch/typescript/bob_party/assets/BobsSkins/BobClassic.png', '0'),
(2, 'Bob blue', 'https://codefirst.iut.uca.fr/git/BOB_PARTEAM/BOB_PARTY/raw/branch/typescript/bob_party/assets/BobsSkins/BobBlue.png', '100'),
(3, 'Bob green', 'https://codefirst.iut.uca.fr/git/BOB_PARTEAM/BOB_PARTY/raw/branch/typescript/bob_party/assets/BobsSkins/BobGreen.png', '100'),
(4, 'Bob BW', 'https://codefirst.iut.uca.fr/git/BOB_PARTEAM/BOB_PARTY/raw/branch/typescript/bob_party/assets/BobsSkins/BobBW.png', '100');
-- --------------------------------------------------------
--
-- Structure de la table `T_J_CONTAIN_MESSAGE_CMG`
--
CREATE TABLE `T_J_CONTAIN_MESSAGE_CMG` (
`FK_CONVERSATION` int(11) NOT NULL,
`FK_MESSAGE` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Déchargement des données de la table `T_J_CONTAIN_MESSAGE_CMG`
--
INSERT INTO `T_J_CONTAIN_MESSAGE_CMG` (`FK_CONVERSATION`, `FK_MESSAGE`) VALUES
(32, 21),
(32, 25),
(32, 57),
(32, 58),
(32, 59),
(32, 60),
(32, 61),
(32, 62),
(32, 63),
(32, 64),
(32, 65),
(32, 66),
(32, 68);
-- --------------------------------------------------------
--
-- Structure de la table `T_J_DISCUSS_DIS`
--
CREATE TABLE `T_J_DISCUSS_DIS` (
`FK_USER` int(11) NOT NULL,
`FK_CONVERSATION` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Déchargement des données de la table `T_J_DISCUSS_DIS`
--
INSERT INTO `T_J_DISCUSS_DIS` (`FK_USER`, `FK_CONVERSATION`) VALUES
(1, 32),
(2, 32),
(3, 32);
-- --------------------------------------------------------
--
-- Structure de la table `T_J_OWN_SKIN_OWN`
--
CREATE TABLE `T_J_OWN_SKIN_OWN` (
`FK_USER` int(11) NOT NULL,
`FK_SKIN` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Déchargement des données de la table `T_J_OWN_SKIN_OWN`
--
INSERT INTO `T_J_OWN_SKIN_OWN` (`FK_USER`, `FK_SKIN`) VALUES
(1, 1),
(1, 2),
(1, 3),
(2, 1),
(3, 1),
(6, 1),
(7, 1),
(8, 1),
(10, 1),
(11, 1);
-- --------------------------------------------------------
--
-- Structure de la table `T_J_PLAY_MATCH_PLM`
--
CREATE TABLE `T_J_PLAY_MATCH_PLM` (
`FK_USER` int(11) NOT NULL,
`FK_MATCH` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Structure de la table `T_S_USER_USR`
--
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_NATIONALITY` varchar(20) NOT NULL,
`USR_SEX` varchar(30) NOT NULL,
`USR_DATE_OF_BIRTH` date DEFAULT NULL,
`USR_CURRENT_NB_COINS` int(11) DEFAULT '0',
`USR_TOTAL_NB_COINS` int(11) DEFAULT '0',
`USR_NB_GAMES_PLAYED` int(11) DEFAULT '0',
`FK_CURRENT_SKIN` int(11) DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Déchargement des données de la table `T_S_USER_USR`
--
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, 'tom', 't', 'Anglais(e)', 'M', '2003-07-01', 100, 600, 12, 2),
(2, 'leilla20', 'l', 'France', 'F', '2003-11-22', 0, 0, 0, 1),
(3, 'test', 't', 'Français(e)', 'H', '1999-12-27', 0, 0, 0, 1),
(6, 'LEBg', 'belleBite63*', 'Espagnol(e)', 'Autre', '2001-12-27', 0, 0, 0, 1),
(7, 'DYLAN', 'argGR65**', 'Anglais(e)', 'Autre', '2002-12-27', 0, 0, 0, 1),
(8, 'Marche', 'je45tE**', 'Anglais(e)', 'Femme', '1999-12-27', 0, 0, 0, 1),
(10, 'dsqdz', 'AEZQzze1*', 'Francais(e)', 'null', '2005-12-27', 0, 0, 0, 1),
(11, 'qdsqdz', 'dqzA12****', 'Francais(e)', 'Homme', '2002-12-27', 0, 0, 0, 1);
--
-- Déclencheurs `T_S_USER_USR`
--
DELIMITER $$
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)
$$
DELIMITER ;
--
-- Index pour les tables déchargées
--
--
-- Index pour la table `T_E_GAME_GAM`
--
ALTER TABLE `T_E_GAME_GAM`
ADD PRIMARY KEY (`PK_ID`),
ADD UNIQUE KEY `GAM_NAME` (`GAM_NAME`,`GAM_IMAGE`);
--
-- Index pour la table `T_E_MATCH_MTC`
--
ALTER TABLE `T_E_MATCH_MTC`
ADD PRIMARY KEY (`PK_ID`),
ADD KEY `FK_GAME` (`FK_GAME`);
--
-- Index pour la table `T_H_CONVERSATION_COV`
--
ALTER TABLE `T_H_CONVERSATION_COV`
ADD PRIMARY KEY (`PK_ID`);
--
-- Index pour la table `T_H_MESSAGE_MSG`
--
ALTER TABLE `T_H_MESSAGE_MSG`
ADD PRIMARY KEY (`PK_ID`),
ADD KEY `FK_SENDER` (`FK_SENDER`);
--
-- Index pour la table `T_H_SKIN_SKI`
--
ALTER TABLE `T_H_SKIN_SKI`
ADD PRIMARY KEY (`PK_ID`),
ADD UNIQUE KEY `SKI_NAME` (`SKI_NAME`),
ADD UNIQUE KEY `SKI_IMAGE` (`SKI_IMAGE`);
--
-- Index pour la table `T_J_CONTAIN_MESSAGE_CMG`
--
ALTER TABLE `T_J_CONTAIN_MESSAGE_CMG`
ADD PRIMARY KEY (`FK_CONVERSATION`,`FK_MESSAGE`),
ADD KEY `FK_MESSAGE` (`FK_MESSAGE`);
--
-- Index pour la table `T_J_DISCUSS_DIS`
--
ALTER TABLE `T_J_DISCUSS_DIS`
ADD PRIMARY KEY (`FK_USER`,`FK_CONVERSATION`),
ADD KEY `FK_CONVERSATION` (`FK_CONVERSATION`);
--
-- Index pour la table `T_J_OWN_SKIN_OWN`
--
ALTER TABLE `T_J_OWN_SKIN_OWN`
ADD PRIMARY KEY (`FK_SKIN`,`FK_USER`),
ADD KEY `FK_USER` (`FK_USER`);
--
-- Index pour la table `T_J_PLAY_MATCH_PLM`
--
ALTER TABLE `T_J_PLAY_MATCH_PLM`
ADD PRIMARY KEY (`FK_USER`,`FK_MATCH`),
ADD KEY `FK_MATCH` (`FK_MATCH`);
--
-- Index pour la table `T_S_USER_USR`
--
ALTER TABLE `T_S_USER_USR`
ADD PRIMARY KEY (`PK_ID`),
ADD UNIQUE KEY `USR_USERNAME` (`USR_USERNAME`),
ADD KEY `FK_CURRENT_SKIN` (`FK_CURRENT_SKIN`);
--
-- AUTO_INCREMENT pour les tables déchargées
--
--
-- AUTO_INCREMENT pour la table `T_E_GAME_GAM`
--
ALTER TABLE `T_E_GAME_GAM`
MODIFY `PK_ID` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT pour la table `T_E_MATCH_MTC`
--
ALTER TABLE `T_E_MATCH_MTC`
MODIFY `PK_ID` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT pour la table `T_H_CONVERSATION_COV`
--
ALTER TABLE `T_H_CONVERSATION_COV`
MODIFY `PK_ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=47;
--
-- AUTO_INCREMENT pour la table `T_H_MESSAGE_MSG`
--
ALTER TABLE `T_H_MESSAGE_MSG`
MODIFY `PK_ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=69;
--
-- AUTO_INCREMENT pour la table `T_H_SKIN_SKI`
--
ALTER TABLE `T_H_SKIN_SKI`
MODIFY `PK_ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT pour la table `T_S_USER_USR`
--
ALTER TABLE `T_S_USER_USR`
MODIFY `PK_ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
--
-- Contraintes pour les tables déchargées
--
--
-- Contraintes pour la table `T_E_MATCH_MTC`
--
ALTER TABLE `T_E_MATCH_MTC`
ADD CONSTRAINT `t_e_match_mtc_ibfk_1` FOREIGN KEY (`FK_GAME`) REFERENCES `T_E_GAME_GAM` (`PK_ID`);
--
-- Contraintes pour la table `T_H_MESSAGE_MSG`
--
ALTER TABLE `T_H_MESSAGE_MSG`
ADD CONSTRAINT `t_h_message_msg_ibfk_1` FOREIGN KEY (`FK_SENDER`) REFERENCES `T_S_USER_USR` (`PK_ID`);
--
-- Contraintes pour la table `T_J_CONTAIN_MESSAGE_CMG`
--
ALTER TABLE `T_J_CONTAIN_MESSAGE_CMG`
ADD CONSTRAINT `t_j_contain_message_cmg_ibfk_1` FOREIGN KEY (`FK_CONVERSATION`) REFERENCES `T_H_CONVERSATION_COV` (`PK_ID`) ON DELETE CASCADE,
ADD CONSTRAINT `t_j_contain_message_cmg_ibfk_2` FOREIGN KEY (`FK_MESSAGE`) REFERENCES `T_H_MESSAGE_MSG` (`PK_ID`) ON DELETE CASCADE;
--
-- Contraintes pour la table `T_J_DISCUSS_DIS`
--
ALTER TABLE `T_J_DISCUSS_DIS`
ADD CONSTRAINT `t_j_discuss_dis_ibfk_1` FOREIGN KEY (`FK_USER`) REFERENCES `T_S_USER_USR` (`PK_ID`) ON DELETE CASCADE,
ADD CONSTRAINT `t_j_discuss_dis_ibfk_2` FOREIGN KEY (`FK_CONVERSATION`) REFERENCES `T_H_CONVERSATION_COV` (`PK_ID`) ON DELETE CASCADE;
--
-- Contraintes pour la table `T_J_OWN_SKIN_OWN`
--
ALTER TABLE `T_J_OWN_SKIN_OWN`
ADD CONSTRAINT `t_j_own_skin_own_ibfk_1` FOREIGN KEY (`FK_USER`) REFERENCES `T_S_USER_USR` (`PK_ID`) ON DELETE CASCADE,
ADD CONSTRAINT `t_j_own_skin_own_ibfk_2` FOREIGN KEY (`FK_SKIN`) REFERENCES `T_H_SKIN_SKI` (`PK_ID`);
--
-- Contraintes pour la table `T_J_PLAY_MATCH_PLM`
--
ALTER TABLE `T_J_PLAY_MATCH_PLM`
ADD CONSTRAINT `t_j_play_match_plm_ibfk_1` FOREIGN KEY (`FK_USER`) REFERENCES `T_S_USER_USR` (`PK_ID`) ON DELETE CASCADE,
ADD CONSTRAINT `t_j_play_match_plm_ibfk_2` FOREIGN KEY (`FK_MATCH`) REFERENCES `T_E_MATCH_MTC` (`PK_ID`) ON DELETE CASCADE;
--
-- Contraintes pour la table `T_S_USER_USR`
--
ALTER TABLE `T_S_USER_USR`
ADD CONSTRAINT `t_s_user_usr_ibfk_1` FOREIGN KEY (`FK_CURRENT_SKIN`) REFERENCES `T_H_SKIN_SKI` (`PK_ID`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

@ -1,16 +1,21 @@
import { FakeSaverConversation } from "./src/services/conversationService/fakeSaverConversation";
import { LoaderConversationApi } from "./src/services/conversationService/loaderConversationApi";
import ManagerConversation from "./src/services/conversationService/managerConversation";
import { SaverConversationApi } from "./src/services/conversationService/saverConversationApi";
import LoaderGameApi from "./src/services/gameService/loaderGameApi";
import ManagerGame from "./src/services/gameService/managerGame";
import LoaderMatchApi from "./src/services/matchServices/loaderMatchApi";
import ManagerMatch from "./src/services/matchServices/managerMatch";
import SaverMatchApi from "./src/services/matchServices/saverMatchApi";
import LoaderSkinApi from "./src/services/skinService/loaderSkinApi";
import ManagerSkin from "./src/services/skinService/managerSkin";
import FakeSaverUser from "./src/services/userServices/fakeSaverUser";
import LoaderUserApi from "./src/services/userServices/loaderUserApi";
import ManagerUser from "./src/services/userServices/managerUser";
import SaverUserApi from "./src/services/userServices/saverUserApi";
export const MANAGER_USER = new ManagerUser(new LoaderUserApi, new FakeSaverUser);
export const MANAGER_CONVERSATION = new ManagerConversation(new LoaderConversationApi, new FakeSaverConversation);
export const MANAGER_USER = new ManagerUser(new LoaderUserApi, new SaverUserApi);
export const MANAGER_CONVERSATION = new ManagerConversation(new LoaderConversationApi, new SaverConversationApi);
export const MANAGER_MATCH = new ManagerMatch(new LoaderMatchApi, new SaverMatchApi);
export const MANAGER_GAME = new ManagerGame(new LoaderGameApi);
export const MANAGER_SKIN = new ManagerSkin(new LoaderSkinApi);

@ -6,17 +6,17 @@ const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const connectUsers = [];
io.on('connection', (socket) => {
console.log(socket.id)
socket.on('inConv', (conv) => {
socket.join("C" + conv.id);
console.log("C"+conv.id);
});
socket.on("messageSent", (conv) =>{
console.log("C"+conv.id);
socket.to("C"+conv.id).emit("messageReceived");
console.log("Message envoyé");
});

@ -1,4 +1,4 @@
const { io } = require("socket.io-client");
export const socket = io("http://192.168.1.25:3000");
export const socket = io("http://192.168.1.54:3000");

@ -7,9 +7,8 @@ import React from "react"
*/
import styles from './style/BotBar.style';
import { useStoreStore } from "../context/storeContext";
import tabSkinApp from "../constSkin";
import { useConversationStore } from "../context/conversationContext";
import { MANAGER_CONVERSATION, MANAGER_USER } from "../../appManagers";
import { MANAGER_CONVERSATION, MANAGER_SKIN, MANAGER_USER } from "../../appManagers";
import { socket } from "../../socketConfig";
/*
@ -50,7 +49,7 @@ export const BotBar:
const handleStoreChange = useCallback(async () => {
let tabSkinStore = [...tabSkinApp];
let tabSkinStore = [...MANAGER_SKIN.getTabSkin()];
MANAGER_USER.getCurrentUser()?.getTabSkin()?.forEach(skin => {
for (let i = 0; i < tabSkinStore.length; i++) {
if (skin.isEqual(tabSkinStore[i])) {

@ -9,8 +9,9 @@ import { Conversation } from "../core/conversation"
*/
import styles from "./style/ConverstationPreviewComponent.style"
import { SkinComponent } from "./Skin"
import { MANAGER_USER } from "../../appManagers"
import { MANAGER_CONVERSATION, MANAGER_USER } from "../../appManagers"
import { User } from "../core/User/user"
import { useConversationStore } from "../context/conversationContext"
export const ConversationPreviewComponent :
/* Parameters :
@ -19,10 +20,13 @@ export const ConversationPreviewComponent :
FC<{conv: Conversation, navigation: any}> =
({conv, navigation}) =>
{
const setCurrentConv = useConversationStore((state) => state.setCurrentConv);
const user1 = MANAGER_USER.getCurrentUser();
let tmp;
if (conv.getTabUser()[0] === user1) tmp = conv.getTabUser()[1];
if (user1?.isEqual(conv.getTabUser()[0])) tmp = conv.getTabUser()[1];
else tmp = conv.getTabUser()[0];
const user2 = tmp;
@ -30,13 +34,13 @@ FC<{conv: Conversation, navigation: any}> =
return(
<Pressable onPress={() => navigation.navigate(Conversation)}>
<Pressable onPress={() => {MANAGER_CONVERSATION.setCurrentConv(conv); setCurrentConv(conv) ;navigation.navigate(Conversation)}}>
<View style={styles.conv}>
<View>
<SkinComponent skin={user2.getCurrentSkin()} state='icon' nav={navigation}/>
</View>
<View style={{marginLeft: '5%', justifyContent: 'space-evenly'}}>
<Text style={styles.textNom}>{conv.getLastMessage().getMessageSender().getUsername()}</Text>
<Text style={styles.textNom}>{conv.getName()}</Text>
<Text style={styles.textMess}>{conv.getLastMessage().getMessageContent()}</Text>
</View>
</View>

@ -21,8 +21,7 @@ FC<{mess: Message}> =
({mess}) =>
{
let messStyle;
const user1 = MANAGER_USER.getCurrentUser();
if (mess.getMessageSender() === user1){
if (MANAGER_USER.getCurrentUser()?.isEqual(mess.getMessageSender())){
return(
<View style={styles.mainRightView}>

@ -12,8 +12,7 @@ import { useUserStore } from "../context/userContext"
import { UserCoinsModifier } from "../core/User/userCoinsModifier"
import UserSkinModifier from "../core/User/userSkinModifier"
import { useStoreStore } from "../context/storeContext"
import tabSkinApp from "../constSkin"
import { MANAGER_USER } from "../../appManagers"
import { MANAGER_SKIN, MANAGER_USER } from "../../appManagers"
@ -50,9 +49,7 @@ export const SkinComponent:
const handleStoreChange = useCallback(async () => {
let tabSkinStore = [...tabSkinApp];
// const tmp=MANAGER_USER.getCurrentUser()?.getTabSkin();
// if (tmp!=undefined){
let tabSkinStore = [...MANAGER_SKIN.getTabSkin()];
MANAGER_USER.getCurrentUser()?.getTabSkin()?.forEach(skin => {
for (let i = 0; i < tabSkinStore.length; i++) {
if (skin.isEqual(tabSkinStore[i])) {
@ -61,9 +58,6 @@ export const SkinComponent:
}
});
setTabSkin(tabSkinStore);
//}
}, []);
async function buySkin(skin: Skin) {

@ -6,14 +6,20 @@ import { Conversation } from "../core/conversation";
// Define store types
interface ConversationState {
tabConv: Conversation[] | null;
currentConv: Conversation | null;
setTabConv: (tabConv: Conversation[]) => void;
resetTabConv: () => void;
setCurrentConv: (currentConv: Conversation | null) => void;
resetCurrentConv: () => void;
}
// Define store data and methods
export const useConversationStore = create<ConversationState>()((set, get) => ({
export const useConversationStore = create<ConversationState>()((set) => ({
tabConv: null,
currentConv: null,
setTabConv: (tabConv) => set((state) => ({ tabConv: tabConv })),
resetTabConv: () => set((state) => ({tabConv: null})),
setCurrentConv: (currentConv) => set((state) => ({ currentConv: currentConv })),
resetCurrentConv: () => set((state) => ({currentConv: null})),
}));

@ -1,7 +1,6 @@
import React from "react";
import create from "zustand";
import { MANAGER_USER } from "../../App";
import tabSkinApp from "../constSkin";
import { MANAGER_SKIN } from "../../appManagers";
import { Skin } from "../core/Skin";
import { User } from "../core/User/user";
@ -15,8 +14,8 @@ interface StoreState {
// Define store data and methods
export const useStoreStore = create<StoreState>()((set, get) => ({
tabSkin: tabSkinApp,
tabSkin: [],
setTabSkin: (tabSkin) => set((state) => ({ tabSkin: tabSkin })),
resetTabSkin: () => set((state) => ({ tabSkin: tabSkinApp })),
resetTabSkin: () => set((state) => ({ tabSkin: [] })),
}));

@ -4,17 +4,8 @@ import tabUS from "../../constUser";
import { User } from '../User/user';
import { updateAlreadyUsedPseudo,updateImpossibleBirthDate,updateUndefinedBirthDate,updateUndefinedNationality,updateTooLongPseudo,updateUndefinedPseudo,updateUndefinedSex, updateTooShortPassword, updateInvalidPassword, updateInvalidPseudo, updateUndefinedPassword } from '../../redux/features/credentialErrorsSlice';
function max(array: User[]){
let max: string = "";
for (let index = 0; index < array.length; index++) {
const element = array[index].getId();
if (element > max) max = element;
}
return max;
}
export const checkNewUserValidity = (login: string, password: string, dateOfBirth: Date, nationality: string, sexe: string, dispatch: any, nav: any) => {
export const checkNewUserValidity = (login: string, password: string, dateOfBirth: Date, nationality: string, sexe: string, dispatch: any) => {
let actualDate : number = Date.now();
let givenDate : number = dateOfBirth.getTime();
let passwordRegex : RegExp = /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-])(?!.*?[.\n\\{}[\],]).{8,}$/;
@ -33,11 +24,11 @@ export const checkNewUserValidity = (login: string, password: string, dateOfBirt
dispatch(updateUndefinedBirthDate(true));
break;
case (nationality == ''):
case (nationality === '' || nationality==null):
dispatch(updateUndefinedNationality(true))
break;
case (sexe == ''):
case (sexe === '' || sexe==null):
dispatch(updateUndefinedSex(true));
break;
@ -64,8 +55,7 @@ export const checkNewUserValidity = (login: string, password: string, dateOfBirt
break;
default:
const newUser : User = new User(0,login,password,nationality,sexe,dateOfBirth);
dispatch(loginUser(newUser));
nav.navigate('HomeTab');
return true;
}
return false;
};

@ -8,12 +8,14 @@ export class UserCoinsModifier{
u.setCurrentCoins(u.getCurrentCoins()+coins);
u.setTotalCoins(u.getTotalCoins()+coins);
await MANAGER_USER.getsaverUser().updateUser(u);
MANAGER_USER.setCurrentUser(u);
}
async removeCoins(u:User, coins:number): Promise<boolean>{
if (u.getCurrentCoins()>=coins){
u.setCurrentCoins(u.getCurrentCoins()-coins);
await MANAGER_USER.getsaverUser().updateUser(u);
MANAGER_USER.setCurrentUser(u);
return true;
}
return false;
@ -22,5 +24,6 @@ export class UserCoinsModifier{
async changeCurrentCoins(u:User, coins:number){
u.setCurrentCoins(coins);
await MANAGER_USER.getsaverUser().updateUser(u);
MANAGER_USER.setCurrentUser(u);
}
}

@ -1,7 +1,4 @@
import { User } from "./user";
import tabSkinApp from "../../constSkin";
import { Conversation } from "../conversation";
import ManagerUser from "../../services/userServices/managerUser";
import { MANAGER_USER } from "../../../appManagers";
export class UserCreator{

@ -6,20 +6,24 @@ export default class UserModificationManager{
async changePassword(user:User, password:string){
user.setPassword(password);
await MANAGER_USER.getsaverUser().updateUser(user);
MANAGER_USER.setCurrentUser(user);
}
async changeUsername(user:User, username:string){
user.setUsername(username);
await MANAGER_USER.getsaverUser().updateUser(user);
MANAGER_USER.setCurrentUser(user);
}
async changeNationality(user:User, nationality:string){
user.setNationality(nationality);
await MANAGER_USER.getsaverUser().updateUser(user);
MANAGER_USER.setCurrentUser(user);
}
async changeSexe(user:User, sexe:string){
user.setSexe(sexe);
await MANAGER_USER.getsaverUser().updateUser(user);
MANAGER_USER.setCurrentUser(user);
}
}

@ -6,7 +6,7 @@ import { User } from './user'
export default class UserSkinModifier{
async addSkin(user:User, skin:Skin){
user.addSkin(skin);
await MANAGER_USER.getsaverUser().updateUser(user);
await MANAGER_USER.getsaverUser().addSkinList(user, skin);
}
async changeCurrentSkin(user:User, skin:Skin){

@ -7,6 +7,10 @@ import { BotBar } from '../components/BotBar';
import { FlatList } from 'react-native-gesture-handler';
import { ConversationPreviewComponent } from '../components/ConversationPreviewComponent';
import { useConversationStore } from '../context/conversationContext';
import { io } from 'socket.io-client';
import { socket } from '../../socketConfig';
import { MANAGER_CONVERSATION, MANAGER_USER } from '../../appManagers';
import { Message } from '../core/message';
function Chat(props: { navigation: any; }) {
const { navigation } = props

@ -1,5 +1,5 @@
import { StatusBar } from 'expo-status-bar'
import {KeyboardAvoidingView, Platform, TextInput, View} from 'react-native'
import {KeyboardAvoidingView, NativeSyntheticEvent, Platform, TextInput, TextInputSubmitEditingEventData, View} from 'react-native'
import React, { useCallback } from 'react';
import stylesScreen from './style/screens.style';
import { TopBar } from '../components/TopBar';
@ -7,13 +7,43 @@ import { BotBar } from '../components/BotBar';
import { FlatList } from 'react-native-gesture-handler';
import { MANAGER_CONVERSATION, MANAGER_USER } from '../../appManagers';
import { MessageComponent } from '../components/MessageComponent';
import { useConversationStore } from '../context/conversationContext';
import { Message } from '../core/message';
import { Conversation } from '../core/conversation';
import { socket } from '../../socketConfig';
function Conversation(props: { navigation: any; }) {
function ConversationScreen(props: { navigation: any; }) {
const { navigation } = props
const chosenConversation = MANAGER_CONVERSATION.getCurrentTabConv()[0].getTabMessage();
const [text, onChangeText] = React.useState("");
const setTabConv = useConversationStore((state) => state.setTabConv);
async function sendMessage(e:NativeSyntheticEvent<TextInputSubmitEditingEventData>){
if (e.nativeEvent.text!=="" || e.nativeEvent.text.match(/^ *$/) === null){
const tmpUs=MANAGER_USER.getCurrentUser();
const tmpConv=MANAGER_CONVERSATION.getCurrentConv();
if (tmpUs!==null && tmpConv!==null){
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);
const index=MANAGER_CONVERSATION.getTabConv().findIndex(trouveIndex);
const tmp=MANAGER_CONVERSATION.getCurrentConv();
if (tmp!==null){
MANAGER_CONVERSATION.getTabConv()[index]=tmp;
setTabConv(MANAGER_CONVERSATION.getTabConv());
socket.emit("messageSent", tmp);
onChangeText("");
}
}
});
}
}
}
const renderMessage = ({ item }) => {
return (
@ -24,13 +54,13 @@ function Conversation(props: { navigation: any; }) {
<KeyboardAvoidingView behavior={Platform.OS == "ios" ? "padding" : "height"} style={stylesScreen.container}>
<View style={stylesScreen.bodyStart}>
<FlatList
data={chosenConversation.reverse()}
data={useConversationStore().currentConv?.getTabMessage().reverse()}
renderItem={renderMessage}
keyExtractor={item => item.getMessageId().toString()}
style={{flexDirection:'column-reverse'}}
/>
<TextInput
<TextInput
style={{height: '7%',
width: '90%',
borderRadius: '15%',
@ -41,13 +71,15 @@ function Conversation(props: { navigation: any; }) {
marginTop: '3%',
}}
placeholder='Votre message...'
onChangeText={(val) => console.log("camarche")}
returnKeyType="send"
onSubmitEditing={() => console.log("oh oui")}
onChangeText={onChangeText}
value={text}
onSubmitEditing={(val) => {sendMessage(val)}}
blurOnSubmit
/>
</View>
</KeyboardAvoidingView>
);
}
export default Conversation
export default ConversationScreen

@ -7,7 +7,10 @@ import { BotBar } from '../components/BotBar';
import { Conversation } from '../core/conversation';
import { ButtonGameTypeChoice } from '../components/ButtonGameTypeChoice';
import { useGameStore } from '../context/gameContext';
import { MANAGER_GAME } from '../../appManagers';
import { MANAGER_CONVERSATION, MANAGER_GAME, MANAGER_USER } from '../../appManagers';
import { socket } from '../../socketConfig';
import { useConversationStore } from '../context/conversationContext';
import { Message } from '../core/message';
@ -18,79 +21,37 @@ function Home(props: { navigation: any; }) {
const { navigation } = props
const setTabGame = useGameStore((state) => state.setTabGame);
const setTabGameSolo = useGameStore((state) => state.setTabGameSolo);
const setTabGameMulti = useGameStore((state) => state.setTabGameMulti);
/*
const handleGame = useCallback(async (typeJeu: string) => {
switch(typeJeu){
case 'solo':
let tabSolo:Game[]=[]
let tmp=MANAGER_GAME.getTabGameSolo();
if (tmp==null){
let tabAll=MANAGER_GAME.getTabGame();
if (tabAll==null){
await MANAGER_GAME.getLoaderGame().loadAllGame().then((res) => {
MANAGER_GAME.setTabGame(res);
setTabGame(res);
});
}
tabAll?.forEach(game =>{
if (game.getNbPlayerMax()==1){
tabSolo.push(game);
}
})
MANAGER_GAME.setTabGameSolo(tabSolo);
setTabGameSolo(tabSolo);
navigation.navigate('GameChoiceTab')
}
else{
navigation.navigate('GameChoiceTab')
}
case 'multi':
let tabMulti:Game[]=[]
let tkt=MANAGER_GAME.getTabGameSolo();
if (tkt==null){
let tabAll=MANAGER_GAME.getTabGame();
if (tabAll==null){
await MANAGER_GAME.getLoaderGame().loadAllGame().then((res) => {
MANAGER_GAME.setTabGame(res);
setTabGame(res);
});
}
tabAll?.forEach(game =>{
if (game.getNbPlayerMax()==1){
tabSolo.push(game);
}
})
MANAGER_GAME.setTabGameMulti(tabMulti);
setTabGameMulti(tabMulti);
navigation.navigate('GameChoiceTab')
}
else{
navigation.navigate('GameChoiceTab')
}
}
}, []);
*/
const setTabConv = useConversationStore((state) => state.setTabConv);
const setCurrentConv = useConversationStore((state) => state.setCurrentConv);
const handleGame = useCallback(async (typeJeu: string) => {
const tmp = MANAGER_GAME.getTabGame();
if (tmp === null) {
await MANAGER_GAME.getLoaderGame().loadAllGame().then((res) => {
MANAGER_GAME.setTabGame(res);
setTabGame(res);
navigation.navigate('GameChoiceTab')
});
}
else {
navigation.navigate('GameChoiceTab')
//It has to be in the home page that way the database will reload the conversations when the user receive a message een if he is in another page
socket.on("messageReceived", async () =>{
console.log("Message reçu");
await handleConversationLoad();
});
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());
}
});
}
}, []);
}
return (
<View style={stylesScreen.container}>
@ -101,11 +62,11 @@ function Home(props: { navigation: any; }) {
<View style={stylesScreen.bodyCenter}>
<ButtonGameTypeChoice
title='Jouer Seul'
onPress={() => { handleGame("solo") }}
onPress={() => { navigation.navigate('GameChoiceTab') }}
/>
<ButtonGameTypeChoice
title='Défier mes amis'
onPress={() => handleGame("multi")}
onPress={() => navigation.navigate('GameChoiceTab')}
/>
</View>
<BotBar

@ -79,8 +79,7 @@ function Settings(props: { navigation: any; }) {
<View>
<View>
<Text style={styles.text}>Pseudo: {useUserStore().user?.getUsername()}</Text>
<ButtonGreySmall onPress={() => {console.log(dialogPseudoVisible);
;setDialogPseudoVisible(true)}} title='Changer le pseudo'/>
<ButtonGreySmall onPress={() => {setDialogPseudoVisible(true)}} title='Changer le pseudo'/>
</View>
<View>
<Text style={styles.text}>Mot de passe: {useUserStore().user?.getPassword()}</Text>

@ -9,9 +9,10 @@ import { RootState } from '../redux/store';
import { updateIncorrectCredentials } from '../redux/features/credentialErrorsSlice';
import Dialog from "react-native-dialog";
import { useUserStore } from '../context/userContext';
import { MANAGER_CONVERSATION, MANAGER_USER } from '../../appManagers';
import { MANAGER_CONVERSATION, MANAGER_GAME, MANAGER_SKIN, MANAGER_USER } from '../../appManagers';
import { socket } from "../../socketConfig";
import { useConversationStore } from '../context/conversationContext';
import { useGameStore } from '../context/gameContext';
@ -19,8 +20,13 @@ import { useConversationStore } from '../context/conversationContext';
function SignIn(props: { navigation: any; }) {
const { navigation } = props
const setUser = useUserStore((state) => state.setUser);
const setTabConv = useConversationStore((state) => state.setTabConv);
const setTabGame = useGameStore((state) => state.setTabGame);
const setTabGameSolo = useGameStore((state) => state.setTabGameSolo);
const setTabGameMulti = useGameStore((state) => state.setTabGameMulti);
const errorList = useSelector((state: RootState) => state.credentialErrors.loginErrorList);
const [pseudo, setPseudo] = useState('');
@ -38,18 +44,28 @@ function SignIn(props: { navigation: any; }) {
if (waitConnect==0){
waitConnect=1;
await MANAGER_USER.getLoaderUser().loadByUsernamePassword(username, password).then(async (res) => {
await MANAGER_USER.getLoaderUser().loadByUsernamePassword(username, password).then(async (res) => {
if (res!=null){
MANAGER_USER.setCurrentUser(res);
setUser(MANAGER_USER.getCurrentUser());
socket.emit("signIn", res);
await handleSkinLoad();
await handleConversationLoad();
MANAGER_CONVERSATION.getCurrentTabConv()?.forEach( conv =>{
await handleGameLoad();
/*
const conv=await MANAGER_CONVERSATION.getsaverConversation().saveConversation("Wesh la conv", res, [2,3], res.getUsername() + " a créé une conversation", new Date());
if (conv!=null){
MANAGER_CONVERSATION.getTabConv().push(conv);
}
*/
MANAGER_CONVERSATION.getTabConv()?.forEach( conv =>{
socket.emit("inConv", conv);
socket.emit("messageSent", conv);
});
navigation.navigate('HomeTab');
navigation.navigate('HomeTab');
}
else{
Alert.alert("Incorrect Username or Password");
}
});
@ -62,16 +78,37 @@ function SignIn(props: { navigation: any; }) {
const tmp = MANAGER_USER.getCurrentUser();
if (tmp !== null) {
await MANAGER_CONVERSATION.getLoaderConversation().loadByUser(tmp).then((res) => {
MANAGER_CONVERSATION.setCurrentTabConv(res);
MANAGER_CONVERSATION.setTabConv(res);
setTabConv(res);
});
}
}
}
async function handleSkinLoad(){
MANAGER_SKIN.setTabSkin(await MANAGER_SKIN.getLoaderSkin().loadAllSkin());
}
socket.on("messageReceived", () =>{
console.log("Message reçu");
handleConversationLoad();
});
async function handleGameLoad(){
MANAGER_GAME.setTabGame(await MANAGER_GAME.getLoaderGame().loadAllGame());
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());
}
return (

@ -4,18 +4,20 @@ import React, { useState } from 'react';
import stylesScreen from './style/screens.style'
import { TextInput } from 'react-native-gesture-handler';
import { ButtonGameTypeChoice } from '../components/ButtonGameTypeChoice';
import styleScreen from "./style/screens.style";
import styles from "./style/SignUp.style";
import { useDispatch, useSelector } from 'react-redux';
import { checkNewUserValidity } from '../core/Auth/newUser';
import DateTimePicker, { DateTimePickerEvent } from '@react-native-community/datetimepicker';
import RNPickerSelect from "react-native-picker-select";
import { PickerGreySmall } from '../components/PickerGreySmall';
import { loginUser } from '../redux/features/currentUserSlice';
import { RootState } from '../redux/store';
import { updateImpossibleBirthDate, updateInvalidPassword, updateInvalidPseudo, updateTooLongPseudo, updateTooShortPassword, updateUndefinedBirthDate, updateUndefinedNationality, updateUndefinedPassword, updateUndefinedPseudo, updateUndefinedSex } from '../redux/features/credentialErrorsSlice';
import { getSystemErrorMap } from 'util';
import RNDateTimePicker from '@react-native-community/datetimepicker';
import { 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';
function SignUp(props: { navigation: any; }) {
const { navigation } = props
@ -24,6 +26,8 @@ function SignUp(props: { navigation: any; }) {
const [password, setPassword] = useState('');
const [date, setDate] = useState(new Date())
const setUser = useUserStore((state) => state.setUser);
function onDateSelected(event : DateTimePickerEvent, value : Date | undefined) {
if (value != undefined) {
@ -83,7 +87,7 @@ function SignUp(props: { navigation: any; }) {
break;
case (errorList.invalidPassword):
Alert.alert("Votre pseudo doit contenir au moins une majuscule, une majuscule, un chiffre et un caractère spécial (#?!@$%^&*-)");
Alert.alert("Votre Password doit contenir au moins une majuscule, une majuscule, un chiffre et un caractère spécial (#?!@$%^&*-)");
dispatch(updateInvalidPassword(false));
break;
@ -97,15 +101,11 @@ function SignUp(props: { navigation: any; }) {
<View style={stylesScreen.container}>
<View style={stylesScreen.bodyCenter}>
<View style={{width: '60%', alignItems: 'center'}}>
<Text style={styles.text}>Login</Text>
<TextInput style={styles.textInput} placeholder='Login' onChangeText={(val) => setPseudo(val)} autoCapitalize='none' />
</View>
<Text style={styles.text}>Login</Text>
<TextInput style={styles.textInput} placeholder='Login' onChangeText={(val) => setPseudo(val) } autoCapitalize='none' />
<View style={{width: '60%', alignItems: 'center'}}>
<Text style={styles.text}>Password</Text>
<TextInput style={styles.textInput} placeholder='Password' onChangeText={(val) => setPassword(val)} autoCapitalize='none' />
</View>
<Text style={styles.text}>Password</Text>
<TextInput style={styles.textInput} placeholder='Password' onChangeText={(val) => setPassword(val)} autoCapitalize='none' secureTextEntry={true}/>
<View style={{width: '70%', alignItems: 'center'}}>
@ -118,14 +118,14 @@ function SignUp(props: { navigation: any; }) {
<View style={{width: '60%', alignItems: 'center'}}>
<Text style={styles.text}>Nationalité</Text>
<PickerGreySmall title='Choisir la Nationalité' valueChange={(value:string) =>
setSelectedNationality(value)} values={["Français", "Anglais"]} />
setSelectedNationality(value)} values={[ { label: 'France', value: 'Francais(e)' }, { label: 'Royaume-Uni', value: 'Anglais(e)' }, { label: 'Espagne', value: 'Espagnol(e)' }, { label: 'Belgique', value: 'Belge' }, { label: 'Allemagne', value: 'Allemand(e)' }, ]} />
</View>
<View style={{width: '60%', alignItems: 'center'}}>
<Text style={styles.text}>Sexe</Text>
<PickerGreySmall title='Choisir le sexe' valueChange={(value:string) => setSelectedSex(value)} values={["Homme","Femme", "Autre"]} />
<PickerGreySmall title='Choisir le sexe' valueChange={(value:string) => setSelectedSex(value)} values={[ { label: 'Homme', value: 'Homme' }, { label: 'Femme', value: 'Femme' }, {label: 'Autre', value: 'Autre' } ]} />
</View>
<Pressable style={styles.button} onPress={() => checkNewUserValidity(pseudo,password,date,selectedNationality,selectedSex, dispatch, navigation)}>
<Pressable style={styles.button} onPress={() => createAccount(pseudo,password,date,selectedNationality,selectedSex, dispatch, navigation)}>
<Text style={styles.text}>S'inscrire</Text>
</Pressable>
<Pressable onPress={() => navigation.navigate('SignIn')}>
@ -134,6 +134,21 @@ function SignUp(props: { navigation: any; }) {
</View>
</View>
);
async function createAccount(pseudo: string,password: string,date: Date,selectedNationality: string,selectedSex: string, dispatch: any, navigation: any) {
if (checkNewUserValidity(pseudo,password,date,selectedNationality,selectedSex, dispatch)){
const tmp:User|null = await MANAGER_USER.getLoaderUser().loadByUsername(pseudo);
if (tmp!=null){
Alert.alert("Ce pseudo existe déjà");
}
await MANAGER_USER.getsaverUser().saveUser(pseudo, password, selectedNationality, selectedSex, date).then((res)=>{
MANAGER_USER.setCurrentUser(res);
setUser(MANAGER_USER.getCurrentUser());
socket.emit("signIn", res);
navigation.navigate('HomeTab');
})
}
}
}
export default SignUp

@ -6,7 +6,6 @@ import { TopBar } from '../components/TopBar';
import { BotBar } from '../components/BotBar';
import { FlatList } from 'react-native-gesture-handler';
import { SkinComponent } from '../components/Skin';
import tabSkinApp from '../constSkin';
import { ScreenIndicator } from '../components/ScreenIndicator';
import { MANAGER_USER } from '../../appManagers';

@ -2,8 +2,8 @@ import { StyleSheet } from "react-native";
export default StyleSheet.create({
textInput: {
width: '100%',
textInput: {
width: '70%',
height: '5%',
backgroundColor: 'white',
padding: 10,

@ -1,4 +1,6 @@
import { Conversation } from "../../core/conversation";
import { Message } from "../../core/message";
import { User } from "../../core/User/user";
export default interface ISaverConversation{
@ -7,7 +9,7 @@ export default interface ISaverConversation{
* c the Conversation we want to save
*/
saveConversation(c:Conversation): Promise<void>;
saveConversation(name: string, user:User, tabId:number[], firstMessage:string, messageDate:Date): Promise<Conversation | null>;
/**
* deleteConversation methode that delete a Conversation in the data management system
@ -20,4 +22,17 @@ export default interface ISaverConversation{
* c the Conversation we want to update
*/
updateConversation(c:Conversation): Promise<void>;
/**
* addMessage methode that add a Message to a Conversation in the data management system
* c the Conversation we want to update
* content the content of the Message
* id the id of the Sender
*/
addMessage(idConv:number, content: string, messageDate:Date, user: User): Promise<Message | null>;
addUserToConversation(c:Conversation, id:number): Promise<void>;
deleteUserToConversation(c:Conversation, u:User): Promise<void>;
}

@ -1,10 +1,25 @@
import { Conversation } from "../../core/conversation";
import { Message } from "../../core/message";
import { User } from "../../core/User/user";
import ISaverConversation from "./ISaverConversation";
export class FakeSaverConversation implements ISaverConversation{
async saveConversation(c: Conversation): Promise<void> {
return;
addMessage(idConv: number, content: string, messageDate: Date, user: User): Promise<Message | null> {
throw new Error("Method not implemented.");
}
saveConversation(name: string, user: User, id: number[]): Promise<Conversation | null> {
throw new Error("Method not implemented.");
}
addUserToConversation(c: Conversation, id: number): Promise<void> {
throw new Error("Method not implemented.");
}
deleteUserToConversation(c: Conversation, u: User): Promise<void> {
throw new Error("Method not implemented.");
}
async deleteConversation(c: Conversation): Promise<void> {
return;
}

@ -1,3 +1,4 @@
import { MANAGER_USER } from "../../../appManagers";
import { Conversation } from "../../core/conversation";
import { Message } from "../../core/message";
import { Skin } from "../../core/skin";
@ -17,23 +18,67 @@ export class LoaderConversationApi implements ILoaderConversation{
async loadByUser(u: User): Promise<Conversation[]> {
let tabConv:Conversation[]=[];
const url='http://localhost:8888/api-rest/index.php/getConversations/' +u.getId();
await this.axios({
method: 'get',
url: 'https://jsonplaceholder.typicode.com/todos/1',
params: {
name: "getConversationByUser",
//Les params genre nom de la fonction en php
}
url: url,
})
.then(function (response: any) {
let skin= new Skin(1, "Bob","https://codefirst.iut.uca.fr/git/BOB_PARTEAM/BOB_PARTY/raw/branch/typescript/bob_party/assets/BobsSkins/BobClassic.png", 0);
tabConv=[new Conversation(40,
[new User(1, "Alban", "oui", "ouioui", "homme", new Date(2022,12,12), 555, 667, 12, skin, [skin]),
new User(3, "Fefe63", "jesuishm", "ouioui", "homme", new Date(2022,12,12), 12222, 123324, 12, skin, [skin])],
[new Message(1, "bonjour", new User(1, "Alban", "oui", "ouioui", "homme", new Date(2022,12,12), 555, 667, 12, skin, [skin]), new Date(2022,12,12)),
new Message(2, "test", new User(2, "Fefe63", "oui", "ouioui", "homme", new Date(2022,12,12), 555, 667, 12, skin, [skin]), new Date(2022,12,13))], "leNom")];
.then(async function (response: any) {
tabConv=await jsonToConversation(response);
});
return tabConv;
}
}
async function jsonToConversation(response:any) {
const tabConv:Conversation[]=[];
let end=new Promise<void>((resolve, reject) => {
response.data.forEach( async (conv: { listIdUsers: any[]; tabMessages: any[]; id: number; name: string; }) => {
const tabUser:User[]=[];
const tabMessage:Message[]=[];
let first = new Promise<void>((resolve,reject) => {
conv.listIdUsers.forEach(async id => {
const user:User | null= await MANAGER_USER.getLoaderUser().loadByID(id);
if (user!=null){
tabUser.push(user);
}
if(conv.listIdUsers.length===tabUser.length){
resolve();
}
});
if (conv.listIdUsers.length===0){
resolve();
}
});
let second= new Promise<void> ((resolve, reject) => {
conv.tabMessages.forEach(async message => {
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)));
}
if(conv.tabMessages.length===tabMessage.length){
resolve();
}
});
if (conv.tabMessages.length===0){
resolve();
}
});
await Promise.all([first, second]);
tabConv.push(new Conversation(conv.id, tabUser, tabMessage, conv.name));
if (tabConv.length===response.data.length){
resolve();
}
});
if (response.data.length==0){
resolve();
}
});
await Promise.all([end]);
return tabConv;
}

@ -4,7 +4,9 @@ import ISaverConversation from "./ISaverConversation";
export default class ManagerConversation{
private currentTabConv:Conversation[]=[];
private currentConv:Conversation | null= null;
private tabConv:Conversation[]=[];
private loaderConversation: ILoaderConversation;
@ -15,12 +17,20 @@ export default class ManagerConversation{
this.saverConversation=saverConversation;
}
getCurrentTabConv(){
return this.currentTabConv;
getCurrentConv(){
return this.currentConv;
}
setCurrentConv(c:Conversation){
this.currentConv=c;
}
getTabConv(){
return this.tabConv;
}
setCurrentTabConv(c:Conversation[]){
this.currentTabConv=c;
setTabConv(c:Conversation[]){
this.tabConv=c;
}
getLoaderConversation(){

@ -0,0 +1,109 @@
import { each } from "jquery";
import { MANAGER_USER } from "../../../appManagers";
import { Conversation } from "../../core/conversation";
import { Message } from "../../core/message";
import { User } from "../../core/User/user";
import ISaverConversation from "./ISaverConversation";
export class SaverConversationApi implements ISaverConversation{
private axios = require('axios').default;
async saveConversation(name: string, user:User, tabId:number[], firstMessage:string, messageDate:Date): Promise<Conversation | null>{
let conv:Conversation | null=null;
let url='http://localhost:8888/api-rest/index.php/postConversation/' + name + "/" +user.getId();
tabId.forEach(id => {
url=url + "," + id;
});
await this.axios({
method: 'post',
url: url,
})
.then(async (response: any) => {
let tabUser:User[]=[];
const id=response.data;
const message:Message|null=await this.addMessage(id, firstMessage, messageDate, user);
let end=new Promise<void>((resolve, reject) => {
tabId.forEach(async id => {
let tmp:User|null=await MANAGER_USER.getLoaderUser().loadByID(id);
if (tmp!=null){
tabUser.push(tmp);
}
if (tabUser.length===tabId.length){
resolve();
}
});
});
await Promise.all([end]);
if (message!=null){
conv=new Conversation(id, tabUser, [message], name);
}
});
return conv;
}
async addMessage(idConv:number, content: string, messageDate:Date, user: User): Promise<Message | null> {
let message:Message | null=null;
let url='http://localhost:8888/api-rest/index.php/addMessageToConversation/' + content + "/" + user.getId() + "/" + idConv + "/" + messageDate.toISOString().split('T')[0] + " " + messageDate.getHours() + ":" + messageDate.getMinutes() + ":" + messageDate.getSeconds();
await this.axios({
method: 'put',
url: url,
})
.then(async (response: any) => {
const id=response.data;
message=new Message(id, content, user, messageDate);
});
return message;
}
addUserToConversation(c: Conversation, id: number): Promise<void> {
throw new Error("Method not implemented.");
}
deleteUserToConversation(c: Conversation, u: User): Promise<void> {
throw new Error("Method not implemented.");
}
async deleteConversation(c: Conversation): Promise<void> {
return;
}
async updateConversation(c: Conversation): Promise<void> {
return;
}
}
async function jsonToConversation(response:any) {
let conv:Conversation | null=null;
const tabUser:User[]=[];
const tabMessage:Message[]=[];
let first = new Promise<void>((resolve,reject) => {
response.data.listIdUsers.forEach(async (id: number) => {
const user:User | null= await MANAGER_USER.getLoaderUser().loadByID(id);
if (user!=null){
tabUser.push(user);
}
if(response.data.listIdUsers.length===tabUser.length){
resolve();
}
});
});
let second= new Promise<void> ((resolve, reject) => {
response.data.tabMessages.forEach(async (message: { idSender: number; id: number; content: string; dateEnvoie: string | number | Date; }) => {
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)));
}
if(response.data.tabMessages.length===tabMessage.length){
resolve();
}
});
});
await Promise.all([first, second]);
conv = new Conversation(response.data.id, tabUser, tabMessage, response.data.name);
return conv;
}

@ -3,11 +3,11 @@ import ILoaderGame from "./ILoaderGame";
export default class ManagerGame{
private tabGame: Game[] | null=null;
private tabGame: Game[]=[];
private tabGameSolo: Game[] | null=null;
private tabGameSolo: Game[]=[];
private tabGameMulti: Game[] | null=null;
private tabGameMulti: Game[]=[];
private loaderGame: ILoaderGame;
@ -19,15 +19,15 @@ export default class ManagerGame{
return this.tabGame;
}
setTabGame(g:Game[] | null){
setTabGame(g:Game[]){
this.tabGame=g;
}
getTabGameSolo(){
return this.tabGame;
return this.tabGameSolo;
}
setTabGameSolo(g:Game[] | null){
setTabGameSolo(g:Game[]){
this.tabGameSolo=g;
}
@ -35,7 +35,7 @@ export default class ManagerGame{
return this.tabGameMulti;
}
setTabGameMulti(g:Game[] | null){
setTabGameMulti(g:Game[]){
this.tabGameMulti=g;
}
@ -43,8 +43,4 @@ export default class ManagerGame{
return this.loaderGame;
}
setLoaderGame(l:ILoaderGame){
this.loaderGame=l;
}
}

@ -27,15 +27,7 @@ export default class ManagerMatch{
return this.loaderMatch;
}
setLoaderMatch(l:ILoaderMatch){
this.loaderMatch=l;
}
getsaverMatch(){
return this.saverMatch;
}
setsaverMatch(s:ISaverMatch){
this.saverMatch=s;
}
}

@ -1,25 +0,0 @@
import { Conversation } from "../../core/conversation";
import { Message } from "../../core/message";
export default interface ILoaderMessage{
/**
* loadAllMessage methode that load every Message from the data management system
* return an array of Message
*/
loadAllMessage(): Promise<Message[]>;
/**
* loadByID methode that load a Message from the data management system by its id
* id the id we want to search
* return a Message if found, if not null
*/
loadByID(id:string): Promise<Message | null>;
/**
* loadByUser methode that load an array of Message from the data management system using a Conversation
* c the Conversation we want the Messages of
* return an array of Message
*/
loadByConversation(c:Conversation): Promise<Message[]>;
}

@ -1,12 +0,0 @@
import { Message } from "../../core/message";
export default interface ISaverMessage{
/**
* saveMessage methode that save a Message in the data management system
* m the Message we want to save
*/
saveMessage(m:Message): Promise<void>;
}

@ -0,0 +1,17 @@
import { Skin } from "../../core/skin";
export default interface ILoaderSkin{
/**
* loadAllSkin methode that load every Skin from the data management system
* return an array of Skin
*/
loadAllSkin(): Promise<Skin[]>;
/**
* loadByID methode that load a Skin from the data management system by its id
* id the id we want to search
* return a Skin if found, if not null
*/
loadByID(id:number): Promise<Skin | null>;
}

@ -0,0 +1,48 @@
import { Skin } from "../../core/skin";
import ILoaderSkin from "./ILoaderSkin";
export default class LoaderSkinApi implements ILoaderSkin{
private axios = require('axios').default;
/**
* loadAllSkin methode that load every Skin from the data management system
* return an array of Skin
*/
async loadAllSkin(): Promise<Skin[]>{
let tabSkin: Skin[]=[];
const url='http://localhost:8888/api-rest/index.php/getSkins';
await this.axios({
method: 'get',
url: url,
})
.then(function (response: any) {
if (response.data != null && response.data != undefined){
response.data.forEach((skins: { id: number; name: string; source: string; cost: number; }) => {
tabSkin.push(new Skin(skins.id, skins.name, skins.source, skins.cost));
});
}
});
return tabSkin;
}
/**
* loadByID methode that load a Skin from the data management system by its id
* id the id we want to search
* return a Skin if found, if not null
*/
async loadByID(id:number): Promise<Skin | null>{
let skin: Skin | null= null;
const url='http://localhost:8888/api-rest/index.php/getSkins';
await this.axios({
method: 'get',
url: url,
})
.then(function (response: any) {
if (response.data != null && response.data != undefined){
skin=new Skin(response.data.currentSkin.id, response.data.currentSkin.name, response.data.currentSkin.source, response.data.currentSkin.cost);
}
});
return skin;
}
}

@ -0,0 +1,27 @@
import { Skin } from "../../core/skin";
import ILoaderSkin from "./ILoaderSkin";
export default class ManagerSkin{
private tabSkin: Skin[]=[];
private loaderSkin: ILoaderSkin;
constructor(loader:ILoaderSkin){
this.loaderSkin=loader;
}
getTabSkin(){
return this.tabSkin;
}
setTabSkin(tab:Skin[]){
this.tabSkin=tab;
}
getLoaderSkin(){
return this.loaderSkin;
}
}

@ -1,3 +1,4 @@
import { Skin } from "../../core/Skin";
import { User } from "../../core/User/user";
export default interface ISaverUser{
@ -20,4 +21,7 @@ export default interface ISaverUser{
* u the user we want to update
*/
updateUser(u:User | null): Promise<void>;
addSkinList(u: User, s:Skin): Promise<void>;
}

@ -27,15 +27,7 @@ export default class ManagerUser{
return this.loaderUser;
}
setLoaderUser(l:ILoaderUser){
this.loaderUser=l;
}
getsaverUser(){
return this.saverUser;
}
setsaverUser(s:ISaverUser){
this.saverUser=s;
}
}

@ -1,3 +1,4 @@
import { Skin } from "../../core/Skin";
import { User } from "../../core/User/user";
import ISaverUser from "./ISaverUser";
@ -13,4 +14,8 @@ export default class FakeSaverUser implements ISaverUser{
async updateUser(u: User): Promise<void> {
return;
}
async addSkinList(u: User, s:Skin): Promise<void> {
return;
}
}

@ -1,4 +1,3 @@
import tabSkinApp from "../../constSkin";
import { Conversation } from "../../core/conversation";
import { Match } from "../../core/Match/match";
import { Skin } from "../../core/skin";
@ -23,90 +22,56 @@ export default class LoaderUserApi implements ILoaderUser{
private axios = require('axios').default;
async loadAllUser() : Promise<User[]> {
let us:User[]=[];
let test=new Test(false, 1, "a", 1);
throw new Error("Method not implemented.");
}
async loadByID(id: number): Promise<User | null> {
let us:User | null=null;
const url='http://localhost:8888/api-rest/index.php/getUserById/'+ id;
await this.axios({
method: 'get',
url: 'https://jsonplaceholder.typicode.com/todos',
params: {
name: "getAllUser",
//Les params genre nom de la fonction en php
}
url: url,
})
.then(function (response: any) {
if (response.data != null && response.data != undefined){
Object.assign(test, response.data);
us.push(new User(1, "Fefe63", "jesuishm", "ouioui", "homme", new Date(2022,12,12), 12222, 123324, 12, tabSkinApp[6], tabSkinApp));
us=JsonToUser(response);
}
});
return us;
}
async loadByID(id: number): Promise<User | null> {
let test = new Test(true, 0, "wesh", 0);
try{
await this.axios({
method: 'get',
url: 'https://jsonplaceholder.typicode.com/todos/1',
params: {
name: "getUserById",
id: id,
//Les params genre nom de la fonction en php
}
})
.then(function (response: any) {
console.log(response.data);
Object.assign(test, response.data);
console.log(test.id);
});
}catch (error) {
console.error(error);
}
return new User(1, "Bite", "jesuishm", "ouioui", "homme", new Date(2022,12,12), 123, 123324, 12, tabSkinApp[6], tabSkinApp);
return us;
}
async loadByUsername(username: string): Promise<User | null> {
let test = new Test(true, 0, "wesh", 0);
try{
await this.axios({
method: 'get',
url: 'https://jsonplaceholder.typicode.com/todos/1',
params: {
name: "getUserByUsername",
username: username,
//Les params genre nom de la fonction en php
}
})
.then(function (response: any) {
console.log(response.data);
Object.assign(test, response.data);
console.log(test.id);
});
}catch (error) {
console.error(error);
}
return null;
let us:User | null=null;
const url='http://localhost:8888/api-rest/index.php/getUserByUsername/'+ username;
await this.axios({
method: 'get',
url: url,
})
.then(function (response: any) {
if (response.data != null && response.data != undefined){
us=JsonToUser(response);
}
});
return us;
}
async loadByUsernamePassword(username: string, password: string): Promise<User | null>{
let user:User | null=null;
let us:User | null=null;
const url='http://localhost:8888/api-rest/index.php/getUserForConnection/'+ username + "/" + password;
await this.axios({
method: 'get',
url: 'https://jsonplaceholder.typicode.com/todos/1',
params: {
name: "getAllUser",
//Les params genre nom de la fonction en php
}
url: url,
})
.then(function (response: any) {
const tabTest=[new Skin(1, "Bob","https://codefirst.iut.uca.fr/git/BOB_PARTEAM/BOB_PARTY/raw/branch/typescript/bob_party/assets/BobsSkins/BobClassic.png", 0),
new Skin(2, "Bob Blue","https://codefirst.iut.uca.fr/git/BOB_PARTEAM/BOB_PARTY/raw/branch/typescript/bob_party/assets/BobsSkins/BobBlue.png", 100)];
user=new User(1, username, password, "ouioui", "homme", new Date(2022,12,12), 0, 0, 12, tabTest[0], tabTest);
if (response.data != null && response.data != undefined){
us=JsonToUser(response);
}
});
return user;
return us;
}
async loadUserByMatch(m: Match): Promise<User[]> {
@ -118,15 +83,15 @@ export default class LoaderUserApi implements ILoaderUser{
throw new Error("Method not implemented.");
}
}
function JsonToUser(response: any): User{
const tabSkin:Skin[]=[];
response.data.tabSkin.forEach((skins: { id: number; name: string; source: string; cost: number; }) => {
tabSkin.push(new Skin(skins.id, skins.name, skins.source, skins.cost));
});
const skin=new Skin(response.data.currentSkin.id, response.data.currentSkin.name, response.data.currentSkin.source, response.data.currentSkin.cost);
return new User(response.data.id, response.data.username, response.data.password, response.data.nationality, response.data.sexe, new Date(response.data.dateOfBirth), response.data.currentCoins, response.data.totalCoins, response.data.nbGamesPlayed, skin, tabSkin);
}
async loadLastId(): Promise<number> {
let test = new Test(true, 0, "wesh", 0);
try {
const response = await this.axios.get('https://jsonplaceholder.typicode.com/todos/1');
console.log(response.data);
} catch (error) {
console.error(error);
}
return 1;
}
}

@ -1,3 +1,5 @@
import { MANAGER_USER } from "../../../appManagers";
import { Skin } from "../../core/Skin";
import { User } from "../../core/User/user";
import ISaverUser from "./ISaverUser";
@ -8,19 +10,12 @@ export default class SaverUserApi implements ISaverUser{
async saveUser(username:string, password:string, nationality:string, sexe:string, date:Date): Promise<User | null> {
let us:User|null=null;
this.axios({
const url='http://localhost:8888/api-rest/index.php/postUser/'+ username + "/" + password + "/" + nationality + "/" + sexe + "/" + date.toISOString().split('T')[0] ;
await this.axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
}).then(function (response: any) {
if (response.data != null && response.data != undefined){
let test:any;
Object.assign(test, response.data);
us=test;
}
url: url,
}).then(async function () {
us = await MANAGER_USER.getLoaderUser().loadByUsername(username);
});
return us;
}
@ -28,7 +23,21 @@ export default class SaverUserApi implements ISaverUser{
throw new Error("Method not implemented.");
}
async updateUser(u: User): Promise<void> {
throw new Error("Method not implemented.");
let us:User|null=null;
const url='http://localhost:8888/api-rest/index.php/putUser/'+ u.getId() + "/" + u.getUsername() + "/" + u.getPassword() + "/" + u.getSexe() + "/" + u.getNationality() + "/" + u.getCurrentCoins() + "/" + u.getTotalCoins() + "/" + u.getGamesPlayed() + "/" + u.getCurrentSkin().getSkinId();
await this.axios({
method: 'put',
url: url,
});
}
async addSkinList(u: User, s:Skin): Promise<void> {
let us:User|null=null;
const url='http://localhost:8888/api-rest/index.php/putSkinList/'+ u.getId() + "/" + s.getSkinId();
await this.axios({
method: 'put',
url: url,
});
}
}

@ -1,150 +0,0 @@
/* This script does:
* create tables of the database
* creates the sequences for the ids(with AUTO_INCREMENT)
* create the triggers and trigger functions
*/
/* ----------------------------------- */
/* TABLES' CREATION */
/* ----------------------------------- */
/* ----- ENTITIES TABLES -----*/
/* -- Table User -- */
CREATE TABLE T_S_USER_USR (
PK_ID int AUTO_INCREMENT PRIMARY KEY,
USR_USERNAME varchar(50) UNIQUE NOT NULL,
USR_PASSWORD varchar(50) NOT NULL,
USR_NATIONALITY varchar(20) NOT NULL,
USR_SEX char(1) NOT NULL,
USR_DATE_OF_BIRTH date,
USR_CURRENT_NB_COINS int DEFAULT 0,
USR_TOTAL_NB_COINS int DEFAULT 0,
USR_NB_GAMES_PLAYED int DEFAULT 0,
FK_CURRENT_SKIN int
REFERENCES T_H_SKIN_SKI(PK_ID)
);
/* -- Table Skin -- */
CREATE TABLE T_H_SKIN_SKI (
PK_ID int AUTO_INCREMENT PRIMARY KEY,
SKI_NAME varchar(50) UNIQUE NOT NULL,
SKI_IMAGE varchar(50) UNIQUE NOT NULL,
SKI_PRICE varchar(30)
);
/* -- Table Game -- */
CREATE TABLE T_E_GAME_GAM (
PK_ID int AUTO_INCREMENT PRIMARY KEY,
GAM_NAME varchar(50) UNIQUE,
GAM_IMAGE varchar(50) UNIQUE,
GAM_NB_PLAYER_MIN int,
GAM_NB_PLAYER_MAX int
);
/* -- Table Match -- */
CREATE TABLE T_E_MATCH_MTC (
PK_ID int AUTO_INCREMENT PRIMARY KEY,
MTC_IN_GAME boolean,
FK_GAME int
REFERENCES T_E_GAME_GAM(PK_ID)
);
/* -- Table Conversation -- */
CREATE TABLE T_H_CONVERSATION_COV (
PK_ID int AUTO_INCREMENT PRIMARY KEY,
COV_NAME varchar(20)
);
/* -- Table Message -- */
CREATE TABLE T_H_MESSAGE_MSG (
PK_ID int AUTO_INCREMENT PRIMARY KEY,
MSG_MESSAGE text,
FK_SENDER int
REFERENCES T_S_USER_USR(PK_ID)
);
/* ----- JUNCTURE TABLES ----- */
/* -- Juncture own skin -- */
CREATE TABLE T_J_OWN_SKIN_OWN (
FK_USER int ,
FOREIGN KEY (FK_USER)
REFERENCES T_S_USER_USR(PK_ID)
ON DELETE CASCADE,
FK_SKIN int ,
FOREIGN KEY (FK_SKIN)
REFERENCES T_H_SKIN_SKI(PK_ID),
PRIMARY KEY(FK_SKIN, FK_USER)
);
/* -- Juncture play match -- */
CREATE TABLE T_J_PLAY_MATCH_PLM (
FK_USER int ,
FOREIGN KEY (FK_USER )
REFERENCES T_S_USER_USR(PK_ID)
ON DELETE CASCADE,
FK_MATCH int ,
FOREIGN KEY (FK_MATCH)
REFERENCES T_E_MATCH_MTC(PK_ID)
ON DELETE CASCADE,
PRIMARY KEY (FK_USER,FK_MATCH)
);
/* -- Juncture discuss -- */
CREATE TABLE T_J_DISCUSS_DIS (
FK_USER int ,
FOREIGN KEY (FK_USER)
REFERENCES T_S_USER_USR(PK_ID)
ON DELETE CASCADE,
FK_CONVERSATION int ,
FOREIGN KEY (FK_CONVERSATION)
REFERENCES T_H_CONVERSATION_COV(PK_ID)
ON DELETE CASCADE,
PRIMARY KEY(FK_USER,FK_CONVERSATION)
);
/* -- Juncture contain message -- */
CREATE TABLE T_J_CONTAIN_MESSAGE_CMG (
FK_CONVERSATION int,
FOREIGN KEY (FK_CONVERSATION)
REFERENCES T_H_CONVERSATION_COV(PK_ID)
ON DELETE CASCADE,
FK_MESSAGE int,
FOREIGN KEY (FK_MESSAGE)
REFERENCES T_H_MESSAGE_MSG(PK_ID)
ON DELETE CASCADE,
PRIMARY KEY (FK_CONVERSATION,FK_MESSAGE)
);
/* ----------------------------------- */
/* TRIGGERS' CREATION */
/* ----------------------------------- */
/* ----- USER's trigger ----- */
/* -- after insert -> add basic skin into the list of skin -- */
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);
/* ----- CONVERSATION's trigger ----- */
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);
Loading…
Cancel
Save