Files
habitica/website/server/middlewares/cron.js
Matteo Pagliazzi e04d4e8bea Drop Cap Notification, Modal and A/B Test (#12651)
* add drop cap notification

* add drop cap notification

* add dismissible notification

* fix(notification): correct remove icon positioning

* track events

* add modal

* add back files

* fix links and add missing analytics

* fix rounded borders and hide sub info for subscribers

* a/b test

* fix comparison

* Translated using Weblate (Spanish)

Currently translated at 98.2% (55 of 56 strings)

Translation: Habitica/Messages
Translate-URL: https://translate.habitica.com/projects/habitica/messages/es/

Translated using Weblate (Spanish)

Currently translated at 99.4% (179 of 180 strings)

Translation: Habitica/Settings
Translate-URL: https://translate.habitica.com/projects/habitica/settings/es/

Merge branch 'origin/develop' into Weblate.

Translated using Weblate (Spanish)

Currently translated at 99.4% (175 of 176 strings)

Translation: Habitica/Subscriber
Translate-URL: https://translate.habitica.com/projects/habitica/subscriber/es/

Translated using Weblate (Spanish (Latin America))

Currently translated at 98.6% (359 of 364 strings)

Translation: Habitica/Groups
Translate-URL: https://translate.habitica.com/projects/habitica/groups/es_419/

Translated using Weblate (Spanish)

Currently translated at 85.7% (151 of 176 strings)

Translation: Habitica/Subscriber
Translate-URL: https://translate.habitica.com/projects/habitica/subscriber/es/

Translated using Weblate (Spanish)

Currently translated at 95.3% (538 of 564 strings)

Translation: Habitica/Backgrounds
Translate-URL: https://translate.habitica.com/projects/habitica/backgrounds/es/

Translated using Weblate (Spanish (Latin America))

Currently translated at 98.6% (359 of 364 strings)

Translation: Habitica/Groups
Translate-URL: https://translate.habitica.com/projects/habitica/groups/es_419/

Translated using Weblate (French)

Currently translated at 100.0% (56 of 56 strings)

Translation: Habitica/Messages
Translate-URL: https://translate.habitica.com/projects/habitica/messages/fr/

Translated using Weblate (German)

Currently translated at 100.0% (56 of 56 strings)

Translation: Habitica/Messages
Translate-URL: https://translate.habitica.com/projects/habitica/messages/de/

Translated using Weblate (French)

Currently translated at 100.0% (718 of 718 strings)

Translation: Habitica/Questscontent
Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/fr/

Translated using Weblate (German)

Currently translated at 100.0% (718 of 718 strings)

Translation: Habitica/Questscontent
Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/de/

Translated using Weblate (Czech)

Currently translated at 100.0% (56 of 56 strings)

Translation: Habitica/Spells
Translate-URL: https://translate.habitica.com/projects/habitica/spells/cs/

Translated using Weblate (Japanese)

Currently translated at 100.0% (175 of 175 strings)

Translation: Habitica/Subscriber
Translate-URL: https://translate.habitica.com/projects/habitica/subscriber/ja/

Translated using Weblate (Italian)

Currently translated at 100.0% (56 of 56 strings)

Translation: Habitica/Messages
Translate-URL: https://translate.habitica.com/projects/habitica/messages/it/

Translated using Weblate (Italian)

Currently translated at 100.0% (718 of 718 strings)

Translation: Habitica/Questscontent
Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/it/

Translated using Weblate (Czech)

Currently translated at 100.0% (180 of 180 strings)

Translation: Habitica/Settings
Translate-URL: https://translate.habitica.com/projects/habitica/settings/cs/

Translated using Weblate (Basque)

Currently translated at 100.0% (2 of 2 strings)

Translation: Habitica/Noscript
Translate-URL: https://translate.habitica.com/projects/habitica/noscript/eu/

Translated using Weblate (Basque)

Currently translated at 6.5% (8 of 123 strings)

Translation: Habitica/Communityguidelines
Translate-URL: https://translate.habitica.com/projects/habitica/communityguidelines/eu/

Translated using Weblate (Chinese (Simplified))

Currently translated at 100.0% (56 of 56 strings)

Translation: Habitica/Messages
Translate-URL: https://translate.habitica.com/projects/habitica/messages/zh_Hans/

Translated using Weblate (Japanese)

Currently translated at 100.0% (56 of 56 strings)

Translation: Habitica/Messages
Translate-URL: https://translate.habitica.com/projects/habitica/messages/ja/

Translated using Weblate (Chinese (Simplified))

Currently translated at 100.0% (718 of 718 strings)

Translation: Habitica/Questscontent
Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/zh_Hans/

Translated using Weblate (Portuguese (Brazil))

Currently translated at 100.0% (718 of 718 strings)

Translation: Habitica/Questscontent
Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/pt_BR/

Translated using Weblate (Portuguese (Brazil))

Currently translated at 99.8% (717 of 718 strings)

Translation: Habitica/Questscontent
Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/pt_BR/

* clarify a/b test values

* add tests

* refactor user dropdown

* fix hover state

* fix user dropdown

* fix user menu hierarchy

* restore i18n files to release version

Co-authored-by: Melior <admin@habitica.com>
2020-10-16 19:50:54 +02:00

208 lines
6.1 KiB
JavaScript

import moment from 'moment';
import * as Tasks from '../models/task';
import { model as Group } from '../models/group';
import { model as User } from '../models/user';
import { recoverCron, cron } from '../libs/cron';
// Wait this length of time in ms before attempting another cron
const CRON_TIMEOUT_WAIT = new Date(60 * 60 * 1000).getTime();
async function checkForActiveCron (user, now) {
// set _cronSignature to current time in ms since epoch time
// so we can make sure to wait at least CRONT_TIMEOUT_WAIT before attempting another cron
const _cronSignature = now.getTime();
// Calculate how long ago cron must have been attempted to try again
const cronRetryTime = _cronSignature - CRON_TIMEOUT_WAIT;
// To avoid double cron we first set _cronSignature
// and then check that it's not changed while processing
const userUpdateResult = await User.update({
_id: user._id,
$or: [ // Make sure last cron was successful or failed before cronRetryTime
{ _cronSignature: 'NOT_RUNNING' },
{ _cronSignature: { $lt: cronRetryTime } },
],
}, {
$set: {
_cronSignature,
'auth.timestamps.loggedin': now,
},
}).exec();
// If the cron signature is already set, cron is running in another request
// throw an error and recover later,
if (userUpdateResult.nMatched === 0 || userUpdateResult.nModified === 0) {
throw new Error('CRON_ALREADY_RUNNING');
}
}
async function updateLastCron (user, now) {
await User.update({
_id: user._id,
}, {
lastCron: now, // setting lastCron now so we don't risk re-running parts of cron if it fails
}).exec();
}
async function unlockUser (user) {
await User.update({
_id: user._id,
}, {
_cronSignature: 'NOT_RUNNING',
}).exec();
}
// Enroll users in the Drop Cap A/B Test
function dropCapABTest (user, req) {
// Only target users that use web for cron and aren't subscribed.
// Those using mobile aren't excluded as they may use it later
const isWeb = req.headers['x-client'] === 'habitica-web';
if (isWeb && !user._ABtests.dropCapNotif && !user.isSubscribed()) {
const testGroup = Math.random();
// Enroll 20% of users, splitting them 50/50
if (testGroup <= 0.1) {
user._ABtests.dropCapNotif = 'drop-cap-notif-enabled';
} else if (testGroup <= 0.2) {
user._ABtests.dropCapNotif = 'drop-cap-notif-disabled';
} else {
user._ABtests.dropCapNotif = 'drop-cap-notif-not-enrolled';
}
user.markModified('_ABtests');
}
}
async function cronAsync (req, res) {
let { user } = res.locals;
if (!user) return null; // User might not be available when authentication is not mandatory
const { analytics } = res;
const now = new Date();
try {
await checkForActiveCron(user, now);
user = await User.findOne({ _id: user._id }).exec();
res.locals.user = user;
const { daysMissed, timezoneUtcOffsetFromUserPrefs } = user.daysUserHasMissed(now, req);
dropCapABTest(user, req);
await updateLastCron(user, now);
if (daysMissed <= 0) {
if (user.isModified()) await user.save();
await unlockUser(user);
return null;
}
const tasks = await Tasks.Task.find({
userId: user._id,
$or: [ // Exclude completed todos
{ type: 'todo', completed: false },
{ type: { $in: ['habit', 'daily', 'reward'] } },
],
}).exec();
const tasksByType = {
habits: [], dailys: [], todos: [], rewards: [],
};
tasks.forEach(task => tasksByType[`${task.type}s`].push(task));
// Run cron
const progress = cron({
user,
tasksByType,
now,
daysMissed,
analytics,
timezoneUtcOffsetFromUserPrefs,
headers: req.headers,
});
// Clear old completed todos - 30 days for free users, 90 for subscribers
// Do not delete challenges completed todos TODO unless the task is broken?
// Do not delete group completed todos
Tasks.Task.remove({
userId: user._id,
type: 'todo',
completed: true,
dateCompleted: {
$lt: moment(now).subtract(user.isSubscribed() ? 90 : 30, 'days').toDate(),
},
'challenge.id': { $exists: false },
'group.id': { $exists: false },
}).exec();
res.locals.wasModified = true; // TODO remove after v2 is retired
Group.tavernBoss(user, progress);
// Save user and tasks
const toSave = [user.save()];
tasks.forEach(async task => {
if (task.isModified()) toSave.push(task.save());
if (task.isModified() && task.group && task.group.taskId) {
const groupTask = await Tasks.Task.findOne({
_id: task.group.taskId,
}).exec();
if (groupTask) {
let delta = (0.9747 ** task.value) * -1;
if (groupTask.group.assignedUsers) delta /= groupTask.group.assignedUsers.length;
await groupTask.scoreChallengeTask(delta, 'down');
}
}
});
await Promise.all(toSave);
await Group.processQuestProgress(user, progress);
// Set _cronSignature, lastCron and auth.timestamps.loggedin to signal end of cron
await User.update({
_id: user._id,
}, {
$set: {
_cronSignature: 'NOT_RUNNING',
},
}).exec();
// Reload user
res.locals.user = await User.findOne({ _id: user._id }).exec();
return null;
} catch (err) {
// If cron was aborted for a race condition try to recover from it
if (err.message === 'CRON_ALREADY_RUNNING') {
// Recovering after abort, wait 300ms and reload user
// do it for max 5 times then reset _cronSignature
// so that it doesn't prevent cron from running
// at the next request
const recoveryStatus = {
times: 0,
};
await recoverCron(recoveryStatus, res.locals);
} else {
// For any other error make sure to reset _cronSignature
// so that it doesn't prevent cron from running
// at the next request
await User.update({
_id: user._id,
}, {
_cronSignature: 'NOT_RUNNING',
}).exec();
throw err; // re-throw the original error
}
return null;
}
}
export default function cronMiddleware (req, res, next) {
cronAsync(req, res)
.then(() => {
next();
})
.catch(next);
}