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:
Blade Barringer
2016-10-02 09:16:22 -05:00
committed by GitHub
parent 556a7e5229
commit 35b92f13a3
46 changed files with 2044 additions and 527 deletions

View File

@@ -1,7 +1,10 @@
import {
createAndPopulateGroup,
translate as t,
sleep,
server,
} from '../../../../helpers/api-v3-integration.helper';
import { v4 as generateUUID } from 'uuid';
describe('POST /chat', () => {
let user, groupWithChat, userWithChatRevoked, member;
@@ -54,6 +57,44 @@ describe('POST /chat', () => {
expect(message.message.id).to.exist;
});
it('sends group chat received webhooks', async () => {
let userUuid = generateUUID();
let memberUuid = generateUUID();
await server.start();
await user.post('/user/webhook', {
url: `http://localhost:${server.port}/webhooks/${userUuid}`,
type: 'groupChatReceived',
enabled: true,
options: {
groupId: groupWithChat.id,
},
});
await member.post('/user/webhook', {
url: `http://localhost:${server.port}/webhooks/${memberUuid}`,
type: 'groupChatReceived',
enabled: true,
options: {
groupId: groupWithChat.id,
},
});
let message = await user.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage });
await sleep();
await server.close();
let userBody = server.getWebhookData(userUuid);
let memberBody = server.getWebhookData(memberUuid);
[userBody, memberBody].forEach((body) => {
expect(body.group.id).to.eql(groupWithChat._id);
expect(body.group.name).to.eql(groupWithChat.name);
expect(body.chat).to.eql(message.message);
});
});
it('notifies other users of new messages for a guild', async () => {
let message = await user.post(`/groups/${groupWithChat._id}/chat`, { message: testMessage});
let memberWithNotification = await member.get('/user');

View File

@@ -1,7 +1,12 @@
import {
generateUser,
translate as t,
generateGroup,
sleep,
generateChallenge,
server,
} from '../../../../helpers/api-integration/v3';
import { v4 as generateUUID } from 'uuid';
describe('DELETE /tasks/:id', () => {
let user;
@@ -42,6 +47,77 @@ describe('DELETE /tasks/:id', () => {
});
});
context('sending task activity webhooks', () => {
before(async () => {
await server.start();
});
after(async () => {
await server.close();
});
it('sends task activity webhooks if task is user owned', async () => {
let uuid = generateUUID();
let task = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
});
await user.post('/user/webhook', {
url: `http://localhost:${server.port}/webhooks/${uuid}`,
type: 'taskActivity',
enabled: true,
options: {
created: false,
deleted: true,
},
});
await user.del(`/tasks/${task.id}`);
await sleep();
let body = server.getWebhookData(uuid);
expect(body.type).to.eql('deleted');
expect(body.task).to.eql(task);
});
it('does not send task activity webhooks if task is not user owned', async () => {
let uuid = generateUUID();
await user.update({
balance: 10,
});
let guild = await generateGroup(user);
let challenge = await generateChallenge(user, guild);
await user.post('/user/webhook', {
url: `http://localhost:${server.port}/webhooks/${uuid}`,
type: 'taskActivity',
enabled: true,
options: {
created: false,
deleted: true,
},
});
let challengeTask = await user.post(`/tasks/challenge/${challenge._id}`, {
text: 'test habit',
type: 'habit',
});
await user.del(`/tasks/${challengeTask.id}`);
await sleep();
let body = server.getWebhookData(uuid);
expect(body).to.not.exist;
});
});
context('task cannot be deleted', () => {
it('cannot delete a non-existant task', async () => {
await expect(user.del('/tasks/550e8400-e29b-41d4-a716-446655440000')).to.eventually.be.rejected.and.eql({

View File

@@ -1,6 +1,8 @@
import {
generateUser,
sleep,
translate as t,
server,
} from '../../../../helpers/api-integration/v3';
import { v4 as generateUUID } from 'uuid';
@@ -45,6 +47,40 @@ describe('POST /tasks/:id/score/:direction', () => {
message: t('invalidReqParams'),
});
});
it('sends task scored webhooks', async () => {
let uuid = generateUUID();
await server.start();
await user.post('/user/webhook', {
url: `http://localhost:${server.port}/webhooks/${uuid}`,
type: 'taskActivity',
enabled: true,
options: {
created: false,
scored: true,
},
});
let task = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
});
await user.post(`/tasks/${task.id}/score/up`);
await sleep();
await server.close();
let body = server.getWebhookData(uuid);
expect(body.user).to.have.all.keys('_id', '_tmp', 'stats');
expect(body.user.stats).to.have.all.keys('hp', 'mp', 'exp', 'gp', 'lvl', 'class', 'points', 'str', 'con', 'int', 'per', 'buffs', 'training', 'maxHealth', 'maxMP', 'toNextLevel');
expect(body.task.id).to.eql(task.id);
expect(body.direction).to.eql('up');
expect(body.delta).to.be.greaterThan(0);
});
});
context('todos', () => {

View File

@@ -1,13 +1,15 @@
import {
generateUser,
sleep,
translate as t,
server,
} from '../../../../helpers/api-v3-integration.helper';
import { v4 as generateUUID } from 'uuid';
describe('POST /tasks/user', () => {
let user;
before(async () => {
beforeEach(async () => {
user = await generateUser();
});
@@ -205,6 +207,71 @@ describe('POST /tasks/user', () => {
});
});
context('sending task activity webhooks', () => {
before(async () => {
await server.start();
});
after(async () => {
await server.close();
});
it('sends task activity webhooks', async () => {
let uuid = generateUUID();
await user.post('/user/webhook', {
url: `http://localhost:${server.port}/webhooks/${uuid}`,
type: 'taskActivity',
enabled: true,
options: {
created: true,
},
});
let task = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
});
await sleep();
let body = server.getWebhookData(uuid);
expect(body.task).to.eql(task);
});
it('sends a task activity webhook for each task', async () => {
let uuid = generateUUID();
await user.post('/user/webhook', {
url: `http://localhost:${server.port}/webhooks/${uuid}`,
type: 'taskActivity',
enabled: true,
options: {
created: true,
},
});
let tasks = await user.post('/tasks/user', [{
text: 'test habit',
type: 'habit',
}, {
text: 'test todo',
type: 'todo',
}]);
await sleep();
let taskBodies = [
server.getWebhookData(uuid),
server.getWebhookData(uuid),
];
expect(taskBodies.find(body => body.task.id === tasks[0].id)).to.exist;
expect(taskBodies.find(body => body.task.id === tasks[1].id)).to.exist;
});
});
context('all types', () => {
it('can create reminders', async () => {
let id1 = generateUUID();

View File

@@ -3,6 +3,7 @@ import {
generateGroup,
sleep,
generateChallenge,
server,
} from '../../../../helpers/api-integration/v3';
import { v4 as generateUUID } from 'uuid';
@@ -145,6 +146,81 @@ describe('PUT /tasks/:id', () => {
});
});
context('sending task activity webhooks', () => {
before(async () => {
await server.start();
});
after(async () => {
await server.close();
});
it('sends task activity webhooks if task is user owned', async () => {
let uuid = generateUUID();
await user.post('/user/webhook', {
url: `http://localhost:${server.port}/webhooks/${uuid}`,
type: 'taskActivity',
enabled: true,
options: {
created: false,
updated: true,
},
});
let task = await user.post('/tasks/user', {
text: 'test habit',
type: 'habit',
});
let updatedTask = await user.put(`/tasks/${task.id}`, {
text: 'updated text',
});
await sleep();
let body = server.getWebhookData(uuid);
expect(body.type).to.eql('updated');
expect(body.task).to.eql(updatedTask);
});
it('does not send task activity webhooks if task is not user owned', async () => {
let uuid = generateUUID();
await user.update({
balance: 10,
});
let guild = await generateGroup(user);
let challenge = await generateChallenge(user, guild);
await user.post('/user/webhook', {
url: `http://localhost:${server.port}/webhooks/${uuid}`,
type: 'taskActivity',
enabled: true,
options: {
created: false,
updated: true,
},
});
let task = await user.post(`/tasks/challenge/${challenge._id}`, {
text: 'test habit',
type: 'habit',
});
await user.put(`/tasks/${task.id}`, {
text: 'updated text',
});
await sleep();
let body = server.getWebhookData(uuid);
expect(body).to.not.exist;
});
});
context('all types', () => {
let daily;

View File

@@ -1,23 +0,0 @@
import {
generateUser,
} from '../../../../helpers/api-integration/v3';
let user;
let endpoint = '/user/webhook';
describe('DELETE /user/webhook', () => {
beforeEach(async () => {
user = await generateUser();
});
it('succeeds', async () => {
let id = 'some-id';
user.preferences.webhooks[id] = { url: 'http://some-url.com', enabled: true };
await user.sync();
expect(user.preferences.webhooks).to.eql({});
let response = await user.del(`${endpoint}/${id}`);
expect(response).to.eql({});
await user.sync();
expect(user.preferences.webhooks).to.eql({});
});
});

View File

@@ -13,12 +13,19 @@ describe('GET /user/anonymized', () => {
before(async () => {
user = await generateUser();
await user.update({ newMessages: ['some', 'new', 'messages'], 'profile.name': 'profile', 'purchased.plan': 'purchased plan',
contributor: 'contributor', invitations: 'invitations', 'items.special.nyeReceived': 'some', 'items.special.valentineReceived': 'some',
webhooks: 'some', 'achievements.challenges': 'some',
'inbox.messages': [{ text: 'some text' }],
tags: [{ name: 'some name', challenge: 'some challenge' }],
});
await user.update({
newMessages: ['some', 'new', 'messages'],
'profile.name': 'profile',
'purchased.plan': 'purchased plan',
contributor: 'contributor',
invitations: 'invitations',
'items.special.nyeReceived': 'some',
'items.special.valentineReceived': 'some',
webhooks: [{url: 'https://somurl.com'}],
'achievements.challenges': 'some',
'inbox.messages': [{ text: 'some text' }],
tags: [{ name: 'some name', challenge: 'some challenge' }],
});
await generateHabit({ userId: user._id });
await generateHabit({ userId: user._id, text: generateUUID() });

View File

@@ -1,29 +0,0 @@
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
let user;
let endpoint = '/user/webhook';
describe('POST /user/webhook', () => {
beforeEach(async () => {
user = await generateUser();
});
it('validates', async () => {
await expect(user.post(endpoint, { enabled: true })).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('invalidUrl'),
});
});
it('successfully adds the webhook', async () => {
expect(user.preferences.webhooks).to.eql({});
let response = await user.post(endpoint, { enabled: true, url: 'http://some-url.com'});
expect(response.id).to.exist;
await user.sync();
expect(user.preferences.webhooks).to.not.eql({});
});
});

View File

@@ -37,6 +37,7 @@ describe('PUT /user', () => {
subscriptions: {'purchased.plan.extraMonths': 500, 'purchased.plan.consecutive.trinkets': 1000},
'customization gem purchases': {'purchased.background.tavern': true, 'purchased.skin.bear': true},
notifications: [{type: 123}],
webhooks: {webhooks: [{url: 'https://foobar.com'}]},
};
each(protectedOperations, (data, testName) => {

View File

@@ -1,32 +0,0 @@
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
let user;
let url = 'http://new-url.com';
let enabled = true;
describe('PUT /user/webhook/:id', () => {
beforeEach(async () => {
user = await generateUser();
});
it('validation fails', async () => {
await expect(user.put('/user/webhook/some-id'), { enabled: true }).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('invalidUrl'),
});
});
it('succeeds', async () => {
let response = await user.post('/user/webhook', { enabled: true, url: 'http://some-url.com'});
await user.sync();
expect(user.preferences.webhooks[response.id].url).to.not.eql(url);
let response2 = await user.put(`/user/webhook/${response.id}`, {url, enabled});
expect(response2.url).to.eql(url);
await user.sync();
expect(user.preferences.webhooks[response.id].url).to.eql(url);
});
});

View File

@@ -0,0 +1,54 @@
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
let user, webhookToDelete;
let endpoint = '/user/webhook';
describe('DELETE /user/webhook', () => {
beforeEach(async () => {
user = await generateUser();
webhookToDelete = await user.post('/user/webhook', {
url: 'http://some-url.com',
enabled: true,
});
await user.post('/user/webhook', {
url: 'http://some-other-url.com',
enabled: false,
});
await user.sync();
});
it('deletes a webhook', async () => {
expect(user.webhooks).to.have.a.lengthOf(2);
await user.del(`${endpoint}/${webhookToDelete.id}`);
await user.sync();
expect(user.webhooks).to.have.a.lengthOf(1);
});
it('returns the remaining webhooks', async () => {
let [remainingWebhook] = await user.del(`${endpoint}/${webhookToDelete.id}`);
await user.sync();
let webhook = user.webhooks[0];
expect(remainingWebhook.id).to.eql(webhook.id);
expect(remainingWebhook.url).to.eql(webhook.url);
expect(remainingWebhook.type).to.eql(webhook.type);
expect(remainingWebhook.options).to.eql(webhook.options);
});
it('returns an error if webhook with id does not exist', async () => {
await expect(user.del(`${endpoint}/id-that-does-not-exist`)).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
message: t('noWebhookWithId', {id: 'id-that-does-not-exist'}),
});
});
});

View File

@@ -0,0 +1,211 @@
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
import { v4 as generateUUID } from 'uuid';
describe('POST /user/webhook', () => {
let user, body;
beforeEach(async () => {
user = await generateUser();
body = {
id: generateUUID(),
url: 'https://example.com/endpoint',
type: 'taskActivity',
enabled: false,
};
});
it('requires a url', async () => {
delete body.url;
await expect(user.post('/user/webhook', body)).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: 'User validation failed',
});
});
it('requires custom id to be a uuid', async () => {
body.id = 'not-a-uuid';
await expect(user.post('/user/webhook', body)).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: 'User validation failed',
});
});
it('defaults id to a uuid', async () => {
delete body.id;
let webhook = await user.post('/user/webhook', body);
expect(webhook.id).to.exist;
});
it('requires type to be of an accetable type', async () => {
body.type = 'not a valid type';
await expect(user.post('/user/webhook', body)).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: 'User validation failed',
});
});
it('defaults enabled to true', async () => {
delete body.enabled;
let webhook = await user.post('/user/webhook', body);
expect(webhook.enabled).to.be.true;
});
it('can pass a label', async () => {
body.label = 'Custom Label';
let webhook = await user.post('/user/webhook', body);
expect(webhook.label).to.equal('Custom Label');
});
it('defaults type to taskActivity', async () => {
delete body.type;
let webhook = await user.post('/user/webhook', body);
expect(webhook.type).to.eql('taskActivity');
});
it('successfully adds the webhook', async () => {
expect(user.webhooks).to.eql([]);
let response = await user.post('/user/webhook', body);
expect(response.id).to.eql(body.id);
expect(response.type).to.eql(body.type);
expect(response.url).to.eql(body.url);
expect(response.enabled).to.eql(body.enabled);
await user.sync();
expect(user.webhooks).to.not.eql([]);
let webhook = user.webhooks[0];
expect(webhook.enabled).to.be.false;
expect(webhook.type).to.eql('taskActivity');
expect(webhook.url).to.eql(body.url);
});
it('defaults taskActivity options', async () => {
body.type = 'taskActivity';
let webhook = await user.post('/user/webhook', body);
expect(webhook.options).to.eql({
created: false,
updated: false,
deleted: false,
scored: true,
});
});
it('can set taskActivity options', async () => {
body.type = 'taskActivity';
body.options = {
created: true,
updated: true,
deleted: true,
scored: false,
};
let webhook = await user.post('/user/webhook', body);
expect(webhook.options).to.eql({
created: true,
updated: true,
deleted: true,
scored: false,
});
});
it('discards extra properties in taskActivity options', async () => {
body.type = 'taskActivity';
body.options = {
created: true,
updated: true,
deleted: true,
scored: false,
foo: 'bar',
};
let webhook = await user.post('/user/webhook', body);
expect(webhook.options.foo).to.not.exist;
expect(webhook.options).to.eql({
created: true,
updated: true,
deleted: true,
scored: false,
});
});
['created', 'updated', 'deleted', 'scored'].forEach((option) => {
it(`requires taskActivity option ${option} to be a boolean`, async () => {
body.type = 'taskActivity';
body.options = {
[option]: 'not a boolean',
};
await expect(user.post('/user/webhook', body)).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('webhookBooleanOption', { option }),
});
});
});
it('can set groupChatReceived options', async () => {
body.type = 'groupChatReceived';
body.options = {
groupId: generateUUID(),
};
let webhook = await user.post('/user/webhook', body);
expect(webhook.options).to.eql({
groupId: body.options.groupId,
});
});
it('groupChatReceived options requires a uuid for the groupId', async () => {
body.type = 'groupChatReceived';
body.options = {
groupId: 'not-a-uuid',
};
await expect(user.post('/user/webhook', body)).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('groupIdRequired'),
});
});
it('discards extra properties in groupChatReceived options', async () => {
body.type = 'groupChatReceived';
body.options = {
groupId: generateUUID(),
foo: 'bar',
};
let webhook = await user.post('/user/webhook', body);
expect(webhook.options.foo).to.not.exist;
expect(webhook.options).to.eql({
groupId: body.options.groupId,
});
});
});

View File

@@ -0,0 +1,132 @@
import {
generateUser,
translate as t,
} from '../../../../helpers/api-integration/v3';
import { v4 as generateUUID} from 'uuid';
describe('PUT /user/webhook/:id', () => {
let user, webhookToUpdate;
beforeEach(async () => {
user = await generateUser();
webhookToUpdate = await user.post('/user/webhook', {
url: 'http://some-url.com',
label: 'Original Label',
enabled: true,
type: 'taskActivity',
options: { created: true, scored: true },
});
await user.post('/user/webhook', {
url: 'http://some-other-url.com',
enabled: false,
});
await user.sync();
});
it('returns an error if webhook with id does not exist', async () => {
await expect(user.put('/user/webhook/id-that-does-not-exist')).to.eventually.be.rejected.and.eql({
code: 404,
error: 'NotFound',
message: t('noWebhookWithId', {id: 'id-that-does-not-exist'}),
});
});
it('returns an error if validation fails', async () => {
await expect(user.put(`/user/webhook/${webhookToUpdate.id}`, { url: 'foo', enabled: true })).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: 'User validation failed',
});
});
it('updates a webhook', async () => {
let url = 'http://a-new-url.com';
let type = 'groupChatReceived';
let label = 'New Label';
let options = { groupId: generateUUID() };
await user.put(`/user/webhook/${webhookToUpdate.id}`, {url, type, options, label});
await user.sync();
let webhook = user.webhooks.find(hook => webhookToUpdate.id === hook.id);
expect(webhook.url).to.equal(url);
expect(webhook.label).to.equal(label);
expect(webhook.type).to.equal(type);
expect(webhook.options).to.eql(options);
});
it('returns the updated webhook', async () => {
let url = 'http://a-new-url.com';
let type = 'groupChatReceived';
let options = { groupId: generateUUID() };
let response = await user.put(`/user/webhook/${webhookToUpdate.id}`, {url, type, options});
expect(response.url).to.eql(url);
expect(response.type).to.eql(type);
expect(response.options).to.eql(options);
});
it('cannot update the id', async () => {
let id = generateUUID();
let url = 'http://a-new-url.com';
await user.put(`/user/webhook/${webhookToUpdate.id}`, {url, id});
await user.sync();
let webhook = user.webhooks.find(hook => webhookToUpdate.id === hook.id);
expect(webhook.id).to.eql(webhookToUpdate.id);
expect(webhook.url).to.eql(url);
});
it('can update taskActivity options', async () => {
let type = 'taskActivity';
let options = {
updated: false,
deleted: true,
};
let webhook = await user.put(`/user/webhook/${webhookToUpdate.id}`, {type, options});
expect(webhook.options).to.eql({
created: true, // starting value
updated: false,
deleted: true,
scored: true, // default value
});
});
it('errors if taskActivity option is not a boolean', async () => {
let type = 'taskActivity';
let options = {
created: 'not a boolean',
updated: false,
deleted: true,
};
await expect(user.put(`/user/webhook/${webhookToUpdate.id}`, {type, options})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('webhookBooleanOption', { option: 'created' }),
});
});
it('errors if groupChatRecieved groupId option is not a uuid', async () => {
let type = 'groupChatReceived';
let options = {
groupId: 'not-a-uuid',
};
await expect(user.put(`/user/webhook/${webhookToUpdate.id}`, {type, options})).to.eventually.be.rejected.and.eql({
code: 400,
error: 'BadRequest',
message: t('groupIdRequired'),
});
});
});

View File

@@ -1,135 +1,376 @@
import request from 'request';
import { sendTaskWebhook } from '../../../../../website/server/libs/webhook';
import {
WebhookSender,
taskScoredWebhook,
groupChatReceivedWebhook,
taskActivityWebhook,
} from '../../../../../website/server/libs/webhook';
describe('webhooks', () => {
let webhooks;
beforeEach(() => {
sandbox.stub(request, 'post');
webhooks = [{
id: 'taskActivity',
url: 'http://task-scored.com',
enabled: true,
type: 'taskActivity',
options: {
created: true,
updated: true,
deleted: true,
scored: true,
},
}, {
id: 'groupChatReceived',
url: 'http://group-chat-received.com',
enabled: true,
type: 'groupChatReceived',
options: {
groupId: 'group-id',
},
}];
});
afterEach(() => {
sandbox.restore();
});
describe('sendTaskWebhook', () => {
let task = {
details: { _id: 'task-id' },
delta: 1.4,
direction: 'up',
};
describe('WebhookSender', () => {
it('creates a new WebhookSender object', () => {
let sendWebhook = new WebhookSender({
type: 'custom',
});
let data = {
task,
user: { _id: 'user-id' },
};
expect(sendWebhook.type).to.equal('custom');
expect(sendWebhook).to.respondTo('send');
});
it('does not send if no webhook endpoints exist', () => {
let webhooks = { };
it('provides default function for data transformation', () => {
sandbox.spy(WebhookSender, 'defaultTransformData');
let sendWebhook = new WebhookSender({
type: 'custom',
});
sendTaskWebhook(webhooks, data);
let body = { foo: 'bar' };
sendWebhook.send([{id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom'}], body);
expect(WebhookSender.defaultTransformData).to.be.calledOnce;
expect(request.post).to.be.calledOnce;
expect(request.post).to.be.calledWithMatch({
body,
});
});
it('can pass in a data transformation function', () => {
sandbox.spy(WebhookSender, 'defaultTransformData');
let sendWebhook = new WebhookSender({
type: 'custom',
transformData (data) {
let dataToSend = Object.assign({baz: 'biz'}, data);
return dataToSend;
},
});
let body = { foo: 'bar' };
sendWebhook.send([{id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom'}], body);
expect(WebhookSender.defaultTransformData).to.not.be.called;
expect(request.post).to.be.calledOnce;
expect(request.post).to.be.calledWithMatch({
body: {
foo: 'bar',
baz: 'biz',
},
});
});
it('provieds a default filter function', () => {
sandbox.spy(WebhookSender, 'defaultWebhookFilter');
let sendWebhook = new WebhookSender({
type: 'custom',
});
let body = { foo: 'bar' };
sendWebhook.send([{id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom'}], body);
expect(WebhookSender.defaultWebhookFilter).to.be.calledOnce;
});
it('can pass in a webhook filter function', () => {
sandbox.spy(WebhookSender, 'defaultWebhookFilter');
let sendWebhook = new WebhookSender({
type: 'custom',
webhookFilter (hook) {
return hook.url !== 'http://custom-url.com';
},
});
let body = { foo: 'bar' };
sendWebhook.send([{id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom'}], body);
expect(WebhookSender.defaultWebhookFilter).to.not.be.called;
expect(request.post).to.not.be.called;
});
it('does not send if no webhooks are enabled', () => {
let webhooks = {
'some-id': {
sort: 0,
id: 'some-id',
enabled: false,
url: 'http://example.org/endpoint',
it('can pass in a webhook filter function that filters on data', () => {
sandbox.spy(WebhookSender, 'defaultWebhookFilter');
let sendWebhook = new WebhookSender({
type: 'custom',
webhookFilter (hook, data) {
return hook.options.foo === data.foo;
},
};
});
sendTaskWebhook(webhooks, data);
let body = { foo: 'bar' };
expect(request.post).to.not.be.called;
});
it('does not send if webhook url is not valid', () => {
let webhooks = {
'some-id': {
sort: 0,
id: 'some-id',
enabled: true,
url: 'http://malformedurl/endpoint',
},
};
sendTaskWebhook(webhooks, data);
expect(request.post).to.not.be.called;
});
it('sends task direction, task, task delta, and abridged user data', () => {
let webhooks = {
'some-id': {
sort: 0,
id: 'some-id',
enabled: true,
url: 'http://example.org/endpoint',
},
};
sendTaskWebhook(webhooks, data);
sendWebhook.send([
{ id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom', options: { foo: 'bar' }},
{ id: 'other-custom-webhook', url: 'http://other-custom-url.com', enabled: true, type: 'custom', options: { foo: 'foo' }},
], body);
expect(request.post).to.be.calledOnce;
expect(request.post).to.be.calledWith({
url: 'http://example.org/endpoint',
body: {
direction: 'up',
task: { _id: 'task-id' },
delta: 1.4,
user: {
_id: 'user-id',
},
},
expect(request.post).to.be.calledWithMatch({
url: 'http://custom-url.com',
});
});
it('ignores disabled webhooks', () => {
let sendWebhook = new WebhookSender({
type: 'custom',
});
let body = { foo: 'bar' };
sendWebhook.send([{id: 'custom-webhook', url: 'http://custom-url.com', enabled: false, type: 'custom'}], body);
expect(request.post).to.not.be.called;
});
it('ignores webhooks with invalid urls', () => {
let sendWebhook = new WebhookSender({
type: 'custom',
});
let body = { foo: 'bar' };
sendWebhook.send([{id: 'custom-webhook', url: 'httxp://custom-url!!', enabled: true, type: 'custom'}], body);
expect(request.post).to.not.be.called;
});
it('ignores webhooks of other types', () => {
let sendWebhook = new WebhookSender({
type: 'custom',
});
let body = { foo: 'bar' };
sendWebhook.send([
{ id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom'},
{ id: 'other-webhook', url: 'http://other-url.com', enabled: true, type: 'other'},
], body);
expect(request.post).to.be.calledOnce;
expect(request.post).to.be.calledWithMatch({
url: 'http://custom-url.com',
body,
json: true,
});
});
it('sends a post request for each webhook endpoint', () => {
let webhooks = {
'some-id': {
sort: 0,
id: 'some-id',
enabled: true,
url: 'http://example.org/endpoint',
},
'second-webhook': {
sort: 1,
id: 'second-webhook',
enabled: true,
url: 'http://example.com/2/endpoint',
},
};
it('sends multiple webhooks of the same type', () => {
let sendWebhook = new WebhookSender({
type: 'custom',
});
sendTaskWebhook(webhooks, data);
let body = { foo: 'bar' };
sendWebhook.send([
{ id: 'custom-webhook', url: 'http://custom-url.com', enabled: true, type: 'custom'},
{ id: 'other-custom-webhook', url: 'http://other-url.com', enabled: true, type: 'custom'},
], body);
expect(request.post).to.be.calledTwice;
expect(request.post).to.be.calledWith({
url: 'http://example.org/endpoint',
body: {
direction: 'up',
task: { _id: 'task-id' },
delta: 1.4,
user: {
_id: 'user-id',
},
},
expect(request.post).to.be.calledWithMatch({
url: 'http://custom-url.com',
body,
json: true,
});
expect(request.post).to.be.calledWith({
url: 'http://example.com/2/endpoint',
body: {
direction: 'up',
task: { _id: 'task-id' },
delta: 1.4,
user: {
_id: 'user-id',
},
},
expect(request.post).to.be.calledWithMatch({
url: 'http://other-url.com',
body,
json: true,
});
});
});
describe('taskScoredWebhook', () => {
let data;
beforeEach(() => {
data = {
user: {
_id: 'user-id',
_tmp: {foo: 'bar'},
stats: {
lvl: 5,
int: 10,
str: 5,
exp: 423,
toJSON () {
return this;
},
},
addComputedStatsToJSONObj () {
let mockStats = Object.assign({
maxHealth: 50,
maxMP: 103,
toNextLevel: 40,
}, this.stats);
delete mockStats.toJSON;
return mockStats;
},
},
task: {
text: 'text',
},
direction: 'up',
delta: 176,
};
});
it('sends task and stats data', () => {
taskScoredWebhook.send(webhooks, data);
expect(request.post).to.be.calledOnce;
expect(request.post).to.be.calledWithMatch({
body: {
type: 'scored',
user: {
_id: 'user-id',
_tmp: {foo: 'bar'},
stats: {
lvl: 5,
int: 10,
str: 5,
exp: 423,
toNextLevel: 40,
maxHealth: 50,
maxMP: 103,
},
},
task: {
text: 'text',
},
direction: 'up',
delta: 176,
},
});
});
it('does not send task scored data if scored option is not true', () => {
webhooks[0].options.scored = false;
taskScoredWebhook.send(webhooks, data);
expect(request.post).to.not.be.called;
});
});
describe('taskActivityWebhook', () => {
let data;
beforeEach(() => {
data = {
task: {
text: 'text',
},
};
});
['created', 'updated', 'deleted'].forEach((type) => {
it(`sends ${type} tasks`, () => {
data.type = type;
taskActivityWebhook.send(webhooks, data);
expect(request.post).to.be.calledOnce;
expect(request.post).to.be.calledWithMatch({
body: {
type,
task: data.task,
},
});
});
it(`does not send task ${type} data if ${type} option is not true`, () => {
data.type = type;
webhooks[0].options[type] = false;
taskActivityWebhook.send(webhooks, data);
expect(request.post).to.not.be.called;
});
});
});
describe('groupChatReceivedWebhook', () => {
it('sends chat data', () => {
let data = {
group: {
id: 'group-id',
name: 'some group',
otherData: 'foo',
},
chat: {
id: 'some-id',
text: 'message',
},
};
groupChatReceivedWebhook.send(webhooks, data);
expect(request.post).to.be.calledOnce;
expect(request.post).to.be.calledWithMatch({
body: {
group: {
id: 'group-id',
name: 'some group',
},
chat: {
id: 'some-id',
text: 'message',
},
},
});
});
it('does not send chat data for group if not selected', () => {
let data = {
group: {
id: 'not-group-id',
name: 'some group',
otherData: 'foo',
},
chat: {
id: 'some-id',
text: 'message',
},
};
groupChatReceivedWebhook.send(webhooks, data);
expect(request.post).to.not.be.called;
});
});
});

View File

@@ -3,9 +3,11 @@ import { model as Group, INVITES_LIMIT } from '../../../../../website/server/mod
import { model as User } from '../../../../../website/server/models/user';
import { BadRequest } from '../../../../../website/server/libs/errors';
import { quests as questScrolls } from '../../../../../website/common/script/content';
import { groupChatReceivedWebhook } from '../../../../../website/server/libs/webhook';
import * as email from '../../../../../website/server/libs/email';
import validator from 'validator';
import { TAVERN_ID } from '../../../../../website/common/script/';
import { v4 as generateUUID } from 'uuid';
describe('Group Model', () => {
let party, questLeader, participatingMember, nonParticipatingMember, undecidedMember;
@@ -1217,5 +1219,163 @@ describe('Group Model', () => {
});
});
});
describe('sendGroupChatReceivedWebhooks', () => {
beforeEach(() => {
sandbox.stub(groupChatReceivedWebhook, 'send');
});
it('looks for users in specified guild with webhooks', () => {
sandbox.spy(User, 'find');
let guild = new Group({
type: 'guild',
});
guild.sendGroupChatReceivedWebhooks({});
expect(User.find).to.be.calledWith({
webhooks: {
$elemMatch: {
type: 'groupChatReceived',
'options.groupId': guild._id,
},
},
guilds: guild._id,
});
});
it('looks for users in specified party with webhooks', () => {
sandbox.spy(User, 'find');
party.sendGroupChatReceivedWebhooks({});
expect(User.find).to.be.calledWith({
webhooks: {
$elemMatch: {
type: 'groupChatReceived',
'options.groupId': party._id,
},
},
'party._id': party._id,
});
});
it('sends webhooks for users with webhooks', async () => {
let guild = new Group({
name: 'some guild',
type: 'guild',
});
let chat = {message: 'text'};
let memberWithWebhook = new User({
guilds: [guild._id],
webhooks: [{
type: 'groupChatReceived',
url: 'http://someurl.com',
options: {
groupId: guild._id,
},
}],
});
let memberWithoutWebhook = new User({
guilds: [guild._id],
});
let nonMemberWithWebhooks = new User({
webhooks: [{
type: 'groupChatReceived',
url: 'http://a-different-url.com',
options: {
groupId: generateUUID(),
},
}],
});
await Promise.all([
memberWithWebhook.save(),
memberWithoutWebhook.save(),
nonMemberWithWebhooks.save(),
]);
guild.leader = memberWithWebhook._id;
await guild.save();
guild.sendGroupChatReceivedWebhooks(chat);
await sleep();
expect(groupChatReceivedWebhook.send).to.be.calledOnce;
let args = groupChatReceivedWebhook.send.args[0];
let webhooks = args[0];
let options = args[1];
expect(webhooks).to.have.a.lengthOf(1);
expect(webhooks[0].id).to.eql(memberWithWebhook.webhooks[0].id);
expect(options.group).to.eql(guild);
expect(options.chat).to.eql(chat);
});
it('sends webhooks for each user with webhooks in group', async () => {
let guild = new Group({
name: 'some guild',
type: 'guild',
});
let chat = {message: 'text'};
let memberWithWebhook = new User({
guilds: [guild._id],
webhooks: [{
type: 'groupChatReceived',
url: 'http://someurl.com',
options: {
groupId: guild._id,
},
}],
});
let memberWithWebhook2 = new User({
guilds: [guild._id],
webhooks: [{
type: 'groupChatReceived',
url: 'http://another-member.com',
options: {
groupId: guild._id,
},
}],
});
let memberWithWebhook3 = new User({
guilds: [guild._id],
webhooks: [{
type: 'groupChatReceived',
url: 'http://a-third-member.com',
options: {
groupId: guild._id,
},
}],
});
await Promise.all([
memberWithWebhook.save(),
memberWithWebhook2.save(),
memberWithWebhook3.save(),
]);
guild.leader = memberWithWebhook._id;
await guild.save();
guild.sendGroupChatReceivedWebhooks(chat);
await sleep();
expect(groupChatReceivedWebhook.send).to.be.calledThrice;
let args = groupChatReceivedWebhook.send.args;
expect(args.find(arg => arg[0][0].id === memberWithWebhook.webhooks[0].id)).to.be.exist;
expect(args.find(arg => arg[0][0].id === memberWithWebhook2.webhooks[0].id)).to.be.exist;
expect(args.find(arg => arg[0][0].id === memberWithWebhook3.webhooks[0].id)).to.be.exist;
});
});
});
});

View File

@@ -40,7 +40,7 @@ describe('User Model', () => {
expect(userToJSON.stats.maxHealth).to.not.exist;
expect(userToJSON.stats.toNextLevel).to.not.exist;
user.addComputedStatsToJSONObj(userToJSON);
user.addComputedStatsToJSONObj(userToJSON.stats);
expect(userToJSON.stats.maxMP).to.exist;
expect(userToJSON.stats.maxHealth).to.equal(common.maxHealth);

View File

@@ -0,0 +1,146 @@
import { model as Webhook } from '../../../../../website/server/models/webhook';
import { BadRequest } from '../../../../../website/server/libs/errors';
import { v4 as generateUUID } from 'uuid';
describe('Webhook Model', () => {
context('Instance Methods', () => {
describe('#formatOptions', () => {
let res;
beforeEach(() => {
res = {
t: sandbox.spy(),
};
});
context('type is taskActivity', () => {
let config;
beforeEach(() => {
config = {
type: 'taskActivity',
url: 'https//exmaple.com/endpoint',
options: {
created: true,
updated: true,
deleted: true,
scored: true,
},
};
});
it('it provides default values for options', () => {
delete config.options;
let wh = new Webhook(config);
wh.formatOptions(res);
expect(wh.options).to.eql({
created: false,
updated: false,
deleted: false,
scored: true,
});
});
it('provides missing task options', () => {
delete config.options.created;
let wh = new Webhook(config);
wh.formatOptions(res);
expect(wh.options).to.eql({
created: false,
updated: true,
deleted: true,
scored: true,
});
});
it('discards additional options', () => {
config.options.foo = 'another option';
let wh = new Webhook(config);
wh.formatOptions(res);
expect(wh.options.foo).to.not.exist;
expect(wh.options).to.eql({
created: true,
updated: true,
deleted: true,
scored: true,
});
});
['created', 'updated', 'deleted', 'scored'].forEach((option) => {
it(`validates that ${option} is a boolean`, (done) => {
config.options[option] = 'not a boolean';
try {
let wh = new Webhook(config);
wh.formatOptions(res);
} catch (err) {
expect(err).to.be.an.instanceOf(BadRequest);
expect(res.t).to.be.calledOnce;
expect(res.t).to.be.calledWith('webhookBooleanOption', { option });
done();
}
});
});
});
context('type is groupChatReceived', () => {
let config;
beforeEach(() => {
config = {
type: 'groupChatReceived',
url: 'https//exmaple.com/endpoint',
options: {
groupId: generateUUID(),
},
};
});
it('creates options', () => {
let wh = new Webhook(config);
wh.formatOptions(res);
expect(wh.options).to.eql(config.options);
});
it('discards additional objects', () => {
config.options.foo = 'another thing';
let wh = new Webhook(config);
wh.formatOptions(res);
expect(wh.options.foo).to.not.exist;
expect(wh.options).to.eql({
groupId: config.options.groupId,
});
});
it('requires groupId option to be a uuid', (done) => {
config.options.groupId = 'not a uuid';
try {
let wh = new Webhook(config);
wh.formatOptions(res);
} catch (err) {
expect(err).to.be.an.instanceOf(BadRequest);
expect(res.t).to.be.calledOnce;
expect(res.t).to.be.calledWith('groupIdRequired');
done();
}
});
});
});
});
});