Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PC-4 Messages endpoints lost commits #8

Merged
merged 7 commits into from
Jan 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion app/app.controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
@include_once "./vendor/autoload.php";
@include_once "./utils/httpException.php";
@include_once "./utils/request.php";
@include_once "./guards/jwtAuthGuard.php";
@include_once "./users/users.controller.php";
@include_once "./db/db.controller.php";
@include_once "./chats/chats.controller.php";
@include_once "./messages/messages.controller.php";
@include_once "./auth/auth.controller.php";
@include_once "./guards/jwtAuthGuard.php";

class AppController
{
Expand All @@ -23,6 +24,7 @@ class AppController
private UsersController $usersController;
private ChatsController $chatsController;
private AuthController $authController;
private MessagesController $messagesController;
# Guards
private JwtAuthGuard $jwtAuthGuard;

Expand All @@ -39,6 +41,7 @@ function __construct($dbConfig)
$this->usersController = new UsersController($this->conn);
$this->authController = new AuthController($this->conn);
$this->chatsController = new ChatsController($this->conn);
$this->messagesController = new MessagesController($this->conn);

# Initialize guards
$this->jwtAuthGuard = new JwtAuthGuard(new UsersService($this->conn));
Expand Down Expand Up @@ -94,6 +97,12 @@ private function router()
$this->chatsController->getChatParticipants($this->_req->getRequest());
return;
}
if (preg_match("/\/api\/chats\/(?'chatId'[a-z0-9]+)\/messages/", $this->req['resource']))
{
$this->_req->useGuard($this->jwtAuthGuard);
$this->messagesController->getChatMessages($this->_req->getRequest());
return;
}
# /chats/:chatId
if (strpos($this->req['resource'], '/api/chats/') === 0)
{
Expand All @@ -116,6 +125,12 @@ private function router()
$this->chatsController->addUserToChat($this->_req->getRequest(), $reqBody["data"]);
return;
}
if (preg_match("/\/api\/chats\/(?'chatId'[a-z0-9]+)\/messages/", $this->req['resource']))
{
$this->_req->useGuard($this->jwtAuthGuard);
$this->messagesController->createMessage($this->_req->getRequest(), $reqBody["data"]);
return;
}
if ($this->req['resource'] === '/api/chats')
{
$this->_req->useGuard($this->jwtAuthGuard);
Expand Down
2 changes: 1 addition & 1 deletion db/db.config.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@
"user" => "root",
"pass" => "root",
"name" => "web_chat",
"charset" => "utf8",
"charset" => "utf8mb4",
];
43 changes: 38 additions & 5 deletions db/db.controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
@include_once("./fixtures/users.php");
@include_once("./fixtures/chats.php");
@include_once("./fixtures/chatParticipants.php");
@include_once("./fixtures/messages.php");

class DbController
{
Expand All @@ -13,15 +14,17 @@ public function __construct($dbConfig)
$this->connectToDb($dbConfig);

// TODO: Don't run this if we are in production mode
$this->dropTables(['ChatParticipants', 'Users', 'Chats']);
$this->dropTables(['ChatParticipants', 'Messages', 'Users', 'Chats']);
// $this->dropDB($dbConfig["name"]);

$this->initialize();
$this->initialize($dbConfig["name"]);

# Include fixtures from global scope here
global $usersFixtures, $chatsFixtures, $chatParticipantsFixtures;
global $usersFixtures, $chatsFixtures, $chatParticipantsFixtures, $messagesFixtures;
$this->seed('Users', $usersFixtures);
$this->seed('Chats', $chatsFixtures);
$this->seed('ChatParticipants', $chatParticipantsFixtures);
$this->seed('Messages', $messagesFixtures);
}

private function connectToDb(array $dbConfig)
Expand All @@ -46,22 +49,39 @@ private function dropTables($tables)
{
try {
foreach ($tables as $table) {
$sql = "DROP TABLE $table";
$sql = "DROP TABLE IF EXISTS $table";
$this->conn->exec($sql);
}
} catch (Exception $ex) {
httpException("Failed to drop db tables", 500);
}
}

private function dropDB($dbName)
{
try {
$sql = "DROP DATABASE IF EXISTS $dbName";
$this->conn->exec($sql);
} catch (Exception $ex) {
httpException("Failed to drop db", 500);
}
}

/**
* Create all tables with hardcoded sql script
*/
private function initialize()
private function initialize($dbName)
{
try {
# Create Users table
$users = <<<SQL
-- CREATE DATABASE IF NOT EXISTS $dbName;
-- CHARACTER SET utf8mb4;
-- COLLATE utf8mb4_unicode_ci;
-- SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

-- USE $dbName;

CREATE TABLE IF NOT EXISTS Users (
id VARCHAR(16) PRIMARY KEY,
username VARCHAR(20) UNIQUE NOT NULL,
Expand All @@ -84,6 +104,18 @@ private function initialize()
chatId VARCHAR(16) NOT NULL,
userId VARCHAR(16) NOT NULL,
permission TINYINT NOT NULL DEFAULT 0,
lastSeenMessageId VARCHAR(16) DEFAULT 0,
FOREIGN KEY (chatId) REFERENCES Chats (id),
FOREIGN KEY (userId) REFERENCES Users (id)
);

CREATE TABLE IF NOT EXISTS Messages (
id VARCHAR(16) PRIMARY KEY,
chatId VARCHAR(16) NOT NULL,
userId VARCHAR(16) NOT NULL,
content NVARCHAR(2048) NOT NULL,
contentType TINYINT NOT NULL DEFAULT 0,
createdAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (chatId) REFERENCES Chats (id),
FOREIGN KEY (userId) REFERENCES Users (id)
);
Expand Down Expand Up @@ -116,6 +148,7 @@ public function seed(string $table, array $fixtures)
$this->conn->prepare($sql)->execute($fixture);
}
} catch (Exception $ex) {
var_dump($ex);
httpException("Failed to seed db, table '$table'", 500)['end']();
}
}
Expand Down
6 changes: 4 additions & 2 deletions fixtures/chatParticipants.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

@include_once __DIR__ . "/chats.php";
@include_once __DIR__ . "/users.php";
@include_once __DIR__ . "/messages.php";

global $MaxAndIlyaChat, $MaxDmitriev, $IlyaMehof, $DeletedChatWithMaxAndMatvey, $MatveyGorelik, $GymPartyPublicChat;
global $MaxAndIlyaChat, $MaxDmitriev, $IlyaMehof, $DeletedChatWithMaxAndMatvey, $MatveyGorelik, $GymPartyPublicChat, $IlyaMessageInChatWithMax;

$MaxInChatWithIlya = [
"chatId" => $MaxAndIlyaChat["id"],
Expand All @@ -14,7 +15,8 @@
$IlyaInChatWithMax = [
"chatId" => $MaxAndIlyaChat["id"],
"userId" => $IlyaMehof["id"],
"permission" => 2
"permission" => 2,
"lastSeenMessageId" => $IlyaMessageInChatWithMax["id"]
];

$MaxInDeletedChatWithMatvey = [
Expand Down
66 changes: 66 additions & 0 deletions fixtures/messages.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

@include_once __DIR__ . "/chats.php";
@include_once __DIR__ . "/users.php";

global $MaxAndIlyaChat, $MaxDmitriev, $IlyaMehof, $DeletedChatWithMaxAndMatvey, $MatveyGorelik, $GymPartyPublicChat;

$MaxMessageInChatWithIlya = [
"id" => "message000000001",
"chatId" => $MaxAndIlyaChat["id"],
"userId" => $MaxDmitriev["id"],
"content" => "Hi there, it's our first message"
];

$IlyaMessageInChatWithMax = [
"id" => "message000000002",
"chatId" => $MaxAndIlyaChat["id"],
"userId" => $IlyaMehof["id"],
"content" => "Hi Max! Nice to meet you here!"
];

$MaxPhotoMessageInChatWithIlya = [
"id" => "message000000003",
"chatId" => $MaxAndIlyaChat["id"],
"userId" => $MaxDmitriev["id"],
"contentType" => 1,
"content" => "https://ixbt.online/live/images/original/04/19/16/2022/01/23/14e5fd3c80.jpg"
];

$MaxMessageInDeletedChatWithMatvey = [
"id" => "message000000004",
"chatId" => $DeletedChatWithMaxAndMatvey["id"],
"userId" => $MaxDmitriev["id"],
"content" => "Hi Matvey, how are you?"
];

$MatveyMessageInDeletedChatWithMax = [
"id" => "message000000005",
"chatId" => $DeletedChatWithMaxAndMatvey["id"],
"userId" => $MatveyGorelik["id"],
"content" => "Hi, I'm fine, can you call me now? I'll delete this chat now"
];

$MaxMessageInGymChat = [
"id" => "message000000006",
"chatId" => $GymPartyPublicChat["id"],
"userId" => $MaxDmitriev["id"],
"content" => "Salam aleykum! Todzhiko ikei vatan, duri mi duhom padat nakin"
];

$IlyaMessageInGymChat = [
"id" => "message000000007",
"chatId" => $GymPartyPublicChat["id"],
"userId" => $IlyaMehof["id"],
"content" => "Nas nikogda nikto ne slomaet"
];

$messagesFixtures = [
$MaxMessageInChatWithIlya,
$IlyaMessageInChatWithMax,
$MaxPhotoMessageInChatWithIlya,
$MaxMessageInDeletedChatWithMatvey,
$MatveyMessageInDeletedChatWithMax,
$IlyaMessageInGymChat,
$MaxMessageInGymChat
];
14 changes: 5 additions & 9 deletions messages/messages.controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,14 @@ function createMessage($req, $messageDto)
httpException($messages["chat_not_found"], 404)['end']();
}

$initiatorParticipant = $this->chatsService->getChatParticipantByUserId($req["user"]["id"], $chat["id"]);
$initiatorParticipant = $this->chatsService->isUserChatParticipant($req["user"]["id"], $chat["id"]);

if (is_null($initiatorParticipant))
if (!$initiatorParticipant)
{
httpException($messages["not_enough_permission"], 403)['end']();
}

$message = $messageDto;

$message["id"] = randomId();

$this->messagesService->createMessage($chat["id"], );
$this->messagesService->createMessage(randomId(), $chat["id"], $req["user"]["id"], $messageDto["content"], $messageDto["contentType"]);

$response = [
"message" => $messages["message_sent"],
Expand All @@ -72,9 +68,9 @@ function getChatMessages($req)
httpException($messages["chat_not_found"], 404)['end']();
}

$initiatorParticipant = $this->chatsService->getChatParticipantByUserId($req["user"]["id"], $chat["id"]);
$initiatorParticipant = $this->chatsService->isUserChatParticipant($req["user"]["id"], $chat["id"]);

if (is_null($initiatorParticipant))
if (!$initiatorParticipant)
{
httpException($messages["not_enough_permission"], 403)['end']();
}
Expand Down
18 changes: 13 additions & 5 deletions messages/messages.service.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,29 @@ function __construct($conn)
$this->conn = $conn;
}

function createMessage($id, )
function createMessage($id, $chatId, $userId, $content, $contentType)
{
$sql = "INSERT INTO Chats (id, ) VALUES (:id, )";
$sql = "INSERT INTO Messages (id, chatId, userId, content, contentType) VALUES (:id, :chatId, :userId, :content, :contentType)";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue(":id", $id);
$stmt->bindValue(":chatId", $chatId);
$stmt->bindValue(":userId", $userId);
$stmt->bindValue(":content", $content);
$stmt->bindValue(":contentType", $contentType);
$stmt->execute();
}

function getChatMessages($chatId)
function getChatMessages($chatId): array
{
$sql = "SELECT * FROM Messages WHERE chatId=:chatId";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue(":chatId", $chatId);
$stmt->execute();

return $stmt->rowCount() > 0;

if ($stmt->rowCount() > 0) {
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
return [];
}
}
}
16 changes: 10 additions & 6 deletions tests/messages-e2e.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ function sendMessageToChat($chatId, $user = null): array
}

$body = [
"message" => "Hello world"
"content" => "Hello world",
"contentType" => 0
];

$response = request(
Expand All @@ -67,6 +68,7 @@ function sendMessageToChat($chatId, $user = null): array
[$response, $json] = getChatMessages($MaxAndIlyaChat["id"], $MaxDmitriev);

assertStrict($response['info']['http_code'], 200);
assertStrict(count($json->data->messages), 3);
});

it("should return error when trying to get private chat messages for NOT a chat participant", function () {
Expand All @@ -84,6 +86,7 @@ function sendMessageToChat($chatId, $user = null): array
[$response, $json] = getChatMessages($GymPartyPublicChat["id"], $MaxDmitriev);

assertStrict($response['info']['http_code'], 200);
assertStrict(count($json->data->messages), 2);
});

it("should return not authorized when trying to get chat messages without authorization", function () {
Expand Down Expand Up @@ -116,11 +119,12 @@ function sendMessageToChat($chatId, $user = null): array

describe("[POST] /api/chats/:chatId/messages", function () {
it("should send message to private chat for chat participant", function () {
global $MaxDmitriev, $MaxAndIlyaChat;
global $MaxDmitriev, $MaxAndIlyaChat, $messages;

[$response, $json] = sendMessageToChat($MaxAndIlyaChat["id"], $MaxDmitriev);

assertStrict($response['info']['http_code'], 200);

assertStrict($response['info']['http_code'], 201);
assertStrict($json->data->message, $messages["message_sent"]);
});

it("should return error when trying to send message to private chat for NOT a chat participant", function () {
Expand All @@ -133,9 +137,9 @@ function sendMessageToChat($chatId, $user = null): array
});

it("should return error when trying to send message to public chat for NOT a chat participant", function () {
global $messages, $MaxDmitriev, $GymPartyPublicChat;
global $messages, $MatveyGorelik, $GymPartyPublicChat;

[$response, $json] = sendMessageToChat($GymPartyPublicChat["id"], $MaxDmitriev);
[$response, $json] = sendMessageToChat($GymPartyPublicChat["id"], $MatveyGorelik);

assertStrict($response['info']['http_code'], 403);
assertStrict($json->data->error, $messages["not_enough_permission"]);
Expand Down