15 } from 'sequelize-typescript'
16 import { CONSTRAINTS_FIELDS, VIDEO_IMPORT_STATES } from '../../initializers'
17 import { getSort, throwIfNotValid } from '../utils'
18 import { ScopeNames as VideoModelScopeNames, VideoModel } from './video'
19 import { isVideoImportStateValid, isVideoImportTargetUrlValid } from '../../helpers/custom-validators/video-imports'
20 import { VideoImport, VideoImportState } from '../../../shared'
21 import { isVideoMagnetUriValid } from '../../helpers/custom-validators/videos'
22 import { UserModel } from '../account/user'
27 model: () => UserModel.unscoped(),
31 model: () => VideoModel.scope([ VideoModelScopeNames.WITH_ACCOUNT_DETAILS, VideoModelScopeNames.WITH_TAGS]),
38 tableName: 'videoImport',
41 fields: [ 'videoId' ],
49 export class VideoImportModel extends Model<VideoImportModel> {
58 @Is('VideoImportTargetUrl', value => throwIfNotValid(value, isVideoImportTargetUrlValid, 'targetUrl'))
59 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_IMPORTS.URL.max))
64 @Is('VideoImportMagnetUri', value => throwIfNotValid(value, isVideoMagnetUriValid, 'magnetUri'))
65 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_IMPORTS.URL.max)) // Use the same constraints than URLs
70 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_IMPORTS.TORRENT_NAME.max))
75 @Is('VideoImportState', value => throwIfNotValid(value, isVideoImportStateValid, 'state'))
77 state: VideoImportState
81 @Column(DataType.TEXT)
84 @ForeignKey(() => UserModel)
88 @BelongsTo(() => UserModel, {
96 @ForeignKey(() => VideoModel)
100 @BelongsTo(() => VideoModel, {
109 static deleteVideoIfFailed (instance: VideoImportModel, options) {
110 if (instance.state === VideoImportState.FAILED) {
111 return instance.Video.destroy({ transaction: options.transaction })
117 static loadAndPopulateVideo (id: number) {
118 return VideoImportModel.findById(id)
121 static listUserVideoImportsForApi (userId: number, start: number, count: number, sort: string) {
126 model: UserModel.unscoped(), // FIXME: Without this, sequelize try to COUNT(DISTINCT(*)) which is an invalid SQL query
132 order: getSort(sort),
138 return VideoImportModel.findAndCountAll(query)
139 .then(({ rows, count }) => {
147 toFormattedJSON (): VideoImport {
148 const videoFormatOptions = {
149 additionalAttributes: { state: true, waitTranscoding: true, scheduledUpdate: true }
151 const video = this.Video
152 ? Object.assign(this.Video.toFormattedJSON(videoFormatOptions), {
153 tags: this.Video.Tags.map(t => t.name)
160 targetUrl: this.targetUrl,
161 magnetUri: this.magnetUri,
162 torrentName: this.torrentName,
166 label: VideoImportModel.getStateLabel(this.state)
169 updatedAt: this.updatedAt.toISOString(),
170 createdAt: this.createdAt.toISOString(),
175 private static getStateLabel (id: number) {
176 return VIDEO_IMPORT_STATES[id] || 'Unknown'