Put config redundancy strategies in "strategies" subkey
[oweals/peertube.git] / server / models / video / tag.ts
1 import * as Bluebird from 'bluebird'
2 import * as Sequelize 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
10 @Table({
11   tableName: 'tag',
12   timestamps: false,
13   indexes: [
14     {
15       fields: [ 'name' ],
16       unique: true
17     }
18   ]
19 })
20 export class TagModel extends Model<TagModel> {
21
22   @AllowNull(false)
23   @Is('VideoTag', value => throwIfNotValid(value, isVideoTagValid, 'tag'))
24   @Column
25   name: string
26
27   @CreatedAt
28   createdAt: Date
29
30   @UpdatedAt
31   updatedAt: Date
32
33   @BelongsToMany(() => VideoModel, {
34     foreignKey: 'tagId',
35     through: () => VideoTagModel,
36     onDelete: 'CASCADE'
37   })
38   Videos: VideoModel[]
39
40   static findOrCreateTags (tags: string[], transaction: Sequelize.Transaction) {
41     if (tags === null) return []
42
43     const tasks: Bluebird<TagModel>[] = []
44     tags.forEach(tag => {
45       const query = {
46         where: {
47           name: tag
48         },
49         defaults: {
50           name: tag
51         },
52         transaction
53       }
54
55       const promise = TagModel.findOrCreate(query)
56         .then(([ tagInstance ]) => tagInstance)
57       tasks.push(promise)
58     })
59
60     return Promise.all(tasks)
61   }
62
63   // threshold corresponds to how many video the field should have to be returned
64   static getRandomSamples (threshold: number, count: number): Bluebird<string[]> {
65     const query = 'SELECT tag.name FROM tag ' +
66       'INNER JOIN "videoTag" ON "videoTag"."tagId" = tag.id ' +
67       'INNER JOIN video ON video.id = "videoTag"."videoId" ' +
68       'WHERE video.privacy = $videoPrivacy AND video.state = $videoState ' +
69       'GROUP BY tag.name HAVING COUNT(tag.name) >= $threshold ' +
70       'ORDER BY random() ' +
71       'LIMIT $count'
72
73     const options = {
74       bind: { threshold, count, videoPrivacy: VideoPrivacy.PUBLIC, videoState: VideoState.PUBLISHED },
75       type: Sequelize.QueryTypes.SELECT
76     }
77
78     return TagModel.sequelize.query(query, options)
79                     .then(data => data.map(d => d.name))
80   }
81 }