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