Cleanup models
[oweals/peertube.git] / server / models / video / video-file.ts
1 import * as Sequelize from 'sequelize'
2 import { values } from 'lodash'
3
4 import { CONSTRAINTS_FIELDS } from '../../initializers'
5 import {
6   isVideoFileResolutionValid,
7   isVideoFileSizeValid,
8   isVideoFileInfoHashValid
9 } from '../../helpers'
10
11 import { addMethodsToModel } from '../utils'
12 import {
13   VideoFileInstance,
14   VideoFileAttributes
15 } from './video-file-interface'
16
17 let VideoFile: Sequelize.Model<VideoFileInstance, VideoFileAttributes>
18
19 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
20   VideoFile = sequelize.define<VideoFileInstance, VideoFileAttributes>('VideoFile',
21     {
22       resolution: {
23         type: DataTypes.INTEGER,
24         allowNull: false,
25         validate: {
26           resolutionValid: value => {
27             const res = isVideoFileResolutionValid(value)
28             if (res === false) throw new Error('Video file resolution is not valid.')
29           }
30         }
31       },
32       size: {
33         type: DataTypes.BIGINT,
34         allowNull: false,
35         validate: {
36           sizeValid: value => {
37             const res = isVideoFileSizeValid(value)
38             if (res === false) throw new Error('Video file size is not valid.')
39           }
40         }
41       },
42       extname: {
43         type: DataTypes.ENUM(values(CONSTRAINTS_FIELDS.VIDEOS.EXTNAME)),
44         allowNull: false
45       },
46       infoHash: {
47         type: DataTypes.STRING,
48         allowNull: false,
49         validate: {
50           infoHashValid: value => {
51             const res = isVideoFileInfoHashValid(value)
52             if (res === false) throw new Error('Video file info hash is not valid.')
53           }
54         }
55       }
56     },
57     {
58       indexes: [
59         {
60           fields: [ 'videoId' ]
61         },
62         {
63           fields: [ 'infoHash' ]
64         }
65       ]
66     }
67   )
68
69   const classMethods = [
70     associate
71   ]
72   addMethodsToModel(VideoFile, classMethods)
73
74   return VideoFile
75 }
76
77 // ------------------------------ STATICS ------------------------------
78
79 function associate (models) {
80   VideoFile.belongsTo(models.Video, {
81     foreignKey: {
82       name: 'videoId',
83       allowNull: false
84     },
85     onDelete: 'CASCADE'
86   })
87 }
88
89 // ------------------------------ METHODS ------------------------------