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 { extname, join } from 'path'
6 import * as Sequelize from 'sequelize'
28 } from 'sequelize-typescript'
29 import { VideoPrivacy, VideoResolution, VideoState } 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'
41 } from '../../helpers/core-utils'
42 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
43 import { isBooleanValid } from '../../helpers/custom-validators/misc'
46 isVideoDescriptionValid,
54 } from '../../helpers/custom-validators/videos'
55 import { generateImageFromVideoFile, getVideoFileFPS, getVideoFileResolution, transcode } from '../../helpers/ffmpeg-utils'
56 import { logger } from '../../helpers/logger'
57 import { getServerActor } from '../../helpers/utils'
64 STATIC_DOWNLOAD_PATHS,
73 } from '../../initializers'
75 getVideoCommentsActivityPubUrl,
76 getVideoDislikesActivityPubUrl,
77 getVideoLikesActivityPubUrl,
78 getVideoSharesActivityPubUrl
79 } from '../../lib/activitypub'
80 import { sendDeleteVideo } from '../../lib/activitypub/send'
81 import { AccountModel } from '../account/account'
82 import { AccountVideoRateModel } from '../account/account-video-rate'
83 import { ActorModel } from '../activitypub/actor'
84 import { AvatarModel } from '../avatar/avatar'
85 import { ServerModel } from '../server/server'
86 import { buildTrigramSearchIndex, createSearchTrigramQuery, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils'
87 import { TagModel } from './tag'
88 import { VideoAbuseModel } from './video-abuse'
89 import { VideoChannelModel } from './video-channel'
90 import { VideoCommentModel } from './video-comment'
91 import { VideoFileModel } from './video-file'
92 import { VideoShareModel } from './video-share'
93 import { VideoTagModel } from './video-tag'
94 import { ScheduleVideoUpdateModel } from './schedule-video-update'
95 import { VideoCaptionModel } from './video-caption'
97 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
98 const indexes: Sequelize.DefineIndexesOptions[] = [
99 buildTrigramSearchIndex('video_name_trigram', 'name'),
102 fields: [ 'createdAt' ]
105 fields: [ 'duration' ]
117 fields: [ 'channelId' ]
120 fields: [ 'id', 'privacy', 'state', 'waitTranscoding' ]
128 export enum ScopeNames {
129 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
130 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
131 WITH_TAGS = 'WITH_TAGS',
132 WITH_FILES = 'WITH_FILES',
133 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE'
137 [ScopeNames.AVAILABLE_FOR_LIST]: (options: {
140 filter?: VideoFilter,
144 videoChannelId?: number
146 const accountInclude = {
147 attributes: [ 'id', 'name' ],
148 model: AccountModel.unscoped(),
153 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
154 model: ActorModel.unscoped(),
156 where: VideoModel.buildActorWhereWithFilter(options.filter),
159 attributes: [ 'host' ],
160 model: ServerModel.unscoped(),
164 model: AvatarModel.unscoped(),
172 const videoChannelInclude = {
173 attributes: [ 'name', 'description', 'id' ],
174 model: VideoChannelModel.unscoped(),
179 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
180 model: ActorModel.unscoped(),
184 attributes: [ 'host' ],
185 model: ServerModel.unscoped(),
189 model: AvatarModel.unscoped(),
198 // Force actorId to be a number to avoid SQL injections
199 const actorIdNumber = parseInt(options.actorId.toString(), 10)
200 const query: IFindOptions<VideoModel> = {
203 [Sequelize.Op.notIn]: Sequelize.literal(
204 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
206 [ Sequelize.Op.in ]: Sequelize.literal(
208 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
209 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
210 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
212 'SELECT "video"."id" AS "id" FROM "video" ' +
213 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
214 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
215 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
216 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
217 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + actorIdNumber +
221 // Always list public videos
222 privacy: VideoPrivacy.PUBLIC,
223 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
224 [ Sequelize.Op.or ]: [
226 state: VideoState.PUBLISHED
229 [ Sequelize.Op.and ]: {
230 state: VideoState.TO_TRANSCODE,
231 waitTranscoding: false
236 include: [ videoChannelInclude ]
239 if (options.withFiles === true) {
241 model: VideoFileModel.unscoped(),
247 if (options.hideNSFW === true) {
248 query.where['nsfw'] = false
251 if (options.category) {
252 query.where['category'] = options.category
255 if (options.accountId) {
256 accountInclude.where = {
257 id: options.accountId
261 if (options.videoChannelId) {
262 videoChannelInclude.where = {
263 id: options.videoChannelId
269 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
272 model: () => VideoChannelModel.unscoped(),
277 exclude: [ 'privateKey', 'publicKey' ]
279 model: () => ActorModel.unscoped(),
283 attributes: [ 'host' ],
284 model: () => ServerModel.unscoped(),
288 model: () => AvatarModel.unscoped(),
294 model: () => AccountModel.unscoped(),
298 model: () => ActorModel.unscoped(),
300 exclude: [ 'privateKey', 'publicKey' ]
305 attributes: [ 'host' ],
306 model: () => ServerModel.unscoped(),
310 model: () => AvatarModel.unscoped(),
321 [ScopeNames.WITH_TAGS]: {
322 include: [ () => TagModel ]
324 [ScopeNames.WITH_FILES]: {
327 model: () => VideoFileModel.unscoped(),
332 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
335 model: () => ScheduleVideoUpdateModel.unscoped(),
345 export class VideoModel extends Model<VideoModel> {
348 @Default(DataType.UUIDV4)
350 @Column(DataType.UUID)
354 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
360 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
366 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
372 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
373 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
377 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
382 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
388 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
389 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
394 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
395 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
399 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
429 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
430 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
435 commentsEnabled: boolean
439 waitTranscoding: boolean
443 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
454 @Default(Sequelize.NOW)
458 @ForeignKey(() => VideoChannelModel)
462 @BelongsTo(() => VideoChannelModel, {
468 VideoChannel: VideoChannelModel
470 @BelongsToMany(() => TagModel, {
471 foreignKey: 'videoId',
472 through: () => VideoTagModel,
477 @HasMany(() => VideoAbuseModel, {
484 VideoAbuses: VideoAbuseModel[]
486 @HasMany(() => VideoFileModel, {
493 VideoFiles: VideoFileModel[]
495 @HasMany(() => VideoShareModel, {
502 VideoShares: VideoShareModel[]
504 @HasMany(() => AccountVideoRateModel, {
511 AccountVideoRates: AccountVideoRateModel[]
513 @HasMany(() => VideoCommentModel, {
521 VideoComments: VideoCommentModel[]
523 @HasOne(() => ScheduleVideoUpdateModel, {
530 ScheduleVideoUpdate: ScheduleVideoUpdateModel
532 @HasMany(() => VideoCaptionModel, {
539 ['separate' as any]: true
541 VideoCaptions: VideoCaptionModel[]
544 static async sendDelete (instance: VideoModel, options) {
545 if (instance.isOwned()) {
546 if (!instance.VideoChannel) {
547 instance.VideoChannel = await instance.$get('VideoChannel', {
551 include: [ ActorModel ]
554 transaction: options.transaction
555 }) as VideoChannelModel
558 logger.debug('Sending delete of video %s.', instance.url)
560 return sendDeleteVideo(instance, options.transaction)
567 static async removeFiles (instance: VideoModel) {
568 const tasks: Promise<any>[] = []
570 logger.debug('Removing files of video %s.', instance.url)
572 tasks.push(instance.removeThumbnail())
574 if (instance.isOwned()) {
575 if (!Array.isArray(instance.VideoFiles)) {
576 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
579 tasks.push(instance.removePreview())
581 // Remove physical files and torrents
582 instance.VideoFiles.forEach(file => {
583 tasks.push(instance.removeFile(file))
584 tasks.push(instance.removeTorrent(file))
588 // Do not wait video deletion because we could be in a transaction
591 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
598 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
601 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
602 function getRawQuery (select: string) {
603 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
604 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
605 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
606 'WHERE "Account"."actorId" = ' + actorId
607 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
608 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
609 'WHERE "VideoShare"."actorId" = ' + actorId
611 return `(${queryVideo}) UNION (${queryVideoShare})`
614 const rawQuery = getRawQuery('"Video"."id"')
615 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
621 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
624 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
627 { privacy: VideoPrivacy.PUBLIC },
628 { privacy: VideoPrivacy.UNLISTED }
633 attributes: [ 'language' ],
634 model: VideoCaptionModel.unscoped(),
638 attributes: [ 'id', 'url' ],
639 model: VideoShareModel.unscoped(),
641 // We only want videos shared by this actor
643 [Sequelize.Op.and]: [
646 [Sequelize.Op.not]: null
656 attributes: [ 'id', 'url' ],
657 model: ActorModel.unscoped()
662 model: VideoChannelModel.unscoped(),
666 attributes: [ 'name' ],
667 model: AccountModel.unscoped(),
671 attributes: [ 'id', 'url', 'followersUrl' ],
672 model: ActorModel.unscoped(),
678 attributes: [ 'id', 'url', 'followersUrl' ],
679 model: ActorModel.unscoped(),
689 return Bluebird.all([
690 // FIXME: typing issue
691 VideoModel.findAll(query as any),
692 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
693 ]).then(([ rows, totals ]) => {
694 // totals: totalVideos + totalVideoShares
696 let totalVideoShares = 0
697 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
698 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
700 const total = totalVideos + totalVideoShares
708 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, hideNSFW: boolean, withFiles = false) {
709 const query: IFindOptions<VideoModel> = {
712 order: getSort(sort),
715 model: VideoChannelModel,
728 model: ScheduleVideoUpdateModel,
734 if (withFiles === true) {
736 model: VideoFileModel.unscoped(),
741 if (hideNSFW === true) {
747 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
755 static async listForApi (options: {
762 filter?: VideoFilter,
764 videoChannelId?: number
767 offset: options.start,
768 limit: options.count,
769 order: getSort(options.sort)
772 const serverActor = await getServerActor()
775 ScopeNames.AVAILABLE_FOR_LIST, {
776 actorId: serverActor.id,
777 hideNSFW: options.hideNSFW,
778 category: options.category,
779 filter: options.filter,
780 withFiles: options.withFiles,
781 accountId: options.accountId,
782 videoChannelId: options.videoChannelId
787 return VideoModel.scope(scopes)
788 .findAndCountAll(query)
789 .then(({ rows, count }) => {
797 static async searchAndPopulateAccountAndServer (value: string, start: number, count: number, sort: string, hideNSFW: boolean) {
798 const query: IFindOptions<VideoModel> = {
800 include: [ createSimilarityAttribute('VideoModel.name', value) ]
804 order: getSort(sort),
805 where: createSearchTrigramQuery('VideoModel.name', value)
808 const serverActor = await getServerActor()
811 ScopeNames.AVAILABLE_FOR_LIST, {
812 actorId: serverActor.id,
818 return VideoModel.scope(scopes)
819 .findAndCountAll(query)
820 .then(({ rows, count }) => {
828 static load (id: number) {
829 return VideoModel.findById(id)
832 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
833 const query: IFindOptions<VideoModel> = {
839 if (t !== undefined) query.transaction = t
841 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
844 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
845 const query: IFindOptions<VideoModel> = {
854 if (t !== undefined) query.transaction = t
856 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
859 static loadAndPopulateAccountAndServerAndTags (id: number) {
861 order: [ [ 'Tags', 'name', 'ASC' ] ]
865 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_SCHEDULED_UPDATE ])
866 .findById(id, options)
869 static loadByUUID (uuid: string) {
877 .scope([ ScopeNames.WITH_FILES ])
881 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string, t?: Sequelize.Transaction) {
883 order: [ [ 'Tags', 'name', 'ASC' ] ],
891 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_SCHEDULED_UPDATE ])
895 static async getStats () {
896 const totalLocalVideos = await VideoModel.count({
901 const totalVideos = await VideoModel.count()
903 let totalLocalVideoViews = await VideoModel.sum('views', {
908 // Sequelize could return null...
909 if (!totalLocalVideoViews) totalLocalVideoViews = 0
913 totalLocalVideoViews,
918 private static buildActorWhereWithFilter (filter?: VideoFilter) {
919 if (filter && filter === 'local') {
928 private static getCategoryLabel (id: number) {
929 return VIDEO_CATEGORIES[id] || 'Misc'
932 private static getLicenceLabel (id: number) {
933 return VIDEO_LICENCES[id] || 'Unknown'
936 private static getLanguageLabel (id: string) {
937 return VIDEO_LANGUAGES[id] || 'Unknown'
940 private static getPrivacyLabel (id: number) {
941 return VIDEO_PRIVACIES[id] || 'Unknown'
944 private static getStateLabel (id: number) {
945 return VIDEO_STATES[id] || 'Unknown'
949 if (Array.isArray(this.VideoFiles) === false) return undefined
951 // The original file is the file that have the higher resolution
952 return maxBy(this.VideoFiles, file => file.resolution)
955 getVideoFilename (videoFile: VideoFileModel) {
956 return this.uuid + '-' + videoFile.resolution + videoFile.extname
959 getThumbnailName () {
960 // We always have a copy of the thumbnail
961 const extension = '.jpg'
962 return this.uuid + extension
966 const extension = '.jpg'
967 return this.uuid + extension
970 getTorrentFileName (videoFile: VideoFileModel) {
971 const extension = '.torrent'
972 return this.uuid + '-' + videoFile.resolution + extension
976 return this.remote === false
979 createPreview (videoFile: VideoFileModel) {
980 return generateImageFromVideoFile(
981 this.getVideoFilePath(videoFile),
982 CONFIG.STORAGE.PREVIEWS_DIR,
983 this.getPreviewName(),
988 createThumbnail (videoFile: VideoFileModel) {
989 return generateImageFromVideoFile(
990 this.getVideoFilePath(videoFile),
991 CONFIG.STORAGE.THUMBNAILS_DIR,
992 this.getThumbnailName(),
997 getTorrentFilePath (videoFile: VideoFileModel) {
998 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1001 getVideoFilePath (videoFile: VideoFileModel) {
1002 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1005 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1007 // Keep the extname, it's used by the client to stream the file inside a web browser
1008 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1009 createdBy: 'PeerTube',
1011 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1012 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1015 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1019 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1021 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1022 logger.info('Creating torrent %s.', filePath)
1024 await writeFilePromise(filePath, torrent)
1026 const parsedTorrent = parseTorrent(torrent)
1027 videoFile.infoHash = parsedTorrent.infoHash
1030 getEmbedStaticPath () {
1031 return '/videos/embed/' + this.uuid
1034 getThumbnailStaticPath () {
1035 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1038 getPreviewStaticPath () {
1039 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1042 toFormattedJSON (options?: {
1043 additionalAttributes: {
1045 waitTranscoding?: boolean,
1046 scheduledUpdate?: boolean
1049 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1050 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1052 const videoObject: Video = {
1058 label: VideoModel.getCategoryLabel(this.category)
1062 label: VideoModel.getLicenceLabel(this.licence)
1066 label: VideoModel.getLanguageLabel(this.language)
1070 label: VideoModel.getPrivacyLabel(this.privacy)
1073 description: this.getTruncatedDescription(),
1074 isLocal: this.isOwned(),
1075 duration: this.duration,
1078 dislikes: this.dislikes,
1079 thumbnailPath: this.getThumbnailStaticPath(),
1080 previewPath: this.getPreviewStaticPath(),
1081 embedPath: this.getEmbedStaticPath(),
1082 createdAt: this.createdAt,
1083 updatedAt: this.updatedAt,
1084 publishedAt: this.publishedAt,
1086 id: formattedAccount.id,
1087 uuid: formattedAccount.uuid,
1088 name: formattedAccount.name,
1089 displayName: formattedAccount.displayName,
1090 url: formattedAccount.url,
1091 host: formattedAccount.host,
1092 avatar: formattedAccount.avatar
1095 id: formattedVideoChannel.id,
1096 uuid: formattedVideoChannel.uuid,
1097 name: formattedVideoChannel.name,
1098 displayName: formattedVideoChannel.displayName,
1099 url: formattedVideoChannel.url,
1100 host: formattedVideoChannel.host,
1101 avatar: formattedVideoChannel.avatar
1106 if (options.additionalAttributes.state === true) {
1107 videoObject.state = {
1109 label: VideoModel.getStateLabel(this.state)
1113 if (options.additionalAttributes.waitTranscoding === true) {
1114 videoObject.waitTranscoding = this.waitTranscoding
1117 if (options.additionalAttributes.scheduledUpdate === true && this.ScheduleVideoUpdate) {
1118 videoObject.scheduledUpdate = {
1119 updateAt: this.ScheduleVideoUpdate.updateAt,
1120 privacy: this.ScheduleVideoUpdate.privacy || undefined
1128 toFormattedDetailsJSON (): VideoDetails {
1129 const formattedJson = this.toFormattedJSON({
1130 additionalAttributes: {
1131 scheduledUpdate: true
1135 const detailsJson = {
1136 support: this.support,
1137 descriptionPath: this.getDescriptionPath(),
1138 channel: this.VideoChannel.toFormattedJSON(),
1139 account: this.VideoChannel.Account.toFormattedJSON(),
1140 tags: map(this.Tags, 'name'),
1141 commentsEnabled: this.commentsEnabled,
1142 waitTranscoding: this.waitTranscoding,
1145 label: VideoModel.getStateLabel(this.state)
1150 // Format and sort video files
1151 detailsJson.files = this.getFormattedVideoFilesJSON()
1153 return Object.assign(formattedJson, detailsJson)
1156 getFormattedVideoFilesJSON (): VideoFile[] {
1157 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1159 return this.VideoFiles
1161 let resolutionLabel = videoFile.resolution + 'p'
1165 id: videoFile.resolution,
1166 label: resolutionLabel
1168 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1169 size: videoFile.size,
1171 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1172 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1173 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1174 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
1178 if (a.resolution.id < b.resolution.id) return 1
1179 if (a.resolution.id === b.resolution.id) return 0
1184 toActivityPubObject (): VideoTorrentObject {
1185 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1186 if (!this.Tags) this.Tags = []
1188 const tag = this.Tags.map(t => ({
1189 type: 'Hashtag' as 'Hashtag',
1194 if (this.language) {
1196 identifier: this.language,
1197 name: VideoModel.getLanguageLabel(this.language)
1202 if (this.category) {
1204 identifier: this.category + '',
1205 name: VideoModel.getCategoryLabel(this.category)
1212 identifier: this.licence + '',
1213 name: VideoModel.getLicenceLabel(this.licence)
1218 for (const file of this.VideoFiles) {
1221 mimeType: VIDEO_EXT_MIMETYPE[file.extname],
1222 href: this.getVideoFileUrl(file, baseUrlHttp),
1223 width: file.resolution,
1229 mimeType: 'application/x-bittorrent',
1230 href: this.getTorrentUrl(file, baseUrlHttp),
1231 width: file.resolution
1236 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1237 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1238 width: file.resolution
1242 // Add video url too
1245 mimeType: 'text/html',
1246 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1249 const subtitleLanguage = []
1250 for (const caption of this.VideoCaptions) {
1251 subtitleLanguage.push({
1252 identifier: caption.language,
1253 name: VideoCaptionModel.getLanguageLabel(caption.language)
1258 type: 'Video' as 'Video',
1261 duration: this.getActivityStreamDuration(),
1268 sensitive: this.nsfw,
1269 waitTranscoding: this.waitTranscoding,
1271 commentsEnabled: this.commentsEnabled,
1272 published: this.publishedAt.toISOString(),
1273 updated: this.updatedAt.toISOString(),
1274 mediaType: 'text/markdown',
1275 content: this.getTruncatedDescription(),
1276 support: this.support,
1280 url: this.getThumbnailUrl(baseUrlHttp),
1281 mediaType: 'image/jpeg',
1282 width: THUMBNAILS_SIZE.width,
1283 height: THUMBNAILS_SIZE.height
1286 likes: getVideoLikesActivityPubUrl(this),
1287 dislikes: getVideoDislikesActivityPubUrl(this),
1288 shares: getVideoSharesActivityPubUrl(this),
1289 comments: getVideoCommentsActivityPubUrl(this),
1293 id: this.VideoChannel.Account.Actor.url
1297 id: this.VideoChannel.Actor.url
1303 getTruncatedDescription () {
1304 if (!this.description) return null
1306 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1307 return peertubeTruncate(this.description, maxLength)
1310 async optimizeOriginalVideofile () {
1311 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1312 const newExtname = '.mp4'
1313 const inputVideoFile = this.getOriginalFile()
1314 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1315 const videoTranscodedPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1317 const transcodeOptions = {
1318 inputPath: videoInputPath,
1319 outputPath: videoTranscodedPath
1322 // Could be very long!
1323 await transcode(transcodeOptions)
1326 await unlinkPromise(videoInputPath)
1328 // Important to do this before getVideoFilename() to take in account the new file extension
1329 inputVideoFile.set('extname', newExtname)
1331 const videoOutputPath = this.getVideoFilePath(inputVideoFile)
1332 await renamePromise(videoTranscodedPath, videoOutputPath)
1333 const stats = await statPromise(videoOutputPath)
1334 const fps = await getVideoFileFPS(videoOutputPath)
1336 inputVideoFile.set('size', stats.size)
1337 inputVideoFile.set('fps', fps)
1339 await this.createTorrentAndSetInfoHash(inputVideoFile)
1340 await inputVideoFile.save()
1343 // Auto destruction...
1344 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1350 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1351 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1352 const extname = '.mp4'
1354 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1355 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1357 const newVideoFile = new VideoFileModel({
1363 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1365 const transcodeOptions = {
1366 inputPath: videoInputPath,
1367 outputPath: videoOutputPath,
1372 await transcode(transcodeOptions)
1374 const stats = await statPromise(videoOutputPath)
1375 const fps = await getVideoFileFPS(videoOutputPath)
1377 newVideoFile.set('size', stats.size)
1378 newVideoFile.set('fps', fps)
1380 await this.createTorrentAndSetInfoHash(newVideoFile)
1382 await newVideoFile.save()
1384 this.VideoFiles.push(newVideoFile)
1387 async importVideoFile (inputFilePath: string) {
1388 const { videoFileResolution } = await getVideoFileResolution(inputFilePath)
1389 const { size } = await statPromise(inputFilePath)
1390 const fps = await getVideoFileFPS(inputFilePath)
1392 let updatedVideoFile = new VideoFileModel({
1393 resolution: videoFileResolution,
1394 extname: extname(inputFilePath),
1400 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
1402 if (currentVideoFile) {
1403 // Remove old file and old torrent
1404 await this.removeFile(currentVideoFile)
1405 await this.removeTorrent(currentVideoFile)
1406 // Remove the old video file from the array
1407 this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile)
1409 // Update the database
1410 currentVideoFile.set('extname', updatedVideoFile.extname)
1411 currentVideoFile.set('size', updatedVideoFile.size)
1412 currentVideoFile.set('fps', updatedVideoFile.fps)
1414 updatedVideoFile = currentVideoFile
1417 const outputPath = this.getVideoFilePath(updatedVideoFile)
1418 await copyFilePromise(inputFilePath, outputPath)
1420 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1422 await updatedVideoFile.save()
1424 this.VideoFiles.push(updatedVideoFile)
1427 getOriginalFileResolution () {
1428 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1430 return getVideoFileResolution(originalFilePath)
1433 getDescriptionPath () {
1434 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1437 removeThumbnail () {
1438 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1439 return unlinkPromise(thumbnailPath)
1443 // Same name than video thumbnail
1444 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1447 removeFile (videoFile: VideoFileModel) {
1448 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1449 return unlinkPromise(filePath)
1452 removeTorrent (videoFile: VideoFileModel) {
1453 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1454 return unlinkPromise(torrentPath)
1457 getActivityStreamDuration () {
1458 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1459 return 'PT' + this.duration + 'S'
1462 private getBaseUrls () {
1466 if (this.isOwned()) {
1467 baseUrlHttp = CONFIG.WEBSERVER.URL
1468 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1470 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1471 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1474 return { baseUrlHttp, baseUrlWs }
1477 private getThumbnailUrl (baseUrlHttp: string) {
1478 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1481 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1482 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1485 private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1486 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1489 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1490 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1493 private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1494 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1497 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1498 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1499 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1500 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1502 const magnetHash = {
1506 infoHash: videoFile.infoHash,
1510 return magnetUtil.encode(magnetHash)