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