- - new ChatBridgeChannel() - - - - -
- - - --
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/.gitignore b/.gitignore index dca5fb89b..6434aeaeb 100644 --- a/.gitignore +++ b/.gitignore @@ -153,3 +153,4 @@ config/datastores.js test/output/* .env .nyc_output/* +coverage/* \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index 323d78ffc..00f3ee851 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,4 +8,7 @@ before_install: install: - npm install script: - - npm test \ No newline at end of file + - npm test + - npm run coverage + +after_script: "cat coverage/lcov.info | node_modules/coveralls/bin/coveralls.js" \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..627034ee0 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,2 @@ +{ + } \ No newline at end of file diff --git a/README.md b/README.md index 0111e28fb..f54a5e5dc 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,6 @@ +[![Coverage Status](https://coveralls.io/repos/github/CatalysmsServerManager/7-days-to-die-server-manager/badge.svg?branch=master)](https://coveralls.io/github/CatalysmsServerManager/7-days-to-die-server-manager?branch=master) +[![Build Status](https://travis-ci.org/CatalysmsServerManager/7-Days-to-Die-API-wrapper.svg?branch=master)](https://travis-ci.org/CatalysmsServerManager/7-Days-to-Die-API-wrapper) + # 7DTD Server manager ## [Public instance of CSMM](https://csmm.catalysm.net/) diff --git a/api/controllers/role/check-permission.js b/api/controllers/role/check-permission.js index 2a8952686..18e8e1940 100644 --- a/api/controllers/role/check-permission.js +++ b/api/controllers/role/check-permission.js @@ -12,6 +12,7 @@ module.exports = { permissionField: { type: 'string', required: true, + isIn: ["manageServer", "manageEconomy", "managePlayers", "manageTickets", "viewAnalytics", "viewDashboard", "useTracking", "useChat", "useCommands", "manageGbl", "discordExec", "discordLookup"] }, serverId: { @@ -59,7 +60,7 @@ module.exports = { let permCheck = await sails.helpers.roles.checkPermission.with(options); - return exits.success(permCheck.hasPermission) + return exits.success(permCheck.hasPermission); } diff --git a/api/controllers/role/update-role.js b/api/controllers/role/update-role.js index 1da143c82..f04c991d8 100644 --- a/api/controllers/role/update-role.js +++ b/api/controllers/role/update-role.js @@ -14,7 +14,7 @@ module.exports = { type: 'number', custom: async (valueToCheck) => { let foundRole = await Role.findOne(valueToCheck); - return foundRole + return foundRole; }, }, @@ -27,6 +27,10 @@ module.exports = { min: 0 }, + isDefault: { + type: 'boolean', + }, + discordRole: { type: 'string' }, @@ -104,6 +108,20 @@ module.exports = { fn: async function (inputs, exits) { + const role = await Role.findOne(inputs.roleId).populate('server'); + const server = role.server; + + // If another role is currently set as default, we must set that one to false. + // There can only be one default role per server. + if (inputs.isDefault) { + await Role.update({ + server: server.id, + isDefault: true + }, { + isDefault: false, + }); + } + let updateObj = { name: inputs.name, level: inputs.level, @@ -122,7 +140,8 @@ module.exports = { manageTickets: inputs.manageTickets, manageGbl: inputs.manageGbl, discordExec: inputs.discordExec, - discordLookup: inputs.discordLookup + discordLookup: inputs.discordLookup, + isDefault: inputs.isDefault, }; let updatedRole = await Role.update({ @@ -131,7 +150,7 @@ module.exports = { sails.log.info(`Updated a role for server ${updatedRole[0].server}`, updatedRole[0]) - return exits.success(updatedRole); + return exits.success(updatedRole[0]); } diff --git a/api/helpers/discord/set-role-from-discord.js b/api/helpers/discord/set-role-from-discord.js index c9f75d7fe..19b80b932 100644 --- a/api/helpers/discord/set-role-from-discord.js +++ b/api/helpers/discord/set-role-from-discord.js @@ -8,20 +8,14 @@ module.exports = { }, }, - exits: { - error: { - friendlyName: 'error' - }, - }, + exits: {}, fn: async function (inputs, exits) { - let player = await Player.findOne(inputs.playerId); if (_.isUndefined(player)) { return exits.error(new Error("Unknown player ID")); } - let user = await User.findOne({ steamId: player.steamId }); @@ -29,10 +23,12 @@ module.exports = { let serverConfig = await SdtdConfig.findOne({ server: player.server }).populate('server'); - let discordClient = sails.hooks.discordbot.getClient(); - let discordGuild = await discordClient.guilds.get(serverConfig.discordGuildId); + if (!discordClient) { + return exits.success(player, undefined); + } + let discordGuild = await discordClient.guilds.get(serverConfig.discordGuildId); if (_.isUndefined(discordGuild) || !discordGuild) { return exits.success(player, undefined); } @@ -40,7 +36,6 @@ module.exports = { if (!user.discordId) { return exits.success(player, undefined); } - let member = await discordGuild.members.get(user.discordId); if (_.isUndefined(member)) { @@ -48,7 +43,6 @@ module.exports = { } let memberRoles = member.roles.array(); - let currentPlayerRole = player.role; let highestRole = await Role.find({ @@ -60,7 +54,6 @@ module.exports = { limit: 1 }); - if (!_.isUndefined(highestRole[0])) { if ((!_.isNull(currentPlayerRole) ? currentPlayerRole.level : 9999999) > highestRole[0].level) { await Player.update({ @@ -70,8 +63,10 @@ module.exports = { }) } sails.log.debug(`Modified a players role - player ${player.id}. ${player.name} to role ${highestRole[0] ? highestRole[0].name : null}`); + return exits.success(player, highestRole[0]); } - return exits.success(player, highestRole[0]); + return exits.error(new Error(`Unexpected to return here, should have returned earlier.`)); + }, }; diff --git a/api/helpers/roles/check-permission.js b/api/helpers/roles/check-permission.js index 1d4d97c78..9bf0a4cc4 100644 --- a/api/helpers/roles/check-permission.js +++ b/api/helpers/roles/check-permission.js @@ -44,13 +44,11 @@ module.exports = { fn: async function (inputs, exits) { - if ((_.isUndefined(inputs.userId) || _.isUndefined(inputs.serverId)) && (_.isUndefined(inputs.discordId) || _.isUndefined(inputs.serverId)) && _.isUndefined(inputs.playerId)) { - return exits.invalidInput('You must provide either userId AND serverID, discordId AND serverId or just a playerId' + JSON.stringify(inputs)); + return exits.invalidInput('You must provide either userId AND serverId, discordId AND serverId or just a playerId' + JSON.stringify(inputs)); } let role; - if (inputs.discordId) { let foundUser = await User.find({ discordId: inputs.discordId @@ -61,6 +59,14 @@ module.exports = { } + if (inputs.playerId) { + try { + await sails.helpers.discord.setRoleFromDiscord(inputs.playerId); + } catch (error) { + sails.log.debug(`Couldn't update players roles via discord - ${error}`) + } + } + if (inputs.userId && inputs.serverId) { role = await sails.helpers.roles.getUserRole(inputs.userId, inputs.serverId); } @@ -69,22 +75,16 @@ module.exports = { role = await sails.helpers.sdtd.getPlayerRole(inputs.playerId); } - // If we find no role for a player, we default to highest level role. if (_.isUndefined(role)) { - let foundRole = await Role.find({ - where: { - server: inputs.serverId - }, - sort: 'level DESC', - limit: 1 - }); - role = foundRole[0] + role = await getDefaultRole(inputs.serverId); } let hasPermission = false; if (!_.isUndefined(inputs.userId)) { let foundUser = await User.findOne(inputs.userId); + + // Override permission check when user is a system admin if (foundUser.steamId === sails.config.custom.adminSteamId) { foundRole = await Role.find({ where: { @@ -92,7 +92,7 @@ module.exports = { }, sort: 'level ASC', limit: 1 - }) + }); if (foundRole[0]) { role = foundRole[0]; } @@ -108,6 +108,7 @@ module.exports = { hasPermission = true } + // Check if the user owns the server on CSMM, in that case we will always return true. if (!_.isUndefined(inputs.userId) && !hasPermission) { let server = await SdtdServer.findOne(inputs.serverId); @@ -116,9 +117,7 @@ module.exports = { } } - - - //sails.log.debug(`Checked if ${inputs.playerId ? `player ${inputs.playerId}` : `user ${inputs.userId}`} has permission ${inputs.permission} - ${hasPermission}`) + sails.log.debug(`Checked if ${inputs.playerId ? `player ${inputs.playerId}` : `user ${inputs.userId}`} has permission ${inputs.permission} - ${hasPermission}`) // All done. return exits.success({ @@ -130,3 +129,46 @@ module.exports = { }; + +async function getDefaultRole(serverId) { + + if (_.isUndefined(serverId)) { + throw new Error(`parameter serverId is required.`); + } + + let roles = await Role.find({ + server: serverId + }); + // Check if server has a role set as default + let defaultRole = roles.filter(role => role.isDefault)[0]; + if (defaultRole) { + return defaultRole; + } + + // If we find no default role for a server, we default to highest level role. + let foundRole = await Role.find({ + where: { + server: serverId + }, + sort: 'level DESC', + limit: 1 + }); + + // If we still can't find a role, it's likely because the server has none configured. In this case we will create a default role. + if (!foundRole[0]) { + let amountOfRoles = await Role.count({server: serverId}); + + sails.log.warn(`Detected ${amountOfRoles} roles for server ${serverId}. Creating a default one`); + if (amountOfRoles === 0) { + let createdRole = await Role.create({ + server: serverId, + name: "Player", + level: "2000", + }).fetch(); + return createdRole; + } + } + + return foundRole[0]; + +} diff --git a/api/helpers/roles/get-user-role.js b/api/helpers/roles/get-user-role.js index ee5164da2..07ba3a1c8 100644 --- a/api/helpers/roles/get-user-role.js +++ b/api/helpers/roles/get-user-role.js @@ -12,18 +12,18 @@ module.exports = { userId: { required: true, type: 'number', - custom: async (valueToCheck) => { + custom: async function (valueToCheck) { let foundUser = await User.findOne(valueToCheck); - return foundUser + return foundUser; }, }, serverId: { required: true, type: 'number', - custom: async (valueToCheck) => { + custom: async function (valueToCheck) { let foundServer = await SdtdServer.findOne(valueToCheck); - return foundServer + return foundServer; }, }, @@ -41,57 +41,19 @@ module.exports = { fn: async function (inputs, exits) { let foundUser = await User.findOne(inputs.userId); - let foundServer = await SdtdServer.findOne(inputs.serverId); - let foundPlayer = await Player.findOne({ where: { steamId: foundUser.steamId, server: inputs.serverId } }); - - try { - if (!_.isUndefined(foundPlayer)) { - await sails.helpers.discord.setRoleFromDiscord(foundPlayer.id); - } - } catch (error) { - sails.log.debug(`Couldn't update players roles via discord - ${error}`) - } - let foundRole; - - let amountOfRoles = await Role.count({ - server: inputs.serverId - }); - - if (amountOfRoles === 0) { - await Role.create({ - name: "Default role", - level: 9999, - server: inputs.serverId, - amountOfteleports: 5 - }); - } - if (!_.isUndefined(foundPlayer)) { if (foundPlayer.role) { foundRole = await Role.findOne(foundPlayer.role); } } - - if (_.isUndefined(foundRole)) { - foundRole = await Role.find({ - where: { - server: inputs.serverId - }, - sort: 'level DESC', - limit: 1 - }); - foundRole = foundRole[0] - } - - //sails.log.verbose(`Found role ${foundRole.name} for user ${foundUser.username}`) return exits.success(foundRole); } diff --git a/api/helpers/sdtd/get-player-role.js b/api/helpers/sdtd/get-player-role.js index 046d6996d..6d4c4626a 100644 --- a/api/helpers/sdtd/get-player-role.js +++ b/api/helpers/sdtd/get-player-role.js @@ -1,74 +1,50 @@ module.exports = { - friendlyName: 'Get player role', + friendlyName: 'Get player role', - description: '', + description: '', - inputs: { - - playerId: { - required: true, - type: 'number', - custom: async (valueToCheck) => { - let foundPlayer = await Player.findOne(valueToCheck); - return foundPlayer - }, - }, + inputs: { + playerId: { + required: true, + type: 'number', + custom: async (valueToCheck) => { + let foundPlayer = await Player.findOne(valueToCheck); + return foundPlayer + }, }, + }, - exits: { - success: { - outputFriendlyName: 'Success', - outputType: 'json' - }, + exits: { + success: { + outputFriendlyName: 'Success', + outputType: 'json' }, - fn: async function (inputs, exits) { - - let player = await Player.findOne(inputs.playerId); - - try { - await sails.helpers.discord.setRoleFromDiscord(inputs.playerId); - } catch (error) { - sails.log.debug(`Couldn't update players roles via discord - ${error}`) - } - - let foundRole; - - let amountOfRoles = await Role.count({server: player.server}); - - if (amountOfRoles === 0) { - await Role.create({ - name: "Default role", - level: 9999, - server: player.server, - amountOfteleports: 5 - }); - } - - if (player.role) { - foundRole = await Role.findOne(player.role); - } else { - foundRole = await Role.find({ - where: { - server: player.server - }, - sort: 'level DESC', - limit: 1 - }); - foundRole = foundRole[0] - } - - //sails.log.verbose(`Found role ${foundRole.name} for player ${player.name}`) - return exits.success(foundRole); + }, + + fn: async function (inputs, exits) { + + let player = await Player.findOne(inputs.playerId); + let foundRole; + + if (player.role) { + foundRole = await Role.findOne(player.role); + } else { + foundRole = undefined; } + //sails.log.verbose(`Found role ${foundRole.name} for player ${player.name}`) + return exits.success(foundRole); + + } + }; diff --git a/api/models/Role.js b/api/models/Role.js index 13402b0ed..1f5059193 100644 --- a/api/models/Role.js +++ b/api/models/Role.js @@ -23,6 +23,12 @@ module.exports = { defaultsTo: 2000 }, + // if true, csmm will use this role for any permission check where role is not explicitly set. + isDefault: { + type: 'boolean', + defaultsTo: false + }, + amountOfTeleports: { type: 'number', defaultsTo: 5 diff --git a/docs/ChatBridgeChannel.html b/docs/ChatBridgeChannel.html deleted file mode 100644 index 09128182d..000000000 --- a/docs/ChatBridgeChannel.html +++ /dev/null @@ -1,199 +0,0 @@ - - -
- -Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -number - - - - | - - - - - -- |
config |
-
-
- - - -json - - - - | - - - - - -- |
Name | - - -Type | - - - - - -Description | -
---|---|---|
connectedMessage |
-
-
- - - -json - - - - | - - - - - -- |
Name | - - -Type | - - - - - -Description | -
---|---|---|
message |
-
-
- - - -string - - - - | - - - - - -- |
serverId |
-
-
- - - -number - - - - | - - - - - -- |
playerSteamId |
-
-
- - - -string - - - - | - - - - - -- |
models/Player.js
,
- line 1
- Name | - - -Type | - - - - - -Description | -
---|---|---|
steamId |
-
-
- - - -number - - - - | - - - - - -- |
entityId |
-
-
- - - -number - - - - | - - - - - -- |
models/Player.js
,
- line 42
- models/Player.js
,
- line 119
- models/Player.js
,
- line 23
- models/Player.js
,
- line 89
- models/Player.js
,
- line 32
- models/Player.js
,
- line 109
- models/Player.js
,
- line 52
- models/Player.js
,
- line 99
- models/Player.js
,
- line 62
- models/Player.js
,
- line 71
- models/Player.js
,
- line 80
- models/Player.js
,
- line 141
- models/Player.js
,
- line 150
- controllers/Player/ban.js
,
- line 37
- Name | - - -Type | - - - - - -Description | -
---|---|---|
steamId |
-
-
- - - -string - - - - | - - - - - -Steam ID of the player | -
serverId |
-
-
- - - -string - - - - | - - - - - -ID of the server | -
Name | - - -Type | - - - - - -Description | -
---|---|---|
steamId |
-
-
- - - -string - - - - | - - - - - -Steam ID of the player | -
serverId |
-
-
- - - -string - - - - | - - - - - -ID of the server | -
Name | - - -Type | - - - - - -Description | -
---|---|---|
steamId |
-
-
- - - -string - - - - | - - - - - -Steam ID of the player | -
serverId |
-
-
- - - -string - - - - | - - - - - -ID of the server | -
Name | - - -Type | - - - - - -Description | -
---|---|---|
steamId |
-
-
- - - -string - - - - | - - - - - -Steam ID of the player | -
serverId |
-
-
- - - -string - - - - | - - - - - -ID of the server | -
Name | - - -Type | - - - - - -Description | -
---|---|---|
playerId |
-
-
- - - -string - - - - | - - - - - -Id of the player | -
Name | - - -Type | - - - - - -Description | -
---|---|---|
steamId |
-
-
- - - -string - - - - | - - - - - -Steam ID of the player | -
serverId |
-
-
- - - -string - - - - | - - - - - -ID of the server | -
Name | - - -Type | - - - - - -Description | -
---|---|---|
playerId |
-
-
- - - -string - - - - | - - - - - -- |
coordX |
-
-
- - - -number - - - - | - - - - - -- |
coordY |
-
-
- - - -number - - - - | - - - - - -- |
coordZ |
-
-
- - - -number - - - - | - - - - - -- |
Name | - - -Type | - - - - - -Description | -
---|---|---|
steamId |
-
-
- - - -string - - - - | - - - - - -Steam ID of the player | -
serverId |
-
-
- - - -string - - - - | - - - - - -ID of the server | -
models/SdtdServer.js
,
- line 1
- models/SdtdServer.js
,
- line 111
- models/SdtdServer.js
,
- line 69
- models/SdtdServer.js
,
- line 79
- models/SdtdConfig.js
,
- line 76
- models/SdtdConfig.js
,
- line 86
- models/SdtdConfig.js
,
- line 66
- models/SdtdServer.js
,
- line 39
- models/SdtdServer.js
,
- line 29
- models/SdtdServer.js
,
- line 20
- models/SdtdConfig.js
,
- line 97
- models/SdtdServer.js
,
- line 100
- models/SdtdServer.js
,
- line 121
- models/SdtdServer.js
,
- line 49
- models/SdtdServer.js
,
- line 132
- models/SdtdServer.js
,
- line 59
- Name | - - -Type | - - - - - -Description | -
---|---|---|
serverip |
-
-
- - - -string - - - - | - - - - - -Ip of the server to add | -
telnetport |
-
-
- - - -number - - - - | - - - - - -Telnet port of the server | -
telnetpassword |
-
-
- - - -string - - - - | - - - - - -Telnet password of the server | -
webport |
-
-
- - - -number - - - - | - - - - - -Port for webserver added by Alloc's fixes | -
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -number - - - - | - - - - - -ID of the server | -
Name | - - -Type | - - - - - -Description | -
---|---|---|
guildId |
-
-
- - - -number - - - - | - - - - - -discord guild id | -
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -string - - - - | - - - - - -- |
newConfig |
-
-
- - - -json - - - - | - - - - - -- |
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -string - - - - | - - - - - -- |
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverID |
-
-
- - - -number - - - - | - - - - - -ID of the server | -
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -string - - - - | - - - - - -- |
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -string - - - - | - - - - - -- |
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverID |
-
-
- - - -number - - - - | - - - - - -ID of the server | -
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -number - - - - | - - - - - -ID of the server | -
command |
-
-
- - - -string - - - - | - - - - - -Command to be executed | -
Name | - - -Type | - - - - - -Description | -
---|---|---|
userId |
-
-
- - - -number - - - - | - - - - - -- |
Name | - - -Type | - - - - - -Description | -
---|---|---|
guildId |
-
-
- - - -string - - - - | - - - - - -- |
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -number - - - - | - - - - - -ID of the server | -
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -number - - - - | - - - - - -ID of the server | -
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -number - - - - | - - - - - -ID of the server | -
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -string - - - - | - - - - - -- |
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -string - - - - | - - - - - -- |
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -string - - - - | - - - - - -- |
message |
-
-
- - - -string - - - - | - - - - - -- |
interval |
-
-
- - - -number - - - - | - - - - - -- |
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverID |
-
-
- - - -number - - - - | - - - - - -ID of the server | -
message |
-
-
- - - -string - - - - | - - - - - -Message to be executed | -
destinationPlayer |
-
-
- - - -string - - - - | - - - - - -SteamID of the player to send a message to | -
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -number - - - - | - - - - - -ID of the server | -
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -number - - - - | - - - - - -ID of the server | -
Type | - - - - - -Description | -
---|---|
- - -serverId - - - - | - - - - - -- |
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -string - - - - | - - - - - -- |
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -string - - - - | - - - - - -- |
serverIp |
-
-
- - - -string - - - - | - - - - - -- |
webPort |
-
-
- - - -number - - - - | - - - - - -- |
authName |
-
-
- - - -string - - - - | - - - - - -- |
authToken |
-
-
- - - -string - - - - | - - - - - -- |
Name | - - -Type | - - - - - -Description | -
---|---|---|
userId |
-
-
- - - -string - - - - | - - - - - -- |
models/User.js
,
- line 1
- models/User.js
,
- line 53
- models/User.js
,
- line 65
- models/User.js
,
- line 85
- models/User.js
,
- line 96
- models/User.js
,
- line 22
- models/User.js
,
- line 42
- var passport = require('passport');
-var jwt = require('jsonwebtoken');
-
-/**
- * AuthController
- *
- * @description Server-side actions for handling incoming requests regarding authentication.
- * @module AuthController
- */
-
-
-module.exports = {
-
- /**
- * @description Authenticate a user via steam
- */
- steamLogin: function (req, res, next) {
- sails.log.debug(`Logging in a user via steam`);
- passport.authenticate('steam', {
- failureRedirect: `${process.env.CSMM_HOSTNAME}`
- })(req, res);
-
- },
-
- /**
- * @description Return link after steam login
- */
-
- steamReturn: function (req, res) {
- passport.authenticate('steam', {
- failureRedirect: '/login'
- },
- async function (err, user) {
- if (err) {
- sails.log.error(`Steam auth error - ${err}`);
- return res.serverError(err);
- };
- sails.log.debug(`User with id ${user.id} successfully logged in`);
- req.session.userId = user.id;
- try {
- let players = await Player.find({
- steamId: user.steamId
- });
- let playerIds = players.map((player) => {
- return player.id;
- });
- await User.addToCollection(user.id, 'players').members(playerIds);
- } catch (error) {
- sails.log.error(`AuthController - Error updating user profile ${error}`);
- }
-
- res.redirect(`/user/${user.id}/dashboard`);
- })(req, res);
- },
-
- discordReturn: function (req, res) {
- passport.authenticate('discord', {
- failureRedirect: '/'
- },
- async function (err, discordProfile) {
- if (err) {
- sails.log.error(`Discord auth error - ${err}`);
- return res.serverError(err);
- };
-
- try {
- await User.update({
- id: req.session.userId
- }, {
- discordId: discordProfile.id,
- });
- sails.log.debug(`User ${req.session.userId} updated discord info successfully`);
- res.redirect('/');
- } catch (error) {
- sails.log.error(`AuthController:discordReturn - Error updating user profile ${error}`);
- }
-
- })(req, res);
- },
-
-
- /**
- * @description login via discord
- */
-
- discordLogin: function (req, res, next) {
- sails.log.debug(`Logging in a user via discord`);
- passport.authenticate('discord', {
- failureRedirect: `${process.env.CSMM_HOSTNAME}`
- })(req, res);
-
- },
-
- /**
- * @description Log out a user, clears the encrypted cookie
- */
-
- logout: function (req, res) {
- delete req.session.userId;
- return res.redirect('/');
- },
-
-
-
-};
-
- var sevenDays = require('machinepack-7daystodiewebapi');
-
-/**
- * @memberof Player
- * @description Get the contents of a players inventory
- * @param {string} steamId Steam ID of the player
- * @param {string} serverId ID of the server
- */
-
-async function getInventory(req, res) {
- const steamId = req.query.steamId;
- const serverId = req.query.serverId;
-
- sails.log.debug(`Showing inventory for player ${steamId} on server ${serverId}`);
-
- if (_.isUndefined(steamId)) {
- return res.badRequest('No steam ID given');
- }
- if (_.isUndefined(serverId)) {
- return res.badRequest('No server ID given');
- }
- try {
- let playerInfo = await sails.helpers.loadPlayerData.with({
- serverId: serverId,
- steamId: steamId
- });
-
- let player = playerInfo.players[0];
- let toSend = new Object();
- toSend.id = player.id;
- toSend.steamId = player.steamId;
- toSend.serverId = player.server;
- toSend.inventory = player.inventory;
- return res.json(toSend);
- } catch (error) {
- sails.log.error(error);
- return res.badRequest();
- }
-}
-
-/**
- * @memberof Player
- * @description Get ban status of a player
- * @param {string} steamId Steam ID of the player
- * @param {string} serverId ID of the server
- */
-
-async function getBanStatus(req, res) {
- const steamId = req.query.steamId;
- const serverId = req.query.serverId;
-
- sails.log.debug(`Showing ban status for player ${steamId} on server ${serverId}`);
-
- if (_.isUndefined(steamId)) {
- return res.badRequest('No steam ID given');
- }
- if (_.isUndefined(serverId)) {
- return res.badRequest('No server ID given');
- }
-
- try {
- let playerInfo = await sails.helpers.loadPlayerData.with({
- serverId: serverId,
- steamId: steamId
- });
-
- let player = playerInfo.players[0];
- let toSend = new Object();
- toSend.id = player.id;
- toSend.steamId = player.steamId;
- toSend.serverId = player.server;
- toSend.banned = player.banned;
- return res.json(toSend);
- } catch (error) {
- sails.log.error(error);
- return res.badRequest();
- }
-}
-
-/**
- * @memberof Player
- * @description Get location of a player
- * @param {string} steamId Steam ID of the player
- * @param {string} serverId ID of the server
- */
-
-async function getLocation(req, res) {
- const steamId = req.query.steamId;
- const serverId = req.query.serverId;
-
- sails.log.debug(`Showing location info for player ${steamId} on server ${serverId}`);
-
- if (_.isUndefined(steamId)) {
- return res.badRequest('No steam ID given');
- }
- if (_.isUndefined(serverId)) {
- return res.badRequest('No server ID given');
- }
-
- try {
- let playerInfo = await sails.helpers.loadPlayerData.with({
- serverId: serverId,
- steamId: steamId
- });
-
- let player = playerInfo.players[0];
- let toSend = new Object();
- toSend.id = player.id;
- toSend.steamId = player.steamId;
- toSend.serverId = player.server;
- toSend.location = player.location;
- return res.json(toSend);
- } catch (error) {
- sails.log.error(error);
- return res.badRequest();
- }
-}
-
-
-
-module.exports = {
- getInventory: getInventory,
- getBanStatus: getBanStatus,
- getLocation: getLocation
-};
-
- var sevenDays = require('machinepack-7daystodiewebapi');
-
-module.exports = {
-
- friendlyName: 'Ban player',
-
- description: 'Ban a player from the server',
-
- inputs: {
- playerId: {
- description: 'The ID of the player',
- type: 'number',
- required: true
- },
- reason: {
- description: 'Reason the player gets banned',
- type: 'string'
- },
- duration: {
- description: 'How long to ban the player for',
- type: 'number'
- },
- durationUnit: {
- description: 'Time unit to ban player', //["minutes", "hours", "days", "weeks", "months", "years"]
- type: 'string'
- }
- },
-
- exits: {
- success: {},
- notFound: {
- description: 'No player with the specified ID was found in the database.',
- responseType: 'notFound'
- }
- },
-
- /**
- * @memberof Player
- * @method ban
- * @description ban a player
- * @param {string} steamId Steam ID of the player
- * @param {string} serverId ID of the server
- */
-
- fn: async function (inputs, exits) {
-
- try {
-
- sails.log.debug(`API - Player:ban - banning player ${inputs.playerId}`);
- let player = await Player.findOne(inputs.playerId).populate('server');
- let server = await SdtdServer.findOne(player.server.id);
- return sevenDays.banPlayer({
- ip: server.ip,
- port: server.webPort,
- authName: server.authName,
- authToken: server.authToken,
- playerId: player.steamId,
- reason: inputs.reason,
- duration: inputs.duration,
- durationUnit: inputs.durationUnit.toLowerCase()
- }).exec({
- error: function (error) {
- return exits.error(error);
- },
- unknownPlayer: function () {
- return exits.notFound('Cannot ban player, invalid ID given!');
- },
- success: function (response) {
- return exits.success(response);
- }
- });
-
- } catch (error) {
- sails.log.error(`API - Player:ban - ${error}`);
- return exits.error(error);
- }
-
-
-
-
- }
-};
-
- var sevenDays = require('machinepack-7daystodiewebapi');
-
-module.exports = {
-
- friendlyName: 'Give item',
-
- description: 'Give item(s) to a player from the server',
-
- inputs: {
- playerId: {
- description: 'The ID of the player',
- type: 'number',
- required: true
- },
-
- itemName: {
- type: 'string',
- required: true
- },
-
- amount: {
- type: 'number',
- required: true
- },
-
- quality: {
- type: 'string'
- }
- },
-
- exits: {
- success: {},
- notFound: {
- description: 'No player with the specified ID was found in the database.',
- responseType: 'notFound'
- }
- },
-
- /**
- * @memberof Player
- * @method give-item
- * @description Give items to a player
- * @param {string} playerId Id of the player
- */
-
- fn: async function (inputs, exits) {
-
- try {
-
- sails.log.debug(`API - Player:give-item - giving ${inputs.amount} of ${inputs.itemName} to ${inputs.playerId} with quality: ${inputs.quality}`);
- let player = await Player.findOne(inputs.playerId).populate('server');
- let server = await SdtdServer.findOne(player.server.id);
-
- return sevenDays.giveItem({
- ip: server.ip,
- port: server.webPort,
- authName: server.authName,
- authToken: server.authToken,
- entityId: player.entityId,
- itemName: inputs.itemName,
- amount: inputs.amount,
- quality: inputs.quality
- }).exec({
- error: function (error) {
- return exits.error(error);
- },
- playerNotFound: function () {
- return exits.notFound('Did not find online player with given ID');
- },
- itemNotFound: function () {
- return exits.notFound('Did not find given item');
- },
- success: function (response) {
- return exits.success(response);
- }
- });
-
- } catch (error) {
- sails.log.error(`API - Player:give-item - ${error}`);
- return exits.error(error);
- }
-
-
-
-
- }
-};
-
- var sevenDays = require('machinepack-7daystodiewebapi');
-
-module.exports = {
-
- friendlyName: 'Kick player',
-
- description: 'Kick a player from the server',
-
- inputs: {
- playerId: {
- description: 'The ID of the player',
- type: 'number',
- required: true
- },
- reason: {
- description: 'Reason the player gets kicked',
- type: 'string'
- }
- },
-
- exits: {
- success: {},
- notFound: {
- description: 'No player with the specified ID was found in the database.',
- responseType: 'notFound'
- }
- },
-
- /**
- * @memberof Player
- * @description Kick a player
- * @method kick
- * @param {string} steamId Steam ID of the player
- * @param {string} serverId ID of the server
- */
-
- fn: async function (inputs, exits) {
-
- try {
-
- sails.log.debug(`API - Player:kick - Kicking player ${inputs.playerId}`);
- let player = await Player.findOne(inputs.playerId).populate('server');
- let server = await SdtdServer.findOne(player.server.id);
- return sevenDays.kickPlayer({
- ip: server.ip,
- port: server.webPort,
- authName: server.authName,
- authToken: server.authToken,
- playerId: player.steamId,
- reason: inputs.reason
- }).exec({
- error: function (error) {
- return exits.error(error);
- },
- unknownPlayer: function () {
- return exits.notFound('Cannot kick player, invalid ID given!');
- },
- success: function (response) {
- return exits.success(response);
- }
- });
-
- } catch (error) {
- sails.log.error(`API - Player:kick - ${error}`);
- return exits.error(error);
- }
-
-
-
-
- }
-};
-
- module.exports = {
-
- friendlyName: 'Player Profile',
-
- description: 'Show profile of a SdtdPlayer',
-
- inputs: {
- playerId: {
- description: 'The ID of the player',
- type: 'number',
- required: true
- }
- },
-
- exits: {
- success: {
- responseType: 'view',
- viewTemplatePath: 'player/profile'
- },
- notFound: {
- description: 'No player with the specified ID was found in the database.',
- responseType: 'notFound'
- },
- forbidden: {
- description: 'Someone who is not authorized tried to view this page',
- responseType: 'forbidden'
- }
- },
-
- /**
- * @memberof module:Player
- * @method profile
- * @description Serves the player profile view
- * @param {number} playerId
- */
-
- fn: async function (inputs, exits) {
-
- sails.log.debug(`VIEW - Player:profile - Showing profile for ${inputs.playerId}`);
-
- try {
- let player = await Player.findOne(inputs.playerId);
- let server = await SdtdServer.findOne(player.server);
- await sails.helpers.loadPlayerData(server.id, player.steamId);
- player = await Player.findOne(inputs.playerId);
-
- const hhmmss = require('@streammedev/hhmmss')
- Object.defineProperty(player, 'playtimeHHMMSS', {
- value: hhmmss(player.playtime)
- })
-
- return exits.success({
- player: player,
- server: server
- });
- } catch (error) {
- sails.log.error(`VIEW - Player:profile - ${error}`);
- throw 'notFound';
- }
-
-
- }
-};
-
- const sevenDays = require('machinepack-7daystodiewebapi');
-
-module.exports = {
-
- friendlyName: 'Teleport player',
-
- description: 'Teleport a player to given coordinates',
-
- inputs: {
- playerId: {
- description: 'The ID of the player',
- type: 'number',
- required: true
- },
- coordX: {
- description: 'X coordinate',
- type: 'number',
- required: true
- },
- coordY: {
- description: 'Y coordinate',
- type: 'number',
- required: true
- },
- coordZ: {
- description: 'Y coordinate',
- type: 'number',
- required: true
- }
- },
-
- exits: {
- success: {},
- notFound: {
- description: 'No player with the specified ID was found in the database.',
- responseType: 'notFound'
- }
- },
-
- /**
- * @memberof Player
- * @description ban a player
- * @method teleport
- * @param {string} playerId
- * @param {number} coordX
- * @param {number} coordY
- * @param {number} coordZ
- */
-
- fn: async function (inputs, exits) {
-
- try {
-
- sails.log.debug(`API - Player:teleport - teleporting player ${inputs.playerId}`);
-
- let player = await Player.findOne(inputs.playerId).populate('server');
- let server = player.server;
-
- sevenDays.teleportPlayer({
- ip: server.ip,
- port: server.webPort,
- authName: server.authName,
- authToken: server.authToken,
- playerId: player.steamId,
- coordinates: `${inputs.coordX} ${inputs.coordY} ${inputs.coordZ}`
- }).exec({
- success: (response) => {
- sails.log.debug(`API - Player:teleport - Successfully teleported player ${inputs.playerId} to ${inputs.coordX} ${inputs.coordY} ${inputs.coordZ}`);
- return exits.success();
- },
- error: (error) => {
- sails.log.error(`API - Player:teleport - ${error}`);
- return exits.error(error);
- }
- });
-
-
- } catch (error) {
- sails.log.error(`API - Player:teleport - ${error}`);
- return exits.error(error);
- }
-
-
-
-
- }
-};
-
- var sevenDays = require('machinepack-7daystodiewebapi');
-
-module.exports = {
-
- friendlyName: 'Unban player',
-
- description: 'Unban a player from the server',
-
- inputs: {
- playerId: {
- description: 'The ID of the player',
- type: 'number',
- required: true
- }
- },
-
- exits: {
- success: {},
- notFound: {
- description: 'No player with the specified ID was found in the database.',
- responseType: 'notFound'
- }
- },
-
- /**
- * @memberof Player
- * @method unban
- * @description unban a player
- * @param {string} steamId Steam ID of the player
- * @param {string} serverId ID of the server
- */
-
- fn: async function (inputs, exits) {
-
- try {
-
- sails.log.debug(`API - Player:unban - unbanning player ${inputs.playerId}`);
- let player = await Player.findOne(inputs.playerId).populate('server');
- let server = await SdtdServer.findOne(player.server.id);
- return sevenDays.unbanPlayer({
- ip: server.ip,
- port: server.webPort,
- authName: server.authName,
- authToken: server.authToken,
- playerId: player.steamId,
- }).exec({
- error: function (error) {
- return exits.error(error);
- },
- unknownPlayer: function () {
- return exits.notFound('Cannot unban player, invalid ID given!');
- },
- success: function (response) {
- return exits.success(response);
- }
- });
-
- } catch (error) {
- sails.log.error(`API - Player:unban - ${error}`);
- return exits.error(error);
- }
-
-
-
-
- }
-};
-
- module.exports = {
-
- friendlyName: 'Add server',
-
- description: '',
-
- inputs: {
-
- serverIp: {
- description: 'Ip of the SdtdServer',
- type: 'string',
- required: true
- },
-
- telnetPort: {
- type: 'number',
- required: true
- },
-
- webPort: {
- type: 'number',
- required: true,
- },
-
- telnetPassword: {
- type: 'string',
- required: true,
- },
-
- serverName: {
- type: 'string',
- required: true
- }
-
- },
-
- exits: {
-
- success: {},
- badTelnet: {
- description: 'Could not connect to telnet!',
- statusCode: 200
- },
- badWebPort: {
- description: 'WebPort given was not valid',
- statusCode: 200
- }
-
- },
-
- /**
- * @memberof SdtdServer
- * @name add-server
- * @method
- * @description Add a server to the system
- * @param {string} serverip Ip of the server to add
- * @param {number} telnetport Telnet port of the server
- * @param {string} telnetpassword Telnet password of the server
- * @param {number} webport Port for webserver added by Alloc's fixes
- */
-
- fn: async function (inputs, exits) {
-
- sails.log.info(`API - SdtdServer:addServer - Adding a new server ${inputs.serverIp} ${inputs.webPort}`);
-
- try {
- let userProfile = await User.findOne(this.req.session.userId);
- let sdtdServer = await sails.helpers.add7DtdServer.with({
- ip: inputs.serverIp,
- serverName: inputs.serverName,
- telnetPort: inputs.telnetPort,
- telnetPassword: inputs.telnetPassword,
- webPort: inputs.webPort,
- owner: userProfile.id
- })
-
- return exits.success(sdtdServer);
- } catch (error) {
- switch (error.code) {
- case 'badTelnet':
- exits.badTelnet({error: 'badTelnet'})
- break;
- case 'badWebPort':
- exits.badWebPort({error: 'badWebPort'})
- break;
- default:
- break;
- }
- sails.log.error(`API - addServer - ${error}`);
- return exits.error(error);
- }
-
-
-
- }
-
-
-};
-
- const sevenDays = require('machinepack-7daystodiewebapi');
-
-module.exports = {
-
-
- friendlyName: 'Get available items',
-
-
- description: 'Returns a list of items on the server',
-
-
- inputs: {
- serverId: {
- required: true,
- example: 4
- },
- item: {
- type: 'string',
- example: 'stew'
- }
-
- },
-
- exits: {
- badRequest: {
- responseType: 'badRequest'
- },
- notFound: {
- responseType: 'notFound',
- description: 'Server was not found in DB'
- }
- },
-
- /**
- * @memberof SdtdServer
- * @method
- * @name available-items
- * @description Returns a list of items on the server
- * @param {number} serverId ID of the server
- * @returns {array}
- */
-
- fn: async function (inputs, exits) {
- sails.log.debug(`API - SdtdServer:available-items - Loading available items!`);
- try {
- let server = await SdtdServer.findOne({
- id: inputs.serverId
- });
-
- if (_.isUndefined(server)) {
- return exits.notFound();
- }
-
- sevenDays.listItems({
- ip: server.ip,
- port: server.webPort,
- authName: server.authName,
- authToken: server.authToken,
- itemToSearch: inputs.item
- }).exec({
- success: (response) => {
- return exits.success(response);
- },
- unknownCommand: (error) => {
- return exits.commandError(error);
- },
- error: (error) => {
- return exits.error(error);
- }
- });
-
- } catch (error) {
- sails.log.error(`API - SdtdServer:available-items - ${error}`);
- return exits.error(error);
- }
-
- }
-
-
-};
-
- module.exports = {
-
- friendlyName: 'Chat',
-
- description: 'Start the chat bridge of a 7 Days to Die server & serve view',
-
- inputs: {
- serverId: {
- description: 'The ID of the server',
- type: 'number',
- required: true
- }
- },
-
- exits: {
- success: {
- responseType: 'view',
- viewTemplatePath: 'sdtdServer/chat'
- },
- notFound: {
- description: 'No server with the specified ID was found in the database.',
- responseType: 'notFound'
- }
- },
-
- /**
- * @memberof SdtdServer
- * @name chat
- * * @method
- * @description Serves the chatbridge view
- * @param {number} serverID ID of the server
- */
-
- fn: async function (inputs, exits) {
-
- sails.log.debug(`VIEW - SdtdServer:chat - Showing chat for ${inputs.serverId}`);
-
- try {
- let server = await SdtdServer.findOne(inputs.serverId);
- return exits.success({
- server: server
- });
- } catch (error) {
- sails.log.error(`VIEW - SdtdServer:chat - ${error}`);
- throw 'notFound';
- }
-
-
- }
-};
-
- module.exports = {
-
-
- friendlyName: 'Commands reload',
-
-
- description: 'Reload server config sdtdCommandsHook',
-
-
- inputs: {
- serverId: {
- required: true,
- type: 'string'
- },
- newConfig: {
- type: 'json',
- required: true
- }
- },
-
-
- exits: {
-
- notFound: {
- description: 'Server with given ID not found in the system',
- responseType: 'notFound'
- },
- success: {
- description: 'Returns true if set to enabled, false if set to disabled'
- },
- badRequest: {
- responseType: 'badRequest'
- }
-
- },
-
- /**
- * @memberof SdtdServer
- * @name commands-reload
- * @method
- * @description Reloads the config of the country ban hook for a server
- * @param {string} serverId
- * @param {json} newConfig
- */
-
-
- fn: async function (inputs, exits) {
-
- try {
- sails.log.debug(`API - SdtdServer:commands-reload - Reloading config for server ${inputs.serverId}`);
-
- let server = await SdtdServer.findOne({
- id: inputs.serverId
- });
- let config = await SdtdConfig.findOne({
- server: server.id
- });
-
- if (_.isUndefined(server)) {
- return exits.notFound();
- }
- if (_.isUndefined(config)) {
- return exits.notFound();
- }
- if (_.isUndefined(inputs.newConfig.commandsEnabled) || _.isUndefined(inputs.newConfig.commandPrefix)) {
- sails.log.error(`API - SdtdServer:commands-reload - Invalid value for commandsEnabled ${inputs.newConfig.commandsEnabled} or commandPrefix ${inputs.newConfig.commandPrefix}`);
- return exits.badRequest(`Invalid value(s) for new config`);
- }
-
- sails.hooks.sdtdcommands.updateConfig(inputs.serverId, inputs.newConfig);
-
- sails.log.debug(`API - SdtdServer:commands-reload - Reloaded config for server ${inputs.serverId}`);
-
- return exits.success();
- } catch (error) {
- sails.log.error(`API - SdtdServer:commands-reload - ${error}`);
- return exits.error(error);
- }
-
-
- }
-
-
-};
-
- module.exports = {
-
-
- friendlyName: 'Commands toggle',
-
-
- description: 'Toggle the SdtdCommandsHook',
-
-
- inputs: {
- serverId: {
- required: true,
- type: 'string'
- }
- },
-
-
- exits: {
-
- notFound: {
- description: 'Server with given ID not found in the system',
- responseType: 'notFound'
- },
- success: {
- description: 'Returns true if set to enabled, false if set to disabled'
- }
-
- },
-
- /**
- * @memberof SdtdServer
- * @name commands-toggle
- * @method
- * @description Toggles the status of the commands hook for a server
- * @param {string} serverId
- */
-
-
- fn: async function (inputs, exits) {
-
- try {
- sails.log.debug(`API - SdtdServer:commands-toggle - Toggling commands for server ${inputs.serverId}`);
-
- let server = await SdtdServer.findOne({
- id: inputs.serverId
- });
- let config = await SdtdConfig.find({
- server: inputs.serverId
- });
-
- if (config.length > 1) {
- return exits.badRequest(`Found more than one config for this server`);
- }
-
- config = config[0];
-
- if (_.isUndefined(server)) {
- return exits.notFound();
- }
-
- let commandStatus = sails.hooks.sdtdcommands.getStatus(inputs.serverId);
-
- if (!commandStatus) {
- config.commandsEnabled = true;
- } else {
- config.commandsEnabled = false;
- }
-
- await sails.hooks.sdtdcommands.updateConfig(inputs.serverId, config);
- let status = sails.hooks.sdtdcommands.getStatus(inputs.serverId);
-
- sails.log.debug(`API - SdtdServer:commands-toggle - New status for server ${inputs.serverId} is ${status}`);
-
- return exits.success(status);
- } catch (error) {
- sails.log.error(`API - SdtdServer:commands-toggle - ${error}`);
- return exits.error(error);
- }
-
-
- }
-
-
-};
-
- module.exports = {
-
- friendlyName: 'Console',
-
- description: 'Start the console of a 7 Days to Die server',
-
- inputs: {
- serverId: {
- description: 'The ID of the server',
- type: 'number',
- required: true
- }
- },
-
- exits: {
- success: {
- responseType: 'view',
- viewTemplatePath: 'sdtdServer/console'
- },
- notFound: {
- description: 'No server with the specified ID was found in the database.',
- responseType: 'notFound'
- }
- },
-
- /**
- * @memberof SdtdServer
- * @name console
- * @method
- * @description Server the console view
- * @param {number} serverID ID of the server
- */
-
- fn: async function (inputs, exits) {
-
- sails.log.debug(`VIEW - SdtdServer:console - Showing console for ${inputs.serverId}`);
-
- try {
- let server = await SdtdServer.findOne(inputs.serverId);
- return exits.success({
- server: server
- });
- } catch (error) {
- sails.log.error(`VIEW - SdtdServer:console - ${error}`);
- throw 'notFound';
- }
-
-
- }
-};
-
- module.exports = {
-
-
- friendlyName: 'CountryBan reload',
-
-
- description: 'Reload server config 7dtdCountryBanHook',
-
-
- inputs: {
- serverId: {
- required: true,
- type: 'string'
- },
- newConfig: {
- type: 'json'
- }
- },
-
-
- exits: {
-
- notFound: {
- description: 'Server with given ID not found in the system',
- responseType: 'notFound'
- },
- success: {
- description: 'Returns true if set to enabled, false if set to disabled'
- }
-
- },
-
- /**
- * @memberof SdtdServer
- * @name country-ban-reload
- * @method
- * @description Reloads the config of the country ban hook for a server
- * @param {string} serverId
- */
-
-
- fn: async function (inputs, exits) {
-
- try {
- sails.log.debug(`API - SdtdServer:country-ban-reload - Reloading config for server ${inputs.serverId}`);
- let server = await SdtdServer.findOne({
- id: inputs.serverId
- });
-
- if (_.isUndefined(server)) {
- return exits.notFound();
- }
-
- let config = await SdtdConfig.findOne({server: server.id});
-
- if (_.isUndefined(inputs.newConfig)) {
- sails.hooks.countryban.reload(inputs.serverId);
- } else {
- let configToSend = config.countryBanConfig;
-
- if (typeof inputs.newConfig.bannedCountries === typeof new Array()) {
- // Handle the input countries & adjust the config to send accordingly
- for (const country of inputs.newConfig.bannedCountries) {
- if (configToSend.bannedCountries.includes(country)) {
- var index = configToSend.bannedCountries.indexOf(country);
- if (index > -1) {
- configToSend.bannedCountries.splice(index, 1);
- }
- } else {
- configToSend.bannedCountries.push(country);
- }
- }
- }
-
- if (_.isArray(inputs.newConfig.whiteListedSteamIds)) {
- configToSend.whiteListedSteamIds = inputs.newConfig.whiteListedSteamIds;
-
- }
-
- configToSend.kickMessage = inputs.newConfig.kickMessage == '' ? configToSend.kickMessage : inputs.newConfig.kickMessage;
-
- sails.hooks.countryban.reload(inputs.serverId, configToSend);
- }
-
- sails.log.debug(`API - SdtdServer:country-ban-reload - Reloaded config for server ${inputs.serverId}`);
-
- return exits.success();
- } catch (error) {
- sails.log.error(`API - SdtdServer:country-ban-reload - ${error}`);
- return exits.error(error);
- }
-
-
- }
-
-
-};
-
- module.exports = {
-
-
- friendlyName: 'CountryBan toggle',
-
-
- description: 'Toggle the 7dtdCountryBanHook',
-
-
- inputs: {
- serverId: {
- required: true,
- type: 'string'
- }
- },
-
-
- exits: {
-
- notFound: {
- description: 'Server with given ID not found in the system',
- responseType: 'notFound'
- },
- success: {
- description: 'Returns true if set to enabled, false if set to disabled'
- }
-
- },
-
- /**
- * @memberof SdtdServer
- * @name country-ban-toggle
- * @method
- * @description Toggles the status of the country ban hook for a server
- * @param {string} serverId
- */
-
-
- fn: async function (inputs, exits) {
-
- try {
- sails.log.debug(`API - SdtdServer:country-ban-toggle - Toggling country ban for server ${inputs.serverId}`);
- let server = await SdtdServer.findOne({
- id: inputs.serverId
- });
- if (_.isUndefined(server)) {
- return exits.notFound();
- }
-
- let countryBanStatus = sails.hooks.countryban.getStatus(inputs.serverId);
-
- if (_.isUndefined(countryBanStatus)) {
- await sails.hooks.countryban.start(inputs.serverId);
- } else {
- await sails.hooks.countryban.stop(inputs.serverId);
- }
- let status = await sails.hooks.countryban.getStatus(inputs.serverId);
-
- sails.log.debug(`API - SdtdServer:country-ban-toggle - New status for server ${inputs.serverId} is ${status}`);
-
- return exits.success(status);
- } catch (error) {
- sails.log.error(`API - SdtdServer:country-ban-toggle - ${error}`);
- return exits.error(error);
- }
-
-
- }
-
-
-};
-
- module.exports = {
-
- friendlyName: 'Dashboard',
-
- description: 'Show the dashboard of a 7 Days to Die server',
-
- inputs: {
- serverId: {
- description: 'The ID of the server to look up.',
- type: 'number',
- required: true
- }
- },
-
- exits: {
- success: {
- responseType: 'view',
- viewTemplatePath: 'sdtdServer/dashboard'
- },
- notFound: {
- description: 'No server with the specified ID was found in the database.',
- responseType: 'notFound'
- }
- },
-
- /**
- * @memberof SdtdServer
- * @name dashboard
- * @method
- * @description Serves the dashboard for a 7 Days to die server
- */
-
- fn: async function (inputs, exits) {
- sails.log.debug(`VIEW - SdtdServer:dashboard - Showing dashboard for ${inputs.serverId}`);
-
- try {
- let sdtdServer = await SdtdServer.findOne(inputs.serverId);
- sdtdServerInfo = await sails.helpers.loadSdtdserverInfo(inputs.serverId)
- .tolerate('unauthorized', (error) => {
- sails.log.warn(`VIEW - SdtdServer:dashboard - unauthorized for server cannot load serverInfo ${inputs.serverId}`)
- });
-
- if (!_.isUndefined(sdtdServerInfo)) {
- sdtdServer = sdtdServerInfo;
- }
- let players = await sails.helpers.loadPlayerData(inputs.serverId)
- .tolerate('unauthorized', (error) => {
- sails.log.warn(`VIEW - SdtdServer:dashboard - unauthorized for server cannot load playerInfo ${inputs.serverId}`)
-
- });
- return exits.success({
- server: sdtdServer,
- players: players
- });
- } catch (error) {
- sails.log.error(`VIEW - SdtdServer:dashboard - ${error}`);
- throw 'notFound';
- }
-
-
- }
-};
-
- const sevenDays = require('machinepack-7daystodiewebapi');
-
-module.exports = {
-
- friendlyName: 'Delete server',
-
- description: 'Delete a server from the system',
-
- inputs: {
- serverId: {
- description: 'The ID of the server',
- type: 'number',
- required: true
- }
- },
-
- exits: {
- success: {
- responseType: 'view',
- viewTemplatePath: 'sdtdServer/delete'
- },
- notFound: {
- description: 'No server with the specified ID was found in the database.',
- responseType: 'notFound'
- }
- },
-
- /**
- * @memberof SdtdServer
- * @name delete
- * @method
- * @description Deletes a server from the system
- * @param {number} serverID ID of the server
- */
-
- fn: async function (inputs, exits) {
-
- sails.log.debug(`VIEW - SdtdServer:delete - Deleting server ${inputs.serverId}`);
-
- try {
- let server = await SdtdServer.findOne(inputs.serverId);
- if (_.isUndefined(server)) {
- return exits.notFound();
- }
-
- await sails.hooks.sdtdlogs.stop(server.id);
-
- sevenDays.executeCommand({
- ip: server.ip,
- port: server.webPort,
- authName: server.authName,
- authToken: server.authToken,
- command: `webtokens remove ${server.authName}`
- }).exec({
- success: result => {
- },
- error: error => {
- sails.log.warn(`VIEW - SdtdServer:delete- Error while trying to delete token - ${error}`);
- }
- })
-
- await SdtdConfig.destroy({
- server: server.id
- });
- await Player.destroy({
- server: server.id
- })
- await SdtdServer.destroy({
- id: server.id
- });
-
- exits.success();
-
- } catch (error) {
- sails.log.error(`VIEW - SdtdServer:delete - ${error}`);
- exits.error(error);
- }
-
-
- }
-};
-
- module.exports = {
-
-
- friendlyName: 'Check if bot is in guild',
-
-
- description: 'Checks if the discord bot is in a discord guild with given ID.',
-
-
- inputs: {
- guildId: {
- required: true,
- example: '336821518250147850'
- }
-
- },
-
- exits: {
- badRequest: {
- responseType: 'badRequest'
- }
- },
-
- /**
- * @memberof SdtdServer
- * @method
- * @name check-if-bot-is-in-guild
- * @param {number} guildId discord guild id
- * @returns {array}
- */
-
- fn: async function (inputs, exits) {
- sails.log.debug(`API - SdtdServer:check-if-bot-is-in-guild - Check if the bot is in server ${inputs.guildId}!`);
- try {
-
- let discordClient = sails.hooks.discordbot.getClient();
-
- exits.success(discordClient.guilds.has(inputs.guildId));
-
- } catch (error) {
- sails.log.error(`API - SdtdServer:check-if-bot-is-in-guild - ${error}`);
- return exits.error(error);
- }
-
- }
-
-
-};
-
- module.exports = {
-
-
- friendlyName: 'Find channels the bot can write in for a guild ID',
-
-
- description: '',
-
-
- inputs: {
- guildId: {
- example: '1337'
- }
-
- },
-
- exits: {
- badRequest: {
- responseType: 'badRequest'
- }
- },
-
- /**
- * @memberof SdtdServer
- * @method
- * @name find-writeable-channels-in-guild
- * @param {string} guildId
- * @returns {array}
- */
-
- fn: async function (inputs, exits) {
-
- try {
-
- let discordClient = sails.hooks.discordbot.getClient();
- let guild = discordClient.guilds.get(inputs.guildId);
- if (_.isUndefined(guild)) {
- return exits.badRequest();
- }
-
- let foundChannels = guild.channels.filter(channel => {
- if (channel.type !== 'text') {
- return false;
- }
- let userPerms = channel.permissionsFor(discordClient.user)
- return userPerms.has('SEND_MESSAGES')
- });
-
- let foundChannelsArray = Array.from(foundChannels.values());
-
- exits.success(foundChannelsArray);
- sails.log.debug(`API - SdtdServer:find-writeable-channels-in-guild - Found ${foundChannelsArray.length} channels for guild ${inputs.guildId}!`);
- } catch (error) {
- sails.log.error(`API - SdtdServer:find-writeable-channels-in-guild - ${error}`);
- return exits.error(error);
- }
-
- }
-
-
- };
-
- const sevenDays = require('machinepack-7daystodiewebapi');
-
-module.exports = {
-
- friendlyName: 'Execute command',
-
- description: 'Execute a command on a 7 Days to Die server',
-
- inputs: {
- serverId: {
- description: 'The ID of the server to look up.',
- type: 'number',
- required: true
- },
- command: {
- description: 'Command to execute',
- type: 'string',
- required: true
- }
- },
-
- exits: {
- success: {},
- notFound: {
- description: 'No server with the specified ID was found in the database.',
- responseType: 'notFound'
- },
- commandError: {
- description: 'Error executing the command',
- responseType: 'badRequest'
- }
- },
-
- /**
- * @memberof SdtdServer
- * @name executeCommand
- * @method
- * @description Executes a command on a 7dtd server
- * @param {number} serverId ID of the server
- * @param {string} command Command to be executed
- */
-
- fn: async function (inputs, exits) {
- sails.log.debug(`API - SdtdServer:executeCommand - Executing a command on server ${inputs.serverId}`);
-
- try {
- let sdtdServer = await SdtdServer.findOne(inputs.serverId);
- if (_.isUndefined(sdtdServer)) {
- return exits.notFound();
- }
- sevenDays.executeCommand({
- ip: sdtdServer.ip,
- port: sdtdServer.webPort,
- authName: sdtdServer.authName,
- authToken: sdtdServer.authToken,
- command: inputs.command
- }).exec({
- success: (response) => {
- let logLine = {
- msg: response.result,
- date: new Date(),
- type: 'commandResponse'
- };
- return exits.success(logLine);
- },
- unknownCommand: (error) => {
- return exits.commandError(error);
- },
- error: (error) => {
- return exits.error(error);
- }
- });
-
- } catch (error) {
- sails.log.error(`API - SdtdServer:executeCommand - ${error}`);
- return exits.error(error);
- }
-
- }
-};
-
- module.exports = {
-
-
- friendlyName: 'Get players view',
-
-
- description: 'Load the player overview view',
-
-
- inputs: {
- serverId: {
- required: true,
- example: 4
- }
- },
-
-
- exits: {
- success: {
- responseType: 'view',
- viewTemplatePath: 'sdtdServer/players'
- }
-
- },
-
- /**
- * @memberof SdtdServer
- * @name get-players-view
- * @method
- * @description Serve the players views
- * @param {number} serverId ID of the server
- */
-
-
- fn: async function (inputs, exits) {
-
- try {
- sails.log.debug('VIEW - SdtdServer:players - serving players view');
- let server = await SdtdServer.findOne({
- id: inputs.serverId
- });
- let players = await Player.find({
- server: server.id
- });
- exits.success({
- players: players,
- server: server
- });
- } catch (error) {
- sails.log.error(`VIEW - SdtdServer:players - ${error}`);
- }
-
- }
-
-
-};
-
- module.exports = {
-
-
- friendlyName: 'Get players',
-
-
- description: 'Loads data about all players associated with a server',
-
-
- inputs: {
- serverId: {
- required: true,
- example: 4
- }
-
- },
-
- exits: {
- notFound: {
- description: 'Server with given ID was not found in the system'
- },
- badRequest: {
- responseType: 'badRequest'
- },
- notFound: {
- responseType: 'notFound',
- description: 'Server was not found in DB'
- }
- },
-
- /**
- * @memberof SdtdServer
- * @method
- * @name get-players
- * @description Get information about all players that have logged into the server
- * @param {number} serverId ID of the server
- */
-
- fn: async function (inputs, exits) {
- sails.log.debug(`API - SdtdServer:getPlayers - Loading player data!`);
- try {
- let server = await SdtdServer.findOne({
- id: inputs.serverId
- });
- if (_.isUndefined(server)) {
- return exits.notFound();
- }
- sails.helpers.loadPlayerData(server.id)
- .switch({
- success: function(data) {
- return exits.success(data);
- },
- error: function(error) {
- return exits.badRequest();
- }
- });
- } catch (error) {
- sails.log.error(`API - SdtdServer:getPlayers - ${error}`);
- return exits.error(error);
- }
-
- }
-
-
-};
-
- module.exports = {
-
-
- friendlyName: 'Load server info',
-
-
- description: 'Load server info and save to database',
-
-
- inputs: {
- serverId: {
- required: true,
- description: 'ID of the server',
- type: 'string'
- }
- },
-
-
- exits: {
- notFound: {
- description: 'Given serverId did not correspond to a server in the system'
- }
- },
-
- /**
- * @memberof SdtdServer
- * @method
- * @name load-server-info
- * @description Load/update server info and save to DB
- * @param {number} serverId ID of the server
- */
-
-
- fn: async function (inputs, exits) {
-
- sails.log.debug(`API - SdtdServer:loadServerInfo - loading info for server ${inputs.serverId}`);
-
- try {
- let serverInfo = await sails.helpers.loadSdtdserverInfo(inputs.serverId);
- exits.success(serverInfo);
- } catch (error) {
- sails.log.error(`API - SdtdServer:loadServerInfo - ${error}`);
- }
- }
-
-
-};
-
- module.exports = {
-
-
- friendlyName: 'Logging toggle',
-
-
- description: 'Toggle the 7dtdLoggingHook',
-
-
- inputs: {
- serverId: {
- required: true,
- type: 'string'
- }
- },
-
-
- exits: {
-
- notFound: {
- description: 'Server with given ID not found in the system',
- responseType: 'notFound'
- },
- success: {
- description: 'Returns true if set to enabled, false if set to disabled'
- }
-
- },
-
- /**
- * @memberof SdtdServer
- * @name logging-toggle
- * @method
- * @description Toggles the status of the logging hook for a server
- * @param {string} serverId
- */
-
-
- fn: async function (inputs, exits) {
-
- try {
- sails.log.debug(`API - SdtdServer:logging-toggle - Toggling logging for server ${inputs.serverId}`);
- let server = await SdtdServer.findOne({
- id: inputs.serverId
- });
- if (_.isUndefined(server)) {
- return exits.notFound();
- }
- if (!sails.hooks.sdtdlogs.getStatus(inputs.serverId)) {
- await sails.hooks.sdtdlogs.start(inputs.serverId);
- } else {
- await sails.hooks.sdtdlogs.stop(inputs.serverId);
- }
- let status = sails.hooks.sdtdlogs.getStatus(inputs.serverId);
- sails.log.debug(`API - SdtdServer:logging-toggle - New status for server ${inputs.serverId} is ${status}`);
- return exits.success(status);
- } catch (error) {
- sails.log.error(`API - SdtdServer:logging-toggle - ${error}`);
- }
-
-
- }
-
-
-};
-
- module.exports = {
-
-
- friendlyName: 'MOTD reload',
-
-
- description: 'Reload server config 7dtdMOTDHook',
-
-
- inputs: {
- serverId: {
- required: true,
- type: 'string'
- },
- newMessage: {
- type: 'string'
- },
- newDelay: {
- type: 'number'
- },
- newStatusOnJoin: {
- type: 'boolean'
- }
- },
-
-
- exits: {
-
- notFound: {
- description: 'Server with given ID not found in the system',
- responseType: 'notFound'
- },
- success: {
- description: 'Returns true if set to enabled, false if set to disabled'
- },
- invalidInput: {
- description: 'invalid inputs',
- responseType: 'badRequest'
- }
-
- },
-
- /**
- * @memberof SdtdServer
- * @name motd-reload
- * @method
- * @description Reloads the config of the country ban hook for a server
- * @param {string} serverId
- */
-
-
- fn: async function (inputs, exits) {
-
- try {
- sails.log.debug(`API - SdtdServer:motd-reload - Reloading config for server ${inputs.serverId}`);
- let server = await SdtdServer.findOne({
- id: inputs.serverId
- });
- let config = await SdtdConfig.findOne({
- server: server.id
- });
-
- if (_.isUndefined(server)) {
- return exits.notFound();
- }
-
- if (!_.isUndefined(inputs.newDelay) && inputs.newDelay != '0') {
- if (isNaN(inputs.newDelay) || (10 > inputs.newDelay) || (2000 < inputs.newDelay) || !Number.isInteger(Number(inputs.newDelay))) {
- return exits.invalidInput();
- }
- }
-
- await sails.hooks.sdtdmotd.updateConfig(inputs.serverId,
- _.isUndefined(inputs.newMessage) ? config.motdMessage : inputs.newMessage,
- _.isUndefined(inputs.newDelay) ? config.motdInterval : inputs.newDelay,
- config.motdEnabled,
- _.isUndefined(inputs.newStatusOnJoin) ? config.motdOnJoinEnabled : inputs.newStatusOnJoin
- );
-
- sails.log.debug(`API - SdtdServer:motd-reload - Reloaded config for server ${inputs.serverId}`);
-
- return exits.success();
- } catch (error) {
- sails.log.error(`API - SdtdServer:motd-reload - ${error}`);
- return exits.error(error);
- }
-
-
- }
-
-
-};
-
- module.exports = {
-
-
- friendlyName: 'MOTD toggle',
-
-
- description: 'Toggle the 7dtdMOTDHook',
-
-
- inputs: {
- serverId: {
- required: true,
- type: 'string'
- },
- message: {
- type: 'string',
- },
- interval: {
- type: 'number'
- }
- },
-
-
- exits: {
-
- notFound: {
- description: 'Server with given ID not found in the system',
- responseType: 'notFound'
- },
- success: {
- description: 'Returns true if set to enabled, false if set to disabled'
- }
-
- },
-
- /**
- * @memberof SdtdServer
- * @name motd-toggle
- * @method
- * @description Toggles the status of the motd hook for a server
- * @param {string} serverId
- * @param {string} message
- * @param {number} interval
- */
-
-
- fn: async function (inputs, exits) {
-
- try {
- sails.log.debug(`API - SdtdServer:motd-toggle - Toggling motd for server ${inputs.serverId}`);
- let server = await SdtdServer.findOne({
- id: inputs.serverId
- });
- let config = await SdtdConfig.findOne({
- server: inputs.serverId
- });
-
- if (_.isUndefined(server) || _.isUndefined(config)) {
- return exits.notFound();
- }
-
- if (config.motdEnabled) {
- await sails.hooks.sdtdmotd.updateConfig(inputs.serverId, config.motdMessage, config.motdInterval, false, config.motdOnJoinEnabled);
- } else {
- await sails.hooks.sdtdmotd.updateConfig(inputs.serverId, config.motdMessage, config.motdInterval, true, config.motdOnJoinEnabled);
- }
-
- let status = sails.hooks.sdtdmotd.getStatus(inputs.serverId);
- sails.log.debug(`API - SdtdServer:motd-toggle - New status for server ${inputs.serverId} is ${status}`);
-
- return exits.success(status);
- } catch (error) {
- sails.log.error(`API - SdtdServer:motd-toggle - ${error}`);
- return exits.error(error);
- }
-
-
- }
-
-
-};
-
- var sevenDays = require('machinepack-7daystodiewebapi');
-
-module.exports = {
-
- friendlyName: 'Restart server',
-
- description: 'Restart a server with configurable countdown',
-
- inputs: {
- serverId: {
- description: 'The ID of the server',
- type: 'number',
- required: true
- },
- delay: {
- description: 'Time to delay (in minutes)',
- type: 'number'
- }
- },
-
- exits: {
- success: {},
- notFound: {
- description: 'No server with the specified ID was found in the database.',
- responseType: 'notFound'
- }
- },
-
- /**
- * @memberof SdtdServer
- * @name restart-server
- * @description Restart a server
- * @param {string} serverId ID of the server
- * @param {number} delay Time to delay the restart (in minutes)
- */
-
- fn: async function (inputs, exits) {
-
- try {
-
- sails.log.debug(`API - SdtdServer:restart-server - Restarting server ${inputs.serverId} in ${inputs.delay} minutes`);
-
- if (_.isUndefined(inputs.delay)) {
- inputs.delay = 5;
- }
-
- let server = await SdtdServer.findOne(inputs.serverId);
-
- setTimeout(() => {
- sevenDays.executeCommand({
- ip: server.ip,
- port: server.webPort,
- authName: server.authName,
- authToken: server.authToken,
- command: `shutdown`
- }).exec({
- error: (error) => {
- sails.log.error(`API - SdtdServer:restart-server - ${error}`);
- },
- success: (response) => {
- sails.log.debug(`API - SdtdServer:restart-server - Successful restart for server ${inputs.serverId} in ${inputs.delay} minutes`);
-
- }
- });
- }, inputs.delay * 60 * 1000);
-
-
-
- for (let index = 0; index < inputs.delay+1; index++) {
- setTimeout(async function () {
- if (inputs.delay - index > 0) {
- await sendXMinutesUntilRestartToServer(inputs.delay - index, server);
- }
- }, index * 60 * 1000);
- }
-
- return exits.success();
-
-
- } catch (error) {
- sails.log.error(`API - SdtdServer:restart-server - ${error}`);
- return exits.error(error);
- }
-
-
-
-
- }
-};
-
-/**
- * @memberof SdtdServer#restart-server
- * @param {number} minutesLeft
- * @param {json} server server object with connection data
- * @returns {number} Amount of minutes left after message (eg input - 1)
- */
-
-function sendXMinutesUntilRestartToServer(minutesLeft, server) {
- return new Promise((resolve, reject) => {
- if (isNaN(minutesLeft)) {
- reject(new Error(`Did not supply a number`));
- }
-
- sevenDays.sendMessage({
- ip: server.ip,
- port: server.webPort,
- authName: server.authName,
- authToken: server.authToken,
- message: `Restarting the server in ${minutesLeft} minute(s)`
- }).exec({
- error: (error) => {
- reject(error);
- },
- success: (response) => {
- resolve(minutesLeft - 1);
- }
- });
- });
-}
-
- const sevenDays = require('machinepack-7daystodiewebapi');
-
-module.exports = {
-
- friendlyName: 'Send message',
-
- description: 'Execute a message on a 7 Days to Die server',
-
- inputs: {
- serverId: {
- description: 'The ID of the server to look up.',
- type: 'number',
- required: true
- },
- message: {
- description: 'message to send',
- type: 'string',
- required: true
- },
- destinationPlayer: {
- description: 'Player to send a message to (steamID)',
- type:'string'
- }
- },
-
- exits: {
- success: {
- },
- notFound: {
- description: 'No server/player with the specified ID was found in the database.',
- responseType: 'notFound'
- }
- },
-
- /**
- * @memberof SdtdServer
- * @name sendMessage
- * @method
- * @description sends a message on a 7dtd server
- * @param {number} serverID ID of the server
- * @param {string} message Message to be executed
- * @param {string} destinationPlayer SteamID of the player to send a message to
- */
-
- fn: async function (inputs, exits) {
-
-
-
- sails.log.debug(`API - SdtdServer:send message - sending a message on server ${inputs.serverId} to player: ${inputs.destinationPlayer}`);
-
- try {
- let sdtdServer = await SdtdServer.findOne(inputs.serverId);
- sevenDays.sendMessage({
- ip: sdtdServer.ip,
- port: sdtdServer.webPort,
- authName: sdtdServer.authName,
- authToken: sdtdServer.authToken,
- message: inputs.message,
- playerID: inputs.destinationPlayer ? inputs.destinationPlayer : undefined
- }).exec({
- success: (response) => {
- return exits.success(response);
- },
- error: (error) => {
- return exits.error(error);
- }
- });
-
- } catch (error) {
- sails.log.error(`API - SdtdServer:sendMessage - ${error}`);
- return exits.error(error);
- }
-
- }
-};
-
- module.exports = {
-
- friendlyName: 'Server info view',
-
- description: 'Serve view witj full serverinfo',
-
- inputs: {
- serverId: {
- description: 'The ID of the server',
- type: 'number',
- required: true
- }
- },
-
- exits: {
- success: {
- responseType: 'view',
- viewTemplatePath: 'sdtdServer/info'
- },
- notFound: {
- description: 'No server with the specified ID was found in the database.',
- responseType: 'notFound'
- }
- },
-
- /**
- * @memberof SdtdServer
- * @name server-infoview
- * @method
- * @description Serves the serverinfo view
- * @param {number} serverId ID of the server
- */
-
- fn: async function (inputs, exits) {
-
- sails.log.debug(`VIEW - SdtdServer:info - Showing info for ${inputs.serverId}`);
-
- try {
- let server = await sails.helpers.loadSdtdserverInfo(inputs.serverId);
- return exits.success({
- server: server
- });
- } catch (error) {
- sails.log.error(`VIEW - SdtdServer:info - ${error}`);
- throw 'notFound';
- }
-
-
- }
-};
-
- module.exports = {
-
- friendlyName: 'Settings',
-
- description: 'Show the settings for a server view',
-
- inputs: {
- serverId: {
- description: 'The ID of the server',
- type: 'number',
- required: true
- }
- },
-
- exits: {
- success: {
- responseType: 'view',
- viewTemplatePath: 'sdtdServer/settings'
- },
- notFound: {
- description: 'No server with the specified ID was found in the database.',
- responseType: 'notFound'
- }
- },
-
- /**
- * @memberof SdtdServer
- * @name settings
- * @method
- * @description Serves the settings view
- * @param {number} serverId ID of the server
- */
-
- fn: async function (inputs, exits) {
-
- sails.log.debug(`VIEW - SdtdServer:settings - Showing settings for ${inputs.serverId}`);
-
- try {
- let server = await SdtdServer.findOne(inputs.serverId);
- let serverConfig = await SdtdConfig.findOne({server: server.id});
- let user = await User.findOne(this.req.session.userId)
- return exits.success({
- server: server,
- config: serverConfig,
- user: user
- });
- } catch (error) {
- sails.log.error(`VIEW - SdtdServer:settings - ${error}`);
- throw 'notFound';
- }
-
-
- }
-};
-
- module.exports = {
-
-
- friendlyName: 'Subscribe to socket',
-
-
- description: 'Subscribe a client to their server socket',
-
-
- inputs: {
- serverId: {
- description: 'Id of the server',
- required: true,
- type: 'string'
- }
-
- },
-
-
- exits: {
-
- serverNotFound: {
- description: 'Server with the specified ID was not found in the system'
- },
- notASocket: {
- description: 'Client that made the request is not a socket'
- }
-
- },
-
- /**
- * @memberof SdtdServer
- * @method
- * @description Subscribe to a socket to receive event notifications
- * @name subscribe-to-socket
- * @param {serverId}
- */
-
- fn: async function (inputs, exits) {
- sails.log.debug(`API - SdtdServer:subscribeToSocket - subscribing to server ${inputs.serverId}`);
-
- if (!this.req.isSocket) {
- throw 'notASocket';
- }
-
- try {
- let server = await SdtdServer.findOne({id: inputs.serverId});
- if (_.isUndefined(server)) {
- throw serverNotFound;
- }
- sails.sockets.join(this.req, inputs.serverId);
- sails.log.debug(`API - SdtdServer:subscribeToSocket - Successfully connected server ${inputs.serverId}`);
- } catch (error) {
- sails.log.error(`API - SdtdServer:subscribeToSocket - ${error}`);
- return exits.error(error);
- }
-
- return exits.success();
-
- }
-
-
-};
-
- const sevenDays = require('machinepack-7daystodiewebapi');
-
-module.exports = {
-
-
- friendlyName: 'Update connection info',
-
-
- description: 'Update ip, port, authname and/or authtoken for a sdtdServer',
-
-
- inputs: {
- serverId: {
- required: true,
- type: 'string'
- },
- serverIp: {
- type: 'string',
- },
-
- webPort: {
- type: 'number',
- },
-
- authName: {
- type: 'string',
- },
-
- authToken: {
- type: 'string',
- },
- serverName: {
- type: 'string'
- }
- },
-
-
- exits: {
-
- notFound: {
- description: 'Server with given ID not found in the system',
- responseType: 'notFound'
- },
- success: {}
-
- },
-
- /**
- * @memberof SdtdServer
- * @name update-connection-info
- * @method
- * @description Updates basic connection info for a server in the DB
- * @param {string} serverId
- * @param {string} serverIp
- * @param {number} webPort
- * @param {string} authName
- * @param {string} authToken
- */
-
-
- fn: async function (inputs, exits) {
-
- try {
- sails.log.debug(`API - SdtdServer:update-connection-info - Updating connection info for server ${inputs.serverId}`);
-
- let server = await SdtdServer.findOne(inputs.serverId);
-
- let ip = ('' == inputs.serverIp) ? server.ip : inputs.serverIp;
- let webPort = ('' == inputs.webPort) ? server.webPort : inputs.webPort;
- let serverName = ('' == inputs.serverName) ? server.name : inputs.serverName;
-
- await SdtdServer.update({
- id: inputs.serverId
- }, {
- ip: ip,
- webPort: webPort,
- name: serverName
- });
-
- if (inputs.webPort || inputs.serverIp) {
- sails.hooks.sdtdlogs.stop(inputs.serverId);
- sails.hooks.sdtdlogs.start(inputs.serverId);
- }
- return exits.success();
- } catch (error) {
- sails.log.error(`API - SdtdServer:update-connection-info - ${error}`);
- return exits.error(error);
- }
-
-
- }
-
-
-};
-
- module.exports = {
-
-
- friendlyName: 'Edit ticket details',
-
-
- description: 'Update the details of a ticket',
-
-
- inputs: {
- ticketId: {
- required: true,
- type: 'string'
- },
- description: {
- type: 'string'
- }
- },
-
-
- exits: {
-
- notFound: {
- description: 'Ticket with given ID not found in the system',
- responseType: 'notFound'
- },
- success: {
- }
-
- },
-
- /**
- * @memberof SdtdTicket
- * @name edit-ticket
- * @method
- * @description Changes details of a ticket
- * @param {string} ticketId
- */
-
-
- fn: async function (inputs, exits) {
-
- try {
- sails.log.debug(`API - SdtdTicket:edit-ticket - Editing info for ticket ${inputs.ticketId}`);
-
- await SdtdTicket.update({id: inputs.ticketId}, {
- description: inputs.description
- });
-
- return exits.success();
- } catch (error) {
- sails.log.error(`API - SdtdTicket:edit-ticket - ${error}`);
- return exits.error(error);
- }
-
-
- }
-
-
-};
-
- module.exports = {
-
-
- friendlyName: 'Get open tickets for a server',
-
-
- description: 'Get open tickets for a server',
-
-
- inputs: {
- serverId: {
- type: 'string'
- }
- },
-
-
- exits: {
- success: {}
-
- },
-
- /**
- * @memberof SdtdTicket
- * @name open-tickets
- * @method
- * @description Get open tickets for a server
- * @param {string} serverId
- */
-
-
- fn: async function (inputs, exits) {
-
- try {
- let openTickets = await SdtdTicket.find({
- server: inputs.serverId,
- status: true
- });
- sails.log.debug(`API - SdtdTicket:open-ticket - found ${openTickets.length} open tickets for server ${inputs.serverId}`)
- return exits.success(openTickets);
- } catch (error) {
- sails.log.error(`API - SdtdTicket:open-tickets - ${error}`);
- return exits.error(error);
- }
-
-
- }
-
-
-};
-
- module.exports = {
-
-
- friendlyName: 'Server tickets view',
-
-
- description: 'Loads relevant ticket data, and serves the view',
-
-
- inputs: {
- serverId: {
- type: 'string',
- required: true
- }
- },
-
-
- exits: {
-
- notFound: {
- description: 'Server with given ID not found in the system',
- responseType: 'notFound'
- },
- success: {
- description: '',
- responseType: 'view',
- viewTemplatePath: 'sdtdServer/tickets'
- }
-
- },
-
- /**
- * @memberof SdtdServer
- * @name tickets-view
- * @method
- * @description Loads relevant ticket data, and serves the view
- * @param {string} serverId
- */
-
-
- fn: async function (inputs, exits) {
-
- try {
- sails.log.debug(`API - SdtdServer:tickets-view - Loading tickets view for server ${inputs.serverId}`);
-
- let server = await SdtdServer.findOne({
- id: inputs.serverId
- });
- let tickets = await SdtdTicket.find({
- server: inputs.serverId
- }).populate('player')
-
- if (_.isUndefined(server) || _.isUndefined(tickets)) {
- return exits.notFound();
- }
-
- sails.log.debug(`API - SdtdServer:tickets-view - Success, loaded ${tickets.length} tickets`);
- return exits.success({
- server: server,
- tickets: tickets
- });
-
- } catch (error) {
- sails.log.error(`API - SdtdServer:tickets-view - ${error}`);
- return exits.error(error);
- }
-
-
- }
-
-
-};
-
- module.exports = {
-
-
- friendlyName: 'Update ticket status',
-
-
- description: 'Update the status of a SdtdTicket to closed/open',
-
-
- inputs: {
- ticketId: {
- required: true,
- type: 'string'
- },
- status: {
- required: true,
- type: 'boolean'
- }
- },
-
-
- exits: {
-
- notFound: {
- description: 'Ticket with given ID not found in the system',
- responseType: 'notFound'
- },
- success: {
- }
-
- },
-
- /**
- * @memberof SdtdTicket
- * @name update-ticket-status
- * @method
- * @description Changes the status of a ticket
- * @param {string} ticketId
- */
-
-
- fn: async function (inputs, exits) {
-
- try {
- sails.log.debug(`API - SdtdTicket:update-ticket-status - Updating status for ticket ${inputs.ticketId}`);
-
- await SdtdTicket.update({id: inputs.ticketId}, {
- status: inputs.status
- });
-
- return exits.success();
- } catch (error) {
- sails.log.error(`API - SdtdTicket:update-ticket-status - ${error}`);
- return exits.error(error);
- }
-
-
- }
-
-
-};
-
- module.exports = {
-
-
- friendlyName: 'User tickets view',
-
-
- description: 'Loads relevant ticket data, and serves the view',
-
-
- inputs: {
- userId: {
- type: 'string',
- required: true
- }
- },
-
-
- exits: {
-
- notFound: {
- description: 'Server with given ID not found in the system',
- responseType: 'notFound'
- },
- success: {
- description: '',
- responseType: 'view',
- viewTemplatePath: 'sdtdServer/tickets'
- }
-
- },
-
- /**
- * @memberof SdtdServer
- * @name user-tickets-view
- * @method
- * @description Loads relevant ticket data, and serves the view
- * @param {string} userId
- */
-
-
- fn: async function (inputs, exits) {
-
- try {
- sails.log.debug(`API - SdtdServer:user-tickets-view - Loading tickets view for user ${inputs.userId}`);
-
- let user = await User.findOne({
- id: inputs.userId
- }).populate('players');
-
- let playerIds = new Array();
-
- user.players.forEach((player) => {
- playerIds.push(player.id);
- });
-
- tickets = await SdtdTicket.find({
- player: playerIds
- });
-
- sails.log.debug(`API - SdtdServer:user-tickets-view - Success, loaded ${tickets.length} tickets`);
- return exits.success({
- user: user,
- tickets: tickets
- });
-
- } catch (error) {
- sails.log.error(`API - SdtdServer:user-tickets-view - ${error}`);
- return exits.error(error);
- }
-
-
- }
-
-
-};
-
- module.exports = {
-
-
- friendlyName: 'View a ticket',
-
-
- description: 'Loads relevant ticket data, and serves the view',
-
-
- inputs: {
- ticketId: {
- type: 'string',
- required: true
- }
- },
-
-
- exits: {
-
- notFound: {
- description: 'Ticket with given ID not found in the system',
- responseType: 'notFound'
- },
- success: {
- description: '',
- responseType: 'view',
- viewTemplatePath: 'sdtdTicket/ticket'
- }
-
- },
-
- /**
- * @memberof SdtdTicket
- * @name view-ticket
- * @method
- * @description Loads relevant ticket data, and serves the view
- * @param {string}ticketId
- */
-
-
- fn: async function (inputs, exits) {
-
- try {
- sails.log.debug(`API - SdtdTicket:viewTicket - Loading ticket view for ticket ${inputs.ticketId}`);
-
- let ticket = await SdtdTicket.findOne(inputs.ticketId);
- let server = await SdtdServer.findOne(ticket.server);
-
- return exits.success({
- server: server,
- ticket: ticket
- });
-
- } catch (error) {
- sails.log.error(`API - SdtdTicket:viewTicket - ${error}`);
- return exits.error(error);
- }
-
-
- }
-
-
-};
-
- module.exports = {
-
- friendlyName: 'Get user dashboard',
-
- description: 'Serves user dashboard view',
-
- inputs: {
- userId: {
- description: 'The ID of the user to look up.',
- type: 'number',
- required: true
- }
- },
-
- exits: {
- success: {
- responseType: 'view',
- viewTemplatePath: 'user/userDashboard'
- },
- notFound: {
- description: 'No user with the specified ID was found in the database.',
- responseType: 'notFound'
- }
- },
-
- /**
- * @memberof User
- * @name dashboard
- * @description Serves user dashboard view
- * @param {number} userId
- */
-
- fn: async function (inputs, exits) {
-
- try {
- let user = await User.findOne(inputs.userId).populate('servers');
- if (_.isUndefined(user)) {
- return exits.notFound()
- }
- let ownedServers = user.servers;
- let ownedServersWithInfo = new Array();
-
- for (const server of ownedServers) {
- let sdtdServerInfo = await sails.helpers.loadSdtdserverInfo(server.id);
- if (!_.isUndefined(sdtdServerInfo)) {
- ownedServersWithInfo.push(sdtdServerInfo)
- }
- }
-
- return exits.success({
- user: user,
- ownedServers: ownedServersWithInfo
- })
- } catch (error) {
- sails.log.warn(`VIEW - User:dashboard - ${error}`)
- return exits.error()
- }
- }
-};
-
- module.exports = {
-
-
- friendlyName: 'Find guilds managed by user',
-
-
- description: '',
-
-
- inputs: {
- userId: {
- required: true,
- example: '1337'
- }
-
- },
-
- exits: {
- badRequest: {
- responseType: 'badRequest'
- }
- },
-
- /**
- * @memberof SdtdServer
- * @method
- * @name find-guilds-managed-by-user
- * @param {number} userId
- * @returns {array}
- */
-
- fn: async function (inputs, exits) {
-
- try {
-
- let discordClient = sails.hooks.discordbot.getClient();
- let foundUser = await User.findOne(inputs.userId);
-
- if (_.isUndefined(foundUser) || "" == foundUser.discordId) {
- return exits.badRequest();
- }
-
- let discordUser = discordClient.users.get(foundUser.discordId);
-
- let foundGuilds = discordClient.guilds.filter(guild => {
- let member = guild.members.get(discordUser.id);
- if (_.isUndefined(member)) {
- return false;
- }
- return member.hasPermission("MANAGE_GUILD");
- })
-
- let foundGuildsArray = Array.from(foundGuilds.values());
-
- exits.success(foundGuildsArray);
- sails.log.debug(`API - SdtdServer:find-guilds-managed-by-user - Found ${foundGuildsArray.length} guilds for user ${inputs.userId}!`);
- } catch (error) {
- sails.log.error(`API - SdtdServer:find-guilds-managed-by-user - ${error}`);
- return exits.error(error);
- }
-
- }
-
-
- };
-
- module.exports = {
-
- friendlyName: 'Get owned servers',
-
- description: 'Get basic server info about servers the given user owns',
-
- inputs: {
- userId: {
- description: 'The ID of the user to look up.',
- type: 'number',
- required: true
- }
- },
-
- exits: {
- success: {},
- notFound: {
- description: 'No player with the specified ID was found in the database.',
- responseType: 'notFound'
- }
- },
-
- /**
- * @memberof User
- * @name getOwnedServers
- * @description gets servers this user is owner of
- * @param {number} userId
- */
-
- fn: async function (inputs, exits) {
- sails.log.debug(`API - User:getOwnedServers - Getting servers for user ${inputs.userId}`);
-
- try {
- let servers = await SdtdServer.find({owner: inputs.userId});
-
-
- return exits.success(servers);
-
- } catch (error) {
- sails.log.error(`API - SdtdServer:sendMessage - ${error}`);
- return exits.error(error);
- }
-
- }
-};
-
- module.exports = {
-
- friendlyName: 'Get user info',
-
- description: 'Get users profile info',
-
- inputs: {
- userId: {
- description: 'The ID of the user to look up.',
- type: 'number',
- required: true
- }
- },
-
- exits: {
- success: {},
- notFound: {
- description: 'No user with the specified ID was found in the database.',
- responseType: 'notFound'
- }
- },
-
- /**
- * @memberof User
- * @name get-user-info
- * @description gets servers this user is owner of
- * @param {number} userId
- */
-
- fn: async function (inputs, exits) {
- sails.log.debug(`API - User:get-user-info - Getting profile for user ${inputs.userId}`);
-
- try {
- let user = await User.findOne(inputs.userId)
- return exits.success(user);
-
- } catch (error) {
- sails.log.error(`API - SdtdServer:get-user-info - ${error}`);
- return exits.error(error);
- }
-
- }
-};
-
- module.exports = {
-
- friendlyName: 'Get user profile',
-
- description: 'Serves user profile view',
-
- inputs: {
- userId: {
- description: 'The ID of the user to look up.',
- type: 'number',
- required: true
- }
- },
-
- exits: {
- success: {
- responseType: 'view',
- viewTemplatePath: 'user/profile'
- },
- notFound: {
- description: 'No user with the specified ID was found in the database.',
- responseType: 'notFound'
- }
- },
-
- /**
- * @memberof User
- * @name profile
- * @description Serves user profile view
- * @param {number} userId
- */
-
- fn: async function (inputs, exits) {
- sails.log.debug(`API - User:profile - Getting profile for user ${inputs.userId}`);
-
- try {
- let user = await User.findOne(inputs.userId);
- let servers = await SdtdServer.find({ owner: inputs.userId });
- let players = await Player.find({ steamId: user.steamId });
-
- return exits.success({
- user: user,
- servers: servers,
- players: players
- })
-
- } catch (error) {
- sails.log.error(`API - SdtdServer:profile - ${error}`);
- return exits.error(error);
- }
-
- }
-};
-
- models/User.js
,
- line 33
- const sevenDays = require('machinepack-7daystodiewebapi');
-
-module.exports = {
-
- friendlyName: 'Add 7 Days to Die server',
-
-
- description: 'Add a 7 Days to Die server to the system (while verifying the input).',
-
-
- inputs: {
-
- serverName: {
- type: 'string',
- required: true
- },
- ip: {
- type: 'string',
- required: true
- },
- telnetPort: {
- type: 'number',
- required: true
- },
- telnetPassword: {
- type: 'string',
- required: true
- },
- webPort: {
- type: 'number',
- required: true
- },
- owner: {
- type: 'string',
- required: true
- },
- discordGuildId: {
- type: 'string',
- required: false
- }
-
- },
-
- exits: {
- badTelnet: {
- description: 'Could not connect to telnet'
- },
- badWebPort: {
- description: 'WebPort given was not valid'
- }
- },
-
- /**
- * @description Adds a 7 Days to die server to the system while verifying input
- * @name Add7dtdServer
- * @param {string} ip
- * @param {number} telnetPort
- * @param {string} telnetPassword
- * @param {number} webPort
- * @param {number} owner The ID of the owner
- * @param {number} discordGuildId
- * @memberof module:Helpers
- * @method
- */
-
- fn: async function (inputs, exits) {
-
- sails.log.debug(`HELPER - add7DtdServer - adding a server with ip: ${inputs.ip} webPort: ${inputs.webPort} owner: ${inputs.owner}`);
-
- try {
- let authInfo = await sails.helpers.createWebToken.with({
- ip: inputs.ip,
- port: inputs.telnetPort,
- password: inputs.telnetPassword
- }).tolerate('badTelnet',() => {
- return undefined
- })
-
- if (_.isUndefined(authInfo)) {
- return exits.badTelnet({error: 'badTelnet'});
- }
-
- await sevenDays.getStats({
- ip: inputs.ip,
- port: inputs.webPort,
- authName: authInfo.authName,
- authToken: authInfo.authToken
- }).exec({
- success: async response => {
- if (!response.gametime) {
- return exits.badWebPort({error: 'badWebPort'});
- } else {
- let server = await updateOrCreateServer(authInfo);
- await SdtdConfig.create({
- server: server.id
- });
- return exits.success(server);
- }
- },
- error: err => {
- return exits.error(err)
- }
- })
-
-
-
- } catch (error) {
- sails.log.error(`HELPER - add7DtdServer - ${error}`);
- if (error.message == 'badWebport') {
- return exits.badWebPort({error: 'badWebPort'});
- }
- return exits.error(error);
- }
-
-
- async function updateOrCreateServer(authInfo) {
- return new Promise(async (resolve, reject) => {
- let newServer = await SdtdServer.findOrCreate({
- ip: inputs.ip,
- webPort: inputs.webPort,
- authName: authInfo.authName,
- authToken: authInfo.authToken
- }, {
- name: inputs.serverName,
- ip: inputs.ip,
- webPort: inputs.webPort,
- telnetPort: inputs.telnetPort,
- authName: authInfo.authName,
- authToken: authInfo.authToken,
- owner: inputs.owner
- });
- sails.log.debug(`HELPER - add7DtdServer - success`);
- sails.hooks.sdtdlogs.start(newServer.id);
- resolve(newServer);
- });
-
-
- }
- }
-
-};
-
- const Telnet = require('telnet-client');
-const randToken = require('rand-token');
-
-/**
- * @module Helpers
- * @description Helper functions
- */
-
-module.exports = {
-
-
- friendlyName: 'Create web token',
-
-
- description: 'Connects to telnet, adds webtokens to the server and returns these',
-
-
- inputs: {
-
- ip: {
- type: 'string',
- description: 'IP address of server to connect to',
- required: true
- },
-
- port: {
- type: 'number',
- description: 'Telnet port',
- required: true
- },
-
- password: {
- type: 'string',
- description: 'Telnet password',
- required: true
- }
-
- },
-
-
- exits: {
- success: {
- outputFriendlyName: 'Connected and tokens added'
- },
- badTelnet: {
- description: 'Could not connect to telnet'
- }
- },
-
- /**
- * @description Executes webtokens add command on a server
- * @name createWebTokens
- * @memberof module:Helpers
- * @returns {json} Authname and token
- * @method
- * @param {string} ip
- * @param {number} port Telnet port
- * @param {string} password Telnet password
- */
-
- fn: async function(inputs, exits) {
- sails.log.debug(`HELPER - createWebTokens - creating tokens for server with ip ${inputs.ip}`);
- const authName = 'CSMM';
- const authToken = randToken.generate(32);
-
- let connection = new Telnet();
- let params = {
- host: inputs.ip,
- port: inputs.port,
- timeout: 3000,
- password: inputs.password,
- failedLoginMatch: 'Password incorrect',
- passwordPrompt: /Please enter password:/i,
- shellPrompt: /\r\n$/,
- };
- connection.connect(params);
-
- connection.on('ready', function(prompt) {
- connection.exec(`webtokens add ${authName} ${authToken} 0`, async function(err, response) {
- if (err) { return exits.error(err); }
- if (_.isUndefined(response) || response.length <= 0) {
- await connection.end();
- return exits.badTelnet(new Error('Did not receive a response from the server'));
- } else {
- sails.log.debug('HELPER - createWebTokens - successfully created tokens');
- await connection.end();
- return exits.success({ authName: authName, authToken: authToken });
- }
-
- });
- });
- }
-
-
-};
-
- var sevenDays = require('machinepack-7daystodiewebapi');
-
-module.exports = {
- friendlyName: 'Load player data',
- description: 'Load player information from a 7 Days to die server',
- inputs: {
- serverId: {
- type: 'number',
- required: true
- },
- steamId: {
- type: 'string'
- }
- },
- exits: {
- error: {
- friendlyName: 'error'
- },
- playerNotFound: {
- friendlyName: 'Player not found',
- description: 'ID was given, but no player found on the server'
- }
- },
-
- /**
- * @description Loads player information and saves it to database
- * @name loadPlayerData
- * @param {number} serverId
- * @memberof module:Helpers
- * @method
- */
-
- fn: async function (inputs, exits) {
- sails.log.verbose(`HELPER - loadPlayerData - Loading player data for server ${inputs.serverId} -- steamId: ${inputs.steamId}`);
-
- try {
- let server = await SdtdServer.findOne(inputs.serverId);
- let playerList = await getPlayerList(server);
- if (playerList.players) {
- let playerListWithInventories = await loadPlayersInventory(playerList.players, server);
- let newPlayerList = await playerListWithInventories.map(await updatePlayerInfo);
-
- if (inputs.steamId) {
- await loadPlayerProfilePicture(inputs.steamId);
- }
- let jsonToSend = await createJSON(newPlayerList);
- exits.success(jsonToSend);
- } else {
- let jsonToSend = await createJSON(playerList);
- exits.success(jsonToSend);
- }
-
-
- } catch (error) {
- sails.log.error(`HELPER - loadPlayerData - ${error}`);
- exits.error(error);
- }
-
- async function loadPlayersInventory(playerList, server) {
- return new Promise((resolve, reject) => {
- let listWithInventories = playerList.map(function (player) {
- return new Promise((resolve, reject) => {
- sevenDays.getPlayerInventory({
- ip: server.ip,
- port: server.webPort,
- authName: server.authName,
- authToken: server.authToken,
- steamId: player.steamid
- }).exec({
- error: function (err) {
- sails.log.warn(err);
- resolve(player);
- },
- success: function (data) {
- player.inventory = new Object();
- player.inventory.bag = data.bag;
- player.inventory.belt = data.belt;
- player.inventory.equipment = data.equipment;
- resolve(player);
- }
- });
- });
- });
- resolve(listWithInventories);
- });
- }
-
- async function updatePlayerInfo(newPlayer) {
- return new Promise(async function (resolve, reject) {
- try {
- newPlayer.then(async function (newPlayer) {
- if (newPlayer.name === '') {
- newPlayer.name = 'Unknown name';
- }
- foundOrCreatedPlayer = await Player.findOrCreate({
- steamId: newPlayer.steamid,
- server: inputs.serverId,
- entityId: newPlayer.entityid
- }, {
- steamId: newPlayer.steamid,
- server: inputs.serverId,
- entityId: newPlayer.entityid,
- name: newPlayer.name,
- ip: newPlayer.ip,
- });
- if (newPlayer.online) {
- playerToSend = await Player.update({
- steamId: foundOrCreatedPlayer.steamId,
- server: inputs.serverId,
- entityId: foundOrCreatedPlayer.entityId
- }).set({
- ip: newPlayer.ip,
- positionX: newPlayer.position.x,
- positionY: newPlayer.position.y,
- positionZ: newPlayer.position.z,
- playtime: newPlayer.totalplaytime,
- inventory: newPlayer.inventory,
- banned: newPlayer.banned,
- }).fetch();
- } else {
- playerToSend = await Player.update({
- steamId: foundOrCreatedPlayer.steamId,
- server: inputs.serverId,
- entityId: foundOrCreatedPlayer.entityId
- }).set({
- ip: newPlayer.ip,
- positionX: newPlayer.position.x,
- positionY: newPlayer.position.y,
- positionZ: newPlayer.position.z,
- playtime: newPlayer.totalplaytime,
- banned: newPlayer.banned,
- }).fetch();
- }
-
- playerToSend = playerToSend[0];
- playerToSend.online = newPlayer.online;
- resolve(playerToSend);
- });
- } catch (error) {
- sails.log.warn(error);
- resolve(foundOrCreatedPlayer)
- }
-
- });
- }
-
- async function getPlayerList(server) {
- return new Promise((resolve, reject) => {
- sevenDays.getPlayerList({
- ip: server.ip,
- port: server.webPort,
- authName: server.authName,
- authToken: server.authToken
- }).exec({
- error: function (err) {
- sails.log.warn(err);
- resolve({
- players: []
- });
- },
- success: function (playerList) {
- // If a steam ID is provided, we filter the list to only 1 player
- if (inputs.steamId) {
- let playerToFind;
- playerList.players.forEach(player => {
- if (player.steamid === inputs.steamId) {
- playerToFind = player;
- }
- });
- if (_.isUndefined(playerToFind)) {
- return exits.playerNotFound();
- }
- playerList.players = new Array(playerToFind);
- }
- resolve(playerList);
- }
- });
- });
- }
-
-
- async function createJSON(playerList) {
- return new Promise(function (resolve) {
- try {
- let toSend = {};
- Promise.all(playerList).then(resolvedPlayers => {
- toSend.totalPlayers = playerList.length;
- toSend.players = new Array();
- resolvedPlayers.forEach(function (player) {
- let playerData = new Object();
- playerData.id = player.id;
- playerData.online = player.online;
- playerData.steamId = player.steamId;
- playerData.entityId = player.entityId;
- playerData.location = new Object();
- playerData.location.x = player.positionX;
- playerData.location.y = player.positionY;
- playerData.location.z = player.positionZ;
- playerData.inventory = player.inventory;
- playerData.totalPlaytime = player.playtime;
- playerData.banned = player.banned;
- playerData.server = player.server;
- playerData.name = player.name;
- toSend.players.push(playerData);
- });
- resolve(toSend);
- });
- } catch (error) {
- throw error;
- }
- });
- }
-
- async function loadPlayerProfilePicture(steamId) {
- let request = require('request-promise-native');
- return new Promise((resolve, reject) => {
- request({
- uri: 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002',
- qs: {
- steamids: steamId,
- key: process.env.API_KEY_STEAM,
- },
- json: true
- }).then(async (response) => {
- try {
- if (!_.isUndefined(response.response) || !_.isUndefined(response.response.players)) {
- let avatarUrl = response.response.players[0].avatarfull;
- let updatedPlayer = await Player.update({
- steamId: steamId
- }, {
- avatarUrl: avatarUrl
- });
- resolve(avatarUrl);
- } else {
- let avatarUrl = 'https://i.imgur.com/NMvWd07.png';
- let updatedPlayer = await Player.update({
- steamId: steamId
- }, {
- avatarUrl: avatarUrl
- });
- resolve(avatarUrl);
- }
- } catch (error) {
- sails.log.error(`HELPER - loadPlayerData:loadPlayerProfilePicture - ${error}`);
- }
- }).catch(async (error) => {
- let avatarUrl = 'https://i.imgur.com/NMvWd07.png';
- let updatedPlayer = await Player.update({
- steamId: steamId
- }, {
- avatarUrl: avatarUrl
- });
- resolve(avatarUrl);
- });
- });
- }
-
-
- },
-};
-
- var sevenDays = require('machinepack-7daystodiewebapi');
-
-module.exports = {
-
-
- friendlyName: 'Load sdtdServer info',
-
-
- description: 'Performs several API requests to a sdtd server',
-
-
- inputs: {
- serverId: {
- friendlyName: 'Server ID',
- required: true,
- example: 1
- }
- },
-
-
- exits: {
- success: {
- outputFriendlyName: 'Success'
- },
- connectionError: {
- description: 'Could not connect to the 7 days to die server'
- },
- databaseError: {
- description: 'Error reading or writing data to DB'
- }
- },
-
- /**
- * @description Loads server information
- * @name loadSdtdServerInfo
- * @param {number} serverId
- * @memberof module:Helpers
- * @method
- */
-
-
- fn: async function (inputs, exits) {
-
- try {
- sails.log.debug(`HELPER - loadSdtdserverInfo - Loading server info for server ${inputs.serverId}`);
- // Load serverinfo from DB first
- let server = await SdtdServer.findOne(inputs.serverId);
- server.stats = await loadStats(server);
- server.serverInfo = await loadServerInfo(server);
- exits.success(server);
- } catch (error) {
- sails.log.warn(`HELPER - load-sdtdServer-info - Failed to load info ${error}`)
- return exits.error(error);
- }
-
-
- function loadStats(server) {
- return new Promise((resolve, reject) => {
- sevenDays.getStats({
- ip: server.ip,
- port: server.webPort,
- authName: server.authName,
- authToken: server.authToken
- }).exec({
- error: error => {
- sails.log.warn(error);
- resolve(undefined);
- },
- success: data => {
- resolve(data);
- }
- });
- });
- }
-
- function loadServerInfo(server) {
- return new Promise((resolve, reject) => {
- sevenDays.getServerInfo({
- ip: server.ip,
- port: server.webPort,
- authName: server.authName,
- authToken: server.authToken
- }).exec({
- error: error => {
- sails.log.warn(error);
- resolve(undefined);
- },
- success: data => {
- for (const dataPoint in data) {
- if (data.hasOwnProperty(dataPoint)) {
- data[dataPoint] = data[dataPoint].value;
- }
- }
- resolve(data);
- }
- });
- });
- }
-
-
- }
-
-
-};
-
- var sevenDays = require('machinepack-7daystodiewebapi');
-
-module.exports = {
-
-
- friendlyName: 'Check if available',
-
-
- description: 'Checks if a server can be reached via the web API',
-
-
- inputs: {
-
- serverId: {
- type: 'number',
- description: 'Id of the server',
- required: true
- }
-
- },
-
-
- exits: {
- success: {
- outputFriendlyName: 'Success',
- outputType: 'boolean'
- },
- notAvailable: {
- outputFriendlyName: 'Not available',
- description: 'The server could not be reached'
- }
- },
-
- /**
- * @description Checks if a server can be reached via the web API
- * @name checkIfAvailable
- * @memberof module:Helpers
- * @returns {boolean}
- * @method
- * @param {number} serverId
- */
-
- fn: async function (inputs, exits) {
- try {
- let sdtdServer = await SdtdServer.findOne({
- id: inputs.serverId
- });
- let statsResponse = await checkStats(sdtdServer);
- let commandResponse = await checkCommand(sdtdServer);
-
- if (statsResponse && commandResponse) {
- return exits.success(true);
- } else {
- sails.log.debug(`HELPER - checkIfAvailable - Server ${inputs.serverId} is not available`);
- return exits.notAvailable();
- }
-
- } catch (error) {
- return exits.error(error);
- }
-
-
- async function checkStats(sdtdServer) {
- return new Promise(resolve => {
- let statsResponse = sevenDays.getStats({
- ip: sdtdServer.ip,
- port: sdtdServer.webPort,
- authName: sdtdServer.authName,
- authToken: sdtdServer.authToken
- }).exec({
- success: (response) => {
- if (response.gametime && response.players) {
- resolve(true);
- } else {
- resolve(false)
- }
- },
- error: (error) => {
- resolve(false);
- }
- });
- });
- }
-
- async function checkCommand(sdtdServer) {
- return new Promise(resolve => {
- let statsResponse = sevenDays.executeCommand({
- ip: sdtdServer.ip,
- port: sdtdServer.webPort,
- authName: sdtdServer.authName,
- authToken: sdtdServer.authToken,
- command: 'mem'
- }).exec({
- success: (response) => {
- resolve(true);
- },
- error: (error) => {
- resolve(false);
- }
- });
- });
- }
-
-
- }
-
-
-};
-
- var sevenDays = require('machinepack-7daystodiewebapi');
-
-module.exports = {
-
-
- friendlyName: 'Create support ticket',
-
-
- description: 'Creates a support ticket, with relevant data',
-
-
- inputs: {
-
- serverId: {
- type: 'number',
- description: 'Id of the server',
- required: true
- },
-
- playerId: {
- type: 'number',
- description: 'Id of the player creating the ticket',
- required: true
- },
-
- title: {
- type: 'string',
- description: 'Title of the ticket',
- required: true
- },
-
- description: {
- type: 'string',
- description: 'Description of the ticket'
- }
-
- },
-
-
- exits: {
- success: {
- outputFriendlyName: 'Success',
- outputType: 'json'
- },
-
- notAvailable: {
- outputFriendlyName: 'Not available',
- description: 'The server could not be reached'
- }
- },
-
- /**
- * @description Creates a SdtdTicket
- * @name createTicket
- * @memberof module:Helpers
- * @returns {json} SdtdTicket
- * @method
- * @param {number} serverId
- * @param {number} playerId
- * @param {string} title
- * @param {string} description
- */
-
- fn: async function (inputs, exits) {
- sails.log.debug(`HELPER - createTicket - Creating a ticket for server ${inputs.serverId} by player ${inputs.playerId}`);
-
- try {
- let sdtdServer = await SdtdServer.findOne({
- id: inputs.serverId
- });
- let player = await Player.findOne(inputs.playerId);
- let playerInfo = await sails.helpers.loadPlayerData(inputs.serverId, player.steamId);
-
- if (_.isUndefined(sdtdServer) || _.isUndefined(player)) {
- return exits.error(new Error(`HELPER - createTicket - Invalid server or player ID`));
- }
-
- let ticket = await SdtdTicket.create({
- description: inputs.description,
- title: inputs.title,
- playerInfo: playerInfo.players[0],
- server: inputs.serverId,
- player: inputs.playerId
- }).fetch();
-
- let notificationMsg = `New Ticket by ${player.name}\n${ticket.title}\n${ticket.description}`;
-
- sails.hooks.discordbot.sendNotification(inputs.serverId, notificationMsg);
-
- return exits.success(ticket);
-
- } catch (error) {
- sails.log.error(`HELPER - createTicket - ${error}`);
- return exits.error(error);
- }
-
-
-
-
-
- }
-
-
-};
-
- var sevenDays = require('machinepack-7daystodiewebapi');
-
-/**
- * @module 7dtdCountryBan
- * @description Restrict certain countries access to a server
- */
-module.exports = function sdtdCountryBan(sails) {
-
- let countryBanInfoMap = new Map();
-
- return {
-
- config: {
- enabled: true,
- bannedCountries: [],
- kickMessage: 'Your country has been blocked on this server.',
- allowNull: true
- },
-
- countryList: [
- ['A1', 'Anonymous Proxy'],
- ['A2', 'Satellite Provider'],
- ['O1', 'Other Country'],
- ['AD', 'Andorra'],
- ['AE', 'United Arab Emirates'],
- ['AF', 'Afghanistan'],
- ['AG', 'Antigua and Barbuda'],
- ['AI', 'Anguilla'],
- ['AL', 'Albania'],
- ['AM', 'Armenia'],
- ['AO', 'Angola'],
- ['AP', 'Asia/Pacific Region'],
- ['AQ', 'Antarctica'],
- ['AR', 'Argentina'],
- ['AS', 'American Samoa'],
- ['AT', 'Austria'],
- ['AU', 'Australia'],
- ['AW', 'Aruba'],
- ['AX', 'Aland Islands'],
- ['AZ', 'Azerbaijan'],
- ['BA', 'Bosnia and Herzegovina'],
- ['BB', 'Barbados'],
- ['BD', 'Bangladesh'],
- ['BE', 'Belgium'],
- ['BF', 'Burkina Faso'],
- ['BG', 'Bulgaria'],
- ['BH', 'Bahrain'],
- ['BI', 'Burundi'],
- ['BJ', 'Benin'],
- ['BL', 'Saint Bartelemey'],
- ['BM', 'Bermuda'],
- ['BN', 'Brunei Darussalam'],
- ['BO', 'Bolivia'],
- ['BQ', 'Bonaire, Saint Eustatius and Saba'],
- ['BR', 'Brazil'],
- ['BS', 'Bahamas'],
- ['BT', 'Bhutan'],
- ['BV', 'Bouvet Island'],
- ['BW', 'Botswana'],
- ['BY', 'Belarus'],
- ['BZ', 'Belize'],
- ['CA', 'Canada'],
- ['CC', 'Cocos (Keeling) Islands'],
- ['CD', 'Congo, The Democratic Republic of the'],
- ['CF', 'Central African Republic'],
- ['CG', 'Congo'],
- ['CH', 'Switzerland'],
- ['CI', 'Cote d\'Ivoire'],
- ['CK', 'Cook Islands'],
- ['CL', 'Chile'],
- ['CM', 'Cameroon'],
- ['CN', 'China'],
- ['CO', 'Colombia'],
- ['CR', 'Costa Rica'],
- ['CU', 'Cuba'],
- ['CV', 'Cape Verde'],
- ['CW', 'Curacao'],
- ['CX', 'Christmas Island'],
- ['CY', 'Cyprus'],
- ['CZ', 'Czech Republic'],
- ['DE', 'Germany'],
- ['DJ', 'Djibouti'],
- ['DK', 'Denmark'],
- ['DM', 'Dominica'],
- ['DO', 'Dominican Republic'],
- ['DZ', 'Algeria'],
- ['EC', 'Ecuador'],
- ['EE', 'Estonia'],
- ['EG', 'Egypt'],
- ['EH', 'Western Sahara'],
- ['ER', 'Eritrea'],
- ['ES', 'Spain'],
- ['ET', 'Ethiopia'],
- ['EU', 'Europe'],
- ['FI', 'Finland'],
- ['FJ', 'Fiji'],
- ['FK', 'Falkland Islands (Malvinas)'],
- ['FM', 'Micronesia, Federated States of'],
- ['FO', 'Faroe Islands'],
- ['FR', 'France'],
- ['GA', 'Gabon'],
- ['GB', 'United Kingdom'],
- ['GD', 'Grenada'],
- ['GE', 'Georgia'],
- ['GF', 'French Guiana'],
- ['GG', 'Guernsey'],
- ['GH', 'Ghana'],
- ['GI', 'Gibraltar'],
- ['GL', 'Greenland'],
- ['GM', 'Gambia'],
- ['GN', 'Guinea'],
- ['GP', 'Guadeloupe'],
- ['GQ', 'Equatorial Guinea'],
- ['GR', 'Greece'],
- ['GS', 'South Georgia and the South Sandwich Islands'],
- ['GT', 'Guatemala'],
- ['GU', 'Guam'],
- ['GW', 'Guinea-Bissau'],
- ['GY', 'Guyana'],
- ['HK', 'Hong Kong'],
- ['HM', 'Heard Island and McDonald Islands'],
- ['HN', 'Honduras'],
- ['HR', 'Croatia'],
- ['HT', 'Haiti'],
- ['HU', 'Hungary'],
- ['ID', 'Indonesia'],
- ['IE', 'Ireland'],
- ['IL', 'Israel'],
- ['IM', 'Isle of Man'],
- ['IN', 'India'],
- ['IO', 'British Indian Ocean Territory'],
- ['IQ', 'Iraq'],
- ['IR', 'Iran, Islamic Republic of'],
- ['IS', 'Iceland'],
- ['IT', 'Italy'],
- ['JE', 'Jersey'],
- ['JM', 'Jamaica'],
- ['JO', 'Jordan'],
- ['JP', 'Japan'],
- ['KE', 'Kenya'],
- ['KG', 'Kyrgyzstan'],
- ['KH', 'Cambodia'],
- ['KI', 'Kiribati'],
- ['KM', 'Comoros'],
- ['KN', 'Saint Kitts and Nevis'],
- ['KP', 'Korea, Democratic People\'s Republic of'],
- ['KR', 'Korea, Republic of'],
- ['KW', 'Kuwait'],
- ['KY', 'Cayman Islands'],
- ['KZ', 'Kazakhstan'],
- ['LA', 'Lao People\'s Democratic Republic'],
- ['LB', 'Lebanon'],
- ['LC', 'Saint Lucia'],
- ['LI', 'Liechtenstein'],
- ['LK', 'Sri Lanka'],
- ['LR', 'Liberia'],
- ['LS', 'Lesotho'],
- ['LT', 'Lithuania'],
- ['LU', 'Luxembourg'],
- ['LV', 'Latvia'],
- ['LY', 'Libyan Arab Jamahiriya'],
- ['MA', 'Morocco'],
- ['MC', 'Monaco'],
- ['MD', 'Moldova, Republic of'],
- ['ME', 'Montenegro'],
- ['MF', 'Saint Martin'],
- ['MG', 'Madagascar'],
- ['MH', 'Marshall Islands'],
- ['MK', 'Macedonia'],
- ['ML', 'Mali'],
- ['MM', 'Myanmar'],
- ['MN', 'Mongolia'],
- ['MO', 'Macao'],
- ['MP', 'Northern Mariana Islands'],
- ['MQ', 'Martinique'],
- ['MR', 'Mauritania'],
- ['MS', 'Montserrat'],
- ['MT', 'Malta'],
- ['MU', 'Mauritius'],
- ['MV', 'Maldives'],
- ['MW', 'Malawi'],
- ['MX', 'Mexico'],
- ['MY', 'Malaysia'],
- ['MZ', 'Mozambique'],
- ['NA', 'Namibia'],
- ['NC', 'New Caledonia'],
- ['NE', 'Niger'],
- ['NF', 'Norfolk Island'],
- ['NG', 'Nigeria'],
- ['NI', 'Nicaragua'],
- ['NL', 'Netherlands'],
- ['NO', 'Norway'],
- ['NP', 'Nepal'],
- ['NR', 'Nauru'],
- ['NU', 'Niue'],
- ['NZ', 'New Zealand'],
- ['OM', 'Oman'],
- ['PA', 'Panama'],
- ['PE', 'Peru'],
- ['PF', 'French Polynesia'],
- ['PG', 'Papua New Guinea'],
- ['PH', 'Philippines'],
- ['PK', 'Pakistan'],
- ['PL', 'Poland'],
- ['PM', 'Saint Pierre and Miquelon'],
- ['PN', 'Pitcairn'],
- ['PR', 'Puerto Rico'],
- ['PS', 'Palestinian Territory'],
- ['PT', 'Portugal'],
- ['PW', 'Palau'],
- ['PY', 'Paraguay'],
- ['QA', 'Qatar'],
- ['RE', 'Reunion'],
- ['RO', 'Romania'],
- ['RS', 'Serbia'],
- ['RU', 'Russian Federation'],
- ['RW', 'Rwanda'],
- ['SA', 'Saudi Arabia'],
- ['SB', 'Solomon Islands'],
- ['SC', 'Seychelles'],
- ['SD', 'Sudan'],
- ['SE', 'Sweden'],
- ['SG', 'Singapore'],
- ['SH', 'Saint Helena'],
- ['SI', 'Slovenia'],
- ['SJ', 'Svalbard and Jan Mayen'],
- ['SK', 'Slovakia'],
- ['SL', 'Sierra Leone'],
- ['SM', 'San Marino'],
- ['SN', 'Senegal'],
- ['SO', 'Somalia'],
- ['SR', 'Suriname'],
- ['SS', 'South Sudan'],
- ['ST', 'Sao Tome and Principe'],
- ['SV', 'El Salvador'],
- ['SX', 'Sint Maarten'],
- ['SY', 'Syrian Arab Republic'],
- ['SZ', 'Swaziland'],
- ['TC', 'Turks and Caicos Islands'],
- ['TD', 'Chad'],
- ['TF', 'French Southern Territories'],
- ['TG', 'Togo'],
- ['TH', 'Thailand'],
- ['TJ', 'Tajikistan'],
- ['TK', 'Tokelau'],
- ['TL', 'Timor-Leste'],
- ['TM', 'Turkmenistan'],
- ['TN', 'Tunisia'],
- ['TO', 'Tonga'],
- ['TR', 'Turkey'],
- ['TT', 'Trinidad and Tobago'],
- ['TV', 'Tuvalu'],
- ['TW', 'Taiwan'],
- ['TZ', 'Tanzania, United Republic of'],
- ['UA', 'Ukraine'],
- ['UG', 'Uganda'],
- ['UM', 'United States Minor Outlying Islands'],
- ['US', 'United States'],
- ['UY', 'Uruguay'],
- ['UZ', 'Uzbekistan'],
- ['VA', 'Holy See (Vatican City State)'],
- ['VC', 'Saint Vincent and the Grenadines'],
- ['VE', 'Venezuela'],
- ['VG', 'Virgin Islands, British'],
- ['VI', 'Virgin Islands, U.S.'],
- ['VN', 'Vietnam'],
- ['VU', 'Vanuatu'],
- ['WF', 'Wallis and Futuna'],
- ['WS', 'Samoa'],
- ['YE', 'Yemen'],
- ['YT', 'Mayotte'],
- ['ZA', 'South Africa'],
- ['ZM', 'Zambia'],
- ['ZW', 'Zimbabwe']
- ],
-
- initialize: function (cb) {
- sails.on('hook:orm:loaded', function () {
- sails.on('hook:sdtdlogs:loaded', async function () {
- try {
- let configs = await SdtdConfig.find();
-
- for (const config of configs) {
- if (config.countryBanConfig.enabled) {
- await startCountryBan(config.server);
- }
- }
-
- sails.log.info(`HOOK: countryBan - Initialized ${countryBanInfoMap.size} country ban instances`);
- return cb();
- } catch (error) {
- sails.log.error(`HOOK:countryBan ${error}`);
- }
-
-
- });
- });
- },
-
- /**
- * @name start
- * @memberof module:7dtdCountryBan
- * @description Starts countryBan for a server
- * @param {number} serverId - Id of the server
- * @method
- */
-
- start: async function start(serverId) {
- sails.log.debug(`HOOK:countryBan Starting countryBan for server ${serverId}`);
- startCountryBan(serverId);
- },
-
- /**
- * @name stop
- * @memberof module:7dtdCountryBan
- * @description Stops countryBan for a server
- * @param {number} serverId - Id of the server
- * @method
- */
-
- stop: async function (serverId) {
- sails.log.debug(`HOOK:countryBan Stopping countryBan for server ${serverId} `);
-
- let loggingObj = sails.hooks.sdtdlogs.getLoggingObject(serverId);
-
- let currentConfig = countryBanInfoMap.get(String(serverId));
-
- if (_.isUndefined(currentConfig)) {
- return;
- }
-
- currentConfig.enabled = false;
- await SdtdConfig.update({
- server: serverId
- }, {
- countryBanConfig: currentConfig
- });
-
- if (_.isUndefined(loggingObj)) {
- throw new Error('Could not find logging object for server');
- }
- loggingObj.removeListener('playerConnected', handleCountryBan);
-
- countryBanInfoMap.delete(String(serverId));
- },
-
- /**
- * @name getStatus
- * @memberof module:7dtdCountryBan
- * @description Gets the country ban status/config for a server
- * @param {number} serverId - Id of the server
- * @method
- */
-
- getStatus: function (serverId) {
- sails.log.debug(`HOOK:countryBan Getting countryBan status for server ${serverId} `);
- return countryBanInfoMap.get(String(serverId));
- },
-
- getAmount: function() {
- return countryBanInfoMap.size;
- },
-
- /**
- * @name reload
- * @memberof module:7dtdCountryBan
- * @description Changes banned countries config for a server
- * @param {number} serverId - Id of the server
- * @method
- */
-
- reload: async function (serverId, newConfig) {
-
- try {
- sails.log.debug(`HOOK:countryBan Reloading country ban for server ${serverId} `);
-
- let config = await SdtdConfig.findOne({
- server: serverId
- });
-
- if (_.isUndefined(config)) {
- throw new Error('Could not find server config with specified ID');
- }
-
- if (_.isUndefined(newConfig)) {
- newConfig = config.countryBanConfig;
- }
-
-
- let updatedServer = await SdtdConfig.update({
- server: serverId
- }, {
- countryBanConfig: newConfig
- }).fetch();
- countryBanInfoMap.set(String(serverId), newConfig);
-
- await this.stop(serverId);
- return await this.start(serverId);
- } catch (error) {
- sails.log.error(`HOOK:countryBan ${error}`);
- }
-
- }
- };
-
- async function handleCountryBan(connectedMessage) {
- let country = connectedMessage.country;
- let steamId = connectedMessage.steamID;
- let serverIp = this.serverIp;
- let serverWebPort = this.port;
- try {
- let server = await SdtdServer.find({
- ip: serverIp,
- webPort: serverWebPort
- }).limit(1);
- server = server[0]
-
- let config = await SdtdConfig.find({
- server: server.id
- });
- sails.log.debug(`HOOK:countryBan - Player from ${country} connected to server ${server.id}, checking if needs to be kicked`);
-
- let countryBanConfig = config[0].countryBanConfig;
- if (countryBanConfig.bannedCountries.includes(country) && !countryBanConfig.whiteListedSteamIds.includes(steamId)) {
- sevenDays.kickPlayer({
- ip: server.ip,
- port: server.webPort,
- authName: server.authName,
- authToken: server.authToken,
- reason: `${countryBanConfig.kickMessage}`,
- playerId: connectedMessage.steamID
- }).exec({
- error: (error) => {
- sails.log.warn(`HOOK:countryBan - Failed to kick player from server ${server.id} - ${error}`);
- },
- success: () => {
- sails.log.debug(`HOOK:countryBan - Kicked player ${connectedMessage.playerName} from server ${server.id}`);
- }
- });
- }
-
- } catch (error) {
- sails.log.error(`HOOK:countryBan failed to handle player connnect ${error}`);
- }
- }
-
-
- async function startCountryBan(serverId) {
- try {
- let server = await SdtdServer.findOne(serverId);
- let config = await SdtdConfig.findOne({
- server: serverId
- });
-
- currentConfig = config.countryBanConfig;
- currentConfig.enabled = true;
-
- await SdtdConfig.update({
- server: serverId
- }, {
- countryBanConfig: currentConfig
- });
-
- let loggingObj = sails.hooks.sdtdlogs.getLoggingObject(serverId);
- if (_.isUndefined(loggingObj)) {
- return sails.log.error('Could not find logging object for server');
- }
-
- loggingObj.on('playerConnected', handleCountryBan);
-
- return countryBanInfoMap.set(String(serverId), currentConfig);
- } catch (error) {
- sails.log.error(`HOOK:countryBan ${error}`);
- throw error;
- }
- }
-};
-
- const Commando = require('discord.js-commando');
-const path = require('path');
-
-/**
- * @module DiscordBot
- * @description a Sails project hook. Integrates a discord bot to the system
- * @param {*} sails Global sails instance
- */
-
-/**
- * @module DiscordCommands
- * @description Command guide for users
- */
-
-module.exports = function discordBot(sails) {
-
- return {
-
- /**
- * @memberof module:DiscordBot
- * @method
- * @name initialize
- * @description Starts the discord bot & logs in
- */
- initialize: function (cb) {
- sails.on('hook:orm:loaded', function () {
- sails.on('hook:sdtdlogs:loaded', function () {
- client = new Commando.Client({
- owner: sails.config.custom.botOwners
- });
-
- sails.discordBotClient = client;
-
- // Register custom embed messages
-
- client.customEmbed = require('./util/createEmbed').CustomEmbed;
- client.errorEmbed = require('./util/createEmbed').ErrorEmbed;
-
- // Register some stuff in the registry... yeah..
- client.registry
- .registerGroups([
- ['7dtd', '7 Days to die'],
- ['meta', 'Commands about the system']
- ])
- .registerDefaults()
- .registerCommandsIn(path.join(__dirname, 'commands'));
-
- // Listeners
-
- client.on('commandError', (command, error) => {
- sails.log.error(`Command error! ${command.memberName} trace: ${error.stack}`);
- });
-
- client.on('commandRun', (command, promise, message) => {
- sails.log.info(`Command ${command.name} ran by ${message.author.username}`);
- });
-
- // Login
-
- client.login(sails.config.custom.botToken).then(() => {
- sails.log.info(`Discord bot logged in - ${client.guilds.size} guilds`);
- return cb();
- })
- .catch((err) => {
- sails.log.error(err);
- });
- });
- });
- },
-
- /**
- * @memberof module:DiscordBot
- * @method
- * @name getClient
- * @description returns the discord client
- */
-
- getClient: function () {
- return sails.discordBotClient;
- },
-
- /**
- * @memberof module:DiscordBot
- * @method
- * @name sendNotification
- * @description Sends a notification to servers notification channel
- * @param {string} serverId
- * @param {string} message
- */
-
- sendNotification: async function (serverId, message) {
- try {
- let server = await SdtdServer.find({id: serverId}).limit(1);
- let config = await SdtdConfig.find({id: server.config}).limit(1);
- server = server[0];
- config = config[0];
-
- if (config.notificationChannelId) {
- let notificationChannel = sails.discordBotClient.channels.get(config.notificationChannelId);
- let embed = new client.customEmbed()
- embed.setDescription(message);
- await notificationChannel.send(embed);
- }
-
- } catch (error) {
- sails.log.error(`HOOK - discordBot:sendNotification - ${error}`);
- }
- }
- };
-
-};
-
- const Discord = require('discord.js');
-
-/**
- * @class
- * @name CustomDiscordEmbed
- * @description Creates a RichEmbed & loads basic data relevant to this project.
- * [Discord.js MessageEmbed]{@link https://discord.js.org/#/docs/main/master/class/MessageEmbed}
- */
-
-class CustomEmbed extends Discord.MessageEmbed {
- constructor(data) {
- super();
- this.setTimestamp();
- this.setTitle(sails.config.custom.botEmbedTitle);
- this.setURL(sails.config.custom.botEmbedLink);
- }
-}
-
-class ErrorEmbed extends CustomEmbed {
- constructor(errorMsg) {
- super();
- this.setDescription(`An error occured! See below for more info \n ${errorMsg}`);
- this.setColor('RED');
- }
-}
-
-module.exports.CustomEmbed = CustomEmbed;
-module.exports.ErrorEmbed = ErrorEmbed;
-
- const Discord = require('discord.js');
-const sevenDays = require('machinepack-7daystodiewebapi');
-const hhmmss = require('@streammedev/hhmmss')
-
-
-/**
- * @class
- * @name ChatBridgeChannel
- * @description Discord chat bridge
- */
-
-class ChatBridgeChannel {
- constructor(textChannel, sdtdServer) {
- this.channelId = textChannel.id;
- this.channel = textChannel;
- this.sdtdServer = sdtdServer;
- this.config;
- this.loggingObject = sails.hooks.sdtdlogs.getLoggingObject(this.sdtdServer.id);
- this.start()
- }
-
- async start() {
-
- try {
- this.config = await SdtdConfig.find({
- server: this.sdtdServer.id
- }).limit(1);
- this.config = this.config[0];
- // Bind 'this' to sendMessage functions
- this.sendChatMessageToDiscord = this.sendChatMessageToDiscord.bind(this);
- this.sendConnectedMessageToDiscord = this.sendConnectedMessageToDiscord.bind(this);
- this.sendRichConnectedMessageToDiscord = this.sendRichConnectedMessageToDiscord.bind(this);
- this.sendDeathMessageToDiscord = this.sendDeathMessageToDiscord.bind(this);
- this.sendDisconnectedMessageToDiscord = this.sendDisconnectedMessageToDiscord.bind(this);
- this.sendRichDisconnectedMessageToDiscord = this.sendRichDisconnectedMessageToDiscord.bind(this);
- this.sendMessageToGame = this.sendMessageToGame.bind(this)
-
- if (!_.isUndefined(this.loggingObject) && this.config.chatChannelId) {
-
- if (this.config.chatChannelRichMessages) {
- this.loggingObject.on('playerConnected', this.sendRichConnectedMessageToDiscord);
- this.loggingObject.on('playerDisconnected', this.sendRichDisconnectedMessageToDiscord);
- } else {
- this.loggingObject.on('playerConnected', this.sendConnectedMessageToDiscord);
- this.loggingObject.on('playerDisconnected', this.sendDisconnectedMessageToDiscord);
- }
-
- this.loggingObject.on('chatMessage', this.sendChatMessageToDiscord);
- this.loggingObject.on('playerDeath', this.sendDeathMessageToDiscord);
-
- this.channel.client.on('message', this.sendMessageToGame);
- let embed = new this.channel.client.customEmbed();
- embed.setDescription(':white_check_mark: Initialized a chat bridge')
- .addField(`Rich messages`, this.config.chatChannelRichMessages ? ':white_check_mark:' : ':x:')
- this.channel.send(embed);
- } else {
- this.channel.send(new this.channel.client.errorEmbed(':x: Could not find a logging object for this server'));
- }
- } catch (error) {
- sails.log.error(`HOOK discordChatBridge:chatBridgeChannel:start - ${error}`)
- }
-
- }
-
- stop() {
- let embed = new this.channel.client.customEmbed();
- if (this.loggingObject) {
- this.loggingObject.removeListener('chatMessage', this.sendChatMessageToDiscord);
- this.loggingObject.removeListener('playerDeath', this.sendDeathMessageToDiscord);
- this.loggingObject.removeListener('playerConnected', this.sendConnectedMessageToDiscord);
- this.loggingObject.removeListener('playerDisconnected', this.sendDisconnectedMessageToDiscord);
- this.loggingObject.removeListener('playerConnected', this.sendRichConnectedMessageToDiscord);
- this.loggingObject.removeListener('playerDisconnected', this.sendRichDisconnectedMessageToDiscord);
- this.channel.client.removeListener('message', this.sendMessageToGame);
- embed.setDescription(':x: Disabled chat bridge');
- } else {
- embed.setDescription('Tried to stop chatbridge in this channel but something went wrong!')
- }
- this.channel.send(embed);
- }
-
- sendChatMessageToDiscord(chatMessage) {
- if (chatMessage.playerName == 'Server') {
- this.channel.send(`\`${chatMessage.messageText}\``);
- } else {
- this.channel.send(`${chatMessage.playerName}: ${chatMessage.messageText}`);
- }
- }
-
- sendDeathMessageToDiscord(deathMessage) {
- this.channel.send(`${deathMessage.playerName} died.`);
- }
-
- sendConnectedMessageToDiscord(connectedMsg) {
- this.channel.send(`${connectedMsg.playerName} connected.`);
- }
-
- sendDisconnectedMessageToDiscord(disconnectedMsg) {
- this.channel.send(`${disconnectedMsg.playerName} disconnected.`);
- }
-
-
- async sendRichConnectedMessageToDiscord(connectedMsg) {
- let connectedPlayer = await Player.find({
- steamId: connectedMsg.steamID,
- server: this.sdtdServer.id
- })
- connectedPlayer = connectedPlayer[0]
- let embed = new this.channel.client.customEmbed();
-
- embed.setTitle(`${this.sdtdServer.name} --- ${connectedMsg.playerName} connected`)
- .addField('Steam ID', `[${connectedMsg.steamID}](https://steamidfinder.com/lookup/${connectedMsg.steamID}/)`, true)
- .addField('Country', connectedMsg.country, true)
- .setColor('GREEN')
-
- if (connectedPlayer) {
- embed.addField('Playtime', connectedPlayer.playtime ? hhmmss(connectedPlayer.playtime) : "New player!", true)
- .addField('CSMM profile', `${process.env.CSMM_HOSTNAME}/player/${connectedPlayer.id}/profile`)
- }
-
- if (connectedPlayer.avatarUrl) {
- embed.setThumbnail(connectedPlayer.avatarUrl)
- }
- this.channel.send(embed);
- }
-
- async sendRichDisconnectedMessageToDiscord(disconnectedMsg) {
- let disconnectedPlayer = await Player.find({
- entityId: disconnectedMsg.entityID,
- server: this.sdtdServer.id
- })
- disconnectedPlayer = disconnectedPlayer[0]
- let embed = new this.channel.client.customEmbed();
- embed.setTitle(`${this.sdtdServer.name} --- ${disconnectedMsg.playerName} disconnected`)
- .addField('Steam ID', disconnectedPlayer.steamId ? `[${disconnectedPlayer.steamId}](https://steamidfinder.com/lookup/${disconnectedPlayer.steamId}/)` : `Unknown`, true)
- .addField('Playtime', hhmmss(disconnectedPlayer.playtime), true)
- .addField('CSMM profile', `${process.env.CSMM_HOSTNAME}/player/${disconnectedPlayer.id}/profile`)
- .setColor('RED')
- if (disconnectedPlayer.avatarUrl) {
- embed.setThumbnail(disconnectedPlayer.avatarUrl);
- }
- this.channel.send(embed);
- }
-
- sendMessageToGame(message) {
-
- if (message.channel.id === this.channel.id && message.author.id != message.client.user.id) {
- sevenDays.sendMessage({
- ip: this.sdtdServer.ip,
- port: this.sdtdServer.webPort,
- authName: this.sdtdServer.authName,
- authToken: this.sdtdServer.authToken,
- message: `[${message.author.username}]: ${message.cleanContent}`
- }).exec({
- error: (error) => {
- sails.log.error(`HOOK discordBot:chatBridgeChannel ${error}`)
- message.reply(new this.channel.client.errorEmbed(`:x: Could not send your message to the server! Something is wrong :eyes:`));
- },
- success: () => {
- return true;
- }
- });
- }
- }
-}
-
-module.exports = ChatBridgeChannel;
-
- const ChatBridgeChannel = require('./chatBridgeChannel.js');
-
-/**
- * @module SdtdDiscordChatBridgeHook
- * @description a Sails project hook. Discord chat bridges
- * @param {*} sails Global sails instance
- */
-
-module.exports = function SdtdDiscordChatBridge(sails) {
-
- /**
- * @var {Map} chatBridgeInfoMap Keeps track of servers with chatbridges activated
- * @private
- */
-
- let chatBridgeInfoMap = new Map();
-
- return {
-
- /**
- * @memberof module:SdtdDiscordChatBridgeHook
- * @method
- * @name initialize
- * @description Initializes the chatbridges(s)
- */
- initialize: async function (cb) {
- sails.on('hook:orm:loaded', async function () {
- sails.on('hook:discordbot:loaded', async function () {
- try {
- let enabledServers = await SdtdConfig.find({
- or: [{
- chatChannelId: {
- '!=': ''
- }
- }]
- });
-
- for (const serverConfig of enabledServers) {
- try {
- await start(serverConfig.server);
- } catch (error) {
- sails.log.error(`HOOK - DiscordChatBridge:initialize - Error for server ${serverConfig.server} - ${error}`)
- }
- }
- sails.log.info(`HOOK SdtdDiscordChatBridge:initialize - Initialized ${chatBridgeInfoMap.size} chatbridge(s)`);
-
-
- } catch (error) {
- sails.log.error(`HOOK SdtdDiscordChatBridge:initialize - ${error}`);
- }
- cb();
- });
- });
- },
-
- /**
- * @memberof module:SdtdDiscordChatBridgeHook
- * @method
- * @name start
- * @description Starts the chat bridge(s)
- */
-
- start: start,
-
- /**
- * @memberof module:SdtdDiscordChatBridgeHook
- * @method
- * @name stop
- * @description Stops the chat bridge(s)
- */
-
- stop: stop,
-
- /**
- * @memberof module:SdtdDiscordChatBridgeHook
- * @method
- * @name getStatus
- * @description Get the chat bridge status for a server
- * @returns {boolean}
- */
-
- getStatus: function (serverId) {
- return chatBridgeInfoMap.has(serverId);
- },
-
- getAmount: function() {
- return chatBridgeInfoMap.size
- }
-
- };
-
- async function start(serverId) {
-
- try {
- sails.log.debug(`HOOK SdtdDiscordChatBridge:start - Starting chatbridge for server ${serverId}`);
- let discordClient = sails.hooks.discordbot.getClient();
- let config = await SdtdConfig.find({
- server: serverId
- }).limit(1);
-
- config = config[0]
-
- if (_.isUndefined(config) || !config.chatChannelId) {
- throw new Error(`Tried to start chatbridge for server without config`);
- }
-
- let server = await SdtdServer.findOne(serverId);
- let guild = discordClient.guilds.get(config.discordGuildId);
- let textChannel = discordClient.channels.get(config.chatChannelId);
-
- if (_.isUndefined(server)) {
- throw new Error(`Unknown server`);
- }
-
- if (_.isUndefined(textChannel)) {
- throw new Error(`Did not find textchannel corresponding to ID in config.`);
- }
-
- let chatBridge = new ChatBridgeChannel(textChannel, server);
- chatBridgeInfoMap.set(serverId, chatBridge);
- } catch (error) {
- sails.log.error(`HOOK SdtdDiscordChatBridge:start - ${error}`);
- throw error;
- }
- }
-
- async function stop(serverId) {
- try {
- sails.log.debug(`HOOK SdtdDiscordChatBridge:stop - Stopping chatbridge for server ${serverId}`);
- let chatBridge = chatBridgeInfoMap.get(serverId);
- if (!_.isUndefined(chatBridge)) {
- chatBridge.stop();
- return chatBridgeInfoMap.delete(serverId);
- }
- return;
- } catch (error) {
- sails.log.error(`HOOK SdtdDiscordChatBridge:stop - ${error}`);
- throw error;
- }
- }
-};
-
- /**
- * @memberof module:SdtdCommandsHook
- * @name SdtdCommand
- * @param {number} serverId
- * @description Abstract class to represent ingame commands
- */
-
-class SdtdCommand {
- constructor(serverId) {
- /**
- * @param {number} serverId
- * @name SdtdCommand#serverId
- */
- this.serverId;
- }
-
-
- async run(chatMessage, playerId) {
- throw new Error(`${this.constructor.name} doesn't have a run() method.`);
- }
-}
-
-module.exports = SdtdCommand;
-
- /**
- * @memberof module:SdtdCommandsHook
- * @name commandHandler
- * @param {number} serverId
- * @param {loggingObject} loggingObject Obtained from the logging hook
- * @param {json} config Server commands config
- * @description Handles ingamecommands on a server
- */
-
-
-class CommandHandler {
- constructor(serverId, loggingObject, config) {
- this.serverId = serverId;
- this.loggingObject = loggingObject;
- this.config = config;
- this.commands = CommandHandler.loadCommands.bind(this)();
- this.commandListener = CommandHandler.commandListener.bind(this);
- this.start();
- }
- /**
- * Start listening for commands
- */
- start() {
- this.commands = CommandHandler.loadCommands.bind(this)();
- let listenerFunction = this.commandListener;
- this.loggingObject.on('chatMessage', listenerFunction);
- }
-
- /**
- * Stop listening for commands
- */
-
- stop() {
- let listenerFunction = this.commandListener;
- this.loggingObject.removeListener('chatMessage', listenerFunction);
- }
-
- /**
- * Load enabled commands
- * @returns {Map}
- */
-
- static loadCommands() {
-
- let commands = new Map();
- let config = this.config;
-
- const normalizedPath = require('path').join(__dirname, 'commands');
-
- require('fs').readdirSync(normalizedPath).forEach(function (file) {
- let command = require('./commands/' + file);
- if (config.enabledCommands[command.name] === true) {
- commands.set(command.name.toLowerCase(), new command(config.server));
- }
-
- });
-
- return commands;
-
- }
-
- /**
- * Attached to the logging event emitter
- * @param {json} chatMessage
- */
-
- static async commandListener(chatMessage) {
-
- try {
- if (chatMessage.messageText.startsWith(this.config.commandPrefix)) {
- let trimmedMsg = chatMessage.messageText.slice(this.config.commandPrefix.length, chatMessage.messageText.length);
- let splitString = trimmedMsg.split(' ');
-
- let commandName = splitString[0];
- let args = splitString.splice(1, splitString.length);
-
- if (this.commands.has(commandName)) {
- let player = await Player.find({name: chatMessage.playerName, server: this.config.server});
- player = player[0];
-
- let commandToRun = this.commands.get(commandName);
-
- return commandToRun.run(chatMessage, player.id, args);
- }
- sails.log.debug(`HOOK SdtdCommands:commandListener - Unknown command user by ${chatMessage.playerName} on server ${this.config.server}`);
- }
- } catch (error) {
- sails.log.error(`HOOK SdtdCommands:commandListener - ${error}`);
- }
-
-
-
- }
-}
-
-module.exports = CommandHandler;
-
- const CommandHandler = require('./commandHandler.js');
-/**
- * @module SdtdCommandsHook
- * @description a Sails project hook. Ingame command handler for Sdtd
- * @param {*} sails Global sails instance
- */
-
-/**
- * @module SdtdCommands
- * @description Command guide for users
- */
-
-module.exports = function sdtdCommands(sails) {
-
- /**
- * @var {Map} commandInfoMap Keeps track of servers with commands activated
- * @private
- */
-
- let commandInfoMap = new Map();
-
- return {
-
- /**
- * @memberof module:SdtdCommandsHook
- * @method
- * @name initialize
- * @description Initializes the ingame command listener(s)
- */
- initialize: async function (cb) {
- sails.on('hook:orm:loaded', async function () {
- sails.on('hook:sdtdlogs:loaded', async function () {
- try {
- let enabledServers = await SdtdConfig.find({
- commandsEnabled: true
- });
-
- for (const config of enabledServers) {
- await start(config.server);
- }
-
- sails.log.info(`HOOK SdtdCommands - initialized ${commandInfoMap.size} ingame command listeners`);
- } catch (error) {
- sails.log.error(`HOOK SdtdCommands:initialize - ${error}`);
- }
- cb();
- });
- });
- },
-
- /**
- * @memberof module:SdtdCommandsHook
- * @method
- * @name start
- * @description Starts the ingame command listener(s)
- */
-
- start: start,
-
- /**
- * @memberof module:SdtdCommandsHook
- * @method
- * @name stop
- * @description Stops the ingame command listener(s)
- */
-
- stop: stop,
-
- /**
- * @memberof module:SdtdCommandsHook
- * @method
- * @name getStatus
- * @description Get the commands status for a server
- * @returns {boolean}
- */
-
- getStatus: function (serverId) {
- return commandInfoMap.has(serverId);
- },
-
- getAmount: function() {
- return commandInfoMap.size;
- },
-
- /**
- * @memberof module:SdtdCommandsHook
- * @method
- * @name updateConfig
- * @description Updates command config for a server and reload the hook
- */
-
- updateConfig: async function (serverId, newConfig) {
- try {
- sails.log.debug(`HOOK sdtdCommands:updateConfig - Updating commands config for server ${serverId}`);
-
- if (_.isUndefined(newConfig.commandPrefix) || _.isUndefined(newConfig.commandsEnabled)) {
- throw new Error('Missing value(s) for command config. Please check input');
- }
-
- await SdtdConfig.update({
- server: serverId
- }, {
- commandsEnabled: newConfig.commandsEnabled,
- commandPrefix: newConfig.commandPrefix
- });
-
- if (newConfig.commandsEnabled) {
- this.stop(serverId);
- this.start(serverId);
- } else {
- this.stop(serverId);
- }
-
- } catch (error) {
- sails.log.error(`HOOK SdtdCommands:updateConfig - ${error}`);
- throw error;
- }
- }
-
- };
-
- async function start(serverId) {
-
- try {
- sails.log.silly(`HOOK sdtdCommands:start - Starting commands for server ${serverId}`);
- let serverConfig = await SdtdConfig.findOne({
- server: serverId
- });
- if (serverConfig.commandsEnabled) {
- let serverLoggingObj = sails.hooks.sdtdlogs.getLoggingObject(String(serverId));
- let commandHandler = new CommandHandler(serverId, serverLoggingObj, serverConfig);
- commandInfoMap.set(String(serverId), commandHandler);
- return true;
- }
- } catch (error) {
- sails.log.error(`HOOK SdtdCommands:start - ${error}`);
- throw error;
- }
- }
-
- async function stop(serverId) {
- try {
- sails.log.silly(`HOOK sdtdCommands:stop - Stopping commands for server ${serverId}`);
- let commandHandler = commandInfoMap.get(String(serverId));
- if (!_.isUndefined(commandHandler)) {
- commandHandler.stop();
- return commandInfoMap.delete(String(serverId));
- }
- return;
- } catch (error) {
- sails.log.error(`HOOK SdtdCommands:stop - ${error}`);
- throw error;
- }
- }
-};
-
- var sevenDays = require('machinepack-7daystodiewebapi');
-
-/**
- * @module 7dtdLoggingHook
- * @description Detects events on a 7dtd server.
- */
-module.exports = function sdtdLogs(sails) {
-
- /**
- * @var {Map} loggingInfoMap Keeps track of servers with logging activated
- * @private
- */
-
- let loggingInfoMap = new Map();
-
- return {
- /**
- * @name initialize
- * @memberof module:7dtdLoggingHook
- * @description Called on app launch, loads all servers which have logging enabled and creates logging objects for these
- * @method
- * @private
- */
- initialize: function (cb) {
- sails.on('hook:orm:loaded', async function () {
-
- try {
- let enabledServers = await SdtdConfig.find({
- loggingEnabled: true
- }).populate('server');
- for (let config of enabledServers) {
- let server = config.server;
- let loggingObj = await createLogObject(server.id);
- loggingInfoMap.set(String(server.id), loggingObj);
- }
- sails.log.info(`HOOK: Sdtdlogs - Initialized ${loggingInfoMap.size} logging instances`);
- return cb();
- } catch (error) {
- sails.log.error(`HOOKS - sdtdLogs - ${error}`);
- }
- });
- },
-
- /**
- * @name start
- * @memberof module:7dtdLoggingHook
- * @description Starts logging for a server
- * @param {number} serverID - Id of the server
- * @method
- */
-
- start: async function (serverID) {
- serverID = String(serverID);
- try {
- if (!loggingInfoMap.has(serverID)) {
- sails.log.debug(`HOOKS - sdtdLogs - starting logging for server ${serverID}`);
- await SdtdConfig.update({
- server: serverID
- }, {
- loggingEnabled: true
- });
- let loggingObj = await createLogObject(serverID);
- return loggingInfoMap.set(serverID, loggingObj);
- } else {
- throw new Error(`Tried to start logging for a server that already had it enables`);
- }
-
- } catch (error) {
- sails.log.error(`HOOKS - sdtdLogs - ${error}`);
- }
- },
-
- /**
- * @name stop
- * @memberof module:7dtdLoggingHook
- * @description Stops logging for a server
- * @param {number} serverID - Id of the server
- * @method
- */
-
- stop: async function (serverID) {
- serverID = String(serverID);
- try {
- if (loggingInfoMap.has(serverID)) {
- sails.log.debug(`HOOKS - sdtdLogs - stopping logging for server ${serverID}`);
- await SdtdConfig.update({
- server: serverID
- }, {
- loggingEnabled: false
- });
- let loggingObj = loggingInfoMap.get(serverID);
- loggingInfoMap.delete(serverID);
- return loggingObj.stop();
- }
- } catch (error) {
- sails.log.error(`HOOKS - sdtdLogs - ${error}`);
- }
-
-
- },
-
- /**
- * @name getLoggingObject
- * @memberof module:7dtdLoggingHook
- * @description Gets the logging object for a server
- * @param {number} serverId - Id of the server
- * @method
- */
-
- getLoggingObject: function (serverId) {
- let obj = loggingInfoMap.get(String(serverId));
- return obj;
- },
-
- /**
- * @name getStatus
- * @memberof module:7dtdLoggingHook
- * @description Gets the logging status for a server
- * @param {number} serverId - Id of the server
- * @method
- */
-
- getStatus: function (serverId) {
- serverId = String(serverId);
- let status = loggingInfoMap.has(serverId);
- return status;
- }
- };
-
- /**
- * @name createLoggingObject
- * @memberof module:7dtdLoggingHook
- * @description Creates a logging object for a 7dtd server
- * @param {number} serverID - Id of the server
- * @method
- * @private
- */
-
- function createLogObject(serverID) {
- return new Promise((resolve, reject) => {
- sails.models.sdtdserver.findOne({
- id: serverID
- }).exec(function (error, server) {
- if (error) {
- reject(error);
- }
-
- sevenDays.startLoggingEvents({
- ip: server.ip,
- port: server.webPort,
- authName: server.authName,
- authToken: server.authToken,
- }).exec({
- error: function (error) {
- reject(error);
- },
- success: function (eventEmitter) {
- eventEmitter.on('logLine', function (logLine) {
- sails.sockets.broadcast(server.id, 'logLine', logLine);
- });
-
- eventEmitter.on('chatMessage', function (chatMessage) {
- sails.sockets.broadcast(server.id, 'chatMessage', chatMessage);
- });
-
- eventEmitter.on('playerConnected', async function (connectedMsg) {
- try {
- await sails.helpers.loadPlayerData(server.id, connectedMsg.steamID);
- sails.sockets.broadcast(server.id, 'playerConnected', connectedMsg);
- } catch (error) {
- sails.sockets.broadcast(server.id, 'playerConnected', connectedMsg);
- sails.log.error(`HOOKS - sdtdLogs - ${error}`);
- }
-
- });
-
- eventEmitter.on('playerDisconnected', function (disconectedMsg) {
- sails.sockets.broadcast(server.id, 'playerDisconnected', disconectedMsg);
- });
-
- eventEmitter.on('playerDeath', function (deathMessage) {
- sails.sockets.broadcast(server.id, 'playerDeath', deathMessage);
- });
- resolve(eventEmitter);
- }
- });
- });
- });
-
-
- }
-};
-
- var sevenDays = require('machinepack-7daystodiewebapi');
-const MotdSender = require('./motdSenderClass.js');
-
-/**
- * @module 7dtdMOTDHook
- * @description Detects events on a 7dtd server.
- */
-module.exports = function sdtdLogs(sails) {
-
- /**
- * @var {Map} motdInfoMap Keeps track of servers with MOTD activated
- * @private
- */
-
- let motdInfoMap = new Map();
-
- return {
- /**
- * @name initialize
- * @memberof module:7dtdMOTDHook
- * @description Called on app launch, loads all servers which have logging enabled and creates logging objects for these
- * @method
- * @private
- */
- initialize: function (cb) {
- sails.on('hook:orm:loaded', async function () {
- sails.on('hook:sdtdlogs:loaded', async function () {
- try {
- let enabledServers = await SdtdConfig.find({
- motdEnabled: true
- }).populate('server');
-
- for (const config of enabledServers) {
- let server = config.server;
- let motdSender = new MotdSender(server.id, config);
- motdInfoMap.set(server.id, motdSender);
- }
- sails.log.info(`HOOK: sdtdMotd - Initialized ${motdInfoMap.size} MOTD instances`);
- return cb();
- } catch (error) {
- sails.log.error(`HOOKS - sdtdMotd:initialize - ${error}`);
- }
- });
- });
- },
-
- /**
- * @name start
- * @memberof module:7dtdMOTDHook
- * @description Starts Motd for a server
- * @param {number} serverId
- * @method
- */
-
- start: async function (serverId) {
- serverId = String(serverId);
- try {
- if (!motdInfoMap.has(serverId)) {
- sails.log.debug(`HOOKS - sdtdMotd:start - starting motd for server ${serverId}`);
-
- let config = await SdtdConfig.findOne({
- server: serverId
- });
-
- if (!config.motdEnabled) {
- return;
- }
-
- let motdSender = new MotdSender(serverId, config);
-
- return motdInfoMap.set(serverId, motdSender);
- }
-
- } catch (error) {
- sails.log.error(`HOOKS - sdtdMotd:start - ${error}`);
- }
- },
-
- /**
- * @name stop
- * @memberof module:7dtdMOTDHook
- * @description Stops MOTD for a server
- * @param {number} serverId - Id of the server
- * @method
- */
-
- stop: async function (serverId) {
-
- try {
- if (motdInfoMap.has(String(serverId))) {
- sails.log.debug(`HOOKS - sdtdMotd:stop - stopping MOTD for server ${serverId}`);
-
- let motdSender = motdInfoMap.get(serverId);
- motdSender.stop();
- return motdInfoMap.delete(serverId);
- }
- } catch (error) {
- sails.log.error(`HOOKS - sdtdMotd:stop - ${error}`);
- }
-
-
- },
-
-
- /**
- * @name getStatus
- * @memberof module:7dtdMOTDHook
- * @description Gets the motd status for a server
- * @param {number} serverId - Id of the server
- * @method
- */
-
- getStatus: function (serverId) {
- serverId = String(serverId);
- return motdInfoMap.has(serverId);
- },
-
- getAmount: function() {
- return motdInfoMap.size;
- },
-
- /**
- * @name updateConfig
- * @memberof module:7dtdMOTDHook
- * @description Set new values for motd config
- * @param {number} serverId - Id of the server
- * @param {string} newMessage
- * @param {number} newDelay
- * @param {boolean} newStatus motdEnabled
- * @param {boolean} newStatusOnJoin motdOnJoinEnabled
- * @method
- */
-
- updateConfig: async function (serverId, newMessage, newDelay, newStatus, newStatusOnJoin) {
-
- try {
-
- await SdtdConfig.update({
- server: serverId
- }, {
- motdMessage: newMessage,
- motdEnabled: newStatus,
- motdOnJoinEnabled: newStatusOnJoin,
- motdInterval: newDelay
- });
-
- this.stop(serverId);
- this.start(serverId);
-
- } catch (error) {
- return sails.log.error(`HOOKS - sdtdMotd:updateConfig - ${error}`);
- }
-
- }
- };
-
-
-};
-
- const sevenDays = require('machinepack-7daystodiewebapi');
-
-/** Class to send MOTD messages */
-
-class MotdSender {
- /**
- * Create the class
- * @param {number} serverId
- * @param {json} config
- */
- constructor(serverId, config) {
- this.serverId = serverId;
- this.config = config;
- this.start();
- }
-
- /**
- * Start it
- */
- async start() {
-
- try {
- if (!this.config.motdEnabled) {
- throw new Error(`Invalid usage: MOTD is disabled for this server.`);
- }
-
- if (this.config.motdInterval) {
- this.motdInterval = setInterval(() => {
- this.sendMotd(this.config.motdMessage, this.serverId);
- }, this.config.motdInterval * 1000 * 60);
- }
-
- if (this.config.motdOnJoinEnabled) {
- let loggingObj = sails.hooks.sdtdlogs.getLoggingObject(this.serverId);
- this.onJoinListener = MotdSender.onJoinListener.bind(this);
-
- loggingObj.on('playerConnected', this.onJoinListener);
- }
- } catch (error) {
- sails.log.error(`HOOK 7dtdMOTD:motdSenderClass:start - ${error}`);
- throw error;
- }
-
- }
-
- /**
- * Stop it
- */
- async stop() {
- try {
- if (this.onJoinListener) {
- let loggingObj = sails.hooks.sdtdlogs.getLoggingObject(this.serverId);
- loggingObj.removeListener('playerConnected', this.onJoinListener);
- }
-
- if (this.motdInterval) {
- clearInterval(this.motdInterval);
- }
-
- } catch (error) {
- sails.log.error(`HOOK 7dtdMOTD:motdSenderClass:stop - ${error}`);
- throw error;
- }
-
- }
-
- /**
- * Function to attach to event emitter (loggingObj)
- * @param {json} connectedMessage
- */
-
- static async onJoinListener(connectedMessage) {
- try {
- await this.sendMotd(this.config.motdMessage, this.serverId, connectedMessage.steamID);
- } catch (error) {
- sails.log.error(`HOOK 7dtdMOTD:motdSenderClass:onJoinListener - ${error}`);
- }
- }
-
- /**
- * Send the message to the server or a player if steamId is given
- * @param {string} message
- * @param {number} serverId
- * @param {string} playerSteamId
- */
- async sendMotd(message, serverId, playerSteamId) {
- try {
- let server = await SdtdServer.findOne(serverId);
-
- if (_.isUndefined(server)) {
- return sails.log.error(`HOOKS - sdtdMotd:MotdSender:sendMotd - Unknown server id ${serverId}`);
- }
-
- sevenDays.sendMessage({
- ip: server.ip,
- port: server.webPort,
- authName: server.authName,
- authToken: server.authToken,
- message: message,
- playerID: playerSteamId,
- }).exec({
- success: (response) => {
- sails.log.debug(`HOOKS - sdtdMotd:MotdSender:sendMotd - Successfully sent MOTD message to server ${serverId}`);
- },
- unknownPlayer: (error) => {
- sails.log.error(`HOOKS - sdtdMotd:MotdSender:sendMotd - Tried to send message to unknown player ${serverId}`);
- },
- error: (error) => {
- sails.log.error(`HOOKS - sdtdMotd:MotdSender:sendMotd - Unknown server id ${serverId}`);
- }
- });
-
- } catch (error) {
- sails.log.error(`HOOKS - sdtdMotd:MotdSender:sendMotd - ${error}`);
- }
- }
-
-}
-
-module.exports = MotdSender;
-
- /**
- * Player.js
- *
- * @description A model definition. Represents a ingame player
- * @class Player
- * @param {number} steamId
- * @param {number} entityId
- */
-
-module.exports = {
-
- attributes: {
-
- // ╔═╗╦═╗╦╔╦╗╦╔╦╗╦╦ ╦╔═╗╔═╗
- // ╠═╝╠╦╝║║║║║ ║ ║╚╗╔╝║╣ ╚═╗
- // ╩ ╩╚═╩╩ ╩╩ ╩ ╩ ╚╝ ╚═╝╚═╝
-
- steamId: {
- type: 'string',
- required: true
- },
-
- /**
- * @var {number} entityId
- * @memberof Player
- */
-
- entityId: {
- type: 'number'
- },
-
- /**
- * @var {string} ip
- * @description Last known IP address of the player
- * @memberof Player
- */
-
- ip: {
- type: 'string'
- },
-
- /**
- * @var {string} avatarUrl
- * @description Url of the players' steam avatar
- * @memberOf Player
- */
-
- avatarUrl: {
- type: 'string'
- },
-
- /**
- * @memberof Player
- * @var {string} name
- */
-
- name: {
- type: 'string',
- required: true
- },
-
- /**
- * @memberof Player
- * @var {number} positionX
- */
-
- positionX: {
- type: 'number'
- },
-
- /**
- * @memberof Player
- * @var {number} positionY
- */
-
- positionY: {
- type: 'number'
- },
-
- /**
- * @memberof Player
- * @var {number} positionZ
- */
-
- positionZ: {
- type: 'number'
- },
-
- /**
- * @memberof Player
- * @var {json} inventory
- * @description Last known inventory
- */
-
- inventory: {
- type: 'json',
- },
-
- /**
- * @memberof Player
- * @var {number} playtime
- * @description Total time the player has been online
- */
-
- playtime: {
- type: 'number'
- },
-
- /**
- * @memberof Player
- * @var {string} lastOnline
- * @description When the player was last seen online
- */
-
- lastOnline: {
- type: 'string'
- },
-
- /**
- * @memberof Player
- * @var {boolean} banned
- * @description Whether or not a player is banned
- * @default false
- */
-
- banned: {
- type: 'boolean',
- defaultsTo: false
- },
-
-
- // ╔═╗╔╦╗╔╗ ╔═╗╔╦╗╔═╗
- // ║╣ ║║║╠╩╗║╣ ║║╚═╗
- // ╚═╝╩ ╩╚═╝╚═╝═╩╝╚═╝
-
-
- // ╔═╗╔═╗╔═╗╔═╗╔═╗╦╔═╗╔╦╗╦╔═╗╔╗╔╔═╗
- // ╠═╣╚═╗╚═╗║ ║║ ║╠═╣ ║ ║║ ║║║║╚═╗
- // ╩ ╩╚═╝╚═╝╚═╝╚═╝╩╩ ╩ ╩ ╩╚═╝╝╚╝╚═╝
-
- /**
- * @memberof Player
- * @var server
- * @description What server the player belongs to
- */
- server: {
- model: 'sdtdServer'
- },
-
- /**
- * @memberof Player
- * @var user
- * @description What user corresponds to a player
- */
-
- user: {
- model: 'user'
- }
-
- },
-
-};
-
- /**
- * SdtdConfig.js
- *
- * @description Persistent configuration per server for system features
- * @module SdtdConfig
- */
-
-module.exports = {
-
- attributes: {
-
-
- // _____ _
- // / ____| | |
- // | | ___ _ __ ___ _ __ ___ __ _ _ __ __| |___
- // | | / _ \| '_ ` _ \| '_ ` _ \ / _` | '_ \ / _` / __|
- // | |___| (_) | | | | | | | | | | | (_| | | | | (_| \__ \
- // \_____\___/|_| |_| |_|_| |_| |_|\__,_|_| |_|\__,_|___/
-
- /**
- * @memberof SdtdConfig
- * @var {boolean} commandsEnabled
- * @description Whether or not ingame commands are enabled
- * @default false
- */
-
- commandsEnabled: {
- type: 'boolean',
- defaultsTo: false
- },
-
-
- /**
- * @memberof SdtdConfig
- * @var {string} commandPrefix
- * @description Command prefix to use ingame
- */
-
- commandPrefix: {
- type: 'string',
- defaultsTo: '$'
- },
-
- /**
- * @memberof SdtdConfig
- * @var {json} enabledCommands
- * @description json of enabled commands
- */
-
- enabledCommands: {
- type: 'json',
- defaultsTo: {
- sayHi: true,
- callAdmin: true
- }
- },
-
- // _____ _ _
- // | __ \(_) | |
- // | | | |_ ___ ___ ___ _ __ __| |
- // | | | | / __|/ __/ _ \| '__/ _` |
- // | |__| | \__ \ (_| (_) | | | (_| |
- // |_____/|_|___/\___\___/|_| \__,_|
-
-
- /**
- * @memberof SdtdServer
- * @var {string} discordGuildId
- * @description Id of the disccord guild this server is associated with
- */
-
- discordGuildId: {
- type: 'string'
- },
-
- /**
- * @memberof SdtdServer
- * @var {string} chatChannelId
- * @description Id of the discord channel for chat bridge
- */
-
- chatChannelId: {
- type: 'string'
- },
-
- /**
- * @memberof SdtdServer
- * @var {string} chatChannelRichMessages
- * @description Whether to use rich messages for (dis)connect messages
- */
-
- chatChannelRichMessages: {
- type: 'boolean',
- defaultsTo: true
- },
-
- /**
- * @memberof SdtdServer
- * @var {string} notificationChannelId
- * @description Id of the discord channel for notifications
- */
-
- notificationChannelId: {
- type: 'string'
- },
-
- // _ _
- // | | (_)
- // | | ___ __ _ __ _ _ _ __ __ _
- // | | / _ \ / _` |/ _` | | '_ \ / _` |
- // | |___| (_) | (_| | (_| | | | | | (_| |
- // |______\___/ \__, |\__, |_|_| |_|\__, |
- // __/ | __/ | __/ |
- // |___/ |___/ |___/
-
- /**
- * @memberof SdtdConfig
- * @var {boolean} loggingEnabled
- * @description Whether or not logging is enabled
- * @default true
- */
-
- loggingEnabled: {
- type: 'boolean',
- defaultsTo: true
- },
-
- // _____ _ _
- // / ____| | | | |
- // | | ___ _ _ _ __ | |_ _ __ _ _ | |__ __ _ _ __
- // | | / _ \| | | | '_ \| __| '__| | | | | '_ \ / _` | '_ \
- // | |___| (_) | |_| | | | | |_| | | |_| | | |_) | (_| | | | |
- // \_____\___/ \__,_|_| |_|\__|_| \__, | |_.__/ \__,_|_| |_|
- // __/ |
- // |___/
-
- /**
- * @memberof SdtdConfig
- * @var {json} countryBanConfig
- * @description Config for country ban
- */
-
- countryBanConfig: {
- type: 'json',
- defaultsTo: {
- enabled: false,
- bannedCountries: [],
- kickMessage: 'Your country has been blocked on this server.',
- allowNull: true,
- whiteListedSteamIds: []
- },
- },
-
- // __ __ ____ _______ _____
- // | \/ |/ __ \__ __| __ \
- // | \ / | | | | | | | | | |
- // | |\/| | | | | | | | | | |
- // | | | | |__| | | | | |__| |
- // |_| |_|\____/ |_| |_____/
-
- /**
- * @memberof SdtdConfig
- * @var {boolean} motdEnabled
- */
-
- motdEnabled: {
- type: 'boolean',
- defaultsTo: false
- },
-
- /**
- * @memberof SdtdConfig
- * @var {string} motdMessage
- * @description Message to be sent
- */
-
- motdMessage: {
- type: 'string',
- defaultsTo: 'Enjoy playing on this server!'
- },
-
- /**
- * @memberof SdtdConfig
- * @var {boolean} motdOnJoinEnabled
- * @description Wheter MOTD message should be sent to players on joining
- */
-
- motdOnJoinEnabled: {
- type: 'boolean',
- defaultsTo: false
- },
-
- /**
- * @memberof SdtdConfig
- * @var {number} motdInterval
- * @description Interval the message is sent in minutes
- */
-
- motdInterval: {
- type: 'number',
- defaultsTo: 20
- },
-
-
- // ╔═╗╔═╗╔═╗╔═╗╔═╗╦╔═╗╔╦╗╦╔═╗╔╗╔╔═╗
- // ╠═╣╚═╗╚═╗║ ║║ ║╠═╣ ║ ║║ ║║║║╚═╗
- // ╩ ╩╚═╝╚═╝╚═╝╚═╝╩╩ ╩ ╩ ╩╚═╝╝╚╝╚═╝
-
- /**
- * @var server
- * @description Server this config belongs to
- * @memberof module:SdtdCommandsHook
- */
-
- server: {
- model: 'sdtdserver',
- required: true
- },
-
- },
-
-};
-
- /**
- * SdtdServer.js
- *
- * @description Represents a 7 Days to Die server
- * @class SdtdServer
- */
-
-module.exports = {
-
- customToJSON: function () {
- return _.omit(this, ['authToken', 'authName', 'telnetPort']);
- },
-
- attributes: {
-
- // ╔═╗╦═╗╦╔╦╗╦╔╦╗╦╦ ╦╔═╗╔═╗
- // ╠═╝╠╦╝║║║║║ ║ ║╚╗╔╝║╣ ╚═╗
- // ╩ ╩╚═╩╩ ╩╩ ╩ ╩ ╚╝ ╚═╝╚═╝
-
- /**
- * @memberof SdtdServer
- * @var {string} name
- */
-
- name: {
- type: 'string'
- },
-
- /**
- * @var {string} ip
- * @memberof SdtdServer
- */
-
- ip: {
- type: 'string',
- required: true
- },
-
- /**
- * @memberof SdtdServer
- * @var {number} gamePort
- * @description Port used by players to join the game
- */
-
- gamePort: {
- type: 'number'
- },
-
- /**
- * @memberof SdtdServer
- * @var {number} telnetPort
- */
-
- telnetPort: {
- type: 'number',
- required: true
- },
-
- /**
- * @memberof SdtdServer
- * @var {number} webPort
- * @description Port provided by Alloc's webserver
- */
-
- webPort: {
- type: 'number'
- },
-
- /**
- * @memberof SdtdServer
- * @var {string} authName
- * @description adminuser to use during webrequests
- */
-
- authName: {
- type: 'string'
- },
-
- /**
- * @memberof SdtdServer
- * @var {string} authToken
- * @description admintoken to use during webrequests
- */
-
- authToken: {
- type: 'string'
- },
-
-
-
- // ╔═╗╔╦╗╔╗ ╔═╗╔╦╗╔═╗
- // ║╣ ║║║╠╩╗║╣ ║║╚═╗
- // ╚═╝╩ ╩╚═╝╚═╝═╩╝╚═╝
-
-
- // ╔═╗╔═╗╔═╗╔═╗╔═╗╦╔═╗╔╦╗╦╔═╗╔╗╔╔═╗
- // ╠═╣╚═╗╚═╗║ ║║ ║╠═╣ ║ ║║ ║║║║╚═╗
- // ╩ ╩╚═╝╚═╝╚═╝╚═╝╩╩ ╩ ╩ ╩╚═╝╝╚╝╚═╝
-
- /**
- * @memberof SdtdServer
- * @var owner
- * @description Owner of the server, corresponds to a User
- */
-
- owner: {
- model: 'user',
- required: true
- },
-
- /**
- * @memberof SdtdServer
- * @var admins
- * @description Users allowed to perform admin actions on the server
- */
-
- admins: {
- collection: 'user',
- },
-
- /**
- * @memberof SdtdServer
- * @var players
- * @description Collection of Players that have logged on the server
- */
-
- players: {
- collection: 'player',
- via: 'server'
- },
-
- /**
- * @memberof SdtdServer
- * @var tickets
- * @description Collection of SdtdTickets
- */
-
- tickets: {
- collection: 'sdtdticket',
- via: 'server'
- },
- },
-
-};
-
- /**
- * SdtdTicket.js
- *
- * @description Player-made tickets for admin support
- * @module SdtdTicket
- */
-
-module.exports = {
-
- attributes: {
-
- /**
- * @var description
- * @description Description for this ticket
- * @memberof module:SdtdTicket
- */
-
- description: {
- type: 'string'
- },
-
- /**
- * @var title
- * @description Title of the ticket
- * @memberof module:SdtdTicket
- */
-
- title: {
- type: 'string',
- required: true
- },
-
- /**
- * @var status
- * @description Status of the ticket (open/closed)
- * @memberof module:SdtdTicket
- */
-
- status: {
- type: 'boolean',
- defaultsTo: true
- },
-
- /**
- * @var playerInfo
- * @description playerInfo at the time the ticket was created
- * @memberof module:SdtdTicket
- */
-
- playerInfo: {
- type: 'json'
- },
-
- // ╔═╗╔═╗╔═╗╔═╗╔═╗╦╔═╗╔╦╗╦╔═╗╔╗╔╔═╗
- // ╠═╣╚═╗╚═╗║ ║║ ║╠═╣ ║ ║║ ║║║║╚═╗
- // ╩ ╩╚═╝╚═╝╚═╝╚═╝╩╩ ╩ ╩ ╩╚═╝╝╚╝╚═╝
-
- /**
- * @var server
- * @description Server this ticket belongs to
- * @memberof module:SdtdTicket
- */
-
- server: {
- model: 'sdtdserver',
- required: true,
- },
-
- /**
- * @var player
- * @description Player who made the ticket
- * @memberof module:SdtdTicket
- */
-
- player: {
- model: 'player',
- required: true
- }
-
- },
-
-};
-
- /**
- * User.js
- *
- * @description Represents a user of the system
- * @class User
- */
-
-module.exports = {
-
- toJSON: function () {
- var obj = this.toObject();
- delete obj.encryptedPassword;
- return obj;
- },
-
- attributes: {
-
- // ╔═╗╦═╗╦╔╦╗╦╔╦╗╦╦ ╦╔═╗╔═╗
- // ╠═╝╠╦╝║║║║║ ║ ║╚╗╔╝║╣ ╚═╗
- // ╩ ╩╚═╩╩ ╩╩ ╩ ╩ ╚╝ ╚═╝╚═╝
-
- /**
- * @memberof User
- * @var {string} steamId
- */
-
- steamId: {
- type: 'string',
- unique: true,
- required: true
- },
-
- /**
- * memberof User
- * @var {string} discordId
- */
-
- discordId: {
- type: 'string'
- },
-
- /**
- * @memberof User
- * @var {string} username
- */
-
- username: {
- type: 'string',
- required: true,
- unique: true
- },
-
- /**
- * @var {boolean} admin
- * @memberof User
- * @description If a user can perform admin actions on the system
- * @default false
- */
-
- admin: {
- type: 'boolean',
- defaultsTo: false
- },
-
- /**
- * @var {boolean} banned
- * @memberof User
- * @default false
- */
-
- banned: {
- type: 'boolean',
- defaultsTo: false
- },
-
- // ╔═╗╔╦╗╔╗ ╔═╗╔╦╗╔═╗
- // ║╣ ║║║╠╩╗║╣ ║║╚═╗
- // ╚═╝╩ ╩╚═╝╚═╝═╩╝╚═╝
-
-
- // ╔═╗╔═╗╔═╗╔═╗╔═╗╦╔═╗╔╦╗╦╔═╗╔╗╔╔═╗
- // ╠═╣╚═╗╚═╗║ ║║ ║╠═╣ ║ ║║ ║║║║╚═╗
- // ╩ ╩╚═╝╚═╝╚═╝╚═╝╩╩ ╩ ╩ ╩╚═╝╝╚╝╚═╝
-
- /**
- * @var players
- * @description Ingame Players corresponding to a user
- * @memberof User
- */
-
- players: {
- collection: 'player',
- via: 'user'
- },
-
- /**
- * @var servers
- * @description Servers this User owns
- * @memberof User
- */
-
- servers: {
- collection: 'sdtdServer',
- via: 'owner'
- },
-
- },
-
-};
-
- Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -number - - - - | - - - - - -Id of the server | -
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -number - - - - | - - - - - -Id of the server | -
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -number - - - - | - - - - - -Id of the server | -
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -number - - - - | - - - - - -Id of the server | -
hooks/sdtdLogs/index.js
,
- line 102
- Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -number - - - - | - - - - - -Id of the server | -
hooks/sdtdLogs/index.js
,
- line 115
- Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -number - - - - | - - - - - -Id of the server | -
hooks/sdtdLogs/index.js
,
- line 44
- Name | - - -Type | - - - - - -Description | -
---|---|---|
serverID |
-
-
- - - -number - - - - | - - - - - -Id of the server | -
hooks/sdtdLogs/index.js
,
- line 73
- Name | - - -Type | - - - - - -Description | -
---|---|---|
serverID |
-
-
- - - -number - - - - | - - - - - -Id of the server | -
hooks/sdtdMotd/index.js
,
- line 105
- Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -number - - - - | - - - - - -Id of the server | -
hooks/sdtdMotd/index.js
,
- line 47
- Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -number - - - - | - - - - - -- |
hooks/sdtdMotd/index.js
,
- line 79
- Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -number - - - - | - - - - - -Id of the server | -
hooks/sdtdMotd/index.js
,
- line 122
- Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -number - - - - | - - - - - -Id of the server | -
newMessage |
-
-
- - - -string - - - - | - - - - - -- |
newDelay |
-
-
- - - -number - - - - | - - - - - -- |
newStatus |
-
-
- - - -boolean - - - - | - - - - - -motdEnabled | -
newStatusOnJoin |
-
-
- - - -boolean - - - - | - - - - - -motdOnJoinEnabled | -
Name | - - -Type | - - - - - -Description | -
---|---|---|
sails |
-
-
- - - -* - - - - | - - - - - -Global sails instance | -
hooks/discordBot/index.js
,
- line 71
- hooks/discordBot/index.js
,
- line 19
- hooks/discordBot/index.js
,
- line 82
- Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -string - - - - | - - - - - -- |
message |
-
-
- - - -string - - - - | - - - - - -- |
Name | - - -Type | - - - - - -Description | -
---|---|---|
ip |
-
-
- - - -string - - - - | - - - - - -- |
telnetPort |
-
-
- - - -number - - - - | - - - - - -- |
telnetPassword |
-
-
- - - -string - - - - | - - - - - -- |
webPort |
-
-
- - - -number - - - - | - - - - - -- |
owner |
-
-
- - - -number - - - - | - - - - - -The ID of the owner | -
discordGuildId |
-
-
- - - -number - - - - | - - - - - -- |
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -number - - - - | - - - - - -- |
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -number - - - - | - - - - - -- |
playerId |
-
-
- - - -number - - - - | - - - - - -- |
title |
-
-
- - - -string - - - - | - - - - - -- |
description |
-
-
- - - -string - - - - | - - - - - -- |
Name | - - -Type | - - - - - -Description | -
---|---|---|
ip |
-
-
- - - -string - - - - | - - - - - -- |
port |
-
-
- - - -number - - - - | - - - - - -Telnet port | -
password |
-
-
- - - -string - - - - | - - - - - -Telnet password | -
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -number - - - - | - - - - - -- |
Name | - - -Type | - - - - - -Description | -
---|---|---|
serverId |
-
-
- - - -number - - - - | - - - - - -- |
Name | - - -Type | - - - - - -Description | -
---|---|---|
sails |
-
-
- - - -* - - - - | - - - - - -Global sails instance | -
models/SdtdConfig.js
,
- line 209
- Name | - - -Type | - - - - - -Description | -
---|---|---|
sails |
-
-
- - - -* - - - - | - - - - - -Global sails instance | -
models/SdtdTicket.js
,
- line 12
- models/SdtdTicket.js
,
- line 69
- models/SdtdTicket.js
,
- line 44
- models/SdtdTicket.js
,
- line 58
- models/SdtdTicket.js
,
- line 33
- models/SdtdTicket.js
,
- line 22
- /**
- * isBetaTester
- *
- * Check if logged in user is registered as beta tester.
- *
- */
-
-module.exports = async function isBetaTester(req, res, next) {
- sails.log.silly(`POLICY - isBetaTester - Check if a user is logged in`);
- try {
- let user = await User.findOne(req.session.userId);
- if( sails.config.custom.betaTesters.includes(user.steamId) ) {
- sails.log.silly(`POLICY - isBetaTester - ${user.username} User ${req.session.userId} is a beta tester!`);
- return next();
- } else {
- sails.log.warn(`POLICY - isBetaTester - ${req.ip} tried to access a protected resource!`);
- return res.forbidden(`You are not a beta tester!`);
- }
- } catch (error) {
- sails.log.error(error);
- return res.serverError(error)
- }
-};
-
- /**
- * isLoggedIn
- *
- * A simple policy that allows any request from an authenticated user.
- *
- * For more about how this policy works and how to use it, see:
- * https://sailsjs.com/anatomy/api/policies/isLoggedIn.js
- */
-module.exports = function isLoggedIn(req, res, next) {
- if(!_.isUndefined(req.session.userId)) {
- return next();
- } else {
- sails.log.warn(`POLICY - isLoggedIn - ${req.ip} tried to access a protected resource!`);
- return res.redirect('/auth/steam');
- }
-};
-
- t |