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