lila/bin/mongodb/msg_import.js

91 lines
2.3 KiB
JavaScript
Raw Normal View History

2020-01-26 19:27:18 -07:00
db.msg_msg.drop();
db.msg_thread.drop();
function makeIndexes() {
2021-02-06 06:26:05 -07:00
db.msg_thread.ensureIndex({ users: 1, 'lastMsg.date': -1 }, { background: 1 });
db.msg_thread.ensureIndex({ users: 1 }, { partialFilterExpression: { 'lastMsg.read': false }, background: 1 });
db.msg_msg.ensureIndex({ tid: 1, date: -1 }, { background: 1 });
2020-01-26 19:27:18 -07:00
}
2020-01-24 13:10:07 -07:00
2020-01-25 17:18:21 -07:00
const now = Date.now();
2021-02-06 06:26:05 -07:00
print('Delete old notifications');
db.notify.remove({ 'content.type': 'privateMessage' });
2020-01-25 17:18:21 -07:00
2020-01-28 21:59:24 -07:00
if (!db.m_thread_sorted.count()) {
2021-02-06 06:26:05 -07:00
print('Create db.m_thread_sorted');
2020-01-24 13:10:07 -07:00
db.m_thread_sorted.drop();
2021-02-06 06:26:05 -07:00
db.m_thread
.find({
mod: { $exists: false },
visibleByUserIds: { $size: 2 },
$or: [
{
creatorId: {
$nin: ['lichess', 'lichess-qa', 'lichess-blog', 'lichess-team', 'mirlife', 'lichess4545', 'whatnext'],
},
},
{
updatedAt: { $gt: new Date(Date.now() - 1000 * 3600 * 24 * 14) },
},
],
})
.forEach(t => {
if (t.creatorId == t.invitedId) return;
t.visibleByUserIds.sort();
db.m_thread_sorted.insert(t);
});
2020-01-24 13:10:07 -07:00
}
2021-02-06 06:26:05 -07:00
print('Create db.msg_thread');
db.m_thread_sorted
.aggregate([{ $group: { _id: '$visibleByUserIds', threads: { $push: '$$ROOT' } } }], { allowDiskUse: true })
.forEach(o => {
let userIds = o.threads[0].visibleByUserIds;
userIds.sort();
let threadId = userIds.join('/');
2020-01-24 13:10:07 -07:00
2021-02-06 06:26:05 -07:00
let msgs = [];
2020-01-24 15:48:23 -07:00
2021-02-06 06:26:05 -07:00
o.threads.forEach(t => {
t.posts.forEach(p => {
if (o.creatorId == 'lichess' && isOld(p.createdAt)) return;
msgs.push({
_id: p.id,
tid: threadId,
text: p.text,
user: p.isByCreator ? t.creatorId : t.invitedId,
date: p.createdAt,
});
2020-01-24 15:48:23 -07:00
});
});
2020-01-24 13:10:07 -07:00
2021-02-06 06:26:05 -07:00
if (!msgs.length) return;
2020-01-27 07:32:04 -07:00
2021-02-06 06:26:05 -07:00
msgs.sort((a, b) => new Date(a.date) - new Date(b.date));
2020-01-24 13:10:07 -07:00
2021-02-06 06:26:05 -07:00
let last = msgs[msgs.length - 1];
2020-01-24 13:10:07 -07:00
2021-02-06 06:26:05 -07:00
let thread = {
_id: threadId,
users: userIds,
lastMsg: {
text: last.text.slice(0, 60),
user: last.user,
date: last.date,
read: !o.threads.find(t => t.posts.find(p => p.isRead)) || isOld(last.date),
},
};
2020-01-24 13:10:07 -07:00
2021-02-06 06:26:05 -07:00
db.msg_msg.insertMany(msgs, { ordered: false });
try {
db.msg_thread.insert(thread);
} catch (e) {}
});
2020-01-25 17:18:21 -07:00
2020-01-26 19:27:18 -07:00
makeIndexes();
2020-01-25 17:18:21 -07:00
function isOld(date) {
return now - date > 1000 * 3600 * 24 * 7;
}