Fix error logging
[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   private static getCategoryLabel (id: number) {
806     let categoryLabel = VIDEO_CATEGORIES[id]
807     if (!categoryLabel) categoryLabel = 'Misc'
808
809     return categoryLabel
810   }
811
812   private static getLicenceLabel (id: number) {
813     let licenceLabel = VIDEO_LICENCES[id]
814     if (!licenceLabel) licenceLabel = 'Unknown'
815
816     return licenceLabel
817   }
818
819   private static getLanguageLabel (id: number) {
820     let languageLabel = VIDEO_LANGUAGES[id]
821     if (!languageLabel) languageLabel = 'Unknown'
822
823     return languageLabel
824   }
825
826   getOriginalFile () {
827     if (Array.isArray(this.VideoFiles) === false) return undefined
828
829     // The original file is the file that have the higher resolution
830     return maxBy(this.VideoFiles, file => file.resolution)
831   }
832
833   getVideoFilename (videoFile: VideoFileModel) {
834     return this.uuid + '-' + videoFile.resolution + videoFile.extname
835   }
836
837   getThumbnailName () {
838     // We always have a copy of the thumbnail
839     const extension = '.jpg'
840     return this.uuid + extension
841   }
842
843   getPreviewName () {
844     const extension = '.jpg'
845     return this.uuid + extension
846   }
847
848   getTorrentFileName (videoFile: VideoFileModel) {
849     const extension = '.torrent'
850     return this.uuid + '-' + videoFile.resolution + extension
851   }
852
853   isOwned () {
854     return this.remote === false
855   }
856
857   createPreview (videoFile: VideoFileModel) {
858     return generateImageFromVideoFile(
859       this.getVideoFilePath(videoFile),
860       CONFIG.STORAGE.PREVIEWS_DIR,
861       this.getPreviewName(),
862       PREVIEWS_SIZE
863     )
864   }
865
866   createThumbnail (videoFile: VideoFileModel) {
867     return generateImageFromVideoFile(
868       this.getVideoFilePath(videoFile),
869       CONFIG.STORAGE.THUMBNAILS_DIR,
870       this.getThumbnailName(),
871       THUMBNAILS_SIZE
872     )
873   }
874
875   getVideoFilePath (videoFile: VideoFileModel) {
876     return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
877   }
878
879   createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) {
880     const options = {
881       announceList: [
882         [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
883         [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
884       ],
885       urlList: [
886         CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
887       ]
888     }
889
890     const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
891
892     const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
893     logger.info('Creating torrent %s.', filePath)
894
895     await writeFilePromise(filePath, torrent)
896
897     const parsedTorrent = parseTorrent(torrent)
898     videoFile.infoHash = parsedTorrent.infoHash
899   }
900
901   getEmbedPath () {
902     return '/videos/embed/' + this.uuid
903   }
904
905   getThumbnailPath () {
906     return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
907   }
908
909   getPreviewPath () {
910     return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
911   }
912
913   toFormattedJSON (): Video {
914     const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
915
916     return {
917       id: this.id,
918       uuid: this.uuid,
919       name: this.name,
920       category: {
921         id: this.category,
922         label: VideoModel.getCategoryLabel(this.category)
923       },
924       licence: {
925         id: this.licence,
926         label: VideoModel.getLicenceLabel(this.licence)
927       },
928       language: {
929         id: this.language,
930         label: VideoModel.getLanguageLabel(this.language)
931       },
932       nsfw: this.nsfw,
933       description: this.getTruncatedDescription(),
934       isLocal: this.isOwned(),
935       duration: this.duration,
936       views: this.views,
937       likes: this.likes,
938       dislikes: this.dislikes,
939       thumbnailPath: this.getThumbnailPath(),
940       previewPath: this.getPreviewPath(),
941       embedPath: this.getEmbedPath(),
942       createdAt: this.createdAt,
943       updatedAt: this.updatedAt,
944       account: {
945         name: formattedAccount.name,
946         displayName: formattedAccount.displayName,
947         url: formattedAccount.url,
948         host: formattedAccount.host,
949         avatar: formattedAccount.avatar
950       }
951     }
952   }
953
954   toFormattedDetailsJSON (): VideoDetails {
955     const formattedJson = this.toFormattedJSON()
956
957     // Maybe our server is not up to date and there are new privacy settings since our version
958     let privacyLabel = VIDEO_PRIVACIES[this.privacy]
959     if (!privacyLabel) privacyLabel = 'Unknown'
960
961     const detailsJson = {
962       privacy: {
963         id: this.privacy,
964         label: privacyLabel
965       },
966       support: this.support,
967       descriptionPath: this.getDescriptionPath(),
968       channel: this.VideoChannel.toFormattedJSON(),
969       account: this.VideoChannel.Account.toFormattedJSON(),
970       tags: map<TagModel, string>(this.Tags, 'name'),
971       commentsEnabled: this.commentsEnabled,
972       files: []
973     }
974
975     // Format and sort video files
976     const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
977     detailsJson.files = this.VideoFiles
978       .map(videoFile => {
979         let resolutionLabel = videoFile.resolution + 'p'
980
981         return {
982           resolution: {
983             id: videoFile.resolution,
984             label: resolutionLabel
985           },
986           magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
987           size: videoFile.size,
988           torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
989           fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
990         }
991       })
992       .sort((a, b) => {
993         if (a.resolution.id < b.resolution.id) return 1
994         if (a.resolution.id === b.resolution.id) return 0
995         return -1
996       })
997
998     return Object.assign(formattedJson, detailsJson)
999   }
1000
1001   toActivityPubObject (): VideoTorrentObject {
1002     const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1003     if (!this.Tags) this.Tags = []
1004
1005     const tag = this.Tags.map(t => ({
1006       type: 'Hashtag' as 'Hashtag',
1007       name: t.name
1008     }))
1009
1010     let language
1011     if (this.language) {
1012       language = {
1013         identifier: this.language + '',
1014         name: VideoModel.getLanguageLabel(this.language)
1015       }
1016     }
1017
1018     let category
1019     if (this.category) {
1020       category = {
1021         identifier: this.category + '',
1022         name: VideoModel.getCategoryLabel(this.category)
1023       }
1024     }
1025
1026     let licence
1027     if (this.licence) {
1028       licence = {
1029         identifier: this.licence + '',
1030         name: VideoModel.getLicenceLabel(this.licence)
1031       }
1032     }
1033
1034     let likesObject
1035     let dislikesObject
1036
1037     if (Array.isArray(this.AccountVideoRates)) {
1038       const res = this.toRatesActivityPubObjects()
1039       likesObject = res.likesObject
1040       dislikesObject = res.dislikesObject
1041     }
1042
1043     let sharesObject
1044     if (Array.isArray(this.VideoShares)) {
1045       sharesObject = this.toAnnouncesActivityPubObject()
1046     }
1047
1048     let commentsObject
1049     if (Array.isArray(this.VideoComments)) {
1050       commentsObject = this.toCommentsActivityPubObject()
1051     }
1052
1053     const url = []
1054     for (const file of this.VideoFiles) {
1055       url.push({
1056         type: 'Link',
1057         mimeType: 'video/' + file.extname.replace('.', ''),
1058         href: this.getVideoFileUrl(file, baseUrlHttp),
1059         width: file.resolution,
1060         size: file.size
1061       })
1062
1063       url.push({
1064         type: 'Link',
1065         mimeType: 'application/x-bittorrent',
1066         href: this.getTorrentUrl(file, baseUrlHttp),
1067         width: file.resolution
1068       })
1069
1070       url.push({
1071         type: 'Link',
1072         mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1073         href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1074         width: file.resolution
1075       })
1076     }
1077
1078     // Add video url too
1079     url.push({
1080       type: 'Link',
1081       mimeType: 'text/html',
1082       href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1083     })
1084
1085     return {
1086       type: 'Video' as 'Video',
1087       id: this.url,
1088       name: this.name,
1089       duration: this.getActivityStreamDuration(),
1090       uuid: this.uuid,
1091       tag,
1092       category,
1093       licence,
1094       language,
1095       views: this.views,
1096       sensitive: this.nsfw,
1097       commentsEnabled: this.commentsEnabled,
1098       published: this.createdAt.toISOString(),
1099       updated: this.updatedAt.toISOString(),
1100       mediaType: 'text/markdown',
1101       content: this.getTruncatedDescription(),
1102       support: this.support,
1103       icon: {
1104         type: 'Image',
1105         url: this.getThumbnailUrl(baseUrlHttp),
1106         mediaType: 'image/jpeg',
1107         width: THUMBNAILS_SIZE.width,
1108         height: THUMBNAILS_SIZE.height
1109       },
1110       url,
1111       likes: likesObject,
1112       dislikes: dislikesObject,
1113       shares: sharesObject,
1114       comments: commentsObject,
1115       attributedTo: [
1116         {
1117           type: 'Group',
1118           id: this.VideoChannel.Actor.url
1119         },
1120         {
1121           type: 'Person',
1122           id: this.VideoChannel.Account.Actor.url
1123         }
1124       ]
1125     }
1126   }
1127
1128   toAnnouncesActivityPubObject () {
1129     const shares: string[] = []
1130
1131     for (const videoShare of this.VideoShares) {
1132       shares.push(videoShare.url)
1133     }
1134
1135     return activityPubCollection(getVideoSharesActivityPubUrl(this), shares)
1136   }
1137
1138   toCommentsActivityPubObject () {
1139     const comments: string[] = []
1140
1141     for (const videoComment of this.VideoComments) {
1142       comments.push(videoComment.url)
1143     }
1144
1145     return activityPubCollection(getVideoCommentsActivityPubUrl(this), comments)
1146   }
1147
1148   toRatesActivityPubObjects () {
1149     const likes: string[] = []
1150     const dislikes: string[] = []
1151
1152     for (const rate of this.AccountVideoRates) {
1153       if (rate.type === 'like') {
1154         likes.push(rate.Account.Actor.url)
1155       } else if (rate.type === 'dislike') {
1156         dislikes.push(rate.Account.Actor.url)
1157       }
1158     }
1159
1160     const likesObject = activityPubCollection(getVideoLikesActivityPubUrl(this), likes)
1161     const dislikesObject = activityPubCollection(getVideoDislikesActivityPubUrl(this), dislikes)
1162
1163     return { likesObject, dislikesObject }
1164   }
1165
1166   getTruncatedDescription () {
1167     if (!this.description) return null
1168
1169     const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1170
1171     const options = {
1172       length: maxLength
1173     }
1174     const truncatedDescription = truncate(this.description, options)
1175
1176     // The truncated string is okay, we can return it
1177     if (truncatedDescription.length <= maxLength) return truncatedDescription
1178
1179     // Lodash takes into account all UTF characters, whereas String.prototype.length does not: some characters have a length of 2
1180     // We always use the .length so we need to truncate more if needed
1181     options.length -= maxLength - truncatedDescription.length
1182     return truncate(this.description, options)
1183   }
1184
1185   optimizeOriginalVideofile = async function () {
1186     const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1187     const newExtname = '.mp4'
1188     const inputVideoFile = this.getOriginalFile()
1189     const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1190     const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1191
1192     const transcodeOptions = {
1193       inputPath: videoInputPath,
1194       outputPath: videoOutputPath
1195     }
1196
1197     // Could be very long!
1198     await transcode(transcodeOptions)
1199
1200     try {
1201       await unlinkPromise(videoInputPath)
1202
1203       // Important to do this before getVideoFilename() to take in account the new file extension
1204       inputVideoFile.set('extname', newExtname)
1205
1206       await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1207       const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1208
1209       inputVideoFile.set('size', stats.size)
1210
1211       await this.createTorrentAndSetInfoHash(inputVideoFile)
1212       await inputVideoFile.save()
1213
1214     } catch (err) {
1215       // Auto destruction...
1216       this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1217
1218       throw err
1219     }
1220   }
1221
1222   transcodeOriginalVideofile = async function (resolution: VideoResolution, isPortraitMode: boolean) {
1223     const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1224     const extname = '.mp4'
1225
1226     // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1227     const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1228
1229     const newVideoFile = new VideoFileModel({
1230       resolution,
1231       extname,
1232       size: 0,
1233       videoId: this.id
1234     })
1235     const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1236
1237     const transcodeOptions = {
1238       inputPath: videoInputPath,
1239       outputPath: videoOutputPath,
1240       resolution,
1241       isPortraitMode
1242     }
1243
1244     await transcode(transcodeOptions)
1245
1246     const stats = await statPromise(videoOutputPath)
1247
1248     newVideoFile.set('size', stats.size)
1249
1250     await this.createTorrentAndSetInfoHash(newVideoFile)
1251
1252     await newVideoFile.save()
1253
1254     this.VideoFiles.push(newVideoFile)
1255   }
1256
1257   getOriginalFileResolution () {
1258     const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1259
1260     return getVideoFileResolution(originalFilePath)
1261   }
1262
1263   getDescriptionPath () {
1264     return `/api/${API_VERSION}/videos/${this.uuid}/description`
1265   }
1266
1267   removeThumbnail () {
1268     const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1269     return unlinkPromise(thumbnailPath)
1270   }
1271
1272   removePreview () {
1273     // Same name than video thumbnail
1274     return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1275   }
1276
1277   removeFile (videoFile: VideoFileModel) {
1278     const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1279     return unlinkPromise(filePath)
1280   }
1281
1282   removeTorrent (videoFile: VideoFileModel) {
1283     const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1284     return unlinkPromise(torrentPath)
1285   }
1286
1287   getActivityStreamDuration () {
1288     // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1289     return 'PT' + this.duration + 'S'
1290   }
1291
1292   private getBaseUrls () {
1293     let baseUrlHttp
1294     let baseUrlWs
1295
1296     if (this.isOwned()) {
1297       baseUrlHttp = CONFIG.WEBSERVER.URL
1298       baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1299     } else {
1300       baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1301       baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1302     }
1303
1304     return { baseUrlHttp, baseUrlWs }
1305   }
1306
1307   private getThumbnailUrl (baseUrlHttp: string) {
1308     return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1309   }
1310
1311   private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1312     return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1313   }
1314
1315   private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1316     return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1317   }
1318
1319   private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1320     const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1321     const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1322     const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1323
1324     const magnetHash = {
1325       xs,
1326       announce,
1327       urlList,
1328       infoHash: videoFile.infoHash,
1329       name: this.name
1330     }
1331
1332     return magnetUtil.encode(magnetHash)
1333   }
1334 }