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 { VideoFilter } from '../../../shared/models/videos/video-query.type'
33 import { activityPubCollection } from '../../helpers/activitypub'
34 import { createTorrentPromise, renamePromise, statPromise, unlinkPromise, writeFilePromise } from '../../helpers/core-utils'
35 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
36 import { isBooleanValid } from '../../helpers/custom-validators/misc'
39 isVideoDescriptionValid,
46 } from '../../helpers/custom-validators/videos'
47 import { generateImageFromVideoFile, getVideoFileResolution, transcode } from '../../helpers/ffmpeg-utils'
48 import { logger } from '../../helpers/logger'
49 import { getServerActor } from '../../helpers/utils'
62 } from '../../initializers'
64 getVideoCommentsActivityPubUrl,
65 getVideoDislikesActivityPubUrl,
66 getVideoLikesActivityPubUrl,
67 getVideoSharesActivityPubUrl
68 } from '../../lib/activitypub'
69 import { sendDeleteVideo } from '../../lib/activitypub/send'
70 import { AccountModel } from '../account/account'
71 import { AccountVideoRateModel } from '../account/account-video-rate'
72 import { ActorModel } from '../activitypub/actor'
73 import { AvatarModel } from '../avatar/avatar'
74 import { ServerModel } from '../server/server'
75 import { getSort, throwIfNotValid } from '../utils'
76 import { TagModel } from './tag'
77 import { VideoAbuseModel } from './video-abuse'
78 import { VideoChannelModel } from './video-channel'
79 import { VideoCommentModel } from './video-comment'
80 import { VideoFileModel } from './video-file'
81 import { VideoShareModel } from './video-share'
82 import { VideoTagModel } from './video-tag'
85 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
86 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
87 WITH_TAGS = 'WITH_TAGS',
88 WITH_FILES = 'WITH_FILES',
89 WITH_SHARES = 'WITH_SHARES',
90 WITH_RATES = 'WITH_RATES',
91 WITH_COMMENTS = 'WITH_COMMENTS'
95 [ScopeNames.AVAILABLE_FOR_LIST]: (actorId: number, filter?: VideoFilter) => ({
98 [Sequelize.Op.notIn]: Sequelize.literal(
99 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
101 [ Sequelize.Op.in ]: Sequelize.literal(
103 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
104 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
105 'WHERE "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
107 'SELECT "video"."id" AS "id" FROM "video" ' +
108 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
109 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
110 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
111 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
112 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
116 privacy: VideoPrivacy.PUBLIC
120 attributes: [ 'name', 'description' ],
121 model: VideoChannelModel.unscoped(),
125 attributes: [ 'name' ],
126 model: AccountModel.unscoped(),
130 attributes: [ 'preferredUsername', 'url', 'serverId' ],
131 model: ActorModel.unscoped(),
133 where: VideoModel.buildActorWhereWithFilter(filter),
136 attributes: [ 'host' ],
137 model: ServerModel.unscoped(),
141 model: AvatarModel.unscoped(),
152 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
155 model: () => VideoChannelModel.unscoped(),
160 exclude: [ 'privateKey', 'publicKey' ]
162 model: () => ActorModel.unscoped(),
166 attributes: [ 'host' ],
167 model: () => ServerModel.unscoped(),
173 model: () => AccountModel.unscoped(),
177 model: () => ActorModel.unscoped(),
179 exclude: [ 'privateKey', 'publicKey' ]
184 attributes: [ 'host' ],
185 model: () => ServerModel.unscoped(),
189 model: () => AvatarModel.unscoped(),
200 [ScopeNames.WITH_TAGS]: {
201 include: [ () => TagModel ]
203 [ScopeNames.WITH_FILES]: {
206 model: () => VideoFileModel,
211 [ScopeNames.WITH_SHARES]: {
214 model: () => VideoShareModel,
215 include: [ () => ActorModel ]
219 [ScopeNames.WITH_RATES]: {
222 model: () => AccountVideoRateModel,
223 include: [ () => AccountModel ]
227 [ScopeNames.WITH_COMMENTS]: {
230 model: () => VideoCommentModel
242 fields: [ 'createdAt' ]
245 fields: [ 'duration' ]
257 fields: [ 'channelId' ]
260 fields: [ 'id', 'privacy' ]
268 export class VideoModel extends Model<VideoModel> {
271 @Default(DataType.UUIDV4)
273 @Column(DataType.UUID)
277 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
283 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
289 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
295 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
300 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
305 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
311 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
312 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
317 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
318 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
322 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
352 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
353 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
358 commentsEnabled: boolean
366 @ForeignKey(() => VideoChannelModel)
370 @BelongsTo(() => VideoChannelModel, {
376 VideoChannel: VideoChannelModel
378 @BelongsToMany(() => TagModel, {
379 foreignKey: 'videoId',
380 through: () => VideoTagModel,
385 @HasMany(() => VideoAbuseModel, {
392 VideoAbuses: VideoAbuseModel[]
394 @HasMany(() => VideoFileModel, {
401 VideoFiles: VideoFileModel[]
403 @HasMany(() => VideoShareModel, {
410 VideoShares: VideoShareModel[]
412 @HasMany(() => AccountVideoRateModel, {
419 AccountVideoRates: AccountVideoRateModel[]
421 @HasMany(() => VideoCommentModel, {
429 VideoComments: VideoCommentModel[]
432 static async sendDelete (instance: VideoModel, options) {
433 if (instance.isOwned()) {
434 if (!instance.VideoChannel) {
435 instance.VideoChannel = await instance.$get('VideoChannel', {
439 include: [ ActorModel ]
442 transaction: options.transaction
443 }) as VideoChannelModel
446 logger.debug('Sending delete of video %s.', instance.url)
448 return sendDeleteVideo(instance, options.transaction)
455 static async removeFilesAndSendDelete (instance: VideoModel) {
456 const tasks: Promise<any>[] = []
458 tasks.push(instance.removeThumbnail())
460 if (instance.isOwned()) {
461 if (!Array.isArray(instance.VideoFiles)) {
462 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
465 tasks.push(instance.removePreview())
467 // Remove physical files and torrents
468 instance.VideoFiles.forEach(file => {
469 tasks.push(instance.removeFile(file))
470 tasks.push(instance.removeTorrent(file))
474 return Promise.all(tasks)
476 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, err)
481 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
484 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
485 function getRawQuery (select: string) {
486 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
487 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
488 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
489 'WHERE "Account"."actorId" = ' + actorId
490 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
491 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
492 'WHERE "VideoShare"."actorId" = ' + actorId
494 return `(${queryVideo}) UNION (${queryVideoShare})`
497 const rawQuery = getRawQuery('"Video"."id"')
498 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
504 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
507 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
510 { privacy: VideoPrivacy.PUBLIC },
511 { privacy: VideoPrivacy.UNLISTED }
516 attributes: [ 'id', 'url' ],
517 model: VideoShareModel.unscoped(),
520 [Sequelize.Op.and]: [
523 [Sequelize.Op.not]: null
533 attributes: [ 'id', 'url' ],
534 model: ActorModel.unscoped()
539 model: VideoChannelModel.unscoped(),
543 attributes: [ 'name' ],
544 model: AccountModel.unscoped(),
548 attributes: [ 'id', 'url' ],
549 model: ActorModel.unscoped(),
555 attributes: [ 'id', 'url' ],
556 model: ActorModel.unscoped(),
562 attributes: [ 'type' ],
563 model: AccountVideoRateModel,
567 attributes: [ 'id' ],
568 model: AccountModel.unscoped(),
571 attributes: [ 'url' ],
572 model: ActorModel.unscoped(),
575 attributes: [ 'host' ],
586 attributes: [ 'url' ],
587 model: VideoCommentModel,
595 return Bluebird.all([
596 // FIXME: typing issue
597 VideoModel.findAll(query as any),
598 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
599 ]).then(([ rows, totals ]) => {
600 // totals: totalVideos + totalVideoShares
602 let totalVideoShares = 0
603 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
604 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
606 const total = totalVideos + totalVideoShares
614 static listUserVideosForApi (userId: number, start: number, count: number, sort: string) {
618 order: getSort(sort),
621 model: VideoChannelModel,
636 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
644 static async listForApi (start: number, count: number, sort: string, filter?: VideoFilter) {
651 const serverActor = await getServerActor()
653 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id, filter ] })
654 .findAndCountAll(query)
655 .then(({ rows, count }) => {
663 static async searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) {
664 const query: IFindOptions<VideoModel> = {
667 order: getSort(sort),
670 [Sequelize.Op.iLike]: '%' + value + '%'
675 const serverActor = await getServerActor()
677 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
678 .findAndCountAll(query).then(({ rows, count }) => {
686 static load (id: number) {
687 return VideoModel.findById(id)
690 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
691 const query: IFindOptions<VideoModel> = {
697 if (t !== undefined) query.transaction = t
699 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
702 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
703 const query: IFindOptions<VideoModel> = {
712 if (t !== undefined) query.transaction = t
714 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
717 static loadAndPopulateAccountAndServerAndTags (id: number) {
719 order: [ [ 'Tags', 'name', 'ASC' ] ]
723 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
724 .findById(id, options)
727 static loadByUUID (uuid: string) {
735 .scope([ ScopeNames.WITH_FILES ])
739 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
741 order: [ [ 'Tags', 'name', 'ASC' ] ],
748 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
752 static loadAndPopulateAll (id: number) {
754 order: [ [ 'Tags', 'name', 'ASC' ] ],
762 ScopeNames.WITH_RATES,
763 ScopeNames.WITH_SHARES,
764 ScopeNames.WITH_TAGS,
765 ScopeNames.WITH_FILES,
766 ScopeNames.WITH_ACCOUNT_DETAILS,
767 ScopeNames.WITH_COMMENTS
772 static async getStats () {
773 const totalLocalVideos = await VideoModel.count({
778 const totalVideos = await VideoModel.count()
780 let totalLocalVideoViews = await VideoModel.sum('views', {
785 // Sequelize could return null...
786 if (!totalLocalVideoViews) totalLocalVideoViews = 0
790 totalLocalVideoViews,
795 private static buildActorWhereWithFilter (filter?: VideoFilter) {
796 if (filter && filter === 'local') {
806 if (Array.isArray(this.VideoFiles) === false) return undefined
808 // The original file is the file that have the higher resolution
809 return maxBy(this.VideoFiles, file => file.resolution)
812 getVideoFilename (videoFile: VideoFileModel) {
813 return this.uuid + '-' + videoFile.resolution + videoFile.extname
816 getThumbnailName () {
817 // We always have a copy of the thumbnail
818 const extension = '.jpg'
819 return this.uuid + extension
823 const extension = '.jpg'
824 return this.uuid + extension
827 getTorrentFileName (videoFile: VideoFileModel) {
828 const extension = '.torrent'
829 return this.uuid + '-' + videoFile.resolution + extension
833 return this.remote === false
836 createPreview (videoFile: VideoFileModel) {
837 return generateImageFromVideoFile(
838 this.getVideoFilePath(videoFile),
839 CONFIG.STORAGE.PREVIEWS_DIR,
840 this.getPreviewName(),
845 createThumbnail (videoFile: VideoFileModel) {
846 return generateImageFromVideoFile(
847 this.getVideoFilePath(videoFile),
848 CONFIG.STORAGE.THUMBNAILS_DIR,
849 this.getThumbnailName(),
854 getVideoFilePath (videoFile: VideoFileModel) {
855 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
858 createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) {
861 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
862 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
865 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
869 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
871 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
872 logger.info('Creating torrent %s.', filePath)
874 await writeFilePromise(filePath, torrent)
876 const parsedTorrent = parseTorrent(torrent)
877 videoFile.infoHash = parsedTorrent.infoHash
881 return '/videos/embed/' + this.uuid
884 getThumbnailPath () {
885 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
889 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
892 toFormattedJSON (): Video {
893 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
899 category: this.category,
900 categoryLabel: this.getCategoryLabel(),
901 licence: this.licence,
902 licenceLabel: this.getLicenceLabel(),
903 language: this.language,
904 languageLabel: this.getLanguageLabel(),
906 description: this.getTruncatedDescription(),
907 isLocal: this.isOwned(),
908 duration: this.duration,
911 dislikes: this.dislikes,
912 thumbnailPath: this.getThumbnailPath(),
913 previewPath: this.getPreviewPath(),
914 embedPath: this.getEmbedPath(),
915 createdAt: this.createdAt,
916 updatedAt: this.updatedAt,
918 name: formattedAccount.name,
919 displayName: formattedAccount.displayName,
920 url: formattedAccount.url,
921 host: formattedAccount.host,
922 avatar: formattedAccount.avatar
927 toFormattedDetailsJSON (): VideoDetails {
928 const formattedJson = this.toFormattedJSON()
930 // Maybe our server is not up to date and there are new privacy settings since our version
931 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
932 if (!privacyLabel) privacyLabel = 'Unknown'
934 const detailsJson = {
936 privacy: this.privacy,
937 support: this.support,
938 descriptionPath: this.getDescriptionPath(),
939 channel: this.VideoChannel.toFormattedJSON(),
940 account: this.VideoChannel.Account.toFormattedJSON(),
941 tags: map<TagModel, string>(this.Tags, 'name'),
942 commentsEnabled: this.commentsEnabled,
946 // Format and sort video files
947 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
948 detailsJson.files = this.VideoFiles
950 let resolutionLabel = videoFile.resolution + 'p'
953 resolution: videoFile.resolution,
955 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
956 size: videoFile.size,
957 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
958 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
962 if (a.resolution < b.resolution) return 1
963 if (a.resolution === b.resolution) return 0
967 return Object.assign(formattedJson, detailsJson)
970 toActivityPubObject (): VideoTorrentObject {
971 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
972 if (!this.Tags) this.Tags = []
974 const tag = this.Tags.map(t => ({
975 type: 'Hashtag' as 'Hashtag',
982 identifier: this.language + '',
983 name: this.getLanguageLabel()
990 identifier: this.category + '',
991 name: this.getCategoryLabel()
998 identifier: this.licence + '',
999 name: this.getLicenceLabel()
1006 if (Array.isArray(this.AccountVideoRates)) {
1007 const res = this.toRatesActivityPubObjects()
1008 likesObject = res.likesObject
1009 dislikesObject = res.dislikesObject
1013 if (Array.isArray(this.VideoShares)) {
1014 sharesObject = this.toAnnouncesActivityPubObject()
1018 if (Array.isArray(this.VideoComments)) {
1019 commentsObject = this.toCommentsActivityPubObject()
1023 for (const file of this.VideoFiles) {
1026 mimeType: 'video/' + file.extname.replace('.', ''),
1027 href: this.getVideoFileUrl(file, baseUrlHttp),
1028 width: file.resolution,
1034 mimeType: 'application/x-bittorrent',
1035 href: this.getTorrentUrl(file, baseUrlHttp),
1036 width: file.resolution
1041 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1042 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1043 width: file.resolution
1047 // Add video url too
1050 mimeType: 'text/html',
1051 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1055 type: 'Video' as 'Video',
1058 duration: this.getActivityStreamDuration(),
1065 sensitive: this.nsfw,
1066 commentsEnabled: this.commentsEnabled,
1067 published: this.createdAt.toISOString(),
1068 updated: this.updatedAt.toISOString(),
1069 mediaType: 'text/markdown',
1070 content: this.getTruncatedDescription(),
1071 support: this.support,
1074 url: this.getThumbnailUrl(baseUrlHttp),
1075 mediaType: 'image/jpeg',
1076 width: THUMBNAILS_SIZE.width,
1077 height: THUMBNAILS_SIZE.height
1081 dislikes: dislikesObject,
1082 shares: sharesObject,
1083 comments: commentsObject,
1087 id: this.VideoChannel.Actor.url
1091 id: this.VideoChannel.Account.Actor.url
1097 toAnnouncesActivityPubObject () {
1098 const shares: string[] = []
1100 for (const videoShare of this.VideoShares) {
1101 shares.push(videoShare.url)
1104 return activityPubCollection(getVideoSharesActivityPubUrl(this), shares)
1107 toCommentsActivityPubObject () {
1108 const comments: string[] = []
1110 for (const videoComment of this.VideoComments) {
1111 comments.push(videoComment.url)
1114 return activityPubCollection(getVideoCommentsActivityPubUrl(this), comments)
1117 toRatesActivityPubObjects () {
1118 const likes: string[] = []
1119 const dislikes: string[] = []
1121 for (const rate of this.AccountVideoRates) {
1122 if (rate.type === 'like') {
1123 likes.push(rate.Account.Actor.url)
1124 } else if (rate.type === 'dislike') {
1125 dislikes.push(rate.Account.Actor.url)
1129 const likesObject = activityPubCollection(getVideoLikesActivityPubUrl(this), likes)
1130 const dislikesObject = activityPubCollection(getVideoDislikesActivityPubUrl(this), dislikes)
1132 return { likesObject, dislikesObject }
1135 getTruncatedDescription () {
1136 if (!this.description) return null
1139 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1142 return truncate(this.description, options)
1145 optimizeOriginalVideofile = async function () {
1146 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1147 const newExtname = '.mp4'
1148 const inputVideoFile = this.getOriginalFile()
1149 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1150 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1152 const transcodeOptions = {
1153 inputPath: videoInputPath,
1154 outputPath: videoOutputPath
1157 // Could be very long!
1158 await transcode(transcodeOptions)
1161 await unlinkPromise(videoInputPath)
1163 // Important to do this before getVideoFilename() to take in account the new file extension
1164 inputVideoFile.set('extname', newExtname)
1166 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1167 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1169 inputVideoFile.set('size', stats.size)
1171 await this.createTorrentAndSetInfoHash(inputVideoFile)
1172 await inputVideoFile.save()
1175 // Auto destruction...
1176 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
1182 transcodeOriginalVideofile = async function (resolution: VideoResolution, isPortraitMode: boolean) {
1183 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1184 const extname = '.mp4'
1186 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1187 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1189 const newVideoFile = new VideoFileModel({
1195 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1197 const transcodeOptions = {
1198 inputPath: videoInputPath,
1199 outputPath: videoOutputPath,
1204 await transcode(transcodeOptions)
1206 const stats = await statPromise(videoOutputPath)
1208 newVideoFile.set('size', stats.size)
1210 await this.createTorrentAndSetInfoHash(newVideoFile)
1212 await newVideoFile.save()
1214 this.VideoFiles.push(newVideoFile)
1217 getOriginalFileResolution () {
1218 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1220 return getVideoFileResolution(originalFilePath)
1223 getDescriptionPath () {
1224 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1227 getCategoryLabel () {
1228 let categoryLabel = VIDEO_CATEGORIES[this.category]
1229 if (!categoryLabel) categoryLabel = 'Misc'
1231 return categoryLabel
1234 getLicenceLabel () {
1235 let licenceLabel = VIDEO_LICENCES[this.licence]
1236 if (!licenceLabel) licenceLabel = 'Unknown'
1241 getLanguageLabel () {
1242 let languageLabel = VIDEO_LANGUAGES[this.language]
1243 if (!languageLabel) languageLabel = 'Unknown'
1245 return languageLabel
1248 removeThumbnail () {
1249 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1250 return unlinkPromise(thumbnailPath)
1254 // Same name than video thumbnail
1255 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1258 removeFile (videoFile: VideoFileModel) {
1259 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1260 return unlinkPromise(filePath)
1263 removeTorrent (videoFile: VideoFileModel) {
1264 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1265 return unlinkPromise(torrentPath)
1268 getActivityStreamDuration () {
1269 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1270 return 'PT' + this.duration + 'S'
1273 private getBaseUrls () {
1277 if (this.isOwned()) {
1278 baseUrlHttp = CONFIG.WEBSERVER.URL
1279 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1281 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1282 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1285 return { baseUrlHttp, baseUrlWs }
1288 private getThumbnailUrl (baseUrlHttp: string) {
1289 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1292 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1293 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1296 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1297 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1300 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1301 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1302 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1303 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1305 const magnetHash = {
1309 infoHash: videoFile.infoHash,
1313 return magnetUtil.encode(magnetHash)