1 import * as Bluebird from 'bluebird'
2 import { map, maxBy } 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'
35 createTorrentPromise, peertubeTruncate, renamePromise, statPromise, unlinkPromise,
37 } from '../../helpers/core-utils'
38 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
39 import { isBooleanValid } from '../../helpers/custom-validators/misc'
42 isVideoDescriptionValid,
49 } from '../../helpers/custom-validators/videos'
50 import { generateImageFromVideoFile, getVideoFileResolution, transcode } from '../../helpers/ffmpeg-utils'
51 import { logger } from '../../helpers/logger'
52 import { getServerActor } from '../../helpers/utils'
65 } from '../../initializers'
67 getVideoCommentsActivityPubUrl,
68 getVideoDislikesActivityPubUrl,
69 getVideoLikesActivityPubUrl,
70 getVideoSharesActivityPubUrl
71 } from '../../lib/activitypub'
72 import { sendDeleteVideo } from '../../lib/activitypub/send'
73 import { AccountModel } from '../account/account'
74 import { AccountVideoRateModel } from '../account/account-video-rate'
75 import { ActorModel } from '../activitypub/actor'
76 import { AvatarModel } from '../avatar/avatar'
77 import { ServerModel } from '../server/server'
78 import { getSort, throwIfNotValid } from '../utils'
79 import { TagModel } from './tag'
80 import { VideoAbuseModel } from './video-abuse'
81 import { VideoChannelModel } from './video-channel'
82 import { VideoCommentModel } from './video-comment'
83 import { VideoFileModel } from './video-file'
84 import { VideoShareModel } from './video-share'
85 import { VideoTagModel } from './video-tag'
88 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
89 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
90 WITH_TAGS = 'WITH_TAGS',
91 WITH_FILES = 'WITH_FILES',
92 WITH_SHARES = 'WITH_SHARES',
93 WITH_RATES = 'WITH_RATES',
94 WITH_COMMENTS = 'WITH_COMMENTS'
98 [ScopeNames.AVAILABLE_FOR_LIST]: (actorId: number, filter?: VideoFilter) => ({
101 [Sequelize.Op.notIn]: Sequelize.literal(
102 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
104 [ Sequelize.Op.in ]: Sequelize.literal(
106 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
107 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
108 'WHERE "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
110 'SELECT "video"."id" AS "id" FROM "video" ' +
111 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
112 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
113 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
114 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
115 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
119 privacy: VideoPrivacy.PUBLIC
123 attributes: [ 'name', 'description' ],
124 model: VideoChannelModel.unscoped(),
128 attributes: [ 'name' ],
129 model: AccountModel.unscoped(),
133 attributes: [ 'preferredUsername', 'url', 'serverId' ],
134 model: ActorModel.unscoped(),
136 where: VideoModel.buildActorWhereWithFilter(filter),
139 attributes: [ 'host' ],
140 model: ServerModel.unscoped(),
144 model: AvatarModel.unscoped(),
155 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
158 model: () => VideoChannelModel.unscoped(),
163 exclude: [ 'privateKey', 'publicKey' ]
165 model: () => ActorModel.unscoped(),
169 attributes: [ 'host' ],
170 model: () => ServerModel.unscoped(),
176 model: () => AccountModel.unscoped(),
180 model: () => ActorModel.unscoped(),
182 exclude: [ 'privateKey', 'publicKey' ]
187 attributes: [ 'host' ],
188 model: () => ServerModel.unscoped(),
192 model: () => AvatarModel.unscoped(),
203 [ScopeNames.WITH_TAGS]: {
204 include: [ () => TagModel ]
206 [ScopeNames.WITH_FILES]: {
209 model: () => VideoFileModel.unscoped(),
214 [ScopeNames.WITH_SHARES]: {
217 model: () => VideoShareModel.unscoped()
221 [ScopeNames.WITH_RATES]: {
224 model: () => AccountVideoRateModel,
227 model: () => AccountModel.unscoped(),
231 attributes: [ 'url' ],
232 model: () => ActorModel.unscoped()
240 [ScopeNames.WITH_COMMENTS]: {
243 model: () => VideoCommentModel.unscoped()
255 fields: [ 'createdAt' ]
258 fields: [ 'duration' ]
270 fields: [ 'channelId' ]
273 fields: [ 'id', 'privacy' ]
281 export class VideoModel extends Model<VideoModel> {
284 @Default(DataType.UUIDV4)
286 @Column(DataType.UUID)
290 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
296 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
302 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
308 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
313 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
318 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
324 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
325 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
330 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
331 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
335 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
365 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
366 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
371 commentsEnabled: boolean
379 @ForeignKey(() => VideoChannelModel)
383 @BelongsTo(() => VideoChannelModel, {
389 VideoChannel: VideoChannelModel
391 @BelongsToMany(() => TagModel, {
392 foreignKey: 'videoId',
393 through: () => VideoTagModel,
398 @HasMany(() => VideoAbuseModel, {
405 VideoAbuses: VideoAbuseModel[]
407 @HasMany(() => VideoFileModel, {
414 VideoFiles: VideoFileModel[]
416 @HasMany(() => VideoShareModel, {
423 VideoShares: VideoShareModel[]
425 @HasMany(() => AccountVideoRateModel, {
432 AccountVideoRates: AccountVideoRateModel[]
434 @HasMany(() => VideoCommentModel, {
442 VideoComments: VideoCommentModel[]
445 static async sendDelete (instance: VideoModel, options) {
446 if (instance.isOwned()) {
447 if (!instance.VideoChannel) {
448 instance.VideoChannel = await instance.$get('VideoChannel', {
452 include: [ ActorModel ]
455 transaction: options.transaction
456 }) as VideoChannelModel
459 logger.debug('Sending delete of video %s.', instance.url)
461 return sendDeleteVideo(instance, options.transaction)
468 static async removeFilesAndSendDelete (instance: VideoModel) {
469 const tasks: Promise<any>[] = []
471 tasks.push(instance.removeThumbnail())
473 if (instance.isOwned()) {
474 if (!Array.isArray(instance.VideoFiles)) {
475 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
478 tasks.push(instance.removePreview())
480 // Remove physical files and torrents
481 instance.VideoFiles.forEach(file => {
482 tasks.push(instance.removeFile(file))
483 tasks.push(instance.removeTorrent(file))
487 return Promise.all(tasks)
489 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
494 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
497 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
498 function getRawQuery (select: string) {
499 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
500 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
501 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
502 'WHERE "Account"."actorId" = ' + actorId
503 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
504 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
505 'WHERE "VideoShare"."actorId" = ' + actorId
507 return `(${queryVideo}) UNION (${queryVideoShare})`
510 const rawQuery = getRawQuery('"Video"."id"')
511 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
517 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
520 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
523 { privacy: VideoPrivacy.PUBLIC },
524 { privacy: VideoPrivacy.UNLISTED }
529 attributes: [ 'id', 'url' ],
530 model: VideoShareModel.unscoped(),
533 [Sequelize.Op.and]: [
536 [Sequelize.Op.not]: null
546 attributes: [ 'id', 'url' ],
547 model: ActorModel.unscoped()
552 model: VideoChannelModel.unscoped(),
556 attributes: [ 'name' ],
557 model: AccountModel.unscoped(),
561 attributes: [ 'id', 'url' ],
562 model: ActorModel.unscoped(),
568 attributes: [ 'id', 'url' ],
569 model: ActorModel.unscoped(),
575 attributes: [ 'type' ],
576 model: AccountVideoRateModel,
580 attributes: [ 'id' ],
581 model: AccountModel.unscoped(),
584 attributes: [ 'url' ],
585 model: ActorModel.unscoped(),
588 attributes: [ 'host' ],
599 attributes: [ 'url' ],
600 model: VideoCommentModel,
608 return Bluebird.all([
609 // FIXME: typing issue
610 VideoModel.findAll(query as any),
611 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
612 ]).then(([ rows, totals ]) => {
613 // totals: totalVideos + totalVideoShares
615 let totalVideoShares = 0
616 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
617 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
619 const total = totalVideos + totalVideoShares
627 static listUserVideosForApi (userId: number, start: number, count: number, sort: string) {
631 order: getSort(sort),
634 model: VideoChannelModel,
649 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
657 static async listForApi (start: number, count: number, sort: string, filter?: VideoFilter) {
664 const serverActor = await getServerActor()
666 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id, filter ] })
667 .findAndCountAll(query)
668 .then(({ rows, count }) => {
676 static async searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) {
677 const query: IFindOptions<VideoModel> = {
680 order: getSort(sort),
685 [ Sequelize.Op.iLike ]: '%' + value + '%'
689 preferredUsername: Sequelize.where(Sequelize.col('preferredUsername'), {
690 [ Sequelize.Op.iLike ]: '%' + value + '%'
694 host: Sequelize.where(Sequelize.col('host'), {
695 [ Sequelize.Op.iLike ]: '%' + value + '%'
702 const serverActor = await getServerActor()
704 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
705 .findAndCountAll(query).then(({ rows, count }) => {
713 static load (id: number) {
714 return VideoModel.findById(id)
717 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
718 const query: IFindOptions<VideoModel> = {
724 if (t !== undefined) query.transaction = t
726 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
729 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
730 const query: IFindOptions<VideoModel> = {
739 if (t !== undefined) query.transaction = t
741 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
744 static loadAndPopulateAccountAndServerAndTags (id: number) {
746 order: [ [ 'Tags', 'name', 'ASC' ] ]
750 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
751 .findById(id, options)
754 static loadByUUID (uuid: string) {
762 .scope([ ScopeNames.WITH_FILES ])
766 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
768 order: [ [ 'Tags', 'name', 'ASC' ] ],
775 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
779 static loadAndPopulateAll (id: number) {
781 order: [ [ 'Tags', 'name', 'ASC' ] ],
789 ScopeNames.WITH_RATES,
790 ScopeNames.WITH_SHARES,
791 ScopeNames.WITH_TAGS,
792 ScopeNames.WITH_FILES,
793 ScopeNames.WITH_ACCOUNT_DETAILS,
794 ScopeNames.WITH_COMMENTS
799 static async getStats () {
800 const totalLocalVideos = await VideoModel.count({
805 const totalVideos = await VideoModel.count()
807 let totalLocalVideoViews = await VideoModel.sum('views', {
812 // Sequelize could return null...
813 if (!totalLocalVideoViews) totalLocalVideoViews = 0
817 totalLocalVideoViews,
822 private static buildActorWhereWithFilter (filter?: VideoFilter) {
823 if (filter && filter === 'local') {
832 private static getCategoryLabel (id: number) {
833 let categoryLabel = VIDEO_CATEGORIES[id]
834 if (!categoryLabel) categoryLabel = 'Misc'
839 private static getLicenceLabel (id: number) {
840 let licenceLabel = VIDEO_LICENCES[id]
841 if (!licenceLabel) licenceLabel = 'Unknown'
846 private static getLanguageLabel (id: number) {
847 let languageLabel = VIDEO_LANGUAGES[id]
848 if (!languageLabel) languageLabel = 'Unknown'
854 if (Array.isArray(this.VideoFiles) === false) return undefined
856 // The original file is the file that have the higher resolution
857 return maxBy(this.VideoFiles, file => file.resolution)
860 getVideoFilename (videoFile: VideoFileModel) {
861 return this.uuid + '-' + videoFile.resolution + videoFile.extname
864 getThumbnailName () {
865 // We always have a copy of the thumbnail
866 const extension = '.jpg'
867 return this.uuid + extension
871 const extension = '.jpg'
872 return this.uuid + extension
875 getTorrentFileName (videoFile: VideoFileModel) {
876 const extension = '.torrent'
877 return this.uuid + '-' + videoFile.resolution + extension
881 return this.remote === false
884 createPreview (videoFile: VideoFileModel) {
885 return generateImageFromVideoFile(
886 this.getVideoFilePath(videoFile),
887 CONFIG.STORAGE.PREVIEWS_DIR,
888 this.getPreviewName(),
893 createThumbnail (videoFile: VideoFileModel) {
894 return generateImageFromVideoFile(
895 this.getVideoFilePath(videoFile),
896 CONFIG.STORAGE.THUMBNAILS_DIR,
897 this.getThumbnailName(),
902 getVideoFilePath (videoFile: VideoFileModel) {
903 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
906 createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) {
909 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
910 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
913 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
917 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
919 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
920 logger.info('Creating torrent %s.', filePath)
922 await writeFilePromise(filePath, torrent)
924 const parsedTorrent = parseTorrent(torrent)
925 videoFile.infoHash = parsedTorrent.infoHash
929 return '/videos/embed/' + this.uuid
932 getThumbnailPath () {
933 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
937 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
940 toFormattedJSON (): Video {
941 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
949 label: VideoModel.getCategoryLabel(this.category)
953 label: VideoModel.getLicenceLabel(this.licence)
957 label: VideoModel.getLanguageLabel(this.language)
960 description: this.getTruncatedDescription(),
961 isLocal: this.isOwned(),
962 duration: this.duration,
965 dislikes: this.dislikes,
966 thumbnailPath: this.getThumbnailPath(),
967 previewPath: this.getPreviewPath(),
968 embedPath: this.getEmbedPath(),
969 createdAt: this.createdAt,
970 updatedAt: this.updatedAt,
972 name: formattedAccount.name,
973 displayName: formattedAccount.displayName,
974 url: formattedAccount.url,
975 host: formattedAccount.host,
976 avatar: formattedAccount.avatar
981 toFormattedDetailsJSON (): VideoDetails {
982 const formattedJson = this.toFormattedJSON()
984 // Maybe our server is not up to date and there are new privacy settings since our version
985 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
986 if (!privacyLabel) privacyLabel = 'Unknown'
988 const detailsJson = {
993 support: this.support,
994 descriptionPath: this.getDescriptionPath(),
995 channel: this.VideoChannel.toFormattedJSON(),
996 account: this.VideoChannel.Account.toFormattedJSON(),
997 tags: map<TagModel, string>(this.Tags, 'name'),
998 commentsEnabled: this.commentsEnabled,
1002 // Format and sort video files
1003 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1004 detailsJson.files = this.VideoFiles
1006 let resolutionLabel = videoFile.resolution + 'p'
1010 id: videoFile.resolution,
1011 label: resolutionLabel
1013 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1014 size: videoFile.size,
1015 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1016 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
1020 if (a.resolution.id < b.resolution.id) return 1
1021 if (a.resolution.id === b.resolution.id) return 0
1025 return Object.assign(formattedJson, detailsJson)
1028 toActivityPubObject (): VideoTorrentObject {
1029 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1030 if (!this.Tags) this.Tags = []
1032 const tag = this.Tags.map(t => ({
1033 type: 'Hashtag' as 'Hashtag',
1038 if (this.language) {
1040 identifier: this.language + '',
1041 name: VideoModel.getLanguageLabel(this.language)
1046 if (this.category) {
1048 identifier: this.category + '',
1049 name: VideoModel.getCategoryLabel(this.category)
1056 identifier: this.licence + '',
1057 name: VideoModel.getLicenceLabel(this.licence)
1064 if (Array.isArray(this.AccountVideoRates)) {
1065 const res = this.toRatesActivityPubObjects()
1066 likesObject = res.likesObject
1067 dislikesObject = res.dislikesObject
1071 if (Array.isArray(this.VideoShares)) {
1072 sharesObject = this.toAnnouncesActivityPubObject()
1076 if (Array.isArray(this.VideoComments)) {
1077 commentsObject = this.toCommentsActivityPubObject()
1081 for (const file of this.VideoFiles) {
1084 mimeType: 'video/' + file.extname.replace('.', ''),
1085 href: this.getVideoFileUrl(file, baseUrlHttp),
1086 width: file.resolution,
1092 mimeType: 'application/x-bittorrent',
1093 href: this.getTorrentUrl(file, baseUrlHttp),
1094 width: file.resolution
1099 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1100 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1101 width: file.resolution
1105 // Add video url too
1108 mimeType: 'text/html',
1109 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1113 type: 'Video' as 'Video',
1116 duration: this.getActivityStreamDuration(),
1123 sensitive: this.nsfw,
1124 commentsEnabled: this.commentsEnabled,
1125 published: this.createdAt.toISOString(),
1126 updated: this.updatedAt.toISOString(),
1127 mediaType: 'text/markdown',
1128 content: this.getTruncatedDescription(),
1129 support: this.support,
1132 url: this.getThumbnailUrl(baseUrlHttp),
1133 mediaType: 'image/jpeg',
1134 width: THUMBNAILS_SIZE.width,
1135 height: THUMBNAILS_SIZE.height
1139 dislikes: dislikesObject,
1140 shares: sharesObject,
1141 comments: commentsObject,
1145 id: this.VideoChannel.Account.Actor.url
1149 id: this.VideoChannel.Actor.url
1155 toAnnouncesActivityPubObject () {
1156 const shares: string[] = []
1158 for (const videoShare of this.VideoShares) {
1159 shares.push(videoShare.url)
1162 return activityPubCollection(getVideoSharesActivityPubUrl(this), shares)
1165 toCommentsActivityPubObject () {
1166 const comments: string[] = []
1168 for (const videoComment of this.VideoComments) {
1169 comments.push(videoComment.url)
1172 return activityPubCollection(getVideoCommentsActivityPubUrl(this), comments)
1175 toRatesActivityPubObjects () {
1176 const likes: string[] = []
1177 const dislikes: string[] = []
1179 for (const rate of this.AccountVideoRates) {
1180 if (rate.type === 'like') {
1181 likes.push(rate.Account.Actor.url)
1182 } else if (rate.type === 'dislike') {
1183 dislikes.push(rate.Account.Actor.url)
1187 const likesObject = activityPubCollection(getVideoLikesActivityPubUrl(this), likes)
1188 const dislikesObject = activityPubCollection(getVideoDislikesActivityPubUrl(this), dislikes)
1190 return { likesObject, dislikesObject }
1193 getTruncatedDescription () {
1194 if (!this.description) return null
1196 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1197 return peertubeTruncate(this.description, maxLength)
1200 optimizeOriginalVideofile = async function () {
1201 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1202 const newExtname = '.mp4'
1203 const inputVideoFile = this.getOriginalFile()
1204 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1205 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1207 const transcodeOptions = {
1208 inputPath: videoInputPath,
1209 outputPath: videoOutputPath
1212 // Could be very long!
1213 await transcode(transcodeOptions)
1216 await unlinkPromise(videoInputPath)
1218 // Important to do this before getVideoFilename() to take in account the new file extension
1219 inputVideoFile.set('extname', newExtname)
1221 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1222 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1224 inputVideoFile.set('size', stats.size)
1226 await this.createTorrentAndSetInfoHash(inputVideoFile)
1227 await inputVideoFile.save()
1230 // Auto destruction...
1231 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1237 transcodeOriginalVideofile = async function (resolution: VideoResolution, isPortraitMode: boolean) {
1238 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1239 const extname = '.mp4'
1241 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1242 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1244 const newVideoFile = new VideoFileModel({
1250 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1252 const transcodeOptions = {
1253 inputPath: videoInputPath,
1254 outputPath: videoOutputPath,
1259 await transcode(transcodeOptions)
1261 const stats = await statPromise(videoOutputPath)
1263 newVideoFile.set('size', stats.size)
1265 await this.createTorrentAndSetInfoHash(newVideoFile)
1267 await newVideoFile.save()
1269 this.VideoFiles.push(newVideoFile)
1272 getOriginalFileResolution () {
1273 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1275 return getVideoFileResolution(originalFilePath)
1278 getDescriptionPath () {
1279 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1282 removeThumbnail () {
1283 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1284 return unlinkPromise(thumbnailPath)
1288 // Same name than video thumbnail
1289 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1292 removeFile (videoFile: VideoFileModel) {
1293 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1294 return unlinkPromise(filePath)
1297 removeTorrent (videoFile: VideoFileModel) {
1298 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1299 return unlinkPromise(torrentPath)
1302 getActivityStreamDuration () {
1303 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1304 return 'PT' + this.duration + 'S'
1307 private getBaseUrls () {
1311 if (this.isOwned()) {
1312 baseUrlHttp = CONFIG.WEBSERVER.URL
1313 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1315 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1316 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1319 return { baseUrlHttp, baseUrlWs }
1322 private getThumbnailUrl (baseUrlHttp: string) {
1323 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1326 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1327 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1330 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1331 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1334 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1335 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1336 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1337 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1339 const magnetHash = {
1343 infoHash: videoFile.infoHash,
1347 return magnetUtil.encode(magnetHash)