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