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