Fix insane SQL request when loading all video attributes
[oweals/peertube.git] / server / models / video / video.ts
1 import * as Bluebird from 'bluebird'
2 import { map, maxBy } from 'lodash'
3 import * as magnetUtil from 'magnet-uri'
4 import * as parseTorrent from 'parse-torrent'
5 import { join } from 'path'
6 import * as Sequelize from 'sequelize'
7 import {
8   AfterDestroy,
9   AllowNull,
10   BeforeDestroy,
11   BelongsTo,
12   BelongsToMany,
13   Column,
14   CreatedAt,
15   DataType,
16   Default,
17   ForeignKey,
18   HasMany,
19   IFindOptions,
20   Is,
21   IsInt,
22   IsUUID,
23   Min,
24   Model,
25   Scopes,
26   Table,
27   UpdatedAt
28 } from 'sequelize-typescript'
29 import { VideoPrivacy, VideoResolution } from '../../../shared'
30 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
31 import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos'
32 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
33 import { activityPubCollection } from '../../helpers/activitypub'
34 import {
35   createTorrentPromise, peertubeTruncate, renamePromise, statPromise, unlinkPromise,
36   writeFilePromise
37 } from '../../helpers/core-utils'
38 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
39 import { isBooleanValid } from '../../helpers/custom-validators/misc'
40 import {
41   isVideoCategoryValid,
42   isVideoDescriptionValid,
43   isVideoDurationValid,
44   isVideoLanguageValid,
45   isVideoLicenceValid,
46   isVideoNameValid,
47   isVideoPrivacyValid,
48   isVideoSupportValid
49 } from '../../helpers/custom-validators/videos'
50 import { generateImageFromVideoFile, getVideoFileResolution, transcode } from '../../helpers/ffmpeg-utils'
51 import { logger } from '../../helpers/logger'
52 import { getServerActor } from '../../helpers/utils'
53 import {
54   API_VERSION,
55   CONFIG,
56   CONSTRAINTS_FIELDS,
57   PREVIEWS_SIZE,
58   REMOTE_SCHEME,
59   STATIC_PATHS,
60   THUMBNAILS_SIZE,
61   VIDEO_CATEGORIES,
62   VIDEO_LANGUAGES,
63   VIDEO_LICENCES,
64   VIDEO_PRIVACIES
65 } from '../../initializers'
66 import {
67   getVideoCommentsActivityPubUrl,
68   getVideoDislikesActivityPubUrl,
69   getVideoLikesActivityPubUrl,
70   getVideoSharesActivityPubUrl
71 } from '../../lib/activitypub'
72 import { sendDeleteVideo } from '../../lib/activitypub/send'
73 import { AccountModel } from '../account/account'
74 import { AccountVideoRateModel } from '../account/account-video-rate'
75 import { ActorModel } from '../activitypub/actor'
76 import { AvatarModel } from '../avatar/avatar'
77 import { ServerModel } from '../server/server'
78 import { getSort, throwIfNotValid } from '../utils'
79 import { TagModel } from './tag'
80 import { VideoAbuseModel } from './video-abuse'
81 import { VideoChannelModel } from './video-channel'
82 import { VideoCommentModel } from './video-comment'
83 import { VideoFileModel } from './video-file'
84 import { VideoShareModel } from './video-share'
85 import { VideoTagModel } from './video-tag'
86
87 enum ScopeNames {
88   AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
89   WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
90   WITH_TAGS = 'WITH_TAGS',
91   WITH_FILES = 'WITH_FILES',
92   WITH_SHARES = 'WITH_SHARES',
93   WITH_RATES = 'WITH_RATES',
94   WITH_COMMENTS = 'WITH_COMMENTS'
95 }
96
97 @Scopes({
98   [ScopeNames.AVAILABLE_FOR_LIST]: (options: {
99     actorId: number,
100     hideNSFW: boolean,
101     filter?: VideoFilter,
102     withFiles?: boolean,
103     accountId?: number,
104     videoChannelId?: number
105   }) => {
106     const accountInclude = {
107       attributes: [ 'id', 'name' ],
108       model: AccountModel.unscoped(),
109       required: true,
110       where: {},
111       include: [
112         {
113           attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
114           model: ActorModel.unscoped(),
115           required: true,
116           where: VideoModel.buildActorWhereWithFilter(options.filter),
117           include: [
118             {
119               attributes: [ 'host' ],
120               model: ServerModel.unscoped(),
121               required: false
122             },
123             {
124               model: AvatarModel.unscoped(),
125               required: false
126             }
127           ]
128         }
129       ]
130     }
131
132     const videoChannelInclude = {
133       attributes: [ 'name', 'description', 'id' ],
134       model: VideoChannelModel.unscoped(),
135       required: true,
136       where: {},
137       include: [
138         {
139           attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
140           model: ActorModel.unscoped(),
141           required: true,
142           include: [
143             {
144               attributes: [ 'host' ],
145               model: ServerModel.unscoped(),
146               required: false
147             },
148             {
149               model: AvatarModel.unscoped(),
150               required: false
151             }
152           ]
153         },
154         accountInclude
155       ]
156     }
157
158     // Force actorId to be a number to avoid SQL injections
159     const actorIdNumber = parseInt(options.actorId.toString(), 10)
160     const query: IFindOptions<VideoModel> = {
161       where: {
162         id: {
163           [Sequelize.Op.notIn]: Sequelize.literal(
164             '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
165           ),
166           [ Sequelize.Op.in ]: Sequelize.literal(
167             '(' +
168             'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
169             'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
170             'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
171             ' UNION ' +
172             'SELECT "video"."id" AS "id" FROM "video" ' +
173             'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
174             'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
175             'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
176             'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
177             'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + actorIdNumber +
178             ')'
179           )
180         },
181         privacy: VideoPrivacy.PUBLIC
182       },
183       include: [ videoChannelInclude ]
184     }
185
186     if (options.withFiles === true) {
187       query.include.push({
188         model: VideoFileModel.unscoped(),
189         required: true
190       })
191     }
192
193     // Hide nsfw videos?
194     if (options.hideNSFW === true) {
195       query.where['nsfw'] = false
196     }
197
198     if (options.accountId) {
199       accountInclude.where = {
200         id: options.accountId
201       }
202     }
203
204     if (options.videoChannelId) {
205       videoChannelInclude.where = {
206         id: options.videoChannelId
207       }
208     }
209
210     return query
211   },
212   [ScopeNames.WITH_ACCOUNT_DETAILS]: {
213     include: [
214       {
215         model: () => VideoChannelModel.unscoped(),
216         required: true,
217         include: [
218           {
219             attributes: {
220               exclude: [ 'privateKey', 'publicKey' ]
221             },
222             model: () => ActorModel.unscoped(),
223             required: true,
224             include: [
225               {
226                 attributes: [ 'host' ],
227                 model: () => ServerModel.unscoped(),
228                 required: false
229               }
230             ]
231           },
232           {
233             model: () => AccountModel.unscoped(),
234             required: true,
235             include: [
236               {
237                 model: () => ActorModel.unscoped(),
238                 attributes: {
239                   exclude: [ 'privateKey', 'publicKey' ]
240                 },
241                 required: true,
242                 include: [
243                   {
244                     attributes: [ 'host' ],
245                     model: () => ServerModel.unscoped(),
246                     required: false
247                   },
248                   {
249                     model: () => AvatarModel.unscoped(),
250                     required: false
251                   }
252                 ]
253               }
254             ]
255           }
256         ]
257       }
258     ]
259   },
260   [ScopeNames.WITH_TAGS]: {
261     include: [ () => TagModel ]
262   },
263   [ScopeNames.WITH_FILES]: {
264     include: [
265       {
266         model: () => VideoFileModel.unscoped(),
267         required: true
268       }
269     ]
270   },
271   [ScopeNames.WITH_SHARES]: {
272     include: [
273       {
274         ['separate' as any]: true,
275         model: () => VideoShareModel.unscoped()
276       }
277     ]
278   },
279   [ScopeNames.WITH_RATES]: {
280     include: [
281       {
282         ['separate' as any]: true,
283         model: () => AccountVideoRateModel,
284         include: [
285           {
286             model: () => AccountModel.unscoped(),
287             required: true,
288             include: [
289               {
290                 attributes: [ 'url' ],
291                 model: () => ActorModel.unscoped()
292               }
293             ]
294           }
295         ]
296       }
297     ]
298   },
299   [ScopeNames.WITH_COMMENTS]: {
300     include: [
301       {
302         ['separate' as any]: true,
303         model: () => VideoCommentModel.unscoped()
304       }
305     ]
306   }
307 })
308 @Table({
309   tableName: 'video',
310   indexes: [
311     {
312       fields: [ 'name' ]
313     },
314     {
315       fields: [ 'createdAt' ]
316     },
317     {
318       fields: [ 'duration' ]
319     },
320     {
321       fields: [ 'views' ]
322     },
323     {
324       fields: [ 'likes' ]
325     },
326     {
327       fields: [ 'uuid' ]
328     },
329     {
330       fields: [ 'channelId' ]
331     },
332     {
333       fields: [ 'id', 'privacy' ]
334     },
335     {
336       fields: [ 'url'],
337       unique: true
338     }
339   ]
340 })
341 export class VideoModel extends Model<VideoModel> {
342
343   @AllowNull(false)
344   @Default(DataType.UUIDV4)
345   @IsUUID(4)
346   @Column(DataType.UUID)
347   uuid: string
348
349   @AllowNull(false)
350   @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
351   @Column
352   name: string
353
354   @AllowNull(true)
355   @Default(null)
356   @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
357   @Column
358   category: number
359
360   @AllowNull(true)
361   @Default(null)
362   @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
363   @Column
364   licence: number
365
366   @AllowNull(true)
367   @Default(null)
368   @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
369   @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
370   language: string
371
372   @AllowNull(false)
373   @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
374   @Column
375   privacy: number
376
377   @AllowNull(false)
378   @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
379   @Column
380   nsfw: boolean
381
382   @AllowNull(true)
383   @Default(null)
384   @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
385   @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
386   description: string
387
388   @AllowNull(true)
389   @Default(null)
390   @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
391   @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
392   support: string
393
394   @AllowNull(false)
395   @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
396   @Column
397   duration: number
398
399   @AllowNull(false)
400   @Default(0)
401   @IsInt
402   @Min(0)
403   @Column
404   views: number
405
406   @AllowNull(false)
407   @Default(0)
408   @IsInt
409   @Min(0)
410   @Column
411   likes: number
412
413   @AllowNull(false)
414   @Default(0)
415   @IsInt
416   @Min(0)
417   @Column
418   dislikes: number
419
420   @AllowNull(false)
421   @Column
422   remote: boolean
423
424   @AllowNull(false)
425   @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
426   @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
427   url: string
428
429   @AllowNull(false)
430   @Column
431   commentsEnabled: boolean
432
433   @CreatedAt
434   createdAt: Date
435
436   @UpdatedAt
437   updatedAt: Date
438
439   @AllowNull(false)
440   @Default(Sequelize.NOW)
441   @Column
442   publishedAt: Date
443
444   @ForeignKey(() => VideoChannelModel)
445   @Column
446   channelId: number
447
448   @BelongsTo(() => VideoChannelModel, {
449     foreignKey: {
450       allowNull: true
451     },
452     hooks: true
453   })
454   VideoChannel: VideoChannelModel
455
456   @BelongsToMany(() => TagModel, {
457     foreignKey: 'videoId',
458     through: () => VideoTagModel,
459     onDelete: 'CASCADE'
460   })
461   Tags: TagModel[]
462
463   @HasMany(() => VideoAbuseModel, {
464     foreignKey: {
465       name: 'videoId',
466       allowNull: false
467     },
468     onDelete: 'cascade'
469   })
470   VideoAbuses: VideoAbuseModel[]
471
472   @HasMany(() => VideoFileModel, {
473     foreignKey: {
474       name: 'videoId',
475       allowNull: false
476     },
477     onDelete: 'cascade'
478   })
479   VideoFiles: VideoFileModel[]
480
481   @HasMany(() => VideoShareModel, {
482     foreignKey: {
483       name: 'videoId',
484       allowNull: false
485     },
486     onDelete: 'cascade'
487   })
488   VideoShares: VideoShareModel[]
489
490   @HasMany(() => AccountVideoRateModel, {
491     foreignKey: {
492       name: 'videoId',
493       allowNull: false
494     },
495     onDelete: 'cascade'
496   })
497   AccountVideoRates: AccountVideoRateModel[]
498
499   @HasMany(() => VideoCommentModel, {
500     foreignKey: {
501       name: 'videoId',
502       allowNull: false
503     },
504     onDelete: 'cascade',
505     hooks: true
506   })
507   VideoComments: VideoCommentModel[]
508
509   @BeforeDestroy
510   static async sendDelete (instance: VideoModel, options) {
511     if (instance.isOwned()) {
512       if (!instance.VideoChannel) {
513         instance.VideoChannel = await instance.$get('VideoChannel', {
514           include: [
515             {
516               model: AccountModel,
517               include: [ ActorModel ]
518             }
519           ],
520           transaction: options.transaction
521         }) as VideoChannelModel
522       }
523
524       logger.debug('Sending delete of video %s.', instance.url)
525
526       return sendDeleteVideo(instance, options.transaction)
527     }
528
529     return undefined
530   }
531
532   @BeforeDestroy
533   static async removeFilesAndSendDelete (instance: VideoModel) {
534     const tasks: Promise<any>[] = []
535
536     logger.debug('Removing files of video %s.', instance.url)
537
538     tasks.push(instance.removeThumbnail())
539
540     if (instance.isOwned()) {
541       if (!Array.isArray(instance.VideoFiles)) {
542         instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
543       }
544
545       tasks.push(instance.removePreview())
546
547       // Remove physical files and torrents
548       instance.VideoFiles.forEach(file => {
549         tasks.push(instance.removeFile(file))
550         tasks.push(instance.removeTorrent(file))
551       })
552     }
553
554     // Do not wait video deletion because we could be in a transaction
555     Promise.all(tasks)
556       .catch(err => {
557         logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
558       })
559
560     return undefined
561   }
562
563   static list () {
564     return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
565   }
566
567   static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
568     function getRawQuery (select: string) {
569       const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
570         'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
571         'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
572         'WHERE "Account"."actorId" = ' + actorId
573       const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
574         'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
575         'WHERE "VideoShare"."actorId" = ' + actorId
576
577       return `(${queryVideo}) UNION (${queryVideoShare})`
578     }
579
580     const rawQuery = getRawQuery('"Video"."id"')
581     const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
582
583     const query = {
584       distinct: true,
585       offset: start,
586       limit: count,
587       order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
588       where: {
589         id: {
590           [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
591         },
592         [Sequelize.Op.or]: [
593           { privacy: VideoPrivacy.PUBLIC },
594           { privacy: VideoPrivacy.UNLISTED }
595         ]
596       },
597       include: [
598         {
599           attributes: [ 'id', 'url' ],
600           model: VideoShareModel.unscoped(),
601           required: false,
602           where: {
603             [Sequelize.Op.and]: [
604               {
605                 id: {
606                   [Sequelize.Op.not]: null
607                 }
608               },
609               {
610                 actorId
611               }
612             ]
613           },
614           include: [
615             {
616               attributes: [ 'id', 'url' ],
617               model: ActorModel.unscoped()
618             }
619           ]
620         },
621         {
622           model: VideoChannelModel.unscoped(),
623           required: true,
624           include: [
625             {
626               attributes: [ 'name' ],
627               model: AccountModel.unscoped(),
628               required: true,
629               include: [
630                 {
631                   attributes: [ 'id', 'url' ],
632                   model: ActorModel.unscoped(),
633                   required: true
634                 }
635               ]
636             },
637             {
638               attributes: [ 'id', 'url' ],
639               model: ActorModel.unscoped(),
640               required: true
641             }
642           ]
643         },
644         {
645           attributes: [ 'type' ],
646           model: AccountVideoRateModel,
647           required: false,
648           include: [
649             {
650               attributes: [ 'id' ],
651               model: AccountModel.unscoped(),
652               include: [
653                 {
654                   attributes: [ 'url' ],
655                   model: ActorModel.unscoped(),
656                   include: [
657                     {
658                       attributes: [ 'host' ],
659                       model: ServerModel,
660                       required: false
661                     }
662                   ]
663                 }
664               ]
665             }
666           ]
667         },
668         {
669           attributes: [ 'url' ],
670           model: VideoCommentModel,
671           required: false
672         },
673         VideoFileModel,
674         TagModel
675       ]
676     }
677
678     return Bluebird.all([
679       // FIXME: typing issue
680       VideoModel.findAll(query as any),
681       VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
682     ]).then(([ rows, totals ]) => {
683       // totals: totalVideos + totalVideoShares
684       let totalVideos = 0
685       let totalVideoShares = 0
686       if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
687       if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
688
689       const total = totalVideos + totalVideoShares
690       return {
691         data: rows,
692         total: total
693       }
694     })
695   }
696
697   static listAccountVideosForApi (accountId: number, start: number, count: number, sort: string, hideNSFW: boolean, withFiles = false) {
698     const query: IFindOptions<VideoModel> = {
699       offset: start,
700       limit: count,
701       order: getSort(sort),
702       include: [
703         {
704           model: VideoChannelModel,
705           required: true,
706           include: [
707             {
708               model: AccountModel,
709               where: {
710                 id: accountId
711               },
712               required: true
713             }
714           ]
715         }
716       ]
717     }
718
719     if (withFiles === true) {
720       query.include.push({
721         model: VideoFileModel.unscoped(),
722         required: true
723       })
724     }
725
726     if (hideNSFW === true) {
727       query.where = {
728         nsfw: false
729       }
730     }
731
732     return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
733       return {
734         data: rows,
735         total: count
736       }
737     })
738   }
739
740   static async listForApi (options: {
741     start: number,
742     count: number,
743     sort: string,
744     hideNSFW: boolean,
745     withFiles: boolean,
746     filter?: VideoFilter,
747     accountId?: number,
748     videoChannelId?: number
749   }) {
750     const query = {
751       offset: options.start,
752       limit: options.count,
753       order: getSort(options.sort)
754     }
755
756     const serverActor = await getServerActor()
757     const scopes = {
758       method: [
759         ScopeNames.AVAILABLE_FOR_LIST, {
760           actorId: serverActor.id,
761           hideNSFW: options.hideNSFW,
762           filter: options.filter,
763           withFiles: options.withFiles,
764           accountId: options.accountId,
765           videoChannelId: options.videoChannelId
766         }
767       ]
768     }
769
770     return VideoModel.scope(scopes)
771       .findAndCountAll(query)
772       .then(({ rows, count }) => {
773         return {
774           data: rows,
775           total: count
776         }
777       })
778   }
779
780   static async searchAndPopulateAccountAndServer (value: string, start: number, count: number, sort: string, hideNSFW: boolean) {
781     const query: IFindOptions<VideoModel> = {
782       offset: start,
783       limit: count,
784       order: getSort(sort),
785       where: {
786         [Sequelize.Op.or]: [
787           {
788             name: {
789               [ Sequelize.Op.iLike ]: '%' + value + '%'
790             }
791           },
792           {
793             preferredUsernameChannel: Sequelize.where(Sequelize.col('VideoChannel->Actor.preferredUsername'), {
794               [ Sequelize.Op.iLike ]: '%' + value + '%'
795             })
796           },
797           {
798             preferredUsernameAccount: Sequelize.where(Sequelize.col('VideoChannel->Account->Actor.preferredUsername'), {
799               [ Sequelize.Op.iLike ]: '%' + value + '%'
800             })
801           },
802           {
803             host: Sequelize.where(Sequelize.col('VideoChannel->Account->Actor->Server.host'), {
804               [ Sequelize.Op.iLike ]: '%' + value + '%'
805             })
806           }
807         ]
808       }
809     }
810
811     const serverActor = await getServerActor()
812     const scopes = {
813       method: [
814         ScopeNames.AVAILABLE_FOR_LIST, {
815           actorId: serverActor.id,
816           hideNSFW
817         }
818       ]
819     }
820
821     return VideoModel.scope(scopes)
822       .findAndCountAll(query)
823       .then(({ rows, count }) => {
824         return {
825           data: rows,
826           total: count
827         }
828       })
829   }
830
831   static load (id: number) {
832     return VideoModel.findById(id)
833   }
834
835   static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
836     const query: IFindOptions<VideoModel> = {
837       where: {
838         url
839       }
840     }
841
842     if (t !== undefined) query.transaction = t
843
844     return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
845   }
846
847   static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
848     const query: IFindOptions<VideoModel> = {
849       where: {
850         [Sequelize.Op.or]: [
851           { uuid },
852           { url }
853         ]
854       }
855     }
856
857     if (t !== undefined) query.transaction = t
858
859     return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
860   }
861
862   static loadAndPopulateAccountAndServerAndTags (id: number) {
863     const options = {
864       order: [ [ 'Tags', 'name', 'ASC' ] ]
865     }
866
867     return VideoModel
868       .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
869       .findById(id, options)
870   }
871
872   static loadByUUID (uuid: string) {
873     const options = {
874       where: {
875         uuid
876       }
877     }
878
879     return VideoModel
880       .scope([ ScopeNames.WITH_FILES ])
881       .findOne(options)
882   }
883
884   static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
885     const options = {
886       order: [ [ 'Tags', 'name', 'ASC' ] ],
887       where: {
888         uuid
889       }
890     }
891
892     return VideoModel
893       .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
894       .findOne(options)
895   }
896
897   static loadAndPopulateAll (id: number) {
898     const options = {
899       order: [ [ 'Tags', 'name', 'ASC' ] ],
900       where: {
901         id
902       }
903     }
904
905     return VideoModel
906       .scope([
907         ScopeNames.WITH_RATES,
908         ScopeNames.WITH_SHARES,
909         ScopeNames.WITH_TAGS,
910         ScopeNames.WITH_FILES,
911         ScopeNames.WITH_ACCOUNT_DETAILS,
912         ScopeNames.WITH_COMMENTS
913       ])
914       .findOne(options)
915   }
916
917   static async getStats () {
918     const totalLocalVideos = await VideoModel.count({
919       where: {
920         remote: false
921       }
922     })
923     const totalVideos = await VideoModel.count()
924
925     let totalLocalVideoViews = await VideoModel.sum('views', {
926       where: {
927         remote: false
928       }
929     })
930     // Sequelize could return null...
931     if (!totalLocalVideoViews) totalLocalVideoViews = 0
932
933     return {
934       totalLocalVideos,
935       totalLocalVideoViews,
936       totalVideos
937     }
938   }
939
940   private static buildActorWhereWithFilter (filter?: VideoFilter) {
941     if (filter && filter === 'local') {
942       return {
943         serverId: null
944       }
945     }
946
947     return {}
948   }
949
950   private static getCategoryLabel (id: number) {
951     let categoryLabel = VIDEO_CATEGORIES[id]
952     if (!categoryLabel) categoryLabel = 'Misc'
953
954     return categoryLabel
955   }
956
957   private static getLicenceLabel (id: number) {
958     let licenceLabel = VIDEO_LICENCES[id]
959     if (!licenceLabel) licenceLabel = 'Unknown'
960
961     return licenceLabel
962   }
963
964   private static getLanguageLabel (id: string) {
965     let languageLabel = VIDEO_LANGUAGES[id]
966     if (!languageLabel) languageLabel = 'Unknown'
967
968     return languageLabel
969   }
970
971   private static getPrivacyLabel (id: number) {
972     let privacyLabel = VIDEO_PRIVACIES[id]
973     if (!privacyLabel) privacyLabel = 'Unknown'
974
975     return privacyLabel
976   }
977
978   getOriginalFile () {
979     if (Array.isArray(this.VideoFiles) === false) return undefined
980
981     // The original file is the file that have the higher resolution
982     return maxBy(this.VideoFiles, file => file.resolution)
983   }
984
985   getVideoFilename (videoFile: VideoFileModel) {
986     return this.uuid + '-' + videoFile.resolution + videoFile.extname
987   }
988
989   getThumbnailName () {
990     // We always have a copy of the thumbnail
991     const extension = '.jpg'
992     return this.uuid + extension
993   }
994
995   getPreviewName () {
996     const extension = '.jpg'
997     return this.uuid + extension
998   }
999
1000   getTorrentFileName (videoFile: VideoFileModel) {
1001     const extension = '.torrent'
1002     return this.uuid + '-' + videoFile.resolution + extension
1003   }
1004
1005   isOwned () {
1006     return this.remote === false
1007   }
1008
1009   createPreview (videoFile: VideoFileModel) {
1010     return generateImageFromVideoFile(
1011       this.getVideoFilePath(videoFile),
1012       CONFIG.STORAGE.PREVIEWS_DIR,
1013       this.getPreviewName(),
1014       PREVIEWS_SIZE
1015     )
1016   }
1017
1018   createThumbnail (videoFile: VideoFileModel) {
1019     return generateImageFromVideoFile(
1020       this.getVideoFilePath(videoFile),
1021       CONFIG.STORAGE.THUMBNAILS_DIR,
1022       this.getThumbnailName(),
1023       THUMBNAILS_SIZE
1024     )
1025   }
1026
1027   getVideoFilePath (videoFile: VideoFileModel) {
1028     return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1029   }
1030
1031   async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1032     const options = {
1033       // Keep the extname, it's used by the client to stream the file inside a web browser
1034       name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1035       createdBy: 'PeerTube',
1036       announceList: [
1037         [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1038         [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1039       ],
1040       urlList: [
1041         CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1042       ]
1043     }
1044
1045     const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1046
1047     const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1048     logger.info('Creating torrent %s.', filePath)
1049
1050     await writeFilePromise(filePath, torrent)
1051
1052     const parsedTorrent = parseTorrent(torrent)
1053     videoFile.infoHash = parsedTorrent.infoHash
1054   }
1055
1056   getEmbedPath () {
1057     return '/videos/embed/' + this.uuid
1058   }
1059
1060   getThumbnailPath () {
1061     return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1062   }
1063
1064   getPreviewPath () {
1065     return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1066   }
1067
1068   toFormattedJSON (): Video {
1069     const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1070     const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1071
1072     return {
1073       id: this.id,
1074       uuid: this.uuid,
1075       name: this.name,
1076       category: {
1077         id: this.category,
1078         label: VideoModel.getCategoryLabel(this.category)
1079       },
1080       licence: {
1081         id: this.licence,
1082         label: VideoModel.getLicenceLabel(this.licence)
1083       },
1084       language: {
1085         id: this.language,
1086         label: VideoModel.getLanguageLabel(this.language)
1087       },
1088       privacy: {
1089         id: this.privacy,
1090         label: VideoModel.getPrivacyLabel(this.privacy)
1091       },
1092       nsfw: this.nsfw,
1093       description: this.getTruncatedDescription(),
1094       isLocal: this.isOwned(),
1095       duration: this.duration,
1096       views: this.views,
1097       likes: this.likes,
1098       dislikes: this.dislikes,
1099       thumbnailPath: this.getThumbnailPath(),
1100       previewPath: this.getPreviewPath(),
1101       embedPath: this.getEmbedPath(),
1102       createdAt: this.createdAt,
1103       updatedAt: this.updatedAt,
1104       publishedAt: this.publishedAt,
1105       account: {
1106         id: formattedAccount.id,
1107         uuid: formattedAccount.uuid,
1108         name: formattedAccount.name,
1109         displayName: formattedAccount.displayName,
1110         url: formattedAccount.url,
1111         host: formattedAccount.host,
1112         avatar: formattedAccount.avatar
1113       },
1114       channel: {
1115         id: formattedVideoChannel.id,
1116         uuid: formattedVideoChannel.uuid,
1117         name: formattedVideoChannel.name,
1118         displayName: formattedVideoChannel.displayName,
1119         url: formattedVideoChannel.url,
1120         host: formattedVideoChannel.host,
1121         avatar: formattedVideoChannel.avatar
1122       }
1123     }
1124   }
1125
1126   toFormattedDetailsJSON (): VideoDetails {
1127     const formattedJson = this.toFormattedJSON()
1128
1129     const detailsJson = {
1130       support: this.support,
1131       descriptionPath: this.getDescriptionPath(),
1132       channel: this.VideoChannel.toFormattedJSON(),
1133       account: this.VideoChannel.Account.toFormattedJSON(),
1134       tags: map(this.Tags, 'name'),
1135       commentsEnabled: this.commentsEnabled,
1136       files: []
1137     }
1138
1139     // Format and sort video files
1140     detailsJson.files = this.getFormattedVideoFilesJSON()
1141
1142     return Object.assign(formattedJson, detailsJson)
1143   }
1144
1145   getFormattedVideoFilesJSON (): VideoFile[] {
1146     const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1147
1148     return this.VideoFiles
1149         .map(videoFile => {
1150           let resolutionLabel = videoFile.resolution + 'p'
1151
1152           return {
1153             resolution: {
1154               id: videoFile.resolution,
1155               label: resolutionLabel
1156             },
1157             magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1158             size: videoFile.size,
1159             torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1160             fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
1161           } as VideoFile
1162         })
1163         .sort((a, b) => {
1164           if (a.resolution.id < b.resolution.id) return 1
1165           if (a.resolution.id === b.resolution.id) return 0
1166           return -1
1167         })
1168   }
1169
1170   toActivityPubObject (): VideoTorrentObject {
1171     const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1172     if (!this.Tags) this.Tags = []
1173
1174     const tag = this.Tags.map(t => ({
1175       type: 'Hashtag' as 'Hashtag',
1176       name: t.name
1177     }))
1178
1179     let language
1180     if (this.language) {
1181       language = {
1182         identifier: this.language,
1183         name: VideoModel.getLanguageLabel(this.language)
1184       }
1185     }
1186
1187     let category
1188     if (this.category) {
1189       category = {
1190         identifier: this.category + '',
1191         name: VideoModel.getCategoryLabel(this.category)
1192       }
1193     }
1194
1195     let licence
1196     if (this.licence) {
1197       licence = {
1198         identifier: this.licence + '',
1199         name: VideoModel.getLicenceLabel(this.licence)
1200       }
1201     }
1202
1203     let likesObject
1204     let dislikesObject
1205
1206     if (Array.isArray(this.AccountVideoRates)) {
1207       const res = this.toRatesActivityPubObjects()
1208       likesObject = res.likesObject
1209       dislikesObject = res.dislikesObject
1210     }
1211
1212     let sharesObject
1213     if (Array.isArray(this.VideoShares)) {
1214       sharesObject = this.toAnnouncesActivityPubObject()
1215     }
1216
1217     let commentsObject
1218     if (Array.isArray(this.VideoComments)) {
1219       commentsObject = this.toCommentsActivityPubObject()
1220     }
1221
1222     const url = []
1223     for (const file of this.VideoFiles) {
1224       url.push({
1225         type: 'Link',
1226         mimeType: 'video/' + file.extname.replace('.', ''),
1227         href: this.getVideoFileUrl(file, baseUrlHttp),
1228         width: file.resolution,
1229         size: file.size
1230       })
1231
1232       url.push({
1233         type: 'Link',
1234         mimeType: 'application/x-bittorrent',
1235         href: this.getTorrentUrl(file, baseUrlHttp),
1236         width: file.resolution
1237       })
1238
1239       url.push({
1240         type: 'Link',
1241         mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1242         href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1243         width: file.resolution
1244       })
1245     }
1246
1247     // Add video url too
1248     url.push({
1249       type: 'Link',
1250       mimeType: 'text/html',
1251       href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1252     })
1253
1254     return {
1255       type: 'Video' as 'Video',
1256       id: this.url,
1257       name: this.name,
1258       duration: this.getActivityStreamDuration(),
1259       uuid: this.uuid,
1260       tag,
1261       category,
1262       licence,
1263       language,
1264       views: this.views,
1265       sensitive: this.nsfw,
1266       commentsEnabled: this.commentsEnabled,
1267       published: this.publishedAt.toISOString(),
1268       updated: this.updatedAt.toISOString(),
1269       mediaType: 'text/markdown',
1270       content: this.getTruncatedDescription(),
1271       support: this.support,
1272       icon: {
1273         type: 'Image',
1274         url: this.getThumbnailUrl(baseUrlHttp),
1275         mediaType: 'image/jpeg',
1276         width: THUMBNAILS_SIZE.width,
1277         height: THUMBNAILS_SIZE.height
1278       },
1279       url,
1280       likes: likesObject,
1281       dislikes: dislikesObject,
1282       shares: sharesObject,
1283       comments: commentsObject,
1284       attributedTo: [
1285         {
1286           type: 'Person',
1287           id: this.VideoChannel.Account.Actor.url
1288         },
1289         {
1290           type: 'Group',
1291           id: this.VideoChannel.Actor.url
1292         }
1293       ]
1294     }
1295   }
1296
1297   toAnnouncesActivityPubObject () {
1298     const shares: string[] = []
1299
1300     for (const videoShare of this.VideoShares) {
1301       shares.push(videoShare.url)
1302     }
1303
1304     return activityPubCollection(getVideoSharesActivityPubUrl(this), shares)
1305   }
1306
1307   toCommentsActivityPubObject () {
1308     const comments: string[] = []
1309
1310     for (const videoComment of this.VideoComments) {
1311       comments.push(videoComment.url)
1312     }
1313
1314     return activityPubCollection(getVideoCommentsActivityPubUrl(this), comments)
1315   }
1316
1317   toRatesActivityPubObjects () {
1318     const likes: string[] = []
1319     const dislikes: string[] = []
1320
1321     for (const rate of this.AccountVideoRates) {
1322       if (rate.type === 'like') {
1323         likes.push(rate.Account.Actor.url)
1324       } else if (rate.type === 'dislike') {
1325         dislikes.push(rate.Account.Actor.url)
1326       }
1327     }
1328
1329     const likesObject = activityPubCollection(getVideoLikesActivityPubUrl(this), likes)
1330     const dislikesObject = activityPubCollection(getVideoDislikesActivityPubUrl(this), dislikes)
1331
1332     return { likesObject, dislikesObject }
1333   }
1334
1335   getTruncatedDescription () {
1336     if (!this.description) return null
1337
1338     const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1339     return peertubeTruncate(this.description, maxLength)
1340   }
1341
1342   async optimizeOriginalVideofile () {
1343     const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1344     const newExtname = '.mp4'
1345     const inputVideoFile = this.getOriginalFile()
1346     const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1347     const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1348
1349     const transcodeOptions = {
1350       inputPath: videoInputPath,
1351       outputPath: videoOutputPath
1352     }
1353
1354     // Could be very long!
1355     await transcode(transcodeOptions)
1356
1357     try {
1358       await unlinkPromise(videoInputPath)
1359
1360       // Important to do this before getVideoFilename() to take in account the new file extension
1361       inputVideoFile.set('extname', newExtname)
1362
1363       await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1364       const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1365
1366       inputVideoFile.set('size', stats.size)
1367
1368       await this.createTorrentAndSetInfoHash(inputVideoFile)
1369       await inputVideoFile.save()
1370
1371     } catch (err) {
1372       // Auto destruction...
1373       this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1374
1375       throw err
1376     }
1377   }
1378
1379   async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1380     const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1381     const extname = '.mp4'
1382
1383     // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1384     const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1385
1386     const newVideoFile = new VideoFileModel({
1387       resolution,
1388       extname,
1389       size: 0,
1390       videoId: this.id
1391     })
1392     const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1393
1394     const transcodeOptions = {
1395       inputPath: videoInputPath,
1396       outputPath: videoOutputPath,
1397       resolution,
1398       isPortraitMode
1399     }
1400
1401     await transcode(transcodeOptions)
1402
1403     const stats = await statPromise(videoOutputPath)
1404
1405     newVideoFile.set('size', stats.size)
1406
1407     await this.createTorrentAndSetInfoHash(newVideoFile)
1408
1409     await newVideoFile.save()
1410
1411     this.VideoFiles.push(newVideoFile)
1412   }
1413
1414   getOriginalFileResolution () {
1415     const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1416
1417     return getVideoFileResolution(originalFilePath)
1418   }
1419
1420   getDescriptionPath () {
1421     return `/api/${API_VERSION}/videos/${this.uuid}/description`
1422   }
1423
1424   removeThumbnail () {
1425     const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1426     return unlinkPromise(thumbnailPath)
1427   }
1428
1429   removePreview () {
1430     // Same name than video thumbnail
1431     return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1432   }
1433
1434   removeFile (videoFile: VideoFileModel) {
1435     const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1436     return unlinkPromise(filePath)
1437   }
1438
1439   removeTorrent (videoFile: VideoFileModel) {
1440     const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1441     return unlinkPromise(torrentPath)
1442   }
1443
1444   getActivityStreamDuration () {
1445     // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1446     return 'PT' + this.duration + 'S'
1447   }
1448
1449   private getBaseUrls () {
1450     let baseUrlHttp
1451     let baseUrlWs
1452
1453     if (this.isOwned()) {
1454       baseUrlHttp = CONFIG.WEBSERVER.URL
1455       baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1456     } else {
1457       baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1458       baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1459     }
1460
1461     return { baseUrlHttp, baseUrlWs }
1462   }
1463
1464   private getThumbnailUrl (baseUrlHttp: string) {
1465     return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1466   }
1467
1468   private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1469     return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1470   }
1471
1472   private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1473     return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1474   }
1475
1476   private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1477     const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1478     const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1479     const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1480
1481     const magnetHash = {
1482       xs,
1483       announce,
1484       urlList,
1485       infoHash: videoFile.infoHash,
1486       name: this.name
1487     }
1488
1489     return magnetUtil.encode(magnetHash)
1490   }
1491 }