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