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