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