开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
捐赠
捐赠前请先登录
扫描微信二维码支付
取消
支付完成
支付提示
将跳转至支付宝完成支付
确定
取消
1 Star 1 Fork 0

C++项目/servertech-chat

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
master
分支 (6)
master
feature/48-mysql-connection-pool
gh-pages
bugfix/52-volume-already-in-use
feature/6-simplify-deployment
async-rewrite
master
分支 (6)
master
feature/48-mysql-connection-pool
gh-pages
bugfix/52-volume-already-in-use
feature/6-simplify-deployment
async-rewrite
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
master
分支 (6)
master
feature/48-mysql-connection-pool
gh-pages
bugfix/52-volume-already-in-use
feature/6-simplify-deployment
async-rewrite
servertech-chat
/
server
/
src
/
api
/
chat_websocket.cpp
servertech-chat
/
server
/
src
/
api
/
chat_websocket.cpp
chat_websocket.cpp 7.60 KB
一键复制 编辑 原始数据 按行查看 历史
Ruben Perez 提交于 2023年09月26日 23:21 +08:00 . Authentication, login and account creation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
//
// Copyright (c) 2023 Ruben Perez Hidalgo (rubenperez038 at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "api/chat_websocket.hpp"
#include <boost/asio/spawn.hpp>
#include <boost/beast/websocket/rfc6455.hpp>
#include <boost/core/span.hpp>
#include <boost/variant2/variant.hpp>
#include <cstddef>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
#include "api/api_types.hpp"
#include "business_types.hpp"
#include "error.hpp"
#include "services/cookie_auth_service.hpp"
#include "services/pubsub_service.hpp"
#include "services/redis_client.hpp"
#include "services/room_history_service.hpp"
#include "shared_state.hpp"
#include "util/websocket.hpp"
using namespace chat;
namespace {
// Rooms are static for now.
static constexpr std::array<std::string_view, 4> room_ids{
"beast",
"async",
"db",
"wasm",
};
static constexpr std::array<std::string_view, room_ids.size()> room_names{
"Boost.Beast",
"Boost.Async",
"Database connectors",
"Web assembly",
};
// An owning type containing data for the hello event.
struct hello_data
{
std::vector<room> rooms;
username_map usernames;
};
// Retrieves the data required to send the hello event
static result_with_message<hello_data> get_hello_data(shared_state& st, boost::asio::yield_context yield)
{
// Retrieve room history
room_history_service history_service(st.redis(), st.mysql());
auto history_result = history_service.get_room_history(room_ids, yield);
if (history_result.has_error())
return std::move(history_result).error();
assert(history_result->first.size() == room_ids.size());
// Compose hello data
hello_data res{{}, std::move(history_result->second)};
res.rooms.reserve(room_ids.size());
for (std::size_t i = 0; i < room_ids.size(); ++i)
{
res.rooms.push_back(
room{std::string(room_ids[i]), std::string(room_names[i]), std::move(history_result->first[i])}
);
}
return res;
}
struct event_handler_visitor
{
const user& current_user;
websocket& ws;
shared_state& st;
boost::asio::yield_context yield;
// Parsing error
error_with_message operator()(error_code ec) const noexcept { return error_with_message{ec}; }
// Messages event
error_with_message operator()(client_messages_event& evt) const
{
// Set the timestamp
auto timestamp = timestamp_t::clock::now();
// Compose a message array
std::vector<message> msgs;
msgs.reserve(evt.messages.size());
for (auto& msg : evt.messages)
{
msgs.push_back(message{
"", // blank ID, will be assigned by Redis
std::move(msg.content),
timestamp,
current_user.id,
});
}
// Store it in Redis
auto ids_result = st.redis().store_messages(evt.roomId, msgs, yield);
if (ids_result.has_error())
return std::move(ids_result).error();
auto& ids = ids_result.value();
// Set the message IDs appropriately
assert(msgs.size() == ids.size());
for (std::size_t i = 0; i < msgs.size(); ++i)
msgs[i].id = std::move(ids[i]);
// Compose a server_messages event with all data we have
server_messages_event server_evt{evt.roomId, current_user, msgs};
// Broadcast the event to all clients
st.pubsub().publish(evt.roomId, server_evt.to_json());
return {};
}
// Request room history event
error_with_message operator()(chat::request_room_history_event& evt) const
{
// Get room history
room_history_service svc(st.redis(), st.mysql());
auto history = svc.get_room_history(evt.roomId, yield);
if (history.has_error())
return std::move(history).error();
// Compose a room_history event
chat::room_history_event response_evt{evt.roomId, history->first, history->second};
auto payload = response_evt.to_json();
// Send it
chat::error_code ec;
ws.write(payload, yield[ec]);
return {ec};
}
};
// Messages are broadcast between sessions using the pubsub_service.
// We must implement the message_subscriber interface to use it.
// Each websocket session becomes a subscriber.
// We use room IDs as topic IDs, and websocket message payloads as subscription messages.
class chat_websocket_session final : public message_subscriber,
public std::enable_shared_from_this<chat_websocket_session>
{
websocket ws_;
std::shared_ptr<shared_state> st_;
public:
chat_websocket_session(websocket socket, std::shared_ptr<shared_state> state) noexcept
: ws_(std::move(socket)), st_(std::move(state))
{
}
// Subscriber callback
void on_message(std::string_view serialized_message, boost::asio::yield_context yield) override final
{
ws_.write(serialized_message, yield);
}
// Runs the session until completion
error_with_message run(boost::asio::yield_context yield)
{
error_code ec;
// Check that the user is authenticated
auto user_result = st_->cookie_auth().user_from_cookie(ws_.upgrade_request(), yield);
if (user_result.has_error())
{
// If it's not, close the websocket. This is the preferred approach
// when checking authentication in websockets, as opposed to failing
// the websocket upgrade, since the client doesn't have access to
// upgrade failure information.
log_error(user_result.error(), "Websocket authentication failed");
ws_.close(boost::beast::websocket::policy_error, yield); // Ignore the result
return {};
}
const auto& current_user = user_result.value();
// Lock writes in the websocket. This ensures that no message is written before the hello.
auto write_guard = ws_.lock_writes(yield);
// Subscribe to messages for the available rooms
auto pubsub_guard = st_->pubsub().subscribe_guarded(shared_from_this(), room_ids);
// Retrieve the data required for the hello message
auto hello_data = get_hello_data(*st_, yield);
if (hello_data.has_error())
return hello_data.error();
// Compose the hello event and write it
hello_event hello_evt{current_user, hello_data->rooms, hello_data->usernames};
auto serialized_hello = hello_evt.to_json();
ec = ws_.write_locked(serialized_hello, write_guard, yield);
if (ec)
return {ec};
// Once the hello is sent, we can start sending messages through the websocket
write_guard.reset();
// Read subsequent messages from the websocket and dispatch them
while (true)
{
// Read a message
auto raw_msg = ws_.read(yield);
if (raw_msg.has_error())
return {raw_msg.error()};
// Deserialize it
auto msg = chat::parse_client_event(raw_msg.value());
// Dispatch
auto err = boost::variant2::visit(event_handler_visitor{current_user, ws_, *st_, yield}, msg);
if (err.ec)
return err;
}
}
};
} // namespace
error_with_message chat::handle_chat_websocket(
websocket socket,
std::shared_ptr<shared_state> state,
boost::asio::yield_context yield
)
{
auto sess = std::make_shared<chat_websocket_session>(std::move(socket), std::move(state));
return sess->run(yield);
}
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

Web聊天室项目
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/cppprojects/servertech-chat.git
git@gitee.com:cppprojects/servertech-chat.git
cppprojects
servertech-chat
servertech-chat
master
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /