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