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