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