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