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