fix linting for server (except for length of apidoc)

This commit is contained in:
Matteo Pagliazzi
2019-10-10 20:11:50 +02:00
parent bcf7bcf03c
commit 8bae0223bb
84 changed files with 913 additions and 469 deletions

View File

@@ -4,7 +4,7 @@ import {
} from 'lodash';
import common from '../../../common';
import {
import { // eslint-disable-line import/no-cycle
TAVERN_ID,
model as Group,
} from '../group';
@@ -16,19 +16,20 @@ import {
} from '../message';
import { model as UserNotification } from '../userNotification';
import schema from './schema';
import payments from '../../libs/payments/payments';
import * as inboxLib from '../../libs/inbox';
import amazonPayments from '../../libs/payments/amazon';
import stripePayments from '../../libs/payments/stripe';
import paypalPayments from '../../libs/payments/paypal';
import schema from './schema'; // eslint-disable-line import/no-cycle
import payments from '../../libs/payments/payments'; // eslint-disable-line import/no-cycle
import * as inboxLib from '../../libs/inbox'; // eslint-disable-line import/no-cycle
import amazonPayments from '../../libs/payments/amazon'; // eslint-disable-line import/no-cycle
import stripePayments from '../../libs/payments/stripe'; // eslint-disable-line import/no-cycle
import paypalPayments from '../../libs/payments/paypal'; // eslint-disable-line import/no-cycle
const { daysSince } = common;
schema.methods.isSubscribed = function isSubscribed () {
const now = new Date();
const { plan } = this.purchased;
return plan && plan.customerId && (!plan.dateTerminated || moment(plan.dateTerminated).isAfter(now));
return plan && plan.customerId
&& (!plan.dateTerminated || moment(plan.dateTerminated).isAfter(now));
};
schema.methods.hasNotCancelled = function hasNotCancelled () {
@@ -49,10 +50,12 @@ schema.methods.getGroups = function getUserGroups () {
return userGroups;
};
/* eslint-disable no-unused-vars */ // The checks below all get access to sndr and rcvr, but not all use both
/* eslint-disable no-unused-vars */
// The checks below all get access to sndr and rcvr, but not all use both
const INTERACTION_CHECKS = Object.freeze({
always: [
// Revoked chat privileges block all interactions to prevent the evading of harassment protections
// Revoked chat privileges block all interactions
// to prevent the evading of harassment protections
// See issue #7971 for some discussion
(sndr, rcvr) => sndr.flags.chatRevoked && 'chatPrivilegesRevoked',
@@ -65,7 +68,8 @@ const INTERACTION_CHECKS = Object.freeze({
// Private messaging has an opt-out, which does not affect other interactions
(sndr, rcvr) => rcvr.inbox.optOut && 'notAuthorizedToSendMessageToThisUser',
// We allow a player to message themselves so they can test how PMs work or send their own notes to themselves
// We allow a player to message themselves so they can test how PMs work
// or send their own notes to themselves
],
'transfer-gems': [
@@ -79,10 +83,11 @@ const INTERACTION_CHECKS = Object.freeze({
});
/* eslint-enable no-unused-vars */
export const KNOWN_INTERACTIONS = Object.freeze(Object.keys(INTERACTION_CHECKS).filter(key => key !== 'always'));
export const KNOWN_INTERACTIONS = Object.freeze(Object.keys(INTERACTION_CHECKS) // eslint-disable-line import/prefer-default-export, max-len
.filter(key => key !== 'always'));
// Get an array of error message keys that would be thrown if the given interaction was attempted
schema.methods.getObjectionsToInteraction = function getObjectionsToInteraction (interaction, receiver) {
schema.methods.getObjectionsToInteraction = function getObjectionsToInteraction (interaction, receiver) { // eslint-disable-line max-len
if (!KNOWN_INTERACTIONS.includes(interaction)) {
throw new Error(`Unknown kind of interaction: "${interaction}", expected one of ${KNOWN_INTERACTIONS.join(', ')}`);
}
@@ -125,8 +130,8 @@ schema.methods.sendMessage = async function sendMessage (userToReceiveMessage, o
Object.assign(newReceiverMessage, messageDefaults(options.receiverMsg, sender));
setUserStyles(newReceiverMessage, sender);
userToReceiveMessage.inbox.newMessages++;
userToReceiveMessage._v++;
userToReceiveMessage.inbox.newMessages += 1;
userToReceiveMessage._v += 1;
/* @TODO disabled until mobile is ready
@@ -178,10 +183,12 @@ schema.methods.sendMessage = async function sendMessage (userToReceiveMessage, o
};
/**
* Creates a notification based on the input parameters and adds it to the local user notifications array.
* Creates a notification based on the input parameters and adds
* it to the local user notifications array.
* This does not save the notification to the database or interact with the database in any way.
*
* @param type The type of notification to add to the this. Possible values are defined in the UserNotificaiton Schema
* @param type The type of notification to add to the this.
* Possible values are defined in the UserNotificaiton Schema
* @param data The data to add to the notification
* @param seen If the notification should be marked as seen
*/
@@ -194,16 +201,22 @@ schema.methods.addNotification = function addUserNotification (type, data = {},
};
/**
* Creates a notification based on the type and data input parameters and saves that new notification
* to the database directly using an update statement. The local copy of these users are not updated by
* this operation. Use this function when you want to add a notification to a user(s), but do not have
* Creates a notification based on the type and data input parameters
and saves that new notification
* to the database directly using an update statement.
* The local copy of these users are not updated by
* this operation. Use this function when you want to add a notification to a user(s),
* but do not have
* the user document(s) opened.
*
* @param query A Mongoose query defining the users to add the notification to.
* @param type The type of notification to add to the this. Possible values are defined in the UserNotificaiton Schema
* @param type The type of notification to add to the this.
* Possible values are defined in the UserNotificaiton Schema
* @param data The data to add to the notification
*/
schema.statics.pushNotification = async function pushNotification (query, type, data = {}, seen = false) {
schema.statics.pushNotification = async function pushNotification (
query, type, data = {}, seen = false,
) {
const newNotification = new UserNotification({ type, data, seen });
const validationResult = newNotification.validateSync();
@@ -211,7 +224,11 @@ schema.statics.pushNotification = async function pushNotification (query, type,
throw validationResult;
}
await this.update(query, { $push: { notifications: newNotification.toObject() } }, { multi: true }).exec();
await this.update(
query,
{ $push: { notifications: newNotification.toObject() } },
{ multi: true },
).exec();
};
// Static method to add/remove properties to a JSON User object,
@@ -229,7 +246,10 @@ schema.statics.transformJSONUser = function transformJSONUser (jsonUser, addComp
// Add stats.toNextLevel, stats.maxMP and stats.maxHealth
// to a JSONified User stats object
schema.statics.addComputedStatsToJSONObj = function addComputedStatsToUserJSONObj (userStatsJSON, user) {
schema.statics.addComputedStatsToJSONObj = function addComputedStatsToUserJSONObj (
userStatsJSON,
user,
) {
// NOTE: if an item is manually added to this.stats then
// common/fns/predictableRandom must be tweaked so the new item is not considered.
// Otherwise the client will have it while the server won't and the results will be different.
@@ -251,25 +271,29 @@ schema.statics.addComputedStatsToJSONObj = function addComputedStatsToUserJSONOb
*
* @return a Promise from api.cancelSubscription()
*/
// @TODO: There is currently a three way relation between the user, payment methods and the payment helper
// This creates some odd Dependency Injection issues. To counter that, we use the user as the third layer
// To negotiate between the payment providers and the payment helper (which probably has too many responsiblities)
// In summary, currently is is best practice to use this method to cancel a user subscription, rather than calling the
// @TODO: There is currently a three way relation between the user,
// payment methods and the payment helper
// This creates some odd Dependency Injection issues. To counter that,
// we use the user as the third layer
// To negotiate between the payment providers and the payment helper
// (which probably has too many responsiblities)
// In summary, currently is is best practice to use this method to cancel a user subscription,
// rather than calling the
// payment helper.
schema.methods.cancelSubscription = async function cancelSubscription (options = {}) {
const { plan } = this.purchased;
options.user = this;
if (plan.paymentMethod === amazonPayments.constants.PAYMENT_METHOD) {
return await amazonPayments.cancelSubscription(options);
return amazonPayments.cancelSubscription(options);
} if (plan.paymentMethod === stripePayments.constants.PAYMENT_METHOD) {
return await stripePayments.cancelSubscription(options);
return stripePayments.cancelSubscription(options);
} if (plan.paymentMethod === paypalPayments.constants.PAYMENT_METHOD) {
return await paypalPayments.subscribeCancel(options);
return paypalPayments.subscribeCancel(options);
}
// Android and iOS subscriptions cannot be cancelled by Habitica.
return await payments.cancelSubscription(options);
return payments.cancelSubscription(options);
};
schema.methods.daysUserHasMissed = function daysUserHasMissed (now, req = {}) {
@@ -278,9 +302,13 @@ schema.methods.daysUserHasMissed = function daysUserHasMissed (now, req = {}) {
// both timezones to work out if cron should run.
// CDS = Custom Day Start time.
let timezoneOffsetFromUserPrefs = this.preferences.timezoneOffset;
const timezoneOffsetAtLastCron = isFinite(this.preferences.timezoneOffsetAtLastCron) ? this.preferences.timezoneOffsetAtLastCron : timezoneOffsetFromUserPrefs;
const timezoneOffsetAtLastCron = Number.isFinite(this.preferences.timezoneOffsetAtLastCron)
? this.preferences.timezoneOffsetAtLastCron
: timezoneOffsetFromUserPrefs;
let timezoneOffsetFromBrowser = typeof req.header === 'function' && Number(req.header('x-user-timezoneoffset'));
timezoneOffsetFromBrowser = isFinite(timezoneOffsetFromBrowser) ? timezoneOffsetFromBrowser : timezoneOffsetFromUserPrefs;
timezoneOffsetFromBrowser = Number.isFinite(timezoneOffsetFromBrowser)
? timezoneOffsetFromBrowser
: timezoneOffsetFromUserPrefs;
// NB: All timezone offsets can be 0, so can't use `... || ...` to apply non-zero defaults
if (timezoneOffsetFromBrowser !== timezoneOffsetFromUserPrefs) {
@@ -296,8 +324,8 @@ schema.methods.daysUserHasMissed = function daysUserHasMissed (now, req = {}) {
if (timezoneOffsetAtLastCron !== timezoneOffsetFromUserPrefs) {
// Give the user extra time based on the difference in timezones
if (timezoneOffsetAtLastCron < timezoneOffsetFromUserPrefs) {
const differenceBetweenTimezonesInMinutes = timezoneOffsetFromUserPrefs - timezoneOffsetAtLastCron;
now = moment(now).subtract(differenceBetweenTimezonesInMinutes, 'minutes');
const differenceBetweenTimezonesInMinutes = timezoneOffsetFromUserPrefs - timezoneOffsetAtLastCron; // eslint-disable-line max-len
now = moment(now).subtract(differenceBetweenTimezonesInMinutes, 'minutes'); // eslint-disable-line no-param-reassign, max-len
}
// Since cron last ran, the user's timezone has changed.
@@ -324,7 +352,10 @@ schema.methods.daysUserHasMissed = function daysUserHasMissed (now, req = {}) {
// This should be impossible for this direction of timezone change, but
// just in case I'm wrong...
// TODO
// console.log("zone has changed - old zone says run cron, NEW zone says no - stop cron now only -- SHOULD NOT HAVE GOT TO HERE", timezoneOffsetAtLastCron, timezoneOffsetFromUserPrefs, now); // used in production for confirming this never happens
// console.log("zone has changed - old zone says run cron,
// NEW zone says no - stop cron now only -- SHOULD NOT HAVE GOT TO HERE",
// timezoneOffsetAtLastCron, timezoneOffsetFromUserPrefs, now);
// used in production for confirming this never happens
} else if (daysMissedNewZone > 0) {
// The old timezone says that cron should NOT run -- i.e., cron has
// already run today, from the old timezone's point of view.
@@ -341,7 +372,8 @@ schema.methods.daysUserHasMissed = function daysUserHasMissed (now, req = {}) {
// e.g., for dangerous zone change: 240 - 300 = -60 or -660 - -600 = -60
this.lastCron = moment(this.lastCron).subtract(timezoneOffsetDiff, 'minutes');
// NB: We don't change this.auth.timestamps.loggedin so that will still record the time that the previous cron actually ran.
// NB: We don't change this.auth.timestamps.loggedin so that will still record
// the time that the previous cron actually ran.
// From now on we can ignore the old timezone:
this.preferences.timezoneOffsetAtLastCron = timezoneOffsetFromUserPrefs;
} else {
@@ -351,9 +383,14 @@ schema.methods.daysUserHasMissed = function daysUserHasMissed (now, req = {}) {
}
} else if (timezoneOffsetAtLastCron > timezoneOffsetFromUserPrefs) {
daysMissed = daysMissedNewZone;
// TODO: Either confirm that there is nothing that could possibly go wrong here and remove the need for this else branch, or fix stuff.
// There are probably situations where the Dailies do not reset early enough for a user who was expecting the zone change and wants to use all their Dailies immediately in the new zone;
// if so, we should provide an option for easy reset of Dailies (can't be automatic because there will be other situations where the user was not prepared).
// TODO: Either confirm that there is nothing that could possibly go wrong
// here and remove the need for this else branch, or fix stuff.
// There are probably situations where the Dailies do not reset early enough
// for a user who was expecting the zone change and wants to use all their Dailies
// immediately in the new zone;
// if so, we should provide an option for easy reset of Dailies
// (can't be automatic because there will be other situations where
// the user was not prepared).
}
}
@@ -386,7 +423,8 @@ schema.methods.canGetGems = async function canObtainGems () {
const groups = await getUserGroupData(user);
return groups.every(g => !g.isSubscribed() || g.leader === user._id || g.leaderOnly.getGems !== true);
return groups
.every(g => !g.isSubscribed() || g.leader === user._id || g.leaderOnly.getGems !== true);
};
schema.methods.isMemberOfGroupPlan = async function isMemberOfGroupPlan () {