fix invalid push devices

This commit is contained in:
Matteo Pagliazzi
2020-03-01 21:49:52 +01:00
parent 6deee0ffc8
commit 3f5ee32684
5 changed files with 89 additions and 10 deletions
+27
View File
@@ -1,4 +1,5 @@
import mongoose from 'mongoose';
import _ from 'lodash';
import baseModel from '../libs/baseModel';
const { Schema } = mongoose;
@@ -19,4 +20,30 @@ schema.plugin(baseModel, {
_id: false,
});
/**
* Remove invalid data from an array of push devices.
* Fix for https://github.com/HabitRPG/habitica/issues/11805
* and https://github.com/HabitRPG/habitica/issues/11868
* Called by user's post init hook (models/user/hooks.js)
*/
schema.statics.cleanupCorruptData = function cleanupCorruptPushDevicesData (pushDevices) {
if (!pushDevices) return pushDevices;
let filteredPushDevices = pushDevices.filter(pushDevice => {
// Exclude push devices with a nullish value, no id or no type
if (!pushDevice || !pushDevice.regId || !pushDevice.type) return false;
return true;
});
// Remove duplicate push devices
// can be caused by a race condition when adding a new push device
filteredPushDevices = _.uniqWith(filteredPushDevices, (val, otherVal) => {
if (val.regId === otherVal.regId && val.type === otherVal.type) return true;
return false;
});
return filteredPushDevices;
};
export const model = mongoose.model('PushDevice', schema);
+8
View File
@@ -6,6 +6,9 @@ import * as Tasks from '../task';
import {
model as UserNotification,
} from '../userNotification';
import {
model as PushDevice,
} from '../pushDevice';
import { // eslint-disable-line import/no-cycle
userActivityWebhook,
} from '../../libs/webhook';
@@ -190,6 +193,11 @@ schema.post('init', function postInitUser () {
this.notifications = UserNotification.cleanupCorruptData(this.notifications);
}
// Make sure pushDevices are loaded
if (this.isDirectSelected('pushDevices')) {
this.pushDevices = PushDevice.cleanupCorruptData(this.pushDevices);
}
return true;
});
@@ -93,7 +93,6 @@ export const schema = new Schema({
* Called by user's post init hook (models/user/hooks.js)
*/
schema.statics.cleanupCorruptData = function cleanupCorruptNotificationsData (notifications) {
console.log('fixing stuff', notifications);
if (!notifications) return notifications;
let filteredNotifications = notifications.filter(notification => {