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') {
805 private static getCategoryLabel (id: number) {
806 let categoryLabel = VIDEO_CATEGORIES[id]
807 if (!categoryLabel) categoryLabel = 'Misc'
812 private static getLicenceLabel (id: number) {
813 let licenceLabel = VIDEO_LICENCES[id]
814 if (!licenceLabel) licenceLabel = 'Unknown'
819 private static getLanguageLabel (id: number) {
820 let languageLabel = VIDEO_LANGUAGES[id]
821 if (!languageLabel) languageLabel = 'Unknown'
827 if (Array.isArray(this.VideoFiles) === false) return undefined
829 // The original file is the file that have the higher resolution
830 return maxBy(this.VideoFiles, file => file.resolution)
833 getVideoFilename (videoFile: VideoFileModel) {
834 return this.uuid + '-' + videoFile.resolution + videoFile.extname
837 getThumbnailName () {
838 // We always have a copy of the thumbnail
839 const extension = '.jpg'
840 return this.uuid + extension
844 const extension = '.jpg'
845 return this.uuid + extension
848 getTorrentFileName (videoFile: VideoFileModel) {
849 const extension = '.torrent'
850 return this.uuid + '-' + videoFile.resolution + extension
854 return this.remote === false
857 createPreview (videoFile: VideoFileModel) {
858 return generateImageFromVideoFile(
859 this.getVideoFilePath(videoFile),
860 CONFIG.STORAGE.PREVIEWS_DIR,
861 this.getPreviewName(),
866 createThumbnail (videoFile: VideoFileModel) {
867 return generateImageFromVideoFile(
868 this.getVideoFilePath(videoFile),
869 CONFIG.STORAGE.THUMBNAILS_DIR,
870 this.getThumbnailName(),
875 getVideoFilePath (videoFile: VideoFileModel) {
876 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
879 createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) {
882 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
883 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
886 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
890 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
892 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
893 logger.info('Creating torrent %s.', filePath)
895 await writeFilePromise(filePath, torrent)
897 const parsedTorrent = parseTorrent(torrent)
898 videoFile.infoHash = parsedTorrent.infoHash
902 return '/videos/embed/' + this.uuid
905 getThumbnailPath () {
906 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
910 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
913 toFormattedJSON (): Video {
914 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
922 label: VideoModel.getCategoryLabel(this.category)
926 label: VideoModel.getLicenceLabel(this.licence)
930 label: VideoModel.getLanguageLabel(this.language)
933 description: this.getTruncatedDescription(),
934 isLocal: this.isOwned(),
935 duration: this.duration,
938 dislikes: this.dislikes,
939 thumbnailPath: this.getThumbnailPath(),
940 previewPath: this.getPreviewPath(),
941 embedPath: this.getEmbedPath(),
942 createdAt: this.createdAt,
943 updatedAt: this.updatedAt,
945 name: formattedAccount.name,
946 displayName: formattedAccount.displayName,
947 url: formattedAccount.url,
948 host: formattedAccount.host,
949 avatar: formattedAccount.avatar
954 toFormattedDetailsJSON (): VideoDetails {
955 const formattedJson = this.toFormattedJSON()
957 // Maybe our server is not up to date and there are new privacy settings since our version
958 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
959 if (!privacyLabel) privacyLabel = 'Unknown'
961 const detailsJson = {
966 support: this.support,
967 descriptionPath: this.getDescriptionPath(),
968 channel: this.VideoChannel.toFormattedJSON(),
969 account: this.VideoChannel.Account.toFormattedJSON(),
970 tags: map<TagModel, string>(this.Tags, 'name'),
971 commentsEnabled: this.commentsEnabled,
975 // Format and sort video files
976 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
977 detailsJson.files = this.VideoFiles
979 let resolutionLabel = videoFile.resolution + 'p'
983 id: videoFile.resolution,
984 label: resolutionLabel
986 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
987 size: videoFile.size,
988 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
989 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
993 if (a.resolution.id < b.resolution.id) return 1
994 if (a.resolution.id === b.resolution.id) return 0
998 return Object.assign(formattedJson, detailsJson)
1001 toActivityPubObject (): VideoTorrentObject {
1002 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1003 if (!this.Tags) this.Tags = []
1005 const tag = this.Tags.map(t => ({
1006 type: 'Hashtag' as 'Hashtag',
1011 if (this.language) {
1013 identifier: this.language + '',
1014 name: VideoModel.getLanguageLabel(this.language)
1019 if (this.category) {
1021 identifier: this.category + '',
1022 name: VideoModel.getCategoryLabel(this.category)
1029 identifier: this.licence + '',
1030 name: VideoModel.getLicenceLabel(this.licence)
1037 if (Array.isArray(this.AccountVideoRates)) {
1038 const res = this.toRatesActivityPubObjects()
1039 likesObject = res.likesObject
1040 dislikesObject = res.dislikesObject
1044 if (Array.isArray(this.VideoShares)) {
1045 sharesObject = this.toAnnouncesActivityPubObject()
1049 if (Array.isArray(this.VideoComments)) {
1050 commentsObject = this.toCommentsActivityPubObject()
1054 for (const file of this.VideoFiles) {
1057 mimeType: 'video/' + file.extname.replace('.', ''),
1058 href: this.getVideoFileUrl(file, baseUrlHttp),
1059 width: file.resolution,
1065 mimeType: 'application/x-bittorrent',
1066 href: this.getTorrentUrl(file, baseUrlHttp),
1067 width: file.resolution
1072 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1073 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1074 width: file.resolution
1078 // Add video url too
1081 mimeType: 'text/html',
1082 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1086 type: 'Video' as 'Video',
1089 duration: this.getActivityStreamDuration(),
1096 sensitive: this.nsfw,
1097 commentsEnabled: this.commentsEnabled,
1098 published: this.createdAt.toISOString(),
1099 updated: this.updatedAt.toISOString(),
1100 mediaType: 'text/markdown',
1101 content: this.getTruncatedDescription(),
1102 support: this.support,
1105 url: this.getThumbnailUrl(baseUrlHttp),
1106 mediaType: 'image/jpeg',
1107 width: THUMBNAILS_SIZE.width,
1108 height: THUMBNAILS_SIZE.height
1112 dislikes: dislikesObject,
1113 shares: sharesObject,
1114 comments: commentsObject,
1118 id: this.VideoChannel.Account.Actor.url
1122 id: this.VideoChannel.Actor.url
1128 toAnnouncesActivityPubObject () {
1129 const shares: string[] = []
1131 for (const videoShare of this.VideoShares) {
1132 shares.push(videoShare.url)
1135 return activityPubCollection(getVideoSharesActivityPubUrl(this), shares)
1138 toCommentsActivityPubObject () {
1139 const comments: string[] = []
1141 for (const videoComment of this.VideoComments) {
1142 comments.push(videoComment.url)
1145 return activityPubCollection(getVideoCommentsActivityPubUrl(this), comments)
1148 toRatesActivityPubObjects () {
1149 const likes: string[] = []
1150 const dislikes: string[] = []
1152 for (const rate of this.AccountVideoRates) {
1153 if (rate.type === 'like') {
1154 likes.push(rate.Account.Actor.url)
1155 } else if (rate.type === 'dislike') {
1156 dislikes.push(rate.Account.Actor.url)
1160 const likesObject = activityPubCollection(getVideoLikesActivityPubUrl(this), likes)
1161 const dislikesObject = activityPubCollection(getVideoDislikesActivityPubUrl(this), dislikes)
1163 return { likesObject, dislikesObject }
1166 getTruncatedDescription () {
1167 if (!this.description) return null
1169 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1174 const truncatedDescription = truncate(this.description, options)
1176 // The truncated string is okay, we can return it
1177 if (truncatedDescription.length <= maxLength) return truncatedDescription
1179 // Lodash takes into account all UTF characters, whereas String.prototype.length does not: some characters have a length of 2
1180 // We always use the .length so we need to truncate more if needed
1181 options.length -= maxLength - truncatedDescription.length
1182 return truncate(this.description, options)
1185 optimizeOriginalVideofile = async function () {
1186 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1187 const newExtname = '.mp4'
1188 const inputVideoFile = this.getOriginalFile()
1189 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1190 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1192 const transcodeOptions = {
1193 inputPath: videoInputPath,
1194 outputPath: videoOutputPath
1197 // Could be very long!
1198 await transcode(transcodeOptions)
1201 await unlinkPromise(videoInputPath)
1203 // Important to do this before getVideoFilename() to take in account the new file extension
1204 inputVideoFile.set('extname', newExtname)
1206 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1207 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1209 inputVideoFile.set('size', stats.size)
1211 await this.createTorrentAndSetInfoHash(inputVideoFile)
1212 await inputVideoFile.save()
1215 // Auto destruction...
1216 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1222 transcodeOriginalVideofile = async function (resolution: VideoResolution, isPortraitMode: boolean) {
1223 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1224 const extname = '.mp4'
1226 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1227 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1229 const newVideoFile = new VideoFileModel({
1235 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1237 const transcodeOptions = {
1238 inputPath: videoInputPath,
1239 outputPath: videoOutputPath,
1244 await transcode(transcodeOptions)
1246 const stats = await statPromise(videoOutputPath)
1248 newVideoFile.set('size', stats.size)
1250 await this.createTorrentAndSetInfoHash(newVideoFile)
1252 await newVideoFile.save()
1254 this.VideoFiles.push(newVideoFile)
1257 getOriginalFileResolution () {
1258 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1260 return getVideoFileResolution(originalFilePath)
1263 getDescriptionPath () {
1264 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1267 removeThumbnail () {
1268 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1269 return unlinkPromise(thumbnailPath)
1273 // Same name than video thumbnail
1274 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1277 removeFile (videoFile: VideoFileModel) {
1278 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1279 return unlinkPromise(filePath)
1282 removeTorrent (videoFile: VideoFileModel) {
1283 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1284 return unlinkPromise(torrentPath)
1287 getActivityStreamDuration () {
1288 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1289 return 'PT' + this.duration + 'S'
1292 private getBaseUrls () {
1296 if (this.isOwned()) {
1297 baseUrlHttp = CONFIG.WEBSERVER.URL
1298 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1300 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1301 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1304 return { baseUrlHttp, baseUrlWs }
1307 private getThumbnailUrl (baseUrlHttp: string) {
1308 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1311 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1312 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1315 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1316 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1319 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1320 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1321 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1322 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1324 const magnetHash = {
1328 infoHash: videoFile.infoHash,
1332 return magnetUtil.encode(magnetHash)