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