#include "user.h" #include #include #include #include #include #include "room.h" #include #include #include #include namespace Yc { namespace Lib { User::User(Room *parent, std::string name, std::string color, int socket) : _parent(parent), _name(name), _color(color), _socket(socket), _stop(false) { _token = Yc::Lib::Tools::generateRandomString(32); sendMsg(token, _token, "", ""); thread = new std::thread(&User::checkerTask, this); } User::~User() { delete thread; _parent->addMessage(User::system, "leaved_chat", _name, _color); } std::string User::name() const { return _name; } bool User::validateToken(std::string token) { return (token == _token); } bool User::isUser(User *toValidate) { return (toValidate == this); } void User::sendMsg(MsgType type, std::string message , std::string userName, std::string color) { Json::Value sendMessage; sendMessage["type"] = type; sendMessage["message"] = message; sendMessage["userName"] = userName; sendMessage["color"] = color; send(sendMessage); } void User::sendMsg(User::MsgType type, Json::Value message, std::string userName, std::string color) { Json::Value sendMessage; sendMessage["type"] = type; sendMessage["message"] = message; sendMessage["userName"] = userName; sendMessage["color"] = color; send(sendMessage); } void User::checkerTask() { while (!_stop) { fd_set readSd; FD_ZERO(&readSd); FD_SET(_socket, &readSd); timeval tv; tv.tv_sec = 0; tv.tv_usec = 500; int selectResult = select(_socket + 1, &readSd, NULL, NULL, &tv); std::cout << selectResult << "/" << FD_ISSET(_socket, &readSd) << std::endl; if (selectResult == 1 && FD_ISSET(_socket, &readSd) == 1) { _parent->removeUser(_token); _stop = true; } std::string msg = readSocket(_socket); if (msg == "") { continue; } std::cout << msg << std::endl; handleMessage(msg); } } void User::stop() { _stop = true; } std::string User::color() const { return _color; } void User::send(std::string out) { Base::send(_socket, out); } void User::send(Json::Value out) { Base::send(_socket, out); } void User::handleMessage(std::string message) { Json::Value jsonTree = getJsonTree(message); if (jsonTree["type"].asString() == "message") { _parent->addMessage(User::message, jsonTree["message"].asString(), _name, _color); } } } // namespace Lib } // namespace Yc