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