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, 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'
96 export enum ScopeNames {
97 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
98 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
99 WITH_TAGS = 'WITH_TAGS',
100 WITH_FILES = 'WITH_FILES'
104 [ScopeNames.AVAILABLE_FOR_LIST]: (options: {
107 filter?: VideoFilter,
110 videoChannelId?: number
112 const accountInclude = {
113 attributes: [ 'id', 'name' ],
114 model: AccountModel.unscoped(),
119 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
120 model: ActorModel.unscoped(),
122 where: VideoModel.buildActorWhereWithFilter(options.filter),
125 attributes: [ 'host' ],
126 model: ServerModel.unscoped(),
130 model: AvatarModel.unscoped(),
138 const videoChannelInclude = {
139 attributes: [ 'name', 'description', 'id' ],
140 model: VideoChannelModel.unscoped(),
145 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
146 model: ActorModel.unscoped(),
150 attributes: [ 'host' ],
151 model: ServerModel.unscoped(),
155 model: AvatarModel.unscoped(),
164 // Force actorId to be a number to avoid SQL injections
165 const actorIdNumber = parseInt(options.actorId.toString(), 10)
166 const query: IFindOptions<VideoModel> = {
169 [Sequelize.Op.notIn]: Sequelize.literal(
170 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
172 [ Sequelize.Op.in ]: Sequelize.literal(
174 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
175 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
176 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
178 'SELECT "video"."id" AS "id" FROM "video" ' +
179 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
180 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
181 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
182 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
183 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + actorIdNumber +
187 // Always list public videos
188 privacy: VideoPrivacy.PUBLIC,
189 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
190 [ Sequelize.Op.or ]: [
192 state: VideoState.PUBLISHED
195 [ Sequelize.Op.and ]: {
196 state: VideoState.TO_TRANSCODE,
197 waitTranscoding: false
202 include: [ videoChannelInclude ]
205 if (options.withFiles === true) {
207 model: VideoFileModel.unscoped(),
213 if (options.hideNSFW === true) {
214 query.where['nsfw'] = false
217 if (options.accountId) {
218 accountInclude.where = {
219 id: options.accountId
223 if (options.videoChannelId) {
224 videoChannelInclude.where = {
225 id: options.videoChannelId
231 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
234 model: () => VideoChannelModel.unscoped(),
239 exclude: [ 'privateKey', 'publicKey' ]
241 model: () => ActorModel.unscoped(),
245 attributes: [ 'host' ],
246 model: () => ServerModel.unscoped(),
252 model: () => AccountModel.unscoped(),
256 model: () => ActorModel.unscoped(),
258 exclude: [ 'privateKey', 'publicKey' ]
263 attributes: [ 'host' ],
264 model: () => ServerModel.unscoped(),
268 model: () => AvatarModel.unscoped(),
279 [ScopeNames.WITH_TAGS]: {
280 include: [ () => TagModel ]
282 [ScopeNames.WITH_FILES]: {
285 model: () => VideoFileModel.unscoped(),
298 fields: [ 'createdAt' ]
301 fields: [ 'duration' ]
313 fields: [ 'channelId' ]
316 fields: [ 'id', 'privacy', 'state', 'waitTranscoding' ]
324 export class VideoModel extends Model<VideoModel> {
327 @Default(DataType.UUIDV4)
329 @Column(DataType.UUID)
333 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
339 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
345 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
351 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
352 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
356 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
361 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
367 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
368 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
373 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
374 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
378 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
408 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
409 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
414 commentsEnabled: boolean
418 waitTranscoding: boolean
422 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
433 @Default(Sequelize.NOW)
437 @ForeignKey(() => VideoChannelModel)
441 @BelongsTo(() => VideoChannelModel, {
447 VideoChannel: VideoChannelModel
449 @BelongsToMany(() => TagModel, {
450 foreignKey: 'videoId',
451 through: () => VideoTagModel,
456 @HasMany(() => VideoAbuseModel, {
463 VideoAbuses: VideoAbuseModel[]
465 @HasMany(() => VideoFileModel, {
472 VideoFiles: VideoFileModel[]
474 @HasMany(() => VideoShareModel, {
481 VideoShares: VideoShareModel[]
483 @HasMany(() => AccountVideoRateModel, {
490 AccountVideoRates: AccountVideoRateModel[]
492 @HasMany(() => VideoCommentModel, {
500 VideoComments: VideoCommentModel[]
502 @HasOne(() => ScheduleVideoUpdateModel, {
509 ScheduleVideoUpdate: ScheduleVideoUpdateModel
512 static async sendDelete (instance: VideoModel, options) {
513 if (instance.isOwned()) {
514 if (!instance.VideoChannel) {
515 instance.VideoChannel = await instance.$get('VideoChannel', {
519 include: [ ActorModel ]
522 transaction: options.transaction
523 }) as VideoChannelModel
526 logger.debug('Sending delete of video %s.', instance.url)
528 return sendDeleteVideo(instance, options.transaction)
535 static async removeFilesAndSendDelete (instance: VideoModel) {
536 const tasks: Promise<any>[] = []
538 logger.debug('Removing files of video %s.', instance.url)
540 tasks.push(instance.removeThumbnail())
542 if (instance.isOwned()) {
543 if (!Array.isArray(instance.VideoFiles)) {
544 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
547 tasks.push(instance.removePreview())
549 // Remove physical files and torrents
550 instance.VideoFiles.forEach(file => {
551 tasks.push(instance.removeFile(file))
552 tasks.push(instance.removeTorrent(file))
556 // Do not wait video deletion because we could be in a transaction
559 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
566 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
569 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
570 function getRawQuery (select: string) {
571 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
572 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
573 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
574 'WHERE "Account"."actorId" = ' + actorId
575 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
576 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
577 'WHERE "VideoShare"."actorId" = ' + actorId
579 return `(${queryVideo}) UNION (${queryVideoShare})`
582 const rawQuery = getRawQuery('"Video"."id"')
583 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
589 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
592 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
595 { privacy: VideoPrivacy.PUBLIC },
596 { privacy: VideoPrivacy.UNLISTED }
601 attributes: [ 'id', 'url' ],
602 model: VideoShareModel.unscoped(),
604 // We only want videos shared by this actor
606 [Sequelize.Op.and]: [
609 [Sequelize.Op.not]: null
619 attributes: [ 'id', 'url' ],
620 model: ActorModel.unscoped()
625 model: VideoChannelModel.unscoped(),
629 attributes: [ 'name' ],
630 model: AccountModel.unscoped(),
634 attributes: [ 'id', 'url', 'followersUrl' ],
635 model: ActorModel.unscoped(),
641 attributes: [ 'id', 'url', 'followersUrl' ],
642 model: ActorModel.unscoped(),
652 return Bluebird.all([
653 // FIXME: typing issue
654 VideoModel.findAll(query as any),
655 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
656 ]).then(([ rows, totals ]) => {
657 // totals: totalVideos + totalVideoShares
659 let totalVideoShares = 0
660 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
661 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
663 const total = totalVideos + totalVideoShares
671 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, hideNSFW: boolean, withFiles = false) {
672 const query: IFindOptions<VideoModel> = {
675 order: getSort(sort),
678 model: VideoChannelModel,
691 model: ScheduleVideoUpdateModel,
697 if (withFiles === true) {
699 model: VideoFileModel.unscoped(),
704 if (hideNSFW === true) {
710 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
718 static async listForApi (options: {
724 filter?: VideoFilter,
726 videoChannelId?: number
729 offset: options.start,
730 limit: options.count,
731 order: getSort(options.sort)
734 const serverActor = await getServerActor()
737 ScopeNames.AVAILABLE_FOR_LIST, {
738 actorId: serverActor.id,
739 hideNSFW: options.hideNSFW,
740 filter: options.filter,
741 withFiles: options.withFiles,
742 accountId: options.accountId,
743 videoChannelId: options.videoChannelId
748 return VideoModel.scope(scopes)
749 .findAndCountAll(query)
750 .then(({ rows, count }) => {
758 static async searchAndPopulateAccountAndServer (value: string, start: number, count: number, sort: string, hideNSFW: boolean) {
759 const query: IFindOptions<VideoModel> = {
762 order: getSort(sort),
767 [ Sequelize.Op.iLike ]: '%' + value + '%'
771 preferredUsernameChannel: Sequelize.where(Sequelize.col('VideoChannel->Actor.preferredUsername'), {
772 [ Sequelize.Op.iLike ]: '%' + value + '%'
776 preferredUsernameAccount: Sequelize.where(Sequelize.col('VideoChannel->Account->Actor.preferredUsername'), {
777 [ Sequelize.Op.iLike ]: '%' + value + '%'
781 host: Sequelize.where(Sequelize.col('VideoChannel->Account->Actor->Server.host'), {
782 [ Sequelize.Op.iLike ]: '%' + value + '%'
789 const serverActor = await getServerActor()
792 ScopeNames.AVAILABLE_FOR_LIST, {
793 actorId: serverActor.id,
799 return VideoModel.scope(scopes)
800 .findAndCountAll(query)
801 .then(({ rows, count }) => {
809 static load (id: number) {
810 return VideoModel.findById(id)
813 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
814 const query: IFindOptions<VideoModel> = {
820 if (t !== undefined) query.transaction = t
822 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
825 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
826 const query: IFindOptions<VideoModel> = {
835 if (t !== undefined) query.transaction = t
837 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
840 static loadAndPopulateAccountAndServerAndTags (id: number) {
842 order: [ [ 'Tags', 'name', 'ASC' ] ]
846 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
847 .findById(id, options)
850 static loadByUUID (uuid: string) {
858 .scope([ ScopeNames.WITH_FILES ])
862 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string, t?: Sequelize.Transaction) {
864 order: [ [ 'Tags', 'name', 'ASC' ] ],
872 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
876 static async getStats () {
877 const totalLocalVideos = await VideoModel.count({
882 const totalVideos = await VideoModel.count()
884 let totalLocalVideoViews = await VideoModel.sum('views', {
889 // Sequelize could return null...
890 if (!totalLocalVideoViews) totalLocalVideoViews = 0
894 totalLocalVideoViews,
899 private static buildActorWhereWithFilter (filter?: VideoFilter) {
900 if (filter && filter === 'local') {
909 private static getCategoryLabel (id: number) {
910 return VIDEO_CATEGORIES[id] || 'Misc'
913 private static getLicenceLabel (id: number) {
914 return VIDEO_LICENCES[id] || 'Unknown'
917 private static getLanguageLabel (id: string) {
918 return VIDEO_LANGUAGES[id] || 'Unknown'
921 private static getPrivacyLabel (id: number) {
922 return VIDEO_PRIVACIES[id] || 'Unknown'
925 private static getStateLabel (id: number) {
926 return VIDEO_STATES[id] || 'Unknown'
930 if (Array.isArray(this.VideoFiles) === false) return undefined
932 // The original file is the file that have the higher resolution
933 return maxBy(this.VideoFiles, file => file.resolution)
936 getVideoFilename (videoFile: VideoFileModel) {
937 return this.uuid + '-' + videoFile.resolution + videoFile.extname
940 getThumbnailName () {
941 // We always have a copy of the thumbnail
942 const extension = '.jpg'
943 return this.uuid + extension
947 const extension = '.jpg'
948 return this.uuid + extension
951 getTorrentFileName (videoFile: VideoFileModel) {
952 const extension = '.torrent'
953 return this.uuid + '-' + videoFile.resolution + extension
957 return this.remote === false
960 createPreview (videoFile: VideoFileModel) {
961 return generateImageFromVideoFile(
962 this.getVideoFilePath(videoFile),
963 CONFIG.STORAGE.PREVIEWS_DIR,
964 this.getPreviewName(),
969 createThumbnail (videoFile: VideoFileModel) {
970 return generateImageFromVideoFile(
971 this.getVideoFilePath(videoFile),
972 CONFIG.STORAGE.THUMBNAILS_DIR,
973 this.getThumbnailName(),
978 getTorrentFilePath (videoFile: VideoFileModel) {
979 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
982 getVideoFilePath (videoFile: VideoFileModel) {
983 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
986 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
988 // Keep the extname, it's used by the client to stream the file inside a web browser
989 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
990 createdBy: 'PeerTube',
992 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
993 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
996 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1000 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1002 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1003 logger.info('Creating torrent %s.', filePath)
1005 await writeFilePromise(filePath, torrent)
1007 const parsedTorrent = parseTorrent(torrent)
1008 videoFile.infoHash = parsedTorrent.infoHash
1012 return '/videos/embed/' + this.uuid
1015 getThumbnailPath () {
1016 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1020 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1023 toFormattedJSON (options?: {
1024 additionalAttributes: {
1026 waitTranscoding: boolean,
1027 scheduledUpdate: boolean
1030 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1031 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1033 const videoObject: Video = {
1039 label: VideoModel.getCategoryLabel(this.category)
1043 label: VideoModel.getLicenceLabel(this.licence)
1047 label: VideoModel.getLanguageLabel(this.language)
1051 label: VideoModel.getPrivacyLabel(this.privacy)
1054 description: this.getTruncatedDescription(),
1055 isLocal: this.isOwned(),
1056 duration: this.duration,
1059 dislikes: this.dislikes,
1060 thumbnailPath: this.getThumbnailPath(),
1061 previewPath: this.getPreviewPath(),
1062 embedPath: this.getEmbedPath(),
1063 createdAt: this.createdAt,
1064 updatedAt: this.updatedAt,
1065 publishedAt: this.publishedAt,
1067 id: formattedAccount.id,
1068 uuid: formattedAccount.uuid,
1069 name: formattedAccount.name,
1070 displayName: formattedAccount.displayName,
1071 url: formattedAccount.url,
1072 host: formattedAccount.host,
1073 avatar: formattedAccount.avatar
1076 id: formattedVideoChannel.id,
1077 uuid: formattedVideoChannel.uuid,
1078 name: formattedVideoChannel.name,
1079 displayName: formattedVideoChannel.displayName,
1080 url: formattedVideoChannel.url,
1081 host: formattedVideoChannel.host,
1082 avatar: formattedVideoChannel.avatar
1087 if (options.additionalAttributes.state) {
1088 videoObject.state = {
1090 label: VideoModel.getStateLabel(this.state)
1094 if (options.additionalAttributes.waitTranscoding) {
1095 videoObject.waitTranscoding = this.waitTranscoding
1098 if (options.additionalAttributes.scheduledUpdate && this.ScheduleVideoUpdate) {
1099 videoObject.scheduledUpdate = {
1100 updateAt: this.ScheduleVideoUpdate.updateAt,
1101 privacy: this.ScheduleVideoUpdate.privacy || undefined
1109 toFormattedDetailsJSON (): VideoDetails {
1110 const formattedJson = this.toFormattedJSON()
1112 const detailsJson = {
1113 support: this.support,
1114 descriptionPath: this.getDescriptionPath(),
1115 channel: this.VideoChannel.toFormattedJSON(),
1116 account: this.VideoChannel.Account.toFormattedJSON(),
1117 tags: map(this.Tags, 'name'),
1118 commentsEnabled: this.commentsEnabled,
1119 waitTranscoding: this.waitTranscoding,
1122 label: VideoModel.getStateLabel(this.state)
1127 // Format and sort video files
1128 detailsJson.files = this.getFormattedVideoFilesJSON()
1130 return Object.assign(formattedJson, detailsJson)
1133 getFormattedVideoFilesJSON (): VideoFile[] {
1134 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1136 return this.VideoFiles
1138 let resolutionLabel = videoFile.resolution + 'p'
1142 id: videoFile.resolution,
1143 label: resolutionLabel
1145 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1146 size: videoFile.size,
1147 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1148 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1149 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1150 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
1154 if (a.resolution.id < b.resolution.id) return 1
1155 if (a.resolution.id === b.resolution.id) return 0
1160 toActivityPubObject (): VideoTorrentObject {
1161 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1162 if (!this.Tags) this.Tags = []
1164 const tag = this.Tags.map(t => ({
1165 type: 'Hashtag' as 'Hashtag',
1170 if (this.language) {
1172 identifier: this.language,
1173 name: VideoModel.getLanguageLabel(this.language)
1178 if (this.category) {
1180 identifier: this.category + '',
1181 name: VideoModel.getCategoryLabel(this.category)
1188 identifier: this.licence + '',
1189 name: VideoModel.getLicenceLabel(this.licence)
1194 for (const file of this.VideoFiles) {
1197 mimeType: VIDEO_EXT_MIMETYPE[file.extname],
1198 href: this.getVideoFileUrl(file, baseUrlHttp),
1199 width: file.resolution,
1205 mimeType: 'application/x-bittorrent',
1206 href: this.getTorrentUrl(file, baseUrlHttp),
1207 width: file.resolution
1212 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1213 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1214 width: file.resolution
1218 // Add video url too
1221 mimeType: 'text/html',
1222 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1226 type: 'Video' as 'Video',
1229 duration: this.getActivityStreamDuration(),
1236 sensitive: this.nsfw,
1237 waitTranscoding: this.waitTranscoding,
1239 commentsEnabled: this.commentsEnabled,
1240 published: this.publishedAt.toISOString(),
1241 updated: this.updatedAt.toISOString(),
1242 mediaType: 'text/markdown',
1243 content: this.getTruncatedDescription(),
1244 support: this.support,
1247 url: this.getThumbnailUrl(baseUrlHttp),
1248 mediaType: 'image/jpeg',
1249 width: THUMBNAILS_SIZE.width,
1250 height: THUMBNAILS_SIZE.height
1253 likes: getVideoLikesActivityPubUrl(this),
1254 dislikes: getVideoDislikesActivityPubUrl(this),
1255 shares: getVideoSharesActivityPubUrl(this),
1256 comments: getVideoCommentsActivityPubUrl(this),
1260 id: this.VideoChannel.Account.Actor.url
1264 id: this.VideoChannel.Actor.url
1270 getTruncatedDescription () {
1271 if (!this.description) return null
1273 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1274 return peertubeTruncate(this.description, maxLength)
1277 async optimizeOriginalVideofile () {
1278 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1279 const newExtname = '.mp4'
1280 const inputVideoFile = this.getOriginalFile()
1281 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1282 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1284 const transcodeOptions = {
1285 inputPath: videoInputPath,
1286 outputPath: videoOutputPath
1289 // Could be very long!
1290 await transcode(transcodeOptions)
1293 await unlinkPromise(videoInputPath)
1295 // Important to do this before getVideoFilename() to take in account the new file extension
1296 inputVideoFile.set('extname', newExtname)
1298 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1299 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1301 inputVideoFile.set('size', stats.size)
1303 await this.createTorrentAndSetInfoHash(inputVideoFile)
1304 await inputVideoFile.save()
1307 // Auto destruction...
1308 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1314 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1315 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1316 const extname = '.mp4'
1318 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1319 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1321 const newVideoFile = new VideoFileModel({
1327 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1329 const transcodeOptions = {
1330 inputPath: videoInputPath,
1331 outputPath: videoOutputPath,
1336 await transcode(transcodeOptions)
1338 const stats = await statPromise(videoOutputPath)
1340 newVideoFile.set('size', stats.size)
1342 await this.createTorrentAndSetInfoHash(newVideoFile)
1344 await newVideoFile.save()
1346 this.VideoFiles.push(newVideoFile)
1349 async importVideoFile (inputFilePath: string) {
1350 let updatedVideoFile = new VideoFileModel({
1351 resolution: (await getVideoFileResolution(inputFilePath)).videoFileResolution,
1352 extname: extname(inputFilePath),
1353 size: (await statPromise(inputFilePath)).size,
1357 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
1359 if (currentVideoFile) {
1360 // Remove old file and old torrent
1361 await this.removeFile(currentVideoFile)
1362 await this.removeTorrent(currentVideoFile)
1363 // Remove the old video file from the array
1364 this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile)
1366 // Update the database
1367 currentVideoFile.set('extname', updatedVideoFile.extname)
1368 currentVideoFile.set('size', updatedVideoFile.size)
1370 updatedVideoFile = currentVideoFile
1373 const outputPath = this.getVideoFilePath(updatedVideoFile)
1374 await copyFilePromise(inputFilePath, outputPath)
1376 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1378 await updatedVideoFile.save()
1380 this.VideoFiles.push(updatedVideoFile)
1383 getOriginalFileResolution () {
1384 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1386 return getVideoFileResolution(originalFilePath)
1389 getDescriptionPath () {
1390 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1393 removeThumbnail () {
1394 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1395 return unlinkPromise(thumbnailPath)
1399 // Same name than video thumbnail
1400 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1403 removeFile (videoFile: VideoFileModel) {
1404 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1405 return unlinkPromise(filePath)
1408 removeTorrent (videoFile: VideoFileModel) {
1409 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1410 return unlinkPromise(torrentPath)
1413 getActivityStreamDuration () {
1414 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1415 return 'PT' + this.duration + 'S'
1418 private getBaseUrls () {
1422 if (this.isOwned()) {
1423 baseUrlHttp = CONFIG.WEBSERVER.URL
1424 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1426 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1427 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1430 return { baseUrlHttp, baseUrlWs }
1433 private getThumbnailUrl (baseUrlHttp: string) {
1434 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1437 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1438 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1441 private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1442 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1445 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1446 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1449 private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1450 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1453 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1454 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1455 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1456 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1458 const magnetHash = {
1462 infoHash: videoFile.infoHash,
1466 return magnetUtil.encode(magnetHash)