Split types and typings
[oweals/peertube.git] / server / models / video / tag.ts
index 0ae74d80850bbe8f1b0d2a30754967863deb4a22..adbc4fb7d6c22b2d2015399cafbdef4589575ec4 100644 (file)
@@ -1,10 +1,12 @@
 import * as Bluebird from 'bluebird'
-import { Transaction } from 'sequelize'
+import { fn, QueryTypes, Transaction, col } from 'sequelize'
 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'
+import { VideoPrivacy, VideoState } from '../../../shared/models/videos'
+import { MTag } from '@server/types/models'
 
 @Table({
   tableName: 'tag',
@@ -13,6 +15,10 @@ import { VideoTagModel } from './video-tag'
     {
       fields: [ 'name' ],
       unique: true
+    },
+    {
+      name: 'tag_lower_name',
+      fields: [ fn('lower', col('name')) ] as any // FIXME: typings
     }
   ]
 })
@@ -36,8 +42,10 @@ export class TagModel extends Model<TagModel> {
   })
   Videos: VideoModel[]
 
-  static findOrCreateTags (tags: string[], transaction: Transaction) {
-    const tasks: Bluebird<TagModel>[] = []
+  static findOrCreateTags (tags: string[], transaction: Transaction): Promise<MTag[]> {
+    if (tags === null) return Promise.resolve([])
+
+    const tasks: Bluebird<MTag>[] = []
     tags.forEach(tag => {
       const query = {
         where: {
@@ -45,16 +53,34 @@ export class TagModel extends Model<TagModel> {
         },
         defaults: {
           name: tag
-        }
+        },
+        transaction
       }
 
-      if (transaction) query['transaction'] = transaction
-
-      const promise = TagModel.findOrCreate(query)
+      const promise = TagModel.findOrCreate<MTag>(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): 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 },
+      type: QueryTypes.SELECT as QueryTypes.SELECT
+    }
+
+    return TagModel.sequelize.query<{ name: string }>(query, options)
+                    .then(data => data.map(d => d.name))
+  }
 }