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