zischenstand
This commit is contained in:
92
src/modules/socketlib/CHANGELOG.md
Normal file
92
src/modules/socketlib/CHANGELOG.md
Normal file
@@ -0,0 +1,92 @@
|
||||
## 1.1.3
|
||||
- Update compatibility to Foundry 13 (which might also fix an issue with TheForge?)
|
||||
|
||||
## 1.1.2
|
||||
### Compatibility
|
||||
- Updated for compatibility with Foundry 13 (338).
|
||||
|
||||
## 1.1.1
|
||||
- Update module.json for new location and maintainer.
|
||||
|
||||
## 1.1.0
|
||||
### Compatibility
|
||||
- Updated for compatibilty with Foundry 12 (thanks Clemente!)
|
||||
|
||||
## 1.0.13
|
||||
### Compatibility
|
||||
- Verified compatibility with Foundry 11
|
||||
|
||||
|
||||
## 1.0.12
|
||||
### Compatibility
|
||||
- Foundry 10 will no longer show a deprecation warning when modules or systems register in socketlib
|
||||
|
||||
## 1.0.11
|
||||
### Compatibility
|
||||
- Updated for compatibility with Foundry 10
|
||||
|
||||
|
||||
## 1.0.10
|
||||
### Compatibility
|
||||
- Verified compatibility with Foundry 9
|
||||
|
||||
|
||||
## 1.0.9
|
||||
### Compatibility
|
||||
- Verified compatibility with Foundry 0.8.9
|
||||
|
||||
|
||||
## 1.0.8
|
||||
### Compatibility
|
||||
- Verified compatibility with Foundry 0.8.8
|
||||
|
||||
|
||||
## 1.0.7
|
||||
### Compatibility
|
||||
- Verified compatibility with Foundry 0.8.7
|
||||
|
||||
|
||||
## 1.0.6
|
||||
### Compatibility
|
||||
- Verified compatibility with Foundry 0.8.5
|
||||
|
||||
|
||||
## 1.0.5
|
||||
### Compatibility
|
||||
- Add support for Foundry 0.8.2
|
||||
|
||||
|
||||
## 1.0.4
|
||||
### New features
|
||||
- The `this` value of functions now contains the id of the user that triggered the function execution.
|
||||
- Some network packets are now more efficient.
|
||||
|
||||
### Bugfixes
|
||||
- When an invalid user id is specified socketlib will now throw the correct error message.
|
||||
- When a player disconnects the moment an execution has been scheduled for their client the execution function will now throw an exception, as it would if the player hadn't been connected in the first place. Previously the execution would just silently fail and the promise never resolve in such cases.
|
||||
|
||||
|
||||
## 1.0.3
|
||||
### Bugfixes
|
||||
- `executeFor` functions will no longer fail with an exception if a function scheduled to be called by the local user throws.
|
||||
|
||||
|
||||
## 1.0.2
|
||||
### New API endpoints
|
||||
- Added `executeForOthers` and `executeForOtherGMs` that execute for all users/all GMs except the local client.
|
||||
|
||||
### Bugfixes
|
||||
- `executeAsUser` and `executeForUsers` didn't execute locally if the id of the current user was passed in as recipient.
|
||||
- `executeForEveryone` and `executeForAllGMs` now execute locally as well, as they should
|
||||
|
||||
|
||||
## 1.0.1
|
||||
### New features
|
||||
- Added support for game systems
|
||||
|
||||
### Compatibility
|
||||
- Add support for Foundry 0.8.1
|
||||
|
||||
|
||||
## 1.0.0
|
||||
### Initial release
|
||||
21
src/modules/socketlib/LICENSE
Normal file
21
src/modules/socketlib/LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021 Manuel Vögele
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
178
src/modules/socketlib/README.md
Normal file
178
src/modules/socketlib/README.md
Normal file
@@ -0,0 +1,178 @@
|
||||
[](https://ko-fi.com/farling)
|
||||
[](https://patreon.com/amusingtime)
|
||||

|
||||

|
||||

|
||||
|
||||
# socketlib
|
||||
A library for simplifying working with foundries sockets. This module does not have any user facing features. You only need to install it if one of the modules you use lists it as a dependency.
|
||||
|
||||
This library makes it easy to execute functions in the clients of other connected users. Parameters can be passed to the remote functions as easy as they can be passed to regular functions and it's possible to retrieve the return value of the remote function via `await`. The features of socketlib are:
|
||||
- **Execute a function as GM**: socketlib allows you to execute a function as a gm user. If a GM client is connected, that client will execute that function. The original client can wait for the GM to finish the execution of the function and retrieve the return value of the function via `await`. If multiple GMs are connected, socketlib will make sure only one of the GMs will execute the function.
|
||||
- **Execute a function as another user**: socketlib allows you to execute a function in the client of another user. The original client can wait for the other user to finish execution of the function and retrieve the return value the function via `await`.
|
||||
- **Execute a function for all users**: socketlib will execute a function in the clients of all other connected users.
|
||||
- **Execute a function for all GMs**: socketlib will execute a function in the clients of all connected GMs.
|
||||
- **Execute a function for a specified list of players**: socketlib will execute a function in the clients of several players that can be identified by their id.
|
||||
|
||||
## API
|
||||
Below is a small example code that demonstrates the usage of socketlib. All of socketlibs functions are accessible via `socketlib.`. Documentation for each of the available functions can be found blow the example code.
|
||||
|
||||
### Example Code
|
||||
|
||||
```javascript
|
||||
let socket;
|
||||
|
||||
Hooks.once("socketlib.ready", () => {
|
||||
socket = socketlib.registerModule("my-module");
|
||||
socket.register("hello", showHelloMessage);
|
||||
socket.register("add", add);
|
||||
});
|
||||
|
||||
Hooks.once("ready", async () => {
|
||||
// Let's send a greeting to all other connected users.
|
||||
// Functions can either be called by their given name...
|
||||
socket.executeForEveryone("hello", game.user.name);
|
||||
// ...or by passing in the function that you'd like to call.
|
||||
socket.executeForEveryone(showHelloMessage, game.user.name);
|
||||
// The following function will be executed on a GM client.
|
||||
// The return value will be sent back to us.
|
||||
const result = await socket.executeAsGM("add", 5, 3);
|
||||
console.log(`The GM client calculated: ${result}`);
|
||||
});
|
||||
|
||||
function showHelloMessage(userName) {
|
||||
console.log(`User ${userName} says hello!`);
|
||||
}
|
||||
|
||||
function add(a, b) {
|
||||
console.log("The addition is performed on a GM client.");
|
||||
return a + b;
|
||||
}
|
||||
```
|
||||
|
||||
The example code registers the hook `socketlib.ready` this hook is fired once socketlib has initialized and is ready to do it's job. The module registers itself with socketlib. This causes socketlib to start listening for socket messages coming in for the registered module. In addition the registration returns a socket that will be used for all further interactions with socketlib.
|
||||
|
||||
To be able to call a function via socketlib, that function has to be registered in the socket on all clients and must be given a unique name. Since a function can only be called via socketlib if it has been registered on both the calling client and the executing client it's advisable to register all the relevant functions immediately after you've registered your module in socketlib.
|
||||
|
||||
Once foundry is loaded up, the example code sends a hello message to all connected users. For illustrative purposes this is done twice, once by passing in the name given to the function during registration and once by passing in the function that should be called on the other clients. Both ways work. Afterwards the function `add` will be invoked on the client of *one* of the connected GMs. The add function will print a message into the log, which allows you to verify that the function is indeed being executed on the GMs client. The GM will perform the calculation and result, which will be sent back to the original client, which will write the result into it's own log.
|
||||
|
||||
### Function documentation
|
||||
#### socketlib.registerModule
|
||||
```javascript
|
||||
socketlib.registerModule(moduleName);
|
||||
```
|
||||
|
||||
Call `registerModule` to make socketlib listen for sockets that come in for your module. This is the first function in socketlib that your module should call.
|
||||
|
||||
- **moduleName** is the name of your module as specificed in your modules's manifest.
|
||||
|
||||
**Return value**: A socket instance is returned, that is used for all further interactions with socketlib.
|
||||
|
||||
#### socketlib.registerSystem
|
||||
```javascript
|
||||
registerSystem(systemId);
|
||||
```
|
||||
|
||||
Call `registerSystem` to make socketlib listen for sockets that come in for your game system. This is the first function in socketlib that your game system should call.
|
||||
|
||||
- **systemId** the id of your game system as specified in your game system's manifest.
|
||||
|
||||
**Return value**: A socket instance is returned, that is used for all further interactions with socketlib.
|
||||
|
||||
#### socket.register
|
||||
```javascript
|
||||
socket.register(name, func);
|
||||
```
|
||||
|
||||
Registers a function that can subsequently be called using socketlib. It's important that the registration of a function is done on all connected clients before the function is being called via socketlib. Otherwise the call won't succeed. For this reason it's recommended to register all relevant functions during the `socketlib.ready` hook, immediatly after `socketlib.registerModule` has been called.
|
||||
|
||||
- **name** is a name that is used to identify the function within socketlib. This name can be used to call the function later. This name must be unique among all names your module registers within socketlib.
|
||||
- **func** is the function that's being registered within socketlib.
|
||||
|
||||
**Return value**: This function has no return value.
|
||||
|
||||
#### socket.executeAsGM
|
||||
```javascript
|
||||
async socket.executeAsGM(handler, parameters...);
|
||||
```
|
||||
|
||||
Executes a function on the client of exactly one GM. If multiple GMs are connected, one of the GMs will be selected to execute the function. This function will fail if there is no GM connected. The function must have been registered using [`socket.register`](#socketregister) before it can be invoked via this function.
|
||||
|
||||
- **handler** can either be the function that should be executed or the name given to that function during registration.
|
||||
- **parameters...** the parameters that should be passed to the called function. Pass the parameters in comma separated, as you would do for a regular function call.
|
||||
|
||||
**Return value**: The promise that this function returns will resolve once the GM has finished the execution of the invoked function and will yield the return value of that function. If the execution on the GM client fails for some reason, this function will fail with an appropriate Error as well.
|
||||
|
||||
#### socket.executeAsUser
|
||||
```javascript
|
||||
async socket.executeAsUser(handler, userId, parameters...);
|
||||
```
|
||||
|
||||
Executes a function on the client of the specified user. This function will fail if the specified user is not connected. The function must have been registered using [`socket.register`](#socketregister) before it can be invoked via this function.
|
||||
|
||||
- **handler** can either be the function that should be executed or the name given to that function during registration.
|
||||
- **userId** the id of the user that should execute this function.
|
||||
- **parameters...** the parameters that should be passed to the called function. Pass the parameters in comma separated, as you would do for a regular function call.
|
||||
|
||||
**Return value**: The promise that this function returns will resolve once the user has finished the execution of the invoked function and will yield the return value of that function. If the execution on other user's client fails for some reason, this function will fail with an appropriate Error as well.
|
||||
|
||||
#### socket.executeForAllGMs
|
||||
```javascript
|
||||
async socket.executeForAllGMs(handler, parameters...);
|
||||
```
|
||||
|
||||
Executes a function on the clients of all connected GMs. If the current user is a GM the function will be executed locally as well. The function must have been registered using [`socket.register`](#socketregister) before it can be invoked via this function.
|
||||
|
||||
- **handler** can either be the function that should be executed or the name given to that function during registration.
|
||||
- **parameters...** the parameters that should be passed to the called function. Pass the parameters in comma separated, as you would do for a regular function call.
|
||||
|
||||
**Return value**: The promise returned by this function will resolve as soon as the request for execution has been sent to the connected GM clients and *will not* wait until those clients have finished processing that function. The promise will not yield any return value.
|
||||
|
||||
#### socket.executeForOtherGMs
|
||||
```javascript
|
||||
async socket.executeForOtherGMs(handler, parameters...);
|
||||
```
|
||||
|
||||
Executes a function on the clients of all connected GMs, except for the current user. If the current user is not a GM this function has the same behavior as [`socket.executeForAllGMs`](#socketexecuteasgm). The function must have been registered using [`socket.register`](#socketregister) before it can be invoked via this function.
|
||||
|
||||
- **handler** can either be the function that should be executed or the name given to that function during registration.
|
||||
- **parameters...** the parameters that should be passed to the called function. Pass the parameters in comma separated, as you would do for a regular function call.
|
||||
|
||||
**Return value**: The promise returned by this function will resolve as soon as the request for execution has been sent to the connected GM clients and *will not* wait until those clients have finished processing that function. The promise will not yield any return value.
|
||||
|
||||
#### socket.executeForEveryone
|
||||
```javascript
|
||||
async socket.executeForEveryone(handler, ...args);
|
||||
```
|
||||
|
||||
Executes a function on all connected clients, including on the local client. The function must have been registered using [`socket.register`](#socketregister) before it can be invoked via this function.
|
||||
|
||||
- **handler** can either be the function that should be executed or the name given to that function during registration.
|
||||
- **parameters...** the parameters that should be passed to the called function. Pass the parameters in comma separated, as you would do for a regular function call.
|
||||
|
||||
**Return value**: The promise returned by this function will resolve as soon as the request for execution has been sent to the connected clients and *will not* wait until those clients have finished processing that function. The promise will not yield any return value.
|
||||
|
||||
#### socket.executeForOthers
|
||||
```javascript
|
||||
async socket.executeForOthers(handler, ...args);
|
||||
```
|
||||
|
||||
Executes a function on all connected clients, but not locally. The function must have been registered using [`socket.register`](#socketregister) before it can be invoked via this function.
|
||||
|
||||
- **handler** can either be the function that should be executed or the name given to that function during registration.
|
||||
- **parameters...** the parameters that should be passed to the called function. Pass the parameters in comma separated, as you would do for a regular function call.
|
||||
|
||||
**Return value**: The promise returned by this function will resolve as soon as the request for execution has been sent to the connected clients and *will not* wait until those clients have finished processing that function. The promise will not yield any return value.
|
||||
|
||||
#### socket.executeForUsers
|
||||
```javascript
|
||||
async executeForUsers(handler, recipients, ...args);
|
||||
```
|
||||
|
||||
Executes a function on the clients of a specified list of players. The function must have been registered using [`socket.register`](#socketregister) before it can be invoked via this function.
|
||||
|
||||
- **handler** can either be the function that should be executed or the name given to that function during registration.
|
||||
- **recipients** an array of user ids that should execute the function.
|
||||
- **parameters...** the parameters that should be passed to the called function. Pass the parameters in comma separated, as you would do for a regular function call.
|
||||
|
||||
**Return value**: The promise returned by this function will resolve as soon as the request for execution has been sent to the specified clients and *will not* wait until those clients have finished processing that function. The promise will not yield any return value.
|
||||
36
src/modules/socketlib/module.json
Normal file
36
src/modules/socketlib/module.json
Normal file
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"id": "socketlib",
|
||||
"title": "socketlib",
|
||||
"description": "A library for easier handling of foundry sockets",
|
||||
"version": "v1.1.3",
|
||||
"compatibility": {
|
||||
"minimum": "11",
|
||||
"verified": "13"
|
||||
},
|
||||
"library": true,
|
||||
"authors": [
|
||||
{
|
||||
"name": "Farling",
|
||||
"url": "https://github.com/farling42",
|
||||
"email": "foundryvtt@amusingtime.uk",
|
||||
"discord": "farling",
|
||||
"ko-fi": "farling",
|
||||
"patreon": "amusingtime"
|
||||
},
|
||||
{
|
||||
"name": "Manuel Vögele",
|
||||
"email": "develop@manuel-voegele.de",
|
||||
"discord": "Stäbchenfisch#5107",
|
||||
"flags": {}
|
||||
}
|
||||
],
|
||||
"esmodules": [
|
||||
"src/socketlib.js"
|
||||
],
|
||||
"url": "https://github.com/farling42/foundryvtt-socketlib",
|
||||
"download": "https://github.com/farling42/foundryvtt-socketlib/releases/download/v1.1.3/module.zip",
|
||||
"manifest": "https://github.com/farling42/foundryvtt-socketlib/releases/latest/download/module.json",
|
||||
"readme": "https://github.com/farling42/foundryvtt-socketlib/blob/master/README.md",
|
||||
"changelog": "https://github.com/farling42/foundryvtt-socketlib/blob/master/CHANGELOG.md",
|
||||
"bugs": "https://github.com/farling42/foundryvtt-socketlib/issues"
|
||||
}
|
||||
41
src/modules/socketlib/src/errors.js
Normal file
41
src/modules/socketlib/src/errors.js
Normal file
@@ -0,0 +1,41 @@
|
||||
export class SocketlibError extends Error {
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
this.name = "SocketlibError";
|
||||
}
|
||||
}
|
||||
|
||||
export class SocketlibInternalError extends SocketlibError {
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
this.name = "SocketlibInternalError";
|
||||
}
|
||||
}
|
||||
|
||||
export class SocketlibInvalidUserError extends SocketlibError {
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
this.name = "SocketlibInvalidUserError";
|
||||
}
|
||||
}
|
||||
|
||||
export class SocketlibNoGMConnectedError extends SocketlibError {
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
this.name = "SocketlibNoGMConnectedError";
|
||||
}
|
||||
}
|
||||
|
||||
export class SocketlibRemoteException extends SocketlibError {
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
this.name = "SocketlibRemoteException";
|
||||
}
|
||||
}
|
||||
|
||||
export class SocketlibUnregisteredHandlerError extends SocketlibError {
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
this.name = "SocketlibUnregisteredHandlerError";
|
||||
}
|
||||
}
|
||||
335
src/modules/socketlib/src/socketlib.js
Normal file
335
src/modules/socketlib/src/socketlib.js
Normal file
@@ -0,0 +1,335 @@
|
||||
import * as errors from "./errors.js";
|
||||
|
||||
const RECIPIENT_TYPES = {
|
||||
ONE_GM: 0,
|
||||
ALL_GMS: 1,
|
||||
EVERYONE: 2,
|
||||
}
|
||||
|
||||
const MESSAGE_TYPES = {
|
||||
COMMAND: 0,
|
||||
REQUEST: 1,
|
||||
RESPONSE: 2,
|
||||
RESULT: 3,
|
||||
EXCEPTION: 4,
|
||||
UNREGISTERED: 5,
|
||||
}
|
||||
|
||||
Hooks.once("init", () => {
|
||||
window.socketlib = new Socketlib();
|
||||
Hooks.callAll("socketlib.ready");
|
||||
});
|
||||
|
||||
Hooks.on("userConnected", handleUserActivity);
|
||||
|
||||
class Socketlib {
|
||||
constructor() {
|
||||
this.modules = new Map();
|
||||
this.system = undefined;
|
||||
this.errors = errors;
|
||||
}
|
||||
|
||||
registerModule(moduleName) {
|
||||
const existingSocket = this.modules.get(moduleName);
|
||||
if (existingSocket)
|
||||
return existingSocket;
|
||||
const module = game.modules.get(moduleName);
|
||||
if (!module?.active) {
|
||||
console.error(`socketlib | Someone tried to register module '${moduleName}', but no module with that name is active. As a result the registration request has been ignored.`);
|
||||
return undefined;
|
||||
}
|
||||
if (!module.socket) {
|
||||
console.error(`socketlib | Failed to register socket for module '${moduleName}'. Please set '"socket":true' in your manifset and restart foundry (you need to reload your world - simply reloading your browser won't do).`);
|
||||
return undefined;
|
||||
}
|
||||
const newSocket = new SocketlibSocket(moduleName, "module");
|
||||
this.modules.set(moduleName, newSocket);
|
||||
return newSocket;
|
||||
}
|
||||
|
||||
registerSystem(systemId) {
|
||||
if (game.system.id !== systemId) {
|
||||
console.error(`socketlib | Someone tried to register system '${systemId}', but that system isn't active. As a result the registration request has been ignored.`);
|
||||
return undefined;
|
||||
}
|
||||
const existingSocket = this.system;
|
||||
if (existingSocket)
|
||||
return existingSocket;
|
||||
if (!game.system.socket) {
|
||||
console.error(`socketlib | Failed to register socket for system '${systemId}'. Please set '"socket":true' in your manifest and restart foundry (you need to reload your world - simply reloading your browser won't do).`);
|
||||
}
|
||||
const newSocket = new SocketlibSocket(systemId, "system");
|
||||
this.system = newSocket;
|
||||
return newSocket;
|
||||
}
|
||||
}
|
||||
|
||||
class SocketlibSocket {
|
||||
constructor(moduleName, moduleType) {
|
||||
this.functions = new Map();
|
||||
this.socketName = `${moduleType}.${moduleName}`;
|
||||
this.pendingRequests = new Map();
|
||||
game.socket.on(this.socketName, this._onSocketReceived.bind(this));
|
||||
}
|
||||
|
||||
register(name, func) {
|
||||
if (!(func instanceof Function)) {
|
||||
console.error(`socketlib | Cannot register non-function as socket handler for '${name}' for '${this.socketName}'.`);
|
||||
return;
|
||||
}
|
||||
if (this.functions.has(name)) {
|
||||
console.warn(`socketlib | Function '${name}' is already registered for '${this.socketName}'. Ignoring registration request.`);
|
||||
return;
|
||||
}
|
||||
this.functions.set(name, func);
|
||||
}
|
||||
|
||||
async executeAsGM(handler, ...args) {
|
||||
const [name, func] = this._resolveFunction(handler);
|
||||
if (game.user.isGM) {
|
||||
return this._executeLocal(func, ...args);
|
||||
}
|
||||
else {
|
||||
if (!game.users.activeGM) {
|
||||
throw new errors.SocketlibNoGMConnectedError(`Could not execute handler '${name}' (${func.name}) as GM, because no GM is connected.`);
|
||||
}
|
||||
return this._sendRequest(name, args, RECIPIENT_TYPES.ONE_GM);
|
||||
}
|
||||
}
|
||||
|
||||
async executeAsUser(handler, userId, ...args) {
|
||||
const [name, func] = this._resolveFunction(handler);
|
||||
if (userId === game.userId)
|
||||
return this._executeLocal(func, ...args);
|
||||
const user = game.users.get(userId);
|
||||
if (!user)
|
||||
throw new errors.SocketlibInvalidUserError(`No user with id '${userId}' exists.`);
|
||||
if (!user.active)
|
||||
throw new errors.SocketlibInvalidUserError(`User '${user.name}' (${userId}) is not connected.`);
|
||||
return this._sendRequest(name, args, [userId]);
|
||||
}
|
||||
|
||||
async executeForAllGMs(handler, ...args) {
|
||||
const [name, func] = this._resolveFunction(handler);
|
||||
this._sendCommand(name, args, RECIPIENT_TYPES.ALL_GMS);
|
||||
if (game.user.isGM) {
|
||||
try {
|
||||
this._executeLocal(func, ...args);
|
||||
}
|
||||
catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async executeForOtherGMs(handler, ...args) {
|
||||
const [name, func] = this._resolveFunction(handler);
|
||||
this._sendCommand(name, args, RECIPIENT_TYPES.ALL_GMS);
|
||||
}
|
||||
|
||||
async executeForEveryone(handler, ...args) {
|
||||
const [name, func] = this._resolveFunction(handler);
|
||||
this._sendCommand(name, args, RECIPIENT_TYPES.EVERYONE);
|
||||
try {
|
||||
this._executeLocal(func, ...args);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
async executeForOthers(handler, ...args) {
|
||||
const [name, func] = this._resolveFunction(handler);
|
||||
this._sendCommand(name, args, RECIPIENT_TYPES.EVERYONE);
|
||||
}
|
||||
|
||||
async executeForUsers(handler, recipients, ...args) {
|
||||
if (!(recipients instanceof Array))
|
||||
throw new TypeError("Recipients parameter must be an array of user ids.");
|
||||
const [name, func] = this._resolveFunction(handler);
|
||||
const currentUserIndex = recipients.indexOf(game.userId);
|
||||
if (currentUserIndex >= 0)
|
||||
recipients.splice(currentUserIndex, 1);
|
||||
this._sendCommand(name, args, recipients);
|
||||
if (currentUserIndex >= 0) {
|
||||
try {
|
||||
this._executeLocal(func, ...args);
|
||||
}
|
||||
catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_sendRequest(handlerName, args, recipient) {
|
||||
const message = {handlerName, args, recipient};
|
||||
message.id = foundry.utils.randomID();
|
||||
message.type = MESSAGE_TYPES.REQUEST;
|
||||
const promise = new Promise((resolve, reject) => this.pendingRequests.set(message.id, {handlerName, resolve, reject, recipient}));
|
||||
game.socket.emit(this.socketName, message);
|
||||
return promise;
|
||||
}
|
||||
|
||||
_sendCommand(handlerName, args, recipient) {
|
||||
const message = {handlerName, args, recipient};
|
||||
message.type = MESSAGE_TYPES.COMMAND;
|
||||
game.socket.emit(this.socketName, message);
|
||||
}
|
||||
|
||||
_sendResult(id, result) {
|
||||
const message = {id, result};
|
||||
message.type = MESSAGE_TYPES.RESULT;
|
||||
game.socket.emit(this.socketName, message);
|
||||
}
|
||||
|
||||
_sendError(id, type) {
|
||||
const message = {id, type};
|
||||
message.userId = game.userId;
|
||||
game.socket.emit(this.socketName, message);
|
||||
}
|
||||
|
||||
_executeLocal(func, ...args) {
|
||||
const socketdata = {userId: game.userId};
|
||||
return func.call({socketdata}, ...args);
|
||||
}
|
||||
|
||||
_resolveFunction(func) {
|
||||
if (func instanceof Function) {
|
||||
const entry = Array.from(this.functions.entries()).find(([key, val]) => val === func);
|
||||
if (!entry)
|
||||
throw new errors.SocketlibUnregisteredHandlerError(`Function '${func.name}' has not been registered as a socket handler.`);
|
||||
return [entry[0], func];
|
||||
}
|
||||
else {
|
||||
const fn = this.functions.get(func);
|
||||
if (!fn)
|
||||
throw new errors.SocketlibUnregisteredHandlerError(`No socket handler with the name '${func}' has been registered.`)
|
||||
return [func, fn];
|
||||
}
|
||||
}
|
||||
|
||||
_onSocketReceived(message, senderId) {
|
||||
if (message.type === MESSAGE_TYPES.COMMAND || message.type === MESSAGE_TYPES.REQUEST)
|
||||
this._handleRequest(message, senderId);
|
||||
else
|
||||
this._handleResponse(message, senderId);
|
||||
}
|
||||
|
||||
async _handleRequest(message, senderId) {
|
||||
const {handlerName, args, recipient, id, type} = message;
|
||||
// Check if we're the recipient of the received message. If not, return early.
|
||||
if (recipient instanceof Array) {
|
||||
if (!recipient.includes(game.userId))
|
||||
return;
|
||||
}
|
||||
else {
|
||||
switch (recipient) {
|
||||
case RECIPIENT_TYPES.ONE_GM:
|
||||
if (!game.users.activeGM?.isSelf)
|
||||
return;
|
||||
break;
|
||||
case RECIPIENT_TYPES.ALL_GMS:
|
||||
if (!game.user.isGM)
|
||||
return;
|
||||
break;
|
||||
case RECIPIENT_TYPES.EVERYONE:
|
||||
break;
|
||||
default:
|
||||
console.error(`Unkown recipient '${recipient}' when trying to execute '${handlerName}' for '${this.socketName}'. This should never happen. If you see this message, please open an issue in the bug tracker of the socketlib repository.`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
let name, func;
|
||||
try {
|
||||
[name, func] = this._resolveFunction(handlerName);
|
||||
}
|
||||
catch (e) {
|
||||
if (e instanceof errors.SocketlibUnregisteredHandlerError && type === MESSAGE_TYPES.REQUEST) {
|
||||
this._sendError(id, MESSAGE_TYPES.UNREGISTERED);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
const socketdata = {userId: senderId};
|
||||
const _this = {socketdata};
|
||||
if (type === MESSAGE_TYPES.COMMAND) {
|
||||
func.call(_this, ...args);
|
||||
}
|
||||
else {
|
||||
let result;
|
||||
try {
|
||||
result = await func.call(_this, ...args);
|
||||
}
|
||||
catch (e) {
|
||||
console.error(`An exception occured while executing handler '${name}'.`);
|
||||
this._sendError(id, MESSAGE_TYPES.EXCEPTION);
|
||||
throw e;
|
||||
}
|
||||
this._sendResult(id, result);
|
||||
}
|
||||
}
|
||||
|
||||
_handleResponse(message, senderId) {
|
||||
const {id, result, type} = message;
|
||||
const request = this.pendingRequests.get(id);
|
||||
if (!request)
|
||||
return;
|
||||
if (!this._isResponseSenderValid(senderId, request.recipient)) {
|
||||
console.warn("socketlib | Dropped a response that was received from the wrong user. This means that either someone is inserting messages into the socket or this is a socketlib issue. If the latter is the case please file a bug report in the socketlib repository.")
|
||||
console.info(senderId, request.recipient);
|
||||
return;
|
||||
}
|
||||
switch (type) {
|
||||
case MESSAGE_TYPES.RESULT:
|
||||
request.resolve(result);
|
||||
break;
|
||||
case MESSAGE_TYPES.EXCEPTION:
|
||||
request.reject(new errors.SocketlibRemoteException(`An exception occured during remote execution of handler '${request.handlerName}'. Please see ${game.users.get(message.userId).name}'s error console for details.`));
|
||||
break;
|
||||
case MESSAGE_TYPES.UNREGISTERED:
|
||||
request.reject(new errors.SocketlibUnregisteredHandlerError(`Executing the handler '${request.handlerName}' has been refused by ${game.users.get(message.userId).name}'s client, because this handler hasn't been registered on that client.`));
|
||||
break;
|
||||
default:
|
||||
request.reject(new errors.SocketlibInternalError(`Unknown result type '${type}' for handler '${request.handlerName}'. This should never happen. If you see this message, please open an issue in the bug tracker of the socketlib repository.`));
|
||||
break;
|
||||
}
|
||||
this.pendingRequests.delete(id);
|
||||
}
|
||||
|
||||
_isResponseSenderValid(senderId, recipients) {
|
||||
if (recipients === RECIPIENT_TYPES.ONE_GM && game.users.get(senderId).isGM)
|
||||
return true;
|
||||
if (recipients instanceof Array && recipients.includes(senderId))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleUserActivity(user, active) {
|
||||
if (!active) {
|
||||
const modules = Array.from(socketlib.modules.values());
|
||||
if (socketlib.system)
|
||||
modules.concat(socketlib.system);
|
||||
// Reject all promises that are still waiting for a response from this player
|
||||
for (const socket of modules) {
|
||||
const failedRequests = Array.from(socket.pendingRequests.entries()).filter(([id, request]) => {
|
||||
const recipient = request.recipient;
|
||||
const handlerName = request.handlerName;
|
||||
if (recipient === RECIPIENT_TYPES.ONE_GM) {
|
||||
if (!game.users.activeGM) {
|
||||
request.reject(new errors.SocketlibNoGMConnectedError(`Could not execute handler '${handlerName}' as GM, because all GMs disconnected while the execution was being dispatched.`));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
else if (recipient instanceof Array) {
|
||||
if (recipient.includes(user.id)) {
|
||||
request.reject(new errors.SocketlibInvalidUserError(`User '${user.name}' (${user.id}) disconnected while handler '${handlerName}' was being dispatched.`));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
for (const [id, request] of failedRequests) {
|
||||
socket.pendingRequests.delete(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user