]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video/video.ts
Upgrade server dependencies
[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'
65fcc311 5import { join } from 'path'
e02643f3 6import * as Sequelize from 'sequelize'
3fd3ab2d 7import {
4ba3b8ea
C
8 AfterDestroy,
9 AllowNull,
10 BeforeDestroy,
11 BelongsTo,
12 BelongsToMany,
13 Column,
14 CreatedAt,
15 DataType,
16 Default,
17 ForeignKey,
18 HasMany,
19 IFindOptions,
20 Is,
21 IsInt,
22 IsUUID,
23 Min,
24 Model,
25 Scopes,
26 Table,
27 UpdatedAt
3fd3ab2d 28} from 'sequelize-typescript'
571389d4 29import { VideoPrivacy, VideoResolution } from '../../../shared'
3fd3ab2d 30import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
a8462c8e 31import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos'
066e94c5 32import { VideoFilter } from '../../../shared/models/videos/video-query.type'
da854ddd 33import { activityPubCollection } from '../../helpers/activitypub'
c73e83da
C
34import {
35 createTorrentPromise, peertubeTruncate, renamePromise, statPromise, unlinkPromise,
36 writeFilePromise
37} from '../../helpers/core-utils'
da854ddd 38import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
47564bbe 39import { isBooleanValid } from '../../helpers/custom-validators/misc'
3fd3ab2d 40import {
4ba3b8ea
C
41 isVideoCategoryValid,
42 isVideoDescriptionValid,
43 isVideoDurationValid,
44 isVideoLanguageValid,
45 isVideoLicenceValid,
46 isVideoNameValid,
b64c950a
C
47 isVideoPrivacyValid,
48 isVideoSupportValid
3fd3ab2d 49} from '../../helpers/custom-validators/videos'
056aa7f2 50import { generateImageFromVideoFile, getVideoFileResolution, transcode } from '../../helpers/ffmpeg-utils'
da854ddd 51import { logger } from '../../helpers/logger'
f05a1c30 52import { getServerActor } from '../../helpers/utils'
65fcc311 53import {
4ba3b8ea
C
54 API_VERSION,
55 CONFIG,
56 CONSTRAINTS_FIELDS,
57 PREVIEWS_SIZE,
58 REMOTE_SCHEME,
59 STATIC_PATHS,
60 THUMBNAILS_SIZE,
61 VIDEO_CATEGORIES,
62 VIDEO_LANGUAGES,
63 VIDEO_LICENCES,
64 VIDEO_PRIVACIES
3fd3ab2d 65} from '../../initializers'
46531a0a
C
66import {
67 getVideoCommentsActivityPubUrl,
68 getVideoDislikesActivityPubUrl,
69 getVideoLikesActivityPubUrl,
70 getVideoSharesActivityPubUrl
71} from '../../lib/activitypub'
50d6de9c 72import { sendDeleteVideo } from '../../lib/activitypub/send'
3fd3ab2d
C
73import { AccountModel } from '../account/account'
74import { AccountVideoRateModel } from '../account/account-video-rate'
50d6de9c 75import { ActorModel } from '../activitypub/actor'
b6a4fd6b 76import { AvatarModel } from '../avatar/avatar'
3fd3ab2d
C
77import { ServerModel } from '../server/server'
78import { getSort, throwIfNotValid } from '../utils'
79import { TagModel } from './tag'
80import { VideoAbuseModel } from './video-abuse'
81import { VideoChannelModel } from './video-channel'
da854ddd 82import { VideoCommentModel } from './video-comment'
3fd3ab2d
C
83import { VideoFileModel } from './video-file'
84import { VideoShareModel } from './video-share'
85import { VideoTagModel } from './video-tag'
86
d48ff09d 87enum ScopeNames {
50d6de9c 88 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
4cb6d457 89 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
d48ff09d
C
90 WITH_TAGS = 'WITH_TAGS',
91 WITH_FILES = 'WITH_FILES',
92 WITH_SHARES = 'WITH_SHARES',
da854ddd
C
93 WITH_RATES = 'WITH_RATES',
94 WITH_COMMENTS = 'WITH_COMMENTS'
d48ff09d
C
95}
96
97@Scopes({
066e94c5 98 [ScopeNames.AVAILABLE_FOR_LIST]: (actorId: number, filter?: VideoFilter) => ({
d48ff09d
C
99 where: {
100 id: {
101 [Sequelize.Op.notIn]: Sequelize.literal(
102 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
2d9ab590
C
103 ),
104 [ Sequelize.Op.in ]: Sequelize.literal(
105 '(' +
106 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
107 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
108 'WHERE "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
109 ' UNION ' +
110 'SELECT "video"."id" AS "id" FROM "video" ' +
111 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
112 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
113 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
114 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
115 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
116 ')'
d48ff09d 117 )
50d6de9c 118 },
2d9ab590 119 privacy: VideoPrivacy.PUBLIC
f05a1c30 120 },
4cb6d457
C
121 include: [
122 {
f05a1c30
C
123 attributes: [ 'name', 'description' ],
124 model: VideoChannelModel.unscoped(),
4cb6d457
C
125 required: true,
126 include: [
127 {
128 attributes: [ 'name' ],
f05a1c30 129 model: AccountModel.unscoped(),
4cb6d457
C
130 required: true,
131 include: [
132 {
b64c950a 133 attributes: [ 'preferredUsername', 'url', 'serverId' ],
f05a1c30 134 model: ActorModel.unscoped(),
4cb6d457 135 required: true,
066e94c5 136 where: VideoModel.buildActorWhereWithFilter(filter),
4cb6d457
C
137 include: [
138 {
f05a1c30 139 attributes: [ 'host' ],
b64c950a
C
140 model: ServerModel.unscoped(),
141 required: false
142 },
143 {
144 model: AvatarModel.unscoped(),
145 required: false
4cb6d457
C
146 }
147 ]
148 }
149 ]
150 }
151 ]
152 }
153 ]
f05a1c30 154 }),
4cb6d457 155 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
d48ff09d
C
156 include: [
157 {
6120941f 158 model: () => VideoChannelModel.unscoped(),
d48ff09d
C
159 required: true,
160 include: [
6120941f
C
161 {
162 attributes: {
163 exclude: [ 'privateKey', 'publicKey' ]
164 },
3e500247
C
165 model: () => ActorModel.unscoped(),
166 required: true,
167 include: [
168 {
169 attributes: [ 'host' ],
170 model: () => ServerModel.unscoped(),
171 required: false
172 }
173 ]
6120941f 174 },
d48ff09d 175 {
3e500247 176 model: () => AccountModel.unscoped(),
d48ff09d
C
177 required: true,
178 include: [
179 {
3e500247 180 model: () => ActorModel.unscoped(),
6120941f
C
181 attributes: {
182 exclude: [ 'privateKey', 'publicKey' ]
183 },
50d6de9c
C
184 required: true,
185 include: [
186 {
3e500247
C
187 attributes: [ 'host' ],
188 model: () => ServerModel.unscoped(),
50d6de9c 189 required: false
b6a4fd6b
C
190 },
191 {
192 model: () => AvatarModel.unscoped(),
193 required: false
50d6de9c
C
194 }
195 ]
d48ff09d
C
196 }
197 ]
198 }
199 ]
200 }
201 ]
202 },
203 [ScopeNames.WITH_TAGS]: {
204 include: [ () => TagModel ]
205 },
206 [ScopeNames.WITH_FILES]: {
207 include: [
208 {
e53f952e 209 model: () => VideoFileModel.unscoped(),
d48ff09d
C
210 required: true
211 }
212 ]
213 },
214 [ScopeNames.WITH_SHARES]: {
215 include: [
216 {
e53f952e 217 model: () => VideoShareModel.unscoped()
d48ff09d
C
218 }
219 ]
220 },
221 [ScopeNames.WITH_RATES]: {
222 include: [
223 {
224 model: () => AccountVideoRateModel,
e53f952e
C
225 include: [
226 {
227 model: () => AccountModel.unscoped(),
228 required: true,
229 include: [
230 {
231 attributes: [ 'url' ],
232 model: () => ActorModel.unscoped()
233 }
234 ]
235 }
236 ]
d48ff09d
C
237 }
238 ]
da854ddd
C
239 },
240 [ScopeNames.WITH_COMMENTS]: {
241 include: [
242 {
e53f952e 243 model: () => VideoCommentModel.unscoped()
da854ddd
C
244 }
245 ]
d48ff09d
C
246 }
247})
3fd3ab2d
C
248@Table({
249 tableName: 'video',
250 indexes: [
feb4bdfd 251 {
3fd3ab2d 252 fields: [ 'name' ]
feb4bdfd
C
253 },
254 {
3fd3ab2d
C
255 fields: [ 'createdAt' ]
256 },
257 {
258 fields: [ 'duration' ]
259 },
260 {
261 fields: [ 'views' ]
262 },
263 {
264 fields: [ 'likes' ]
265 },
266 {
267 fields: [ 'uuid' ]
268 },
269 {
270 fields: [ 'channelId' ]
4cb6d457
C
271 },
272 {
273 fields: [ 'id', 'privacy' ]
2ccaeeb3
C
274 },
275 {
276 fields: [ 'url'],
277 unique: true
feb4bdfd 278 }
e02643f3 279 ]
3fd3ab2d
C
280})
281export class VideoModel extends Model<VideoModel> {
282
283 @AllowNull(false)
284 @Default(DataType.UUIDV4)
285 @IsUUID(4)
286 @Column(DataType.UUID)
287 uuid: string
288
289 @AllowNull(false)
290 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
291 @Column
292 name: string
293
294 @AllowNull(true)
295 @Default(null)
296 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
297 @Column
298 category: number
299
300 @AllowNull(true)
301 @Default(null)
302 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
303 @Column
304 licence: number
305
306 @AllowNull(true)
307 @Default(null)
308 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
309 @Column
310 language: number
311
312 @AllowNull(false)
313 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
314 @Column
315 privacy: number
316
317 @AllowNull(false)
47564bbe 318 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
3fd3ab2d
C
319 @Column
320 nsfw: boolean
321
322 @AllowNull(true)
323 @Default(null)
324 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
325 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
326 description: string
327
2422c46b
C
328 @AllowNull(true)
329 @Default(null)
330 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
331 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
332 support: string
333
3fd3ab2d
C
334 @AllowNull(false)
335 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
336 @Column
337 duration: number
338
339 @AllowNull(false)
340 @Default(0)
341 @IsInt
342 @Min(0)
343 @Column
344 views: number
345
346 @AllowNull(false)
347 @Default(0)
348 @IsInt
349 @Min(0)
350 @Column
351 likes: number
352
353 @AllowNull(false)
354 @Default(0)
355 @IsInt
356 @Min(0)
357 @Column
358 dislikes: number
359
360 @AllowNull(false)
361 @Column
362 remote: boolean
363
364 @AllowNull(false)
365 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
366 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
367 url: string
368
47564bbe
C
369 @AllowNull(false)
370 @Column
371 commentsEnabled: boolean
372
3fd3ab2d
C
373 @CreatedAt
374 createdAt: Date
375
376 @UpdatedAt
377 updatedAt: Date
378
2922e048
JLB
379 @AllowNull(false)
380 @Default(Sequelize.NOW)
381 @Column
382 publishedAt: Date
383
3fd3ab2d
C
384 @ForeignKey(() => VideoChannelModel)
385 @Column
386 channelId: number
387
388 @BelongsTo(() => VideoChannelModel, {
feb4bdfd 389 foreignKey: {
50d6de9c 390 allowNull: true
feb4bdfd
C
391 },
392 onDelete: 'cascade'
393 })
3fd3ab2d 394 VideoChannel: VideoChannelModel
7920c273 395
3fd3ab2d 396 @BelongsToMany(() => TagModel, {
7920c273 397 foreignKey: 'videoId',
3fd3ab2d
C
398 through: () => VideoTagModel,
399 onDelete: 'CASCADE'
7920c273 400 })
3fd3ab2d 401 Tags: TagModel[]
55fa55a9 402
3fd3ab2d 403 @HasMany(() => VideoAbuseModel, {
55fa55a9
C
404 foreignKey: {
405 name: 'videoId',
406 allowNull: false
407 },
408 onDelete: 'cascade'
409 })
3fd3ab2d 410 VideoAbuses: VideoAbuseModel[]
93e1258c 411
3fd3ab2d 412 @HasMany(() => VideoFileModel, {
93e1258c
C
413 foreignKey: {
414 name: 'videoId',
415 allowNull: false
416 },
417 onDelete: 'cascade'
418 })
3fd3ab2d 419 VideoFiles: VideoFileModel[]
e71bcc0f 420
3fd3ab2d 421 @HasMany(() => VideoShareModel, {
e71bcc0f
C
422 foreignKey: {
423 name: 'videoId',
424 allowNull: false
425 },
426 onDelete: 'cascade'
427 })
3fd3ab2d 428 VideoShares: VideoShareModel[]
16b90975 429
3fd3ab2d 430 @HasMany(() => AccountVideoRateModel, {
16b90975
C
431 foreignKey: {
432 name: 'videoId',
433 allowNull: false
434 },
435 onDelete: 'cascade'
436 })
3fd3ab2d 437 AccountVideoRates: AccountVideoRateModel[]
f285faa0 438
da854ddd
C
439 @HasMany(() => VideoCommentModel, {
440 foreignKey: {
441 name: 'videoId',
442 allowNull: false
443 },
f05a1c30
C
444 onDelete: 'cascade',
445 hooks: true
da854ddd
C
446 })
447 VideoComments: VideoCommentModel[]
448
f05a1c30
C
449 @BeforeDestroy
450 static async sendDelete (instance: VideoModel, options) {
451 if (instance.isOwned()) {
452 if (!instance.VideoChannel) {
453 instance.VideoChannel = await instance.$get('VideoChannel', {
454 include: [
455 {
456 model: AccountModel,
457 include: [ ActorModel ]
458 }
459 ],
460 transaction: options.transaction
461 }) as VideoChannelModel
462 }
463
464 logger.debug('Sending delete of video %s.', instance.url)
465
466 return sendDeleteVideo(instance, options.transaction)
467 }
468
469 return undefined
470 }
471
3fd3ab2d 472 @AfterDestroy
f05a1c30
C
473 static async removeFilesAndSendDelete (instance: VideoModel) {
474 const tasks: Promise<any>[] = []
f285faa0 475
f05a1c30 476 tasks.push(instance.removeThumbnail())
93e1258c 477
3fd3ab2d 478 if (instance.isOwned()) {
f05a1c30
C
479 if (!Array.isArray(instance.VideoFiles)) {
480 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
481 }
482
483 tasks.push(instance.removePreview())
40298b02 484
3fd3ab2d
C
485 // Remove physical files and torrents
486 instance.VideoFiles.forEach(file => {
487 tasks.push(instance.removeFile(file))
488 tasks.push(instance.removeTorrent(file))
489 })
490 }
40298b02 491
3fd3ab2d
C
492 return Promise.all(tasks)
493 .catch(err => {
d5b7d911 494 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
3fd3ab2d
C
495 })
496 }
f285faa0 497
3fd3ab2d 498 static list () {
d48ff09d 499 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
3fd3ab2d 500 }
f285faa0 501
50d6de9c 502 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
3fd3ab2d
C
503 function getRawQuery (select: string) {
504 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
505 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
50d6de9c
C
506 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
507 'WHERE "Account"."actorId" = ' + actorId
3fd3ab2d
C
508 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
509 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
50d6de9c 510 'WHERE "VideoShare"."actorId" = ' + actorId
558d7c23 511
3fd3ab2d
C
512 return `(${queryVideo}) UNION (${queryVideoShare})`
513 }
aaf61f38 514
3fd3ab2d
C
515 const rawQuery = getRawQuery('"Video"."id"')
516 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
517
518 const query = {
519 distinct: true,
520 offset: start,
521 limit: count,
3bb6c526 522 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
3fd3ab2d
C
523 where: {
524 id: {
525 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
3c75ce12
C
526 },
527 [Sequelize.Op.or]: [
528 { privacy: VideoPrivacy.PUBLIC },
529 { privacy: VideoPrivacy.UNLISTED }
530 ]
3fd3ab2d
C
531 },
532 include: [
533 {
1d230c44 534 attributes: [ 'id', 'url' ],
2c897999 535 model: VideoShareModel.unscoped(),
3fd3ab2d
C
536 required: false,
537 where: {
538 [Sequelize.Op.and]: [
539 {
540 id: {
541 [Sequelize.Op.not]: null
542 }
543 },
544 {
50d6de9c 545 actorId
3fd3ab2d
C
546 }
547 ]
548 },
50d6de9c
C
549 include: [
550 {
2c897999
C
551 attributes: [ 'id', 'url' ],
552 model: ActorModel.unscoped()
50d6de9c
C
553 }
554 ]
3fd3ab2d
C
555 },
556 {
2c897999 557 model: VideoChannelModel.unscoped(),
3fd3ab2d
C
558 required: true,
559 include: [
560 {
2c897999
C
561 attributes: [ 'name' ],
562 model: AccountModel.unscoped(),
563 required: true,
564 include: [
565 {
566 attributes: [ 'id', 'url' ],
567 model: ActorModel.unscoped(),
568 required: true
569 }
570 ]
571 },
572 {
573 attributes: [ 'id', 'url' ],
574 model: ActorModel.unscoped(),
3fd3ab2d
C
575 required: true
576 }
577 ]
578 },
579 {
2c897999 580 attributes: [ 'type' ],
3fd3ab2d 581 model: AccountVideoRateModel,
2c897999
C
582 required: false,
583 include: [
584 {
585 attributes: [ 'id' ],
586 model: AccountModel.unscoped(),
587 include: [
588 {
589 attributes: [ 'url' ],
590 model: ActorModel.unscoped(),
591 include: [
592 {
593 attributes: [ 'host' ],
594 model: ServerModel,
595 required: false
596 }
597 ]
598 }
599 ]
600 }
601 ]
602 },
603 {
604 attributes: [ 'url' ],
605 model: VideoCommentModel,
606 required: false
3fd3ab2d
C
607 },
608 VideoFileModel,
2c897999 609 TagModel
3fd3ab2d
C
610 ]
611 }
164174a6 612
3fd3ab2d
C
613 return Bluebird.all([
614 // FIXME: typing issue
615 VideoModel.findAll(query as any),
616 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
617 ]).then(([ rows, totals ]) => {
618 // totals: totalVideos + totalVideoShares
619 let totalVideos = 0
620 let totalVideoShares = 0
621 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
622 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
623
624 const total = totalVideos + totalVideoShares
625 return {
626 data: rows,
627 total: total
628 }
629 })
630 }
93e1258c 631
3fd3ab2d
C
632 static listUserVideosForApi (userId: number, start: number, count: number, sort: string) {
633 const query = {
3fd3ab2d
C
634 offset: start,
635 limit: count,
3bb6c526 636 order: getSort(sort),
3fd3ab2d
C
637 include: [
638 {
639 model: VideoChannelModel,
640 required: true,
641 include: [
642 {
643 model: AccountModel,
644 where: {
645 userId
646 },
647 required: true
648 }
649 ]
d48ff09d 650 }
3fd3ab2d
C
651 ]
652 }
d8755eed 653
3fd3ab2d
C
654 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
655 return {
656 data: rows,
657 total: count
658 }
659 })
660 }
93e1258c 661
066e94c5 662 static async listForApi (start: number, count: number, sort: string, filter?: VideoFilter) {
3fd3ab2d 663 const query = {
3fd3ab2d
C
664 offset: start,
665 limit: count,
6ff9c676 666 order: getSort(sort)
3fd3ab2d 667 }
93e1258c 668
f05a1c30
C
669 const serverActor = await getServerActor()
670
066e94c5 671 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id, filter ] })
d48ff09d
C
672 .findAndCountAll(query)
673 .then(({ rows, count }) => {
674 return {
675 data: rows,
676 total: count
677 }
678 })
93e1258c
C
679 }
680
f05a1c30
C
681 static async searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) {
682 const query: IFindOptions<VideoModel> = {
683 offset: start,
684 limit: count,
3bb6c526 685 order: getSort(sort),
f05a1c30 686 where: {
3e0c9ff5
C
687 [Sequelize.Op.or]: [
688 {
689 name: {
690 [ Sequelize.Op.iLike ]: '%' + value + '%'
691 }
692 },
693 {
694 preferredUsername: Sequelize.where(Sequelize.col('preferredUsername'), {
695 [ Sequelize.Op.iLike ]: '%' + value + '%'
696 })
697 },
698 {
699 host: Sequelize.where(Sequelize.col('host'), {
700 [ Sequelize.Op.iLike ]: '%' + value + '%'
701 })
702 }
703 ]
f05a1c30
C
704 }
705 }
706
707 const serverActor = await getServerActor()
708
709 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
710 .findAndCountAll(query).then(({ rows, count }) => {
711 return {
712 data: rows,
713 total: count
714 }
715 })
716 }
717
3fd3ab2d
C
718 static load (id: number) {
719 return VideoModel.findById(id)
720 }
fdbda9e3 721
3fd3ab2d
C
722 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
723 const query: IFindOptions<VideoModel> = {
724 where: {
725 url
d48ff09d 726 }
3fd3ab2d 727 }
d8755eed 728
3fd3ab2d 729 if (t !== undefined) query.transaction = t
d8755eed 730
4cb6d457 731 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
3fd3ab2d 732 }
d8755eed 733
2ccaeeb3 734 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
3fd3ab2d
C
735 const query: IFindOptions<VideoModel> = {
736 where: {
737 [Sequelize.Op.or]: [
738 { uuid },
739 { url }
740 ]
d48ff09d 741 }
3fd3ab2d 742 }
feb4bdfd 743
3fd3ab2d 744 if (t !== undefined) query.transaction = t
feb4bdfd 745
2ccaeeb3 746 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
72c7248b
C
747 }
748
3fd3ab2d
C
749 static loadAndPopulateAccountAndServerAndTags (id: number) {
750 const options = {
d48ff09d 751 order: [ [ 'Tags', 'name', 'ASC' ] ]
3fd3ab2d 752 }
72c7248b 753
d48ff09d 754 return VideoModel
4cb6d457 755 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
d48ff09d 756 .findById(id, options)
3fd3ab2d 757 }
72c7248b 758
8fa5653a
C
759 static loadByUUID (uuid: string) {
760 const options = {
761 where: {
762 uuid
763 }
764 }
765
766 return VideoModel
767 .scope([ ScopeNames.WITH_FILES ])
768 .findOne(options)
769 }
770
3fd3ab2d
C
771 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
772 const options = {
773 order: [ [ 'Tags', 'name', 'ASC' ] ],
774 where: {
775 uuid
d48ff09d 776 }
3fd3ab2d 777 }
fd45e8f4 778
d48ff09d 779 return VideoModel
4cb6d457 780 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
da854ddd
C
781 .findOne(options)
782 }
783
784 static loadAndPopulateAll (id: number) {
785 const options = {
786 order: [ [ 'Tags', 'name', 'ASC' ] ],
787 where: {
788 id
789 }
790 }
791
792 return VideoModel
793 .scope([
794 ScopeNames.WITH_RATES,
795 ScopeNames.WITH_SHARES,
796 ScopeNames.WITH_TAGS,
797 ScopeNames.WITH_FILES,
4cb6d457 798 ScopeNames.WITH_ACCOUNT_DETAILS,
da854ddd
C
799 ScopeNames.WITH_COMMENTS
800 ])
d48ff09d 801 .findOne(options)
aaf61f38
C
802 }
803
09cababd
C
804 static async getStats () {
805 const totalLocalVideos = await VideoModel.count({
806 where: {
807 remote: false
808 }
809 })
810 const totalVideos = await VideoModel.count()
811
812 let totalLocalVideoViews = await VideoModel.sum('views', {
813 where: {
814 remote: false
815 }
816 })
817 // Sequelize could return null...
818 if (!totalLocalVideoViews) totalLocalVideoViews = 0
819
820 return {
821 totalLocalVideos,
822 totalLocalVideoViews,
823 totalVideos
824 }
825 }
826
066e94c5
C
827 private static buildActorWhereWithFilter (filter?: VideoFilter) {
828 if (filter && filter === 'local') {
829 return {
830 serverId: null
831 }
832 }
833
834 return {}
835 }
836
ae5a3dd6
C
837 private static getCategoryLabel (id: number) {
838 let categoryLabel = VIDEO_CATEGORIES[id]
839 if (!categoryLabel) categoryLabel = 'Misc'
840
841 return categoryLabel
842 }
843
844 private static getLicenceLabel (id: number) {
845 let licenceLabel = VIDEO_LICENCES[id]
846 if (!licenceLabel) licenceLabel = 'Unknown'
847
848 return licenceLabel
849 }
850
851 private static getLanguageLabel (id: number) {
852 let languageLabel = VIDEO_LANGUAGES[id]
853 if (!languageLabel) languageLabel = 'Unknown'
854
855 return languageLabel
856 }
857
3fd3ab2d
C
858 getOriginalFile () {
859 if (Array.isArray(this.VideoFiles) === false) return undefined
aaf61f38 860
3fd3ab2d
C
861 // The original file is the file that have the higher resolution
862 return maxBy(this.VideoFiles, file => file.resolution)
e4f97bab 863 }
aaf61f38 864
3fd3ab2d
C
865 getVideoFilename (videoFile: VideoFileModel) {
866 return this.uuid + '-' + videoFile.resolution + videoFile.extname
867 }
165cdc75 868
3fd3ab2d
C
869 getThumbnailName () {
870 // We always have a copy of the thumbnail
871 const extension = '.jpg'
872 return this.uuid + extension
7b1f49de
C
873 }
874
3fd3ab2d
C
875 getPreviewName () {
876 const extension = '.jpg'
877 return this.uuid + extension
878 }
7b1f49de 879
3fd3ab2d
C
880 getTorrentFileName (videoFile: VideoFileModel) {
881 const extension = '.torrent'
882 return this.uuid + '-' + videoFile.resolution + extension
883 }
8e7f08b5 884
3fd3ab2d
C
885 isOwned () {
886 return this.remote === false
9567011b
C
887 }
888
3fd3ab2d 889 createPreview (videoFile: VideoFileModel) {
3fd3ab2d
C
890 return generateImageFromVideoFile(
891 this.getVideoFilePath(videoFile),
892 CONFIG.STORAGE.PREVIEWS_DIR,
893 this.getPreviewName(),
26670720 894 PREVIEWS_SIZE
3fd3ab2d
C
895 )
896 }
9567011b 897
3fd3ab2d 898 createThumbnail (videoFile: VideoFileModel) {
3fd3ab2d
C
899 return generateImageFromVideoFile(
900 this.getVideoFilePath(videoFile),
901 CONFIG.STORAGE.THUMBNAILS_DIR,
902 this.getThumbnailName(),
26670720 903 THUMBNAILS_SIZE
3fd3ab2d 904 )
14d3270f
C
905 }
906
3fd3ab2d
C
907 getVideoFilePath (videoFile: VideoFileModel) {
908 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
909 }
14d3270f 910
3fd3ab2d
C
911 createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) {
912 const options = {
913 announceList: [
0edf0581
C
914 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
915 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
3fd3ab2d
C
916 ],
917 urlList: [
918 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
919 ]
920 }
14d3270f 921
3fd3ab2d 922 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
e4f97bab 923
3fd3ab2d
C
924 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
925 logger.info('Creating torrent %s.', filePath)
e4f97bab 926
3fd3ab2d 927 await writeFilePromise(filePath, torrent)
e4f97bab 928
3fd3ab2d
C
929 const parsedTorrent = parseTorrent(torrent)
930 videoFile.infoHash = parsedTorrent.infoHash
931 }
e4f97bab 932
3fd3ab2d
C
933 getEmbedPath () {
934 return '/videos/embed/' + this.uuid
935 }
e4f97bab 936
3fd3ab2d
C
937 getThumbnailPath () {
938 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
e4f97bab 939 }
227d02fe 940
3fd3ab2d
C
941 getPreviewPath () {
942 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
943 }
40298b02 944
2422c46b 945 toFormattedJSON (): Video {
b64c950a 946 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
14d3270f 947
3fd3ab2d
C
948 return {
949 id: this.id,
950 uuid: this.uuid,
951 name: this.name,
ae5a3dd6
C
952 category: {
953 id: this.category,
954 label: VideoModel.getCategoryLabel(this.category)
955 },
956 licence: {
957 id: this.licence,
958 label: VideoModel.getLicenceLabel(this.licence)
959 },
960 language: {
961 id: this.language,
962 label: VideoModel.getLanguageLabel(this.language)
963 },
3fd3ab2d
C
964 nsfw: this.nsfw,
965 description: this.getTruncatedDescription(),
3fd3ab2d 966 isLocal: this.isOwned(),
3fd3ab2d
C
967 duration: this.duration,
968 views: this.views,
969 likes: this.likes,
970 dislikes: this.dislikes,
3fd3ab2d
C
971 thumbnailPath: this.getThumbnailPath(),
972 previewPath: this.getPreviewPath(),
973 embedPath: this.getEmbedPath(),
974 createdAt: this.createdAt,
b64c950a 975 updatedAt: this.updatedAt,
2922e048 976 publishedAt: this.publishedAt,
b64c950a
C
977 account: {
978 name: formattedAccount.name,
979 displayName: formattedAccount.displayName,
980 url: formattedAccount.url,
981 host: formattedAccount.host,
982 avatar: formattedAccount.avatar
983 }
2422c46b 984 }
14d3270f 985 }
14d3270f 986
2422c46b 987 toFormattedDetailsJSON (): VideoDetails {
3fd3ab2d 988 const formattedJson = this.toFormattedJSON()
e4f97bab 989
3fd3ab2d
C
990 // Maybe our server is not up to date and there are new privacy settings since our version
991 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
992 if (!privacyLabel) privacyLabel = 'Unknown'
e4f97bab 993
3fd3ab2d 994 const detailsJson = {
ae5a3dd6
C
995 privacy: {
996 id: this.privacy,
997 label: privacyLabel
998 },
2422c46b 999 support: this.support,
3fd3ab2d
C
1000 descriptionPath: this.getDescriptionPath(),
1001 channel: this.VideoChannel.toFormattedJSON(),
1002 account: this.VideoChannel.Account.toFormattedJSON(),
ee28cdf1 1003 tags: map(this.Tags, 'name'),
47564bbe 1004 commentsEnabled: this.commentsEnabled,
3fd3ab2d
C
1005 files: []
1006 }
e4f97bab 1007
3fd3ab2d
C
1008 // Format and sort video files
1009 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1010 detailsJson.files = this.VideoFiles
1011 .map(videoFile => {
1012 let resolutionLabel = videoFile.resolution + 'p'
1013
1014 return {
ae5a3dd6
C
1015 resolution: {
1016 id: videoFile.resolution,
1017 label: resolutionLabel
1018 },
3fd3ab2d
C
1019 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1020 size: videoFile.size,
1021 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1022 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
a8462c8e 1023 } as VideoFile
3fd3ab2d
C
1024 })
1025 .sort((a, b) => {
552586ed
C
1026 if (a.resolution.id < b.resolution.id) return 1
1027 if (a.resolution.id === b.resolution.id) return 0
3fd3ab2d
C
1028 return -1
1029 })
1030
2422c46b 1031 return Object.assign(formattedJson, detailsJson)
3fd3ab2d 1032 }
e4f97bab 1033
3fd3ab2d
C
1034 toActivityPubObject (): VideoTorrentObject {
1035 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1036 if (!this.Tags) this.Tags = []
e4f97bab 1037
3fd3ab2d
C
1038 const tag = this.Tags.map(t => ({
1039 type: 'Hashtag' as 'Hashtag',
1040 name: t.name
1041 }))
40298b02 1042
3fd3ab2d
C
1043 let language
1044 if (this.language) {
1045 language = {
5d00a3d7 1046 identifier: this.language + '',
ae5a3dd6 1047 name: VideoModel.getLanguageLabel(this.language)
3fd3ab2d
C
1048 }
1049 }
40298b02 1050
3fd3ab2d
C
1051 let category
1052 if (this.category) {
1053 category = {
1054 identifier: this.category + '',
ae5a3dd6 1055 name: VideoModel.getCategoryLabel(this.category)
3fd3ab2d
C
1056 }
1057 }
40298b02 1058
3fd3ab2d
C
1059 let licence
1060 if (this.licence) {
1061 licence = {
1062 identifier: this.licence + '',
ae5a3dd6 1063 name: VideoModel.getLicenceLabel(this.licence)
3fd3ab2d
C
1064 }
1065 }
9567011b 1066
3fd3ab2d
C
1067 let likesObject
1068 let dislikesObject
e4f97bab 1069
3fd3ab2d 1070 if (Array.isArray(this.AccountVideoRates)) {
46531a0a
C
1071 const res = this.toRatesActivityPubObjects()
1072 likesObject = res.likesObject
1073 dislikesObject = res.dislikesObject
3fd3ab2d 1074 }
e4f97bab 1075
3fd3ab2d
C
1076 let sharesObject
1077 if (Array.isArray(this.VideoShares)) {
46531a0a 1078 sharesObject = this.toAnnouncesActivityPubObject()
3fd3ab2d 1079 }
93e1258c 1080
da854ddd
C
1081 let commentsObject
1082 if (Array.isArray(this.VideoComments)) {
46531a0a 1083 commentsObject = this.toCommentsActivityPubObject()
da854ddd
C
1084 }
1085
3fd3ab2d
C
1086 const url = []
1087 for (const file of this.VideoFiles) {
1088 url.push({
1089 type: 'Link',
1090 mimeType: 'video/' + file.extname.replace('.', ''),
9fb3abfd 1091 href: this.getVideoFileUrl(file, baseUrlHttp),
3fd3ab2d
C
1092 width: file.resolution,
1093 size: file.size
1094 })
1095
1096 url.push({
1097 type: 'Link',
1098 mimeType: 'application/x-bittorrent',
9fb3abfd 1099 href: this.getTorrentUrl(file, baseUrlHttp),
3fd3ab2d
C
1100 width: file.resolution
1101 })
1102
1103 url.push({
1104 type: 'Link',
1105 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
9fb3abfd 1106 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
3fd3ab2d
C
1107 width: file.resolution
1108 })
1109 }
93e1258c 1110
3fd3ab2d
C
1111 // Add video url too
1112 url.push({
1113 type: 'Link',
1114 mimeType: 'text/html',
9fb3abfd 1115 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
3fd3ab2d 1116 })
93e1258c 1117
3fd3ab2d
C
1118 return {
1119 type: 'Video' as 'Video',
1120 id: this.url,
1121 name: this.name,
093237cf 1122 duration: this.getActivityStreamDuration(),
3fd3ab2d
C
1123 uuid: this.uuid,
1124 tag,
1125 category,
1126 licence,
1127 language,
1128 views: this.views,
0a67e28b 1129 sensitive: this.nsfw,
47564bbe 1130 commentsEnabled: this.commentsEnabled,
2922e048 1131 published: this.publishedAt.toISOString(),
3fd3ab2d
C
1132 updated: this.updatedAt.toISOString(),
1133 mediaType: 'text/markdown',
1134 content: this.getTruncatedDescription(),
2422c46b 1135 support: this.support,
3fd3ab2d
C
1136 icon: {
1137 type: 'Image',
1138 url: this.getThumbnailUrl(baseUrlHttp),
1139 mediaType: 'image/jpeg',
1140 width: THUMBNAILS_SIZE.width,
1141 height: THUMBNAILS_SIZE.height
1142 },
1143 url,
1144 likes: likesObject,
1145 dislikes: dislikesObject,
50d6de9c 1146 shares: sharesObject,
da854ddd 1147 comments: commentsObject,
50d6de9c 1148 attributedTo: [
2ccaeeb3
C
1149 {
1150 type: 'Person',
1151 id: this.VideoChannel.Account.Actor.url
fc27b17c
C
1152 },
1153 {
1154 type: 'Group',
1155 id: this.VideoChannel.Actor.url
50d6de9c
C
1156 }
1157 ]
3fd3ab2d
C
1158 }
1159 }
1160
46531a0a
C
1161 toAnnouncesActivityPubObject () {
1162 const shares: string[] = []
1163
1164 for (const videoShare of this.VideoShares) {
1165 shares.push(videoShare.url)
1166 }
1167
1168 return activityPubCollection(getVideoSharesActivityPubUrl(this), shares)
1169 }
1170
1171 toCommentsActivityPubObject () {
1172 const comments: string[] = []
1173
1174 for (const videoComment of this.VideoComments) {
1175 comments.push(videoComment.url)
1176 }
1177
1178 return activityPubCollection(getVideoCommentsActivityPubUrl(this), comments)
1179 }
1180
1181 toRatesActivityPubObjects () {
1182 const likes: string[] = []
1183 const dislikes: string[] = []
1184
1185 for (const rate of this.AccountVideoRates) {
1186 if (rate.type === 'like') {
1187 likes.push(rate.Account.Actor.url)
1188 } else if (rate.type === 'dislike') {
1189 dislikes.push(rate.Account.Actor.url)
1190 }
1191 }
1192
1193 const likesObject = activityPubCollection(getVideoLikesActivityPubUrl(this), likes)
1194 const dislikesObject = activityPubCollection(getVideoDislikesActivityPubUrl(this), dislikes)
1195
1196 return { likesObject, dislikesObject }
1197 }
1198
3fd3ab2d
C
1199 getTruncatedDescription () {
1200 if (!this.description) return null
93e1258c 1201
bffbebbe 1202 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
c73e83da 1203 return peertubeTruncate(this.description, maxLength)
93e1258c
C
1204 }
1205
3fd3ab2d
C
1206 optimizeOriginalVideofile = async function () {
1207 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1208 const newExtname = '.mp4'
1209 const inputVideoFile = this.getOriginalFile()
1210 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1211 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
b769007f 1212
3fd3ab2d
C
1213 const transcodeOptions = {
1214 inputPath: videoInputPath,
1215 outputPath: videoOutputPath
1216 }
c46edbc2 1217
b0ef1782
C
1218 // Could be very long!
1219 await transcode(transcodeOptions)
c46edbc2 1220
b0ef1782 1221 try {
3fd3ab2d 1222 await unlinkPromise(videoInputPath)
c46edbc2 1223
3fd3ab2d
C
1224 // Important to do this before getVideoFilename() to take in account the new file extension
1225 inputVideoFile.set('extname', newExtname)
e71bcc0f 1226
3fd3ab2d
C
1227 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1228 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
e71bcc0f 1229
3fd3ab2d 1230 inputVideoFile.set('size', stats.size)
e71bcc0f 1231
3fd3ab2d
C
1232 await this.createTorrentAndSetInfoHash(inputVideoFile)
1233 await inputVideoFile.save()
fd45e8f4 1234
3fd3ab2d
C
1235 } catch (err) {
1236 // Auto destruction...
d5b7d911 1237 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
fd45e8f4 1238
3fd3ab2d
C
1239 throw err
1240 }
feb4bdfd
C
1241 }
1242
056aa7f2 1243 transcodeOriginalVideofile = async function (resolution: VideoResolution, isPortraitMode: boolean) {
3fd3ab2d
C
1244 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1245 const extname = '.mp4'
aaf61f38 1246
3fd3ab2d
C
1247 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1248 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
feb4bdfd 1249
3fd3ab2d
C
1250 const newVideoFile = new VideoFileModel({
1251 resolution,
1252 extname,
1253 size: 0,
1254 videoId: this.id
1255 })
1256 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
a041b171 1257
3fd3ab2d
C
1258 const transcodeOptions = {
1259 inputPath: videoInputPath,
1260 outputPath: videoOutputPath,
056aa7f2
C
1261 resolution,
1262 isPortraitMode
3fd3ab2d 1263 }
a041b171 1264
3fd3ab2d 1265 await transcode(transcodeOptions)
a041b171 1266
3fd3ab2d 1267 const stats = await statPromise(videoOutputPath)
d7d5611c 1268
3fd3ab2d 1269 newVideoFile.set('size', stats.size)
d7d5611c 1270
3fd3ab2d 1271 await this.createTorrentAndSetInfoHash(newVideoFile)
d7d5611c 1272
3fd3ab2d
C
1273 await newVideoFile.save()
1274
1275 this.VideoFiles.push(newVideoFile)
0d0e8dd0
C
1276 }
1277
056aa7f2 1278 getOriginalFileResolution () {
3fd3ab2d 1279 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
0d0e8dd0 1280
056aa7f2 1281 return getVideoFileResolution(originalFilePath)
3fd3ab2d 1282 }
0d0e8dd0 1283
3fd3ab2d
C
1284 getDescriptionPath () {
1285 return `/api/${API_VERSION}/videos/${this.uuid}/description`
feb4bdfd
C
1286 }
1287
3fd3ab2d
C
1288 removeThumbnail () {
1289 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1290 return unlinkPromise(thumbnailPath)
feb4bdfd
C
1291 }
1292
3fd3ab2d
C
1293 removePreview () {
1294 // Same name than video thumbnail
1295 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
7920c273
C
1296 }
1297
3fd3ab2d
C
1298 removeFile (videoFile: VideoFileModel) {
1299 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1300 return unlinkPromise(filePath)
feb4bdfd
C
1301 }
1302
3fd3ab2d
C
1303 removeTorrent (videoFile: VideoFileModel) {
1304 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1305 return unlinkPromise(torrentPath)
aaf61f38
C
1306 }
1307
093237cf
C
1308 getActivityStreamDuration () {
1309 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1310 return 'PT' + this.duration + 'S'
1311 }
1312
3fd3ab2d
C
1313 private getBaseUrls () {
1314 let baseUrlHttp
1315 let baseUrlWs
7920c273 1316
3fd3ab2d
C
1317 if (this.isOwned()) {
1318 baseUrlHttp = CONFIG.WEBSERVER.URL
1319 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1320 } else {
50d6de9c
C
1321 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1322 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
6fcd19ba 1323 }
aaf61f38 1324
3fd3ab2d 1325 return { baseUrlHttp, baseUrlWs }
15d4ee04 1326 }
a96aed15 1327
3fd3ab2d
C
1328 private getThumbnailUrl (baseUrlHttp: string) {
1329 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
a96aed15
C
1330 }
1331
3fd3ab2d
C
1332 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1333 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1334 }
e4f97bab 1335
3fd3ab2d
C
1336 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1337 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1338 }
a96aed15 1339
3fd3ab2d
C
1340 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1341 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1342 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1343 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1344
1345 const magnetHash = {
1346 xs,
1347 announce,
1348 urlList,
1349 infoHash: videoFile.infoHash,
1350 name: this.name
1351 }
a96aed15 1352
3fd3ab2d 1353 return magnetUtil.encode(magnetHash)
a96aed15 1354 }
a96aed15 1355}