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