Filter tracker based on infohash
[oweals/peertube.git] / server / models / video / video-file.ts
1 import { values } from 'lodash'
2 import { AllowNull, BelongsTo, Column, CreatedAt, DataType, Default, ForeignKey, Is, Model, Table, UpdatedAt } from 'sequelize-typescript'
3 import {
4   isVideoFileInfoHashValid,
5   isVideoFileResolutionValid,
6   isVideoFileSizeValid,
7   isVideoFPSResolutionValid
8 } from '../../helpers/custom-validators/videos'
9 import { CONSTRAINTS_FIELDS } from '../../initializers'
10 import { throwIfNotValid } from '../utils'
11 import { VideoModel } from './video'
12 import * as Sequelize from 'sequelize'
13
14 @Table({
15   tableName: 'videoFile',
16   indexes: [
17     {
18       fields: [ 'videoId' ]
19     },
20     {
21       fields: [ 'infoHash' ]
22     },
23     {
24       fields: [ 'videoId', 'resolution', 'fps' ],
25       unique: true
26     }
27   ]
28 })
29 export class VideoFileModel extends Model<VideoFileModel> {
30   @CreatedAt
31   createdAt: Date
32
33   @UpdatedAt
34   updatedAt: Date
35
36   @AllowNull(false)
37   @Is('VideoFileResolution', value => throwIfNotValid(value, isVideoFileResolutionValid, 'resolution'))
38   @Column
39   resolution: number
40
41   @AllowNull(false)
42   @Is('VideoFileSize', value => throwIfNotValid(value, isVideoFileSizeValid, 'size'))
43   @Column(DataType.BIGINT)
44   size: number
45
46   @AllowNull(false)
47   @Column(DataType.ENUM(values(CONSTRAINTS_FIELDS.VIDEOS.EXTNAME)))
48   extname: string
49
50   @AllowNull(false)
51   @Is('VideoFileSize', value => throwIfNotValid(value, isVideoFileInfoHashValid, 'info hash'))
52   @Column
53   infoHash: string
54
55   @AllowNull(true)
56   @Default(null)
57   @Is('VideoFileFPS', value => throwIfNotValid(value, isVideoFPSResolutionValid, 'fps'))
58   @Column
59   fps: number
60
61   @ForeignKey(() => VideoModel)
62   @Column
63   videoId: number
64
65   @BelongsTo(() => VideoModel, {
66     foreignKey: {
67       allowNull: false
68     },
69     onDelete: 'CASCADE'
70   })
71   Video: VideoModel
72
73   static isInfohashExists (infoHash: string) {
74     const query = 'SELECT 1 FROM "videoFile" WHERE "infoHash" = $infoHash LIMIT 1'
75     const options = {
76       type: Sequelize.QueryTypes.SELECT,
77       bind: { infoHash },
78       raw: true
79     }
80
81     return VideoModel.sequelize.query(query, options)
82               .then(results => {
83                 return results.length === 1
84               })
85   }
86 }