]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video/video.ts
Add federation to ownership change
[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'
2186386c 30import { 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'
47564bbe 36import { 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'
3fd3ab2d 93
57c36b27
C
94// FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
95const indexes: Sequelize.DefineIndexesOptions[] = [
96 buildTrigramSearchIndex('video_name_trigram', 'name'),
97
8cd72bd3
C
98 { fields: [ 'createdAt' ] },
99 { fields: [ 'publishedAt' ] },
100 { fields: [ 'duration' ] },
101 { fields: [ 'category' ] },
102 { fields: [ 'licence' ] },
103 { fields: [ 'nsfw' ] },
104 { fields: [ 'language' ] },
105 { fields: [ 'waitTranscoding' ] },
106 { fields: [ 'state' ] },
107 { fields: [ 'remote' ] },
108 { fields: [ 'views' ] },
109 { fields: [ 'likes' ] },
110 { fields: [ 'channelId' ] },
57c36b27 111 {
8cd72bd3
C
112 fields: [ 'uuid' ],
113 unique: true
57c36b27
C
114 },
115 {
8ea6f49a 116 fields: [ 'url' ],
57c36b27
C
117 unique: true
118 }
119]
120
2baea0c7 121export enum ScopeNames {
afd2cba5
C
122 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
123 FOR_API = 'FOR_API',
4cb6d457 124 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
d48ff09d 125 WITH_TAGS = 'WITH_TAGS',
bbe0f064 126 WITH_FILES = 'WITH_FILES',
191764f3
C
127 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
128 WITH_BLACKLISTED = 'WITH_BLACKLISTED'
d48ff09d
C
129}
130
afd2cba5
C
131type ForAPIOptions = {
132 ids: number[]
133 withFiles?: boolean
134}
135
136type AvailableForListIDsOptions = {
137 actorId: number
138 includeLocalVideos: boolean
139 filter?: VideoFilter
140 categoryOneOf?: number[]
141 nsfw?: boolean
142 licenceOneOf?: number[]
143 languageOneOf?: string[]
144 tagsOneOf?: string[]
145 tagsAllOf?: string[]
146 withFiles?: boolean
147 accountId?: number
d525fc39 148 videoChannelId?: number
9a629c6e 149 trendingDays?: number
d525fc39
C
150}
151
d48ff09d 152@Scopes({
8ea6f49a 153 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
0626e7af 154 const accountInclude = {
03e12d7c 155 attributes: [ 'id', 'name' ],
0626e7af
C
156 model: AccountModel.unscoped(),
157 required: true,
0626e7af
C
158 include: [
159 {
03e12d7c 160 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
0626e7af
C
161 model: ActorModel.unscoped(),
162 required: true,
0626e7af
C
163 include: [
164 {
165 attributes: [ 'host' ],
166 model: ServerModel.unscoped(),
167 required: false
168 },
169 {
170 model: AvatarModel.unscoped(),
171 required: false
172 }
173 ]
174 }
175 ]
176 }
177
48dce1c9 178 const videoChannelInclude = {
0f320037 179 attributes: [ 'name', 'description', 'id' ],
48dce1c9
C
180 model: VideoChannelModel.unscoped(),
181 required: true,
48dce1c9 182 include: [
0f320037
C
183 {
184 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
185 model: ActorModel.unscoped(),
186 required: true,
187 include: [
188 {
189 attributes: [ 'host' ],
190 model: ServerModel.unscoped(),
191 required: false
192 },
193 {
194 model: AvatarModel.unscoped(),
195 required: false
196 }
197 ]
198 },
48dce1c9
C
199 accountInclude
200 ]
201 }
202
244e76a5 203 const query: IFindOptions<VideoModel> = {
afd2cba5
C
204 where: {
205 id: {
8ea6f49a 206 [ Sequelize.Op.any ]: options.ids
afd2cba5
C
207 }
208 },
209 include: [ videoChannelInclude ]
210 }
211
212 if (options.withFiles === true) {
213 query.include.push({
214 model: VideoFileModel.unscoped(),
215 required: true
216 })
217 }
218
219 return query
220 },
8ea6f49a 221 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
afd2cba5
C
222 const query: IFindOptions<VideoModel> = {
223 attributes: [ 'id' ],
244e76a5
RK
224 where: {
225 id: {
8ea6f49a 226 [ Sequelize.Op.and ]: [
b6314e3c
C
227 {
228 [ Sequelize.Op.notIn ]: Sequelize.literal(
229 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
230 )
231 }
232 ]
244e76a5 233 },
2186386c
C
234 // Always list public videos
235 privacy: VideoPrivacy.PUBLIC,
236 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
237 [ Sequelize.Op.or ]: [
238 {
239 state: VideoState.PUBLISHED
240 },
241 {
242 [ Sequelize.Op.and ]: {
243 state: VideoState.TO_TRANSCODE,
244 waitTranscoding: false
245 }
246 }
247 ]
50d6de9c 248 },
8ea6f49a 249 include: []
afd2cba5
C
250 }
251
252 if (options.filter || options.accountId || options.videoChannelId) {
253 const videoChannelInclude: IIncludeOptions = {
254 attributes: [],
255 model: VideoChannelModel.unscoped(),
256 required: true
257 }
258
259 if (options.videoChannelId) {
260 videoChannelInclude.where = {
261 id: options.videoChannelId
262 }
263 }
264
265 if (options.filter || options.accountId) {
266 const accountInclude: IIncludeOptions = {
267 attributes: [],
268 model: AccountModel.unscoped(),
269 required: true
270 }
271
272 if (options.filter) {
273 accountInclude.include = [
274 {
275 attributes: [],
276 model: ActorModel.unscoped(),
277 required: true,
278 where: VideoModel.buildActorWhereWithFilter(options.filter)
279 }
280 ]
281 }
282
283 if (options.accountId) {
284 accountInclude.where = { id: options.accountId }
285 }
286
287 videoChannelInclude.include = [ accountInclude ]
288 }
289
290 query.include.push(videoChannelInclude)
244e76a5
RK
291 }
292
687d638c
C
293 if (options.actorId) {
294 let localVideosReq = ''
295 if (options.includeLocalVideos === true) {
296 localVideosReq = ' UNION ALL ' +
297 'SELECT "video"."id" AS "id" FROM "video" ' +
298 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
299 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
300 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
301 'WHERE "actor"."serverId" IS NULL'
302 }
303
304 // Force actorId to be a number to avoid SQL injections
305 const actorIdNumber = parseInt(options.actorId.toString(), 10)
8ea6f49a 306 query.where[ 'id' ][ Sequelize.Op.and ].push({
b6314e3c
C
307 [ Sequelize.Op.in ]: Sequelize.literal(
308 '(' +
8ea6f49a
C
309 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
310 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
311 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
312 ' UNION ALL ' +
313 'SELECT "video"."id" AS "id" FROM "video" ' +
314 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
315 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
316 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
317 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
318 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
319 localVideosReq +
b6314e3c
C
320 ')'
321 )
322 })
687d638c
C
323 }
324
48dce1c9 325 if (options.withFiles === true) {
8ea6f49a 326 query.where[ 'id' ][ Sequelize.Op.and ].push({
b6314e3c
C
327 [ Sequelize.Op.in ]: Sequelize.literal(
328 '(SELECT "videoId" FROM "videoFile")'
329 )
244e76a5
RK
330 })
331 }
332
d525fc39
C
333 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
334 if (options.tagsAllOf || options.tagsOneOf) {
335 const createTagsIn = (tags: string[]) => {
336 return tags.map(t => VideoModel.sequelize.escape(t))
337 .join(', ')
338 }
339
340 if (options.tagsOneOf) {
8ea6f49a
C
341 query.where[ 'id' ][ Sequelize.Op.and ].push({
342 [ Sequelize.Op.in ]: Sequelize.literal(
b6314e3c 343 '(' +
d525fc39
C
344 'SELECT "videoId" FROM "videoTag" ' +
345 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
346 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
b6314e3c
C
347 ')'
348 )
349 })
d525fc39
C
350 }
351
352 if (options.tagsAllOf) {
8ea6f49a
C
353 query.where[ 'id' ][ Sequelize.Op.and ].push({
354 [ Sequelize.Op.in ]: Sequelize.literal(
d525fc39 355 '(' +
b6314e3c
C
356 'SELECT "videoId" FROM "videoTag" ' +
357 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
358 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
359 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
d525fc39 360 ')'
b6314e3c
C
361 )
362 })
d525fc39
C
363 }
364 }
365
366 if (options.nsfw === true || options.nsfw === false) {
8ea6f49a 367 query.where[ 'nsfw' ] = options.nsfw
d525fc39
C
368 }
369
370 if (options.categoryOneOf) {
8ea6f49a
C
371 query.where[ 'category' ] = {
372 [ Sequelize.Op.or ]: options.categoryOneOf
d525fc39
C
373 }
374 }
375
376 if (options.licenceOneOf) {
8ea6f49a
C
377 query.where[ 'licence' ] = {
378 [ Sequelize.Op.or ]: options.licenceOneOf
d525fc39 379 }
0883b324
C
380 }
381
d525fc39 382 if (options.languageOneOf) {
8ea6f49a
C
383 query.where[ 'language' ] = {
384 [ Sequelize.Op.or ]: options.languageOneOf
d525fc39 385 }
61b909b9
P
386 }
387
9a629c6e
C
388 if (options.trendingDays) {
389 query.include.push({
390 attributes: [],
391 model: VideoViewModel,
392 required: false,
393 where: {
394 startDate: {
395 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * options.trendingDays)
396 }
397 }
398 })
399
400 query.subQuery = false
401 }
402
244e76a5
RK
403 return query
404 },
8ea6f49a 405 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
d48ff09d
C
406 include: [
407 {
6120941f 408 model: () => VideoChannelModel.unscoped(),
d48ff09d
C
409 required: true,
410 include: [
6120941f
C
411 {
412 attributes: {
413 exclude: [ 'privateKey', 'publicKey' ]
414 },
3e500247
C
415 model: () => ActorModel.unscoped(),
416 required: true,
417 include: [
418 {
419 attributes: [ 'host' ],
420 model: () => ServerModel.unscoped(),
421 required: false
52d9f792
C
422 },
423 {
424 model: () => AvatarModel.unscoped(),
425 required: false
3e500247
C
426 }
427 ]
6120941f 428 },
d48ff09d 429 {
3e500247 430 model: () => AccountModel.unscoped(),
d48ff09d
C
431 required: true,
432 include: [
433 {
3e500247 434 model: () => ActorModel.unscoped(),
6120941f
C
435 attributes: {
436 exclude: [ 'privateKey', 'publicKey' ]
437 },
50d6de9c
C
438 required: true,
439 include: [
440 {
3e500247
C
441 attributes: [ 'host' ],
442 model: () => ServerModel.unscoped(),
50d6de9c 443 required: false
b6a4fd6b
C
444 },
445 {
446 model: () => AvatarModel.unscoped(),
447 required: false
50d6de9c
C
448 }
449 ]
d48ff09d
C
450 }
451 ]
452 }
453 ]
454 }
455 ]
456 },
8ea6f49a 457 [ ScopeNames.WITH_TAGS ]: {
d48ff09d
C
458 include: [ () => TagModel ]
459 },
8ea6f49a 460 [ ScopeNames.WITH_BLACKLISTED ]: {
191764f3
C
461 include: [
462 {
463 attributes: [ 'id', 'reason' ],
464 model: () => VideoBlacklistModel,
465 required: false
466 }
467 ]
468 },
8ea6f49a 469 [ ScopeNames.WITH_FILES ]: {
d48ff09d
C
470 include: [
471 {
e53f952e 472 model: () => VideoFileModel.unscoped(),
fbad87b0 473 required: false
d48ff09d
C
474 }
475 ]
bbe0f064 476 },
8ea6f49a 477 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
bbe0f064
C
478 include: [
479 {
480 model: () => ScheduleVideoUpdateModel.unscoped(),
481 required: false
482 }
483 ]
d48ff09d
C
484 }
485})
3fd3ab2d
C
486@Table({
487 tableName: 'video',
57c36b27 488 indexes
3fd3ab2d
C
489})
490export class VideoModel extends Model<VideoModel> {
491
492 @AllowNull(false)
493 @Default(DataType.UUIDV4)
494 @IsUUID(4)
495 @Column(DataType.UUID)
496 uuid: string
497
498 @AllowNull(false)
499 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
500 @Column
501 name: string
502
503 @AllowNull(true)
504 @Default(null)
505 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
506 @Column
507 category: number
508
509 @AllowNull(true)
510 @Default(null)
511 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
512 @Column
513 licence: number
514
515 @AllowNull(true)
516 @Default(null)
517 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
9d3ef9fe
C
518 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
519 language: string
3fd3ab2d
C
520
521 @AllowNull(false)
522 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
523 @Column
524 privacy: number
525
526 @AllowNull(false)
47564bbe 527 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
3fd3ab2d
C
528 @Column
529 nsfw: boolean
530
531 @AllowNull(true)
532 @Default(null)
533 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
534 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
535 description: string
536
2422c46b
C
537 @AllowNull(true)
538 @Default(null)
539 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
540 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
541 support: string
542
3fd3ab2d
C
543 @AllowNull(false)
544 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
545 @Column
546 duration: number
547
548 @AllowNull(false)
549 @Default(0)
550 @IsInt
551 @Min(0)
552 @Column
553 views: number
554
555 @AllowNull(false)
556 @Default(0)
557 @IsInt
558 @Min(0)
559 @Column
560 likes: number
561
562 @AllowNull(false)
563 @Default(0)
564 @IsInt
565 @Min(0)
566 @Column
567 dislikes: number
568
569 @AllowNull(false)
570 @Column
571 remote: boolean
572
573 @AllowNull(false)
574 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
575 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
576 url: string
577
47564bbe
C
578 @AllowNull(false)
579 @Column
580 commentsEnabled: boolean
581
2186386c
C
582 @AllowNull(false)
583 @Column
584 waitTranscoding: boolean
585
586 @AllowNull(false)
587 @Default(null)
588 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
589 @Column
590 state: VideoState
591
3fd3ab2d
C
592 @CreatedAt
593 createdAt: Date
594
595 @UpdatedAt
596 updatedAt: Date
597
2922e048
JLB
598 @AllowNull(false)
599 @Default(Sequelize.NOW)
600 @Column
601 publishedAt: Date
602
3fd3ab2d
C
603 @ForeignKey(() => VideoChannelModel)
604 @Column
605 channelId: number
606
607 @BelongsTo(() => VideoChannelModel, {
feb4bdfd 608 foreignKey: {
50d6de9c 609 allowNull: true
feb4bdfd 610 },
6b738c7a 611 hooks: true
feb4bdfd 612 })
3fd3ab2d 613 VideoChannel: VideoChannelModel
7920c273 614
3fd3ab2d 615 @BelongsToMany(() => TagModel, {
7920c273 616 foreignKey: 'videoId',
3fd3ab2d
C
617 through: () => VideoTagModel,
618 onDelete: 'CASCADE'
7920c273 619 })
3fd3ab2d 620 Tags: TagModel[]
55fa55a9 621
3fd3ab2d 622 @HasMany(() => VideoAbuseModel, {
55fa55a9
C
623 foreignKey: {
624 name: 'videoId',
625 allowNull: false
626 },
627 onDelete: 'cascade'
628 })
3fd3ab2d 629 VideoAbuses: VideoAbuseModel[]
93e1258c 630
3fd3ab2d 631 @HasMany(() => VideoFileModel, {
93e1258c
C
632 foreignKey: {
633 name: 'videoId',
634 allowNull: false
635 },
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
C
1065 static load (id: number, t?: Sequelize.Transaction) {
1066 const options = t ? { transaction: t } : undefined
1067
1068 return VideoModel.findById(id, options)
3fd3ab2d 1069 }
fdbda9e3 1070
3fd3ab2d
C
1071 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
1072 const query: IFindOptions<VideoModel> = {
1073 where: {
1074 url
d48ff09d 1075 }
3fd3ab2d 1076 }
d8755eed 1077
3fd3ab2d 1078 if (t !== undefined) query.transaction = t
d8755eed 1079
4cb6d457 1080 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
3fd3ab2d 1081 }
d8755eed 1082
3fd3ab2d
C
1083 static loadAndPopulateAccountAndServerAndTags (id: number) {
1084 const options = {
d48ff09d 1085 order: [ [ 'Tags', 'name', 'ASC' ] ]
3fd3ab2d 1086 }
72c7248b 1087
d48ff09d 1088 return VideoModel
191764f3
C
1089 .scope([
1090 ScopeNames.WITH_TAGS,
1091 ScopeNames.WITH_BLACKLISTED,
1092 ScopeNames.WITH_FILES,
1093 ScopeNames.WITH_ACCOUNT_DETAILS,
1094 ScopeNames.WITH_SCHEDULED_UPDATE
1095 ])
d48ff09d 1096 .findById(id, options)
3fd3ab2d 1097 }
72c7248b 1098
8fa5653a
C
1099 static loadByUUID (uuid: string) {
1100 const options = {
1101 where: {
1102 uuid
1103 }
1104 }
1105
1106 return VideoModel
1107 .scope([ ScopeNames.WITH_FILES ])
1108 .findOne(options)
1109 }
1110
2186386c 1111 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string, t?: Sequelize.Transaction) {
3fd3ab2d
C
1112 const options = {
1113 order: [ [ 'Tags', 'name', 'ASC' ] ],
1114 where: {
1115 uuid
2186386c
C
1116 },
1117 transaction: t
3fd3ab2d 1118 }
fd45e8f4 1119
d48ff09d 1120 return VideoModel
191764f3
C
1121 .scope([
1122 ScopeNames.WITH_TAGS,
1123 ScopeNames.WITH_BLACKLISTED,
1124 ScopeNames.WITH_FILES,
1125 ScopeNames.WITH_ACCOUNT_DETAILS,
1126 ScopeNames.WITH_SCHEDULED_UPDATE
1127 ])
da854ddd
C
1128 .findOne(options)
1129 }
1130
09cababd
C
1131 static async getStats () {
1132 const totalLocalVideos = await VideoModel.count({
1133 where: {
1134 remote: false
1135 }
1136 })
1137 const totalVideos = await VideoModel.count()
1138
1139 let totalLocalVideoViews = await VideoModel.sum('views', {
1140 where: {
1141 remote: false
1142 }
1143 })
1144 // Sequelize could return null...
1145 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1146
1147 return {
1148 totalLocalVideos,
1149 totalLocalVideoViews,
1150 totalVideos
1151 }
1152 }
1153
6b616860
C
1154 static incrementViews (id: number, views: number) {
1155 return VideoModel.increment('views', {
1156 by: views,
1157 where: {
1158 id
1159 }
1160 })
1161 }
1162
2d3741d6
C
1163 // threshold corresponds to how many video the field should have to be returned
1164 static getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1165 const query: IFindOptions<VideoModel> = {
1166 attributes: [ field ],
1167 limit: count,
1168 group: field,
1169 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
8ea6f49a 1170 [ Sequelize.Op.gte ]: threshold
2d3741d6
C
1171 }) as any, // FIXME: typings
1172 where: {
8ea6f49a
C
1173 [ field ]: {
1174 [ Sequelize.Op.not ]: null
2d3741d6
C
1175 },
1176 privacy: VideoPrivacy.PUBLIC,
1177 state: VideoState.PUBLISHED
1178 },
1179 order: [ this.sequelize.random() ]
1180 }
1181
1182 return VideoModel.findAll(query)
8ea6f49a 1183 .then(rows => rows.map(r => r[ field ]))
2d3741d6
C
1184 }
1185
066e94c5
C
1186 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1187 if (filter && filter === 'local') {
1188 return {
1189 serverId: null
1190 }
1191 }
1192
1193 return {}
1194 }
afd2cba5
C
1195
1196 private static async getAvailableForApi (query: IFindOptions<VideoModel>, options: AvailableForListIDsOptions) {
1197 const idsScope = {
1198 method: [
1199 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1200 ]
1201 }
1202
8ea6f49a
C
1203 // Remove trending sort on count, because it uses a group by
1204 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1205 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1206 const countScope = {
1207 method: [
1208 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1209 ]
1210 }
1211
1212 const [ count, rowsId ] = await Promise.all([
1213 VideoModel.scope(countScope).count(countQuery),
1214 VideoModel.scope(idsScope).findAll(query)
1215 ])
afd2cba5
C
1216 const ids = rowsId.map(r => r.id)
1217
1218 if (ids.length === 0) return { data: [], total: count }
1219
1220 const apiScope = {
1221 method: [ ScopeNames.FOR_API, { ids, withFiles: options.withFiles } as ForAPIOptions ]
1222 }
b6314e3c
C
1223
1224 const secondQuery = {
1225 offset: 0,
1226 limit: query.limit,
9a629c6e
C
1227 attributes: query.attributes,
1228 order: [ // Keep original order
1229 Sequelize.literal(
1230 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1231 )
1232 ]
b6314e3c
C
1233 }
1234 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
afd2cba5
C
1235
1236 return {
1237 data: rows,
1238 total: count
1239 }
1240 }
066e94c5 1241
ae5a3dd6 1242 private static getCategoryLabel (id: number) {
8ea6f49a 1243 return VIDEO_CATEGORIES[ id ] || 'Misc'
ae5a3dd6
C
1244 }
1245
1246 private static getLicenceLabel (id: number) {
8ea6f49a 1247 return VIDEO_LICENCES[ id ] || 'Unknown'
ae5a3dd6
C
1248 }
1249
9d3ef9fe 1250 private static getLanguageLabel (id: string) {
8ea6f49a 1251 return VIDEO_LANGUAGES[ id ] || 'Unknown'
ae5a3dd6
C
1252 }
1253
2243730c 1254 private static getPrivacyLabel (id: number) {
8ea6f49a 1255 return VIDEO_PRIVACIES[ id ] || 'Unknown'
2186386c 1256 }
2243730c 1257
2186386c 1258 private static getStateLabel (id: number) {
8ea6f49a 1259 return VIDEO_STATES[ id ] || 'Unknown'
2243730c
C
1260 }
1261
3fd3ab2d
C
1262 getOriginalFile () {
1263 if (Array.isArray(this.VideoFiles) === false) return undefined
aaf61f38 1264
3fd3ab2d
C
1265 // The original file is the file that have the higher resolution
1266 return maxBy(this.VideoFiles, file => file.resolution)
e4f97bab 1267 }
aaf61f38 1268
3fd3ab2d
C
1269 getVideoFilename (videoFile: VideoFileModel) {
1270 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1271 }
165cdc75 1272
3fd3ab2d
C
1273 getThumbnailName () {
1274 // We always have a copy of the thumbnail
1275 const extension = '.jpg'
1276 return this.uuid + extension
7b1f49de
C
1277 }
1278
3fd3ab2d
C
1279 getPreviewName () {
1280 const extension = '.jpg'
1281 return this.uuid + extension
1282 }
7b1f49de 1283
3fd3ab2d
C
1284 getTorrentFileName (videoFile: VideoFileModel) {
1285 const extension = '.torrent'
1286 return this.uuid + '-' + videoFile.resolution + extension
1287 }
8e7f08b5 1288
3fd3ab2d
C
1289 isOwned () {
1290 return this.remote === false
9567011b
C
1291 }
1292
3fd3ab2d 1293 createPreview (videoFile: VideoFileModel) {
3fd3ab2d
C
1294 return generateImageFromVideoFile(
1295 this.getVideoFilePath(videoFile),
1296 CONFIG.STORAGE.PREVIEWS_DIR,
1297 this.getPreviewName(),
26670720 1298 PREVIEWS_SIZE
3fd3ab2d
C
1299 )
1300 }
9567011b 1301
3fd3ab2d 1302 createThumbnail (videoFile: VideoFileModel) {
3fd3ab2d
C
1303 return generateImageFromVideoFile(
1304 this.getVideoFilePath(videoFile),
1305 CONFIG.STORAGE.THUMBNAILS_DIR,
1306 this.getThumbnailName(),
26670720 1307 THUMBNAILS_SIZE
3fd3ab2d 1308 )
14d3270f
C
1309 }
1310
02756fbd
C
1311 getTorrentFilePath (videoFile: VideoFileModel) {
1312 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1313 }
1314
3fd3ab2d
C
1315 getVideoFilePath (videoFile: VideoFileModel) {
1316 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1317 }
14d3270f 1318
81e504b3 1319 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
3fd3ab2d 1320 const options = {
6cced8f9
C
1321 // Keep the extname, it's used by the client to stream the file inside a web browser
1322 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
81e504b3 1323 createdBy: 'PeerTube',
3fd3ab2d 1324 announceList: [
0edf0581
C
1325 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1326 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
3fd3ab2d
C
1327 ],
1328 urlList: [
1329 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1330 ]
1331 }
14d3270f 1332
3fd3ab2d 1333 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
e4f97bab 1334
3fd3ab2d
C
1335 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1336 logger.info('Creating torrent %s.', filePath)
e4f97bab 1337
62689b94 1338 await writeFile(filePath, torrent)
e4f97bab 1339
3fd3ab2d
C
1340 const parsedTorrent = parseTorrent(torrent)
1341 videoFile.infoHash = parsedTorrent.infoHash
1342 }
e4f97bab 1343
40e87e9e 1344 getEmbedStaticPath () {
3fd3ab2d
C
1345 return '/videos/embed/' + this.uuid
1346 }
e4f97bab 1347
40e87e9e 1348 getThumbnailStaticPath () {
3fd3ab2d 1349 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
e4f97bab 1350 }
227d02fe 1351
40e87e9e 1352 getPreviewStaticPath () {
3fd3ab2d
C
1353 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1354 }
40298b02 1355
2186386c
C
1356 toFormattedJSON (options?: {
1357 additionalAttributes: {
bbe0f064
C
1358 state?: boolean,
1359 waitTranscoding?: boolean,
26b7305a
C
1360 scheduledUpdate?: boolean,
1361 blacklistInfo?: boolean
2186386c
C
1362 }
1363 }): Video {
b64c950a 1364 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
0f320037 1365 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
14d3270f 1366
2186386c 1367 const videoObject: Video = {
3fd3ab2d
C
1368 id: this.id,
1369 uuid: this.uuid,
1370 name: this.name,
ae5a3dd6
C
1371 category: {
1372 id: this.category,
1373 label: VideoModel.getCategoryLabel(this.category)
1374 },
1375 licence: {
1376 id: this.licence,
1377 label: VideoModel.getLicenceLabel(this.licence)
1378 },
1379 language: {
1380 id: this.language,
1381 label: VideoModel.getLanguageLabel(this.language)
1382 },
2243730c
C
1383 privacy: {
1384 id: this.privacy,
1385 label: VideoModel.getPrivacyLabel(this.privacy)
1386 },
3fd3ab2d
C
1387 nsfw: this.nsfw,
1388 description: this.getTruncatedDescription(),
3fd3ab2d 1389 isLocal: this.isOwned(),
3fd3ab2d
C
1390 duration: this.duration,
1391 views: this.views,
1392 likes: this.likes,
1393 dislikes: this.dislikes,
40e87e9e
C
1394 thumbnailPath: this.getThumbnailStaticPath(),
1395 previewPath: this.getPreviewStaticPath(),
1396 embedPath: this.getEmbedStaticPath(),
3fd3ab2d 1397 createdAt: this.createdAt,
b64c950a 1398 updatedAt: this.updatedAt,
2922e048 1399 publishedAt: this.publishedAt,
b64c950a 1400 account: {
03e12d7c
C
1401 id: formattedAccount.id,
1402 uuid: formattedAccount.uuid,
b64c950a
C
1403 name: formattedAccount.name,
1404 displayName: formattedAccount.displayName,
1405 url: formattedAccount.url,
1406 host: formattedAccount.host,
1407 avatar: formattedAccount.avatar
0f320037
C
1408 },
1409 channel: {
1410 id: formattedVideoChannel.id,
1411 uuid: formattedVideoChannel.uuid,
1412 name: formattedVideoChannel.name,
1413 displayName: formattedVideoChannel.displayName,
1414 url: formattedVideoChannel.url,
1415 host: formattedVideoChannel.host,
1416 avatar: formattedVideoChannel.avatar
b64c950a 1417 }
2422c46b 1418 }
2186386c
C
1419
1420 if (options) {
bbe0f064 1421 if (options.additionalAttributes.state === true) {
2186386c
C
1422 videoObject.state = {
1423 id: this.state,
1424 label: VideoModel.getStateLabel(this.state)
1425 }
1426 }
1427
bbe0f064 1428 if (options.additionalAttributes.waitTranscoding === true) {
2baea0c7
C
1429 videoObject.waitTranscoding = this.waitTranscoding
1430 }
1431
bbe0f064 1432 if (options.additionalAttributes.scheduledUpdate === true && this.ScheduleVideoUpdate) {
2baea0c7
C
1433 videoObject.scheduledUpdate = {
1434 updateAt: this.ScheduleVideoUpdate.updateAt,
1435 privacy: this.ScheduleVideoUpdate.privacy || undefined
1436 }
1437 }
26b7305a
C
1438
1439 if (options.additionalAttributes.blacklistInfo === true) {
1440 videoObject.blacklisted = !!this.VideoBlacklist
1441 videoObject.blacklistedReason = this.VideoBlacklist ? this.VideoBlacklist.reason : null
1442 }
2186386c
C
1443 }
1444
1445 return videoObject
14d3270f 1446 }
14d3270f 1447
2422c46b 1448 toFormattedDetailsJSON (): VideoDetails {
bbe0f064
C
1449 const formattedJson = this.toFormattedJSON({
1450 additionalAttributes: {
191764f3
C
1451 scheduledUpdate: true,
1452 blacklistInfo: true
bbe0f064
C
1453 }
1454 })
e4f97bab 1455
3fd3ab2d 1456 const detailsJson = {
2422c46b 1457 support: this.support,
3fd3ab2d
C
1458 descriptionPath: this.getDescriptionPath(),
1459 channel: this.VideoChannel.toFormattedJSON(),
1460 account: this.VideoChannel.Account.toFormattedJSON(),
ee28cdf1 1461 tags: map(this.Tags, 'name'),
47564bbe 1462 commentsEnabled: this.commentsEnabled,
2186386c
C
1463 waitTranscoding: this.waitTranscoding,
1464 state: {
1465 id: this.state,
1466 label: VideoModel.getStateLabel(this.state)
1467 },
3fd3ab2d
C
1468 files: []
1469 }
e4f97bab 1470
3fd3ab2d 1471 // Format and sort video files
244e76a5
RK
1472 detailsJson.files = this.getFormattedVideoFilesJSON()
1473
1474 return Object.assign(formattedJson, detailsJson)
1475 }
1476
1477 getFormattedVideoFilesJSON (): VideoFile[] {
3fd3ab2d 1478 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
3fd3ab2d 1479
244e76a5 1480 return this.VideoFiles
8ea6f49a
C
1481 .map(videoFile => {
1482 let resolutionLabel = videoFile.resolution + 'p'
1483
1484 return {
1485 resolution: {
1486 id: videoFile.resolution,
1487 label: resolutionLabel
1488 },
1489 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1490 size: videoFile.size,
1491 fps: videoFile.fps,
1492 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1493 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1494 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1495 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
1496 } as VideoFile
1497 })
1498 .sort((a, b) => {
1499 if (a.resolution.id < b.resolution.id) return 1
1500 if (a.resolution.id === b.resolution.id) return 0
1501 return -1
1502 })
3fd3ab2d 1503 }
e4f97bab 1504
3fd3ab2d
C
1505 toActivityPubObject (): VideoTorrentObject {
1506 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1507 if (!this.Tags) this.Tags = []
e4f97bab 1508
3fd3ab2d
C
1509 const tag = this.Tags.map(t => ({
1510 type: 'Hashtag' as 'Hashtag',
1511 name: t.name
1512 }))
40298b02 1513
3fd3ab2d
C
1514 let language
1515 if (this.language) {
1516 language = {
9d3ef9fe 1517 identifier: this.language,
ae5a3dd6 1518 name: VideoModel.getLanguageLabel(this.language)
3fd3ab2d
C
1519 }
1520 }
40298b02 1521
3fd3ab2d
C
1522 let category
1523 if (this.category) {
1524 category = {
1525 identifier: this.category + '',
ae5a3dd6 1526 name: VideoModel.getCategoryLabel(this.category)
3fd3ab2d
C
1527 }
1528 }
40298b02 1529
3fd3ab2d
C
1530 let licence
1531 if (this.licence) {
1532 licence = {
1533 identifier: this.licence + '',
ae5a3dd6 1534 name: VideoModel.getLicenceLabel(this.licence)
3fd3ab2d
C
1535 }
1536 }
9567011b 1537
3fd3ab2d
C
1538 const url = []
1539 for (const file of this.VideoFiles) {
1540 url.push({
1541 type: 'Link',
8ea6f49a 1542 mimeType: VIDEO_EXT_MIMETYPE[ file.extname ],
9fb3abfd 1543 href: this.getVideoFileUrl(file, baseUrlHttp),
965c4b22 1544 height: file.resolution,
b2977eec
C
1545 size: file.size,
1546 fps: file.fps
3fd3ab2d
C
1547 })
1548
1549 url.push({
1550 type: 'Link',
1551 mimeType: 'application/x-bittorrent',
9fb3abfd 1552 href: this.getTorrentUrl(file, baseUrlHttp),
965c4b22 1553 height: file.resolution
3fd3ab2d
C
1554 })
1555
1556 url.push({
1557 type: 'Link',
1558 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
9fb3abfd 1559 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
965c4b22 1560 height: file.resolution
3fd3ab2d
C
1561 })
1562 }
93e1258c 1563
3fd3ab2d
C
1564 // Add video url too
1565 url.push({
1566 type: 'Link',
1567 mimeType: 'text/html',
9fb3abfd 1568 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
3fd3ab2d 1569 })
93e1258c 1570
40e87e9e
C
1571 const subtitleLanguage = []
1572 for (const caption of this.VideoCaptions) {
1573 subtitleLanguage.push({
1574 identifier: caption.language,
1575 name: VideoCaptionModel.getLanguageLabel(caption.language)
1576 })
1577 }
1578
3fd3ab2d
C
1579 return {
1580 type: 'Video' as 'Video',
1581 id: this.url,
1582 name: this.name,
093237cf 1583 duration: this.getActivityStreamDuration(),
3fd3ab2d
C
1584 uuid: this.uuid,
1585 tag,
1586 category,
1587 licence,
1588 language,
1589 views: this.views,
0a67e28b 1590 sensitive: this.nsfw,
2186386c
C
1591 waitTranscoding: this.waitTranscoding,
1592 state: this.state,
47564bbe 1593 commentsEnabled: this.commentsEnabled,
2922e048 1594 published: this.publishedAt.toISOString(),
3fd3ab2d
C
1595 updated: this.updatedAt.toISOString(),
1596 mediaType: 'text/markdown',
1597 content: this.getTruncatedDescription(),
2422c46b 1598 support: this.support,
40e87e9e 1599 subtitleLanguage,
3fd3ab2d
C
1600 icon: {
1601 type: 'Image',
1602 url: this.getThumbnailUrl(baseUrlHttp),
1603 mediaType: 'image/jpeg',
1604 width: THUMBNAILS_SIZE.width,
1605 height: THUMBNAILS_SIZE.height
1606 },
1607 url,
8fffe21a
C
1608 likes: getVideoLikesActivityPubUrl(this),
1609 dislikes: getVideoDislikesActivityPubUrl(this),
1610 shares: getVideoSharesActivityPubUrl(this),
1611 comments: getVideoCommentsActivityPubUrl(this),
50d6de9c 1612 attributedTo: [
2ccaeeb3
C
1613 {
1614 type: 'Person',
1615 id: this.VideoChannel.Account.Actor.url
fc27b17c
C
1616 },
1617 {
1618 type: 'Group',
1619 id: this.VideoChannel.Actor.url
50d6de9c
C
1620 }
1621 ]
3fd3ab2d
C
1622 }
1623 }
1624
1625 getTruncatedDescription () {
1626 if (!this.description) return null
93e1258c 1627
bffbebbe 1628 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
c73e83da 1629 return peertubeTruncate(this.description, maxLength)
93e1258c
C
1630 }
1631
81e504b3 1632 async optimizeOriginalVideofile () {
3fd3ab2d
C
1633 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1634 const newExtname = '.mp4'
1635 const inputVideoFile = this.getOriginalFile()
1636 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
3a6f351b 1637 const videoTranscodedPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
b769007f 1638
3fd3ab2d
C
1639 const transcodeOptions = {
1640 inputPath: videoInputPath,
3a6f351b 1641 outputPath: videoTranscodedPath
3fd3ab2d 1642 }
c46edbc2 1643
b0ef1782
C
1644 // Could be very long!
1645 await transcode(transcodeOptions)
c46edbc2 1646
b0ef1782 1647 try {
62689b94 1648 await remove(videoInputPath)
c46edbc2 1649
3fd3ab2d
C
1650 // Important to do this before getVideoFilename() to take in account the new file extension
1651 inputVideoFile.set('extname', newExtname)
e71bcc0f 1652
3a6f351b 1653 const videoOutputPath = this.getVideoFilePath(inputVideoFile)
62689b94
C
1654 await rename(videoTranscodedPath, videoOutputPath)
1655 const stats = await stat(videoOutputPath)
3a6f351b 1656 const fps = await getVideoFileFPS(videoOutputPath)
e71bcc0f 1657
3fd3ab2d 1658 inputVideoFile.set('size', stats.size)
3a6f351b 1659 inputVideoFile.set('fps', fps)
e71bcc0f 1660
3fd3ab2d
C
1661 await this.createTorrentAndSetInfoHash(inputVideoFile)
1662 await inputVideoFile.save()
fd45e8f4 1663
3fd3ab2d
C
1664 } catch (err) {
1665 // Auto destruction...
d5b7d911 1666 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
fd45e8f4 1667
3fd3ab2d
C
1668 throw err
1669 }
feb4bdfd
C
1670 }
1671
81e504b3 1672 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
3fd3ab2d
C
1673 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1674 const extname = '.mp4'
aaf61f38 1675
3fd3ab2d
C
1676 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1677 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
feb4bdfd 1678
3fd3ab2d
C
1679 const newVideoFile = new VideoFileModel({
1680 resolution,
1681 extname,
1682 size: 0,
1683 videoId: this.id
1684 })
1685 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
a041b171 1686
3fd3ab2d
C
1687 const transcodeOptions = {
1688 inputPath: videoInputPath,
1689 outputPath: videoOutputPath,
056aa7f2
C
1690 resolution,
1691 isPortraitMode
3fd3ab2d 1692 }
a041b171 1693
3fd3ab2d 1694 await transcode(transcodeOptions)
a041b171 1695
62689b94 1696 const stats = await stat(videoOutputPath)
3a6f351b 1697 const fps = await getVideoFileFPS(videoOutputPath)
d7d5611c 1698
3fd3ab2d 1699 newVideoFile.set('size', stats.size)
3a6f351b 1700 newVideoFile.set('fps', fps)
d7d5611c 1701
3fd3ab2d 1702 await this.createTorrentAndSetInfoHash(newVideoFile)
d7d5611c 1703
3fd3ab2d
C
1704 await newVideoFile.save()
1705
1706 this.VideoFiles.push(newVideoFile)
0d0e8dd0
C
1707 }
1708
0138af92 1709 async importVideoFile (inputFilePath: string) {
3a6f351b 1710 const { videoFileResolution } = await getVideoFileResolution(inputFilePath)
62689b94 1711 const { size } = await stat(inputFilePath)
3a6f351b
C
1712 const fps = await getVideoFileFPS(inputFilePath)
1713
0138af92 1714 let updatedVideoFile = new VideoFileModel({
3a6f351b 1715 resolution: videoFileResolution,
0138af92 1716 extname: extname(inputFilePath),
3a6f351b
C
1717 size,
1718 fps,
0138af92
FF
1719 videoId: this.id
1720 })
1721
0138af92 1722 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
0138af92 1723
28be8916
C
1724 if (currentVideoFile) {
1725 // Remove old file and old torrent
1726 await this.removeFile(currentVideoFile)
1727 await this.removeTorrent(currentVideoFile)
1728 // Remove the old video file from the array
1729 this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile)
1730
1731 // Update the database
1732 currentVideoFile.set('extname', updatedVideoFile.extname)
0138af92 1733 currentVideoFile.set('size', updatedVideoFile.size)
3a6f351b 1734 currentVideoFile.set('fps', updatedVideoFile.fps)
28be8916 1735
0138af92
FF
1736 updatedVideoFile = currentVideoFile
1737 }
1738
6ccdf3a2 1739 const outputPath = this.getVideoFilePath(updatedVideoFile)
62689b94 1740 await copy(inputFilePath, outputPath)
6ccdf3a2 1741
0138af92
FF
1742 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1743
1744 await updatedVideoFile.save()
1745
28be8916 1746 this.VideoFiles.push(updatedVideoFile)
0138af92
FF
1747 }
1748
056aa7f2 1749 getOriginalFileResolution () {
3fd3ab2d 1750 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
0d0e8dd0 1751
056aa7f2 1752 return getVideoFileResolution(originalFilePath)
3fd3ab2d 1753 }
0d0e8dd0 1754
3fd3ab2d
C
1755 getDescriptionPath () {
1756 return `/api/${API_VERSION}/videos/${this.uuid}/description`
feb4bdfd
C
1757 }
1758
3fd3ab2d
C
1759 removeThumbnail () {
1760 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
62689b94 1761 return remove(thumbnailPath)
ed31c059 1762 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
feb4bdfd
C
1763 }
1764
3fd3ab2d 1765 removePreview () {
ed31c059 1766 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
62689b94 1767 return remove(previewPath)
ed31c059 1768 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
7920c273
C
1769 }
1770
3fd3ab2d
C
1771 removeFile (videoFile: VideoFileModel) {
1772 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
62689b94 1773 return remove(filePath)
ed31c059 1774 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
feb4bdfd
C
1775 }
1776
3fd3ab2d
C
1777 removeTorrent (videoFile: VideoFileModel) {
1778 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
62689b94 1779 return remove(torrentPath)
ed31c059 1780 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
aaf61f38
C
1781 }
1782
093237cf
C
1783 getActivityStreamDuration () {
1784 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1785 return 'PT' + this.duration + 'S'
1786 }
1787
1297eb5d
C
1788 isOutdated () {
1789 if (this.isOwned()) return false
1790
1791 const now = Date.now()
1792 const createdAtTime = this.createdAt.getTime()
1793 const updatedAtTime = this.updatedAt.getTime()
1794
1795 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1796 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1797 }
1798
3fd3ab2d
C
1799 private getBaseUrls () {
1800 let baseUrlHttp
1801 let baseUrlWs
7920c273 1802
3fd3ab2d
C
1803 if (this.isOwned()) {
1804 baseUrlHttp = CONFIG.WEBSERVER.URL
1805 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1806 } else {
50d6de9c
C
1807 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1808 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
6fcd19ba 1809 }
aaf61f38 1810
3fd3ab2d 1811 return { baseUrlHttp, baseUrlWs }
15d4ee04 1812 }
a96aed15 1813
3fd3ab2d
C
1814 private getThumbnailUrl (baseUrlHttp: string) {
1815 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
a96aed15
C
1816 }
1817
3fd3ab2d
C
1818 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1819 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1820 }
e4f97bab 1821
02756fbd
C
1822 private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1823 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1824 }
1825
3fd3ab2d
C
1826 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1827 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1828 }
a96aed15 1829
02756fbd
C
1830 private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1831 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1832 }
1833
3fd3ab2d
C
1834 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1835 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1836 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1837 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1838
1839 const magnetHash = {
1840 xs,
1841 announce,
1842 urlList,
1843 infoHash: videoFile.infoHash,
1844 name: this.name
1845 }
a96aed15 1846
3fd3ab2d 1847 return magnetUtil.encode(magnetHash)
a96aed15 1848 }
a96aed15 1849}