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