Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 71c149a954 | |||
| 2e03f5a5c3 | |||
| 39c30c357a | |||
| b3b8b138bf | |||
| fb3aeaf813 | |||
| 5d9dd82a7d | |||
| 6a70df04e7 | |||
| 1fa8e03406 | |||
| 1646bbbe3b | |||
| 971c92b21a | |||
| 6a5190b0a8 | |||
| 86b0162c9c | |||
| 2909bc16f5 | |||
| 4852da9bd5 |
25
CHANGELOG.md
25
CHANGELOG.md
@@ -1,3 +1,28 @@
|
|||||||
|
## 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
|
## 1.0.2
|
||||||
### New API endpoints
|
### New API endpoints
|
||||||
- Added `executeForOthers` and `executeForOtherGMs` that execute for all users/all GMs except the local client.
|
- Added `executeForOthers` and `executeForOtherGMs` that execute for all users/all GMs except the local client.
|
||||||
|
|||||||
14
README.md
14
README.md
@@ -92,7 +92,7 @@ Registers a function that can subsequently be called using socketlib. It's impor
|
|||||||
async socket.executeAsGM(handler, parameters...);
|
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.
|
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.
|
- **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.
|
- **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.
|
||||||
@@ -104,7 +104,7 @@ Executes a function on the client of exactly one GM. If multiple GMs are connect
|
|||||||
async socket.executeAsUser(handler, userId, parameters...);
|
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.
|
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.
|
- **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.
|
- **userId** the id of the user that should execute this function.
|
||||||
@@ -117,7 +117,7 @@ Executes a function on the client of the specified user. This function will fail
|
|||||||
async socket.executeForAllGMs(handler, parameters...);
|
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.
|
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.
|
- **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.
|
- **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.
|
||||||
@@ -129,7 +129,7 @@ Executes a function on the clients of all connected GMs. If the current user is
|
|||||||
async socket.executeForOtherGMs(handler, parameters...);
|
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).
|
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.
|
- **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.
|
- **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.
|
||||||
@@ -141,7 +141,7 @@ Executes a function on the clients of all connected GMs, except for the current
|
|||||||
async socket.executeForEveryone(handler, ...args);
|
async socket.executeForEveryone(handler, ...args);
|
||||||
```
|
```
|
||||||
|
|
||||||
Executes a function on all connected clients, including on the local client.
|
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.
|
- **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.
|
- **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.
|
||||||
@@ -153,7 +153,7 @@ Executes a function on all connected clients, including on the local client.
|
|||||||
async socket.executeForOthers(handler, ...args);
|
async socket.executeForOthers(handler, ...args);
|
||||||
```
|
```
|
||||||
|
|
||||||
Executes a function on all connected clients, but not locally.
|
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.
|
- **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.
|
- **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.
|
||||||
@@ -165,7 +165,7 @@ Executes a function on all connected clients, but not locally.
|
|||||||
async executeForUsers(handler, recipients, ...args);
|
async executeForUsers(handler, recipients, ...args);
|
||||||
```
|
```
|
||||||
|
|
||||||
Executes a function on the clients of a specified list of players.
|
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.
|
- **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.
|
- **recipients** an array of user ids that should execute the function.
|
||||||
|
|||||||
@@ -2,9 +2,9 @@
|
|||||||
"name": "socketlib",
|
"name": "socketlib",
|
||||||
"title": "socketlib",
|
"title": "socketlib",
|
||||||
"description": "A library for easier handling of foundry sockets",
|
"description": "A library for easier handling of foundry sockets",
|
||||||
"version": "1.0.2",
|
"version": "1.0.6",
|
||||||
"minimumCoreVersion" : "0.7.9",
|
"minimumCoreVersion" : "0.7.9",
|
||||||
"compatibleCoreVersion" : "0.8.1",
|
"compatibleCoreVersion" : "0.8.5",
|
||||||
"library": true,
|
"library": true,
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
@@ -14,10 +14,11 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"esmodules": [
|
"esmodules": [
|
||||||
|
"src/libwrapper_shim.js",
|
||||||
"src/socketlib.js"
|
"src/socketlib.js"
|
||||||
],
|
],
|
||||||
"url": "https://github.com/manuelVo/foundryvtt-socketlib",
|
"url": "https://github.com/manuelVo/foundryvtt-socketlib",
|
||||||
"download": "https://github.com/manuelVo/foundryvtt-socketlib/archive/v1.0.2.zip",
|
"download": "https://github.com/manuelVo/foundryvtt-socketlib/archive/v1.0.6.zip",
|
||||||
"manifest": "https://raw.githubusercontent.com/manuelVo/foundryvtt-socketlib/master/module.json",
|
"manifest": "https://raw.githubusercontent.com/manuelVo/foundryvtt-socketlib/master/module.json",
|
||||||
"readme": "https://github.com/manuelVo/foundryvtt-socketlib/blob/master/README.md",
|
"readme": "https://github.com/manuelVo/foundryvtt-socketlib/blob/master/README.md",
|
||||||
"changelog": "https://github.com/manuelVo/foundryvtt-socketlib/blob/master/CHANGELOG.md",
|
"changelog": "https://github.com/manuelVo/foundryvtt-socketlib/blob/master/CHANGELOG.md",
|
||||||
|
|||||||
61
src/libwrapper_shim.js
Normal file
61
src/libwrapper_shim.js
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
// Copyright © 2021 fvtt-lib-wrapper Rui Pinheiro
|
||||||
|
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
// A shim for the libWrapper library
|
||||||
|
export let libWrapper = undefined;
|
||||||
|
|
||||||
|
Hooks.once('init', () => {
|
||||||
|
// Check if the real module is already loaded - if so, use it
|
||||||
|
if(globalThis.libWrapper && !(globalThis.libWrapper.is_fallback ?? true)) {
|
||||||
|
libWrapper = globalThis.libWrapper;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback implementation
|
||||||
|
libWrapper = class {
|
||||||
|
static get is_fallback() { return true };
|
||||||
|
|
||||||
|
static register(module, target, fn, type="MIXED", {chain=undefined}={}) {
|
||||||
|
const is_setter = target.endsWith('#set');
|
||||||
|
target = !is_setter ? target : target.slice(0, -4);
|
||||||
|
const split = target.split('.');
|
||||||
|
const fn_name = split.pop();
|
||||||
|
const root_nm = split.splice(0,1)[0];
|
||||||
|
const _eval = eval; // The browser doesn't expose all global variables (e.g. 'Game') inside globalThis, but it does to an eval. We copy it to a variable to have it run in global scope.
|
||||||
|
const obj = split.reduce((x,y)=>x[y], globalThis[root_nm] ?? _eval(root_nm));
|
||||||
|
|
||||||
|
let iObj = obj;
|
||||||
|
let descriptor = null;
|
||||||
|
while(iObj) {
|
||||||
|
descriptor = Object.getOwnPropertyDescriptor(iObj, fn_name);
|
||||||
|
if(descriptor) break;
|
||||||
|
iObj = Object.getPrototypeOf(iObj);
|
||||||
|
}
|
||||||
|
if(!descriptor || descriptor?.configurable === false) throw `libWrapper Shim: '${target}' does not exist, could not be found, or has a non-configurable descriptor.`;
|
||||||
|
|
||||||
|
let original = null;
|
||||||
|
const wrapper = (chain ?? type != 'OVERRIDE') ? function() { return fn.call(this, original.bind(this), ...arguments); } : function() { return fn.apply(this, arguments); };
|
||||||
|
|
||||||
|
if(!is_setter) {
|
||||||
|
if(descriptor.value) {
|
||||||
|
original = descriptor.value;
|
||||||
|
descriptor.value = wrapper;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
original = descriptor.get;
|
||||||
|
descriptor.get = wrapper;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
if(!descriptor.set) throw `libWrapper Shim: '${target}' does not have a setter`;
|
||||||
|
original = descriptor.set;
|
||||||
|
descriptor.set = wrapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
descriptor.configurable = true;
|
||||||
|
Object.defineProperty(obj, fn_name, descriptor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
127
src/socketlib.js
127
src/socketlib.js
@@ -1,3 +1,4 @@
|
|||||||
|
import {libWrapper} from "./libwrapper_shim.js";
|
||||||
import * as errors from "./errors.js";
|
import * as errors from "./errors.js";
|
||||||
|
|
||||||
const RECIPIENT_TYPES = {
|
const RECIPIENT_TYPES = {
|
||||||
@@ -17,12 +18,14 @@ const MESSAGE_TYPES = {
|
|||||||
|
|
||||||
Hooks.once("init", () => {
|
Hooks.once("init", () => {
|
||||||
window.socketlib = new Socketlib();
|
window.socketlib = new Socketlib();
|
||||||
|
libWrapper.register("socketlib", "Users.prototype.constructor._handleUserActivity", handleUserActivity);
|
||||||
Hooks.callAll("socketlib.ready");
|
Hooks.callAll("socketlib.ready");
|
||||||
});
|
}, "WRAPPER");
|
||||||
|
|
||||||
class Socketlib {
|
class Socketlib {
|
||||||
constructor() {
|
constructor() {
|
||||||
this.modules = new Map();
|
this.modules = new Map();
|
||||||
|
this.system = undefined;
|
||||||
this.errors = errors;
|
this.errors = errors;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,10 +87,10 @@ class SocketlibSocket {
|
|||||||
async executeAsGM(handler, ...args) {
|
async executeAsGM(handler, ...args) {
|
||||||
const [name, func] = this._resolveFunction(handler);
|
const [name, func] = this._resolveFunction(handler);
|
||||||
if (game.user.isGM) {
|
if (game.user.isGM) {
|
||||||
return func(...args);
|
return this._executeLocal(func, ...args);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
if (!game.users.find(user => user.isGM && user.active)) {
|
if (!game.users.find(isActiveGM)) {
|
||||||
throw new errors.SocketlibNoGMConnectedError(`Could not execute handler '${name}' (${func.name}) as GM, because no GM is connected.`);
|
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);
|
return this._sendRequest(name, args, RECIPIENT_TYPES.ONE_GM);
|
||||||
@@ -97,21 +100,26 @@ class SocketlibSocket {
|
|||||||
async executeAsUser(handler, userId, ...args) {
|
async executeAsUser(handler, userId, ...args) {
|
||||||
const [name, func] = this._resolveFunction(handler);
|
const [name, func] = this._resolveFunction(handler);
|
||||||
if (userId === game.userId)
|
if (userId === game.userId)
|
||||||
return func(...args);
|
return this._executeLocal(func, ...args);
|
||||||
const user = game.users.get(userId);
|
const user = game.users.get(userId);
|
||||||
if (!user)
|
if (!user)
|
||||||
throw new SocketlibInvalidUserError(`No user with id '${userId}' exists.`);
|
throw new errors.SocketlibInvalidUserError(`No user with id '${userId}' exists.`);
|
||||||
if (!user.active)
|
if (!user.active)
|
||||||
throw new SocketlibInvalidUserError(`User '${user.name}' (${userId}) is not connected.`);
|
throw new errors.SocketlibInvalidUserError(`User '${user.name}' (${userId}) is not connected.`);
|
||||||
return this._sendRequest(name, args, [userId]);
|
return this._sendRequest(name, args, [userId]);
|
||||||
}
|
}
|
||||||
|
|
||||||
async executeForAllGMs(handler, ...args) {
|
async executeForAllGMs(handler, ...args) {
|
||||||
const [name, func] = this._resolveFunction(handler);
|
const [name, func] = this._resolveFunction(handler);
|
||||||
this._sendCommand(name, args, RECIPIENT_TYPES.ALL_GMS);
|
this._sendCommand(name, args, RECIPIENT_TYPES.ALL_GMS);
|
||||||
if (game.user.isGM)
|
if (game.user.isGM) {
|
||||||
// TODO Make this function call run async, even if the function isn't delcared as async to prevent exceptions to propagate through executeForUsers
|
try {
|
||||||
func(...args);
|
this._executeLocal(func, ...args);
|
||||||
|
}
|
||||||
|
catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async executeForOtherGMs(handler, ...args) {
|
async executeForOtherGMs(handler, ...args) {
|
||||||
@@ -122,8 +130,11 @@ class SocketlibSocket {
|
|||||||
async executeForEveryone(handler, ...args) {
|
async executeForEveryone(handler, ...args) {
|
||||||
const [name, func] = this._resolveFunction(handler);
|
const [name, func] = this._resolveFunction(handler);
|
||||||
this._sendCommand(name, args, RECIPIENT_TYPES.EVERYONE);
|
this._sendCommand(name, args, RECIPIENT_TYPES.EVERYONE);
|
||||||
// TODO Make this function call run async, even if the function isn't delcared as async to prevent exceptions to propagate through executeForUsers
|
try {
|
||||||
func(...args);
|
this._executeLocal(func, ...args);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async executeForOthers(handler, ...args) {
|
async executeForOthers(handler, ...args) {
|
||||||
@@ -139,23 +150,27 @@ class SocketlibSocket {
|
|||||||
if (currentUserIndex >= 0)
|
if (currentUserIndex >= 0)
|
||||||
recipients.splice(currentUserIndex, 1);
|
recipients.splice(currentUserIndex, 1);
|
||||||
this._sendCommand(name, args, recipients);
|
this._sendCommand(name, args, recipients);
|
||||||
if (currentUserIndex >= 0)
|
if (currentUserIndex >= 0) {
|
||||||
// TODO Make this function call run async, even if the function isn't delcared as async to prevent exceptions to propagate through executeForUsers
|
try {
|
||||||
func(...args);
|
this._executeLocal(func, ...args);
|
||||||
|
}
|
||||||
|
catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
_sendRequest(handlerName, args, recipient) {
|
_sendRequest(handlerName, args, recipient) {
|
||||||
const message = {handlerName, args, recipient};
|
const message = {handlerName, args, recipient};
|
||||||
message.id = randomID();
|
message.id = randomID();
|
||||||
message.type = MESSAGE_TYPES.REQUEST;
|
message.type = MESSAGE_TYPES.REQUEST;
|
||||||
const promise = new Promise((resolve, reject) => this.pendingRequests.set(message.id, {handlerName, resolve, reject}));
|
const promise = new Promise((resolve, reject) => this.pendingRequests.set(message.id, {handlerName, resolve, reject, recipient}));
|
||||||
game.socket.emit(this.socketName, message);
|
game.socket.emit(this.socketName, message);
|
||||||
return promise;
|
return promise;
|
||||||
}
|
}
|
||||||
|
|
||||||
_sendCommand(handlerName, args, recipient) {
|
_sendCommand(handlerName, args, recipient) {
|
||||||
const message = {handlerName, args, recipient};
|
const message = {handlerName, args, recipient};
|
||||||
message.id = randomID();
|
|
||||||
message.type = MESSAGE_TYPES.COMMAND;
|
message.type = MESSAGE_TYPES.COMMAND;
|
||||||
game.socket.emit(this.socketName, message);
|
game.socket.emit(this.socketName, message);
|
||||||
}
|
}
|
||||||
@@ -172,6 +187,11 @@ class SocketlibSocket {
|
|||||||
game.socket.emit(this.socketName, message);
|
game.socket.emit(this.socketName, message);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_executeLocal(func, ...args) {
|
||||||
|
const socketdata = {userId: game.userId};
|
||||||
|
return func.call({socketdata}, ...args);
|
||||||
|
}
|
||||||
|
|
||||||
_resolveFunction(func) {
|
_resolveFunction(func) {
|
||||||
if (func instanceof Function) {
|
if (func instanceof Function) {
|
||||||
const entry = Array.from(this.functions.entries()).find(([key, val]) => val === func);
|
const entry = Array.from(this.functions.entries()).find(([key, val]) => val === func);
|
||||||
@@ -187,14 +207,14 @@ class SocketlibSocket {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
_onSocketReceived(message) {
|
_onSocketReceived(message, senderId) {
|
||||||
if (message.type === MESSAGE_TYPES.COMMAND || message.type === MESSAGE_TYPES.REQUEST)
|
if (message.type === MESSAGE_TYPES.COMMAND || message.type === MESSAGE_TYPES.REQUEST)
|
||||||
this._handleRequest(message);
|
this._handleRequest(message, senderId);
|
||||||
else
|
else
|
||||||
this._handleResponse(message);
|
this._handleResponse(message, senderId);
|
||||||
}
|
}
|
||||||
|
|
||||||
async _handleRequest(message) {
|
async _handleRequest(message, senderId) {
|
||||||
const {handlerName, args, recipient, id, type} = message;
|
const {handlerName, args, recipient, id, type} = message;
|
||||||
// Check if we're the recipient of the received message. If not, return early.
|
// Check if we're the recipient of the received message. If not, return early.
|
||||||
if (recipient instanceof Array) {
|
if (recipient instanceof Array) {
|
||||||
@@ -223,18 +243,20 @@ class SocketlibSocket {
|
|||||||
[name, func] = this._resolveFunction(handlerName);
|
[name, func] = this._resolveFunction(handlerName);
|
||||||
}
|
}
|
||||||
catch (e) {
|
catch (e) {
|
||||||
if (e instanceof errors.SocketlibUnregisteredHandlerError) {
|
if (e instanceof errors.SocketlibUnregisteredHandlerError && type === MESSAGE_TYPES.REQUEST) {
|
||||||
this._sendError(id, MESSAGE_TYPES.UNREGISTERED);
|
this._sendError(id, MESSAGE_TYPES.UNREGISTERED);
|
||||||
}
|
}
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
|
const socketdata = {userId: senderId};
|
||||||
|
const _this = {socketdata};
|
||||||
if (type === MESSAGE_TYPES.COMMAND) {
|
if (type === MESSAGE_TYPES.COMMAND) {
|
||||||
func(...args);
|
func.call(_this, ...args);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
let result;
|
let result;
|
||||||
try {
|
try {
|
||||||
result = await func(...args);
|
result = await func.call(_this, ...args);
|
||||||
}
|
}
|
||||||
catch (e) {
|
catch (e) {
|
||||||
console.error(`An exception occured while executing handler '${name}'.`);
|
console.error(`An exception occured while executing handler '${name}'.`);
|
||||||
@@ -245,11 +267,16 @@ class SocketlibSocket {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
_handleResponse(message) {
|
_handleResponse(message, senderId) {
|
||||||
const {id, result, type} = message;
|
const {id, result, type} = message;
|
||||||
const request = this.pendingRequests.get(id);
|
const request = this.pendingRequests.get(id);
|
||||||
if (!request)
|
if (!request)
|
||||||
return;
|
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) {
|
switch (type) {
|
||||||
case MESSAGE_TYPES.RESULT:
|
case MESSAGE_TYPES.RESULT:
|
||||||
request.resolve(result);
|
request.resolve(result);
|
||||||
@@ -266,11 +293,61 @@ class SocketlibSocket {
|
|||||||
}
|
}
|
||||||
this.pendingRequests.delete(id);
|
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 isResponsibleGM() {
|
function isResponsibleGM() {
|
||||||
const connectedGMs = game.users.filter(user => user.isGM && user.active);
|
|
||||||
if (!game.user.isGM)
|
if (!game.user.isGM)
|
||||||
return false;
|
return false;
|
||||||
|
const connectedGMs = game.users.filter(isActiveGM);
|
||||||
return !connectedGMs.some(other => other.data._id < game.user.data._id);
|
return !connectedGMs.some(other => other.data._id < game.user.data._id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isActiveGM(user) {
|
||||||
|
return user.active && user.isGM;
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleUserActivity(wrapper, userId, activityData={}) {
|
||||||
|
const user = game.users.get(userId);
|
||||||
|
const wasActive = user.active;
|
||||||
|
const result = wrapper(userId, activityData);
|
||||||
|
|
||||||
|
// If user disconnected
|
||||||
|
if (!user.active && wasActive) {
|
||||||
|
const modules = Array.from(socketlib.modules.values());
|
||||||
|
if (socketlib.system)
|
||||||
|
modules.concat(socketlib.system);
|
||||||
|
const GMConnected = Boolean(game.users.find(isActiveGM));
|
||||||
|
// 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 (!GMConnected) {
|
||||||
|
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(userId)) {
|
||||||
|
request.reject(new errors.SocketlibInvalidUserError(`User '${game.users.get(userId).name}' (${userId}) disconnected while handler '${handlerName}' was being dispatched.`));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
for (const [id, request] of failedRequests) {
|
||||||
|
socket.pendingRequests.delete(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user