]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video/video.ts
Raw query to get video ids
[github/Chocobozzz/PeerTube.git] / server / models / video / video.ts
CommitLineData
39445ead 1import * as Bluebird from 'bluebird'
c73e83da 2import { map, maxBy } from 'lodash'
571389d4 3import * as magnetUtil from 'magnet-uri'
4d4e5cd4 4import * as parseTorrent from 'parse-torrent'
28be8916 5import { extname, join } from 'path'
e02643f3 6import * as Sequelize from 'sequelize'
3fd3ab2d 7import {
4ba3b8ea
C
8 AllowNull,
9 BeforeDestroy,
10 BelongsTo,
11 BelongsToMany,
12 Column,
13 CreatedAt,
14 DataType,
15 Default,
16 ForeignKey,
17 HasMany,
2baea0c7 18 HasOne,
4ba3b8ea 19 IFindOptions,
9a629c6e 20 IIncludeOptions,
4ba3b8ea
C
21 Is,
22 IsInt,
23 IsUUID,
24 Min,
25 Model,
26 Scopes,
27 Table,
9a629c6e 28 UpdatedAt
3fd3ab2d 29} from 'sequelize-typescript'
c48e82b5 30import { ActivityUrlObject, VideoPrivacy, VideoResolution, VideoState } from '../../../shared'
3fd3ab2d 31import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
a8462c8e 32import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos'
066e94c5 33import { VideoFilter } from '../../../shared/models/videos/video-query.type'
62689b94 34import { createTorrentPromise, peertubeTruncate } from '../../helpers/core-utils'
da854ddd 35import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
c48e82b5 36import { isArray, isBooleanValid } from '../../helpers/custom-validators/misc'
3fd3ab2d 37import {
4ba3b8ea
C
38 isVideoCategoryValid,
39 isVideoDescriptionValid,
40 isVideoDurationValid,
41 isVideoLanguageValid,
42 isVideoLicenceValid,
43 isVideoNameValid,
2baea0c7
C
44 isVideoPrivacyValid,
45 isVideoStateValid,
b64c950a 46 isVideoSupportValid
3fd3ab2d 47} from '../../helpers/custom-validators/videos'
3a6f351b 48import { generateImageFromVideoFile, getVideoFileFPS, getVideoFileResolution, transcode } from '../../helpers/ffmpeg-utils'
da854ddd 49import { logger } from '../../helpers/logger'
f05a1c30 50import { getServerActor } from '../../helpers/utils'
65fcc311 51import {
1297eb5d 52 ACTIVITY_PUB,
4ba3b8ea
C
53 API_VERSION,
54 CONFIG,
55 CONSTRAINTS_FIELDS,
56 PREVIEWS_SIZE,
57 REMOTE_SCHEME,
02756fbd 58 STATIC_DOWNLOAD_PATHS,
4ba3b8ea
C
59 STATIC_PATHS,
60 THUMBNAILS_SIZE,
61 VIDEO_CATEGORIES,
28be8916 62 VIDEO_EXT_MIMETYPE,
4ba3b8ea
C
63 VIDEO_LANGUAGES,
64 VIDEO_LICENCES,
2baea0c7
C
65 VIDEO_PRIVACIES,
66 VIDEO_STATES
3fd3ab2d 67} from '../../initializers'
46531a0a
C
68import {
69 getVideoCommentsActivityPubUrl,
70 getVideoDislikesActivityPubUrl,
71 getVideoLikesActivityPubUrl,
72 getVideoSharesActivityPubUrl
73} from '../../lib/activitypub'
50d6de9c 74import { sendDeleteVideo } from '../../lib/activitypub/send'
3fd3ab2d
C
75import { AccountModel } from '../account/account'
76import { AccountVideoRateModel } from '../account/account-video-rate'
50d6de9c 77import { ActorModel } from '../activitypub/actor'
b6a4fd6b 78import { AvatarModel } from '../avatar/avatar'
3fd3ab2d 79import { ServerModel } from '../server/server'
9a629c6e 80import { buildTrigramSearchIndex, createSimilarityAttribute, getVideoSort, throwIfNotValid } from '../utils'
3fd3ab2d
C
81import { TagModel } from './tag'
82import { VideoAbuseModel } from './video-abuse'
83import { VideoChannelModel } from './video-channel'
da854ddd 84import { VideoCommentModel } from './video-comment'
3fd3ab2d
C
85import { VideoFileModel } from './video-file'
86import { VideoShareModel } from './video-share'
87import { VideoTagModel } from './video-tag'
2baea0c7 88import { ScheduleVideoUpdateModel } from './schedule-video-update'
40e87e9e 89import { VideoCaptionModel } from './video-caption'
26b7305a 90import { VideoBlacklistModel } from './video-blacklist'
62689b94 91import { copy, remove, rename, stat, writeFile } from 'fs-extra'
9a629c6e 92import { VideoViewModel } from './video-views'
c48e82b5 93import { VideoRedundancyModel } from '../redundancy/video-redundancy'
3fd3ab2d 94
57c36b27
C
95// FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
96const indexes: Sequelize.DefineIndexesOptions[] = [
97 buildTrigramSearchIndex('video_name_trigram', 'name'),
98
8cd72bd3
C
99 { fields: [ 'createdAt' ] },
100 { fields: [ 'publishedAt' ] },
101 { fields: [ 'duration' ] },
102 { fields: [ 'category' ] },
103 { fields: [ 'licence' ] },
104 { fields: [ 'nsfw' ] },
105 { fields: [ 'language' ] },
106 { fields: [ 'waitTranscoding' ] },
107 { fields: [ 'state' ] },
108 { fields: [ 'remote' ] },
109 { fields: [ 'views' ] },
110 { fields: [ 'likes' ] },
111 { fields: [ 'channelId' ] },
57c36b27 112 {
8cd72bd3
C
113 fields: [ 'uuid' ],
114 unique: true
57c36b27
C
115 },
116 {
8ea6f49a 117 fields: [ 'url' ],
57c36b27
C
118 unique: true
119 }
120]
121
2baea0c7 122export enum ScopeNames {
afd2cba5
C
123 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
124 FOR_API = 'FOR_API',
4cb6d457 125 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
d48ff09d 126 WITH_TAGS = 'WITH_TAGS',
bbe0f064 127 WITH_FILES = 'WITH_FILES',
191764f3
C
128 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
129 WITH_BLACKLISTED = 'WITH_BLACKLISTED'
d48ff09d
C
130}
131
afd2cba5
C
132type ForAPIOptions = {
133 ids: number[]
134 withFiles?: boolean
135}
136
137type AvailableForListIDsOptions = {
138 actorId: number
139 includeLocalVideos: boolean
140 filter?: VideoFilter
141 categoryOneOf?: number[]
142 nsfw?: boolean
143 licenceOneOf?: number[]
144 languageOneOf?: string[]
145 tagsOneOf?: string[]
146 tagsAllOf?: string[]
147 withFiles?: boolean
148 accountId?: number
d525fc39 149 videoChannelId?: number
9a629c6e 150 trendingDays?: number
d525fc39
C
151}
152
d48ff09d 153@Scopes({
8ea6f49a 154 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
0626e7af 155 const accountInclude = {
03e12d7c 156 attributes: [ 'id', 'name' ],
0626e7af
C
157 model: AccountModel.unscoped(),
158 required: true,
0626e7af
C
159 include: [
160 {
03e12d7c 161 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
0626e7af
C
162 model: ActorModel.unscoped(),
163 required: true,
0626e7af
C
164 include: [
165 {
166 attributes: [ 'host' ],
167 model: ServerModel.unscoped(),
168 required: false
169 },
170 {
171 model: AvatarModel.unscoped(),
172 required: false
173 }
174 ]
175 }
176 ]
177 }
178
48dce1c9 179 const videoChannelInclude = {
0f320037 180 attributes: [ 'name', 'description', 'id' ],
48dce1c9
C
181 model: VideoChannelModel.unscoped(),
182 required: true,
48dce1c9 183 include: [
0f320037
C
184 {
185 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
186 model: ActorModel.unscoped(),
187 required: true,
188 include: [
189 {
190 attributes: [ 'host' ],
191 model: ServerModel.unscoped(),
192 required: false
193 },
194 {
195 model: AvatarModel.unscoped(),
196 required: false
197 }
198 ]
199 },
48dce1c9
C
200 accountInclude
201 ]
202 }
203
244e76a5 204 const query: IFindOptions<VideoModel> = {
afd2cba5
C
205 where: {
206 id: {
8ea6f49a 207 [ Sequelize.Op.any ]: options.ids
afd2cba5
C
208 }
209 },
210 include: [ videoChannelInclude ]
211 }
212
213 if (options.withFiles === true) {
214 query.include.push({
215 model: VideoFileModel.unscoped(),
216 required: true
217 })
218 }
219
220 return query
221 },
8ea6f49a 222 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
afd2cba5 223 const query: IFindOptions<VideoModel> = {
2b62cccd 224 raw: true,
afd2cba5 225 attributes: [ 'id' ],
244e76a5
RK
226 where: {
227 id: {
8ea6f49a 228 [ Sequelize.Op.and ]: [
b6314e3c
C
229 {
230 [ Sequelize.Op.notIn ]: Sequelize.literal(
231 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
232 )
233 }
234 ]
244e76a5 235 },
2186386c
C
236 // Always list public videos
237 privacy: VideoPrivacy.PUBLIC,
238 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
239 [ Sequelize.Op.or ]: [
240 {
241 state: VideoState.PUBLISHED
242 },
243 {
244 [ Sequelize.Op.and ]: {
245 state: VideoState.TO_TRANSCODE,
246 waitTranscoding: false
247 }
248 }
249 ]
50d6de9c 250 },
8ea6f49a 251 include: []
afd2cba5
C
252 }
253
254 if (options.filter || options.accountId || options.videoChannelId) {
255 const videoChannelInclude: IIncludeOptions = {
256 attributes: [],
257 model: VideoChannelModel.unscoped(),
258 required: true
259 }
260
261 if (options.videoChannelId) {
262 videoChannelInclude.where = {
263 id: options.videoChannelId
264 }
265 }
266
267 if (options.filter || options.accountId) {
268 const accountInclude: IIncludeOptions = {
269 attributes: [],
270 model: AccountModel.unscoped(),
271 required: true
272 }
273
274 if (options.filter) {
275 accountInclude.include = [
276 {
277 attributes: [],
278 model: ActorModel.unscoped(),
279 required: true,
280 where: VideoModel.buildActorWhereWithFilter(options.filter)
281 }
282 ]
283 }
284
285 if (options.accountId) {
286 accountInclude.where = { id: options.accountId }
287 }
288
289 videoChannelInclude.include = [ accountInclude ]
290 }
291
292 query.include.push(videoChannelInclude)
244e76a5
RK
293 }
294
687d638c
C
295 if (options.actorId) {
296 let localVideosReq = ''
297 if (options.includeLocalVideos === true) {
298 localVideosReq = ' UNION ALL ' +
299 'SELECT "video"."id" AS "id" FROM "video" ' +
300 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
301 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
302 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
303 'WHERE "actor"."serverId" IS NULL'
304 }
305
306 // Force actorId to be a number to avoid SQL injections
307 const actorIdNumber = parseInt(options.actorId.toString(), 10)
8ea6f49a 308 query.where[ 'id' ][ Sequelize.Op.and ].push({
b6314e3c
C
309 [ Sequelize.Op.in ]: Sequelize.literal(
310 '(' +
8ea6f49a
C
311 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
312 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
313 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
314 ' UNION ALL ' +
315 'SELECT "video"."id" AS "id" FROM "video" ' +
316 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
317 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
318 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
319 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
320 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
321 localVideosReq +
b6314e3c
C
322 ')'
323 )
324 })
687d638c
C
325 }
326
48dce1c9 327 if (options.withFiles === true) {
8ea6f49a 328 query.where[ 'id' ][ Sequelize.Op.and ].push({
b6314e3c
C
329 [ Sequelize.Op.in ]: Sequelize.literal(
330 '(SELECT "videoId" FROM "videoFile")'
331 )
244e76a5
RK
332 })
333 }
334
d525fc39
C
335 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
336 if (options.tagsAllOf || options.tagsOneOf) {
337 const createTagsIn = (tags: string[]) => {
338 return tags.map(t => VideoModel.sequelize.escape(t))
339 .join(', ')
340 }
341
342 if (options.tagsOneOf) {
8ea6f49a
C
343 query.where[ 'id' ][ Sequelize.Op.and ].push({
344 [ Sequelize.Op.in ]: Sequelize.literal(
b6314e3c 345 '(' +
d525fc39
C
346 'SELECT "videoId" FROM "videoTag" ' +
347 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
348 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
b6314e3c
C
349 ')'
350 )
351 })
d525fc39
C
352 }
353
354 if (options.tagsAllOf) {
8ea6f49a
C
355 query.where[ 'id' ][ Sequelize.Op.and ].push({
356 [ Sequelize.Op.in ]: Sequelize.literal(
d525fc39 357 '(' +
b6314e3c
C
358 'SELECT "videoId" FROM "videoTag" ' +
359 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
360 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
361 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
d525fc39 362 ')'
b6314e3c
C
363 )
364 })
d525fc39
C
365 }
366 }
367
368 if (options.nsfw === true || options.nsfw === false) {
8ea6f49a 369 query.where[ 'nsfw' ] = options.nsfw
d525fc39
C
370 }
371
372 if (options.categoryOneOf) {
8ea6f49a
C
373 query.where[ 'category' ] = {
374 [ Sequelize.Op.or ]: options.categoryOneOf
d525fc39
C
375 }
376 }
377
378 if (options.licenceOneOf) {
8ea6f49a
C
379 query.where[ 'licence' ] = {
380 [ Sequelize.Op.or ]: options.licenceOneOf
d525fc39 381 }
0883b324
C
382 }
383
d525fc39 384 if (options.languageOneOf) {
8ea6f49a
C
385 query.where[ 'language' ] = {
386 [ Sequelize.Op.or ]: options.languageOneOf
d525fc39 387 }
61b909b9
P
388 }
389
9a629c6e 390 if (options.trendingDays) {
b36f41ca 391 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
9a629c6e
C
392
393 query.subQuery = false
394 }
395
244e76a5
RK
396 return query
397 },
8ea6f49a 398 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
d48ff09d
C
399 include: [
400 {
6120941f 401 model: () => VideoChannelModel.unscoped(),
d48ff09d
C
402 required: true,
403 include: [
6120941f
C
404 {
405 attributes: {
406 exclude: [ 'privateKey', 'publicKey' ]
407 },
3e500247
C
408 model: () => ActorModel.unscoped(),
409 required: true,
410 include: [
411 {
412 attributes: [ 'host' ],
413 model: () => ServerModel.unscoped(),
414 required: false
52d9f792
C
415 },
416 {
417 model: () => AvatarModel.unscoped(),
418 required: false
3e500247
C
419 }
420 ]
6120941f 421 },
d48ff09d 422 {
3e500247 423 model: () => AccountModel.unscoped(),
d48ff09d
C
424 required: true,
425 include: [
426 {
3e500247 427 model: () => ActorModel.unscoped(),
6120941f
C
428 attributes: {
429 exclude: [ 'privateKey', 'publicKey' ]
430 },
50d6de9c
C
431 required: true,
432 include: [
433 {
3e500247
C
434 attributes: [ 'host' ],
435 model: () => ServerModel.unscoped(),
50d6de9c 436 required: false
b6a4fd6b
C
437 },
438 {
439 model: () => AvatarModel.unscoped(),
440 required: false
50d6de9c
C
441 }
442 ]
d48ff09d
C
443 }
444 ]
445 }
446 ]
447 }
448 ]
449 },
8ea6f49a 450 [ ScopeNames.WITH_TAGS ]: {
d48ff09d
C
451 include: [ () => TagModel ]
452 },
8ea6f49a 453 [ ScopeNames.WITH_BLACKLISTED ]: {
191764f3
C
454 include: [
455 {
456 attributes: [ 'id', 'reason' ],
457 model: () => VideoBlacklistModel,
458 required: false
459 }
460 ]
461 },
8ea6f49a 462 [ ScopeNames.WITH_FILES ]: {
d48ff09d
C
463 include: [
464 {
e53f952e 465 model: () => VideoFileModel.unscoped(),
c48e82b5
C
466 required: false,
467 include: [
468 {
469 model: () => VideoRedundancyModel.unscoped(),
470 required: false
471 }
472 ]
d48ff09d
C
473 }
474 ]
bbe0f064 475 },
8ea6f49a 476 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
bbe0f064
C
477 include: [
478 {
479 model: () => ScheduleVideoUpdateModel.unscoped(),
480 required: false
481 }
482 ]
d48ff09d
C
483 }
484})
3fd3ab2d
C
485@Table({
486 tableName: 'video',
57c36b27 487 indexes
3fd3ab2d
C
488})
489export class VideoModel extends Model<VideoModel> {
490
491 @AllowNull(false)
492 @Default(DataType.UUIDV4)
493 @IsUUID(4)
494 @Column(DataType.UUID)
495 uuid: string
496
497 @AllowNull(false)
498 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
499 @Column
500 name: string
501
502 @AllowNull(true)
503 @Default(null)
504 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
505 @Column
506 category: number
507
508 @AllowNull(true)
509 @Default(null)
510 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
511 @Column
512 licence: number
513
514 @AllowNull(true)
515 @Default(null)
516 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
9d3ef9fe
C
517 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
518 language: string
3fd3ab2d
C
519
520 @AllowNull(false)
521 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
522 @Column
523 privacy: number
524
525 @AllowNull(false)
47564bbe 526 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
3fd3ab2d
C
527 @Column
528 nsfw: boolean
529
530 @AllowNull(true)
531 @Default(null)
532 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
533 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
534 description: string
535
2422c46b
C
536 @AllowNull(true)
537 @Default(null)
538 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
539 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
540 support: string
541
3fd3ab2d
C
542 @AllowNull(false)
543 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
544 @Column
545 duration: number
546
547 @AllowNull(false)
548 @Default(0)
549 @IsInt
550 @Min(0)
551 @Column
552 views: number
553
554 @AllowNull(false)
555 @Default(0)
556 @IsInt
557 @Min(0)
558 @Column
559 likes: number
560
561 @AllowNull(false)
562 @Default(0)
563 @IsInt
564 @Min(0)
565 @Column
566 dislikes: number
567
568 @AllowNull(false)
569 @Column
570 remote: boolean
571
572 @AllowNull(false)
573 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
574 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
575 url: string
576
47564bbe
C
577 @AllowNull(false)
578 @Column
579 commentsEnabled: boolean
580
2186386c
C
581 @AllowNull(false)
582 @Column
583 waitTranscoding: boolean
584
585 @AllowNull(false)
586 @Default(null)
587 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
588 @Column
589 state: VideoState
590
3fd3ab2d
C
591 @CreatedAt
592 createdAt: Date
593
594 @UpdatedAt
595 updatedAt: Date
596
2922e048
JLB
597 @AllowNull(false)
598 @Default(Sequelize.NOW)
599 @Column
600 publishedAt: Date
601
3fd3ab2d
C
602 @ForeignKey(() => VideoChannelModel)
603 @Column
604 channelId: number
605
606 @BelongsTo(() => VideoChannelModel, {
feb4bdfd 607 foreignKey: {
50d6de9c 608 allowNull: true
feb4bdfd 609 },
6b738c7a 610 hooks: true
feb4bdfd 611 })
3fd3ab2d 612 VideoChannel: VideoChannelModel
7920c273 613
3fd3ab2d 614 @BelongsToMany(() => TagModel, {
7920c273 615 foreignKey: 'videoId',
3fd3ab2d
C
616 through: () => VideoTagModel,
617 onDelete: 'CASCADE'
7920c273 618 })
3fd3ab2d 619 Tags: TagModel[]
55fa55a9 620
3fd3ab2d 621 @HasMany(() => VideoAbuseModel, {
55fa55a9
C
622 foreignKey: {
623 name: 'videoId',
624 allowNull: false
625 },
626 onDelete: 'cascade'
627 })
3fd3ab2d 628 VideoAbuses: VideoAbuseModel[]
93e1258c 629
3fd3ab2d 630 @HasMany(() => VideoFileModel, {
93e1258c
C
631 foreignKey: {
632 name: 'videoId',
633 allowNull: false
634 },
c48e82b5 635 hooks: true,
93e1258c
C
636 onDelete: 'cascade'
637 })
3fd3ab2d 638 VideoFiles: VideoFileModel[]
e71bcc0f 639
3fd3ab2d 640 @HasMany(() => VideoShareModel, {
e71bcc0f
C
641 foreignKey: {
642 name: 'videoId',
643 allowNull: false
644 },
645 onDelete: 'cascade'
646 })
3fd3ab2d 647 VideoShares: VideoShareModel[]
16b90975 648
3fd3ab2d 649 @HasMany(() => AccountVideoRateModel, {
16b90975
C
650 foreignKey: {
651 name: 'videoId',
652 allowNull: false
653 },
654 onDelete: 'cascade'
655 })
3fd3ab2d 656 AccountVideoRates: AccountVideoRateModel[]
f285faa0 657
da854ddd
C
658 @HasMany(() => VideoCommentModel, {
659 foreignKey: {
660 name: 'videoId',
661 allowNull: false
662 },
f05a1c30
C
663 onDelete: 'cascade',
664 hooks: true
da854ddd
C
665 })
666 VideoComments: VideoCommentModel[]
667
9a629c6e
C
668 @HasMany(() => VideoViewModel, {
669 foreignKey: {
670 name: 'videoId',
671 allowNull: false
672 },
673 onDelete: 'cascade',
674 hooks: true
675 })
676 VideoViews: VideoViewModel[]
677
2baea0c7
C
678 @HasOne(() => ScheduleVideoUpdateModel, {
679 foreignKey: {
680 name: 'videoId',
681 allowNull: false
682 },
683 onDelete: 'cascade'
684 })
685 ScheduleVideoUpdate: ScheduleVideoUpdateModel
686
26b7305a
C
687 @HasOne(() => VideoBlacklistModel, {
688 foreignKey: {
689 name: 'videoId',
690 allowNull: false
691 },
692 onDelete: 'cascade'
693 })
694 VideoBlacklist: VideoBlacklistModel
695
40e87e9e
C
696 @HasMany(() => VideoCaptionModel, {
697 foreignKey: {
698 name: 'videoId',
699 allowNull: false
700 },
701 onDelete: 'cascade',
702 hooks: true,
8ea6f49a 703 [ 'separate' as any ]: true
40e87e9e
C
704 })
705 VideoCaptions: VideoCaptionModel[]
706
f05a1c30
C
707 @BeforeDestroy
708 static async sendDelete (instance: VideoModel, options) {
709 if (instance.isOwned()) {
710 if (!instance.VideoChannel) {
711 instance.VideoChannel = await instance.$get('VideoChannel', {
712 include: [
713 {
714 model: AccountModel,
715 include: [ ActorModel ]
716 }
717 ],
718 transaction: options.transaction
719 }) as VideoChannelModel
720 }
721
f05a1c30
C
722 return sendDeleteVideo(instance, options.transaction)
723 }
724
725 return undefined
726 }
727
6b738c7a 728 @BeforeDestroy
40e87e9e 729 static async removeFiles (instance: VideoModel) {
f05a1c30 730 const tasks: Promise<any>[] = []
f285faa0 731
8e0fd45e 732 logger.info('Removing files of video %s.', instance.url)
6b738c7a 733
f05a1c30 734 tasks.push(instance.removeThumbnail())
93e1258c 735
3fd3ab2d 736 if (instance.isOwned()) {
f05a1c30
C
737 if (!Array.isArray(instance.VideoFiles)) {
738 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
739 }
740
741 tasks.push(instance.removePreview())
40298b02 742
3fd3ab2d
C
743 // Remove physical files and torrents
744 instance.VideoFiles.forEach(file => {
745 tasks.push(instance.removeFile(file))
746 tasks.push(instance.removeTorrent(file))
747 })
748 }
40298b02 749
6b738c7a
C
750 // Do not wait video deletion because we could be in a transaction
751 Promise.all(tasks)
8ea6f49a
C
752 .catch(err => {
753 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
754 })
6b738c7a
C
755
756 return undefined
3fd3ab2d 757 }
f285faa0 758
3fd3ab2d 759 static list () {
d48ff09d 760 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
3fd3ab2d 761 }
f285faa0 762
50d6de9c 763 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
3fd3ab2d
C
764 function getRawQuery (select: string) {
765 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
766 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
50d6de9c
C
767 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
768 'WHERE "Account"."actorId" = ' + actorId
3fd3ab2d
C
769 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
770 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
50d6de9c 771 'WHERE "VideoShare"."actorId" = ' + actorId
558d7c23 772
3fd3ab2d
C
773 return `(${queryVideo}) UNION (${queryVideoShare})`
774 }
aaf61f38 775
3fd3ab2d
C
776 const rawQuery = getRawQuery('"Video"."id"')
777 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
778
779 const query = {
780 distinct: true,
781 offset: start,
782 limit: count,
9a629c6e 783 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
3fd3ab2d
C
784 where: {
785 id: {
8ea6f49a 786 [ Sequelize.Op.in ]: Sequelize.literal('(' + rawQuery + ')')
3c75ce12 787 },
8ea6f49a 788 [ Sequelize.Op.or ]: [
3c75ce12
C
789 { privacy: VideoPrivacy.PUBLIC },
790 { privacy: VideoPrivacy.UNLISTED }
791 ]
3fd3ab2d
C
792 },
793 include: [
40e87e9e
C
794 {
795 attributes: [ 'language' ],
796 model: VideoCaptionModel.unscoped(),
797 required: false
798 },
3fd3ab2d 799 {
1d230c44 800 attributes: [ 'id', 'url' ],
2c897999 801 model: VideoShareModel.unscoped(),
3fd3ab2d 802 required: false,
e3d5ea4f
C
803 // We only want videos shared by this actor
804 where: {
8ea6f49a 805 [ Sequelize.Op.and ]: [
e3d5ea4f
C
806 {
807 id: {
8ea6f49a 808 [ Sequelize.Op.not ]: null
e3d5ea4f
C
809 }
810 },
811 {
812 actorId
813 }
814 ]
815 },
50d6de9c
C
816 include: [
817 {
2c897999
C
818 attributes: [ 'id', 'url' ],
819 model: ActorModel.unscoped()
50d6de9c
C
820 }
821 ]
3fd3ab2d
C
822 },
823 {
2c897999 824 model: VideoChannelModel.unscoped(),
3fd3ab2d
C
825 required: true,
826 include: [
827 {
2c897999
C
828 attributes: [ 'name' ],
829 model: AccountModel.unscoped(),
830 required: true,
831 include: [
832 {
e3d5ea4f 833 attributes: [ 'id', 'url', 'followersUrl' ],
2c897999
C
834 model: ActorModel.unscoped(),
835 required: true
836 }
837 ]
838 },
839 {
e3d5ea4f 840 attributes: [ 'id', 'url', 'followersUrl' ],
2c897999 841 model: ActorModel.unscoped(),
3fd3ab2d
C
842 required: true
843 }
844 ]
845 },
3fd3ab2d 846 VideoFileModel,
2c897999 847 TagModel
3fd3ab2d
C
848 ]
849 }
164174a6 850
3fd3ab2d
C
851 return Bluebird.all([
852 // FIXME: typing issue
853 VideoModel.findAll(query as any),
854 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
855 ]).then(([ rows, totals ]) => {
856 // totals: totalVideos + totalVideoShares
857 let totalVideos = 0
858 let totalVideoShares = 0
8ea6f49a
C
859 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
860 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
3fd3ab2d
C
861
862 const total = totalVideos + totalVideoShares
863 return {
864 data: rows,
865 total: total
866 }
867 })
868 }
93e1258c 869
26b7305a 870 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
244e76a5 871 const query: IFindOptions<VideoModel> = {
3fd3ab2d
C
872 offset: start,
873 limit: count,
9a629c6e 874 order: getVideoSort(sort),
3fd3ab2d
C
875 include: [
876 {
877 model: VideoChannelModel,
878 required: true,
879 include: [
880 {
881 model: AccountModel,
882 where: {
7b87d2d5 883 id: accountId
3fd3ab2d
C
884 },
885 required: true
886 }
887 ]
2baea0c7
C
888 },
889 {
890 model: ScheduleVideoUpdateModel,
891 required: false
26b7305a
C
892 },
893 {
894 model: VideoBlacklistModel,
895 required: false
d48ff09d 896 }
3fd3ab2d
C
897 ]
898 }
d8755eed 899
244e76a5
RK
900 if (withFiles === true) {
901 query.include.push({
902 model: VideoFileModel.unscoped(),
903 required: true
904 })
905 }
906
3fd3ab2d
C
907 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
908 return {
909 data: rows,
910 total: count
911 }
912 })
913 }
93e1258c 914
48dce1c9 915 static async listForApi (options: {
0626e7af
C
916 start: number,
917 count: number,
918 sort: string,
d525fc39 919 nsfw: boolean,
06a05d5f 920 includeLocalVideos: boolean,
48dce1c9 921 withFiles: boolean,
d525fc39
C
922 categoryOneOf?: number[],
923 licenceOneOf?: number[],
924 languageOneOf?: string[],
925 tagsOneOf?: string[],
926 tagsAllOf?: string[],
0626e7af 927 filter?: VideoFilter,
48dce1c9 928 accountId?: number,
06a05d5f
C
929 videoChannelId?: number,
930 actorId?: number
9a629c6e 931 trendingDays?: number
48dce1c9 932 }) {
9a629c6e 933 const query: IFindOptions<VideoModel> = {
48dce1c9
C
934 offset: options.start,
935 limit: options.count,
9a629c6e
C
936 order: getVideoSort(options.sort)
937 }
938
939 let trendingDays: number
940 if (options.sort.endsWith('trending')) {
941 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
942
943 query.group = 'VideoModel.id'
3fd3ab2d 944 }
93e1258c 945
687d638c
C
946 // actorId === null has a meaning, so just check undefined
947 const actorId = options.actorId !== undefined ? options.actorId : (await getServerActor()).id
06a05d5f 948
afd2cba5
C
949 const queryOptions = {
950 actorId,
951 nsfw: options.nsfw,
952 categoryOneOf: options.categoryOneOf,
953 licenceOneOf: options.licenceOneOf,
954 languageOneOf: options.languageOneOf,
955 tagsOneOf: options.tagsOneOf,
956 tagsAllOf: options.tagsAllOf,
957 filter: options.filter,
958 withFiles: options.withFiles,
959 accountId: options.accountId,
960 videoChannelId: options.videoChannelId,
9a629c6e
C
961 includeLocalVideos: options.includeLocalVideos,
962 trendingDays
48dce1c9
C
963 }
964
afd2cba5 965 return VideoModel.getAvailableForApi(query, queryOptions)
93e1258c
C
966 }
967
0b18f4aa 968 static async searchAndPopulateAccountAndServer (options: {
06a05d5f 969 includeLocalVideos: boolean
d4112450 970 search?: string
0b18f4aa
C
971 start?: number
972 count?: number
973 sort?: string
974 startDate?: string // ISO 8601
975 endDate?: string // ISO 8601
976 nsfw?: boolean
977 categoryOneOf?: number[]
978 licenceOneOf?: number[]
979 languageOneOf?: string[]
980 tagsOneOf?: string[]
981 tagsAllOf?: string[]
982 durationMin?: number // seconds
983 durationMax?: number // seconds
984 }) {
8ea6f49a 985 const whereAnd = []
d525fc39
C
986
987 if (options.startDate || options.endDate) {
8ea6f49a 988 const publishedAtRange = {}
d525fc39 989
8ea6f49a
C
990 if (options.startDate) publishedAtRange[ Sequelize.Op.gte ] = options.startDate
991 if (options.endDate) publishedAtRange[ Sequelize.Op.lte ] = options.endDate
d525fc39
C
992
993 whereAnd.push({ publishedAt: publishedAtRange })
994 }
995
996 if (options.durationMin || options.durationMax) {
8ea6f49a 997 const durationRange = {}
d525fc39 998
8ea6f49a
C
999 if (options.durationMin) durationRange[ Sequelize.Op.gte ] = options.durationMin
1000 if (options.durationMax) durationRange[ Sequelize.Op.lte ] = options.durationMax
d525fc39
C
1001
1002 whereAnd.push({ duration: durationRange })
1003 }
1004
d4112450 1005 const attributesInclude = []
dbfd3e9b
C
1006 const escapedSearch = VideoModel.sequelize.escape(options.search)
1007 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
d4112450
C
1008 if (options.search) {
1009 whereAnd.push(
1010 {
dbfd3e9b
C
1011 id: {
1012 [ Sequelize.Op.in ]: Sequelize.literal(
1013 '(' +
8ea6f49a
C
1014 'SELECT "video"."id" FROM "video" ' +
1015 'WHERE ' +
1016 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1017 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1018 'UNION ALL ' +
1019 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1020 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1021 'WHERE "tag"."name" = ' + escapedSearch +
dbfd3e9b
C
1022 ')'
1023 )
1024 }
d4112450
C
1025 }
1026 )
1027
1028 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1029 }
1030
1031 // Cannot search on similarity if we don't have a search
1032 if (!options.search) {
1033 attributesInclude.push(
1034 Sequelize.literal('0 as similarity')
1035 )
1036 }
d525fc39 1037
f05a1c30 1038 const query: IFindOptions<VideoModel> = {
57c36b27 1039 attributes: {
d4112450 1040 include: attributesInclude
57c36b27 1041 },
d525fc39
C
1042 offset: options.start,
1043 limit: options.count,
9a629c6e 1044 order: getVideoSort(options.sort),
d525fc39
C
1045 where: {
1046 [ Sequelize.Op.and ]: whereAnd
1047 }
f05a1c30
C
1048 }
1049
1050 const serverActor = await getServerActor()
afd2cba5
C
1051 const queryOptions = {
1052 actorId: serverActor.id,
1053 includeLocalVideos: options.includeLocalVideos,
1054 nsfw: options.nsfw,
1055 categoryOneOf: options.categoryOneOf,
1056 licenceOneOf: options.licenceOneOf,
1057 languageOneOf: options.languageOneOf,
1058 tagsOneOf: options.tagsOneOf,
1059 tagsAllOf: options.tagsAllOf
48dce1c9 1060 }
f05a1c30 1061
afd2cba5 1062 return VideoModel.getAvailableForApi(query, queryOptions)
f05a1c30
C
1063 }
1064
516df59b 1065 static load (id: number, t?: Sequelize.Transaction) {
b36f41ca
C
1066 return VideoModel.findById(id, { transaction: t })
1067 }
516df59b 1068
b36f41ca
C
1069 static loadWithFile (id: number, t?: Sequelize.Transaction, logging?: boolean) {
1070 return VideoModel.scope(ScopeNames.WITH_FILES)
1071 .findById(id, { transaction: t, logging })
3fd3ab2d 1072 }
fdbda9e3 1073
3fd3ab2d
C
1074 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
1075 const query: IFindOptions<VideoModel> = {
1076 where: {
1077 url
d48ff09d 1078 }
3fd3ab2d 1079 }
d8755eed 1080
3fd3ab2d 1081 if (t !== undefined) query.transaction = t
d8755eed 1082
4cb6d457 1083 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
3fd3ab2d 1084 }
d8755eed 1085
3fd3ab2d
C
1086 static loadAndPopulateAccountAndServerAndTags (id: number) {
1087 const options = {
d48ff09d 1088 order: [ [ 'Tags', 'name', 'ASC' ] ]
3fd3ab2d 1089 }
72c7248b 1090
d48ff09d 1091 return VideoModel
191764f3
C
1092 .scope([
1093 ScopeNames.WITH_TAGS,
1094 ScopeNames.WITH_BLACKLISTED,
1095 ScopeNames.WITH_FILES,
1096 ScopeNames.WITH_ACCOUNT_DETAILS,
1097 ScopeNames.WITH_SCHEDULED_UPDATE
1098 ])
d48ff09d 1099 .findById(id, options)
3fd3ab2d 1100 }
72c7248b 1101
8fa5653a
C
1102 static loadByUUID (uuid: string) {
1103 const options = {
1104 where: {
1105 uuid
1106 }
1107 }
1108
1109 return VideoModel
1110 .scope([ ScopeNames.WITH_FILES ])
1111 .findOne(options)
1112 }
1113
2186386c 1114 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string, t?: Sequelize.Transaction) {
3fd3ab2d
C
1115 const options = {
1116 order: [ [ 'Tags', 'name', 'ASC' ] ],
1117 where: {
1118 uuid
2186386c
C
1119 },
1120 transaction: t
3fd3ab2d 1121 }
fd45e8f4 1122
d48ff09d 1123 return VideoModel
191764f3
C
1124 .scope([
1125 ScopeNames.WITH_TAGS,
1126 ScopeNames.WITH_BLACKLISTED,
1127 ScopeNames.WITH_FILES,
1128 ScopeNames.WITH_ACCOUNT_DETAILS,
1129 ScopeNames.WITH_SCHEDULED_UPDATE
1130 ])
da854ddd
C
1131 .findOne(options)
1132 }
1133
09cababd
C
1134 static async getStats () {
1135 const totalLocalVideos = await VideoModel.count({
1136 where: {
1137 remote: false
1138 }
1139 })
1140 const totalVideos = await VideoModel.count()
1141
1142 let totalLocalVideoViews = await VideoModel.sum('views', {
1143 where: {
1144 remote: false
1145 }
1146 })
1147 // Sequelize could return null...
1148 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1149
1150 return {
1151 totalLocalVideos,
1152 totalLocalVideoViews,
1153 totalVideos
1154 }
1155 }
1156
6b616860
C
1157 static incrementViews (id: number, views: number) {
1158 return VideoModel.increment('views', {
1159 by: views,
1160 where: {
1161 id
1162 }
1163 })
1164 }
1165
2d3741d6
C
1166 // threshold corresponds to how many video the field should have to be returned
1167 static getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1168 const query: IFindOptions<VideoModel> = {
1169 attributes: [ field ],
1170 limit: count,
1171 group: field,
1172 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
8ea6f49a 1173 [ Sequelize.Op.gte ]: threshold
2d3741d6
C
1174 }) as any, // FIXME: typings
1175 where: {
8ea6f49a
C
1176 [ field ]: {
1177 [ Sequelize.Op.not ]: null
2d3741d6
C
1178 },
1179 privacy: VideoPrivacy.PUBLIC,
1180 state: VideoState.PUBLISHED
1181 },
1182 order: [ this.sequelize.random() ]
1183 }
1184
1185 return VideoModel.findAll(query)
8ea6f49a 1186 .then(rows => rows.map(r => r[ field ]))
2d3741d6
C
1187 }
1188
b36f41ca
C
1189 static buildTrendingQuery (trendingDays: number) {
1190 return {
1191 attributes: [],
1192 subQuery: false,
1193 model: VideoViewModel,
1194 required: false,
1195 where: {
1196 startDate: {
1197 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1198 }
1199 }
1200 }
1201 }
1202
066e94c5
C
1203 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1204 if (filter && filter === 'local') {
1205 return {
1206 serverId: null
1207 }
1208 }
1209
1210 return {}
1211 }
afd2cba5
C
1212
1213 private static async getAvailableForApi (query: IFindOptions<VideoModel>, options: AvailableForListIDsOptions) {
1214 const idsScope = {
1215 method: [
1216 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1217 ]
1218 }
1219
8ea6f49a
C
1220 // Remove trending sort on count, because it uses a group by
1221 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1222 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1223 const countScope = {
1224 method: [
1225 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1226 ]
1227 }
1228
1229 const [ count, rowsId ] = await Promise.all([
1230 VideoModel.scope(countScope).count(countQuery),
1231 VideoModel.scope(idsScope).findAll(query)
1232 ])
afd2cba5
C
1233 const ids = rowsId.map(r => r.id)
1234
1235 if (ids.length === 0) return { data: [], total: count }
1236
1237 const apiScope = {
1238 method: [ ScopeNames.FOR_API, { ids, withFiles: options.withFiles } as ForAPIOptions ]
1239 }
b6314e3c
C
1240
1241 const secondQuery = {
1242 offset: 0,
1243 limit: query.limit,
9a629c6e
C
1244 attributes: query.attributes,
1245 order: [ // Keep original order
1246 Sequelize.literal(
1247 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1248 )
1249 ]
b6314e3c
C
1250 }
1251 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
afd2cba5
C
1252
1253 return {
1254 data: rows,
1255 total: count
1256 }
1257 }
066e94c5 1258
ae5a3dd6 1259 private static getCategoryLabel (id: number) {
8ea6f49a 1260 return VIDEO_CATEGORIES[ id ] || 'Misc'
ae5a3dd6
C
1261 }
1262
1263 private static getLicenceLabel (id: number) {
8ea6f49a 1264 return VIDEO_LICENCES[ id ] || 'Unknown'
ae5a3dd6
C
1265 }
1266
9d3ef9fe 1267 private static getLanguageLabel (id: string) {
8ea6f49a 1268 return VIDEO_LANGUAGES[ id ] || 'Unknown'
ae5a3dd6
C
1269 }
1270
2243730c 1271 private static getPrivacyLabel (id: number) {
8ea6f49a 1272 return VIDEO_PRIVACIES[ id ] || 'Unknown'
2186386c 1273 }
2243730c 1274
2186386c 1275 private static getStateLabel (id: number) {
8ea6f49a 1276 return VIDEO_STATES[ id ] || 'Unknown'
2243730c
C
1277 }
1278
3fd3ab2d
C
1279 getOriginalFile () {
1280 if (Array.isArray(this.VideoFiles) === false) return undefined
aaf61f38 1281
3fd3ab2d
C
1282 // The original file is the file that have the higher resolution
1283 return maxBy(this.VideoFiles, file => file.resolution)
e4f97bab 1284 }
aaf61f38 1285
3fd3ab2d
C
1286 getVideoFilename (videoFile: VideoFileModel) {
1287 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1288 }
165cdc75 1289
3fd3ab2d
C
1290 getThumbnailName () {
1291 // We always have a copy of the thumbnail
1292 const extension = '.jpg'
1293 return this.uuid + extension
7b1f49de
C
1294 }
1295
3fd3ab2d
C
1296 getPreviewName () {
1297 const extension = '.jpg'
1298 return this.uuid + extension
1299 }
7b1f49de 1300
3fd3ab2d
C
1301 getTorrentFileName (videoFile: VideoFileModel) {
1302 const extension = '.torrent'
1303 return this.uuid + '-' + videoFile.resolution + extension
1304 }
8e7f08b5 1305
3fd3ab2d
C
1306 isOwned () {
1307 return this.remote === false
9567011b
C
1308 }
1309
3fd3ab2d 1310 createPreview (videoFile: VideoFileModel) {
3fd3ab2d
C
1311 return generateImageFromVideoFile(
1312 this.getVideoFilePath(videoFile),
1313 CONFIG.STORAGE.PREVIEWS_DIR,
1314 this.getPreviewName(),
26670720 1315 PREVIEWS_SIZE
3fd3ab2d
C
1316 )
1317 }
9567011b 1318
3fd3ab2d 1319 createThumbnail (videoFile: VideoFileModel) {
3fd3ab2d
C
1320 return generateImageFromVideoFile(
1321 this.getVideoFilePath(videoFile),
1322 CONFIG.STORAGE.THUMBNAILS_DIR,
1323 this.getThumbnailName(),
26670720 1324 THUMBNAILS_SIZE
3fd3ab2d 1325 )
14d3270f
C
1326 }
1327
02756fbd
C
1328 getTorrentFilePath (videoFile: VideoFileModel) {
1329 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1330 }
1331
3fd3ab2d
C
1332 getVideoFilePath (videoFile: VideoFileModel) {
1333 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1334 }
14d3270f 1335
81e504b3 1336 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
3fd3ab2d 1337 const options = {
6cced8f9
C
1338 // Keep the extname, it's used by the client to stream the file inside a web browser
1339 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
81e504b3 1340 createdBy: 'PeerTube',
3fd3ab2d 1341 announceList: [
0edf0581
C
1342 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1343 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
3fd3ab2d 1344 ],
c48e82b5 1345 urlList: [ CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
3fd3ab2d 1346 }
14d3270f 1347
3fd3ab2d 1348 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
e4f97bab 1349
3fd3ab2d
C
1350 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1351 logger.info('Creating torrent %s.', filePath)
e4f97bab 1352
62689b94 1353 await writeFile(filePath, torrent)
e4f97bab 1354
3fd3ab2d
C
1355 const parsedTorrent = parseTorrent(torrent)
1356 videoFile.infoHash = parsedTorrent.infoHash
1357 }
e4f97bab 1358
40e87e9e 1359 getEmbedStaticPath () {
3fd3ab2d
C
1360 return '/videos/embed/' + this.uuid
1361 }
e4f97bab 1362
40e87e9e 1363 getThumbnailStaticPath () {
3fd3ab2d 1364 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
e4f97bab 1365 }
227d02fe 1366
40e87e9e 1367 getPreviewStaticPath () {
3fd3ab2d
C
1368 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1369 }
40298b02 1370
2186386c
C
1371 toFormattedJSON (options?: {
1372 additionalAttributes: {
bbe0f064
C
1373 state?: boolean,
1374 waitTranscoding?: boolean,
26b7305a
C
1375 scheduledUpdate?: boolean,
1376 blacklistInfo?: boolean
2186386c
C
1377 }
1378 }): Video {
b64c950a 1379 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
0f320037 1380 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
14d3270f 1381
2186386c 1382 const videoObject: Video = {
3fd3ab2d
C
1383 id: this.id,
1384 uuid: this.uuid,
1385 name: this.name,
ae5a3dd6
C
1386 category: {
1387 id: this.category,
1388 label: VideoModel.getCategoryLabel(this.category)
1389 },
1390 licence: {
1391 id: this.licence,
1392 label: VideoModel.getLicenceLabel(this.licence)
1393 },
1394 language: {
1395 id: this.language,
1396 label: VideoModel.getLanguageLabel(this.language)
1397 },
2243730c
C
1398 privacy: {
1399 id: this.privacy,
1400 label: VideoModel.getPrivacyLabel(this.privacy)
1401 },
3fd3ab2d
C
1402 nsfw: this.nsfw,
1403 description: this.getTruncatedDescription(),
3fd3ab2d 1404 isLocal: this.isOwned(),
3fd3ab2d
C
1405 duration: this.duration,
1406 views: this.views,
1407 likes: this.likes,
1408 dislikes: this.dislikes,
40e87e9e
C
1409 thumbnailPath: this.getThumbnailStaticPath(),
1410 previewPath: this.getPreviewStaticPath(),
1411 embedPath: this.getEmbedStaticPath(),
3fd3ab2d 1412 createdAt: this.createdAt,
b64c950a 1413 updatedAt: this.updatedAt,
2922e048 1414 publishedAt: this.publishedAt,
b64c950a 1415 account: {
03e12d7c
C
1416 id: formattedAccount.id,
1417 uuid: formattedAccount.uuid,
b64c950a
C
1418 name: formattedAccount.name,
1419 displayName: formattedAccount.displayName,
1420 url: formattedAccount.url,
1421 host: formattedAccount.host,
1422 avatar: formattedAccount.avatar
0f320037
C
1423 },
1424 channel: {
1425 id: formattedVideoChannel.id,
1426 uuid: formattedVideoChannel.uuid,
1427 name: formattedVideoChannel.name,
1428 displayName: formattedVideoChannel.displayName,
1429 url: formattedVideoChannel.url,
1430 host: formattedVideoChannel.host,
1431 avatar: formattedVideoChannel.avatar
b64c950a 1432 }
2422c46b 1433 }
2186386c
C
1434
1435 if (options) {
bbe0f064 1436 if (options.additionalAttributes.state === true) {
2186386c
C
1437 videoObject.state = {
1438 id: this.state,
1439 label: VideoModel.getStateLabel(this.state)
1440 }
1441 }
1442
bbe0f064 1443 if (options.additionalAttributes.waitTranscoding === true) {
2baea0c7
C
1444 videoObject.waitTranscoding = this.waitTranscoding
1445 }
1446
bbe0f064 1447 if (options.additionalAttributes.scheduledUpdate === true && this.ScheduleVideoUpdate) {
2baea0c7
C
1448 videoObject.scheduledUpdate = {
1449 updateAt: this.ScheduleVideoUpdate.updateAt,
1450 privacy: this.ScheduleVideoUpdate.privacy || undefined
1451 }
1452 }
26b7305a
C
1453
1454 if (options.additionalAttributes.blacklistInfo === true) {
1455 videoObject.blacklisted = !!this.VideoBlacklist
1456 videoObject.blacklistedReason = this.VideoBlacklist ? this.VideoBlacklist.reason : null
1457 }
2186386c
C
1458 }
1459
1460 return videoObject
14d3270f 1461 }
14d3270f 1462
2422c46b 1463 toFormattedDetailsJSON (): VideoDetails {
bbe0f064
C
1464 const formattedJson = this.toFormattedJSON({
1465 additionalAttributes: {
191764f3
C
1466 scheduledUpdate: true,
1467 blacklistInfo: true
bbe0f064
C
1468 }
1469 })
e4f97bab 1470
3fd3ab2d 1471 const detailsJson = {
2422c46b 1472 support: this.support,
3fd3ab2d
C
1473 descriptionPath: this.getDescriptionPath(),
1474 channel: this.VideoChannel.toFormattedJSON(),
1475 account: this.VideoChannel.Account.toFormattedJSON(),
ee28cdf1 1476 tags: map(this.Tags, 'name'),
47564bbe 1477 commentsEnabled: this.commentsEnabled,
2186386c
C
1478 waitTranscoding: this.waitTranscoding,
1479 state: {
1480 id: this.state,
1481 label: VideoModel.getStateLabel(this.state)
1482 },
3fd3ab2d
C
1483 files: []
1484 }
e4f97bab 1485
3fd3ab2d 1486 // Format and sort video files
244e76a5
RK
1487 detailsJson.files = this.getFormattedVideoFilesJSON()
1488
1489 return Object.assign(formattedJson, detailsJson)
1490 }
1491
1492 getFormattedVideoFilesJSON (): VideoFile[] {
3fd3ab2d 1493 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
3fd3ab2d 1494
244e76a5 1495 return this.VideoFiles
8ea6f49a
C
1496 .map(videoFile => {
1497 let resolutionLabel = videoFile.resolution + 'p'
1498
1499 return {
1500 resolution: {
1501 id: videoFile.resolution,
1502 label: resolutionLabel
1503 },
1504 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1505 size: videoFile.size,
1506 fps: videoFile.fps,
1507 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1508 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1509 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1510 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
1511 } as VideoFile
1512 })
1513 .sort((a, b) => {
1514 if (a.resolution.id < b.resolution.id) return 1
1515 if (a.resolution.id === b.resolution.id) return 0
1516 return -1
1517 })
3fd3ab2d 1518 }
e4f97bab 1519
3fd3ab2d
C
1520 toActivityPubObject (): VideoTorrentObject {
1521 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1522 if (!this.Tags) this.Tags = []
e4f97bab 1523
3fd3ab2d
C
1524 const tag = this.Tags.map(t => ({
1525 type: 'Hashtag' as 'Hashtag',
1526 name: t.name
1527 }))
40298b02 1528
3fd3ab2d
C
1529 let language
1530 if (this.language) {
1531 language = {
9d3ef9fe 1532 identifier: this.language,
ae5a3dd6 1533 name: VideoModel.getLanguageLabel(this.language)
3fd3ab2d
C
1534 }
1535 }
40298b02 1536
3fd3ab2d
C
1537 let category
1538 if (this.category) {
1539 category = {
1540 identifier: this.category + '',
ae5a3dd6 1541 name: VideoModel.getCategoryLabel(this.category)
3fd3ab2d
C
1542 }
1543 }
40298b02 1544
3fd3ab2d
C
1545 let licence
1546 if (this.licence) {
1547 licence = {
1548 identifier: this.licence + '',
ae5a3dd6 1549 name: VideoModel.getLicenceLabel(this.licence)
3fd3ab2d
C
1550 }
1551 }
9567011b 1552
c48e82b5 1553 const url: ActivityUrlObject[] = []
3fd3ab2d
C
1554 for (const file of this.VideoFiles) {
1555 url.push({
1556 type: 'Link',
c48e82b5 1557 mimeType: VIDEO_EXT_MIMETYPE[ file.extname ] as any,
9fb3abfd 1558 href: this.getVideoFileUrl(file, baseUrlHttp),
965c4b22 1559 height: file.resolution,
b2977eec
C
1560 size: file.size,
1561 fps: file.fps
3fd3ab2d
C
1562 })
1563
1564 url.push({
1565 type: 'Link',
c48e82b5 1566 mimeType: 'application/x-bittorrent' as 'application/x-bittorrent',
9fb3abfd 1567 href: this.getTorrentUrl(file, baseUrlHttp),
965c4b22 1568 height: file.resolution
3fd3ab2d
C
1569 })
1570
1571 url.push({
1572 type: 'Link',
c48e82b5 1573 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet' as 'application/x-bittorrent;x-scheme-handler/magnet',
9fb3abfd 1574 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
965c4b22 1575 height: file.resolution
3fd3ab2d
C
1576 })
1577 }
93e1258c 1578
3fd3ab2d
C
1579 // Add video url too
1580 url.push({
1581 type: 'Link',
1582 mimeType: 'text/html',
9fb3abfd 1583 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
3fd3ab2d 1584 })
93e1258c 1585
40e87e9e
C
1586 const subtitleLanguage = []
1587 for (const caption of this.VideoCaptions) {
1588 subtitleLanguage.push({
1589 identifier: caption.language,
1590 name: VideoCaptionModel.getLanguageLabel(caption.language)
1591 })
1592 }
1593
3fd3ab2d
C
1594 return {
1595 type: 'Video' as 'Video',
1596 id: this.url,
1597 name: this.name,
093237cf 1598 duration: this.getActivityStreamDuration(),
3fd3ab2d
C
1599 uuid: this.uuid,
1600 tag,
1601 category,
1602 licence,
1603 language,
1604 views: this.views,
0a67e28b 1605 sensitive: this.nsfw,
2186386c
C
1606 waitTranscoding: this.waitTranscoding,
1607 state: this.state,
47564bbe 1608 commentsEnabled: this.commentsEnabled,
2922e048 1609 published: this.publishedAt.toISOString(),
3fd3ab2d
C
1610 updated: this.updatedAt.toISOString(),
1611 mediaType: 'text/markdown',
1612 content: this.getTruncatedDescription(),
2422c46b 1613 support: this.support,
40e87e9e 1614 subtitleLanguage,
3fd3ab2d
C
1615 icon: {
1616 type: 'Image',
1617 url: this.getThumbnailUrl(baseUrlHttp),
1618 mediaType: 'image/jpeg',
1619 width: THUMBNAILS_SIZE.width,
1620 height: THUMBNAILS_SIZE.height
1621 },
1622 url,
8fffe21a
C
1623 likes: getVideoLikesActivityPubUrl(this),
1624 dislikes: getVideoDislikesActivityPubUrl(this),
1625 shares: getVideoSharesActivityPubUrl(this),
1626 comments: getVideoCommentsActivityPubUrl(this),
50d6de9c 1627 attributedTo: [
2ccaeeb3
C
1628 {
1629 type: 'Person',
1630 id: this.VideoChannel.Account.Actor.url
fc27b17c
C
1631 },
1632 {
1633 type: 'Group',
1634 id: this.VideoChannel.Actor.url
50d6de9c
C
1635 }
1636 ]
3fd3ab2d
C
1637 }
1638 }
1639
1640 getTruncatedDescription () {
1641 if (!this.description) return null
93e1258c 1642
bffbebbe 1643 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
c73e83da 1644 return peertubeTruncate(this.description, maxLength)
93e1258c
C
1645 }
1646
81e504b3 1647 async optimizeOriginalVideofile () {
3fd3ab2d
C
1648 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1649 const newExtname = '.mp4'
1650 const inputVideoFile = this.getOriginalFile()
1651 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
3a6f351b 1652 const videoTranscodedPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
b769007f 1653
3fd3ab2d
C
1654 const transcodeOptions = {
1655 inputPath: videoInputPath,
3a6f351b 1656 outputPath: videoTranscodedPath
3fd3ab2d 1657 }
c46edbc2 1658
b0ef1782
C
1659 // Could be very long!
1660 await transcode(transcodeOptions)
c46edbc2 1661
b0ef1782 1662 try {
62689b94 1663 await remove(videoInputPath)
c46edbc2 1664
3fd3ab2d
C
1665 // Important to do this before getVideoFilename() to take in account the new file extension
1666 inputVideoFile.set('extname', newExtname)
e71bcc0f 1667
3a6f351b 1668 const videoOutputPath = this.getVideoFilePath(inputVideoFile)
62689b94
C
1669 await rename(videoTranscodedPath, videoOutputPath)
1670 const stats = await stat(videoOutputPath)
3a6f351b 1671 const fps = await getVideoFileFPS(videoOutputPath)
e71bcc0f 1672
3fd3ab2d 1673 inputVideoFile.set('size', stats.size)
3a6f351b 1674 inputVideoFile.set('fps', fps)
e71bcc0f 1675
3fd3ab2d
C
1676 await this.createTorrentAndSetInfoHash(inputVideoFile)
1677 await inputVideoFile.save()
fd45e8f4 1678
3fd3ab2d
C
1679 } catch (err) {
1680 // Auto destruction...
d5b7d911 1681 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
fd45e8f4 1682
3fd3ab2d
C
1683 throw err
1684 }
feb4bdfd
C
1685 }
1686
81e504b3 1687 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
3fd3ab2d
C
1688 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1689 const extname = '.mp4'
aaf61f38 1690
3fd3ab2d
C
1691 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1692 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
feb4bdfd 1693
3fd3ab2d
C
1694 const newVideoFile = new VideoFileModel({
1695 resolution,
1696 extname,
1697 size: 0,
1698 videoId: this.id
1699 })
1700 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
a041b171 1701
3fd3ab2d
C
1702 const transcodeOptions = {
1703 inputPath: videoInputPath,
1704 outputPath: videoOutputPath,
056aa7f2
C
1705 resolution,
1706 isPortraitMode
3fd3ab2d 1707 }
a041b171 1708
3fd3ab2d 1709 await transcode(transcodeOptions)
a041b171 1710
62689b94 1711 const stats = await stat(videoOutputPath)
3a6f351b 1712 const fps = await getVideoFileFPS(videoOutputPath)
d7d5611c 1713
3fd3ab2d 1714 newVideoFile.set('size', stats.size)
3a6f351b 1715 newVideoFile.set('fps', fps)
d7d5611c 1716
3fd3ab2d 1717 await this.createTorrentAndSetInfoHash(newVideoFile)
d7d5611c 1718
3fd3ab2d
C
1719 await newVideoFile.save()
1720
1721 this.VideoFiles.push(newVideoFile)
0d0e8dd0
C
1722 }
1723
0138af92 1724 async importVideoFile (inputFilePath: string) {
3a6f351b 1725 const { videoFileResolution } = await getVideoFileResolution(inputFilePath)
62689b94 1726 const { size } = await stat(inputFilePath)
3a6f351b
C
1727 const fps = await getVideoFileFPS(inputFilePath)
1728
0138af92 1729 let updatedVideoFile = new VideoFileModel({
3a6f351b 1730 resolution: videoFileResolution,
0138af92 1731 extname: extname(inputFilePath),
3a6f351b
C
1732 size,
1733 fps,
0138af92
FF
1734 videoId: this.id
1735 })
1736
0138af92 1737 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
0138af92 1738
28be8916
C
1739 if (currentVideoFile) {
1740 // Remove old file and old torrent
1741 await this.removeFile(currentVideoFile)
1742 await this.removeTorrent(currentVideoFile)
1743 // Remove the old video file from the array
1744 this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile)
1745
1746 // Update the database
1747 currentVideoFile.set('extname', updatedVideoFile.extname)
0138af92 1748 currentVideoFile.set('size', updatedVideoFile.size)
3a6f351b 1749 currentVideoFile.set('fps', updatedVideoFile.fps)
28be8916 1750
0138af92
FF
1751 updatedVideoFile = currentVideoFile
1752 }
1753
6ccdf3a2 1754 const outputPath = this.getVideoFilePath(updatedVideoFile)
62689b94 1755 await copy(inputFilePath, outputPath)
6ccdf3a2 1756
0138af92
FF
1757 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1758
1759 await updatedVideoFile.save()
1760
28be8916 1761 this.VideoFiles.push(updatedVideoFile)
0138af92
FF
1762 }
1763
056aa7f2 1764 getOriginalFileResolution () {
3fd3ab2d 1765 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
0d0e8dd0 1766
056aa7f2 1767 return getVideoFileResolution(originalFilePath)
3fd3ab2d 1768 }
0d0e8dd0 1769
3fd3ab2d
C
1770 getDescriptionPath () {
1771 return `/api/${API_VERSION}/videos/${this.uuid}/description`
feb4bdfd
C
1772 }
1773
3fd3ab2d
C
1774 removeThumbnail () {
1775 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
62689b94 1776 return remove(thumbnailPath)
ed31c059 1777 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
feb4bdfd
C
1778 }
1779
3fd3ab2d 1780 removePreview () {
ed31c059 1781 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
62689b94 1782 return remove(previewPath)
ed31c059 1783 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
7920c273
C
1784 }
1785
3fd3ab2d
C
1786 removeFile (videoFile: VideoFileModel) {
1787 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
62689b94 1788 return remove(filePath)
ed31c059 1789 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
feb4bdfd
C
1790 }
1791
3fd3ab2d
C
1792 removeTorrent (videoFile: VideoFileModel) {
1793 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
62689b94 1794 return remove(torrentPath)
ed31c059 1795 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
aaf61f38
C
1796 }
1797
093237cf
C
1798 getActivityStreamDuration () {
1799 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1800 return 'PT' + this.duration + 'S'
1801 }
1802
1297eb5d
C
1803 isOutdated () {
1804 if (this.isOwned()) return false
1805
1806 const now = Date.now()
1807 const createdAtTime = this.createdAt.getTime()
1808 const updatedAtTime = this.updatedAt.getTime()
1809
1810 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1811 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1812 }
1813
c48e82b5 1814 getBaseUrls () {
3fd3ab2d
C
1815 let baseUrlHttp
1816 let baseUrlWs
7920c273 1817
3fd3ab2d
C
1818 if (this.isOwned()) {
1819 baseUrlHttp = CONFIG.WEBSERVER.URL
1820 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1821 } else {
50d6de9c
C
1822 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1823 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
6fcd19ba 1824 }
aaf61f38 1825
3fd3ab2d 1826 return { baseUrlHttp, baseUrlWs }
15d4ee04 1827 }
a96aed15 1828
c48e82b5
C
1829 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1830 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1831 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1832 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1833
1834 const redundancies = videoFile.RedundancyVideos
1835 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1836
1837 const magnetHash = {
1838 xs,
1839 announce,
1840 urlList,
1841 infoHash: videoFile.infoHash,
1842 name: this.name
1843 }
1844
1845 return magnetUtil.encode(magnetHash)
1846 }
1847
1848 getThumbnailUrl (baseUrlHttp: string) {
3fd3ab2d 1849 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
a96aed15
C
1850 }
1851
c48e82b5 1852 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
3fd3ab2d
C
1853 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1854 }
e4f97bab 1855
c48e82b5 1856 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
02756fbd
C
1857 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1858 }
1859
c48e82b5 1860 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
3fd3ab2d
C
1861 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1862 }
a96aed15 1863
c48e82b5 1864 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
02756fbd
C
1865 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1866 }
a96aed15 1867}