1 import * as Bluebird from 'bluebird'
2 import { fn, QueryTypes, Transaction, col } from 'sequelize'
3 import { AllowNull, BelongsToMany, Column, CreatedAt, Is, Model, Table, UpdatedAt } from 'sequelize-typescript'
4 import { isVideoTagValid } from '../../helpers/custom-validators/videos'
5 import { throwIfNotValid } from '../utils'
6 import { VideoModel } from './video'
7 import { VideoTagModel } from './video-tag'
8 import { VideoPrivacy, VideoState } from '../../../shared/models/videos'
9 import { MTag } from '@server/types/models'
20 name: 'tag_lower_name',
21 fields: [ fn('lower', col('name')) ] as any // FIXME: typings
25 export class TagModel extends Model<TagModel> {
28 @Is('VideoTag', value => throwIfNotValid(value, isVideoTagValid, 'tag'))
38 @BelongsToMany(() => VideoModel, {
40 through: () => VideoTagModel,
45 static findOrCreateTags (tags: string[], transaction: Transaction): Promise<MTag[]> {
46 if (tags === null) return Promise.resolve([])
48 const tasks: Bluebird<MTag>[] = []
60 const promise = TagModel.findOrCreate<MTag>(query)
61 .then(([ tagInstance ]) => tagInstance)
65 return Promise.all(tasks)
68 // threshold corresponds to how many video the field should have to be returned
69 static getRandomSamples (threshold: number, count: number): Bluebird<string[]> {
70 const query = 'SELECT tag.name FROM tag ' +
71 'INNER JOIN "videoTag" ON "videoTag"."tagId" = tag.id ' +
72 'INNER JOIN video ON video.id = "videoTag"."videoId" ' +
73 'WHERE video.privacy = $videoPrivacy AND video.state = $videoState ' +
74 'GROUP BY tag.name HAVING COUNT(tag.name) >= $threshold ' +
75 'ORDER BY random() ' +
79 bind: { threshold, count, videoPrivacy: VideoPrivacy.PUBLIC, videoState: VideoState.PUBLISHED },
80 type: QueryTypes.SELECT as QueryTypes.SELECT
83 return TagModel.sequelize.query<{ name: string }>(query, options)
84 .then(data => data.map(d => d.name))