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'
28 } from 'sequelize-typescript'
29 import { VideoPrivacy, VideoResolution } from '../../../shared'
30 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
31 import { Video, VideoDetails } from '../../../shared/models/videos'
32 import { activityPubCollection } from '../../helpers/activitypub'
33 import { createTorrentPromise, renamePromise, statPromise, unlinkPromise, writeFilePromise } from '../../helpers/core-utils'
34 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
35 import { isBooleanValid } from '../../helpers/custom-validators/misc'
38 isVideoDescriptionValid,
45 } from '../../helpers/custom-validators/videos'
46 import { generateImageFromVideoFile, getVideoFileResolution, transcode } from '../../helpers/ffmpeg-utils'
47 import { logger } from '../../helpers/logger'
48 import { getServerActor } from '../../helpers/utils'
61 } from '../../initializers'
63 getVideoCommentsActivityPubUrl,
64 getVideoDislikesActivityPubUrl,
65 getVideoLikesActivityPubUrl,
66 getVideoSharesActivityPubUrl
67 } from '../../lib/activitypub'
68 import { sendDeleteVideo } from '../../lib/activitypub/send'
69 import { AccountModel } from '../account/account'
70 import { AccountVideoRateModel } from '../account/account-video-rate'
71 import { ActorModel } from '../activitypub/actor'
72 import { AvatarModel } from '../avatar/avatar'
73 import { ServerModel } from '../server/server'
74 import { getSort, throwIfNotValid } from '../utils'
75 import { TagModel } from './tag'
76 import { VideoAbuseModel } from './video-abuse'
77 import { VideoChannelModel } from './video-channel'
78 import { VideoCommentModel } from './video-comment'
79 import { VideoFileModel } from './video-file'
80 import { VideoShareModel } from './video-share'
81 import { VideoTagModel } from './video-tag'
84 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
85 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
86 WITH_TAGS = 'WITH_TAGS',
87 WITH_FILES = 'WITH_FILES',
88 WITH_SHARES = 'WITH_SHARES',
89 WITH_RATES = 'WITH_RATES',
90 WITH_COMMENTS = 'WITH_COMMENTS'
94 [ScopeNames.AVAILABLE_FOR_LIST]: (actorId: number) => ({
97 [Sequelize.Op.notIn]: Sequelize.literal(
98 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
100 [ Sequelize.Op.in ]: Sequelize.literal(
102 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
103 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
104 'WHERE "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
106 'SELECT "video"."id" AS "id" FROM "video" ' +
107 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
108 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
109 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
110 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
111 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
115 privacy: VideoPrivacy.PUBLIC
119 attributes: [ 'name', 'description' ],
120 model: VideoChannelModel.unscoped(),
124 attributes: [ 'name' ],
125 model: AccountModel.unscoped(),
129 attributes: [ 'preferredUsername', 'url', 'serverId' ],
130 model: ActorModel.unscoped(),
134 attributes: [ 'host' ],
135 model: ServerModel.unscoped(),
139 model: AvatarModel.unscoped(),
150 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
153 model: () => VideoChannelModel.unscoped(),
158 exclude: [ 'privateKey', 'publicKey' ]
160 model: () => ActorModel.unscoped(),
164 attributes: [ 'host' ],
165 model: () => ServerModel.unscoped(),
171 model: () => AccountModel.unscoped(),
175 model: () => ActorModel.unscoped(),
177 exclude: [ 'privateKey', 'publicKey' ]
182 attributes: [ 'host' ],
183 model: () => ServerModel.unscoped(),
187 model: () => AvatarModel.unscoped(),
198 [ScopeNames.WITH_TAGS]: {
199 include: [ () => TagModel ]
201 [ScopeNames.WITH_FILES]: {
204 model: () => VideoFileModel,
209 [ScopeNames.WITH_SHARES]: {
212 model: () => VideoShareModel,
213 include: [ () => ActorModel ]
217 [ScopeNames.WITH_RATES]: {
220 model: () => AccountVideoRateModel,
221 include: [ () => AccountModel ]
225 [ScopeNames.WITH_COMMENTS]: {
228 model: () => VideoCommentModel
240 fields: [ 'createdAt' ]
243 fields: [ 'duration' ]
255 fields: [ 'channelId' ]
258 fields: [ 'id', 'privacy' ]
266 export class VideoModel extends Model<VideoModel> {
269 @Default(DataType.UUIDV4)
271 @Column(DataType.UUID)
275 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
281 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
287 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
293 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
298 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
303 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
309 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
310 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
315 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
316 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
320 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
350 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
351 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
356 commentsEnabled: boolean
364 @ForeignKey(() => VideoChannelModel)
368 @BelongsTo(() => VideoChannelModel, {
374 VideoChannel: VideoChannelModel
376 @BelongsToMany(() => TagModel, {
377 foreignKey: 'videoId',
378 through: () => VideoTagModel,
383 @HasMany(() => VideoAbuseModel, {
390 VideoAbuses: VideoAbuseModel[]
392 @HasMany(() => VideoFileModel, {
399 VideoFiles: VideoFileModel[]
401 @HasMany(() => VideoShareModel, {
408 VideoShares: VideoShareModel[]
410 @HasMany(() => AccountVideoRateModel, {
417 AccountVideoRates: AccountVideoRateModel[]
419 @HasMany(() => VideoCommentModel, {
427 VideoComments: VideoCommentModel[]
430 static async sendDelete (instance: VideoModel, options) {
431 if (instance.isOwned()) {
432 if (!instance.VideoChannel) {
433 instance.VideoChannel = await instance.$get('VideoChannel', {
437 include: [ ActorModel ]
440 transaction: options.transaction
441 }) as VideoChannelModel
444 logger.debug('Sending delete of video %s.', instance.url)
446 return sendDeleteVideo(instance, options.transaction)
453 static async removeFilesAndSendDelete (instance: VideoModel) {
454 const tasks: Promise<any>[] = []
456 tasks.push(instance.removeThumbnail())
458 if (instance.isOwned()) {
459 if (!Array.isArray(instance.VideoFiles)) {
460 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
463 tasks.push(instance.removePreview())
465 // Remove physical files and torrents
466 instance.VideoFiles.forEach(file => {
467 tasks.push(instance.removeFile(file))
468 tasks.push(instance.removeTorrent(file))
472 return Promise.all(tasks)
474 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, err)
479 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
482 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
483 function getRawQuery (select: string) {
484 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
485 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
486 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
487 'WHERE "Account"."actorId" = ' + actorId
488 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
489 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
490 'WHERE "VideoShare"."actorId" = ' + actorId
492 return `(${queryVideo}) UNION (${queryVideoShare})`
495 const rawQuery = getRawQuery('"Video"."id"')
496 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
502 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
505 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
508 { privacy: VideoPrivacy.PUBLIC },
509 { privacy: VideoPrivacy.UNLISTED }
514 attributes: [ 'id', 'url' ],
515 model: VideoShareModel.unscoped(),
518 [Sequelize.Op.and]: [
521 [Sequelize.Op.not]: null
531 attributes: [ 'id', 'url' ],
532 model: ActorModel.unscoped()
537 model: VideoChannelModel.unscoped(),
541 attributes: [ 'name' ],
542 model: AccountModel.unscoped(),
546 attributes: [ 'id', 'url' ],
547 model: ActorModel.unscoped(),
553 attributes: [ 'id', 'url' ],
554 model: ActorModel.unscoped(),
560 attributes: [ 'type' ],
561 model: AccountVideoRateModel,
565 attributes: [ 'id' ],
566 model: AccountModel.unscoped(),
569 attributes: [ 'url' ],
570 model: ActorModel.unscoped(),
573 attributes: [ 'host' ],
584 attributes: [ 'url' ],
585 model: VideoCommentModel,
593 return Bluebird.all([
594 // FIXME: typing issue
595 VideoModel.findAll(query as any),
596 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
597 ]).then(([ rows, totals ]) => {
598 // totals: totalVideos + totalVideoShares
600 let totalVideoShares = 0
601 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
602 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
604 const total = totalVideos + totalVideoShares
612 static listUserVideosForApi (userId: number, start: number, count: number, sort: string) {
616 order: getSort(sort),
619 model: VideoChannelModel,
634 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
642 static async listForApi (start: number, count: number, sort: string) {
649 const serverActor = await getServerActor()
651 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
652 .findAndCountAll(query)
653 .then(({ rows, count }) => {
661 static async searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) {
662 const query: IFindOptions<VideoModel> = {
665 order: getSort(sort),
668 [Sequelize.Op.iLike]: '%' + value + '%'
673 const serverActor = await getServerActor()
675 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
676 .findAndCountAll(query).then(({ rows, count }) => {
684 static load (id: number) {
685 return VideoModel.findById(id)
688 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
689 const query: IFindOptions<VideoModel> = {
695 if (t !== undefined) query.transaction = t
697 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
700 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
701 const query: IFindOptions<VideoModel> = {
710 if (t !== undefined) query.transaction = t
712 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
715 static loadAndPopulateAccountAndServerAndTags (id: number) {
717 order: [ [ 'Tags', 'name', 'ASC' ] ]
721 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
722 .findById(id, options)
725 static loadByUUID (uuid: string) {
733 .scope([ ScopeNames.WITH_FILES ])
737 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
739 order: [ [ 'Tags', 'name', 'ASC' ] ],
746 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
750 static loadAndPopulateAll (id: number) {
752 order: [ [ 'Tags', 'name', 'ASC' ] ],
760 ScopeNames.WITH_RATES,
761 ScopeNames.WITH_SHARES,
762 ScopeNames.WITH_TAGS,
763 ScopeNames.WITH_FILES,
764 ScopeNames.WITH_ACCOUNT_DETAILS,
765 ScopeNames.WITH_COMMENTS
770 static async getStats () {
771 const totalLocalVideos = await VideoModel.count({
776 const totalVideos = await VideoModel.count()
778 let totalLocalVideoViews = await VideoModel.sum('views', {
783 // Sequelize could return null...
784 if (!totalLocalVideoViews) totalLocalVideoViews = 0
788 totalLocalVideoViews,
794 if (Array.isArray(this.VideoFiles) === false) return undefined
796 // The original file is the file that have the higher resolution
797 return maxBy(this.VideoFiles, file => file.resolution)
800 getVideoFilename (videoFile: VideoFileModel) {
801 return this.uuid + '-' + videoFile.resolution + videoFile.extname
804 getThumbnailName () {
805 // We always have a copy of the thumbnail
806 const extension = '.jpg'
807 return this.uuid + extension
811 const extension = '.jpg'
812 return this.uuid + extension
815 getTorrentFileName (videoFile: VideoFileModel) {
816 const extension = '.torrent'
817 return this.uuid + '-' + videoFile.resolution + extension
821 return this.remote === false
824 createPreview (videoFile: VideoFileModel) {
825 return generateImageFromVideoFile(
826 this.getVideoFilePath(videoFile),
827 CONFIG.STORAGE.PREVIEWS_DIR,
828 this.getPreviewName(),
833 createThumbnail (videoFile: VideoFileModel) {
834 return generateImageFromVideoFile(
835 this.getVideoFilePath(videoFile),
836 CONFIG.STORAGE.THUMBNAILS_DIR,
837 this.getThumbnailName(),
842 getVideoFilePath (videoFile: VideoFileModel) {
843 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
846 createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) {
849 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
850 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
853 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
857 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
859 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
860 logger.info('Creating torrent %s.', filePath)
862 await writeFilePromise(filePath, torrent)
864 const parsedTorrent = parseTorrent(torrent)
865 videoFile.infoHash = parsedTorrent.infoHash
869 return '/videos/embed/' + this.uuid
872 getThumbnailPath () {
873 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
877 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
880 toFormattedJSON (): Video {
881 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
887 category: this.category,
888 categoryLabel: this.getCategoryLabel(),
889 licence: this.licence,
890 licenceLabel: this.getLicenceLabel(),
891 language: this.language,
892 languageLabel: this.getLanguageLabel(),
894 description: this.getTruncatedDescription(),
895 isLocal: this.isOwned(),
896 duration: this.duration,
899 dislikes: this.dislikes,
900 thumbnailPath: this.getThumbnailPath(),
901 previewPath: this.getPreviewPath(),
902 embedPath: this.getEmbedPath(),
903 createdAt: this.createdAt,
904 updatedAt: this.updatedAt,
906 name: formattedAccount.name,
907 displayName: formattedAccount.displayName,
908 url: formattedAccount.url,
909 host: formattedAccount.host,
910 avatar: formattedAccount.avatar
915 toFormattedDetailsJSON (): VideoDetails {
916 const formattedJson = this.toFormattedJSON()
918 // Maybe our server is not up to date and there are new privacy settings since our version
919 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
920 if (!privacyLabel) privacyLabel = 'Unknown'
922 const detailsJson = {
924 privacy: this.privacy,
925 support: this.support,
926 descriptionPath: this.getDescriptionPath(),
927 channel: this.VideoChannel.toFormattedJSON(),
928 account: this.VideoChannel.Account.toFormattedJSON(),
929 tags: map<TagModel, string>(this.Tags, 'name'),
930 commentsEnabled: this.commentsEnabled,
934 // Format and sort video files
935 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
936 detailsJson.files = this.VideoFiles
938 let resolutionLabel = videoFile.resolution + 'p'
941 resolution: videoFile.resolution,
943 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
944 size: videoFile.size,
945 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
946 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
950 if (a.resolution < b.resolution) return 1
951 if (a.resolution === b.resolution) return 0
955 return Object.assign(formattedJson, detailsJson)
958 toActivityPubObject (): VideoTorrentObject {
959 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
960 if (!this.Tags) this.Tags = []
962 const tag = this.Tags.map(t => ({
963 type: 'Hashtag' as 'Hashtag',
970 identifier: this.language + '',
971 name: this.getLanguageLabel()
978 identifier: this.category + '',
979 name: this.getCategoryLabel()
986 identifier: this.licence + '',
987 name: this.getLicenceLabel()
994 if (Array.isArray(this.AccountVideoRates)) {
995 const res = this.toRatesActivityPubObjects()
996 likesObject = res.likesObject
997 dislikesObject = res.dislikesObject
1001 if (Array.isArray(this.VideoShares)) {
1002 sharesObject = this.toAnnouncesActivityPubObject()
1006 if (Array.isArray(this.VideoComments)) {
1007 commentsObject = this.toCommentsActivityPubObject()
1011 for (const file of this.VideoFiles) {
1014 mimeType: 'video/' + file.extname.replace('.', ''),
1015 href: this.getVideoFileUrl(file, baseUrlHttp),
1016 width: file.resolution,
1022 mimeType: 'application/x-bittorrent',
1023 href: this.getTorrentUrl(file, baseUrlHttp),
1024 width: file.resolution
1029 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1030 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1031 width: file.resolution
1035 // Add video url too
1038 mimeType: 'text/html',
1039 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1043 type: 'Video' as 'Video',
1046 duration: this.getActivityStreamDuration(),
1053 sensitive: this.nsfw,
1054 commentsEnabled: this.commentsEnabled,
1055 published: this.createdAt.toISOString(),
1056 updated: this.updatedAt.toISOString(),
1057 mediaType: 'text/markdown',
1058 content: this.getTruncatedDescription(),
1059 support: this.support,
1062 url: this.getThumbnailUrl(baseUrlHttp),
1063 mediaType: 'image/jpeg',
1064 width: THUMBNAILS_SIZE.width,
1065 height: THUMBNAILS_SIZE.height
1069 dislikes: dislikesObject,
1070 shares: sharesObject,
1071 comments: commentsObject,
1075 id: this.VideoChannel.Actor.url
1079 id: this.VideoChannel.Account.Actor.url
1085 toAnnouncesActivityPubObject () {
1086 const shares: string[] = []
1088 for (const videoShare of this.VideoShares) {
1089 shares.push(videoShare.url)
1092 return activityPubCollection(getVideoSharesActivityPubUrl(this), shares)
1095 toCommentsActivityPubObject () {
1096 const comments: string[] = []
1098 for (const videoComment of this.VideoComments) {
1099 comments.push(videoComment.url)
1102 return activityPubCollection(getVideoCommentsActivityPubUrl(this), comments)
1105 toRatesActivityPubObjects () {
1106 const likes: string[] = []
1107 const dislikes: string[] = []
1109 for (const rate of this.AccountVideoRates) {
1110 if (rate.type === 'like') {
1111 likes.push(rate.Account.Actor.url)
1112 } else if (rate.type === 'dislike') {
1113 dislikes.push(rate.Account.Actor.url)
1117 const likesObject = activityPubCollection(getVideoLikesActivityPubUrl(this), likes)
1118 const dislikesObject = activityPubCollection(getVideoDislikesActivityPubUrl(this), dislikes)
1120 return { likesObject, dislikesObject }
1123 getTruncatedDescription () {
1124 if (!this.description) return null
1127 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1130 return truncate(this.description, options)
1133 optimizeOriginalVideofile = async function () {
1134 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1135 const newExtname = '.mp4'
1136 const inputVideoFile = this.getOriginalFile()
1137 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1138 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1140 const transcodeOptions = {
1141 inputPath: videoInputPath,
1142 outputPath: videoOutputPath
1145 // Could be very long!
1146 await transcode(transcodeOptions)
1149 await unlinkPromise(videoInputPath)
1151 // Important to do this before getVideoFilename() to take in account the new file extension
1152 inputVideoFile.set('extname', newExtname)
1154 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1155 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1157 inputVideoFile.set('size', stats.size)
1159 await this.createTorrentAndSetInfoHash(inputVideoFile)
1160 await inputVideoFile.save()
1163 // Auto destruction...
1164 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
1170 transcodeOriginalVideofile = async function (resolution: VideoResolution, isPortraitMode: boolean) {
1171 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1172 const extname = '.mp4'
1174 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1175 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1177 const newVideoFile = new VideoFileModel({
1183 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1185 const transcodeOptions = {
1186 inputPath: videoInputPath,
1187 outputPath: videoOutputPath,
1192 await transcode(transcodeOptions)
1194 const stats = await statPromise(videoOutputPath)
1196 newVideoFile.set('size', stats.size)
1198 await this.createTorrentAndSetInfoHash(newVideoFile)
1200 await newVideoFile.save()
1202 this.VideoFiles.push(newVideoFile)
1205 getOriginalFileResolution () {
1206 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1208 return getVideoFileResolution(originalFilePath)
1211 getDescriptionPath () {
1212 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1215 getCategoryLabel () {
1216 let categoryLabel = VIDEO_CATEGORIES[this.category]
1217 if (!categoryLabel) categoryLabel = 'Misc'
1219 return categoryLabel
1222 getLicenceLabel () {
1223 let licenceLabel = VIDEO_LICENCES[this.licence]
1224 if (!licenceLabel) licenceLabel = 'Unknown'
1229 getLanguageLabel () {
1230 let languageLabel = VIDEO_LANGUAGES[this.language]
1231 if (!languageLabel) languageLabel = 'Unknown'
1233 return languageLabel
1236 removeThumbnail () {
1237 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1238 return unlinkPromise(thumbnailPath)
1242 // Same name than video thumbnail
1243 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1246 removeFile (videoFile: VideoFileModel) {
1247 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1248 return unlinkPromise(filePath)
1251 removeTorrent (videoFile: VideoFileModel) {
1252 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1253 return unlinkPromise(torrentPath)
1256 getActivityStreamDuration () {
1257 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1258 return 'PT' + this.duration + 'S'
1261 private getBaseUrls () {
1265 if (this.isOwned()) {
1266 baseUrlHttp = CONFIG.WEBSERVER.URL
1267 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1269 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1270 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1273 return { baseUrlHttp, baseUrlWs }
1276 private getThumbnailUrl (baseUrlHttp: string) {
1277 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1280 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1281 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1284 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1285 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1288 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1289 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1290 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1291 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1293 const magnetHash = {
1297 infoHash: videoFile.infoHash,
1301 return magnetUtil.encode(magnetHash)