X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=server%2Fmodels%2Fvideo%2Ftag.ts;h=61dfb224d37c21d5223aa4495e9ec5504f03d8c2;hb=fa66c9a601d69f6d57c956a3513e8bbed7ee9616;hp=6d79a55756ad212f84977a383be0757525d950dd;hpb=2efd32f697549c59337db5177a93749af8e605d8;p=github%2FChocobozzz%2FPeerTube.git diff --git a/server/models/video/tag.ts b/server/models/video/tag.ts index 6d79a5575..61dfb224d 100644 --- a/server/models/video/tag.ts +++ b/server/models/video/tag.ts @@ -1,6 +1,8 @@ -import * as Bluebird from 'bluebird' -import { Transaction } from 'sequelize' +import { col, fn, QueryTypes, Transaction } from 'sequelize' import { AllowNull, BelongsToMany, Column, CreatedAt, Is, Model, Table, UpdatedAt } from 'sequelize-typescript' +import { MTag } from '@server/types/models' +import { AttributesOnly } from '@shared/core-utils' +import { VideoPrivacy, VideoState } from '../../../shared/models/videos' import { isVideoTagValid } from '../../helpers/custom-validators/videos' import { throwIfNotValid } from '../utils' import { VideoModel } from './video' @@ -13,10 +15,14 @@ import { VideoTagModel } from './video-tag' { fields: [ 'name' ], unique: true + }, + { + name: 'tag_lower_name', + fields: [ fn('lower', col('name')) ] } ] }) -export class TagModel extends Model { +export class TagModel extends Model>> { @AllowNull(false) @Is('VideoTag', value => throwIfNotValid(value, isVideoTagValid, 'tag')) @@ -36,10 +42,10 @@ export class TagModel extends Model { }) Videos: VideoModel[] - static findOrCreateTags (tags: string[], transaction: Transaction) { - if (tags === null) return [] + static findOrCreateTags (tags: string[], transaction: Transaction): Promise { + if (tags === null) return Promise.resolve([]) - const tasks: Bluebird[] = [] + const tasks: Promise[] = [] tags.forEach(tag => { const query = { where: { @@ -47,16 +53,34 @@ export class TagModel extends Model { }, defaults: { name: tag - } + }, + transaction } - if (transaction) query['transaction'] = transaction - - const promise = TagModel.findOrCreate(query) + const promise = TagModel.findOrCreate(query) .then(([ tagInstance ]) => tagInstance) tasks.push(promise) }) return Promise.all(tasks) } + + // threshold corresponds to how many video the field should have to be returned + static getRandomSamples (threshold: number, count: number): Promise { + 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 }, + type: QueryTypes.SELECT as QueryTypes.SELECT + } + + return TagModel.sequelize.query<{ name: string }>(query, options) + .then(data => data.map(d => d.name)) + } }