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 { 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 export enum ScopeNames {
98 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
99 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
100 WITH_TAGS = 'WITH_TAGS',
101 WITH_FILES = 'WITH_FILES',
102 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE'
106 [ScopeNames.AVAILABLE_FOR_LIST]: (options: {
109 filter?: VideoFilter,
113 videoChannelId?: number
115 const accountInclude = {
116 attributes: [ 'id', 'name' ],
117 model: AccountModel.unscoped(),
122 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
123 model: ActorModel.unscoped(),
125 where: VideoModel.buildActorWhereWithFilter(options.filter),
128 attributes: [ 'host' ],
129 model: ServerModel.unscoped(),
133 model: AvatarModel.unscoped(),
141 const videoChannelInclude = {
142 attributes: [ 'name', 'description', 'id' ],
143 model: VideoChannelModel.unscoped(),
148 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
149 model: ActorModel.unscoped(),
153 attributes: [ 'host' ],
154 model: ServerModel.unscoped(),
158 model: AvatarModel.unscoped(),
167 // Force actorId to be a number to avoid SQL injections
168 const actorIdNumber = parseInt(options.actorId.toString(), 10)
169 const query: IFindOptions<VideoModel> = {
172 [Sequelize.Op.notIn]: Sequelize.literal(
173 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
175 [ Sequelize.Op.in ]: Sequelize.literal(
177 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
178 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
179 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
181 'SELECT "video"."id" AS "id" FROM "video" ' +
182 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
183 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
184 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
185 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
186 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + actorIdNumber +
190 // Always list public videos
191 privacy: VideoPrivacy.PUBLIC,
192 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
193 [ Sequelize.Op.or ]: [
195 state: VideoState.PUBLISHED
198 [ Sequelize.Op.and ]: {
199 state: VideoState.TO_TRANSCODE,
200 waitTranscoding: false
205 include: [ videoChannelInclude ]
208 if (options.withFiles === true) {
210 model: VideoFileModel.unscoped(),
216 if (options.hideNSFW === true) {
217 query.where['nsfw'] = false
220 if (options.category) {
221 query.where['category'] = options.category
224 if (options.accountId) {
225 accountInclude.where = {
226 id: options.accountId
230 if (options.videoChannelId) {
231 videoChannelInclude.where = {
232 id: options.videoChannelId
238 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
241 model: () => VideoChannelModel.unscoped(),
246 exclude: [ 'privateKey', 'publicKey' ]
248 model: () => ActorModel.unscoped(),
252 attributes: [ 'host' ],
253 model: () => ServerModel.unscoped(),
257 model: () => AvatarModel.unscoped(),
263 model: () => AccountModel.unscoped(),
267 model: () => ActorModel.unscoped(),
269 exclude: [ 'privateKey', 'publicKey' ]
274 attributes: [ 'host' ],
275 model: () => ServerModel.unscoped(),
279 model: () => AvatarModel.unscoped(),
290 [ScopeNames.WITH_TAGS]: {
291 include: [ () => TagModel ]
293 [ScopeNames.WITH_FILES]: {
296 model: () => VideoFileModel.unscoped(),
301 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
304 model: () => ScheduleVideoUpdateModel.unscoped(),
317 fields: [ 'createdAt' ]
320 fields: [ 'duration' ]
332 fields: [ 'channelId' ]
335 fields: [ 'id', 'privacy', 'state', 'waitTranscoding' ]
343 export class VideoModel extends Model<VideoModel> {
346 @Default(DataType.UUIDV4)
348 @Column(DataType.UUID)
352 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
358 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
364 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
370 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
371 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
375 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
380 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
386 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
387 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
392 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
393 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
397 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
427 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
428 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
433 commentsEnabled: boolean
437 waitTranscoding: boolean
441 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
452 @Default(Sequelize.NOW)
456 @ForeignKey(() => VideoChannelModel)
460 @BelongsTo(() => VideoChannelModel, {
466 VideoChannel: VideoChannelModel
468 @BelongsToMany(() => TagModel, {
469 foreignKey: 'videoId',
470 through: () => VideoTagModel,
475 @HasMany(() => VideoAbuseModel, {
482 VideoAbuses: VideoAbuseModel[]
484 @HasMany(() => VideoFileModel, {
491 VideoFiles: VideoFileModel[]
493 @HasMany(() => VideoShareModel, {
500 VideoShares: VideoShareModel[]
502 @HasMany(() => AccountVideoRateModel, {
509 AccountVideoRates: AccountVideoRateModel[]
511 @HasMany(() => VideoCommentModel, {
519 VideoComments: VideoCommentModel[]
521 @HasOne(() => ScheduleVideoUpdateModel, {
528 ScheduleVideoUpdate: ScheduleVideoUpdateModel
530 @HasMany(() => VideoCaptionModel, {
537 ['separate' as any]: true
539 VideoCaptions: VideoCaptionModel[]
542 static async sendDelete (instance: VideoModel, options) {
543 if (instance.isOwned()) {
544 if (!instance.VideoChannel) {
545 instance.VideoChannel = await instance.$get('VideoChannel', {
549 include: [ ActorModel ]
552 transaction: options.transaction
553 }) as VideoChannelModel
556 logger.debug('Sending delete of video %s.', instance.url)
558 return sendDeleteVideo(instance, options.transaction)
565 static async removeFiles (instance: VideoModel) {
566 const tasks: Promise<any>[] = []
568 logger.debug('Removing files of video %s.', instance.url)
570 tasks.push(instance.removeThumbnail())
572 if (instance.isOwned()) {
573 if (!Array.isArray(instance.VideoFiles)) {
574 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
577 tasks.push(instance.removePreview())
579 // Remove physical files and torrents
580 instance.VideoFiles.forEach(file => {
581 tasks.push(instance.removeFile(file))
582 tasks.push(instance.removeTorrent(file))
586 // Do not wait video deletion because we could be in a transaction
589 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
596 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
599 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
600 function getRawQuery (select: string) {
601 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
602 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
603 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
604 'WHERE "Account"."actorId" = ' + actorId
605 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
606 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
607 'WHERE "VideoShare"."actorId" = ' + actorId
609 return `(${queryVideo}) UNION (${queryVideoShare})`
612 const rawQuery = getRawQuery('"Video"."id"')
613 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
619 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
622 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
625 { privacy: VideoPrivacy.PUBLIC },
626 { privacy: VideoPrivacy.UNLISTED }
631 attributes: [ 'language' ],
632 model: VideoCaptionModel.unscoped(),
636 attributes: [ 'id', 'url' ],
637 model: VideoShareModel.unscoped(),
639 // We only want videos shared by this actor
641 [Sequelize.Op.and]: [
644 [Sequelize.Op.not]: null
654 attributes: [ 'id', 'url' ],
655 model: ActorModel.unscoped()
660 model: VideoChannelModel.unscoped(),
664 attributes: [ 'name' ],
665 model: AccountModel.unscoped(),
669 attributes: [ 'id', 'url', 'followersUrl' ],
670 model: ActorModel.unscoped(),
676 attributes: [ 'id', 'url', 'followersUrl' ],
677 model: ActorModel.unscoped(),
687 return Bluebird.all([
688 // FIXME: typing issue
689 VideoModel.findAll(query as any),
690 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
691 ]).then(([ rows, totals ]) => {
692 // totals: totalVideos + totalVideoShares
694 let totalVideoShares = 0
695 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
696 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
698 const total = totalVideos + totalVideoShares
706 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, hideNSFW: boolean, withFiles = false) {
707 const query: IFindOptions<VideoModel> = {
710 order: getSort(sort),
713 model: VideoChannelModel,
726 model: ScheduleVideoUpdateModel,
732 if (withFiles === true) {
734 model: VideoFileModel.unscoped(),
739 if (hideNSFW === true) {
745 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
753 static async listForApi (options: {
760 filter?: VideoFilter,
762 videoChannelId?: number
765 offset: options.start,
766 limit: options.count,
767 order: getSort(options.sort)
770 const serverActor = await getServerActor()
773 ScopeNames.AVAILABLE_FOR_LIST, {
774 actorId: serverActor.id,
775 hideNSFW: options.hideNSFW,
776 category: options.category,
777 filter: options.filter,
778 withFiles: options.withFiles,
779 accountId: options.accountId,
780 videoChannelId: options.videoChannelId
785 return VideoModel.scope(scopes)
786 .findAndCountAll(query)
787 .then(({ rows, count }) => {
795 static async searchAndPopulateAccountAndServer (value: string, start: number, count: number, sort: string, hideNSFW: boolean) {
796 const query: IFindOptions<VideoModel> = {
799 order: getSort(sort),
804 [ Sequelize.Op.iLike ]: '%' + value + '%'
808 preferredUsernameChannel: Sequelize.where(Sequelize.col('VideoChannel->Actor.preferredUsername'), {
809 [ Sequelize.Op.iLike ]: '%' + value + '%'
813 preferredUsernameAccount: Sequelize.where(Sequelize.col('VideoChannel->Account->Actor.preferredUsername'), {
814 [ Sequelize.Op.iLike ]: '%' + value + '%'
818 host: Sequelize.where(Sequelize.col('VideoChannel->Account->Actor->Server.host'), {
819 [ Sequelize.Op.iLike ]: '%' + value + '%'
826 const serverActor = await getServerActor()
829 ScopeNames.AVAILABLE_FOR_LIST, {
830 actorId: serverActor.id,
836 return VideoModel.scope(scopes)
837 .findAndCountAll(query)
838 .then(({ rows, count }) => {
846 static load (id: number) {
847 return VideoModel.findById(id)
850 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
851 const query: IFindOptions<VideoModel> = {
857 if (t !== undefined) query.transaction = t
859 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
862 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
863 const query: IFindOptions<VideoModel> = {
872 if (t !== undefined) query.transaction = t
874 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
877 static loadAndPopulateAccountAndServerAndTags (id: number) {
879 order: [ [ 'Tags', 'name', 'ASC' ] ]
883 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_SCHEDULED_UPDATE ])
884 .findById(id, options)
887 static loadByUUID (uuid: string) {
895 .scope([ ScopeNames.WITH_FILES ])
899 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string, t?: Sequelize.Transaction) {
901 order: [ [ 'Tags', 'name', 'ASC' ] ],
909 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_SCHEDULED_UPDATE ])
913 static async getStats () {
914 const totalLocalVideos = await VideoModel.count({
919 const totalVideos = await VideoModel.count()
921 let totalLocalVideoViews = await VideoModel.sum('views', {
926 // Sequelize could return null...
927 if (!totalLocalVideoViews) totalLocalVideoViews = 0
931 totalLocalVideoViews,
936 private static buildActorWhereWithFilter (filter?: VideoFilter) {
937 if (filter && filter === 'local') {
946 private static getCategoryLabel (id: number) {
947 return VIDEO_CATEGORIES[id] || 'Misc'
950 private static getLicenceLabel (id: number) {
951 return VIDEO_LICENCES[id] || 'Unknown'
954 private static getLanguageLabel (id: string) {
955 return VIDEO_LANGUAGES[id] || 'Unknown'
958 private static getPrivacyLabel (id: number) {
959 return VIDEO_PRIVACIES[id] || 'Unknown'
962 private static getStateLabel (id: number) {
963 return VIDEO_STATES[id] || 'Unknown'
967 if (Array.isArray(this.VideoFiles) === false) return undefined
969 // The original file is the file that have the higher resolution
970 return maxBy(this.VideoFiles, file => file.resolution)
973 getVideoFilename (videoFile: VideoFileModel) {
974 return this.uuid + '-' + videoFile.resolution + videoFile.extname
977 getThumbnailName () {
978 // We always have a copy of the thumbnail
979 const extension = '.jpg'
980 return this.uuid + extension
984 const extension = '.jpg'
985 return this.uuid + extension
988 getTorrentFileName (videoFile: VideoFileModel) {
989 const extension = '.torrent'
990 return this.uuid + '-' + videoFile.resolution + extension
994 return this.remote === false
997 createPreview (videoFile: VideoFileModel) {
998 return generateImageFromVideoFile(
999 this.getVideoFilePath(videoFile),
1000 CONFIG.STORAGE.PREVIEWS_DIR,
1001 this.getPreviewName(),
1006 createThumbnail (videoFile: VideoFileModel) {
1007 return generateImageFromVideoFile(
1008 this.getVideoFilePath(videoFile),
1009 CONFIG.STORAGE.THUMBNAILS_DIR,
1010 this.getThumbnailName(),
1015 getTorrentFilePath (videoFile: VideoFileModel) {
1016 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1019 getVideoFilePath (videoFile: VideoFileModel) {
1020 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1023 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1025 // Keep the extname, it's used by the client to stream the file inside a web browser
1026 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1027 createdBy: 'PeerTube',
1029 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1030 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1033 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1037 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1039 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1040 logger.info('Creating torrent %s.', filePath)
1042 await writeFilePromise(filePath, torrent)
1044 const parsedTorrent = parseTorrent(torrent)
1045 videoFile.infoHash = parsedTorrent.infoHash
1048 getEmbedStaticPath () {
1049 return '/videos/embed/' + this.uuid
1052 getThumbnailStaticPath () {
1053 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1056 getPreviewStaticPath () {
1057 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1060 toFormattedJSON (options?: {
1061 additionalAttributes: {
1063 waitTranscoding?: boolean,
1064 scheduledUpdate?: boolean
1067 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1068 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1070 const videoObject: Video = {
1076 label: VideoModel.getCategoryLabel(this.category)
1080 label: VideoModel.getLicenceLabel(this.licence)
1084 label: VideoModel.getLanguageLabel(this.language)
1088 label: VideoModel.getPrivacyLabel(this.privacy)
1091 description: this.getTruncatedDescription(),
1092 isLocal: this.isOwned(),
1093 duration: this.duration,
1096 dislikes: this.dislikes,
1097 thumbnailPath: this.getThumbnailStaticPath(),
1098 previewPath: this.getPreviewStaticPath(),
1099 embedPath: this.getEmbedStaticPath(),
1100 createdAt: this.createdAt,
1101 updatedAt: this.updatedAt,
1102 publishedAt: this.publishedAt,
1104 id: formattedAccount.id,
1105 uuid: formattedAccount.uuid,
1106 name: formattedAccount.name,
1107 displayName: formattedAccount.displayName,
1108 url: formattedAccount.url,
1109 host: formattedAccount.host,
1110 avatar: formattedAccount.avatar
1113 id: formattedVideoChannel.id,
1114 uuid: formattedVideoChannel.uuid,
1115 name: formattedVideoChannel.name,
1116 displayName: formattedVideoChannel.displayName,
1117 url: formattedVideoChannel.url,
1118 host: formattedVideoChannel.host,
1119 avatar: formattedVideoChannel.avatar
1124 if (options.additionalAttributes.state === true) {
1125 videoObject.state = {
1127 label: VideoModel.getStateLabel(this.state)
1131 if (options.additionalAttributes.waitTranscoding === true) {
1132 videoObject.waitTranscoding = this.waitTranscoding
1135 if (options.additionalAttributes.scheduledUpdate === true && this.ScheduleVideoUpdate) {
1136 videoObject.scheduledUpdate = {
1137 updateAt: this.ScheduleVideoUpdate.updateAt,
1138 privacy: this.ScheduleVideoUpdate.privacy || undefined
1146 toFormattedDetailsJSON (): VideoDetails {
1147 const formattedJson = this.toFormattedJSON({
1148 additionalAttributes: {
1149 scheduledUpdate: true
1153 const detailsJson = {
1154 support: this.support,
1155 descriptionPath: this.getDescriptionPath(),
1156 channel: this.VideoChannel.toFormattedJSON(),
1157 account: this.VideoChannel.Account.toFormattedJSON(),
1158 tags: map(this.Tags, 'name'),
1159 commentsEnabled: this.commentsEnabled,
1160 waitTranscoding: this.waitTranscoding,
1163 label: VideoModel.getStateLabel(this.state)
1168 // Format and sort video files
1169 detailsJson.files = this.getFormattedVideoFilesJSON()
1171 return Object.assign(formattedJson, detailsJson)
1174 getFormattedVideoFilesJSON (): VideoFile[] {
1175 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1177 return this.VideoFiles
1179 let resolutionLabel = videoFile.resolution + 'p'
1183 id: videoFile.resolution,
1184 label: resolutionLabel
1186 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1187 size: videoFile.size,
1189 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1190 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1191 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1192 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
1196 if (a.resolution.id < b.resolution.id) return 1
1197 if (a.resolution.id === b.resolution.id) return 0
1202 toActivityPubObject (): VideoTorrentObject {
1203 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1204 if (!this.Tags) this.Tags = []
1206 const tag = this.Tags.map(t => ({
1207 type: 'Hashtag' as 'Hashtag',
1212 if (this.language) {
1214 identifier: this.language,
1215 name: VideoModel.getLanguageLabel(this.language)
1220 if (this.category) {
1222 identifier: this.category + '',
1223 name: VideoModel.getCategoryLabel(this.category)
1230 identifier: this.licence + '',
1231 name: VideoModel.getLicenceLabel(this.licence)
1236 for (const file of this.VideoFiles) {
1239 mimeType: VIDEO_EXT_MIMETYPE[file.extname],
1240 href: this.getVideoFileUrl(file, baseUrlHttp),
1241 width: file.resolution,
1247 mimeType: 'application/x-bittorrent',
1248 href: this.getTorrentUrl(file, baseUrlHttp),
1249 width: file.resolution
1254 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1255 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1256 width: file.resolution
1260 // Add video url too
1263 mimeType: 'text/html',
1264 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1267 const subtitleLanguage = []
1268 for (const caption of this.VideoCaptions) {
1269 subtitleLanguage.push({
1270 identifier: caption.language,
1271 name: VideoCaptionModel.getLanguageLabel(caption.language)
1276 type: 'Video' as 'Video',
1279 duration: this.getActivityStreamDuration(),
1286 sensitive: this.nsfw,
1287 waitTranscoding: this.waitTranscoding,
1289 commentsEnabled: this.commentsEnabled,
1290 published: this.publishedAt.toISOString(),
1291 updated: this.updatedAt.toISOString(),
1292 mediaType: 'text/markdown',
1293 content: this.getTruncatedDescription(),
1294 support: this.support,
1298 url: this.getThumbnailUrl(baseUrlHttp),
1299 mediaType: 'image/jpeg',
1300 width: THUMBNAILS_SIZE.width,
1301 height: THUMBNAILS_SIZE.height
1304 likes: getVideoLikesActivityPubUrl(this),
1305 dislikes: getVideoDislikesActivityPubUrl(this),
1306 shares: getVideoSharesActivityPubUrl(this),
1307 comments: getVideoCommentsActivityPubUrl(this),
1311 id: this.VideoChannel.Account.Actor.url
1315 id: this.VideoChannel.Actor.url
1321 getTruncatedDescription () {
1322 if (!this.description) return null
1324 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1325 return peertubeTruncate(this.description, maxLength)
1328 async optimizeOriginalVideofile () {
1329 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1330 const newExtname = '.mp4'
1331 const inputVideoFile = this.getOriginalFile()
1332 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1333 const videoTranscodedPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1335 const transcodeOptions = {
1336 inputPath: videoInputPath,
1337 outputPath: videoTranscodedPath
1340 // Could be very long!
1341 await transcode(transcodeOptions)
1344 await unlinkPromise(videoInputPath)
1346 // Important to do this before getVideoFilename() to take in account the new file extension
1347 inputVideoFile.set('extname', newExtname)
1349 const videoOutputPath = this.getVideoFilePath(inputVideoFile)
1350 await renamePromise(videoTranscodedPath, videoOutputPath)
1351 const stats = await statPromise(videoOutputPath)
1352 const fps = await getVideoFileFPS(videoOutputPath)
1354 inputVideoFile.set('size', stats.size)
1355 inputVideoFile.set('fps', fps)
1357 await this.createTorrentAndSetInfoHash(inputVideoFile)
1358 await inputVideoFile.save()
1361 // Auto destruction...
1362 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1368 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1369 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1370 const extname = '.mp4'
1372 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1373 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1375 const newVideoFile = new VideoFileModel({
1381 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1383 const transcodeOptions = {
1384 inputPath: videoInputPath,
1385 outputPath: videoOutputPath,
1390 await transcode(transcodeOptions)
1392 const stats = await statPromise(videoOutputPath)
1393 const fps = await getVideoFileFPS(videoOutputPath)
1395 newVideoFile.set('size', stats.size)
1396 newVideoFile.set('fps', fps)
1398 await this.createTorrentAndSetInfoHash(newVideoFile)
1400 await newVideoFile.save()
1402 this.VideoFiles.push(newVideoFile)
1405 async importVideoFile (inputFilePath: string) {
1406 const { videoFileResolution } = await getVideoFileResolution(inputFilePath)
1407 const { size } = await statPromise(inputFilePath)
1408 const fps = await getVideoFileFPS(inputFilePath)
1410 let updatedVideoFile = new VideoFileModel({
1411 resolution: videoFileResolution,
1412 extname: extname(inputFilePath),
1418 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
1420 if (currentVideoFile) {
1421 // Remove old file and old torrent
1422 await this.removeFile(currentVideoFile)
1423 await this.removeTorrent(currentVideoFile)
1424 // Remove the old video file from the array
1425 this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile)
1427 // Update the database
1428 currentVideoFile.set('extname', updatedVideoFile.extname)
1429 currentVideoFile.set('size', updatedVideoFile.size)
1430 currentVideoFile.set('fps', updatedVideoFile.fps)
1432 updatedVideoFile = currentVideoFile
1435 const outputPath = this.getVideoFilePath(updatedVideoFile)
1436 await copyFilePromise(inputFilePath, outputPath)
1438 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1440 await updatedVideoFile.save()
1442 this.VideoFiles.push(updatedVideoFile)
1445 getOriginalFileResolution () {
1446 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1448 return getVideoFileResolution(originalFilePath)
1451 getDescriptionPath () {
1452 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1455 removeThumbnail () {
1456 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1457 return unlinkPromise(thumbnailPath)
1461 // Same name than video thumbnail
1462 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1465 removeFile (videoFile: VideoFileModel) {
1466 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1467 return unlinkPromise(filePath)
1470 removeTorrent (videoFile: VideoFileModel) {
1471 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1472 return unlinkPromise(torrentPath)
1475 getActivityStreamDuration () {
1476 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1477 return 'PT' + this.duration + 'S'
1480 private getBaseUrls () {
1484 if (this.isOwned()) {
1485 baseUrlHttp = CONFIG.WEBSERVER.URL
1486 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1488 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1489 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1492 return { baseUrlHttp, baseUrlWs }
1495 private getThumbnailUrl (baseUrlHttp: string) {
1496 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1499 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1500 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1503 private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1504 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1507 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1508 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1511 private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1512 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1515 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1516 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1517 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1518 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1520 const magnetHash = {
1524 infoHash: videoFile.infoHash,
1528 return magnetUtil.encode(magnetHash)