misskey/src/server/api/common/inject-promo.ts

35 lines
976 B
TypeScript
Raw Normal View History

2020-02-18 08:41:32 +09:00
import rndstr from 'rndstr';
import { Note } from '../../../models/entities/note';
import { User } from '../../../models/entities/user';
import { PromoReads, PromoNotes, Notes, Users } from '../../../models';
2020-02-18 19:05:11 +09:00
export async function injectPromo(timeline: Note[], user?: User | null) {
2020-02-18 08:41:32 +09:00
if (timeline.length < 5) return;
// TODO: readやexpireフィルタはクエリ側でやる
2020-02-18 19:05:11 +09:00
const reads = user ? await PromoReads.find({
2020-02-18 08:41:32 +09:00
userId: user.id
2020-02-18 19:05:11 +09:00
}) : [];
2020-02-18 08:41:32 +09: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 19:05:11 +09:00
// Pick random promo
2020-02-18 08:41:32 +09:00
const promo = promos[Math.floor(Math.random() * promos.length)];
2021-02-13 15:33:38 +09:00
const note = await Notes.findOneOrFail(promo.noteId);
2020-02-18 08:41:32 +09:00
// Join
2021-02-13 15:33:38 +09:00
note.user = await Users.findOneOrFail(note.userId);
2020-02-18 08:41:32 +09:00
2020-02-18 19:05:11 +09:00
(note as any)._prId_ = rndstr('a-z0-9', 8);
2020-02-18 08:41:32 +09:00
// Inject promo
timeline.splice(3, 0, note);
}