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