Compare commits
52 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 212297bcc9 | |||
| 46f9703989 | |||
| 1b657b463d | |||
| c17402a551 | |||
| 970e99ff92 | |||
| ce19c69086 | |||
| d2f5edf38e | |||
| 559a45cdef | |||
| 2fd1060ea8 | |||
| ecbd26a89d | |||
| 238f7f057a | |||
| fe527cd944 | |||
| 0fa4b52704 | |||
| 6b2deb0392 | |||
| a28ca6cc6d | |||
| 5c995983f0 | |||
| 800e7de263 | |||
| 93d1587f61 | |||
| c80346917e | |||
| c65506ba0c | |||
| bf59633a16 | |||
| c75eef77b8 | |||
| 2a7f9cc52e | |||
| bfc7fb4955 | |||
| 3bdb4d8d6c | |||
| 97c143926a | |||
| 4afb56f9be | |||
| 7315c0fa4c | |||
| d8125e7592 | |||
| 48121fe6c6 | |||
| 51c02f81ea | |||
| a1179579f9 | |||
| 71c149a954 | |||
| 2e03f5a5c3 | |||
| 39c30c357a | |||
| b3b8b138bf | |||
| fb3aeaf813 | |||
| 5d9dd82a7d | |||
| 6a70df04e7 | |||
| 1fa8e03406 | |||
| 1646bbbe3b | |||
| 971c92b21a | |||
| 6a5190b0a8 | |||
| 86b0162c9c | |||
| 2909bc16f5 | |||
| 4852da9bd5 | |||
| 5fa28a9364 | |||
| 148f442857 | |||
| 326bc0e017 | |||
| be642cfb88 | |||
| 8d165c2984 | |||
| de4a289395 |
@@ -0,0 +1,121 @@
|
||||
# GitHub Actions workflow for creating a new FoundryVTT module release.
|
||||
#
|
||||
# Useful References:
|
||||
# - https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions
|
||||
# - https://docs.github.com/en/actions/learn-github-actions/contexts
|
||||
# - https://docs.github.com/en/actions/learn-github-actions/environment-variables
|
||||
#
|
||||
# Troubleshooting Checklist:
|
||||
# - Is the module's manifest file valid JSON?
|
||||
# You can test your manifest file using https://jsonlint.com/.
|
||||
#
|
||||
# - Does the module's manifest have all the required keys?
|
||||
# See https://foundryvtt.com/article/module-development/#manifest for more
|
||||
# information.
|
||||
#
|
||||
# - Are all the proper files and directories being included in the release's
|
||||
# module archive ("module.zip")?
|
||||
# Check that the correct files are being passed to the `zip` command run
|
||||
# in the "Create Module Archive" step below.
|
||||
#
|
||||
# - Is the release tag the proper format?
|
||||
# See the comments for the "Extract Version From Tag" step below.
|
||||
#
|
||||
# - Is a GitHub release being published?
|
||||
# This workflow will only run when a release is published, not when a
|
||||
# release is updated. Furthermore, note that while a GitHub release will
|
||||
# (by default) create a repository tag, a repository tag will not create
|
||||
# or publish a GitHub release.
|
||||
#
|
||||
# - Has the module's entry on FoundryVTT's module administration site
|
||||
# (https://foundryvtt.com/admin) been updated?
|
||||
#
|
||||
name: Create Module Files For GitHub Release
|
||||
|
||||
|
||||
env:
|
||||
# The URL used for the module's "Project URL" link on FoundryVTT's website.
|
||||
project_url: "https://github.com/${{github.repository}}"
|
||||
|
||||
# A URL that will always point to the latest manifest.
|
||||
# FoundryVTT uses this URL to check whether the current module version that
|
||||
# is installed is the latest version. This URL should NOT change,
|
||||
# otherwise FoundryVTT won't be able to perform this check.
|
||||
latest_manifest_url: "https://github.com/${{github.repository}}/releases/latest/download/module.json"
|
||||
|
||||
# The URL to the module archive associated with the module release being
|
||||
# processed by this workflow.
|
||||
release_module_url: "https://github.com/${{github.repository}}/releases/download/${{github.event.release.tag_name}}/module.zip"
|
||||
|
||||
|
||||
on:
|
||||
# Only run this workflow when a release is published.
|
||||
# To modify this workflow when other events occur, see:
|
||||
# - https://docs.github.com/en/actions/using-workflows/triggering-a-workflow
|
||||
# - https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows
|
||||
# - https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#on
|
||||
#
|
||||
# Note that some steps may depend on context variables that are only
|
||||
# available for release events, so if you add other events, you may need to
|
||||
# alter other parts of this workflow.
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# Substitute the Manifest and Download URLs in the module.json
|
||||
- name: Substitute Manifest and Download Links For Versioned Ones
|
||||
id: sub_manifest_link_version
|
||||
uses: microsoft/variable-substitution@v1
|
||||
with:
|
||||
files: 'module.json'
|
||||
env:
|
||||
version: ${{github.event.release.tag_name}}
|
||||
url: https://github.com/${{github.repository}}
|
||||
manifest: https://github.com/${{github.repository}}/releases/latest/download/module.json
|
||||
download: https://github.com/${{github.repository}}/releases/download/${{github.event.release.tag_name}}/module.zip
|
||||
|
||||
# Create a "module.zip" archive containing all the module's required files.
|
||||
# If you have other directories or files that will need to be added to
|
||||
# your packaged module, add them here.
|
||||
- name: Create Module Archive
|
||||
run: |
|
||||
# Note that `zip` will only emit warnings when a file or directory
|
||||
# doesn't exist, it will not fail.
|
||||
zip \
|
||||
`# Options` \
|
||||
--recurse-paths \
|
||||
`# The name of the output file` \
|
||||
./module.zip \
|
||||
`# The files that will be included.` \
|
||||
module.json \
|
||||
LICENSE \
|
||||
CHANGELOG.md \
|
||||
README.md \
|
||||
src/
|
||||
# Don't forget to add a backslash at the end of the line for any
|
||||
# additional files or directories!
|
||||
|
||||
|
||||
# Update the GitHub release with the manifest and module archive files.
|
||||
- name: Update Release With Files
|
||||
id: create_version_release
|
||||
uses: ncipollo/release-action@v1
|
||||
with:
|
||||
allowUpdates: true
|
||||
name: ${{ github.event.release.name }}
|
||||
draft: ${{ github.event.release.unpublished }}
|
||||
prerelease: ${{ github.event.release.prerelease }}
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
artifacts: './module.json, ./module.zip'
|
||||
tag: ${{ github.event.release.tag_name }}
|
||||
body: ${{ github.event.release.body }}
|
||||
@@ -0,0 +1 @@
|
||||
socketlib.lock
|
||||
@@ -1,2 +1,89 @@
|
||||
## 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
|
||||
|
||||
@@ -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.
|
||||
@@ -1,4 +1,8 @@
|
||||
[](https://ko-fi.com/staebchenfisch)
|
||||
[](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.
|
||||
@@ -64,6 +68,17 @@ Call `registerModule` to make socketlib listen for sockets that come in for your
|
||||
|
||||
**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);
|
||||
@@ -81,7 +96,7 @@ Registers a function that can subsequently be called using socketlib. It's impor
|
||||
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.
|
||||
- **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.
|
||||
@@ -93,7 +108,7 @@ Executes a function on the client of exactly one GM. If multiple GMs are connect
|
||||
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.
|
||||
- **userId** the id of the user that should execute this function.
|
||||
@@ -106,7 +121,19 @@ Executes a function on the client of the specified user. This function will fail
|
||||
async socket.executeForAllGMs(handler, parameters...);
|
||||
```
|
||||
|
||||
Executes a function on the clients of all connected GMs.
|
||||
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.
|
||||
@@ -118,7 +145,19 @@ Executes a function on the clients of all connected GMs.
|
||||
async socket.executeForEveryone(handler, ...args);
|
||||
```
|
||||
|
||||
Executes a function on all connected clients.
|
||||
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.
|
||||
@@ -130,7 +169,7 @@ Executes a function on all connected clients.
|
||||
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.
|
||||
- **recipients** an array of user ids that should execute the function.
|
||||
|
||||
+23
-13
@@ -1,26 +1,36 @@
|
||||
{
|
||||
"name": "socketlib",
|
||||
"id": "socketlib",
|
||||
"title": "socketlib",
|
||||
"description": "A library for easier handling of foundry sockets",
|
||||
"version": "1.0.0",
|
||||
"minimumCoreVersion" : "0.7.9",
|
||||
"compatibleCoreVersion" : "0.7.9",
|
||||
"version": "1.1.1",
|
||||
"compatibility": {
|
||||
"minimum": "11",
|
||||
"verified": "13.338"
|
||||
},
|
||||
"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"
|
||||
"discord": "Stäbchenfisch#5107",
|
||||
"flags": {}
|
||||
}
|
||||
],
|
||||
"esmodules": [
|
||||
"src/socketlib.js"
|
||||
],
|
||||
"url": "https://github.com/manuelVo/foundryvtt-socketlib",
|
||||
"download": "https://github.com/manuelVo/foundryvtt-socketlib/archive/v1.0.0.zip",
|
||||
"manifest": "https://raw.githubusercontent.com/manuelVo/foundryvtt-socketlib/master/module.json",
|
||||
"readme": "https://github.com/manuelVo/foundryvtt-socketlib/blob/master/README.md",
|
||||
"changelog": "https://github.com/manuelVo/foundryvtt-socketlib/blob/master/CHANGELOG.md",
|
||||
"bugs": "https://github.com/manuelVo/foundryvtt-socketlib/issues",
|
||||
"allowBugReporter": false
|
||||
"url": "https://github.com/farling42/foundryvtt-socketlib",
|
||||
"download": "https://github.com/farling42/foundryvtt-socketlib/releases/download/v1.1.1/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"
|
||||
}
|
||||
|
||||
+123
-26
@@ -20,9 +20,12 @@ Hooks.once("init", () => {
|
||||
Hooks.callAll("socketlib.ready");
|
||||
});
|
||||
|
||||
Hooks.on("userConnected", handleUserActivity);
|
||||
|
||||
class Socketlib {
|
||||
constructor() {
|
||||
this.modules = new Map();
|
||||
this.system = undefined;
|
||||
this.errors = errors;
|
||||
}
|
||||
|
||||
@@ -35,21 +38,36 @@ class Socketlib {
|
||||
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.data.socket) {
|
||||
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);
|
||||
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) {
|
||||
this.moduleName = moduleName;
|
||||
constructor(moduleName, moduleType) {
|
||||
this.functions = new Map();
|
||||
this.socketName = `module.${moduleName}`;
|
||||
this.socketName = `${moduleType}.${moduleName}`;
|
||||
this.pendingRequests = new Map();
|
||||
game.socket.on(this.socketName, this._onSocketReceived.bind(this));
|
||||
}
|
||||
@@ -69,10 +87,10 @@ class SocketlibSocket {
|
||||
async executeAsGM(handler, ...args) {
|
||||
const [name, func] = this._resolveFunction(handler);
|
||||
if (game.user.isGM) {
|
||||
return func(...args);
|
||||
return this._executeLocal(func, ...args);
|
||||
}
|
||||
else {
|
||||
if (!game.users.find(user => user.isGM && user.active)) {
|
||||
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);
|
||||
@@ -81,43 +99,78 @@ class SocketlibSocket {
|
||||
|
||||
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 SocketlibInvalidUserError(`No user with id '${userId}' exists.`);
|
||||
throw new errors.SocketlibInvalidUserError(`No user with id '${userId}' exists.`);
|
||||
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]);
|
||||
}
|
||||
|
||||
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 = randomID();
|
||||
message.id = foundry.utils.randomID();
|
||||
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);
|
||||
return promise;
|
||||
}
|
||||
|
||||
_sendCommand(handlerName, args, recipient) {
|
||||
const message = {handlerName, args, recipient};
|
||||
message.id = randomID();
|
||||
message.type = MESSAGE_TYPES.COMMAND;
|
||||
game.socket.emit(this.socketName, message);
|
||||
}
|
||||
@@ -134,6 +187,11 @@ class SocketlibSocket {
|
||||
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);
|
||||
@@ -149,14 +207,14 @@ class SocketlibSocket {
|
||||
}
|
||||
}
|
||||
|
||||
_onSocketReceived(message) {
|
||||
_onSocketReceived(message, senderId) {
|
||||
if (message.type === MESSAGE_TYPES.COMMAND || message.type === MESSAGE_TYPES.REQUEST)
|
||||
this._handleRequest(message);
|
||||
this._handleRequest(message, senderId);
|
||||
else
|
||||
this._handleResponse(message);
|
||||
this._handleResponse(message, senderId);
|
||||
}
|
||||
|
||||
async _handleRequest(message) {
|
||||
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) {
|
||||
@@ -166,7 +224,7 @@ class SocketlibSocket {
|
||||
else {
|
||||
switch (recipient) {
|
||||
case RECIPIENT_TYPES.ONE_GM:
|
||||
if (!isResponsibleGM())
|
||||
if (!game.users.activeGM?.isSelf)
|
||||
return;
|
||||
break;
|
||||
case RECIPIENT_TYPES.ALL_GMS:
|
||||
@@ -185,18 +243,20 @@ class SocketlibSocket {
|
||||
[name, func] = this._resolveFunction(handlerName);
|
||||
}
|
||||
catch (e) {
|
||||
if (e instanceof errors.SocketlibUnregisteredHandlerError) {
|
||||
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(...args);
|
||||
func.call(_this, ...args);
|
||||
}
|
||||
else {
|
||||
let result;
|
||||
try {
|
||||
result = await func(...args);
|
||||
result = await func.call(_this, ...args);
|
||||
}
|
||||
catch (e) {
|
||||
console.error(`An exception occured while executing handler '${name}'.`);
|
||||
@@ -207,11 +267,16 @@ class SocketlibSocket {
|
||||
}
|
||||
}
|
||||
|
||||
_handleResponse(message) {
|
||||
_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);
|
||||
@@ -228,11 +293,43 @@ class SocketlibSocket {
|
||||
}
|
||||
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() {
|
||||
const connectedGMs = game.users.filter(user => user.isGM && user.active);
|
||||
if (!game.user.isGM)
|
||||
return false;
|
||||
return !connectedGMs.some(other => other.data._id < game.user.data._id);
|
||||
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