PeerTube/server/models/video/tag.ts

82 lines
2.3 KiB
TypeScript
Raw Normal View History

2017-12-12 17:53:50 +01:00
import * as Bluebird from 'bluebird'
2019-04-18 11:28:17 +02:00
import { QueryTypes, Transaction } from 'sequelize'
2017-12-12 17:53:50 +01:00
import { AllowNull, BelongsToMany, Column, CreatedAt, Is, Model, Table, UpdatedAt } from 'sequelize-typescript'
import { isVideoTagValid } from '../../helpers/custom-validators/videos'
import { throwIfNotValid } from '../utils'
import { VideoModel } from './video'
import { VideoTagModel } from './video-tag'
2018-08-30 14:58:00 +02:00
import { VideoPrivacy, VideoState } from '../../../shared/models/videos'
2017-12-12 17:53:50 +01:00
@Table({
tableName: 'tag',
timestamps: false,
indexes: [
2016-12-24 16:59:17 +01:00
{
2017-12-12 17:53:50 +01:00
fields: [ 'name' ],
unique: true
2016-12-24 16:59:17 +01:00
}
2017-05-22 20:58:25 +02:00
]
2017-12-12 17:53:50 +01:00
})
export class TagModel extends Model<TagModel> {
2017-05-22 20:58:25 +02:00
2017-12-12 17:53:50 +01:00
@AllowNull(false)
@Is('VideoTag', value => throwIfNotValid(value, isVideoTagValid, 'tag'))
@Column
name: string
2016-12-24 16:59:17 +01:00
2017-12-12 17:53:50 +01:00
@CreatedAt
createdAt: Date
2016-12-24 16:59:17 +01:00
2017-12-12 17:53:50 +01:00
@UpdatedAt
updatedAt: Date
@BelongsToMany(() => VideoModel, {
2016-12-24 16:59:17 +01:00
foreignKey: 'tagId',
2017-12-12 17:53:50 +01:00
through: () => VideoTagModel,
onDelete: 'CASCADE'
2016-12-24 16:59:17 +01:00
})
2017-12-12 17:53:50 +01:00
Videos: VideoModel[]
2019-04-18 11:28:17 +02:00
static findOrCreateTags (tags: string[], transaction: Transaction) {
2018-05-16 09:28:18 +02:00
if (tags === null) return []
2017-12-12 17:53:50 +01:00
const tasks: Bluebird<TagModel>[] = []
tags.forEach(tag => {
const query = {
where: {
name: tag
},
defaults: {
name: tag
},
transaction
2016-12-29 18:02:03 +01:00
}
2017-12-12 17:53:50 +01:00
const promise = TagModel.findOrCreate(query)
.then(([ tagInstance ]) => tagInstance)
tasks.push(promise)
})
2017-12-12 17:53:50 +01:00
return Promise.all(tasks)
}
2018-08-30 14:58:00 +02:00
// threshold corresponds to how many video the field should have to be returned
static getRandomSamples (threshold: number, count: number): Bluebird<string[]> {
const query = 'SELECT tag.name FROM tag ' +
'INNER JOIN "videoTag" ON "videoTag"."tagId" = tag.id ' +
'INNER JOIN video ON video.id = "videoTag"."videoId" ' +
'WHERE video.privacy = $videoPrivacy AND video.state = $videoState ' +
'GROUP BY tag.name HAVING COUNT(tag.name) >= $threshold ' +
'ORDER BY random() ' +
'LIMIT $count'
const options = {
bind: { threshold, count, videoPrivacy: VideoPrivacy.PUBLIC, videoState: VideoState.PUBLISHED },
2019-04-18 11:28:17 +02:00
type: QueryTypes.SELECT as QueryTypes.SELECT
2018-08-30 14:58:00 +02:00
}
2019-04-18 11:28:17 +02:00
return TagModel.sequelize.query<{ name }>(query, options)
2018-08-30 14:58:00 +02:00
.then(data => data.map(d => d.name))
}
2016-12-29 18:02:03 +01:00
}