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