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