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'
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'
19 isVideoCategoryValid, isVideoDescriptionValid, isVideoDurationValid, isVideoLanguageValid, isVideoLicenceValid, isVideoNameValid,
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'
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 { ServerModel } from '../server/server'
35 import { getSort, throwIfNotValid } from '../utils'
36 import { TagModel } from './tag'
37 import { VideoAbuseModel } from './video-abuse'
38 import { VideoChannelModel } from './video-channel'
39 import { VideoCommentModel } from './video-comment'
40 import { VideoFileModel } from './video-file'
41 import { VideoShareModel } from './video-share'
42 import { VideoTagModel } from './video-tag'
45 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
46 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
47 WITH_TAGS = 'WITH_TAGS',
48 WITH_FILES = 'WITH_FILES',
49 WITH_SHARES = 'WITH_SHARES',
50 WITH_RATES = 'WITH_RATES',
51 WITH_COMMENTS = 'WITH_COMMENTS'
55 [ScopeNames.AVAILABLE_FOR_LIST]: (actorId: number) => ({
58 [Sequelize.Op.notIn]: Sequelize.literal(
59 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
61 [ Sequelize.Op.in ]: Sequelize.literal(
63 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
64 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
65 'WHERE "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
67 'SELECT "video"."id" AS "id" FROM "video" ' +
68 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
69 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
70 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
71 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
72 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
76 privacy: VideoPrivacy.PUBLIC
80 attributes: [ 'name', 'description' ],
81 model: VideoChannelModel.unscoped(),
85 attributes: [ 'name' ],
86 model: AccountModel.unscoped(),
90 attributes: [ 'serverId' ],
91 model: ActorModel.unscoped(),
95 attributes: [ 'host' ],
96 model: ServerModel.unscoped()
106 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
109 model: () => VideoChannelModel.unscoped(),
114 exclude: [ 'privateKey', 'publicKey' ]
116 model: () => ActorModel.unscoped(),
120 attributes: [ 'host' ],
121 model: () => ServerModel.unscoped(),
127 model: () => AccountModel.unscoped(),
131 model: () => ActorModel.unscoped(),
133 exclude: [ 'privateKey', 'publicKey' ]
138 attributes: [ 'host' ],
139 model: () => ServerModel.unscoped(),
150 [ScopeNames.WITH_TAGS]: {
151 include: [ () => TagModel ]
153 [ScopeNames.WITH_FILES]: {
156 model: () => VideoFileModel,
161 [ScopeNames.WITH_SHARES]: {
164 model: () => VideoShareModel,
165 include: [ () => ActorModel ]
169 [ScopeNames.WITH_RATES]: {
172 model: () => AccountVideoRateModel,
173 include: [ () => AccountModel ]
177 [ScopeNames.WITH_COMMENTS]: {
180 model: () => VideoCommentModel
192 fields: [ 'createdAt' ]
195 fields: [ 'duration' ]
207 fields: [ 'channelId' ]
210 fields: [ 'id', 'privacy' ]
218 export class VideoModel extends Model<VideoModel> {
221 @Default(DataType.UUIDV4)
223 @Column(DataType.UUID)
227 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
233 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
239 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
245 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
250 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
255 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
261 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
262 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
266 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
296 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
297 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
302 commentsEnabled: boolean
310 @ForeignKey(() => VideoChannelModel)
314 @BelongsTo(() => VideoChannelModel, {
320 VideoChannel: VideoChannelModel
322 @BelongsToMany(() => TagModel, {
323 foreignKey: 'videoId',
324 through: () => VideoTagModel,
329 @HasMany(() => VideoAbuseModel, {
336 VideoAbuses: VideoAbuseModel[]
338 @HasMany(() => VideoFileModel, {
345 VideoFiles: VideoFileModel[]
347 @HasMany(() => VideoShareModel, {
354 VideoShares: VideoShareModel[]
356 @HasMany(() => AccountVideoRateModel, {
363 AccountVideoRates: AccountVideoRateModel[]
365 @HasMany(() => VideoCommentModel, {
373 VideoComments: VideoCommentModel[]
376 static async sendDelete (instance: VideoModel, options) {
377 if (instance.isOwned()) {
378 if (!instance.VideoChannel) {
379 instance.VideoChannel = await instance.$get('VideoChannel', {
383 include: [ ActorModel ]
386 transaction: options.transaction
387 }) as VideoChannelModel
390 logger.debug('Sending delete of video %s.', instance.url)
392 return sendDeleteVideo(instance, options.transaction)
399 static async removeFilesAndSendDelete (instance: VideoModel) {
400 const tasks: Promise<any>[] = []
402 tasks.push(instance.removeThumbnail())
404 if (instance.isOwned()) {
405 if (!Array.isArray(instance.VideoFiles)) {
406 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
409 tasks.push(instance.removePreview())
411 // Remove physical files and torrents
412 instance.VideoFiles.forEach(file => {
413 tasks.push(instance.removeFile(file))
414 tasks.push(instance.removeTorrent(file))
418 return Promise.all(tasks)
420 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, err)
425 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
428 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
429 function getRawQuery (select: string) {
430 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
431 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
432 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
433 'WHERE "Account"."actorId" = ' + actorId
434 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
435 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
436 'WHERE "VideoShare"."actorId" = ' + actorId
438 return `(${queryVideo}) UNION (${queryVideoShare})`
441 const rawQuery = getRawQuery('"Video"."id"')
442 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
448 order: [ getSort('createdAt'), [ 'Tags', 'name', 'ASC' ] ],
451 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
456 attributes: [ 'id' ],
457 model: VideoShareModel.unscoped(),
460 [Sequelize.Op.and]: [
463 [Sequelize.Op.not]: null
473 attributes: [ 'id', 'url' ],
474 model: ActorModel.unscoped()
479 model: VideoChannelModel.unscoped(),
483 attributes: [ 'name' ],
484 model: AccountModel.unscoped(),
488 attributes: [ 'id', 'url' ],
489 model: ActorModel.unscoped(),
495 attributes: [ 'id', 'url' ],
496 model: ActorModel.unscoped(),
502 attributes: [ 'type' ],
503 model: AccountVideoRateModel,
507 attributes: [ 'id' ],
508 model: AccountModel.unscoped(),
511 attributes: [ 'url' ],
512 model: ActorModel.unscoped(),
515 attributes: [ 'host' ],
526 attributes: [ 'url' ],
527 model: VideoCommentModel,
535 return Bluebird.all([
536 // FIXME: typing issue
537 VideoModel.findAll(query as any),
538 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
539 ]).then(([ rows, totals ]) => {
540 // totals: totalVideos + totalVideoShares
542 let totalVideoShares = 0
543 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
544 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
546 const total = totalVideos + totalVideoShares
554 static listUserVideosForApi (userId: number, start: number, count: number, sort: string) {
558 order: [ getSort(sort) ],
561 model: VideoChannelModel,
576 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
584 static async listForApi (start: number, count: number, sort: string) {
588 order: [ getSort(sort) ]
591 const serverActor = await getServerActor()
593 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
594 .findAndCountAll(query)
595 .then(({ rows, count }) => {
603 static async searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) {
604 const query: IFindOptions<VideoModel> = {
607 order: [ getSort(sort) ],
610 [Sequelize.Op.iLike]: '%' + value + '%'
615 const serverActor = await getServerActor()
617 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
618 .findAndCountAll(query).then(({ rows, count }) => {
626 static load (id: number) {
627 return VideoModel.findById(id)
630 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
631 const query: IFindOptions<VideoModel> = {
637 if (t !== undefined) query.transaction = t
639 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
642 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
643 const query: IFindOptions<VideoModel> = {
652 if (t !== undefined) query.transaction = t
654 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
657 static loadAndPopulateAccountAndServerAndTags (id: number) {
659 order: [ [ 'Tags', 'name', 'ASC' ] ]
663 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
664 .findById(id, options)
667 static loadByUUID (uuid: string) {
675 .scope([ ScopeNames.WITH_FILES ])
679 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
681 order: [ [ 'Tags', 'name', 'ASC' ] ],
688 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
692 static loadAndPopulateAll (id: number) {
694 order: [ [ 'Tags', 'name', 'ASC' ] ],
702 ScopeNames.WITH_RATES,
703 ScopeNames.WITH_SHARES,
704 ScopeNames.WITH_TAGS,
705 ScopeNames.WITH_FILES,
706 ScopeNames.WITH_ACCOUNT_DETAILS,
707 ScopeNames.WITH_COMMENTS
713 if (Array.isArray(this.VideoFiles) === false) return undefined
715 // The original file is the file that have the higher resolution
716 return maxBy(this.VideoFiles, file => file.resolution)
719 getVideoFilename (videoFile: VideoFileModel) {
720 return this.uuid + '-' + videoFile.resolution + videoFile.extname
723 getThumbnailName () {
724 // We always have a copy of the thumbnail
725 const extension = '.jpg'
726 return this.uuid + extension
730 const extension = '.jpg'
731 return this.uuid + extension
734 getTorrentFileName (videoFile: VideoFileModel) {
735 const extension = '.torrent'
736 return this.uuid + '-' + videoFile.resolution + extension
740 return this.remote === false
743 createPreview (videoFile: VideoFileModel) {
744 const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height
746 return generateImageFromVideoFile(
747 this.getVideoFilePath(videoFile),
748 CONFIG.STORAGE.PREVIEWS_DIR,
749 this.getPreviewName(),
754 createThumbnail (videoFile: VideoFileModel) {
755 const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height
757 return generateImageFromVideoFile(
758 this.getVideoFilePath(videoFile),
759 CONFIG.STORAGE.THUMBNAILS_DIR,
760 this.getThumbnailName(),
765 getVideoFilePath (videoFile: VideoFileModel) {
766 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
769 createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) {
772 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
773 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
776 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
780 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
782 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
783 logger.info('Creating torrent %s.', filePath)
785 await writeFilePromise(filePath, torrent)
787 const parsedTorrent = parseTorrent(torrent)
788 videoFile.infoHash = parsedTorrent.infoHash
792 return '/videos/embed/' + this.uuid
795 getThumbnailPath () {
796 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
800 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
806 if (this.VideoChannel.Account.Actor.Server) {
807 serverHost = this.VideoChannel.Account.Actor.Server.host
809 // It means it's our video
810 serverHost = CONFIG.WEBSERVER.HOST
817 category: this.category,
818 categoryLabel: this.getCategoryLabel(),
819 licence: this.licence,
820 licenceLabel: this.getLicenceLabel(),
821 language: this.language,
822 languageLabel: this.getLanguageLabel(),
824 description: this.getTruncatedDescription(),
826 isLocal: this.isOwned(),
827 accountName: this.VideoChannel.Account.name,
828 duration: this.duration,
831 dislikes: this.dislikes,
832 thumbnailPath: this.getThumbnailPath(),
833 previewPath: this.getPreviewPath(),
834 embedPath: this.getEmbedPath(),
835 createdAt: this.createdAt,
836 updatedAt: this.updatedAt
840 toFormattedDetailsJSON () {
841 const formattedJson = this.toFormattedJSON()
843 // Maybe our server is not up to date and there are new privacy settings since our version
844 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
845 if (!privacyLabel) privacyLabel = 'Unknown'
847 const detailsJson = {
849 privacy: this.privacy,
850 descriptionPath: this.getDescriptionPath(),
851 channel: this.VideoChannel.toFormattedJSON(),
852 account: this.VideoChannel.Account.toFormattedJSON(),
853 tags: map<TagModel, string>(this.Tags, 'name'),
854 commentsEnabled: this.commentsEnabled,
858 // Format and sort video files
859 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
860 detailsJson.files = this.VideoFiles
862 let resolutionLabel = videoFile.resolution + 'p'
865 resolution: videoFile.resolution,
867 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
868 size: videoFile.size,
869 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
870 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
874 if (a.resolution < b.resolution) return 1
875 if (a.resolution === b.resolution) return 0
879 return Object.assign(formattedJson, detailsJson) as VideoDetails
882 toActivityPubObject (): VideoTorrentObject {
883 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
884 if (!this.Tags) this.Tags = []
886 const tag = this.Tags.map(t => ({
887 type: 'Hashtag' as 'Hashtag',
894 identifier: this.language + '',
895 name: this.getLanguageLabel()
902 identifier: this.category + '',
903 name: this.getCategoryLabel()
910 identifier: this.licence + '',
911 name: this.getLicenceLabel()
918 if (Array.isArray(this.AccountVideoRates)) {
919 const likes: string[] = []
920 const dislikes: string[] = []
922 for (const rate of this.AccountVideoRates) {
923 if (rate.type === 'like') {
924 likes.push(rate.Account.Actor.url)
925 } else if (rate.type === 'dislike') {
926 dislikes.push(rate.Account.Actor.url)
930 likesObject = activityPubCollection(likes)
931 dislikesObject = activityPubCollection(dislikes)
935 if (Array.isArray(this.VideoShares)) {
936 const shares: string[] = []
938 for (const videoShare of this.VideoShares) {
939 const shareUrl = getAnnounceActivityPubUrl(this.url, videoShare.Actor)
940 shares.push(shareUrl)
943 sharesObject = activityPubCollection(shares)
947 if (Array.isArray(this.VideoComments)) {
948 const comments: string[] = []
950 for (const videoComment of this.VideoComments) {
951 comments.push(videoComment.url)
954 commentsObject = activityPubCollection(comments)
958 for (const file of this.VideoFiles) {
961 mimeType: 'video/' + file.extname.replace('.', ''),
962 href: this.getVideoFileUrl(file, baseUrlHttp),
963 width: file.resolution,
969 mimeType: 'application/x-bittorrent',
970 href: this.getTorrentUrl(file, baseUrlHttp),
971 width: file.resolution
976 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
977 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
978 width: file.resolution
985 mimeType: 'text/html',
986 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
990 type: 'Video' as 'Video',
993 duration: this.getActivityStreamDuration(),
1001 commentsEnabled: this.commentsEnabled,
1002 published: this.createdAt.toISOString(),
1003 updated: this.updatedAt.toISOString(),
1004 mediaType: 'text/markdown',
1005 content: this.getTruncatedDescription(),
1008 url: this.getThumbnailUrl(baseUrlHttp),
1009 mediaType: 'image/jpeg',
1010 width: THUMBNAILS_SIZE.width,
1011 height: THUMBNAILS_SIZE.height
1015 dislikes: dislikesObject,
1016 shares: sharesObject,
1017 comments: commentsObject,
1021 id: this.VideoChannel.Actor.url
1025 id: this.VideoChannel.Account.Actor.url
1031 getTruncatedDescription () {
1032 if (!this.description) return null
1035 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1038 return truncate(this.description, options)
1041 optimizeOriginalVideofile = async function () {
1042 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1043 const newExtname = '.mp4'
1044 const inputVideoFile = this.getOriginalFile()
1045 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1046 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1048 const transcodeOptions = {
1049 inputPath: videoInputPath,
1050 outputPath: videoOutputPath
1054 // Could be very long!
1055 await transcode(transcodeOptions)
1057 await unlinkPromise(videoInputPath)
1059 // Important to do this before getVideoFilename() to take in account the new file extension
1060 inputVideoFile.set('extname', newExtname)
1062 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1063 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1065 inputVideoFile.set('size', stats.size)
1067 await this.createTorrentAndSetInfoHash(inputVideoFile)
1068 await inputVideoFile.save()
1071 // Auto destruction...
1072 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
1078 transcodeOriginalVideofile = async function (resolution: VideoResolution) {
1079 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1080 const extname = '.mp4'
1082 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1083 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1085 const newVideoFile = new VideoFileModel({
1091 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1093 const transcodeOptions = {
1094 inputPath: videoInputPath,
1095 outputPath: videoOutputPath,
1099 await transcode(transcodeOptions)
1101 const stats = await statPromise(videoOutputPath)
1103 newVideoFile.set('size', stats.size)
1105 await this.createTorrentAndSetInfoHash(newVideoFile)
1107 await newVideoFile.save()
1109 this.VideoFiles.push(newVideoFile)
1112 getOriginalFileHeight () {
1113 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1115 return getVideoFileHeight(originalFilePath)
1118 getDescriptionPath () {
1119 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1122 getCategoryLabel () {
1123 let categoryLabel = VIDEO_CATEGORIES[this.category]
1124 if (!categoryLabel) categoryLabel = 'Misc'
1126 return categoryLabel
1129 getLicenceLabel () {
1130 let licenceLabel = VIDEO_LICENCES[this.licence]
1131 if (!licenceLabel) licenceLabel = 'Unknown'
1136 getLanguageLabel () {
1137 let languageLabel = VIDEO_LANGUAGES[this.language]
1138 if (!languageLabel) languageLabel = 'Unknown'
1140 return languageLabel
1143 removeThumbnail () {
1144 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1145 return unlinkPromise(thumbnailPath)
1149 // Same name than video thumbnail
1150 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1153 removeFile (videoFile: VideoFileModel) {
1154 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1155 return unlinkPromise(filePath)
1158 removeTorrent (videoFile: VideoFileModel) {
1159 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1160 return unlinkPromise(torrentPath)
1163 getActivityStreamDuration () {
1164 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1165 return 'PT' + this.duration + 'S'
1168 private getBaseUrls () {
1172 if (this.isOwned()) {
1173 baseUrlHttp = CONFIG.WEBSERVER.URL
1174 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1176 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1177 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1180 return { baseUrlHttp, baseUrlWs }
1183 private getThumbnailUrl (baseUrlHttp: string) {
1184 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1187 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1188 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1191 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1192 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1195 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1196 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1197 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1198 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1200 const magnetHash = {
1204 infoHash: videoFile.infoHash,
1208 return magnetUtil.encode(magnetHash)