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