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.unscoped(),
211 [ScopeNames.WITH_SHARES]: {
214 model: () => VideoShareModel.unscoped()
218 [ScopeNames.WITH_RATES]: {
221 model: () => AccountVideoRateModel,
224 model: () => AccountModel.unscoped(),
228 attributes: [ 'url' ],
229 model: () => ActorModel.unscoped()
237 [ScopeNames.WITH_COMMENTS]: {
240 model: () => VideoCommentModel.unscoped()
252 fields: [ 'createdAt' ]
255 fields: [ 'duration' ]
267 fields: [ 'channelId' ]
270 fields: [ 'id', 'privacy' ]
278 export class VideoModel extends Model<VideoModel> {
281 @Default(DataType.UUIDV4)
283 @Column(DataType.UUID)
287 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
293 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
299 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
305 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
310 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
315 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
321 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
322 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
327 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
328 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
332 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
362 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
363 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
368 commentsEnabled: boolean
376 @ForeignKey(() => VideoChannelModel)
380 @BelongsTo(() => VideoChannelModel, {
386 VideoChannel: VideoChannelModel
388 @BelongsToMany(() => TagModel, {
389 foreignKey: 'videoId',
390 through: () => VideoTagModel,
395 @HasMany(() => VideoAbuseModel, {
402 VideoAbuses: VideoAbuseModel[]
404 @HasMany(() => VideoFileModel, {
411 VideoFiles: VideoFileModel[]
413 @HasMany(() => VideoShareModel, {
420 VideoShares: VideoShareModel[]
422 @HasMany(() => AccountVideoRateModel, {
429 AccountVideoRates: AccountVideoRateModel[]
431 @HasMany(() => VideoCommentModel, {
439 VideoComments: VideoCommentModel[]
442 static async sendDelete (instance: VideoModel, options) {
443 if (instance.isOwned()) {
444 if (!instance.VideoChannel) {
445 instance.VideoChannel = await instance.$get('VideoChannel', {
449 include: [ ActorModel ]
452 transaction: options.transaction
453 }) as VideoChannelModel
456 logger.debug('Sending delete of video %s.', instance.url)
458 return sendDeleteVideo(instance, options.transaction)
465 static async removeFilesAndSendDelete (instance: VideoModel) {
466 const tasks: Promise<any>[] = []
468 tasks.push(instance.removeThumbnail())
470 if (instance.isOwned()) {
471 if (!Array.isArray(instance.VideoFiles)) {
472 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
475 tasks.push(instance.removePreview())
477 // Remove physical files and torrents
478 instance.VideoFiles.forEach(file => {
479 tasks.push(instance.removeFile(file))
480 tasks.push(instance.removeTorrent(file))
484 return Promise.all(tasks)
486 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
491 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
494 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
495 function getRawQuery (select: string) {
496 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
497 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
498 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
499 'WHERE "Account"."actorId" = ' + actorId
500 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
501 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
502 'WHERE "VideoShare"."actorId" = ' + actorId
504 return `(${queryVideo}) UNION (${queryVideoShare})`
507 const rawQuery = getRawQuery('"Video"."id"')
508 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
514 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
517 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
520 { privacy: VideoPrivacy.PUBLIC },
521 { privacy: VideoPrivacy.UNLISTED }
526 attributes: [ 'id', 'url' ],
527 model: VideoShareModel.unscoped(),
530 [Sequelize.Op.and]: [
533 [Sequelize.Op.not]: null
543 attributes: [ 'id', 'url' ],
544 model: ActorModel.unscoped()
549 model: VideoChannelModel.unscoped(),
553 attributes: [ 'name' ],
554 model: AccountModel.unscoped(),
558 attributes: [ 'id', 'url' ],
559 model: ActorModel.unscoped(),
565 attributes: [ 'id', 'url' ],
566 model: ActorModel.unscoped(),
572 attributes: [ 'type' ],
573 model: AccountVideoRateModel,
577 attributes: [ 'id' ],
578 model: AccountModel.unscoped(),
581 attributes: [ 'url' ],
582 model: ActorModel.unscoped(),
585 attributes: [ 'host' ],
596 attributes: [ 'url' ],
597 model: VideoCommentModel,
605 return Bluebird.all([
606 // FIXME: typing issue
607 VideoModel.findAll(query as any),
608 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
609 ]).then(([ rows, totals ]) => {
610 // totals: totalVideos + totalVideoShares
612 let totalVideoShares = 0
613 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
614 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
616 const total = totalVideos + totalVideoShares
624 static listUserVideosForApi (userId: number, start: number, count: number, sort: string) {
628 order: getSort(sort),
631 model: VideoChannelModel,
646 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
654 static async listForApi (start: number, count: number, sort: string, filter?: VideoFilter) {
661 const serverActor = await getServerActor()
663 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id, filter ] })
664 .findAndCountAll(query)
665 .then(({ rows, count }) => {
673 static async searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) {
674 const query: IFindOptions<VideoModel> = {
677 order: getSort(sort),
680 [Sequelize.Op.iLike]: '%' + value + '%'
685 const serverActor = await getServerActor()
687 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
688 .findAndCountAll(query).then(({ rows, count }) => {
696 static load (id: number) {
697 return VideoModel.findById(id)
700 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
701 const query: IFindOptions<VideoModel> = {
707 if (t !== undefined) query.transaction = t
709 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
712 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
713 const query: IFindOptions<VideoModel> = {
722 if (t !== undefined) query.transaction = t
724 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
727 static loadAndPopulateAccountAndServerAndTags (id: number) {
729 order: [ [ 'Tags', 'name', 'ASC' ] ]
733 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
734 .findById(id, options)
737 static loadByUUID (uuid: string) {
745 .scope([ ScopeNames.WITH_FILES ])
749 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
751 order: [ [ 'Tags', 'name', 'ASC' ] ],
758 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
762 static loadAndPopulateAll (id: number) {
764 order: [ [ 'Tags', 'name', 'ASC' ] ],
772 ScopeNames.WITH_RATES,
773 ScopeNames.WITH_SHARES,
774 ScopeNames.WITH_TAGS,
775 ScopeNames.WITH_FILES,
776 ScopeNames.WITH_ACCOUNT_DETAILS,
777 ScopeNames.WITH_COMMENTS
782 static async getStats () {
783 const totalLocalVideos = await VideoModel.count({
788 const totalVideos = await VideoModel.count()
790 let totalLocalVideoViews = await VideoModel.sum('views', {
795 // Sequelize could return null...
796 if (!totalLocalVideoViews) totalLocalVideoViews = 0
800 totalLocalVideoViews,
805 private static buildActorWhereWithFilter (filter?: VideoFilter) {
806 if (filter && filter === 'local') {
815 private static getCategoryLabel (id: number) {
816 let categoryLabel = VIDEO_CATEGORIES[id]
817 if (!categoryLabel) categoryLabel = 'Misc'
822 private static getLicenceLabel (id: number) {
823 let licenceLabel = VIDEO_LICENCES[id]
824 if (!licenceLabel) licenceLabel = 'Unknown'
829 private static getLanguageLabel (id: number) {
830 let languageLabel = VIDEO_LANGUAGES[id]
831 if (!languageLabel) languageLabel = 'Unknown'
837 if (Array.isArray(this.VideoFiles) === false) return undefined
839 // The original file is the file that have the higher resolution
840 return maxBy(this.VideoFiles, file => file.resolution)
843 getVideoFilename (videoFile: VideoFileModel) {
844 return this.uuid + '-' + videoFile.resolution + videoFile.extname
847 getThumbnailName () {
848 // We always have a copy of the thumbnail
849 const extension = '.jpg'
850 return this.uuid + extension
854 const extension = '.jpg'
855 return this.uuid + extension
858 getTorrentFileName (videoFile: VideoFileModel) {
859 const extension = '.torrent'
860 return this.uuid + '-' + videoFile.resolution + extension
864 return this.remote === false
867 createPreview (videoFile: VideoFileModel) {
868 return generateImageFromVideoFile(
869 this.getVideoFilePath(videoFile),
870 CONFIG.STORAGE.PREVIEWS_DIR,
871 this.getPreviewName(),
876 createThumbnail (videoFile: VideoFileModel) {
877 return generateImageFromVideoFile(
878 this.getVideoFilePath(videoFile),
879 CONFIG.STORAGE.THUMBNAILS_DIR,
880 this.getThumbnailName(),
885 getVideoFilePath (videoFile: VideoFileModel) {
886 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
889 createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) {
892 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
893 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
896 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
900 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
902 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
903 logger.info('Creating torrent %s.', filePath)
905 await writeFilePromise(filePath, torrent)
907 const parsedTorrent = parseTorrent(torrent)
908 videoFile.infoHash = parsedTorrent.infoHash
912 return '/videos/embed/' + this.uuid
915 getThumbnailPath () {
916 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
920 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
923 toFormattedJSON (): Video {
924 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
932 label: VideoModel.getCategoryLabel(this.category)
936 label: VideoModel.getLicenceLabel(this.licence)
940 label: VideoModel.getLanguageLabel(this.language)
943 description: this.getTruncatedDescription(),
944 isLocal: this.isOwned(),
945 duration: this.duration,
948 dislikes: this.dislikes,
949 thumbnailPath: this.getThumbnailPath(),
950 previewPath: this.getPreviewPath(),
951 embedPath: this.getEmbedPath(),
952 createdAt: this.createdAt,
953 updatedAt: this.updatedAt,
955 name: formattedAccount.name,
956 displayName: formattedAccount.displayName,
957 url: formattedAccount.url,
958 host: formattedAccount.host,
959 avatar: formattedAccount.avatar
964 toFormattedDetailsJSON (): VideoDetails {
965 const formattedJson = this.toFormattedJSON()
967 // Maybe our server is not up to date and there are new privacy settings since our version
968 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
969 if (!privacyLabel) privacyLabel = 'Unknown'
971 const detailsJson = {
976 support: this.support,
977 descriptionPath: this.getDescriptionPath(),
978 channel: this.VideoChannel.toFormattedJSON(),
979 account: this.VideoChannel.Account.toFormattedJSON(),
980 tags: map<TagModel, string>(this.Tags, 'name'),
981 commentsEnabled: this.commentsEnabled,
985 // Format and sort video files
986 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
987 detailsJson.files = this.VideoFiles
989 let resolutionLabel = videoFile.resolution + 'p'
993 id: videoFile.resolution,
994 label: resolutionLabel
996 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
997 size: videoFile.size,
998 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
999 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
1003 if (a.resolution.id < b.resolution.id) return 1
1004 if (a.resolution.id === b.resolution.id) return 0
1008 return Object.assign(formattedJson, detailsJson)
1011 toActivityPubObject (): VideoTorrentObject {
1012 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1013 if (!this.Tags) this.Tags = []
1015 const tag = this.Tags.map(t => ({
1016 type: 'Hashtag' as 'Hashtag',
1021 if (this.language) {
1023 identifier: this.language + '',
1024 name: VideoModel.getLanguageLabel(this.language)
1029 if (this.category) {
1031 identifier: this.category + '',
1032 name: VideoModel.getCategoryLabel(this.category)
1039 identifier: this.licence + '',
1040 name: VideoModel.getLicenceLabel(this.licence)
1047 if (Array.isArray(this.AccountVideoRates)) {
1048 const res = this.toRatesActivityPubObjects()
1049 likesObject = res.likesObject
1050 dislikesObject = res.dislikesObject
1054 if (Array.isArray(this.VideoShares)) {
1055 sharesObject = this.toAnnouncesActivityPubObject()
1059 if (Array.isArray(this.VideoComments)) {
1060 commentsObject = this.toCommentsActivityPubObject()
1064 for (const file of this.VideoFiles) {
1067 mimeType: 'video/' + file.extname.replace('.', ''),
1068 href: this.getVideoFileUrl(file, baseUrlHttp),
1069 width: file.resolution,
1075 mimeType: 'application/x-bittorrent',
1076 href: this.getTorrentUrl(file, baseUrlHttp),
1077 width: file.resolution
1082 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1083 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1084 width: file.resolution
1088 // Add video url too
1091 mimeType: 'text/html',
1092 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1096 type: 'Video' as 'Video',
1099 duration: this.getActivityStreamDuration(),
1106 sensitive: this.nsfw,
1107 commentsEnabled: this.commentsEnabled,
1108 published: this.createdAt.toISOString(),
1109 updated: this.updatedAt.toISOString(),
1110 mediaType: 'text/markdown',
1111 content: this.getTruncatedDescription(),
1112 support: this.support,
1115 url: this.getThumbnailUrl(baseUrlHttp),
1116 mediaType: 'image/jpeg',
1117 width: THUMBNAILS_SIZE.width,
1118 height: THUMBNAILS_SIZE.height
1122 dislikes: dislikesObject,
1123 shares: sharesObject,
1124 comments: commentsObject,
1128 id: this.VideoChannel.Account.Actor.url
1132 id: this.VideoChannel.Actor.url
1138 toAnnouncesActivityPubObject () {
1139 const shares: string[] = []
1141 for (const videoShare of this.VideoShares) {
1142 shares.push(videoShare.url)
1145 return activityPubCollection(getVideoSharesActivityPubUrl(this), shares)
1148 toCommentsActivityPubObject () {
1149 const comments: string[] = []
1151 for (const videoComment of this.VideoComments) {
1152 comments.push(videoComment.url)
1155 return activityPubCollection(getVideoCommentsActivityPubUrl(this), comments)
1158 toRatesActivityPubObjects () {
1159 const likes: string[] = []
1160 const dislikes: string[] = []
1162 for (const rate of this.AccountVideoRates) {
1163 if (rate.type === 'like') {
1164 likes.push(rate.Account.Actor.url)
1165 } else if (rate.type === 'dislike') {
1166 dislikes.push(rate.Account.Actor.url)
1170 const likesObject = activityPubCollection(getVideoLikesActivityPubUrl(this), likes)
1171 const dislikesObject = activityPubCollection(getVideoDislikesActivityPubUrl(this), dislikes)
1173 return { likesObject, dislikesObject }
1176 getTruncatedDescription () {
1177 if (!this.description) return null
1179 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1184 const truncatedDescription = truncate(this.description, options)
1186 // The truncated string is okay, we can return it
1187 if (truncatedDescription.length <= maxLength) return truncatedDescription
1189 // Lodash takes into account all UTF characters, whereas String.prototype.length does not: some characters have a length of 2
1190 // We always use the .length so we need to truncate more if needed
1191 options.length -= maxLength - truncatedDescription.length
1192 return truncate(this.description, options)
1195 optimizeOriginalVideofile = async function () {
1196 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1197 const newExtname = '.mp4'
1198 const inputVideoFile = this.getOriginalFile()
1199 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1200 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1202 const transcodeOptions = {
1203 inputPath: videoInputPath,
1204 outputPath: videoOutputPath
1207 // Could be very long!
1208 await transcode(transcodeOptions)
1211 await unlinkPromise(videoInputPath)
1213 // Important to do this before getVideoFilename() to take in account the new file extension
1214 inputVideoFile.set('extname', newExtname)
1216 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1217 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1219 inputVideoFile.set('size', stats.size)
1221 await this.createTorrentAndSetInfoHash(inputVideoFile)
1222 await inputVideoFile.save()
1225 // Auto destruction...
1226 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1232 transcodeOriginalVideofile = async function (resolution: VideoResolution, isPortraitMode: boolean) {
1233 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1234 const extname = '.mp4'
1236 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1237 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1239 const newVideoFile = new VideoFileModel({
1245 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1247 const transcodeOptions = {
1248 inputPath: videoInputPath,
1249 outputPath: videoOutputPath,
1254 await transcode(transcodeOptions)
1256 const stats = await statPromise(videoOutputPath)
1258 newVideoFile.set('size', stats.size)
1260 await this.createTorrentAndSetInfoHash(newVideoFile)
1262 await newVideoFile.save()
1264 this.VideoFiles.push(newVideoFile)
1267 getOriginalFileResolution () {
1268 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1270 return getVideoFileResolution(originalFilePath)
1273 getDescriptionPath () {
1274 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1277 removeThumbnail () {
1278 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1279 return unlinkPromise(thumbnailPath)
1283 // Same name than video thumbnail
1284 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1287 removeFile (videoFile: VideoFileModel) {
1288 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1289 return unlinkPromise(filePath)
1292 removeTorrent (videoFile: VideoFileModel) {
1293 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1294 return unlinkPromise(torrentPath)
1297 getActivityStreamDuration () {
1298 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1299 return 'PT' + this.duration + 'S'
1302 private getBaseUrls () {
1306 if (this.isOwned()) {
1307 baseUrlHttp = CONFIG.WEBSERVER.URL
1308 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1310 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1311 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1314 return { baseUrlHttp, baseUrlWs }
1317 private getThumbnailUrl (baseUrlHttp: string) {
1318 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1321 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1322 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1325 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1326 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1329 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1330 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1331 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1332 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1334 const magnetHash = {
1338 infoHash: videoFile.infoHash,
1342 return magnetUtil.encode(magnetHash)