tag.ts 2.4 KB

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