1 import * as Bluebird from 'bluebird'
2 import { QueryTypes, Transaction } 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/typings/models'
21 export class TagModel extends Model<TagModel> {
24 @Is('VideoTag', value => throwIfNotValid(value, isVideoTagValid, 'tag'))
34 @BelongsToMany(() => VideoModel, {
36 through: () => VideoTagModel,
41 static findOrCreateTags (tags: string[], transaction: Transaction): Promise<MTag[]> {
42 if (tags === null) return Promise.resolve([])
44 const tasks: Bluebird<MTag>[] = []
56 const promise = TagModel.findOrCreate<MTag>(query)
57 .then(([ tagInstance ]) => tagInstance)
61 return Promise.all(tasks)
64 // threshold corresponds to how many video the field should have to be returned
65 static getRandomSamples (threshold: number, count: number): Bluebird<string[]> {
66 const query = 'SELECT tag.name FROM tag ' +
67 'INNER JOIN "videoTag" ON "videoTag"."tagId" = tag.id ' +
68 'INNER JOIN video ON video.id = "videoTag"."videoId" ' +
69 'WHERE video.privacy = $videoPrivacy AND video.state = $videoState ' +
70 'GROUP BY tag.name HAVING COUNT(tag.name) >= $threshold ' +
71 'ORDER BY random() ' +
75 bind: { threshold, count, videoPrivacy: VideoPrivacy.PUBLIC, videoState: VideoState.PUBLISHED },
76 type: QueryTypes.SELECT as QueryTypes.SELECT
79 return TagModel.sequelize.query<{ name: string }>(query, options)
80 .then(data => data.map(d => d.name))