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