Merge branch 'release/1.4.0' into develop
[oweals/peertube.git] / server / models / video / tag.ts
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'
10
11 @Table({
12   tableName: 'tag',
13   timestamps: false,
14   indexes: [
15     {
16       fields: [ 'name' ],
17       unique: true
18     }
19   ]
20 })
21 export class TagModel extends Model<TagModel> {
22
23   @AllowNull(false)
24   @Is('VideoTag', value => throwIfNotValid(value, isVideoTagValid, 'tag'))
25   @Column
26   name: string
27
28   @CreatedAt
29   createdAt: Date
30
31   @UpdatedAt
32   updatedAt: Date
33
34   @BelongsToMany(() => VideoModel, {
35     foreignKey: 'tagId',
36     through: () => VideoTagModel,
37     onDelete: 'CASCADE'
38   })
39   Videos: VideoModel[]
40
41   static findOrCreateTags (tags: string[], transaction: Transaction): Promise<MTag[]> {
42     if (tags === null) return Promise.resolve([])
43
44     const tasks: Bluebird<MTag>[] = []
45     tags.forEach(tag => {
46       const query = {
47         where: {
48           name: tag
49         },
50         defaults: {
51           name: tag
52         },
53         transaction
54       }
55
56       const promise = TagModel.findOrCreate<MTag>(query)
57         .then(([ tagInstance ]) => tagInstance)
58       tasks.push(promise)
59     })
60
61     return Promise.all(tasks)
62   }
63
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() ' +
72       'LIMIT $count'
73
74     const options = {
75       bind: { threshold, count, videoPrivacy: VideoPrivacy.PUBLIC, videoState: VideoState.PUBLISHED },
76       type: QueryTypes.SELECT as QueryTypes.SELECT
77     }
78
79     return TagModel.sequelize.query<{ name: string }>(query, options)
80                     .then(data => data.map(d => d.name))
81   }
82 }