2020-02-17 23:41:32 +00:00
|
|
|
import rndstr from 'rndstr';
|
|
|
|
import { Note } from '../../../models/entities/note';
|
|
|
|
import { User } from '../../../models/entities/user';
|
|
|
|
import { PromoReads, PromoNotes, Notes, Users } from '../../../models';
|
|
|
|
import { ensure } from '../../../prelude/ensure';
|
|
|
|
|
2020-02-18 10:05:11 +00:00
|
|
|
export async function injectPromo(timeline: Note[], user?: User | null) {
|
2020-02-17 23:41:32 +00:00
|
|
|
if (timeline.length < 5) return;
|
|
|
|
|
|
|
|
// TODO: readやexpireフィルタはクエリ側でやる
|
|
|
|
|
2020-02-18 10:05:11 +00:00
|
|
|
const reads = user ? await PromoReads.find({
|
2020-02-17 23:41:32 +00:00
|
|
|
userId: user.id
|
2020-02-18 10:05:11 +00:00
|
|
|
}) : [];
|
2020-02-17 23:41:32 +00:00
|
|
|
|
|
|
|
let promos = await PromoNotes.find();
|
|
|
|
|
|
|
|
promos = promos.filter(n => n.expiresAt.getTime() > Date.now());
|
|
|
|
promos = promos.filter(n => !reads.map(r => r.noteId).includes(n.noteId));
|
|
|
|
|
|
|
|
if (promos.length === 0) return;
|
|
|
|
|
2020-02-18 10:05:11 +00:00
|
|
|
// Pick random promo
|
2020-02-17 23:41:32 +00:00
|
|
|
const promo = promos[Math.floor(Math.random() * promos.length)];
|
|
|
|
|
|
|
|
const note = await Notes.findOne(promo.noteId).then(ensure);
|
|
|
|
|
|
|
|
// Join
|
|
|
|
note.user = await Users.findOne(note.userId).then(ensure);
|
|
|
|
|
2020-02-18 10:05:11 +00:00
|
|
|
(note as any)._prId_ = rndstr('a-z0-9', 8);
|
2020-02-17 23:41:32 +00:00
|
|
|
|
|
|
|
// Inject promo
|
|
|
|
timeline.splice(3, 0, note);
|
|
|
|
}
|