mirror of
https://github.com/HabitRPG/habitica.git
synced 2025-12-17 22:57:21 +01:00
Webhook improvements (#7879)
* refactor: Move translate test utility to helpers directory * Add kind property to webhooks * feat: Add options to create webhook route * refactor: Move webhook ops into single file * refactor: Create webhook objects for specific webhook behavior * chore(tests): Add default sleep helper value of 1 second * feat(api): Add method for groups to send out webhook * feat(api): Add taskCreated webhook task creation * feat(api): Send chat webhooks after a chat is sent * refactor: Move webhook routes to own controller * lint: Correct linting errors * fix(api): Correct taskCreated webhook method * fix(api): Fix webhook logging to only log when there is an error * fix: Update groupChatRecieved webhook creation * chore: Add integration tests for webhooks * fix: Set webhook creation response to 201 * fix: Correct how task scored webhook data is sent * Revert group chat recieved webhook to only support one group * Remove quest activity option for webhooks * feat: Send webhook for each task created * feat: Allow webhooks without a type to default to taskScored * feat: Add logic for adding ids to webhook * feat: optimize webhook url check by shortcircuiting if no url is passed * refactor: Use full name for webhook variable * feat: Add missing params to client webhook * lint: Add missing semicolon * chore(tests): Fix inccorect webhook tests * chore: Add migration to update task scored webhooks * feat: Allow default value of webhook add route to be enabled * chore: Update webhook documentation * chore: Remove special handling for v2 * refactor: adjust addComputedStatsToJSONObject to work for webhooks * refactor: combine taskScored and taskActivity webhooks * feat(api): Add task activity to task update and delete routes * chore: Change references to taskScored to taskActivity * fix: Correct stats object being passed in for transform * chore: Remove extra line break * fix: Pass in the language to use for the translations * refactor(api): Move webhooks from user.preferences.webhooks to user.webhooks * chore: Update migration to set webhook array * lint: Correct brace spacing * chore: convert webhook lib to use user.webhooks * refactor(api): Consolidate filters * chore: clarify migration instructions * fix(test): Correct user creation in user anonymized tests * chore: add test that webhooks cannot be updated via PUT /user * refactor: Simplify default webhook id value * refactor(client): Push newly created webhook instead of doing a sync * chore(test): Add test file for webhook model * refactor: Remove webhook validation * refactor: Remove need for watch on webhooks * refactor(client): Update webhooks object without syncing * chore: update webhook documentation * Fix migrations issues * chore: remove v2 test helper * fix(api): Provide webhook type in task scored webhook * fix(client): Fix webhook deletion appearing to delete all webhooks * feat(api): add optional label field for webhooks * feat: provide empty string as default for webhook label * chore: Update webhook migration * chore: update webhook migration name
This commit is contained in:
@@ -124,6 +124,8 @@ api.postChat = {
|
||||
} else {
|
||||
res.respond(200, {message: savedGroup.chat[0]});
|
||||
}
|
||||
|
||||
group.sendGroupChatReceivedWebhooks(newChatMessage);
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ api.getMember = {
|
||||
|
||||
// manually call toJSON with minimize: true so empty paths aren't returned
|
||||
let memberToJSON = member.toJSON({minimize: true});
|
||||
member.addComputedStatsToJSONObj(memberToJSON);
|
||||
member.addComputedStatsToJSONObj(memberToJSON.stats);
|
||||
|
||||
res.respond(200, memberToJSON);
|
||||
},
|
||||
@@ -145,7 +145,7 @@ function _getMembersForItem (type) {
|
||||
// manually call toJSON with minimize: true so empty paths aren't returned
|
||||
let membersToJSON = members.map(member => {
|
||||
let memberToJSON = member.toJSON({minimize: true});
|
||||
if (addComputedStats) member.addComputedStatsToJSONObj(memberToJSON);
|
||||
if (addComputedStats) member.addComputedStatsToJSONObj(memberToJSON.stats);
|
||||
|
||||
return memberToJSON;
|
||||
});
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { authWithHeaders } from '../../middlewares/auth';
|
||||
import { sendTaskWebhook } from '../../libs/webhook';
|
||||
import {
|
||||
taskActivityWebhook,
|
||||
taskScoredWebhook,
|
||||
} from '../../libs/webhook';
|
||||
import { removeFromArray } from '../../libs/collectionManipulators';
|
||||
import * as Tasks from '../../models/task';
|
||||
import { model as Challenge } from '../../models/challenge';
|
||||
@@ -37,7 +40,15 @@ api.createUserTasks = {
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let tasks = await createTasks(req, res, {user});
|
||||
|
||||
res.respond(201, tasks.length === 1 ? tasks[0] : tasks);
|
||||
|
||||
tasks.forEach((task) => {
|
||||
taskActivityWebhook.send(user.webhooks, {
|
||||
type: 'created',
|
||||
task,
|
||||
});
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
@@ -245,35 +256,18 @@ api.updateTask = {
|
||||
}
|
||||
|
||||
res.respond(200, savedTask);
|
||||
if (challenge) challenge.updateTask(savedTask);
|
||||
|
||||
if (challenge) {
|
||||
challenge.updateTask(savedTask);
|
||||
} else {
|
||||
taskActivityWebhook.send(user.webhooks, {
|
||||
type: 'updated',
|
||||
task: savedTask,
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
function _generateWebhookTaskData (task, direction, delta, stats, user) {
|
||||
let extendedStats = _.extend(stats, {
|
||||
toNextLevel: common.tnl(user.stats.lvl),
|
||||
maxHealth: common.maxHealth,
|
||||
maxMP: common.statsComputed(user).maxMP,
|
||||
});
|
||||
|
||||
let userData = {
|
||||
_id: user._id,
|
||||
_tmp: user._tmp,
|
||||
stats: extendedStats,
|
||||
};
|
||||
|
||||
let taskData = {
|
||||
details: task,
|
||||
direction,
|
||||
delta,
|
||||
};
|
||||
|
||||
return {
|
||||
task: taskData,
|
||||
user: userData,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/tasks/:taskId/score/:direction Score a task
|
||||
* @apiVersion 3.0.0
|
||||
@@ -335,7 +329,12 @@ api.scoreTask = {
|
||||
let resJsonData = _.extend({delta, _tmp: user._tmp}, userStats);
|
||||
res.respond(200, resJsonData);
|
||||
|
||||
sendTaskWebhook(user.preferences.webhooks, _generateWebhookTaskData(task, direction, delta, userStats, user));
|
||||
taskScoredWebhook.send(user.webhooks, {
|
||||
task,
|
||||
direction,
|
||||
delta,
|
||||
user,
|
||||
});
|
||||
|
||||
if (task.challenge && task.challenge.id && task.challenge.taskId && !task.challenge.broken && task.type !== 'reward') {
|
||||
// Wrapping everything in a try/catch block because if an error occurs using `await` it MUST NOT bubble up because the request has already been handled
|
||||
@@ -869,7 +868,15 @@ api.deleteTask = {
|
||||
}
|
||||
|
||||
res.respond(200, {});
|
||||
if (challenge) challenge.removeTask(task);
|
||||
|
||||
if (challenge) {
|
||||
challenge.removeTask(task);
|
||||
} else {
|
||||
taskActivityWebhook.send(user.webhooks, {
|
||||
type: 'deleted',
|
||||
task,
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ api.getUser = {
|
||||
// Remove apiToken from response TODO make it private at the user level? returned in signup/login
|
||||
delete userToJSON.apiToken;
|
||||
|
||||
user.addComputedStatsToJSONObj(userToJSON);
|
||||
user.addComputedStatsToJSONObj(userToJSON.stats);
|
||||
return res.respond(200, userToJSON);
|
||||
},
|
||||
};
|
||||
@@ -921,76 +921,6 @@ api.userOpenMysteryItem = {
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/user/webhook Create a new webhook - BETA
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName UserAddWebhook
|
||||
* @apiGroup User
|
||||
*
|
||||
* @apiParam {String} url Body parameter - The webhook's URL
|
||||
* @apiParam {Boolean} enabled Body parameter - If the webhook should be enabled
|
||||
*
|
||||
* @apiSuccess {Object} data The created webhook
|
||||
*/
|
||||
api.addWebhook = {
|
||||
method: 'POST',
|
||||
middlewares: [authWithHeaders()],
|
||||
url: '/user/webhook',
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let addWebhookRes = common.ops.addWebhook(user, req);
|
||||
await user.save();
|
||||
res.respond(200, ...addWebhookRes);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {put} /api/v3/user/webhook/:id Edit a webhook - BETA
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName UserUpdateWebhook
|
||||
* @apiGroup User
|
||||
*
|
||||
* @apiParam {UUID} id The id of the webhook to update
|
||||
* @apiParam {String} url Body parameter - The webhook's URL
|
||||
* @apiParam {Boolean} enabled Body parameter - If the webhook should be enabled
|
||||
*
|
||||
* @apiSuccess {Object} data The updated webhook
|
||||
*/
|
||||
api.updateWebhook = {
|
||||
method: 'PUT',
|
||||
middlewares: [authWithHeaders()],
|
||||
url: '/user/webhook/:id',
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let updateWebhookRes = common.ops.updateWebhook(user, req);
|
||||
await user.save();
|
||||
res.respond(200, ...updateWebhookRes);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {delete} /api/v3/user/webhook/:id Delete a webhook - BETA
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName UserDeleteWebhook
|
||||
* @apiGroup User
|
||||
*
|
||||
* @apiParam {UUID} id The id of the webhook to delete
|
||||
*
|
||||
* @apiSuccess {Object} data The user webhooks
|
||||
*/
|
||||
api.deleteWebhook = {
|
||||
method: 'DELETE',
|
||||
middlewares: [authWithHeaders()],
|
||||
url: '/user/webhook/:id',
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let deleteWebhookRes = common.ops.deleteWebhook(user, req);
|
||||
await user.save();
|
||||
res.respond(200, ...deleteWebhookRes);
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
/* @api {post} /api/v3/user/release-pets Release pets
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName UserReleasePets
|
||||
|
||||
193
website/server/controllers/api-v3/webhook.js
Normal file
193
website/server/controllers/api-v3/webhook.js
Normal file
@@ -0,0 +1,193 @@
|
||||
import { authWithHeaders } from '../../middlewares/auth';
|
||||
import { model as Webhook } from '../../models/webhook';
|
||||
import { removeFromArray } from '../../libs/collectionManipulators';
|
||||
import { NotFound } from '../../libs/errors';
|
||||
|
||||
let api = {};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/user/webhook Create a new webhook - BETA
|
||||
* @apiName AddWebhook
|
||||
* @apiGroup Webhook
|
||||
*
|
||||
* @apiParam {UUID} [id="Randomly Generated UUID"] Body parameter - The webhook's id
|
||||
* @apiParam {String} url Body parameter - The webhook's URL
|
||||
* @apiParam {String} [label] Body parameter - A label to remind you what this webhook does
|
||||
* @apiParam {Boolean} [enabled=true] Body parameter - If the webhook should be enabled
|
||||
* @apiParam {Sring="taskActivity","groupChatReceived"} [type="taskActivity"] Body parameter - The webhook's type.
|
||||
* @apiParam {Object} [options] Body parameter - The webhook's options. Wil differ depending on type. Required for `groupChatReceived` type. If a webhook supports options, the default values are displayed in the examples below
|
||||
* @apiParamExample {json} Task Activity Example
|
||||
* {
|
||||
* "enabled": true, // default
|
||||
* "url": "http://some-webhook-url.com",
|
||||
* "label": "My Webhook",
|
||||
* "type": "taskActivity", // default
|
||||
* "options": {
|
||||
* "created": false, // default
|
||||
* "updated": false, // default
|
||||
* "deleted": false, // default
|
||||
* "scored": true // default
|
||||
* }
|
||||
* }
|
||||
* @apiParamExample {json} Group Chat Received Example
|
||||
* {
|
||||
* "enabled": true,
|
||||
* "url": "http://some-webhook-url.com",
|
||||
* "label": "My Chat Webhook",
|
||||
* "type": "groupChatReceived",
|
||||
* "options": {
|
||||
* "groupId": "required-uuid-of-group"
|
||||
* }
|
||||
* }
|
||||
* @apiParamExample {json} Minimal Example
|
||||
* {
|
||||
* "url": "http://some-webhook-url.com"
|
||||
* }
|
||||
*
|
||||
* @apiSuccess {Object} data The created webhook
|
||||
* @apiSuccess {UUID} data.id The uuid of the webhook
|
||||
* @apiSuccess {String} data.url The url of the webhook
|
||||
* @apiSuccess {String} data.label A label for you to keep track of what this webhooks is for
|
||||
* @apiSuccess {Boolean} data.enabled Whether the webhook should be sent
|
||||
* @apiSuccess {String} data.type The type of the webhook
|
||||
* @apiSuccess {Object} data.options The options for the webhook (See examples)
|
||||
*
|
||||
* @apiError InvalidUUID The `id` was not a valid `UUID`
|
||||
* @apiError InvalidEnable The `enable` param was not a `Boolean` value
|
||||
* @apiError InvalidUrl The `url` param was not valid url
|
||||
* @apiError InvalidWebhookType The `type` param was not a supported Webhook type
|
||||
* @apiError GroupIdIsNotUUID The `options.groupId` param is not a valid UUID for `groupChatReceived` webhook type
|
||||
* @apiError TaskActivityOptionNotBoolean The `options` provided for the `taskActivity` webhook were not of `Boolean` value
|
||||
*/
|
||||
api.addWebhook = {
|
||||
method: 'POST',
|
||||
middlewares: [authWithHeaders()],
|
||||
url: '/user/webhook',
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let webhook = new Webhook(req.body);
|
||||
|
||||
webhook.formatOptions(res);
|
||||
|
||||
user.webhooks.push(webhook);
|
||||
|
||||
await user.save();
|
||||
|
||||
res.respond(201, webhook);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {put} /api/v3/user/webhook/:id Edit a webhook - BETA
|
||||
* @apiName UserUpdateWebhook
|
||||
* @apiGroup Webhook
|
||||
* @apiDescription Can change `url`, `enabled`, `type`, and `options` properties. Cannot change `id`.
|
||||
*
|
||||
* @apiParam {UUID} id URL parameter - The id of the webhook to update
|
||||
* @apiParam {String} [url] Body parameter - The webhook's URL
|
||||
* @apiParam {String} [label] Body parameter - A label to remind you what this webhook does
|
||||
* @apiParam {Boolean} [enabled] Body parameter - If the webhook should be enabled
|
||||
* @apiParam {Sring="taskActivity","groupChatReceived"} [type] Body parameter - The webhook's type.
|
||||
* @apiParam {Object} [options] Body parameter - The webhook's options. Wil differ depending on type. The options are enumerated in the [add webhook examples](#api-Webhook-UserAddWebhook).
|
||||
* @apiParamExample {json} Update Enabled and Type Properties
|
||||
* {
|
||||
* "enabled": false,
|
||||
* "type": "taskActivity"
|
||||
* }
|
||||
* @apiParamExample {json} Update Group Id for Group Chat Receieved Webhook
|
||||
* {
|
||||
* "options": {
|
||||
* "groupId": "new-uuid-of-group"
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* @apiSuccess {Object} data The updated webhook
|
||||
* @apiSuccess {UUID} data.id The uuid of the webhook
|
||||
* @apiSuccess {String} data.url The url of the webhook
|
||||
* @apiSuccess {String} data.label A label for you to keep track of what this webhooks is for
|
||||
* @apiSuccess {Boolean} data.enabled Whether the webhook should be sent
|
||||
* @apiSuccess {String} data.type The type of the webhook
|
||||
* @apiSuccess {Object} data.options The options for the webhook (See webhook add examples)
|
||||
*
|
||||
* @apiError WebhookDoesNotExist A webhook with that `id` does not exist
|
||||
* @apiError InvalidEnable The `enable` param was not a `Boolean` value
|
||||
* @apiError InvalidUrl The `url` param was not valid url
|
||||
* @apiError InvalidWebhookType The `type` param was not a supported Webhook type
|
||||
* @apiError GroupIdIsNotUUID The `options.groupId` param is not a valid UUID for `groupChatReceived` webhook type
|
||||
* @apiError TaskActivityOptionNotBoolean The `options` provided for the `taskActivity` webhook were not of `Boolean` value
|
||||
*
|
||||
*/
|
||||
api.updateWebhook = {
|
||||
method: 'PUT',
|
||||
middlewares: [authWithHeaders()],
|
||||
url: '/user/webhook/:id',
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let id = req.params.id;
|
||||
let webhook = user.webhooks.find(hook => hook.id === id);
|
||||
let { url, label, type, enabled, options } = req.body;
|
||||
|
||||
if (!webhook) {
|
||||
throw new NotFound(res.t('noWebhookWithId', {id}));
|
||||
}
|
||||
|
||||
if (url) {
|
||||
webhook.url = url;
|
||||
}
|
||||
|
||||
if (label) {
|
||||
webhook.label = label;
|
||||
}
|
||||
|
||||
if (type) {
|
||||
webhook.type = type;
|
||||
}
|
||||
|
||||
if (enabled !== undefined) {
|
||||
webhook.enabled = enabled;
|
||||
}
|
||||
|
||||
if (options) {
|
||||
webhook.options = Object.assign(webhook.options, options);
|
||||
}
|
||||
|
||||
webhook.formatOptions(res);
|
||||
|
||||
await user.save();
|
||||
res.respond(200, webhook);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {delete} /api/v3/user/webhook/:id Delete a webhook - BETA
|
||||
* @apiName UserDeleteWebhook
|
||||
* @apiGroup Webhook
|
||||
*
|
||||
* @apiParam {UUID} id The id of the webhook to delete
|
||||
*
|
||||
* @apiSuccess {Array} data The remaining webhooks for the user
|
||||
* @apiError WebhookDoesNotExist A webhook with that `id` does not exist
|
||||
*/
|
||||
api.deleteWebhook = {
|
||||
method: 'DELETE',
|
||||
middlewares: [authWithHeaders()],
|
||||
url: '/user/webhook/:id',
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let id = req.params.id;
|
||||
|
||||
let webhook = user.webhooks.find(hook => hook.id === id);
|
||||
|
||||
if (!webhook) {
|
||||
throw new NotFound(res.t('noWebhookWithId', {id}));
|
||||
}
|
||||
|
||||
removeFromArray(user.webhooks, webhook);
|
||||
|
||||
await user.save();
|
||||
|
||||
res.respond(200, user.webhooks);
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = api;
|
||||
Reference in New Issue
Block a user