diff options
| author | syuilo <Syuilotan@yahoo.co.jp> | 2020-02-18 08:41:32 +0900 |
|---|---|---|
| committer | syuilo <Syuilotan@yahoo.co.jp> | 2020-02-18 08:41:32 +0900 |
| commit | a54de07260c3555d0230492970448604ffb9d586 (patch) | |
| tree | 0650c5de48af1cd5b5945da6a3dff6093ceaefd1 /src/server/api/common | |
| parent | Fix type (diff) | |
| download | sharkey-a54de07260c3555d0230492970448604ffb9d586.tar.gz sharkey-a54de07260c3555d0230492970448604ffb9d586.tar.bz2 sharkey-a54de07260c3555d0230492970448604ffb9d586.zip | |
Resolve #5963
Diffstat (limited to 'src/server/api/common')
| -rw-r--r-- | src/server/api/common/inject-promo.ts | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/src/server/api/common/inject-promo.ts b/src/server/api/common/inject-promo.ts new file mode 100644 index 0000000000..785d7af085 --- /dev/null +++ b/src/server/api/common/inject-promo.ts @@ -0,0 +1,36 @@ +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'; + +export async function injectPromo(user: User, timeline: Note[]) { + if (timeline.length < 5) return; + + // TODO: readやexpireフィルタはクエリ側でやる + + const reads = await PromoReads.find({ + userId: user.id + }); + + 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; + + const promo = promos[Math.floor(Math.random() * promos.length)]; + + // Pick random promo + const note = await Notes.findOne(promo.noteId).then(ensure); + + // Join + note.user = await Users.findOne(note.userId).then(ensure); + + (note as any)._prInjectionId_ = rndstr('a-z0-9', 8); + + // Inject promo + timeline.splice(3, 0, note); + timeline.pop(); +} |