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, VideoFile } 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]: (options: {
101 filter?: VideoFilter,
104 videoChannelId?: number
106 const accountInclude = {
107 attributes: [ 'name' ],
108 model: AccountModel.unscoped(),
113 attributes: [ 'preferredUsername', 'url', 'serverId', 'avatarId' ],
114 model: ActorModel.unscoped(),
116 where: VideoModel.buildActorWhereWithFilter(options.filter),
119 attributes: [ 'host' ],
120 model: ServerModel.unscoped(),
124 model: AvatarModel.unscoped(),
132 const videoChannelInclude = {
133 attributes: [ 'name', 'description' ],
134 model: VideoChannelModel.unscoped(),
142 // Force actorId to be a number to avoid SQL injections
143 const actorIdNumber = parseInt(options.actorId.toString(), 10)
144 const query: IFindOptions<VideoModel> = {
147 [Sequelize.Op.notIn]: Sequelize.literal(
148 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
150 [ Sequelize.Op.in ]: Sequelize.literal(
152 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
153 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
154 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
156 'SELECT "video"."id" AS "id" FROM "video" ' +
157 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
158 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
159 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
160 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
161 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + actorIdNumber +
165 privacy: VideoPrivacy.PUBLIC
167 include: [ videoChannelInclude ]
170 if (options.withFiles === true) {
172 model: VideoFileModel.unscoped(),
178 if (options.hideNSFW === true) {
179 query.where['nsfw'] = false
182 if (options.accountId) {
183 accountInclude.where = {
184 id: options.accountId
188 if (options.videoChannelId) {
189 videoChannelInclude.where = {
190 id: options.videoChannelId
196 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
199 model: () => VideoChannelModel.unscoped(),
204 exclude: [ 'privateKey', 'publicKey' ]
206 model: () => ActorModel.unscoped(),
210 attributes: [ 'host' ],
211 model: () => ServerModel.unscoped(),
217 model: () => AccountModel.unscoped(),
221 model: () => ActorModel.unscoped(),
223 exclude: [ 'privateKey', 'publicKey' ]
228 attributes: [ 'host' ],
229 model: () => ServerModel.unscoped(),
233 model: () => AvatarModel.unscoped(),
244 [ScopeNames.WITH_TAGS]: {
245 include: [ () => TagModel ]
247 [ScopeNames.WITH_FILES]: {
250 model: () => VideoFileModel.unscoped(),
255 [ScopeNames.WITH_SHARES]: {
258 model: () => VideoShareModel.unscoped()
262 [ScopeNames.WITH_RATES]: {
265 model: () => AccountVideoRateModel,
268 model: () => AccountModel.unscoped(),
272 attributes: [ 'url' ],
273 model: () => ActorModel.unscoped()
281 [ScopeNames.WITH_COMMENTS]: {
284 model: () => VideoCommentModel.unscoped()
296 fields: [ 'createdAt' ]
299 fields: [ 'duration' ]
311 fields: [ 'channelId' ]
314 fields: [ 'id', 'privacy' ]
322 export class VideoModel extends Model<VideoModel> {
325 @Default(DataType.UUIDV4)
327 @Column(DataType.UUID)
331 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
337 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
343 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
349 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
350 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
354 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
359 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
365 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
366 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
371 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
372 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
376 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
406 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
407 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
412 commentsEnabled: boolean
421 @Default(Sequelize.NOW)
425 @ForeignKey(() => VideoChannelModel)
429 @BelongsTo(() => VideoChannelModel, {
435 VideoChannel: VideoChannelModel
437 @BelongsToMany(() => TagModel, {
438 foreignKey: 'videoId',
439 through: () => VideoTagModel,
444 @HasMany(() => VideoAbuseModel, {
451 VideoAbuses: VideoAbuseModel[]
453 @HasMany(() => VideoFileModel, {
460 VideoFiles: VideoFileModel[]
462 @HasMany(() => VideoShareModel, {
469 VideoShares: VideoShareModel[]
471 @HasMany(() => AccountVideoRateModel, {
478 AccountVideoRates: AccountVideoRateModel[]
480 @HasMany(() => VideoCommentModel, {
488 VideoComments: VideoCommentModel[]
491 static async sendDelete (instance: VideoModel, options) {
492 if (instance.isOwned()) {
493 if (!instance.VideoChannel) {
494 instance.VideoChannel = await instance.$get('VideoChannel', {
498 include: [ ActorModel ]
501 transaction: options.transaction
502 }) as VideoChannelModel
505 logger.debug('Sending delete of video %s.', instance.url)
507 return sendDeleteVideo(instance, options.transaction)
514 static async removeFilesAndSendDelete (instance: VideoModel) {
515 const tasks: Promise<any>[] = []
517 tasks.push(instance.removeThumbnail())
519 if (instance.isOwned()) {
520 if (!Array.isArray(instance.VideoFiles)) {
521 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
524 tasks.push(instance.removePreview())
526 // Remove physical files and torrents
527 instance.VideoFiles.forEach(file => {
528 tasks.push(instance.removeFile(file))
529 tasks.push(instance.removeTorrent(file))
533 return Promise.all(tasks)
535 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
540 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
543 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
544 function getRawQuery (select: string) {
545 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
546 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
547 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
548 'WHERE "Account"."actorId" = ' + actorId
549 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
550 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
551 'WHERE "VideoShare"."actorId" = ' + actorId
553 return `(${queryVideo}) UNION (${queryVideoShare})`
556 const rawQuery = getRawQuery('"Video"."id"')
557 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
563 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
566 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
569 { privacy: VideoPrivacy.PUBLIC },
570 { privacy: VideoPrivacy.UNLISTED }
575 attributes: [ 'id', 'url' ],
576 model: VideoShareModel.unscoped(),
579 [Sequelize.Op.and]: [
582 [Sequelize.Op.not]: null
592 attributes: [ 'id', 'url' ],
593 model: ActorModel.unscoped()
598 model: VideoChannelModel.unscoped(),
602 attributes: [ 'name' ],
603 model: AccountModel.unscoped(),
607 attributes: [ 'id', 'url' ],
608 model: ActorModel.unscoped(),
614 attributes: [ 'id', 'url' ],
615 model: ActorModel.unscoped(),
621 attributes: [ 'type' ],
622 model: AccountVideoRateModel,
626 attributes: [ 'id' ],
627 model: AccountModel.unscoped(),
630 attributes: [ 'url' ],
631 model: ActorModel.unscoped(),
634 attributes: [ 'host' ],
645 attributes: [ 'url' ],
646 model: VideoCommentModel,
654 return Bluebird.all([
655 // FIXME: typing issue
656 VideoModel.findAll(query as any),
657 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
658 ]).then(([ rows, totals ]) => {
659 // totals: totalVideos + totalVideoShares
661 let totalVideoShares = 0
662 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
663 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
665 const total = totalVideos + totalVideoShares
673 static listAccountVideosForApi (accountId: number, start: number, count: number, sort: string, hideNSFW: boolean, withFiles = false) {
674 const query: IFindOptions<VideoModel> = {
677 order: getSort(sort),
680 model: VideoChannelModel,
695 if (withFiles === true) {
697 model: VideoFileModel.unscoped(),
702 if (hideNSFW === true) {
708 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
716 static async listForApi (options: {
722 filter?: VideoFilter,
724 videoChannelId?: number
727 offset: options.start,
728 limit: options.count,
729 order: getSort(options.sort)
732 const serverActor = await getServerActor()
735 ScopeNames.AVAILABLE_FOR_LIST, {
736 actorId: serverActor.id,
737 hideNSFW: options.hideNSFW,
738 filter: options.filter,
739 withFiles: options.withFiles,
740 accountId: options.accountId,
741 videoChannelId: options.videoChannelId
746 return VideoModel.scope(scopes)
747 .findAndCountAll(query)
748 .then(({ rows, count }) => {
756 static async searchAndPopulateAccountAndServer (value: string, start: number, count: number, sort: string, hideNSFW: boolean) {
757 const query: IFindOptions<VideoModel> = {
760 order: getSort(sort),
765 [ Sequelize.Op.iLike ]: '%' + value + '%'
769 preferredUsername: Sequelize.where(Sequelize.col('preferredUsername'), {
770 [ Sequelize.Op.iLike ]: '%' + value + '%'
774 host: Sequelize.where(Sequelize.col('host'), {
775 [ Sequelize.Op.iLike ]: '%' + value + '%'
782 const serverActor = await getServerActor()
785 ScopeNames.AVAILABLE_FOR_LIST, {
786 actorId: serverActor.id,
792 return VideoModel.scope(scopes)
793 .findAndCountAll(query)
794 .then(({ rows, count }) => {
802 static load (id: number) {
803 return VideoModel.findById(id)
806 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
807 const query: IFindOptions<VideoModel> = {
813 if (t !== undefined) query.transaction = t
815 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
818 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
819 const query: IFindOptions<VideoModel> = {
828 if (t !== undefined) query.transaction = t
830 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
833 static loadAndPopulateAccountAndServerAndTags (id: number) {
835 order: [ [ 'Tags', 'name', 'ASC' ] ]
839 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
840 .findById(id, options)
843 static loadByUUID (uuid: string) {
851 .scope([ ScopeNames.WITH_FILES ])
855 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
857 order: [ [ 'Tags', 'name', 'ASC' ] ],
864 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
868 static loadAndPopulateAll (id: number) {
870 order: [ [ 'Tags', 'name', 'ASC' ] ],
878 ScopeNames.WITH_RATES,
879 ScopeNames.WITH_SHARES,
880 ScopeNames.WITH_TAGS,
881 ScopeNames.WITH_FILES,
882 ScopeNames.WITH_ACCOUNT_DETAILS,
883 ScopeNames.WITH_COMMENTS
888 static async getStats () {
889 const totalLocalVideos = await VideoModel.count({
894 const totalVideos = await VideoModel.count()
896 let totalLocalVideoViews = await VideoModel.sum('views', {
901 // Sequelize could return null...
902 if (!totalLocalVideoViews) totalLocalVideoViews = 0
906 totalLocalVideoViews,
911 private static buildActorWhereWithFilter (filter?: VideoFilter) {
912 if (filter && filter === 'local') {
921 private static getCategoryLabel (id: number) {
922 let categoryLabel = VIDEO_CATEGORIES[id]
923 if (!categoryLabel) categoryLabel = 'Misc'
928 private static getLicenceLabel (id: number) {
929 let licenceLabel = VIDEO_LICENCES[id]
930 if (!licenceLabel) licenceLabel = 'Unknown'
935 private static getLanguageLabel (id: string) {
936 let languageLabel = VIDEO_LANGUAGES[id]
937 if (!languageLabel) languageLabel = 'Unknown'
942 private static getPrivacyLabel (id: number) {
943 let privacyLabel = VIDEO_PRIVACIES[id]
944 if (!privacyLabel) privacyLabel = 'Unknown'
950 if (Array.isArray(this.VideoFiles) === false) return undefined
952 // The original file is the file that have the higher resolution
953 return maxBy(this.VideoFiles, file => file.resolution)
956 getVideoFilename (videoFile: VideoFileModel) {
957 return this.uuid + '-' + videoFile.resolution + videoFile.extname
960 getThumbnailName () {
961 // We always have a copy of the thumbnail
962 const extension = '.jpg'
963 return this.uuid + extension
967 const extension = '.jpg'
968 return this.uuid + extension
971 getTorrentFileName (videoFile: VideoFileModel) {
972 const extension = '.torrent'
973 return this.uuid + '-' + videoFile.resolution + extension
977 return this.remote === false
980 createPreview (videoFile: VideoFileModel) {
981 return generateImageFromVideoFile(
982 this.getVideoFilePath(videoFile),
983 CONFIG.STORAGE.PREVIEWS_DIR,
984 this.getPreviewName(),
989 createThumbnail (videoFile: VideoFileModel) {
990 return generateImageFromVideoFile(
991 this.getVideoFilePath(videoFile),
992 CONFIG.STORAGE.THUMBNAILS_DIR,
993 this.getThumbnailName(),
998 getVideoFilePath (videoFile: VideoFileModel) {
999 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1002 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1004 // Keep the extname, it's used by the client to stream the file inside a web browser
1005 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1006 createdBy: 'PeerTube',
1008 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1009 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1012 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1016 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1018 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1019 logger.info('Creating torrent %s.', filePath)
1021 await writeFilePromise(filePath, torrent)
1023 const parsedTorrent = parseTorrent(torrent)
1024 videoFile.infoHash = parsedTorrent.infoHash
1028 return '/videos/embed/' + this.uuid
1031 getThumbnailPath () {
1032 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1036 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1039 toFormattedJSON (): Video {
1040 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1048 label: VideoModel.getCategoryLabel(this.category)
1052 label: VideoModel.getLicenceLabel(this.licence)
1056 label: VideoModel.getLanguageLabel(this.language)
1060 label: VideoModel.getPrivacyLabel(this.privacy)
1063 description: this.getTruncatedDescription(),
1064 isLocal: this.isOwned(),
1065 duration: this.duration,
1068 dislikes: this.dislikes,
1069 thumbnailPath: this.getThumbnailPath(),
1070 previewPath: this.getPreviewPath(),
1071 embedPath: this.getEmbedPath(),
1072 createdAt: this.createdAt,
1073 updatedAt: this.updatedAt,
1074 publishedAt: this.publishedAt,
1076 name: formattedAccount.name,
1077 displayName: formattedAccount.displayName,
1078 url: formattedAccount.url,
1079 host: formattedAccount.host,
1080 avatar: formattedAccount.avatar
1085 toFormattedDetailsJSON (): VideoDetails {
1086 const formattedJson = this.toFormattedJSON()
1088 const detailsJson = {
1089 support: this.support,
1090 descriptionPath: this.getDescriptionPath(),
1091 channel: this.VideoChannel.toFormattedJSON(),
1092 account: this.VideoChannel.Account.toFormattedJSON(),
1093 tags: map(this.Tags, 'name'),
1094 commentsEnabled: this.commentsEnabled,
1098 // Format and sort video files
1099 detailsJson.files = this.getFormattedVideoFilesJSON()
1101 return Object.assign(formattedJson, detailsJson)
1104 getFormattedVideoFilesJSON (): VideoFile[] {
1105 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1107 return this.VideoFiles
1109 let resolutionLabel = videoFile.resolution + 'p'
1113 id: videoFile.resolution,
1114 label: resolutionLabel
1116 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1117 size: videoFile.size,
1118 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1119 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
1123 if (a.resolution.id < b.resolution.id) return 1
1124 if (a.resolution.id === b.resolution.id) return 0
1129 toActivityPubObject (): VideoTorrentObject {
1130 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1131 if (!this.Tags) this.Tags = []
1133 const tag = this.Tags.map(t => ({
1134 type: 'Hashtag' as 'Hashtag',
1139 if (this.language) {
1141 identifier: this.language,
1142 name: VideoModel.getLanguageLabel(this.language)
1147 if (this.category) {
1149 identifier: this.category + '',
1150 name: VideoModel.getCategoryLabel(this.category)
1157 identifier: this.licence + '',
1158 name: VideoModel.getLicenceLabel(this.licence)
1165 if (Array.isArray(this.AccountVideoRates)) {
1166 const res = this.toRatesActivityPubObjects()
1167 likesObject = res.likesObject
1168 dislikesObject = res.dislikesObject
1172 if (Array.isArray(this.VideoShares)) {
1173 sharesObject = this.toAnnouncesActivityPubObject()
1177 if (Array.isArray(this.VideoComments)) {
1178 commentsObject = this.toCommentsActivityPubObject()
1182 for (const file of this.VideoFiles) {
1185 mimeType: 'video/' + file.extname.replace('.', ''),
1186 href: this.getVideoFileUrl(file, baseUrlHttp),
1187 width: file.resolution,
1193 mimeType: 'application/x-bittorrent',
1194 href: this.getTorrentUrl(file, baseUrlHttp),
1195 width: file.resolution
1200 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1201 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1202 width: file.resolution
1206 // Add video url too
1209 mimeType: 'text/html',
1210 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1214 type: 'Video' as 'Video',
1217 duration: this.getActivityStreamDuration(),
1224 sensitive: this.nsfw,
1225 commentsEnabled: this.commentsEnabled,
1226 published: this.publishedAt.toISOString(),
1227 updated: this.updatedAt.toISOString(),
1228 mediaType: 'text/markdown',
1229 content: this.getTruncatedDescription(),
1230 support: this.support,
1233 url: this.getThumbnailUrl(baseUrlHttp),
1234 mediaType: 'image/jpeg',
1235 width: THUMBNAILS_SIZE.width,
1236 height: THUMBNAILS_SIZE.height
1240 dislikes: dislikesObject,
1241 shares: sharesObject,
1242 comments: commentsObject,
1246 id: this.VideoChannel.Account.Actor.url
1250 id: this.VideoChannel.Actor.url
1256 toAnnouncesActivityPubObject () {
1257 const shares: string[] = []
1259 for (const videoShare of this.VideoShares) {
1260 shares.push(videoShare.url)
1263 return activityPubCollection(getVideoSharesActivityPubUrl(this), shares)
1266 toCommentsActivityPubObject () {
1267 const comments: string[] = []
1269 for (const videoComment of this.VideoComments) {
1270 comments.push(videoComment.url)
1273 return activityPubCollection(getVideoCommentsActivityPubUrl(this), comments)
1276 toRatesActivityPubObjects () {
1277 const likes: string[] = []
1278 const dislikes: string[] = []
1280 for (const rate of this.AccountVideoRates) {
1281 if (rate.type === 'like') {
1282 likes.push(rate.Account.Actor.url)
1283 } else if (rate.type === 'dislike') {
1284 dislikes.push(rate.Account.Actor.url)
1288 const likesObject = activityPubCollection(getVideoLikesActivityPubUrl(this), likes)
1289 const dislikesObject = activityPubCollection(getVideoDislikesActivityPubUrl(this), dislikes)
1291 return { likesObject, dislikesObject }
1294 getTruncatedDescription () {
1295 if (!this.description) return null
1297 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1298 return peertubeTruncate(this.description, maxLength)
1301 async optimizeOriginalVideofile () {
1302 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1303 const newExtname = '.mp4'
1304 const inputVideoFile = this.getOriginalFile()
1305 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1306 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1308 const transcodeOptions = {
1309 inputPath: videoInputPath,
1310 outputPath: videoOutputPath
1313 // Could be very long!
1314 await transcode(transcodeOptions)
1317 await unlinkPromise(videoInputPath)
1319 // Important to do this before getVideoFilename() to take in account the new file extension
1320 inputVideoFile.set('extname', newExtname)
1322 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1323 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1325 inputVideoFile.set('size', stats.size)
1327 await this.createTorrentAndSetInfoHash(inputVideoFile)
1328 await inputVideoFile.save()
1331 // Auto destruction...
1332 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1338 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1339 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1340 const extname = '.mp4'
1342 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1343 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1345 const newVideoFile = new VideoFileModel({
1351 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1353 const transcodeOptions = {
1354 inputPath: videoInputPath,
1355 outputPath: videoOutputPath,
1360 await transcode(transcodeOptions)
1362 const stats = await statPromise(videoOutputPath)
1364 newVideoFile.set('size', stats.size)
1366 await this.createTorrentAndSetInfoHash(newVideoFile)
1368 await newVideoFile.save()
1370 this.VideoFiles.push(newVideoFile)
1373 getOriginalFileResolution () {
1374 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1376 return getVideoFileResolution(originalFilePath)
1379 getDescriptionPath () {
1380 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1383 removeThumbnail () {
1384 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1385 return unlinkPromise(thumbnailPath)
1389 // Same name than video thumbnail
1390 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1393 removeFile (videoFile: VideoFileModel) {
1394 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1395 return unlinkPromise(filePath)
1398 removeTorrent (videoFile: VideoFileModel) {
1399 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1400 return unlinkPromise(torrentPath)
1403 getActivityStreamDuration () {
1404 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1405 return 'PT' + this.duration + 'S'
1408 private getBaseUrls () {
1412 if (this.isOwned()) {
1413 baseUrlHttp = CONFIG.WEBSERVER.URL
1414 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1416 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1417 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1420 return { baseUrlHttp, baseUrlWs }
1423 private getThumbnailUrl (baseUrlHttp: string) {
1424 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1427 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1428 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1431 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1432 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1435 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1436 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1437 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1438 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1440 const magnetHash = {
1444 infoHash: videoFile.infoHash,
1448 return magnetUtil.encode(magnetHash)