Add ability to import video with youtube-dl
[oweals/peertube.git] / server / models / video / video-import.ts
1 import {
2   AllowNull,
3   BelongsTo,
4   Column,
5   CreatedAt,
6   DataType,
7   Default,
8   DefaultScope,
9   ForeignKey,
10   Is,
11   Model,
12   Table,
13   UpdatedAt
14 } from 'sequelize-typescript'
15 import { CONSTRAINTS_FIELDS } from '../../initializers'
16 import { throwIfNotValid } from '../utils'
17 import { VideoModel } from './video'
18 import { isVideoImportStateValid, isVideoImportTargetUrlValid } from '../../helpers/custom-validators/video-imports'
19 import { VideoImport, VideoImportState } from '../../../shared'
20 import { VideoChannelModel } from './video-channel'
21 import { AccountModel } from '../account/account'
22
23 @DefaultScope({
24   include: [
25     {
26       model: () => VideoModel,
27       required: true,
28       include: [
29         {
30           model: () => VideoChannelModel,
31           required: true,
32           include: [
33             {
34               model: () => AccountModel,
35               required: true
36             }
37           ]
38         }
39       ]
40     }
41   ]
42 })
43
44 @Table({
45   tableName: 'videoImport',
46   indexes: [
47     {
48       fields: [ 'videoId' ],
49       unique: true
50     }
51   ]
52 })
53 export class VideoImportModel extends Model<VideoImportModel> {
54   @CreatedAt
55   createdAt: Date
56
57   @UpdatedAt
58   updatedAt: Date
59
60   @AllowNull(false)
61   @Is('VideoImportTargetUrl', value => throwIfNotValid(value, isVideoImportTargetUrlValid, 'targetUrl'))
62   @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_IMPORTS.URL.max))
63   targetUrl: string
64
65   @AllowNull(false)
66   @Default(null)
67   @Is('VideoImportState', value => throwIfNotValid(value, isVideoImportStateValid, 'state'))
68   @Column
69   state: VideoImportState
70
71   @AllowNull(true)
72   @Default(null)
73   @Column(DataType.TEXT)
74   error: string
75
76   @ForeignKey(() => VideoModel)
77   @Column
78   videoId: number
79
80   @BelongsTo(() => VideoModel, {
81     foreignKey: {
82       allowNull: false
83     },
84     onDelete: 'CASCADE'
85   })
86   Video: VideoModel
87
88   static loadAndPopulateVideo (id: number) {
89     return VideoImportModel.findById(id)
90   }
91
92   toFormattedJSON (): VideoImport {
93     const videoFormatOptions = {
94       additionalAttributes: { state: true, waitTranscoding: true, scheduledUpdate: true }
95     }
96     const video = Object.assign(this.Video.toFormattedJSON(videoFormatOptions), {
97       tags: this.Video.Tags.map(t => t.name)
98     })
99
100     return {
101       targetUrl: this.targetUrl,
102       video
103     }
104   }
105 }