]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/video/video.ts
Add advanced search in client
[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: {
855 search: string
856 start?: number
857 count?: number
858 sort?: string
859 startDate?: string // ISO 8601
860 endDate?: string // ISO 8601
861 nsfw?: boolean
862 categoryOneOf?: number[]
863 licenceOneOf?: number[]
864 languageOneOf?: string[]
865 tagsOneOf?: string[]
866 tagsAllOf?: string[]
867 durationMin?: number // seconds
868 durationMax?: number // seconds
869 }) {
870 const whereAnd = [ ]
871
872 if (options.startDate || options.endDate) {
873 const publishedAtRange = { }
874
875 if (options.startDate) publishedAtRange[Sequelize.Op.gte] = options.startDate
876 if (options.endDate) publishedAtRange[Sequelize.Op.lte] = options.endDate
877
878 whereAnd.push({ publishedAt: publishedAtRange })
879 }
880
881 if (options.durationMin || options.durationMax) {
882 const durationRange = { }
883
884 if (options.durationMin) durationRange[Sequelize.Op.gte] = options.durationMin
885 if (options.durationMax) durationRange[Sequelize.Op.lte] = options.durationMax
886
887 whereAnd.push({ duration: durationRange })
888 }
889
890 whereAnd.push(createSearchTrigramQuery('VideoModel.name', options.search))
891
892 const query: IFindOptions<VideoModel> = {
893 attributes: {
894 include: [ createSimilarityAttribute('VideoModel.name', options.search) ]
895 },
896 offset: options.start,
897 limit: options.count,
898 order: getSort(options.sort),
899 where: {
900 [ Sequelize.Op.and ]: whereAnd
901 }
902 }
903
904 const serverActor = await getServerActor()
905 const scopes = {
906 method: [
907 ScopeNames.AVAILABLE_FOR_LIST, {
908 actorId: serverActor.id,
909 nsfw: options.nsfw,
910 categoryOneOf: options.categoryOneOf,
911 licenceOneOf: options.licenceOneOf,
912 languageOneOf: options.languageOneOf,
913 tagsOneOf: options.tagsOneOf,
914 tagsAllOf: options.tagsAllOf
915 } as AvailableForListOptions
916 ]
917 }
918
919 return VideoModel.scope(scopes)
920 .findAndCountAll(query)
921 .then(({ rows, count }) => {
922 return {
923 data: rows,
924 total: count
925 }
926 })
927 }
928
929 static load (id: number) {
930 return VideoModel.findById(id)
931 }
932
933 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
934 const query: IFindOptions<VideoModel> = {
935 where: {
936 url
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 loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
946 const query: IFindOptions<VideoModel> = {
947 where: {
948 [Sequelize.Op.or]: [
949 { uuid },
950 { url }
951 ]
952 }
953 }
954
955 if (t !== undefined) query.transaction = t
956
957 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
958 }
959
960 static loadAndPopulateAccountAndServerAndTags (id: number) {
961 const options = {
962 order: [ [ 'Tags', 'name', 'ASC' ] ]
963 }
964
965 return VideoModel
966 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_SCHEDULED_UPDATE ])
967 .findById(id, options)
968 }
969
970 static loadByUUID (uuid: string) {
971 const options = {
972 where: {
973 uuid
974 }
975 }
976
977 return VideoModel
978 .scope([ ScopeNames.WITH_FILES ])
979 .findOne(options)
980 }
981
982 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string, t?: Sequelize.Transaction) {
983 const options = {
984 order: [ [ 'Tags', 'name', 'ASC' ] ],
985 where: {
986 uuid
987 },
988 transaction: t
989 }
990
991 return VideoModel
992 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_SCHEDULED_UPDATE ])
993 .findOne(options)
994 }
995
996 static async getStats () {
997 const totalLocalVideos = await VideoModel.count({
998 where: {
999 remote: false
1000 }
1001 })
1002 const totalVideos = await VideoModel.count()
1003
1004 let totalLocalVideoViews = await VideoModel.sum('views', {
1005 where: {
1006 remote: false
1007 }
1008 })
1009 // Sequelize could return null...
1010 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1011
1012 return {
1013 totalLocalVideos,
1014 totalLocalVideoViews,
1015 totalVideos
1016 }
1017 }
1018
1019 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1020 if (filter && filter === 'local') {
1021 return {
1022 serverId: null
1023 }
1024 }
1025
1026 return {}
1027 }
1028
1029 private static getCategoryLabel (id: number) {
1030 return VIDEO_CATEGORIES[id] || 'Misc'
1031 }
1032
1033 private static getLicenceLabel (id: number) {
1034 return VIDEO_LICENCES[id] || 'Unknown'
1035 }
1036
1037 private static getLanguageLabel (id: string) {
1038 return VIDEO_LANGUAGES[id] || 'Unknown'
1039 }
1040
1041 private static getPrivacyLabel (id: number) {
1042 return VIDEO_PRIVACIES[id] || 'Unknown'
1043 }
1044
1045 private static getStateLabel (id: number) {
1046 return VIDEO_STATES[id] || 'Unknown'
1047 }
1048
1049 getOriginalFile () {
1050 if (Array.isArray(this.VideoFiles) === false) return undefined
1051
1052 // The original file is the file that have the higher resolution
1053 return maxBy(this.VideoFiles, file => file.resolution)
1054 }
1055
1056 getVideoFilename (videoFile: VideoFileModel) {
1057 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1058 }
1059
1060 getThumbnailName () {
1061 // We always have a copy of the thumbnail
1062 const extension = '.jpg'
1063 return this.uuid + extension
1064 }
1065
1066 getPreviewName () {
1067 const extension = '.jpg'
1068 return this.uuid + extension
1069 }
1070
1071 getTorrentFileName (videoFile: VideoFileModel) {
1072 const extension = '.torrent'
1073 return this.uuid + '-' + videoFile.resolution + extension
1074 }
1075
1076 isOwned () {
1077 return this.remote === false
1078 }
1079
1080 createPreview (videoFile: VideoFileModel) {
1081 return generateImageFromVideoFile(
1082 this.getVideoFilePath(videoFile),
1083 CONFIG.STORAGE.PREVIEWS_DIR,
1084 this.getPreviewName(),
1085 PREVIEWS_SIZE
1086 )
1087 }
1088
1089 createThumbnail (videoFile: VideoFileModel) {
1090 return generateImageFromVideoFile(
1091 this.getVideoFilePath(videoFile),
1092 CONFIG.STORAGE.THUMBNAILS_DIR,
1093 this.getThumbnailName(),
1094 THUMBNAILS_SIZE
1095 )
1096 }
1097
1098 getTorrentFilePath (videoFile: VideoFileModel) {
1099 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1100 }
1101
1102 getVideoFilePath (videoFile: VideoFileModel) {
1103 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1104 }
1105
1106 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1107 const options = {
1108 // Keep the extname, it's used by the client to stream the file inside a web browser
1109 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1110 createdBy: 'PeerTube',
1111 announceList: [
1112 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1113 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1114 ],
1115 urlList: [
1116 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1117 ]
1118 }
1119
1120 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1121
1122 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1123 logger.info('Creating torrent %s.', filePath)
1124
1125 await writeFilePromise(filePath, torrent)
1126
1127 const parsedTorrent = parseTorrent(torrent)
1128 videoFile.infoHash = parsedTorrent.infoHash
1129 }
1130
1131 getEmbedStaticPath () {
1132 return '/videos/embed/' + this.uuid
1133 }
1134
1135 getThumbnailStaticPath () {
1136 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1137 }
1138
1139 getPreviewStaticPath () {
1140 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1141 }
1142
1143 toFormattedJSON (options?: {
1144 additionalAttributes: {
1145 state?: boolean,
1146 waitTranscoding?: boolean,
1147 scheduledUpdate?: boolean
1148 }
1149 }): Video {
1150 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1151 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1152
1153 const videoObject: Video = {
1154 id: this.id,
1155 uuid: this.uuid,
1156 name: this.name,
1157 category: {
1158 id: this.category,
1159 label: VideoModel.getCategoryLabel(this.category)
1160 },
1161 licence: {
1162 id: this.licence,
1163 label: VideoModel.getLicenceLabel(this.licence)
1164 },
1165 language: {
1166 id: this.language,
1167 label: VideoModel.getLanguageLabel(this.language)
1168 },
1169 privacy: {
1170 id: this.privacy,
1171 label: VideoModel.getPrivacyLabel(this.privacy)
1172 },
1173 nsfw: this.nsfw,
1174 description: this.getTruncatedDescription(),
1175 isLocal: this.isOwned(),
1176 duration: this.duration,
1177 views: this.views,
1178 likes: this.likes,
1179 dislikes: this.dislikes,
1180 thumbnailPath: this.getThumbnailStaticPath(),
1181 previewPath: this.getPreviewStaticPath(),
1182 embedPath: this.getEmbedStaticPath(),
1183 createdAt: this.createdAt,
1184 updatedAt: this.updatedAt,
1185 publishedAt: this.publishedAt,
1186 account: {
1187 id: formattedAccount.id,
1188 uuid: formattedAccount.uuid,
1189 name: formattedAccount.name,
1190 displayName: formattedAccount.displayName,
1191 url: formattedAccount.url,
1192 host: formattedAccount.host,
1193 avatar: formattedAccount.avatar
1194 },
1195 channel: {
1196 id: formattedVideoChannel.id,
1197 uuid: formattedVideoChannel.uuid,
1198 name: formattedVideoChannel.name,
1199 displayName: formattedVideoChannel.displayName,
1200 url: formattedVideoChannel.url,
1201 host: formattedVideoChannel.host,
1202 avatar: formattedVideoChannel.avatar
1203 }
1204 }
1205
1206 if (options) {
1207 if (options.additionalAttributes.state === true) {
1208 videoObject.state = {
1209 id: this.state,
1210 label: VideoModel.getStateLabel(this.state)
1211 }
1212 }
1213
1214 if (options.additionalAttributes.waitTranscoding === true) {
1215 videoObject.waitTranscoding = this.waitTranscoding
1216 }
1217
1218 if (options.additionalAttributes.scheduledUpdate === true && this.ScheduleVideoUpdate) {
1219 videoObject.scheduledUpdate = {
1220 updateAt: this.ScheduleVideoUpdate.updateAt,
1221 privacy: this.ScheduleVideoUpdate.privacy || undefined
1222 }
1223 }
1224 }
1225
1226 return videoObject
1227 }
1228
1229 toFormattedDetailsJSON (): VideoDetails {
1230 const formattedJson = this.toFormattedJSON({
1231 additionalAttributes: {
1232 scheduledUpdate: true
1233 }
1234 })
1235
1236 const detailsJson = {
1237 support: this.support,
1238 descriptionPath: this.getDescriptionPath(),
1239 channel: this.VideoChannel.toFormattedJSON(),
1240 account: this.VideoChannel.Account.toFormattedJSON(),
1241 tags: map(this.Tags, 'name'),
1242 commentsEnabled: this.commentsEnabled,
1243 waitTranscoding: this.waitTranscoding,
1244 state: {
1245 id: this.state,
1246 label: VideoModel.getStateLabel(this.state)
1247 },
1248 files: []
1249 }
1250
1251 // Format and sort video files
1252 detailsJson.files = this.getFormattedVideoFilesJSON()
1253
1254 return Object.assign(formattedJson, detailsJson)
1255 }
1256
1257 getFormattedVideoFilesJSON (): VideoFile[] {
1258 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1259
1260 return this.VideoFiles
1261 .map(videoFile => {
1262 let resolutionLabel = videoFile.resolution + 'p'
1263
1264 return {
1265 resolution: {
1266 id: videoFile.resolution,
1267 label: resolutionLabel
1268 },
1269 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1270 size: videoFile.size,
1271 fps: videoFile.fps,
1272 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1273 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1274 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1275 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
1276 } as VideoFile
1277 })
1278 .sort((a, b) => {
1279 if (a.resolution.id < b.resolution.id) return 1
1280 if (a.resolution.id === b.resolution.id) return 0
1281 return -1
1282 })
1283 }
1284
1285 toActivityPubObject (): VideoTorrentObject {
1286 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1287 if (!this.Tags) this.Tags = []
1288
1289 const tag = this.Tags.map(t => ({
1290 type: 'Hashtag' as 'Hashtag',
1291 name: t.name
1292 }))
1293
1294 let language
1295 if (this.language) {
1296 language = {
1297 identifier: this.language,
1298 name: VideoModel.getLanguageLabel(this.language)
1299 }
1300 }
1301
1302 let category
1303 if (this.category) {
1304 category = {
1305 identifier: this.category + '',
1306 name: VideoModel.getCategoryLabel(this.category)
1307 }
1308 }
1309
1310 let licence
1311 if (this.licence) {
1312 licence = {
1313 identifier: this.licence + '',
1314 name: VideoModel.getLicenceLabel(this.licence)
1315 }
1316 }
1317
1318 const url = []
1319 for (const file of this.VideoFiles) {
1320 url.push({
1321 type: 'Link',
1322 mimeType: VIDEO_EXT_MIMETYPE[file.extname],
1323 href: this.getVideoFileUrl(file, baseUrlHttp),
1324 width: file.resolution,
1325 size: file.size
1326 })
1327
1328 url.push({
1329 type: 'Link',
1330 mimeType: 'application/x-bittorrent',
1331 href: this.getTorrentUrl(file, baseUrlHttp),
1332 width: file.resolution
1333 })
1334
1335 url.push({
1336 type: 'Link',
1337 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1338 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1339 width: file.resolution
1340 })
1341 }
1342
1343 // Add video url too
1344 url.push({
1345 type: 'Link',
1346 mimeType: 'text/html',
1347 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1348 })
1349
1350 const subtitleLanguage = []
1351 for (const caption of this.VideoCaptions) {
1352 subtitleLanguage.push({
1353 identifier: caption.language,
1354 name: VideoCaptionModel.getLanguageLabel(caption.language)
1355 })
1356 }
1357
1358 return {
1359 type: 'Video' as 'Video',
1360 id: this.url,
1361 name: this.name,
1362 duration: this.getActivityStreamDuration(),
1363 uuid: this.uuid,
1364 tag,
1365 category,
1366 licence,
1367 language,
1368 views: this.views,
1369 sensitive: this.nsfw,
1370 waitTranscoding: this.waitTranscoding,
1371 state: this.state,
1372 commentsEnabled: this.commentsEnabled,
1373 published: this.publishedAt.toISOString(),
1374 updated: this.updatedAt.toISOString(),
1375 mediaType: 'text/markdown',
1376 content: this.getTruncatedDescription(),
1377 support: this.support,
1378 subtitleLanguage,
1379 icon: {
1380 type: 'Image',
1381 url: this.getThumbnailUrl(baseUrlHttp),
1382 mediaType: 'image/jpeg',
1383 width: THUMBNAILS_SIZE.width,
1384 height: THUMBNAILS_SIZE.height
1385 },
1386 url,
1387 likes: getVideoLikesActivityPubUrl(this),
1388 dislikes: getVideoDislikesActivityPubUrl(this),
1389 shares: getVideoSharesActivityPubUrl(this),
1390 comments: getVideoCommentsActivityPubUrl(this),
1391 attributedTo: [
1392 {
1393 type: 'Person',
1394 id: this.VideoChannel.Account.Actor.url
1395 },
1396 {
1397 type: 'Group',
1398 id: this.VideoChannel.Actor.url
1399 }
1400 ]
1401 }
1402 }
1403
1404 getTruncatedDescription () {
1405 if (!this.description) return null
1406
1407 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1408 return peertubeTruncate(this.description, maxLength)
1409 }
1410
1411 async optimizeOriginalVideofile () {
1412 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1413 const newExtname = '.mp4'
1414 const inputVideoFile = this.getOriginalFile()
1415 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1416 const videoTranscodedPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1417
1418 const transcodeOptions = {
1419 inputPath: videoInputPath,
1420 outputPath: videoTranscodedPath
1421 }
1422
1423 // Could be very long!
1424 await transcode(transcodeOptions)
1425
1426 try {
1427 await unlinkPromise(videoInputPath)
1428
1429 // Important to do this before getVideoFilename() to take in account the new file extension
1430 inputVideoFile.set('extname', newExtname)
1431
1432 const videoOutputPath = this.getVideoFilePath(inputVideoFile)
1433 await renamePromise(videoTranscodedPath, videoOutputPath)
1434 const stats = await statPromise(videoOutputPath)
1435 const fps = await getVideoFileFPS(videoOutputPath)
1436
1437 inputVideoFile.set('size', stats.size)
1438 inputVideoFile.set('fps', fps)
1439
1440 await this.createTorrentAndSetInfoHash(inputVideoFile)
1441 await inputVideoFile.save()
1442
1443 } catch (err) {
1444 // Auto destruction...
1445 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1446
1447 throw err
1448 }
1449 }
1450
1451 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1452 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1453 const extname = '.mp4'
1454
1455 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1456 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1457
1458 const newVideoFile = new VideoFileModel({
1459 resolution,
1460 extname,
1461 size: 0,
1462 videoId: this.id
1463 })
1464 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1465
1466 const transcodeOptions = {
1467 inputPath: videoInputPath,
1468 outputPath: videoOutputPath,
1469 resolution,
1470 isPortraitMode
1471 }
1472
1473 await transcode(transcodeOptions)
1474
1475 const stats = await statPromise(videoOutputPath)
1476 const fps = await getVideoFileFPS(videoOutputPath)
1477
1478 newVideoFile.set('size', stats.size)
1479 newVideoFile.set('fps', fps)
1480
1481 await this.createTorrentAndSetInfoHash(newVideoFile)
1482
1483 await newVideoFile.save()
1484
1485 this.VideoFiles.push(newVideoFile)
1486 }
1487
1488 async importVideoFile (inputFilePath: string) {
1489 const { videoFileResolution } = await getVideoFileResolution(inputFilePath)
1490 const { size } = await statPromise(inputFilePath)
1491 const fps = await getVideoFileFPS(inputFilePath)
1492
1493 let updatedVideoFile = new VideoFileModel({
1494 resolution: videoFileResolution,
1495 extname: extname(inputFilePath),
1496 size,
1497 fps,
1498 videoId: this.id
1499 })
1500
1501 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
1502
1503 if (currentVideoFile) {
1504 // Remove old file and old torrent
1505 await this.removeFile(currentVideoFile)
1506 await this.removeTorrent(currentVideoFile)
1507 // Remove the old video file from the array
1508 this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile)
1509
1510 // Update the database
1511 currentVideoFile.set('extname', updatedVideoFile.extname)
1512 currentVideoFile.set('size', updatedVideoFile.size)
1513 currentVideoFile.set('fps', updatedVideoFile.fps)
1514
1515 updatedVideoFile = currentVideoFile
1516 }
1517
1518 const outputPath = this.getVideoFilePath(updatedVideoFile)
1519 await copyFilePromise(inputFilePath, outputPath)
1520
1521 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1522
1523 await updatedVideoFile.save()
1524
1525 this.VideoFiles.push(updatedVideoFile)
1526 }
1527
1528 getOriginalFileResolution () {
1529 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1530
1531 return getVideoFileResolution(originalFilePath)
1532 }
1533
1534 getDescriptionPath () {
1535 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1536 }
1537
1538 removeThumbnail () {
1539 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1540 return unlinkPromise(thumbnailPath)
1541 }
1542
1543 removePreview () {
1544 // Same name than video thumbnail
1545 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1546 }
1547
1548 removeFile (videoFile: VideoFileModel) {
1549 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1550 return unlinkPromise(filePath)
1551 }
1552
1553 removeTorrent (videoFile: VideoFileModel) {
1554 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1555 return unlinkPromise(torrentPath)
1556 }
1557
1558 getActivityStreamDuration () {
1559 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1560 return 'PT' + this.duration + 'S'
1561 }
1562
1563 private getBaseUrls () {
1564 let baseUrlHttp
1565 let baseUrlWs
1566
1567 if (this.isOwned()) {
1568 baseUrlHttp = CONFIG.WEBSERVER.URL
1569 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1570 } else {
1571 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1572 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1573 }
1574
1575 return { baseUrlHttp, baseUrlWs }
1576 }
1577
1578 private getThumbnailUrl (baseUrlHttp: string) {
1579 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1580 }
1581
1582 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1583 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1584 }
1585
1586 private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1587 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1588 }
1589
1590 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1591 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1592 }
1593
1594 private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1595 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1596 }
1597
1598 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1599 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1600 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1601 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1602
1603 const magnetHash = {
1604 xs,
1605 announce,
1606 urlList,
1607 infoHash: videoFile.infoHash,
1608 name: this.name
1609 }
1610
1611 return magnetUtil.encode(magnetHash)
1612 }
1613 }