60 lines
2.0 KiB
TypeScript
60 lines
2.0 KiB
TypeScript
import { ChatMessage, Client, LocalClient, NetworkMessage, PeerClient, PeerServer } from "@/network";
|
|
import { ActionTree, Commit } from "vuex";
|
|
|
|
import { AppState } from "../types";
|
|
import { ConnectOptions, NetworkState, StartServerOptions } from "./types";
|
|
|
|
function bindClientEvents(commit: Commit, client: Client) {
|
|
client.on("handshake", () => {
|
|
commit("playerListChanged", client.players);
|
|
});
|
|
client.on("player-joined", () => commit("playerListChanged", client.players));
|
|
client.on("player-left", () => commit("playerListChanged", client.players));
|
|
client.on("rename", () => commit("playerListChanged", client.players));
|
|
}
|
|
|
|
const actions: ActionTree<NetworkState, AppState> = {
|
|
startServer({ commit }, options: StartServerOptions) {
|
|
const local = new LocalClient(options.playerInfo);
|
|
const server = new PeerServer(options.roomInfo, local, options._customPeer);
|
|
server.once("open", id => {
|
|
commit("serverAssignedID", id);
|
|
});
|
|
bindClientEvents(commit, local);
|
|
commit("becomeServer", { local, server });
|
|
},
|
|
|
|
connect({ commit }, options: ConnectOptions) {
|
|
const client = new PeerClient(options.playerInfo, options._customPeer);
|
|
commit("becomeClient", { peer: client, id: options.serverID });
|
|
client.on("connected", () => {
|
|
commit("connectionStatusChanged", "connected");
|
|
});
|
|
client.on("disconnected", () => {
|
|
commit("connectionStatusChanged", "disconnected");
|
|
});
|
|
client.on("error", err => {
|
|
commit("connectionError", err);
|
|
});
|
|
bindClientEvents(commit, client);
|
|
client.connect(options.serverID);
|
|
},
|
|
|
|
sendChatMessage({ commit, dispatch, getters }, message: ChatMessage) {
|
|
if (getters.connectionType == "none") {
|
|
throw new Error("not connected");
|
|
}
|
|
dispatch("sendMessage", message);
|
|
commit("receivedChatMessage", message);
|
|
},
|
|
|
|
sendMessage({ getters }, message: NetworkMessage) {
|
|
if (getters.connectionType == "none") {
|
|
throw new Error("not connected");
|
|
}
|
|
(getters.client as Client).send(message);
|
|
}
|
|
};
|
|
|
|
export default actions;
|