Files
habitica/website/server/controllers/api-v3/quests.js
Phillip Thelen 98f9d2a8f4 Update to new method for fcm (#15238)
* begin moving to new fcm library

* Add error handling

* Add opening notification to correct screen

* Fix tests and make async

* lint fix

* Rename pushNotificationstest..js to pushNotifications.test.js

* fix(potions): remove Fungi Potion time banner

* 5.24.3

* update(content): add 2024-06 content prebuild (#15231)

* update sprites

* add 2024-06 content

* add 2024-06 enchanted armoire items

* update sprites

* update sprites

* fix errors found in testing

* Fix liveliness probes being rate limited (#15236)

* Do not rate limit any liveliness probes

* update example config

* Translated using Weblate (German)

Currently translated at 96.2% (181 of 188 strings)

Translated using Weblate (Japanese)

Currently translated at 99.4% (769 of 773 strings)

Translated using Weblate (German)

Currently translated at 93.6% (176 of 188 strings)

Translated using Weblate (Japanese)

Currently translated at 96.2% (2972 of 3089 strings)

Translated using Weblate (Japanese)

Currently translated at 100.0% (232 of 232 strings)

Translated using Weblate (Japanese)

Currently translated at 96.8% (841 of 868 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (94 of 94 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (113 of 113 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (131 of 131 strings)

Translated using Weblate (Japanese)

Currently translated at 100.0% (286 of 286 strings)

Translated using Weblate (German)

Currently translated at 86.7% (163 of 188 strings)

Translated using Weblate (German)

Currently translated at 85.1% (160 of 188 strings)

Translated using Weblate (German)

Currently translated at 84.0% (158 of 188 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (94 of 94 strings)

Translated using Weblate (German)

Currently translated at 83.5% (157 of 188 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (113 of 113 strings)

Translated using Weblate (German)

Currently translated at 82.9% (156 of 188 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (113 of 113 strings)

Translated using Weblate (German)

Currently translated at 81.9% (154 of 188 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (113 of 113 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (8 of 8 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (8 of 8 strings)

Translated using Weblate (Chinese (Simplified))

Currently translated at 100.0% (188 of 188 strings)

Translated using Weblate (German)

Currently translated at 79.2% (149 of 188 strings)

Translated using Weblate (Chinese (Simplified))

Currently translated at 100.0% (189 of 189 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (8 of 8 strings)

Translated using Weblate (German)

Currently translated at 90.6% (2799 of 3089 strings)

Translated using Weblate (German)

Currently translated at 77.6% (146 of 188 strings)

Translated using Weblate (German)

Currently translated at 90.5% (2797 of 3089 strings)

Translated using Weblate (German)

Currently translated at 90.4% (2794 of 3089 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (131 of 131 strings)

Translated using Weblate (German)

Currently translated at 90.1% (2786 of 3089 strings)

Translated using Weblate (Chinese (Simplified))

Currently translated at 100.0% (188 of 188 strings)

Translated using Weblate (German)

Currently translated at 77.1% (145 of 188 strings)

Translated using Weblate (Chinese (Simplified))

Currently translated at 98.7% (763 of 773 strings)

Translated using Weblate (Chinese (Simplified))

Currently translated at 100.0% (868 of 868 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (131 of 131 strings)

Translated using Weblate (Spanish)

Currently translated at 100.0% (286 of 286 strings)

Translated using Weblate (German)

Currently translated at 90.0% (2782 of 3089 strings)

Translated using Weblate (Spanish)

Currently translated at 100.0% (773 of 773 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (378 of 378 strings)

Translated using Weblate (Spanish)

Currently translated at 100.0% (868 of 868 strings)

Translated using Weblate (Spanish)

Currently translated at 100.0% (167 of 167 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (259 of 259 strings)

Translated using Weblate (Japanese)

Currently translated at 100.0% (259 of 259 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (131 of 131 strings)

Translated using Weblate (Chinese (Simplified))

Currently translated at 100.0% (286 of 286 strings)

Translated using Weblate (Chinese (Simplified))

Currently translated at 100.0% (239 of 239 strings)

Translated using Weblate (Chinese (Simplified))

Currently translated at 100.0% (188 of 188 strings)

Translated using Weblate (French)

Currently translated at 100.0% (188 of 188 strings)

Translated using Weblate (German)

Currently translated at 75.0% (141 of 188 strings)

Translated using Weblate (Spanish)

Currently translated at 99.0% (766 of 773 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (189 of 189 strings)

Translated using Weblate (Chinese (Simplified))

Currently translated at 100.0% (868 of 868 strings)

Translated using Weblate (Japanese)

Currently translated at 98.8% (764 of 773 strings)

Translated using Weblate (Japanese)

Currently translated at 99.6% (258 of 259 strings)

Translated using Weblate (Japanese)

Currently translated at 100.0% (378 of 378 strings)

Translated using Weblate (Japanese)

Currently translated at 100.0% (188 of 188 strings)

Translated using Weblate (Chinese (Simplified))

Currently translated at 100.0% (140 of 140 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (131 of 131 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (286 of 286 strings)

Translated using Weblate (Ukrainian)

Currently translated at 62.5% (1931 of 3089 strings)

Translated using Weblate (German)

Currently translated at 89.8% (2777 of 3089 strings)

Translated using Weblate (French)

Currently translated at 100.0% (188 of 188 strings)

Translated using Weblate (Chinese (Simplified))

Currently translated at 98.5% (762 of 773 strings)

Translated using Weblate (Chinese (Simplified))

Currently translated at 100.0% (868 of 868 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (286 of 286 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (286 of 286 strings)

Translated using Weblate (French)

Currently translated at 82.9% (156 of 188 strings)

Translated using Weblate (German)

Currently translated at 93.0% (241 of 259 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (286 of 286 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (8 of 8 strings)

Translated using Weblate (Chinese (Simplified))

Currently translated at 100.0% (427 of 427 strings)

Translated using Weblate (Chinese (Simplified))

Currently translated at 98.5% (762 of 773 strings)

Translated using Weblate (Chinese (Simplified))

Currently translated at 100.0% (868 of 868 strings)

Translated using Weblate (Chinese (Simplified))

Currently translated at 100.0% (167 of 167 strings)

Translated using Weblate (Japanese)

Currently translated at 99.2% (257 of 259 strings)

Translated using Weblate (Chinese (Simplified))

Currently translated at 98.5% (762 of 773 strings)

Translated using Weblate (Chinese (Simplified))

Currently translated at 100.0% (868 of 868 strings)

Translated using Weblate (German)

Currently translated at 92.2% (239 of 259 strings)

Translated using Weblate (Chinese (Simplified))

Currently translated at 100.0% (286 of 286 strings)

Translated using Weblate (Chinese (Simplified))

Currently translated at 100.0% (239 of 239 strings)

Translated using Weblate (Chinese (Simplified))

Currently translated at 100.0% (188 of 188 strings)

Translated using Weblate (German)

Currently translated at 91.8% (238 of 259 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (131 of 131 strings)

Translated using Weblate (Chinese (Simplified))

Currently translated at 98.5% (762 of 773 strings)

Translated using Weblate (German)

Currently translated at 90.3% (234 of 259 strings)

Co-authored-by: Finrod <963505255@qq.com>
Co-authored-by: Jaime Martí <jaumemarti77@icloud.com>
Co-authored-by: Kem Kembo <medamamef@gmail.com>
Co-authored-by: Sophie LE MASLE <sophiesuff@gmail.com>
Co-authored-by: TOMA Mitsuru <toma0001@gmail.com>
Co-authored-by: Tetiana <merekka13@gmail.com>
Co-authored-by: Toro Mor <thomas.bizer@gmx.de>
Co-authored-by: Weblate <noreply@weblate.org>
Translate-URL: https://translate.habitica.com/projects/habitica/achievements/es/
Translate-URL: https://translate.habitica.com/projects/habitica/achievements/zh_Hans/
Translate-URL: https://translate.habitica.com/projects/habitica/backgrounds/es/
Translate-URL: https://translate.habitica.com/projects/habitica/backgrounds/ja/
Translate-URL: https://translate.habitica.com/projects/habitica/backgrounds/zh_Hans/
Translate-URL: https://translate.habitica.com/projects/habitica/character/uk/
Translate-URL: https://translate.habitica.com/projects/habitica/character/zh_Hans/
Translate-URL: https://translate.habitica.com/projects/habitica/content/ja/
Translate-URL: https://translate.habitica.com/projects/habitica/content/uk/
Translate-URL: https://translate.habitica.com/projects/habitica/faq/de/
Translate-URL: https://translate.habitica.com/projects/habitica/faq/fr/
Translate-URL: https://translate.habitica.com/projects/habitica/faq/ja/
Translate-URL: https://translate.habitica.com/projects/habitica/faq/zh_Hans/
Translate-URL: https://translate.habitica.com/projects/habitica/gear/de/
Translate-URL: https://translate.habitica.com/projects/habitica/gear/ja/
Translate-URL: https://translate.habitica.com/projects/habitica/gear/uk/
Translate-URL: https://translate.habitica.com/projects/habitica/generic/zh_Hans/
Translate-URL: https://translate.habitica.com/projects/habitica/groups/zh_Hans/
Translate-URL: https://translate.habitica.com/projects/habitica/inventory/uk/
Translate-URL: https://translate.habitica.com/projects/habitica/limited/es/
Translate-URL: https://translate.habitica.com/projects/habitica/limited/ja/
Translate-URL: https://translate.habitica.com/projects/habitica/limited/uk/
Translate-URL: https://translate.habitica.com/projects/habitica/limited/zh_Hans/
Translate-URL: https://translate.habitica.com/projects/habitica/npc/uk/
Translate-URL: https://translate.habitica.com/projects/habitica/overview/uk/
Translate-URL: https://translate.habitica.com/projects/habitica/pets/uk/
Translate-URL: https://translate.habitica.com/projects/habitica/quests/uk/
Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/es/
Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/ja/
Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/zh_Hans/
Translate-URL: https://translate.habitica.com/projects/habitica/settings/de/
Translate-URL: https://translate.habitica.com/projects/habitica/settings/ja/
Translate-URL: https://translate.habitica.com/projects/habitica/settings/uk/
Translate-URL: https://translate.habitica.com/projects/habitica/subscriber/ja/
Translate-URL: https://translate.habitica.com/projects/habitica/tasks/zh_Hans/
Translation: Habitica/Achievements
Translation: Habitica/Backgrounds
Translation: Habitica/Character
Translation: Habitica/Content
Translation: Habitica/Faq
Translation: Habitica/Gear
Translation: Habitica/Generic
Translation: Habitica/Groups
Translation: Habitica/Inventory
Translation: Habitica/Limited
Translation: Habitica/Npc
Translation: Habitica/Overview
Translation: Habitica/Pets
Translation: Habitica/Quests
Translation: Habitica/Questscontent
Translation: Habitica/Settings
Translation: Habitica/Subscriber
Translation: Habitica/Tasks

* 5.25.0

* Fix dockerfile (#15241)

* Fix issue with l4p not resetting properly (#15240)

* actually clear out seeking field on user. Even when creating a party

* Add tests to ensure party.seeking is cleared

* fix(lint): don't assign unused const

---------

Co-authored-by: Sabe Jones <sabe@habitica.com>

---------

Co-authored-by: Sabe Jones <sabe@habitica.com>
Co-authored-by: Natalie <78037386+CuriousMagpie@users.noreply.github.com>
Co-authored-by: Weblate <noreply@weblate.org>
Co-authored-by: Finrod <963505255@qq.com>
Co-authored-by: Jaime Martí <jaumemarti77@icloud.com>
Co-authored-by: Kem Kembo <medamamef@gmail.com>
Co-authored-by: Sophie LE MASLE <sophiesuff@gmail.com>
Co-authored-by: TOMA Mitsuru <toma0001@gmail.com>
Co-authored-by: Tetiana <merekka13@gmail.com>
Co-authored-by: Toro Mor <thomas.bizer@gmx.de>
Co-authored-by: Rafał Jagielski <jagielski.rafal.uwm@gmail.com>
2024-06-11 13:19:03 -05:00

538 lines
16 KiB
JavaScript

import _ from 'lodash';
import { authWithHeaders } from '../../middlewares/auth';
import { getAnalyticsServiceByEnvironment } from '../../libs/analyticsService';
import {
model as Group,
basicFields as basicGroupFields,
} from '../../models/group';
import { model as User } from '../../models/user';
import {
NotFound,
NotAuthorized,
BadRequest,
} from '../../libs/errors';
import {
getUserInfo,
sendTxn as sendTxnEmail,
} from '../../libs/email';
import common from '../../../common';
import { sendNotification as sendPushNotification } from '../../libs/pushNotifications';
import { apiError } from '../../libs/apiError';
import { questActivityWebhook } from '../../libs/webhook';
const analytics = getAnalyticsServiceByEnvironment();
const questScrolls = common.content.quests;
function canStartQuestAutomatically (group) {
// If all members are either true (accepted) or false (rejected) return true
// If any member is null/undefined (undecided) return false
return _.every(group.quest.members, _.isBoolean);
}
/**
* @apiDefine QuestNotFound
* @apiError (404) {NotFound} QuestNotFound The specified quest could not be found.
*/
/**
* @apiDefine QuestLeader Quest Leader
* The quest leader can use this route.
*/
const api = {};
/**
* @api {post} /api/v3/groups/:groupId/quests/invite/:questKey Invite users to a quest
* @apiName InviteToQuest
* @apiGroup Quest
*
* @apiParam (Path) {String} groupId The group _id (or 'party')
* @apiParam (Path) {String} questKey
*
* @apiSuccess {Object} data Quest object
*
* @apiUse GroupNotFound
* @apiUse QuestNotFound
*/
api.inviteToQuest = {
method: 'POST',
url: '/groups/:groupId/quests/invite/:questKey',
middlewares: [authWithHeaders()],
async handler (req, res) {
const { user } = res.locals;
const { questKey } = req.params;
const quest = questScrolls[questKey];
req.checkParams('groupId', apiError('groupIdRequired')).notEmpty();
const validationErrors = req.validationErrors();
if (validationErrors) throw validationErrors;
const group = await Group.getGroup({ user, groupId: req.params.groupId, fields: basicGroupFields.concat(' quest chat') });
if (!group) throw new NotFound(res.t('groupNotFound'));
if (group.type !== 'party') throw new NotAuthorized(res.t('guildQuestsNotSupported'));
if (!quest) throw new NotFound(apiError('questNotFound', { key: questKey }));
if (!user.items.quests[questKey]) throw new NotAuthorized(res.t('questNotOwned'));
if (group.quest.key) throw new NotAuthorized(res.t('questAlreadyUnderway'));
const members = await User.find({
'party._id': group._id,
_id: { $ne: user._id },
})
.select('auth preferences.emailNotifications preferences.pushNotifications preferences.language profile.name pushDevices webhooks')
.exec();
group.markModified('quest');
group.quest.key = questKey;
group.quest.leader = user._id;
group.quest.members = {};
group.quest.members[user._id] = true;
user.party.quest.RSVPNeeded = false;
user.party.quest.key = questKey;
await User.updateMany({
'party._id': group._id,
_id: { $ne: user._id },
}, {
$set: {
'party.quest.RSVPNeeded': true,
'party.quest.key': questKey,
},
}).exec();
_.each(members, member => {
group.quest.members[member._id] = null;
});
if (canStartQuestAutomatically(group)) {
await group.startQuest(user);
}
const [savedGroup] = await Promise.all([
group.save(),
user.save(),
]);
res.respond(200, savedGroup.quest);
// send out invites
const inviterVars = getUserInfo(user, ['name', 'email']);
const membersToEmail = members.filter(async member => {
// send push notifications while filtering members before sending emails
if (member.preferences.pushNotifications.invitedQuest !== false) {
await sendPushNotification(
member,
{
title: quest.text(member.preferences.language),
message: res.t('questInvitationNotificationInfo', member.preferences.language),
identifier: 'questInvitation',
category: 'questInvitation',
},
);
}
// Send webhooks
questActivityWebhook.send(member, {
type: 'questInvited',
group,
quest,
});
return member.preferences.emailNotifications.invitedQuest !== false;
});
sendTxnEmail(membersToEmail, `invite-${quest.boss ? 'boss' : 'collection'}-quest`, [
{ name: 'QUEST_NAME', content: quest.text() },
{ name: 'INVITER', content: inviterVars.name },
{ name: 'PARTY_URL', content: '/party' },
]);
// Send webhook to the inviter too
questActivityWebhook.send(user, {
type: 'questInvited',
group,
quest,
});
// track that the inviting user has accepted the quest
analytics.track('quest', {
category: 'behavior',
owner: true,
response: 'accept',
gaLabel: 'accept',
questName: questKey,
uuid: user._id,
headers: req.headers,
});
},
};
/**
* @api {post} /api/v3/groups/:groupId/quests/accept Accept a pending quest
* @apiName AcceptQuest
* @apiGroup Quest
*
* @apiParam (Path) {String} groupId The group _id (or 'party')
*
* @apiSuccess {Object} data Quest Object
*
* @apiUse GroupNotFound
* @apiUse QuestNotFound
*/
api.acceptQuest = {
method: 'POST',
url: '/groups/:groupId/quests/accept',
middlewares: [authWithHeaders()],
async handler (req, res) {
const { user } = res.locals;
req.checkParams('groupId', apiError('groupIdRequired')).notEmpty();
const validationErrors = req.validationErrors();
if (validationErrors) throw validationErrors;
const group = await Group.getGroup({ user, groupId: req.params.groupId, fields: basicGroupFields.concat(' quest chat') });
if (!group) throw new NotFound(res.t('groupNotFound'));
if (group.type !== 'party') throw new NotAuthorized(res.t('guildQuestsNotSupported'));
if (!group.quest.key) throw new NotFound(res.t('questInviteNotFound'));
if (group.quest.active) throw new NotAuthorized(res.t('questAlreadyStartedFriendly'));
if (group.quest.members[user._id]) throw new BadRequest(res.t('questAlreadyAccepted'));
const acceptedSuccessfully = await group.handleQuestInvitation(user, true);
if (!acceptedSuccessfully) {
throw new NotAuthorized(res.t('questAlreadyAccepted'));
}
user.party.quest.RSVPNeeded = false;
await user.save();
if (canStartQuestAutomatically(group)) {
await group.startQuest(user);
}
const savedGroup = await group.save();
res.respond(200, savedGroup.quest);
// track that a user has accepted the quest
analytics.track('quest', {
category: 'behavior',
owner: false,
response: 'accept',
gaLabel: 'accept',
questName: group.quest.key,
uuid: user._id,
headers: req.headers,
});
},
};
/**
* @api {post} /api/v3/groups/:groupId/quests/reject Reject a quest
* @apiName RejectQuest
* @apiGroup Quest
*
* @apiParam (Path) {String} groupId The group _id (or 'party')
*
* @apiSuccess {Object} data Quest Object
*
* @apiUse GroupNotFound
* @apiUse QuestNotFound
*/
api.rejectQuest = {
method: 'POST',
url: '/groups/:groupId/quests/reject',
middlewares: [authWithHeaders()],
async handler (req, res) {
const { user } = res.locals;
req.checkParams('groupId', apiError('groupIdRequired')).notEmpty();
const validationErrors = req.validationErrors();
if (validationErrors) throw validationErrors;
const group = await Group.getGroup({ user, groupId: req.params.groupId, fields: basicGroupFields.concat(' quest chat') });
if (!group) throw new NotFound(res.t('groupNotFound'));
if (group.type !== 'party') throw new NotAuthorized(res.t('guildQuestsNotSupported'));
if (!group.quest.key) throw new NotFound(res.t('questInvitationDoesNotExist'));
if (group.quest.active) throw new NotAuthorized(res.t('questAlreadyStartedFriendly'));
if (group.quest.members[user._id]) throw new BadRequest(res.t('questAlreadyAccepted'));
if (group.quest.members[user._id] === false) throw new BadRequest(res.t('questAlreadyRejected'));
const rejectedSuccessfully = await group.handleQuestInvitation(user, false);
if (!rejectedSuccessfully) {
throw new NotAuthorized(res.t('questAlreadyRejected'));
}
user.party.quest = Group.cleanQuestUser(user.party.quest.progress);
user.markModified('party.quest');
await user.save();
if (canStartQuestAutomatically(group)) {
await group.startQuest(user);
}
const savedGroup = await group.save();
res.respond(200, savedGroup.quest);
analytics.track('quest', {
category: 'behavior',
owner: false,
response: 'reject',
gaLabel: 'reject',
questName: group.quest.key,
uuid: user._id,
headers: req.headers,
});
},
};
/**
* @api {post} /api/v3/groups/:groupId/quests/force-start Force-start a pending quest
* @apiName ForceQuestStart
* @apiGroup Quest
*
* @apiParam (Path) {String} groupId The group _id (or 'party')
*
* @apiSuccess {Object} data Quest Object
*
* @apiPermission QuestLeader
* @apiPermission GroupLeader
*
* @apiUse GroupNotFound
* @apiUse QuestNotFound
*/
api.forceStart = {
method: 'POST',
url: '/groups/:groupId/quests/force-start',
middlewares: [authWithHeaders()],
async handler (req, res) {
const { user } = res.locals;
req.checkParams('groupId', apiError('groupIdRequired')).notEmpty();
const validationErrors = req.validationErrors();
if (validationErrors) throw validationErrors;
const group = await Group.getGroup({ user, groupId: req.params.groupId, fields: basicGroupFields.concat(' quest chat') });
if (!group) throw new NotFound(res.t('groupNotFound'));
if (group.type !== 'party') throw new NotAuthorized(res.t('guildQuestsNotSupported'));
if (!group.quest.key) throw new NotFound(res.t('questNotPending'));
if (group.quest.active) throw new NotAuthorized(res.t('questAlreadyStarted'));
if (!(user._id === group.quest.leader || user._id === group.leader)) {
throw new NotAuthorized(res.t('questOrGroupLeaderOnlyStartQuest'));
}
group.markModified('quest');
await group.startQuest(user);
const [savedGroup] = await Promise.all([
group.save(),
user.save(),
]);
res.respond(200, savedGroup.quest);
analytics.track('quest', {
category: 'behavior',
owner: user._id === group.quest.leader,
response: 'force-start',
gaLabel: 'force-start',
questName: group.quest.key,
uuid: user._id,
headers: req.headers,
});
},
};
/**
* @api {post} /api/v3/groups/:groupId/quests/cancel Cancel a quest that is not active
* @apiName CancelQuest
* @apiGroup Quest
*
* @apiParam (Path) {String} groupId The group _id (or 'party')
*
* @apiSuccess {Object} data Quest Object
*
* @apiPermission QuestLeader
* @apiPermission GroupLeader
*
* @apiUse GroupNotFound
* @apiUse QuestNotFound
*/
api.cancelQuest = {
method: 'POST',
url: '/groups/:groupId/quests/cancel',
middlewares: [authWithHeaders()],
async handler (req, res) {
// Cancel a quest BEFORE it has begun (i.e., in the invitation stage)
// Quest scroll has not yet left quest owner's inventory so no need to return it.
// Do not wipe quest progress for members because they'll
// want it to be applied to the next quest that's started.
const { user } = res.locals;
const { groupId } = req.params;
req.checkParams('groupId', apiError('groupIdRequired')).notEmpty();
const validationErrors = req.validationErrors();
if (validationErrors) throw validationErrors;
const group = await Group.getGroup({ user, groupId, fields: basicGroupFields.concat(' quest') });
if (!group) throw new NotFound(res.t('groupNotFound'));
if (group.type !== 'party') throw new NotAuthorized(res.t('guildQuestsNotSupported'));
if (!group.quest.key) throw new NotFound(res.t('questInvitationDoesNotExist'));
if (user._id !== group.leader && group.quest.leader !== user._id) {
throw new NotAuthorized(res.t('onlyLeaderCancelQuest'));
}
if (group.quest.active) throw new NotAuthorized(res.t('cantCancelActiveQuest'));
const questName = questScrolls[group.quest.key].text('en');
const newChatMessage = await group.sendChat({
message: `\`${user.profile.name} cancelled the party quest ${questName}.\``,
info: {
type: 'quest_cancel',
user: user.profile.name,
quest: group.quest.key,
},
});
group.quest = Group.cleanGroupQuest();
group.markModified('quest');
const [savedGroup] = await Promise.all([
group.save(),
newChatMessage.save(),
User.updateMany(
{ 'party._id': groupId },
Group.cleanQuestParty(),
).exec(),
]);
res.respond(200, savedGroup.quest);
},
};
/**
* @api {post} /api/v3/groups/:groupId/quests/abort Abort the current quest
* @apiName AbortQuest
* @apiGroup Quest
*
* @apiParam (Path) {String} groupId The group _id (or 'party')
*
* @apiSuccess {Object} data Quest Object
*
* @apiPermission QuestLeader
* @apiPermission GroupLeader
*
* @apiUse GroupNotFound
* @apiUse QuestNotFound
*/
api.abortQuest = {
method: 'POST',
url: '/groups/:groupId/quests/abort',
middlewares: [authWithHeaders()],
async handler (req, res) {
// Abort a quest AFTER it has begun
const { user } = res.locals;
const { groupId } = req.params;
req.checkParams('groupId', apiError('groupIdRequired')).notEmpty();
const validationErrors = req.validationErrors();
if (validationErrors) throw validationErrors;
const group = await Group.getGroup({ user, groupId, fields: basicGroupFields.concat(' quest chat') });
if (!group) throw new NotFound(res.t('groupNotFound'));
if (group.type !== 'party') throw new NotAuthorized(res.t('guildQuestsNotSupported'));
if (!group.quest.active) throw new NotFound(res.t('noActiveQuestToAbort'));
if (user._id !== group.leader && user._id !== group.quest.leader) throw new NotAuthorized(res.t('onlyLeaderAbortQuest'));
const questName = questScrolls[group.quest.key].text('en');
const newChatMessage = await group.sendChat({
message: `\`${common.i18n.t('chatQuestAborted', { username: user.profile.name, questName }, 'en')}\``,
info: {
type: 'quest_abort',
user: user.profile.name,
quest: group.quest.key,
},
});
await newChatMessage.save();
const memberUpdates = User.updateMany({
'party._id': groupId,
}, Group.cleanQuestParty()).exec();
const questLeaderUpdate = User.updateOne({
_id: group.quest.leader,
}, {
$inc: {
[`items.quests.${group.quest.key}`]: 1, // give back the quest to the quest leader
},
}).exec();
group.quest = Group.cleanGroupQuest();
group.markModified('quest');
const [groupSaved] = await Promise.all([group.save(), memberUpdates, questLeaderUpdate]);
res.respond(200, groupSaved.quest);
},
};
/**
* @api {post} /api/v3/groups/:groupId/quests/leave Leave the active quest
* @apiName LeaveQuest
* @apiGroup Quest
*
* @apiParam (Path) {String} groupId The group _id (or 'party')
*
* @apiSuccess {Object} data Quest Object
*
* @apiUse GroupNotFound
* @apiUse QuestNotFound
*/
api.leaveQuest = {
method: 'POST',
url: '/groups/:groupId/quests/leave',
middlewares: [authWithHeaders()],
async handler (req, res) {
const { user } = res.locals;
const { groupId } = req.params;
req.checkParams('groupId', apiError('groupIdRequired')).notEmpty();
const validationErrors = req.validationErrors();
if (validationErrors) throw validationErrors;
const group = await Group.getGroup({ user, groupId, fields: basicGroupFields.concat(' quest') });
if (!group) throw new NotFound(res.t('groupNotFound'));
if (group.type !== 'party') throw new NotAuthorized(res.t('guildQuestsNotSupported'));
if (group.quest.leader === user._id) throw new NotAuthorized(res.t('questLeaderCannotLeaveQuest'));
if (!group.quest.members[user._id]) throw new NotAuthorized(res.t('notPartOfQuest'));
group.quest.members[user._id] = false;
group.markModified('quest.members');
user.party.quest = Group.cleanQuestUser(user.party.quest.progress);
user.markModified('party.quest');
const [savedGroup] = await Promise.all([
group.save(),
user.save(),
]);
res.respond(200, savedGroup.quest);
},
};
export default api;