]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video/video.ts
Add create-import-video-file-job command
[github/Chocobozzz/PeerTube.git] / server / models / video / video.ts
CommitLineData
39445ead 1import * as Bluebird from 'bluebird'
c73e83da 2import { map, maxBy } from 'lodash'
571389d4 3import * as magnetUtil from 'magnet-uri'
4d4e5cd4 4import * as parseTorrent from 'parse-torrent'
0138af92 5import { join, extname } from 'path'
e02643f3 6import * as Sequelize from 'sequelize'
3fd3ab2d 7import {
4ba3b8ea
C
8 AllowNull,
9 BeforeDestroy,
10 BelongsTo,
11 BelongsToMany,
12 Column,
13 CreatedAt,
14 DataType,
15 Default,
16 ForeignKey,
17 HasMany,
18 IFindOptions,
19 Is,
20 IsInt,
21 IsUUID,
22 Min,
23 Model,
24 Scopes,
25 Table,
26 UpdatedAt
3fd3ab2d 27} from 'sequelize-typescript'
571389d4 28import { VideoPrivacy, VideoResolution } from '../../../shared'
3fd3ab2d 29import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
a8462c8e 30import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos'
066e94c5 31import { VideoFilter } from '../../../shared/models/videos/video-query.type'
c73e83da 32import {
06be7ed0
C
33 createTorrentPromise,
34 peertubeTruncate,
0138af92 35 copyFilePromise,
06be7ed0
C
36 renamePromise,
37 statPromise,
38 unlinkPromise,
c73e83da
C
39 writeFilePromise
40} from '../../helpers/core-utils'
da854ddd 41import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
47564bbe 42import { isBooleanValid } from '../../helpers/custom-validators/misc'
3fd3ab2d 43import {
4ba3b8ea
C
44 isVideoCategoryValid,
45 isVideoDescriptionValid,
46 isVideoDurationValid,
47 isVideoLanguageValid,
48 isVideoLicenceValid,
49 isVideoNameValid,
b64c950a
C
50 isVideoPrivacyValid,
51 isVideoSupportValid
3fd3ab2d 52} from '../../helpers/custom-validators/videos'
056aa7f2 53import { generateImageFromVideoFile, getVideoFileResolution, transcode } from '../../helpers/ffmpeg-utils'
da854ddd 54import { logger } from '../../helpers/logger'
f05a1c30 55import { getServerActor } from '../../helpers/utils'
65fcc311 56import {
4ba3b8ea
C
57 API_VERSION,
58 CONFIG,
59 CONSTRAINTS_FIELDS,
60 PREVIEWS_SIZE,
61 REMOTE_SCHEME,
02756fbd 62 STATIC_DOWNLOAD_PATHS,
4ba3b8ea
C
63 STATIC_PATHS,
64 THUMBNAILS_SIZE,
65 VIDEO_CATEGORIES,
66 VIDEO_LANGUAGES,
67 VIDEO_LICENCES,
68 VIDEO_PRIVACIES
3fd3ab2d 69} from '../../initializers'
46531a0a
C
70import {
71 getVideoCommentsActivityPubUrl,
72 getVideoDislikesActivityPubUrl,
73 getVideoLikesActivityPubUrl,
74 getVideoSharesActivityPubUrl
75} from '../../lib/activitypub'
50d6de9c 76import { sendDeleteVideo } from '../../lib/activitypub/send'
3fd3ab2d
C
77import { AccountModel } from '../account/account'
78import { AccountVideoRateModel } from '../account/account-video-rate'
50d6de9c 79import { ActorModel } from '../activitypub/actor'
b6a4fd6b 80import { AvatarModel } from '../avatar/avatar'
3fd3ab2d
C
81import { ServerModel } from '../server/server'
82import { getSort, throwIfNotValid } from '../utils'
83import { TagModel } from './tag'
84import { VideoAbuseModel } from './video-abuse'
85import { VideoChannelModel } from './video-channel'
da854ddd 86import { VideoCommentModel } from './video-comment'
3fd3ab2d
C
87import { VideoFileModel } from './video-file'
88import { VideoShareModel } from './video-share'
89import { VideoTagModel } from './video-tag'
90
d48ff09d 91enum ScopeNames {
50d6de9c 92 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
4cb6d457 93 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
d48ff09d
C
94 WITH_TAGS = 'WITH_TAGS',
95 WITH_FILES = 'WITH_FILES',
96 WITH_SHARES = 'WITH_SHARES',
da854ddd
C
97 WITH_RATES = 'WITH_RATES',
98 WITH_COMMENTS = 'WITH_COMMENTS'
d48ff09d
C
99}
100
101@Scopes({
48dce1c9
C
102 [ScopeNames.AVAILABLE_FOR_LIST]: (options: {
103 actorId: number,
104 hideNSFW: boolean,
105 filter?: VideoFilter,
106 withFiles?: boolean,
107 accountId?: number,
108 videoChannelId?: number
109 }) => {
0626e7af 110 const accountInclude = {
03e12d7c 111 attributes: [ 'id', 'name' ],
0626e7af
C
112 model: AccountModel.unscoped(),
113 required: true,
114 where: {},
115 include: [
116 {
03e12d7c 117 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
0626e7af
C
118 model: ActorModel.unscoped(),
119 required: true,
48dce1c9 120 where: VideoModel.buildActorWhereWithFilter(options.filter),
0626e7af
C
121 include: [
122 {
123 attributes: [ 'host' ],
124 model: ServerModel.unscoped(),
125 required: false
126 },
127 {
128 model: AvatarModel.unscoped(),
129 required: false
130 }
131 ]
132 }
133 ]
134 }
135
48dce1c9 136 const videoChannelInclude = {
0f320037 137 attributes: [ 'name', 'description', 'id' ],
48dce1c9
C
138 model: VideoChannelModel.unscoped(),
139 required: true,
140 where: {},
141 include: [
0f320037
C
142 {
143 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
144 model: ActorModel.unscoped(),
145 required: true,
146 include: [
147 {
148 attributes: [ 'host' ],
149 model: ServerModel.unscoped(),
150 required: false
151 },
152 {
153 model: AvatarModel.unscoped(),
154 required: false
155 }
156 ]
157 },
48dce1c9
C
158 accountInclude
159 ]
160 }
161
162 // Force actorId to be a number to avoid SQL injections
163 const actorIdNumber = parseInt(options.actorId.toString(), 10)
244e76a5
RK
164 const query: IFindOptions<VideoModel> = {
165 where: {
166 id: {
167 [Sequelize.Op.notIn]: Sequelize.literal(
168 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
169 ),
170 [ Sequelize.Op.in ]: Sequelize.literal(
171 '(' +
2d9ab590
C
172 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
173 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
48dce1c9 174 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
2d9ab590
C
175 ' UNION ' +
176 'SELECT "video"."id" AS "id" FROM "video" ' +
177 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
178 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
179 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
180 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
48dce1c9 181 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + actorIdNumber +
244e76a5
RK
182 ')'
183 )
184 },
185 privacy: VideoPrivacy.PUBLIC
50d6de9c 186 },
48dce1c9 187 include: [ videoChannelInclude ]
244e76a5
RK
188 }
189
48dce1c9 190 if (options.withFiles === true) {
244e76a5
RK
191 query.include.push({
192 model: VideoFileModel.unscoped(),
193 required: true
194 })
195 }
196
0883b324 197 // Hide nsfw videos?
48dce1c9 198 if (options.hideNSFW === true) {
0883b324
C
199 query.where['nsfw'] = false
200 }
201
48dce1c9 202 if (options.accountId) {
0626e7af 203 accountInclude.where = {
48dce1c9
C
204 id: options.accountId
205 }
206 }
207
208 if (options.videoChannelId) {
209 videoChannelInclude.where = {
210 id: options.videoChannelId
0626e7af
C
211 }
212 }
213
244e76a5
RK
214 return query
215 },
4cb6d457 216 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
d48ff09d
C
217 include: [
218 {
6120941f 219 model: () => VideoChannelModel.unscoped(),
d48ff09d
C
220 required: true,
221 include: [
6120941f
C
222 {
223 attributes: {
224 exclude: [ 'privateKey', 'publicKey' ]
225 },
3e500247
C
226 model: () => ActorModel.unscoped(),
227 required: true,
228 include: [
229 {
230 attributes: [ 'host' ],
231 model: () => ServerModel.unscoped(),
232 required: false
233 }
234 ]
6120941f 235 },
d48ff09d 236 {
3e500247 237 model: () => AccountModel.unscoped(),
d48ff09d
C
238 required: true,
239 include: [
240 {
3e500247 241 model: () => ActorModel.unscoped(),
6120941f
C
242 attributes: {
243 exclude: [ 'privateKey', 'publicKey' ]
244 },
50d6de9c
C
245 required: true,
246 include: [
247 {
3e500247
C
248 attributes: [ 'host' ],
249 model: () => ServerModel.unscoped(),
50d6de9c 250 required: false
b6a4fd6b
C
251 },
252 {
253 model: () => AvatarModel.unscoped(),
254 required: false
50d6de9c
C
255 }
256 ]
d48ff09d
C
257 }
258 ]
259 }
260 ]
261 }
262 ]
263 },
264 [ScopeNames.WITH_TAGS]: {
265 include: [ () => TagModel ]
266 },
267 [ScopeNames.WITH_FILES]: {
268 include: [
269 {
e53f952e 270 model: () => VideoFileModel.unscoped(),
d48ff09d
C
271 required: true
272 }
273 ]
274 },
275 [ScopeNames.WITH_SHARES]: {
276 include: [
277 {
e1a540b5 278 ['separate' as any]: true,
e53f952e 279 model: () => VideoShareModel.unscoped()
d48ff09d
C
280 }
281 ]
282 },
283 [ScopeNames.WITH_RATES]: {
284 include: [
285 {
e1a540b5 286 ['separate' as any]: true,
d48ff09d 287 model: () => AccountVideoRateModel,
e53f952e
C
288 include: [
289 {
290 model: () => AccountModel.unscoped(),
291 required: true,
292 include: [
293 {
294 attributes: [ 'url' ],
295 model: () => ActorModel.unscoped()
296 }
297 ]
298 }
299 ]
d48ff09d
C
300 }
301 ]
da854ddd
C
302 },
303 [ScopeNames.WITH_COMMENTS]: {
304 include: [
305 {
e1a540b5 306 ['separate' as any]: true,
e53f952e 307 model: () => VideoCommentModel.unscoped()
da854ddd
C
308 }
309 ]
d48ff09d
C
310 }
311})
3fd3ab2d
C
312@Table({
313 tableName: 'video',
314 indexes: [
feb4bdfd 315 {
3fd3ab2d 316 fields: [ 'name' ]
feb4bdfd
C
317 },
318 {
3fd3ab2d
C
319 fields: [ 'createdAt' ]
320 },
321 {
322 fields: [ 'duration' ]
323 },
324 {
325 fields: [ 'views' ]
326 },
327 {
328 fields: [ 'likes' ]
329 },
330 {
331 fields: [ 'uuid' ]
332 },
333 {
334 fields: [ 'channelId' ]
4cb6d457
C
335 },
336 {
337 fields: [ 'id', 'privacy' ]
2ccaeeb3
C
338 },
339 {
340 fields: [ 'url'],
341 unique: true
feb4bdfd 342 }
e02643f3 343 ]
3fd3ab2d
C
344})
345export class VideoModel extends Model<VideoModel> {
346
347 @AllowNull(false)
348 @Default(DataType.UUIDV4)
349 @IsUUID(4)
350 @Column(DataType.UUID)
351 uuid: string
352
353 @AllowNull(false)
354 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
355 @Column
356 name: string
357
358 @AllowNull(true)
359 @Default(null)
360 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
361 @Column
362 category: number
363
364 @AllowNull(true)
365 @Default(null)
366 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
367 @Column
368 licence: number
369
370 @AllowNull(true)
371 @Default(null)
372 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
9d3ef9fe
C
373 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
374 language: string
3fd3ab2d
C
375
376 @AllowNull(false)
377 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
378 @Column
379 privacy: number
380
381 @AllowNull(false)
47564bbe 382 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
3fd3ab2d
C
383 @Column
384 nsfw: boolean
385
386 @AllowNull(true)
387 @Default(null)
388 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
389 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
390 description: string
391
2422c46b
C
392 @AllowNull(true)
393 @Default(null)
394 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
395 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
396 support: string
397
3fd3ab2d
C
398 @AllowNull(false)
399 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
400 @Column
401 duration: number
402
403 @AllowNull(false)
404 @Default(0)
405 @IsInt
406 @Min(0)
407 @Column
408 views: number
409
410 @AllowNull(false)
411 @Default(0)
412 @IsInt
413 @Min(0)
414 @Column
415 likes: number
416
417 @AllowNull(false)
418 @Default(0)
419 @IsInt
420 @Min(0)
421 @Column
422 dislikes: number
423
424 @AllowNull(false)
425 @Column
426 remote: boolean
427
428 @AllowNull(false)
429 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
430 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
431 url: string
432
47564bbe
C
433 @AllowNull(false)
434 @Column
435 commentsEnabled: boolean
436
3fd3ab2d
C
437 @CreatedAt
438 createdAt: Date
439
440 @UpdatedAt
441 updatedAt: Date
442
2922e048
JLB
443 @AllowNull(false)
444 @Default(Sequelize.NOW)
445 @Column
446 publishedAt: Date
447
3fd3ab2d
C
448 @ForeignKey(() => VideoChannelModel)
449 @Column
450 channelId: number
451
452 @BelongsTo(() => VideoChannelModel, {
feb4bdfd 453 foreignKey: {
50d6de9c 454 allowNull: true
feb4bdfd 455 },
6b738c7a 456 hooks: true
feb4bdfd 457 })
3fd3ab2d 458 VideoChannel: VideoChannelModel
7920c273 459
3fd3ab2d 460 @BelongsToMany(() => TagModel, {
7920c273 461 foreignKey: 'videoId',
3fd3ab2d
C
462 through: () => VideoTagModel,
463 onDelete: 'CASCADE'
7920c273 464 })
3fd3ab2d 465 Tags: TagModel[]
55fa55a9 466
3fd3ab2d 467 @HasMany(() => VideoAbuseModel, {
55fa55a9
C
468 foreignKey: {
469 name: 'videoId',
470 allowNull: false
471 },
472 onDelete: 'cascade'
473 })
3fd3ab2d 474 VideoAbuses: VideoAbuseModel[]
93e1258c 475
3fd3ab2d 476 @HasMany(() => VideoFileModel, {
93e1258c
C
477 foreignKey: {
478 name: 'videoId',
479 allowNull: false
480 },
481 onDelete: 'cascade'
482 })
3fd3ab2d 483 VideoFiles: VideoFileModel[]
e71bcc0f 484
3fd3ab2d 485 @HasMany(() => VideoShareModel, {
e71bcc0f
C
486 foreignKey: {
487 name: 'videoId',
488 allowNull: false
489 },
490 onDelete: 'cascade'
491 })
3fd3ab2d 492 VideoShares: VideoShareModel[]
16b90975 493
3fd3ab2d 494 @HasMany(() => AccountVideoRateModel, {
16b90975
C
495 foreignKey: {
496 name: 'videoId',
497 allowNull: false
498 },
499 onDelete: 'cascade'
500 })
3fd3ab2d 501 AccountVideoRates: AccountVideoRateModel[]
f285faa0 502
da854ddd
C
503 @HasMany(() => VideoCommentModel, {
504 foreignKey: {
505 name: 'videoId',
506 allowNull: false
507 },
f05a1c30
C
508 onDelete: 'cascade',
509 hooks: true
da854ddd
C
510 })
511 VideoComments: VideoCommentModel[]
512
f05a1c30
C
513 @BeforeDestroy
514 static async sendDelete (instance: VideoModel, options) {
515 if (instance.isOwned()) {
516 if (!instance.VideoChannel) {
517 instance.VideoChannel = await instance.$get('VideoChannel', {
518 include: [
519 {
520 model: AccountModel,
521 include: [ ActorModel ]
522 }
523 ],
524 transaction: options.transaction
525 }) as VideoChannelModel
526 }
527
528 logger.debug('Sending delete of video %s.', instance.url)
529
530 return sendDeleteVideo(instance, options.transaction)
531 }
532
533 return undefined
534 }
535
6b738c7a 536 @BeforeDestroy
f05a1c30
C
537 static async removeFilesAndSendDelete (instance: VideoModel) {
538 const tasks: Promise<any>[] = []
f285faa0 539
6b738c7a
C
540 logger.debug('Removing files of video %s.', instance.url)
541
f05a1c30 542 tasks.push(instance.removeThumbnail())
93e1258c 543
3fd3ab2d 544 if (instance.isOwned()) {
f05a1c30
C
545 if (!Array.isArray(instance.VideoFiles)) {
546 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
547 }
548
549 tasks.push(instance.removePreview())
40298b02 550
3fd3ab2d
C
551 // Remove physical files and torrents
552 instance.VideoFiles.forEach(file => {
553 tasks.push(instance.removeFile(file))
554 tasks.push(instance.removeTorrent(file))
555 })
556 }
40298b02 557
6b738c7a
C
558 // Do not wait video deletion because we could be in a transaction
559 Promise.all(tasks)
3fd3ab2d 560 .catch(err => {
d5b7d911 561 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
3fd3ab2d 562 })
6b738c7a
C
563
564 return undefined
3fd3ab2d 565 }
f285faa0 566
3fd3ab2d 567 static list () {
d48ff09d 568 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
3fd3ab2d 569 }
f285faa0 570
50d6de9c 571 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
3fd3ab2d
C
572 function getRawQuery (select: string) {
573 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
574 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
50d6de9c
C
575 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
576 'WHERE "Account"."actorId" = ' + actorId
3fd3ab2d
C
577 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
578 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
50d6de9c 579 'WHERE "VideoShare"."actorId" = ' + actorId
558d7c23 580
3fd3ab2d
C
581 return `(${queryVideo}) UNION (${queryVideoShare})`
582 }
aaf61f38 583
3fd3ab2d
C
584 const rawQuery = getRawQuery('"Video"."id"')
585 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
586
587 const query = {
588 distinct: true,
589 offset: start,
590 limit: count,
3bb6c526 591 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
3fd3ab2d
C
592 where: {
593 id: {
594 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
3c75ce12
C
595 },
596 [Sequelize.Op.or]: [
597 { privacy: VideoPrivacy.PUBLIC },
598 { privacy: VideoPrivacy.UNLISTED }
599 ]
3fd3ab2d
C
600 },
601 include: [
602 {
1d230c44 603 attributes: [ 'id', 'url' ],
2c897999 604 model: VideoShareModel.unscoped(),
3fd3ab2d 605 required: false,
e3d5ea4f
C
606 // We only want videos shared by this actor
607 where: {
608 [Sequelize.Op.and]: [
609 {
610 id: {
611 [Sequelize.Op.not]: null
612 }
613 },
614 {
615 actorId
616 }
617 ]
618 },
50d6de9c
C
619 include: [
620 {
2c897999
C
621 attributes: [ 'id', 'url' ],
622 model: ActorModel.unscoped()
50d6de9c
C
623 }
624 ]
3fd3ab2d
C
625 },
626 {
2c897999 627 model: VideoChannelModel.unscoped(),
3fd3ab2d
C
628 required: true,
629 include: [
630 {
2c897999
C
631 attributes: [ 'name' ],
632 model: AccountModel.unscoped(),
633 required: true,
634 include: [
635 {
e3d5ea4f 636 attributes: [ 'id', 'url', 'followersUrl' ],
2c897999
C
637 model: ActorModel.unscoped(),
638 required: true
639 }
640 ]
641 },
642 {
e3d5ea4f 643 attributes: [ 'id', 'url', 'followersUrl' ],
2c897999 644 model: ActorModel.unscoped(),
3fd3ab2d
C
645 required: true
646 }
647 ]
648 },
3fd3ab2d 649 VideoFileModel,
2c897999 650 TagModel
3fd3ab2d
C
651 ]
652 }
164174a6 653
3fd3ab2d
C
654 return Bluebird.all([
655 // FIXME: typing issue
656 VideoModel.findAll(query as any),
657 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
658 ]).then(([ rows, totals ]) => {
659 // totals: totalVideos + totalVideoShares
660 let totalVideos = 0
661 let totalVideoShares = 0
662 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
663 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
664
665 const total = totalVideos + totalVideoShares
666 return {
667 data: rows,
668 total: total
669 }
670 })
671 }
93e1258c 672
0883b324 673 static listAccountVideosForApi (accountId: number, start: number, count: number, sort: string, hideNSFW: boolean, withFiles = false) {
244e76a5 674 const query: IFindOptions<VideoModel> = {
3fd3ab2d
C
675 offset: start,
676 limit: count,
3bb6c526 677 order: getSort(sort),
3fd3ab2d
C
678 include: [
679 {
680 model: VideoChannelModel,
681 required: true,
682 include: [
683 {
684 model: AccountModel,
685 where: {
7b87d2d5 686 id: accountId
3fd3ab2d
C
687 },
688 required: true
689 }
690 ]
d48ff09d 691 }
3fd3ab2d
C
692 ]
693 }
d8755eed 694
244e76a5
RK
695 if (withFiles === true) {
696 query.include.push({
697 model: VideoFileModel.unscoped(),
698 required: true
699 })
700 }
701
0883b324
C
702 if (hideNSFW === true) {
703 query.where = {
704 nsfw: false
705 }
706 }
707
3fd3ab2d
C
708 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
709 return {
710 data: rows,
711 total: count
712 }
713 })
714 }
93e1258c 715
48dce1c9 716 static async listForApi (options: {
0626e7af
C
717 start: number,
718 count: number,
719 sort: string,
720 hideNSFW: boolean,
48dce1c9 721 withFiles: boolean,
0626e7af 722 filter?: VideoFilter,
48dce1c9
C
723 accountId?: number,
724 videoChannelId?: number
725 }) {
3fd3ab2d 726 const query = {
48dce1c9
C
727 offset: options.start,
728 limit: options.count,
729 order: getSort(options.sort)
3fd3ab2d 730 }
93e1258c 731
f05a1c30 732 const serverActor = await getServerActor()
48dce1c9
C
733 const scopes = {
734 method: [
735 ScopeNames.AVAILABLE_FOR_LIST, {
736 actorId: serverActor.id,
737 hideNSFW: options.hideNSFW,
738 filter: options.filter,
739 withFiles: options.withFiles,
740 accountId: options.accountId,
741 videoChannelId: options.videoChannelId
742 }
743 ]
744 }
745
746 return VideoModel.scope(scopes)
d48ff09d
C
747 .findAndCountAll(query)
748 .then(({ rows, count }) => {
749 return {
750 data: rows,
751 total: count
752 }
753 })
93e1258c
C
754 }
755
0883b324 756 static async searchAndPopulateAccountAndServer (value: string, start: number, count: number, sort: string, hideNSFW: boolean) {
f05a1c30
C
757 const query: IFindOptions<VideoModel> = {
758 offset: start,
759 limit: count,
3bb6c526 760 order: getSort(sort),
f05a1c30 761 where: {
3e0c9ff5
C
762 [Sequelize.Op.or]: [
763 {
764 name: {
765 [ Sequelize.Op.iLike ]: '%' + value + '%'
766 }
767 },
768 {
0f320037 769 preferredUsernameChannel: Sequelize.where(Sequelize.col('VideoChannel->Actor.preferredUsername'), {
3e0c9ff5
C
770 [ Sequelize.Op.iLike ]: '%' + value + '%'
771 })
772 },
773 {
0f320037
C
774 preferredUsernameAccount: Sequelize.where(Sequelize.col('VideoChannel->Account->Actor.preferredUsername'), {
775 [ Sequelize.Op.iLike ]: '%' + value + '%'
776 })
777 },
778 {
779 host: Sequelize.where(Sequelize.col('VideoChannel->Account->Actor->Server.host'), {
3e0c9ff5
C
780 [ Sequelize.Op.iLike ]: '%' + value + '%'
781 })
782 }
783 ]
f05a1c30
C
784 }
785 }
786
787 const serverActor = await getServerActor()
48dce1c9
C
788 const scopes = {
789 method: [
790 ScopeNames.AVAILABLE_FOR_LIST, {
791 actorId: serverActor.id,
792 hideNSFW
793 }
794 ]
795 }
f05a1c30 796
48dce1c9 797 return VideoModel.scope(scopes)
244e76a5
RK
798 .findAndCountAll(query)
799 .then(({ rows, count }) => {
f05a1c30
C
800 return {
801 data: rows,
802 total: count
803 }
804 })
805 }
806
3fd3ab2d
C
807 static load (id: number) {
808 return VideoModel.findById(id)
809 }
fdbda9e3 810
3fd3ab2d
C
811 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
812 const query: IFindOptions<VideoModel> = {
813 where: {
814 url
d48ff09d 815 }
3fd3ab2d 816 }
d8755eed 817
3fd3ab2d 818 if (t !== undefined) query.transaction = t
d8755eed 819
4cb6d457 820 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
3fd3ab2d 821 }
d8755eed 822
2ccaeeb3 823 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
3fd3ab2d
C
824 const query: IFindOptions<VideoModel> = {
825 where: {
826 [Sequelize.Op.or]: [
827 { uuid },
828 { url }
829 ]
d48ff09d 830 }
3fd3ab2d 831 }
feb4bdfd 832
3fd3ab2d 833 if (t !== undefined) query.transaction = t
feb4bdfd 834
2ccaeeb3 835 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
72c7248b
C
836 }
837
3fd3ab2d
C
838 static loadAndPopulateAccountAndServerAndTags (id: number) {
839 const options = {
d48ff09d 840 order: [ [ 'Tags', 'name', 'ASC' ] ]
3fd3ab2d 841 }
72c7248b 842
d48ff09d 843 return VideoModel
4cb6d457 844 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
d48ff09d 845 .findById(id, options)
3fd3ab2d 846 }
72c7248b 847
8fa5653a
C
848 static loadByUUID (uuid: string) {
849 const options = {
850 where: {
851 uuid
852 }
853 }
854
855 return VideoModel
856 .scope([ ScopeNames.WITH_FILES ])
857 .findOne(options)
858 }
859
3fd3ab2d
C
860 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
861 const options = {
862 order: [ [ 'Tags', 'name', 'ASC' ] ],
863 where: {
864 uuid
d48ff09d 865 }
3fd3ab2d 866 }
fd45e8f4 867
d48ff09d 868 return VideoModel
4cb6d457 869 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
da854ddd
C
870 .findOne(options)
871 }
872
09cababd
C
873 static async getStats () {
874 const totalLocalVideos = await VideoModel.count({
875 where: {
876 remote: false
877 }
878 })
879 const totalVideos = await VideoModel.count()
880
881 let totalLocalVideoViews = await VideoModel.sum('views', {
882 where: {
883 remote: false
884 }
885 })
886 // Sequelize could return null...
887 if (!totalLocalVideoViews) totalLocalVideoViews = 0
888
889 return {
890 totalLocalVideos,
891 totalLocalVideoViews,
892 totalVideos
893 }
894 }
895
066e94c5
C
896 private static buildActorWhereWithFilter (filter?: VideoFilter) {
897 if (filter && filter === 'local') {
898 return {
899 serverId: null
900 }
901 }
902
903 return {}
904 }
905
ae5a3dd6
C
906 private static getCategoryLabel (id: number) {
907 let categoryLabel = VIDEO_CATEGORIES[id]
908 if (!categoryLabel) categoryLabel = 'Misc'
909
910 return categoryLabel
911 }
912
913 private static getLicenceLabel (id: number) {
914 let licenceLabel = VIDEO_LICENCES[id]
915 if (!licenceLabel) licenceLabel = 'Unknown'
916
917 return licenceLabel
918 }
919
9d3ef9fe 920 private static getLanguageLabel (id: string) {
ae5a3dd6
C
921 let languageLabel = VIDEO_LANGUAGES[id]
922 if (!languageLabel) languageLabel = 'Unknown'
923
924 return languageLabel
925 }
926
2243730c
C
927 private static getPrivacyLabel (id: number) {
928 let privacyLabel = VIDEO_PRIVACIES[id]
929 if (!privacyLabel) privacyLabel = 'Unknown'
930
931 return privacyLabel
932 }
933
3fd3ab2d
C
934 getOriginalFile () {
935 if (Array.isArray(this.VideoFiles) === false) return undefined
aaf61f38 936
3fd3ab2d
C
937 // The original file is the file that have the higher resolution
938 return maxBy(this.VideoFiles, file => file.resolution)
e4f97bab 939 }
aaf61f38 940
3fd3ab2d
C
941 getVideoFilename (videoFile: VideoFileModel) {
942 return this.uuid + '-' + videoFile.resolution + videoFile.extname
943 }
165cdc75 944
3fd3ab2d
C
945 getThumbnailName () {
946 // We always have a copy of the thumbnail
947 const extension = '.jpg'
948 return this.uuid + extension
7b1f49de
C
949 }
950
3fd3ab2d
C
951 getPreviewName () {
952 const extension = '.jpg'
953 return this.uuid + extension
954 }
7b1f49de 955
3fd3ab2d
C
956 getTorrentFileName (videoFile: VideoFileModel) {
957 const extension = '.torrent'
958 return this.uuid + '-' + videoFile.resolution + extension
959 }
8e7f08b5 960
3fd3ab2d
C
961 isOwned () {
962 return this.remote === false
9567011b
C
963 }
964
3fd3ab2d 965 createPreview (videoFile: VideoFileModel) {
3fd3ab2d
C
966 return generateImageFromVideoFile(
967 this.getVideoFilePath(videoFile),
968 CONFIG.STORAGE.PREVIEWS_DIR,
969 this.getPreviewName(),
26670720 970 PREVIEWS_SIZE
3fd3ab2d
C
971 )
972 }
9567011b 973
3fd3ab2d 974 createThumbnail (videoFile: VideoFileModel) {
3fd3ab2d
C
975 return generateImageFromVideoFile(
976 this.getVideoFilePath(videoFile),
977 CONFIG.STORAGE.THUMBNAILS_DIR,
978 this.getThumbnailName(),
26670720 979 THUMBNAILS_SIZE
3fd3ab2d 980 )
14d3270f
C
981 }
982
02756fbd
C
983 getTorrentFilePath (videoFile: VideoFileModel) {
984 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
985 }
986
3fd3ab2d
C
987 getVideoFilePath (videoFile: VideoFileModel) {
988 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
989 }
14d3270f 990
81e504b3 991 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
3fd3ab2d 992 const options = {
6cced8f9
C
993 // Keep the extname, it's used by the client to stream the file inside a web browser
994 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
81e504b3 995 createdBy: 'PeerTube',
3fd3ab2d 996 announceList: [
0edf0581
C
997 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
998 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
3fd3ab2d
C
999 ],
1000 urlList: [
1001 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1002 ]
1003 }
14d3270f 1004
3fd3ab2d 1005 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
e4f97bab 1006
3fd3ab2d
C
1007 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1008 logger.info('Creating torrent %s.', filePath)
e4f97bab 1009
3fd3ab2d 1010 await writeFilePromise(filePath, torrent)
e4f97bab 1011
3fd3ab2d
C
1012 const parsedTorrent = parseTorrent(torrent)
1013 videoFile.infoHash = parsedTorrent.infoHash
1014 }
e4f97bab 1015
3fd3ab2d
C
1016 getEmbedPath () {
1017 return '/videos/embed/' + this.uuid
1018 }
e4f97bab 1019
3fd3ab2d
C
1020 getThumbnailPath () {
1021 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
e4f97bab 1022 }
227d02fe 1023
3fd3ab2d
C
1024 getPreviewPath () {
1025 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1026 }
40298b02 1027
2422c46b 1028 toFormattedJSON (): Video {
b64c950a 1029 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
0f320037 1030 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
14d3270f 1031
3fd3ab2d
C
1032 return {
1033 id: this.id,
1034 uuid: this.uuid,
1035 name: this.name,
ae5a3dd6
C
1036 category: {
1037 id: this.category,
1038 label: VideoModel.getCategoryLabel(this.category)
1039 },
1040 licence: {
1041 id: this.licence,
1042 label: VideoModel.getLicenceLabel(this.licence)
1043 },
1044 language: {
1045 id: this.language,
1046 label: VideoModel.getLanguageLabel(this.language)
1047 },
2243730c
C
1048 privacy: {
1049 id: this.privacy,
1050 label: VideoModel.getPrivacyLabel(this.privacy)
1051 },
3fd3ab2d
C
1052 nsfw: this.nsfw,
1053 description: this.getTruncatedDescription(),
3fd3ab2d 1054 isLocal: this.isOwned(),
3fd3ab2d
C
1055 duration: this.duration,
1056 views: this.views,
1057 likes: this.likes,
1058 dislikes: this.dislikes,
3fd3ab2d
C
1059 thumbnailPath: this.getThumbnailPath(),
1060 previewPath: this.getPreviewPath(),
1061 embedPath: this.getEmbedPath(),
1062 createdAt: this.createdAt,
b64c950a 1063 updatedAt: this.updatedAt,
2922e048 1064 publishedAt: this.publishedAt,
b64c950a 1065 account: {
03e12d7c
C
1066 id: formattedAccount.id,
1067 uuid: formattedAccount.uuid,
b64c950a
C
1068 name: formattedAccount.name,
1069 displayName: formattedAccount.displayName,
1070 url: formattedAccount.url,
1071 host: formattedAccount.host,
1072 avatar: formattedAccount.avatar
0f320037
C
1073 },
1074 channel: {
1075 id: formattedVideoChannel.id,
1076 uuid: formattedVideoChannel.uuid,
1077 name: formattedVideoChannel.name,
1078 displayName: formattedVideoChannel.displayName,
1079 url: formattedVideoChannel.url,
1080 host: formattedVideoChannel.host,
1081 avatar: formattedVideoChannel.avatar
b64c950a 1082 }
2422c46b 1083 }
14d3270f 1084 }
14d3270f 1085
2422c46b 1086 toFormattedDetailsJSON (): VideoDetails {
3fd3ab2d 1087 const formattedJson = this.toFormattedJSON()
e4f97bab 1088
3fd3ab2d 1089 const detailsJson = {
2422c46b 1090 support: this.support,
3fd3ab2d
C
1091 descriptionPath: this.getDescriptionPath(),
1092 channel: this.VideoChannel.toFormattedJSON(),
1093 account: this.VideoChannel.Account.toFormattedJSON(),
ee28cdf1 1094 tags: map(this.Tags, 'name'),
47564bbe 1095 commentsEnabled: this.commentsEnabled,
3fd3ab2d
C
1096 files: []
1097 }
e4f97bab 1098
3fd3ab2d 1099 // Format and sort video files
244e76a5
RK
1100 detailsJson.files = this.getFormattedVideoFilesJSON()
1101
1102 return Object.assign(formattedJson, detailsJson)
1103 }
1104
1105 getFormattedVideoFilesJSON (): VideoFile[] {
3fd3ab2d 1106 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
3fd3ab2d 1107
244e76a5
RK
1108 return this.VideoFiles
1109 .map(videoFile => {
1110 let resolutionLabel = videoFile.resolution + 'p'
3fd3ab2d 1111
244e76a5
RK
1112 return {
1113 resolution: {
1114 id: videoFile.resolution,
1115 label: resolutionLabel
1116 },
1117 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1118 size: videoFile.size,
1119 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
02756fbd
C
1120 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1121 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1122 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
244e76a5
RK
1123 } as VideoFile
1124 })
1125 .sort((a, b) => {
1126 if (a.resolution.id < b.resolution.id) return 1
1127 if (a.resolution.id === b.resolution.id) return 0
1128 return -1
1129 })
3fd3ab2d 1130 }
e4f97bab 1131
3fd3ab2d
C
1132 toActivityPubObject (): VideoTorrentObject {
1133 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1134 if (!this.Tags) this.Tags = []
e4f97bab 1135
3fd3ab2d
C
1136 const tag = this.Tags.map(t => ({
1137 type: 'Hashtag' as 'Hashtag',
1138 name: t.name
1139 }))
40298b02 1140
3fd3ab2d
C
1141 let language
1142 if (this.language) {
1143 language = {
9d3ef9fe 1144 identifier: this.language,
ae5a3dd6 1145 name: VideoModel.getLanguageLabel(this.language)
3fd3ab2d
C
1146 }
1147 }
40298b02 1148
3fd3ab2d
C
1149 let category
1150 if (this.category) {
1151 category = {
1152 identifier: this.category + '',
ae5a3dd6 1153 name: VideoModel.getCategoryLabel(this.category)
3fd3ab2d
C
1154 }
1155 }
40298b02 1156
3fd3ab2d
C
1157 let licence
1158 if (this.licence) {
1159 licence = {
1160 identifier: this.licence + '',
ae5a3dd6 1161 name: VideoModel.getLicenceLabel(this.licence)
3fd3ab2d
C
1162 }
1163 }
9567011b 1164
3fd3ab2d
C
1165 const url = []
1166 for (const file of this.VideoFiles) {
1167 url.push({
1168 type: 'Link',
1169 mimeType: 'video/' + file.extname.replace('.', ''),
9fb3abfd 1170 href: this.getVideoFileUrl(file, baseUrlHttp),
3fd3ab2d
C
1171 width: file.resolution,
1172 size: file.size
1173 })
1174
1175 url.push({
1176 type: 'Link',
1177 mimeType: 'application/x-bittorrent',
9fb3abfd 1178 href: this.getTorrentUrl(file, baseUrlHttp),
3fd3ab2d
C
1179 width: file.resolution
1180 })
1181
1182 url.push({
1183 type: 'Link',
1184 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
9fb3abfd 1185 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
3fd3ab2d
C
1186 width: file.resolution
1187 })
1188 }
93e1258c 1189
3fd3ab2d
C
1190 // Add video url too
1191 url.push({
1192 type: 'Link',
1193 mimeType: 'text/html',
9fb3abfd 1194 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
3fd3ab2d 1195 })
93e1258c 1196
3fd3ab2d
C
1197 return {
1198 type: 'Video' as 'Video',
1199 id: this.url,
1200 name: this.name,
093237cf 1201 duration: this.getActivityStreamDuration(),
3fd3ab2d
C
1202 uuid: this.uuid,
1203 tag,
1204 category,
1205 licence,
1206 language,
1207 views: this.views,
0a67e28b 1208 sensitive: this.nsfw,
47564bbe 1209 commentsEnabled: this.commentsEnabled,
2922e048 1210 published: this.publishedAt.toISOString(),
3fd3ab2d
C
1211 updated: this.updatedAt.toISOString(),
1212 mediaType: 'text/markdown',
1213 content: this.getTruncatedDescription(),
2422c46b 1214 support: this.support,
3fd3ab2d
C
1215 icon: {
1216 type: 'Image',
1217 url: this.getThumbnailUrl(baseUrlHttp),
1218 mediaType: 'image/jpeg',
1219 width: THUMBNAILS_SIZE.width,
1220 height: THUMBNAILS_SIZE.height
1221 },
1222 url,
8fffe21a
C
1223 likes: getVideoLikesActivityPubUrl(this),
1224 dislikes: getVideoDislikesActivityPubUrl(this),
1225 shares: getVideoSharesActivityPubUrl(this),
1226 comments: getVideoCommentsActivityPubUrl(this),
50d6de9c 1227 attributedTo: [
2ccaeeb3
C
1228 {
1229 type: 'Person',
1230 id: this.VideoChannel.Account.Actor.url
fc27b17c
C
1231 },
1232 {
1233 type: 'Group',
1234 id: this.VideoChannel.Actor.url
50d6de9c
C
1235 }
1236 ]
3fd3ab2d
C
1237 }
1238 }
1239
1240 getTruncatedDescription () {
1241 if (!this.description) return null
93e1258c 1242
bffbebbe 1243 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
c73e83da 1244 return peertubeTruncate(this.description, maxLength)
93e1258c
C
1245 }
1246
81e504b3 1247 async optimizeOriginalVideofile () {
3fd3ab2d
C
1248 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1249 const newExtname = '.mp4'
1250 const inputVideoFile = this.getOriginalFile()
1251 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1252 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
b769007f 1253
3fd3ab2d
C
1254 const transcodeOptions = {
1255 inputPath: videoInputPath,
1256 outputPath: videoOutputPath
1257 }
c46edbc2 1258
b0ef1782
C
1259 // Could be very long!
1260 await transcode(transcodeOptions)
c46edbc2 1261
b0ef1782 1262 try {
3fd3ab2d 1263 await unlinkPromise(videoInputPath)
c46edbc2 1264
3fd3ab2d
C
1265 // Important to do this before getVideoFilename() to take in account the new file extension
1266 inputVideoFile.set('extname', newExtname)
e71bcc0f 1267
3fd3ab2d
C
1268 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1269 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
e71bcc0f 1270
3fd3ab2d 1271 inputVideoFile.set('size', stats.size)
e71bcc0f 1272
3fd3ab2d
C
1273 await this.createTorrentAndSetInfoHash(inputVideoFile)
1274 await inputVideoFile.save()
fd45e8f4 1275
3fd3ab2d
C
1276 } catch (err) {
1277 // Auto destruction...
d5b7d911 1278 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
fd45e8f4 1279
3fd3ab2d
C
1280 throw err
1281 }
feb4bdfd
C
1282 }
1283
81e504b3 1284 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
3fd3ab2d
C
1285 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1286 const extname = '.mp4'
aaf61f38 1287
3fd3ab2d
C
1288 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1289 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
feb4bdfd 1290
3fd3ab2d
C
1291 const newVideoFile = new VideoFileModel({
1292 resolution,
1293 extname,
1294 size: 0,
1295 videoId: this.id
1296 })
1297 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
a041b171 1298
3fd3ab2d
C
1299 const transcodeOptions = {
1300 inputPath: videoInputPath,
1301 outputPath: videoOutputPath,
056aa7f2
C
1302 resolution,
1303 isPortraitMode
3fd3ab2d 1304 }
a041b171 1305
3fd3ab2d 1306 await transcode(transcodeOptions)
a041b171 1307
3fd3ab2d 1308 const stats = await statPromise(videoOutputPath)
d7d5611c 1309
3fd3ab2d 1310 newVideoFile.set('size', stats.size)
d7d5611c 1311
3fd3ab2d 1312 await this.createTorrentAndSetInfoHash(newVideoFile)
d7d5611c 1313
3fd3ab2d
C
1314 await newVideoFile.save()
1315
1316 this.VideoFiles.push(newVideoFile)
0d0e8dd0
C
1317 }
1318
0138af92
FF
1319 async importVideoFile (inputFilePath: string) {
1320 let updatedVideoFile = new VideoFileModel({
1321 resolution: (await getVideoFileResolution(inputFilePath)).videoFileResolution,
1322 extname: extname(inputFilePath),
1323 size: (await statPromise(inputFilePath)).size,
1324 videoId: this.id
1325 })
1326
1327 const outputPath = this.getVideoFilePath(updatedVideoFile)
1328 await copyFilePromise(inputFilePath, outputPath)
1329
1330 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
1331 const isNewVideoFile = !currentVideoFile
1332
1333 if (!isNewVideoFile) {
1334 if (currentVideoFile.extname !== updatedVideoFile.extname) {
1335 await this.removeFile(currentVideoFile)
1336 currentVideoFile.set('extname', updatedVideoFile.extname)
1337 }
1338 currentVideoFile.set('size', updatedVideoFile.size)
1339 updatedVideoFile = currentVideoFile
1340 }
1341
1342 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1343
1344 await updatedVideoFile.save()
1345
1346 if (isNewVideoFile) {
1347 this.VideoFiles.push(updatedVideoFile)
1348 }
1349 }
1350
056aa7f2 1351 getOriginalFileResolution () {
3fd3ab2d 1352 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
0d0e8dd0 1353
056aa7f2 1354 return getVideoFileResolution(originalFilePath)
3fd3ab2d 1355 }
0d0e8dd0 1356
3fd3ab2d
C
1357 getDescriptionPath () {
1358 return `/api/${API_VERSION}/videos/${this.uuid}/description`
feb4bdfd
C
1359 }
1360
3fd3ab2d
C
1361 removeThumbnail () {
1362 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1363 return unlinkPromise(thumbnailPath)
feb4bdfd
C
1364 }
1365
3fd3ab2d
C
1366 removePreview () {
1367 // Same name than video thumbnail
1368 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
7920c273
C
1369 }
1370
3fd3ab2d
C
1371 removeFile (videoFile: VideoFileModel) {
1372 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1373 return unlinkPromise(filePath)
feb4bdfd
C
1374 }
1375
3fd3ab2d
C
1376 removeTorrent (videoFile: VideoFileModel) {
1377 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1378 return unlinkPromise(torrentPath)
aaf61f38
C
1379 }
1380
093237cf
C
1381 getActivityStreamDuration () {
1382 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1383 return 'PT' + this.duration + 'S'
1384 }
1385
3fd3ab2d
C
1386 private getBaseUrls () {
1387 let baseUrlHttp
1388 let baseUrlWs
7920c273 1389
3fd3ab2d
C
1390 if (this.isOwned()) {
1391 baseUrlHttp = CONFIG.WEBSERVER.URL
1392 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1393 } else {
50d6de9c
C
1394 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1395 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
6fcd19ba 1396 }
aaf61f38 1397
3fd3ab2d 1398 return { baseUrlHttp, baseUrlWs }
15d4ee04 1399 }
a96aed15 1400
3fd3ab2d
C
1401 private getThumbnailUrl (baseUrlHttp: string) {
1402 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
a96aed15
C
1403 }
1404
3fd3ab2d
C
1405 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1406 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1407 }
e4f97bab 1408
02756fbd
C
1409 private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1410 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1411 }
1412
3fd3ab2d
C
1413 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1414 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1415 }
a96aed15 1416
02756fbd
C
1417 private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1418 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1419 }
1420
3fd3ab2d
C
1421 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1422 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1423 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1424 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1425
1426 const magnetHash = {
1427 xs,
1428 announce,
1429 urlList,
1430 infoHash: videoFile.infoHash,
1431 name: this.name
1432 }
a96aed15 1433
3fd3ab2d 1434 return magnetUtil.encode(magnetHash)
a96aed15 1435 }
a96aed15 1436}