]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video/video.ts
Fix sharedInboxUrl list
[github/Chocobozzz/PeerTube.git] / server / models / video / video.ts
CommitLineData
39445ead 1import * as Bluebird from 'bluebird'
53abc4c2 2import { map, maxBy, truncate } 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 {
da854ddd
C
8 AfterDestroy, AllowNull, BelongsTo, BelongsToMany, Column, CreatedAt, DataType, Default, ForeignKey, HasMany, IFindOptions, Is,
9 IsInt, IsUUID, Min, Model, Scopes, Table, UpdatedAt
3fd3ab2d
C
10} from 'sequelize-typescript'
11import { IIncludeOptions } from 'sequelize-typescript/lib/interfaces/IIncludeOptions'
571389d4 12import { VideoPrivacy, VideoResolution } from '../../../shared'
3fd3ab2d 13import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
d48ff09d 14import { Video, VideoDetails } from '../../../shared/models/videos'
da854ddd
C
15import { activityPubCollection } from '../../helpers/activitypub'
16import { createTorrentPromise, renamePromise, statPromise, unlinkPromise, writeFilePromise } from '../../helpers/core-utils'
17import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
47564bbe 18import { isBooleanValid } from '../../helpers/custom-validators/misc'
3fd3ab2d 19import {
da854ddd 20 isVideoCategoryValid, isVideoDescriptionValid, isVideoDurationValid, isVideoLanguageValid, isVideoLicenceValid, isVideoNameValid,
47564bbe 21 isVideoPrivacyValid
3fd3ab2d 22} from '../../helpers/custom-validators/videos'
da854ddd
C
23import { generateImageFromVideoFile, getVideoFileHeight, transcode } from '../../helpers/ffmpeg-utils'
24import { logger } from '../../helpers/logger'
65fcc311 25import {
da854ddd
C
26 API_VERSION, CONFIG, CONSTRAINTS_FIELDS, PREVIEWS_SIZE, REMOTE_SCHEME, STATIC_PATHS, THUMBNAILS_SIZE, VIDEO_CATEGORIES,
27 VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES
3fd3ab2d
C
28} from '../../initializers'
29import { getAnnounceActivityPubUrl } from '../../lib/activitypub'
50d6de9c 30import { sendDeleteVideo } from '../../lib/activitypub/send'
3fd3ab2d
C
31import { AccountModel } from '../account/account'
32import { AccountVideoRateModel } from '../account/account-video-rate'
50d6de9c 33import { ActorModel } from '../activitypub/actor'
3fd3ab2d
C
34import { ServerModel } from '../server/server'
35import { getSort, throwIfNotValid } from '../utils'
36import { TagModel } from './tag'
37import { VideoAbuseModel } from './video-abuse'
38import { VideoChannelModel } from './video-channel'
da854ddd 39import { VideoCommentModel } from './video-comment'
3fd3ab2d
C
40import { VideoFileModel } from './video-file'
41import { VideoShareModel } from './video-share'
42import { VideoTagModel } from './video-tag'
43
d48ff09d 44enum ScopeNames {
50d6de9c 45 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
4cb6d457
C
46 WITH_ACCOUNT_API = 'WITH_ACCOUNT_API',
47 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
d48ff09d
C
48 WITH_TAGS = 'WITH_TAGS',
49 WITH_FILES = 'WITH_FILES',
50 WITH_SHARES = 'WITH_SHARES',
da854ddd
C
51 WITH_RATES = 'WITH_RATES',
52 WITH_COMMENTS = 'WITH_COMMENTS'
d48ff09d
C
53}
54
55@Scopes({
50d6de9c 56 [ScopeNames.AVAILABLE_FOR_LIST]: {
d48ff09d
C
57 where: {
58 id: {
59 [Sequelize.Op.notIn]: Sequelize.literal(
60 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
61 )
50d6de9c 62 },
d48ff09d
C
63 privacy: VideoPrivacy.PUBLIC
64 }
65 },
4cb6d457
C
66 [ScopeNames.WITH_ACCOUNT_API]: {
67 include: [
68 {
69 model: () => VideoChannelModel.unscoped(),
70 required: true,
71 include: [
72 {
73 attributes: [ 'name' ],
74 model: () => AccountModel.unscoped(),
75 required: true,
76 include: [
77 {
78 attributes: [ 'serverId' ],
79 model: () => ActorModel.unscoped(),
80 required: true,
81 include: [
82 {
83 model: () => ServerModel.unscoped(),
84 required: false
85 }
86 ]
87 }
88 ]
89 }
90 ]
91 }
92 ]
93 },
94 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
d48ff09d
C
95 include: [
96 {
97 model: () => VideoChannelModel,
98 required: true,
99 include: [
100 {
101 model: () => AccountModel,
102 required: true,
103 include: [
104 {
50d6de9c
C
105 model: () => ActorModel,
106 required: true,
107 include: [
108 {
109 model: () => ServerModel,
110 required: false
111 }
112 ]
d48ff09d
C
113 }
114 ]
115 }
116 ]
117 }
118 ]
119 },
120 [ScopeNames.WITH_TAGS]: {
121 include: [ () => TagModel ]
122 },
123 [ScopeNames.WITH_FILES]: {
124 include: [
125 {
126 model: () => VideoFileModel,
127 required: true
128 }
129 ]
130 },
131 [ScopeNames.WITH_SHARES]: {
132 include: [
133 {
134 model: () => VideoShareModel,
50d6de9c 135 include: [ () => ActorModel ]
d48ff09d
C
136 }
137 ]
138 },
139 [ScopeNames.WITH_RATES]: {
140 include: [
141 {
142 model: () => AccountVideoRateModel,
143 include: [ () => AccountModel ]
144 }
145 ]
da854ddd
C
146 },
147 [ScopeNames.WITH_COMMENTS]: {
148 include: [
149 {
150 model: () => VideoCommentModel
151 }
152 ]
d48ff09d
C
153 }
154})
3fd3ab2d
C
155@Table({
156 tableName: 'video',
157 indexes: [
feb4bdfd 158 {
3fd3ab2d 159 fields: [ 'name' ]
feb4bdfd
C
160 },
161 {
3fd3ab2d
C
162 fields: [ 'createdAt' ]
163 },
164 {
165 fields: [ 'duration' ]
166 },
167 {
168 fields: [ 'views' ]
169 },
170 {
171 fields: [ 'likes' ]
172 },
173 {
174 fields: [ 'uuid' ]
175 },
176 {
177 fields: [ 'channelId' ]
4cb6d457
C
178 },
179 {
180 fields: [ 'id', 'privacy' ]
feb4bdfd 181 }
e02643f3 182 ]
3fd3ab2d
C
183})
184export class VideoModel extends Model<VideoModel> {
185
186 @AllowNull(false)
187 @Default(DataType.UUIDV4)
188 @IsUUID(4)
189 @Column(DataType.UUID)
190 uuid: string
191
192 @AllowNull(false)
193 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
194 @Column
195 name: string
196
197 @AllowNull(true)
198 @Default(null)
199 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
200 @Column
201 category: number
202
203 @AllowNull(true)
204 @Default(null)
205 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
206 @Column
207 licence: number
208
209 @AllowNull(true)
210 @Default(null)
211 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
212 @Column
213 language: number
214
215 @AllowNull(false)
216 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
217 @Column
218 privacy: number
219
220 @AllowNull(false)
47564bbe 221 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
3fd3ab2d
C
222 @Column
223 nsfw: boolean
224
225 @AllowNull(true)
226 @Default(null)
227 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
228 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
229 description: string
230
231 @AllowNull(false)
232 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
233 @Column
234 duration: number
235
236 @AllowNull(false)
237 @Default(0)
238 @IsInt
239 @Min(0)
240 @Column
241 views: number
242
243 @AllowNull(false)
244 @Default(0)
245 @IsInt
246 @Min(0)
247 @Column
248 likes: number
249
250 @AllowNull(false)
251 @Default(0)
252 @IsInt
253 @Min(0)
254 @Column
255 dislikes: number
256
257 @AllowNull(false)
258 @Column
259 remote: boolean
260
261 @AllowNull(false)
262 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
263 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
264 url: string
265
47564bbe
C
266 @AllowNull(false)
267 @Column
268 commentsEnabled: boolean
269
3fd3ab2d
C
270 @CreatedAt
271 createdAt: Date
272
273 @UpdatedAt
274 updatedAt: Date
275
276 @ForeignKey(() => VideoChannelModel)
277 @Column
278 channelId: number
279
280 @BelongsTo(() => VideoChannelModel, {
feb4bdfd 281 foreignKey: {
50d6de9c 282 allowNull: true
feb4bdfd
C
283 },
284 onDelete: 'cascade'
285 })
3fd3ab2d 286 VideoChannel: VideoChannelModel
7920c273 287
3fd3ab2d 288 @BelongsToMany(() => TagModel, {
7920c273 289 foreignKey: 'videoId',
3fd3ab2d
C
290 through: () => VideoTagModel,
291 onDelete: 'CASCADE'
7920c273 292 })
3fd3ab2d 293 Tags: TagModel[]
55fa55a9 294
3fd3ab2d 295 @HasMany(() => VideoAbuseModel, {
55fa55a9
C
296 foreignKey: {
297 name: 'videoId',
298 allowNull: false
299 },
300 onDelete: 'cascade'
301 })
3fd3ab2d 302 VideoAbuses: VideoAbuseModel[]
93e1258c 303
3fd3ab2d 304 @HasMany(() => VideoFileModel, {
93e1258c
C
305 foreignKey: {
306 name: 'videoId',
307 allowNull: false
308 },
309 onDelete: 'cascade'
310 })
3fd3ab2d 311 VideoFiles: VideoFileModel[]
e71bcc0f 312
3fd3ab2d 313 @HasMany(() => VideoShareModel, {
e71bcc0f
C
314 foreignKey: {
315 name: 'videoId',
316 allowNull: false
317 },
318 onDelete: 'cascade'
319 })
3fd3ab2d 320 VideoShares: VideoShareModel[]
16b90975 321
3fd3ab2d 322 @HasMany(() => AccountVideoRateModel, {
16b90975
C
323 foreignKey: {
324 name: 'videoId',
325 allowNull: false
326 },
327 onDelete: 'cascade'
328 })
3fd3ab2d 329 AccountVideoRates: AccountVideoRateModel[]
f285faa0 330
da854ddd
C
331 @HasMany(() => VideoCommentModel, {
332 foreignKey: {
333 name: 'videoId',
334 allowNull: false
335 },
336 onDelete: 'cascade'
337 })
338 VideoComments: VideoCommentModel[]
339
3fd3ab2d
C
340 @AfterDestroy
341 static removeFilesAndSendDelete (instance: VideoModel) {
342 const tasks = []
f285faa0 343
93e1258c 344 tasks.push(
3fd3ab2d 345 instance.removeThumbnail()
93e1258c
C
346 )
347
3fd3ab2d
C
348 if (instance.isOwned()) {
349 tasks.push(
350 instance.removePreview(),
351 sendDeleteVideo(instance, undefined)
352 )
40298b02 353
3fd3ab2d
C
354 // Remove physical files and torrents
355 instance.VideoFiles.forEach(file => {
356 tasks.push(instance.removeFile(file))
357 tasks.push(instance.removeTorrent(file))
358 })
359 }
40298b02 360
3fd3ab2d
C
361 return Promise.all(tasks)
362 .catch(err => {
363 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, err)
364 })
365 }
f285faa0 366
3fd3ab2d 367 static list () {
d48ff09d 368 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
3fd3ab2d 369 }
f285faa0 370
50d6de9c 371 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
3fd3ab2d
C
372 function getRawQuery (select: string) {
373 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
374 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
50d6de9c
C
375 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
376 'WHERE "Account"."actorId" = ' + actorId
3fd3ab2d
C
377 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
378 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
50d6de9c 379 'WHERE "VideoShare"."actorId" = ' + actorId
558d7c23 380
3fd3ab2d
C
381 return `(${queryVideo}) UNION (${queryVideoShare})`
382 }
aaf61f38 383
3fd3ab2d
C
384 const rawQuery = getRawQuery('"Video"."id"')
385 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
386
387 const query = {
388 distinct: true,
389 offset: start,
390 limit: count,
391 order: [ getSort('createdAt'), [ 'Tags', 'name', 'ASC' ] ],
392 where: {
393 id: {
394 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
395 }
396 },
397 include: [
398 {
399 model: VideoShareModel,
400 required: false,
401 where: {
402 [Sequelize.Op.and]: [
403 {
404 id: {
405 [Sequelize.Op.not]: null
406 }
407 },
408 {
50d6de9c 409 actorId
3fd3ab2d
C
410 }
411 ]
412 },
50d6de9c
C
413 include: [
414 {
415 model: ActorModel,
416 required: true
417 }
418 ]
3fd3ab2d
C
419 },
420 {
421 model: VideoChannelModel,
422 required: true,
423 include: [
424 {
425 model: AccountModel,
426 required: true
427 }
428 ]
429 },
430 {
431 model: AccountVideoRateModel,
432 include: [ AccountModel ]
433 },
434 VideoFileModel,
da854ddd
C
435 TagModel,
436 VideoCommentModel
3fd3ab2d
C
437 ]
438 }
164174a6 439
3fd3ab2d
C
440 return Bluebird.all([
441 // FIXME: typing issue
442 VideoModel.findAll(query as any),
443 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
444 ]).then(([ rows, totals ]) => {
445 // totals: totalVideos + totalVideoShares
446 let totalVideos = 0
447 let totalVideoShares = 0
448 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
449 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
450
451 const total = totalVideos + totalVideoShares
452 return {
453 data: rows,
454 total: total
455 }
456 })
457 }
93e1258c 458
3fd3ab2d
C
459 static listUserVideosForApi (userId: number, start: number, count: number, sort: string) {
460 const query = {
3fd3ab2d
C
461 offset: start,
462 limit: count,
d48ff09d 463 order: [ getSort(sort) ],
3fd3ab2d
C
464 include: [
465 {
466 model: VideoChannelModel,
467 required: true,
468 include: [
469 {
470 model: AccountModel,
471 where: {
472 userId
473 },
474 required: true
475 }
476 ]
d48ff09d 477 }
3fd3ab2d
C
478 ]
479 }
d8755eed 480
3fd3ab2d
C
481 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
482 return {
483 data: rows,
484 total: count
485 }
486 })
487 }
93e1258c 488
3fd3ab2d
C
489 static listForApi (start: number, count: number, sort: string) {
490 const query = {
3fd3ab2d
C
491 offset: start,
492 limit: count,
d48ff09d 493 order: [ getSort(sort) ]
3fd3ab2d 494 }
93e1258c 495
4cb6d457 496 return VideoModel.scope([ ScopeNames.AVAILABLE_FOR_LIST, ScopeNames.WITH_ACCOUNT_API ])
d48ff09d
C
497 .findAndCountAll(query)
498 .then(({ rows, count }) => {
499 return {
500 data: rows,
501 total: count
502 }
503 })
93e1258c
C
504 }
505
3fd3ab2d
C
506 static load (id: number) {
507 return VideoModel.findById(id)
508 }
fdbda9e3 509
378557ef
C
510 static loadAndPopulateAccount (id: number) {
511 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS ]).findById(id)
512 }
513
6d852470
C
514 static loadByUrl (url: string, t?: Sequelize.Transaction) {
515 const query: IFindOptions<VideoModel> = {
516 where: {
517 url
518 }
519 }
520
521 if (t !== undefined) query.transaction = t
522
523 return VideoModel.findOne(query)
524 }
525
3fd3ab2d
C
526 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
527 const query: IFindOptions<VideoModel> = {
528 where: {
529 url
d48ff09d 530 }
3fd3ab2d 531 }
d8755eed 532
3fd3ab2d 533 if (t !== undefined) query.transaction = t
d8755eed 534
4cb6d457 535 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
3fd3ab2d 536 }
d8755eed 537
3fd3ab2d
C
538 static loadByUUIDOrURL (uuid: string, url: string, t?: Sequelize.Transaction) {
539 const query: IFindOptions<VideoModel> = {
540 where: {
541 [Sequelize.Op.or]: [
542 { uuid },
543 { url }
544 ]
d48ff09d 545 }
3fd3ab2d 546 }
feb4bdfd 547
3fd3ab2d 548 if (t !== undefined) query.transaction = t
feb4bdfd 549
d48ff09d 550 return VideoModel.scope(ScopeNames.WITH_FILES).findOne(query)
72c7248b
C
551 }
552
3fd3ab2d
C
553 static loadAndPopulateAccountAndServerAndTags (id: number) {
554 const options = {
d48ff09d 555 order: [ [ 'Tags', 'name', 'ASC' ] ]
3fd3ab2d 556 }
72c7248b 557
d48ff09d 558 return VideoModel
4cb6d457 559 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
d48ff09d 560 .findById(id, options)
3fd3ab2d 561 }
72c7248b 562
8fa5653a
C
563 static loadByUUID (uuid: string) {
564 const options = {
565 where: {
566 uuid
567 }
568 }
569
570 return VideoModel
571 .scope([ ScopeNames.WITH_FILES ])
572 .findOne(options)
573 }
574
3fd3ab2d
C
575 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
576 const options = {
577 order: [ [ 'Tags', 'name', 'ASC' ] ],
578 where: {
579 uuid
d48ff09d 580 }
3fd3ab2d 581 }
fd45e8f4 582
d48ff09d 583 return VideoModel
4cb6d457 584 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
da854ddd
C
585 .findOne(options)
586 }
587
588 static loadAndPopulateAll (id: number) {
589 const options = {
590 order: [ [ 'Tags', 'name', 'ASC' ] ],
591 where: {
592 id
593 }
594 }
595
596 return VideoModel
597 .scope([
598 ScopeNames.WITH_RATES,
599 ScopeNames.WITH_SHARES,
600 ScopeNames.WITH_TAGS,
601 ScopeNames.WITH_FILES,
4cb6d457 602 ScopeNames.WITH_ACCOUNT_DETAILS,
da854ddd
C
603 ScopeNames.WITH_COMMENTS
604 ])
d48ff09d 605 .findOne(options)
aaf61f38
C
606 }
607
3fd3ab2d
C
608 static searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) {
609 const serverInclude: IIncludeOptions = {
610 model: ServerModel,
611 required: false
612 }
aaf61f38 613
3fd3ab2d
C
614 const accountInclude: IIncludeOptions = {
615 model: AccountModel,
50d6de9c
C
616 include: [
617 {
618 model: ActorModel,
619 required: true,
620 include: [ serverInclude ]
621 }
622 ]
3fd3ab2d 623 }
e4f97bab 624
3fd3ab2d
C
625 const videoChannelInclude: IIncludeOptions = {
626 model: VideoChannelModel,
627 include: [ accountInclude ],
628 required: true
40ff5707 629 }
40ff5707 630
3fd3ab2d
C
631 const tagInclude: IIncludeOptions = {
632 model: TagModel
f595d394 633 }
f595d394 634
3fd3ab2d 635 const query: IFindOptions<VideoModel> = {
d48ff09d 636 distinct: true, // Because we have tags
3fd3ab2d
C
637 offset: start,
638 limit: count,
d48ff09d
C
639 order: [ getSort(sort) ],
640 where: {}
f595d394 641 }
f595d394 642
3fd3ab2d
C
643 // TODO: search on tags too
644 // const escapedValue = Video['sequelize'].escape('%' + value + '%')
645 // query.where['id'][Sequelize.Op.in] = Video['sequelize'].literal(
646 // `(SELECT "VideoTags"."videoId"
647 // FROM "Tags"
648 // INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId"
649 // WHERE name ILIKE ${escapedValue}
650 // )`
651 // )
652
653 // TODO: search on account too
654 // accountInclude.where = {
655 // name: {
656 // [Sequelize.Op.iLike]: '%' + value + '%'
657 // }
658 // }
659 query.where['name'] = {
660 [Sequelize.Op.iLike]: '%' + value + '%'
661 }
16b90975 662
3fd3ab2d
C
663 query.include = [
664 videoChannelInclude, tagInclude
665 ]
16b90975 666
50d6de9c 667 return VideoModel.scope([ ScopeNames.AVAILABLE_FOR_LIST ])
d48ff09d
C
668 .findAndCountAll(query).then(({ rows, count }) => {
669 return {
670 data: rows,
671 total: count
672 }
673 })
4e50b6a1
C
674 }
675
3fd3ab2d
C
676 getOriginalFile () {
677 if (Array.isArray(this.VideoFiles) === false) return undefined
aaf61f38 678
3fd3ab2d
C
679 // The original file is the file that have the higher resolution
680 return maxBy(this.VideoFiles, file => file.resolution)
e4f97bab 681 }
aaf61f38 682
3fd3ab2d
C
683 getVideoFilename (videoFile: VideoFileModel) {
684 return this.uuid + '-' + videoFile.resolution + videoFile.extname
685 }
165cdc75 686
3fd3ab2d
C
687 getThumbnailName () {
688 // We always have a copy of the thumbnail
689 const extension = '.jpg'
690 return this.uuid + extension
7b1f49de
C
691 }
692
3fd3ab2d
C
693 getPreviewName () {
694 const extension = '.jpg'
695 return this.uuid + extension
696 }
7b1f49de 697
3fd3ab2d
C
698 getTorrentFileName (videoFile: VideoFileModel) {
699 const extension = '.torrent'
700 return this.uuid + '-' + videoFile.resolution + extension
701 }
8e7f08b5 702
3fd3ab2d
C
703 isOwned () {
704 return this.remote === false
9567011b
C
705 }
706
3fd3ab2d
C
707 createPreview (videoFile: VideoFileModel) {
708 const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height
709
710 return generateImageFromVideoFile(
711 this.getVideoFilePath(videoFile),
712 CONFIG.STORAGE.PREVIEWS_DIR,
713 this.getPreviewName(),
714 imageSize
715 )
716 }
9567011b 717
3fd3ab2d
C
718 createThumbnail (videoFile: VideoFileModel) {
719 const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height
227d02fe 720
3fd3ab2d
C
721 return generateImageFromVideoFile(
722 this.getVideoFilePath(videoFile),
723 CONFIG.STORAGE.THUMBNAILS_DIR,
724 this.getThumbnailName(),
725 imageSize
726 )
14d3270f
C
727 }
728
3fd3ab2d
C
729 getVideoFilePath (videoFile: VideoFileModel) {
730 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
731 }
14d3270f 732
3fd3ab2d
C
733 createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) {
734 const options = {
735 announceList: [
736 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
737 ],
738 urlList: [
739 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
740 ]
741 }
14d3270f 742
3fd3ab2d 743 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
e4f97bab 744
3fd3ab2d
C
745 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
746 logger.info('Creating torrent %s.', filePath)
e4f97bab 747
3fd3ab2d 748 await writeFilePromise(filePath, torrent)
e4f97bab 749
3fd3ab2d
C
750 const parsedTorrent = parseTorrent(torrent)
751 videoFile.infoHash = parsedTorrent.infoHash
752 }
e4f97bab 753
3fd3ab2d
C
754 getEmbedPath () {
755 return '/videos/embed/' + this.uuid
756 }
e4f97bab 757
3fd3ab2d
C
758 getThumbnailPath () {
759 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
e4f97bab 760 }
227d02fe 761
3fd3ab2d
C
762 getPreviewPath () {
763 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
764 }
40298b02 765
3fd3ab2d
C
766 toFormattedJSON () {
767 let serverHost
40298b02 768
50d6de9c
C
769 if (this.VideoChannel.Account.Actor.Server) {
770 serverHost = this.VideoChannel.Account.Actor.Server.host
3fd3ab2d
C
771 } else {
772 // It means it's our video
773 serverHost = CONFIG.WEBSERVER.HOST
774 }
14d3270f 775
3fd3ab2d
C
776 return {
777 id: this.id,
778 uuid: this.uuid,
779 name: this.name,
780 category: this.category,
781 categoryLabel: this.getCategoryLabel(),
782 licence: this.licence,
783 licenceLabel: this.getLicenceLabel(),
784 language: this.language,
785 languageLabel: this.getLanguageLabel(),
786 nsfw: this.nsfw,
787 description: this.getTruncatedDescription(),
788 serverHost,
789 isLocal: this.isOwned(),
790 accountName: this.VideoChannel.Account.name,
791 duration: this.duration,
792 views: this.views,
793 likes: this.likes,
794 dislikes: this.dislikes,
3fd3ab2d
C
795 thumbnailPath: this.getThumbnailPath(),
796 previewPath: this.getPreviewPath(),
797 embedPath: this.getEmbedPath(),
798 createdAt: this.createdAt,
799 updatedAt: this.updatedAt
d48ff09d 800 } as Video
14d3270f 801 }
14d3270f 802
3fd3ab2d
C
803 toFormattedDetailsJSON () {
804 const formattedJson = this.toFormattedJSON()
e4f97bab 805
3fd3ab2d
C
806 // Maybe our server is not up to date and there are new privacy settings since our version
807 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
808 if (!privacyLabel) privacyLabel = 'Unknown'
e4f97bab 809
3fd3ab2d
C
810 const detailsJson = {
811 privacyLabel,
812 privacy: this.privacy,
813 descriptionPath: this.getDescriptionPath(),
814 channel: this.VideoChannel.toFormattedJSON(),
815 account: this.VideoChannel.Account.toFormattedJSON(),
d48ff09d 816 tags: map<TagModel, string>(this.Tags, 'name'),
47564bbe 817 commentsEnabled: this.commentsEnabled,
3fd3ab2d
C
818 files: []
819 }
e4f97bab 820
3fd3ab2d
C
821 // Format and sort video files
822 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
823 detailsJson.files = this.VideoFiles
824 .map(videoFile => {
825 let resolutionLabel = videoFile.resolution + 'p'
826
827 return {
828 resolution: videoFile.resolution,
829 resolutionLabel,
830 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
831 size: videoFile.size,
832 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
833 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
834 }
835 })
836 .sort((a, b) => {
837 if (a.resolution < b.resolution) return 1
838 if (a.resolution === b.resolution) return 0
839 return -1
840 })
841
d48ff09d 842 return Object.assign(formattedJson, detailsJson) as VideoDetails
3fd3ab2d 843 }
e4f97bab 844
3fd3ab2d
C
845 toActivityPubObject (): VideoTorrentObject {
846 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
847 if (!this.Tags) this.Tags = []
e4f97bab 848
3fd3ab2d
C
849 const tag = this.Tags.map(t => ({
850 type: 'Hashtag' as 'Hashtag',
851 name: t.name
852 }))
40298b02 853
3fd3ab2d
C
854 let language
855 if (this.language) {
856 language = {
857 identifier: this.language + '',
858 name: this.getLanguageLabel()
859 }
860 }
40298b02 861
3fd3ab2d
C
862 let category
863 if (this.category) {
864 category = {
865 identifier: this.category + '',
866 name: this.getCategoryLabel()
867 }
868 }
40298b02 869
3fd3ab2d
C
870 let licence
871 if (this.licence) {
872 licence = {
873 identifier: this.licence + '',
874 name: this.getLicenceLabel()
875 }
876 }
9567011b 877
3fd3ab2d
C
878 let likesObject
879 let dislikesObject
e4f97bab 880
3fd3ab2d
C
881 if (Array.isArray(this.AccountVideoRates)) {
882 const likes: string[] = []
883 const dislikes: string[] = []
e4f97bab 884
3fd3ab2d
C
885 for (const rate of this.AccountVideoRates) {
886 if (rate.type === 'like') {
50d6de9c 887 likes.push(rate.Account.Actor.url)
3fd3ab2d 888 } else if (rate.type === 'dislike') {
50d6de9c 889 dislikes.push(rate.Account.Actor.url)
3fd3ab2d
C
890 }
891 }
e4f97bab 892
3fd3ab2d
C
893 likesObject = activityPubCollection(likes)
894 dislikesObject = activityPubCollection(dislikes)
895 }
e4f97bab 896
3fd3ab2d
C
897 let sharesObject
898 if (Array.isArray(this.VideoShares)) {
899 const shares: string[] = []
e4f97bab 900
3fd3ab2d 901 for (const videoShare of this.VideoShares) {
50d6de9c 902 const shareUrl = getAnnounceActivityPubUrl(this.url, videoShare.Actor)
3fd3ab2d
C
903 shares.push(shareUrl)
904 }
e4f97bab 905
3fd3ab2d
C
906 sharesObject = activityPubCollection(shares)
907 }
93e1258c 908
da854ddd
C
909 let commentsObject
910 if (Array.isArray(this.VideoComments)) {
911 const comments: string[] = []
912
913 for (const videoComment of this.VideoComments) {
914 comments.push(videoComment.url)
915 }
916
917 commentsObject = activityPubCollection(comments)
918 }
919
3fd3ab2d
C
920 const url = []
921 for (const file of this.VideoFiles) {
922 url.push({
923 type: 'Link',
924 mimeType: 'video/' + file.extname.replace('.', ''),
925 url: this.getVideoFileUrl(file, baseUrlHttp),
926 width: file.resolution,
927 size: file.size
928 })
929
930 url.push({
931 type: 'Link',
932 mimeType: 'application/x-bittorrent',
933 url: this.getTorrentUrl(file, baseUrlHttp),
934 width: file.resolution
935 })
936
937 url.push({
938 type: 'Link',
939 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
940 url: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
941 width: file.resolution
942 })
943 }
93e1258c 944
3fd3ab2d
C
945 // Add video url too
946 url.push({
947 type: 'Link',
948 mimeType: 'text/html',
949 url: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
950 })
93e1258c 951
3fd3ab2d
C
952 return {
953 type: 'Video' as 'Video',
954 id: this.url,
955 name: this.name,
956 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
957 duration: 'PT' + this.duration + 'S',
958 uuid: this.uuid,
959 tag,
960 category,
961 licence,
962 language,
963 views: this.views,
964 nsfw: this.nsfw,
47564bbe 965 commentsEnabled: this.commentsEnabled,
3fd3ab2d
C
966 published: this.createdAt.toISOString(),
967 updated: this.updatedAt.toISOString(),
968 mediaType: 'text/markdown',
969 content: this.getTruncatedDescription(),
970 icon: {
971 type: 'Image',
972 url: this.getThumbnailUrl(baseUrlHttp),
973 mediaType: 'image/jpeg',
974 width: THUMBNAILS_SIZE.width,
975 height: THUMBNAILS_SIZE.height
976 },
977 url,
978 likes: likesObject,
979 dislikes: dislikesObject,
50d6de9c 980 shares: sharesObject,
da854ddd 981 comments: commentsObject,
50d6de9c
C
982 attributedTo: [
983 {
984 type: 'Group',
985 id: this.VideoChannel.Actor.url
986 }
987 ]
3fd3ab2d
C
988 }
989 }
990
991 getTruncatedDescription () {
992 if (!this.description) return null
93e1258c 993
3fd3ab2d
C
994 const options = {
995 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
996 }
aaf61f38 997
3fd3ab2d 998 return truncate(this.description, options)
93e1258c
C
999 }
1000
3fd3ab2d
C
1001 optimizeOriginalVideofile = async function () {
1002 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1003 const newExtname = '.mp4'
1004 const inputVideoFile = this.getOriginalFile()
1005 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1006 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
b769007f 1007
3fd3ab2d
C
1008 const transcodeOptions = {
1009 inputPath: videoInputPath,
1010 outputPath: videoOutputPath
1011 }
c46edbc2 1012
3fd3ab2d
C
1013 try {
1014 // Could be very long!
1015 await transcode(transcodeOptions)
c46edbc2 1016
3fd3ab2d 1017 await unlinkPromise(videoInputPath)
c46edbc2 1018
3fd3ab2d
C
1019 // Important to do this before getVideoFilename() to take in account the new file extension
1020 inputVideoFile.set('extname', newExtname)
e71bcc0f 1021
3fd3ab2d
C
1022 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1023 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
e71bcc0f 1024
3fd3ab2d 1025 inputVideoFile.set('size', stats.size)
e71bcc0f 1026
3fd3ab2d
C
1027 await this.createTorrentAndSetInfoHash(inputVideoFile)
1028 await inputVideoFile.save()
fd45e8f4 1029
3fd3ab2d
C
1030 } catch (err) {
1031 // Auto destruction...
1032 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
fd45e8f4 1033
3fd3ab2d
C
1034 throw err
1035 }
feb4bdfd
C
1036 }
1037
3fd3ab2d
C
1038 transcodeOriginalVideofile = async function (resolution: VideoResolution) {
1039 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1040 const extname = '.mp4'
aaf61f38 1041
3fd3ab2d
C
1042 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1043 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
feb4bdfd 1044
3fd3ab2d
C
1045 const newVideoFile = new VideoFileModel({
1046 resolution,
1047 extname,
1048 size: 0,
1049 videoId: this.id
1050 })
1051 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
a041b171 1052
3fd3ab2d
C
1053 const transcodeOptions = {
1054 inputPath: videoInputPath,
1055 outputPath: videoOutputPath,
1056 resolution
1057 }
a041b171 1058
3fd3ab2d 1059 await transcode(transcodeOptions)
a041b171 1060
3fd3ab2d 1061 const stats = await statPromise(videoOutputPath)
d7d5611c 1062
3fd3ab2d 1063 newVideoFile.set('size', stats.size)
d7d5611c 1064
3fd3ab2d 1065 await this.createTorrentAndSetInfoHash(newVideoFile)
d7d5611c 1066
3fd3ab2d
C
1067 await newVideoFile.save()
1068
1069 this.VideoFiles.push(newVideoFile)
0d0e8dd0
C
1070 }
1071
3fd3ab2d
C
1072 getOriginalFileHeight () {
1073 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
0d0e8dd0 1074
3fd3ab2d
C
1075 return getVideoFileHeight(originalFilePath)
1076 }
0d0e8dd0 1077
3fd3ab2d
C
1078 getDescriptionPath () {
1079 return `/api/${API_VERSION}/videos/${this.uuid}/description`
feb4bdfd
C
1080 }
1081
3fd3ab2d
C
1082 getCategoryLabel () {
1083 let categoryLabel = VIDEO_CATEGORIES[this.category]
1084 if (!categoryLabel) categoryLabel = 'Misc'
aaf61f38 1085
3fd3ab2d 1086 return categoryLabel
0a6658fd
C
1087 }
1088
3fd3ab2d
C
1089 getLicenceLabel () {
1090 let licenceLabel = VIDEO_LICENCES[this.licence]
1091 if (!licenceLabel) licenceLabel = 'Unknown'
0a6658fd 1092
3fd3ab2d 1093 return licenceLabel
feb4bdfd 1094 }
7920c273 1095
3fd3ab2d
C
1096 getLanguageLabel () {
1097 let languageLabel = VIDEO_LANGUAGES[this.language]
1098 if (!languageLabel) languageLabel = 'Unknown'
1099
1100 return languageLabel
72c7248b
C
1101 }
1102
3fd3ab2d
C
1103 removeThumbnail () {
1104 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1105 return unlinkPromise(thumbnailPath)
feb4bdfd
C
1106 }
1107
3fd3ab2d
C
1108 removePreview () {
1109 // Same name than video thumbnail
1110 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
7920c273
C
1111 }
1112
3fd3ab2d
C
1113 removeFile (videoFile: VideoFileModel) {
1114 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1115 return unlinkPromise(filePath)
feb4bdfd
C
1116 }
1117
3fd3ab2d
C
1118 removeTorrent (videoFile: VideoFileModel) {
1119 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1120 return unlinkPromise(torrentPath)
aaf61f38
C
1121 }
1122
3fd3ab2d
C
1123 private getBaseUrls () {
1124 let baseUrlHttp
1125 let baseUrlWs
7920c273 1126
3fd3ab2d
C
1127 if (this.isOwned()) {
1128 baseUrlHttp = CONFIG.WEBSERVER.URL
1129 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1130 } else {
50d6de9c
C
1131 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1132 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
6fcd19ba 1133 }
aaf61f38 1134
3fd3ab2d 1135 return { baseUrlHttp, baseUrlWs }
15d4ee04 1136 }
a96aed15 1137
3fd3ab2d
C
1138 private getThumbnailUrl (baseUrlHttp: string) {
1139 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
a96aed15
C
1140 }
1141
3fd3ab2d
C
1142 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1143 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1144 }
e4f97bab 1145
3fd3ab2d
C
1146 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1147 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1148 }
a96aed15 1149
3fd3ab2d
C
1150 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1151 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1152 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1153 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1154
1155 const magnetHash = {
1156 xs,
1157 announce,
1158 urlList,
1159 infoHash: videoFile.infoHash,
1160 name: this.name
1161 }
a96aed15 1162
3fd3ab2d 1163 return magnetUtil.encode(magnetHash)
a96aed15 1164 }
a96aed15 1165}