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',
101 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE'
105 [ScopeNames.AVAILABLE_FOR_LIST]: (options: {
108 filter?: VideoFilter,
111 videoChannelId?: number
113 const accountInclude = {
114 attributes: [ 'id', 'name' ],
115 model: AccountModel.unscoped(),
120 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
121 model: ActorModel.unscoped(),
123 where: VideoModel.buildActorWhereWithFilter(options.filter),
126 attributes: [ 'host' ],
127 model: ServerModel.unscoped(),
131 model: AvatarModel.unscoped(),
139 const videoChannelInclude = {
140 attributes: [ 'name', 'description', 'id' ],
141 model: VideoChannelModel.unscoped(),
146 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
147 model: ActorModel.unscoped(),
151 attributes: [ 'host' ],
152 model: ServerModel.unscoped(),
156 model: AvatarModel.unscoped(),
165 // Force actorId to be a number to avoid SQL injections
166 const actorIdNumber = parseInt(options.actorId.toString(), 10)
167 const query: IFindOptions<VideoModel> = {
170 [Sequelize.Op.notIn]: Sequelize.literal(
171 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
173 [ Sequelize.Op.in ]: Sequelize.literal(
175 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
176 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
177 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
179 'SELECT "video"."id" AS "id" FROM "video" ' +
180 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
181 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
182 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
183 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
184 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + actorIdNumber +
188 // Always list public videos
189 privacy: VideoPrivacy.PUBLIC,
190 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
191 [ Sequelize.Op.or ]: [
193 state: VideoState.PUBLISHED
196 [ Sequelize.Op.and ]: {
197 state: VideoState.TO_TRANSCODE,
198 waitTranscoding: false
203 include: [ videoChannelInclude ]
206 if (options.withFiles === true) {
208 model: VideoFileModel.unscoped(),
214 if (options.hideNSFW === true) {
215 query.where['nsfw'] = false
218 if (options.accountId) {
219 accountInclude.where = {
220 id: options.accountId
224 if (options.videoChannelId) {
225 videoChannelInclude.where = {
226 id: options.videoChannelId
232 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
235 model: () => VideoChannelModel.unscoped(),
240 exclude: [ 'privateKey', 'publicKey' ]
242 model: () => ActorModel.unscoped(),
246 attributes: [ 'host' ],
247 model: () => ServerModel.unscoped(),
253 model: () => AccountModel.unscoped(),
257 model: () => ActorModel.unscoped(),
259 exclude: [ 'privateKey', 'publicKey' ]
264 attributes: [ 'host' ],
265 model: () => ServerModel.unscoped(),
269 model: () => AvatarModel.unscoped(),
280 [ScopeNames.WITH_TAGS]: {
281 include: [ () => TagModel ]
283 [ScopeNames.WITH_FILES]: {
286 model: () => VideoFileModel.unscoped(),
291 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
294 model: () => ScheduleVideoUpdateModel.unscoped(),
307 fields: [ 'createdAt' ]
310 fields: [ 'duration' ]
322 fields: [ 'channelId' ]
325 fields: [ 'id', 'privacy', 'state', 'waitTranscoding' ]
333 export class VideoModel extends Model<VideoModel> {
336 @Default(DataType.UUIDV4)
338 @Column(DataType.UUID)
342 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
348 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
354 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
360 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
361 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
365 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
370 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
376 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
377 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
382 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
383 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
387 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
417 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
418 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
423 commentsEnabled: boolean
427 waitTranscoding: boolean
431 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
442 @Default(Sequelize.NOW)
446 @ForeignKey(() => VideoChannelModel)
450 @BelongsTo(() => VideoChannelModel, {
456 VideoChannel: VideoChannelModel
458 @BelongsToMany(() => TagModel, {
459 foreignKey: 'videoId',
460 through: () => VideoTagModel,
465 @HasMany(() => VideoAbuseModel, {
472 VideoAbuses: VideoAbuseModel[]
474 @HasMany(() => VideoFileModel, {
481 VideoFiles: VideoFileModel[]
483 @HasMany(() => VideoShareModel, {
490 VideoShares: VideoShareModel[]
492 @HasMany(() => AccountVideoRateModel, {
499 AccountVideoRates: AccountVideoRateModel[]
501 @HasMany(() => VideoCommentModel, {
509 VideoComments: VideoCommentModel[]
511 @HasOne(() => ScheduleVideoUpdateModel, {
518 ScheduleVideoUpdate: ScheduleVideoUpdateModel
521 static async sendDelete (instance: VideoModel, options) {
522 if (instance.isOwned()) {
523 if (!instance.VideoChannel) {
524 instance.VideoChannel = await instance.$get('VideoChannel', {
528 include: [ ActorModel ]
531 transaction: options.transaction
532 }) as VideoChannelModel
535 logger.debug('Sending delete of video %s.', instance.url)
537 return sendDeleteVideo(instance, options.transaction)
544 static async removeFilesAndSendDelete (instance: VideoModel) {
545 const tasks: Promise<any>[] = []
547 logger.debug('Removing files of video %s.', instance.url)
549 tasks.push(instance.removeThumbnail())
551 if (instance.isOwned()) {
552 if (!Array.isArray(instance.VideoFiles)) {
553 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
556 tasks.push(instance.removePreview())
558 // Remove physical files and torrents
559 instance.VideoFiles.forEach(file => {
560 tasks.push(instance.removeFile(file))
561 tasks.push(instance.removeTorrent(file))
565 // Do not wait video deletion because we could be in a transaction
568 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
575 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
578 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
579 function getRawQuery (select: string) {
580 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
581 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
582 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
583 'WHERE "Account"."actorId" = ' + actorId
584 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
585 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
586 'WHERE "VideoShare"."actorId" = ' + actorId
588 return `(${queryVideo}) UNION (${queryVideoShare})`
591 const rawQuery = getRawQuery('"Video"."id"')
592 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
598 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
601 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
604 { privacy: VideoPrivacy.PUBLIC },
605 { privacy: VideoPrivacy.UNLISTED }
610 attributes: [ 'id', 'url' ],
611 model: VideoShareModel.unscoped(),
613 // We only want videos shared by this actor
615 [Sequelize.Op.and]: [
618 [Sequelize.Op.not]: null
628 attributes: [ 'id', 'url' ],
629 model: ActorModel.unscoped()
634 model: VideoChannelModel.unscoped(),
638 attributes: [ 'name' ],
639 model: AccountModel.unscoped(),
643 attributes: [ 'id', 'url', 'followersUrl' ],
644 model: ActorModel.unscoped(),
650 attributes: [ 'id', 'url', 'followersUrl' ],
651 model: ActorModel.unscoped(),
661 return Bluebird.all([
662 // FIXME: typing issue
663 VideoModel.findAll(query as any),
664 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
665 ]).then(([ rows, totals ]) => {
666 // totals: totalVideos + totalVideoShares
668 let totalVideoShares = 0
669 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
670 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
672 const total = totalVideos + totalVideoShares
680 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, hideNSFW: boolean, withFiles = false) {
681 const query: IFindOptions<VideoModel> = {
684 order: getSort(sort),
687 model: VideoChannelModel,
700 model: ScheduleVideoUpdateModel,
706 if (withFiles === true) {
708 model: VideoFileModel.unscoped(),
713 if (hideNSFW === true) {
719 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
727 static async listForApi (options: {
733 filter?: VideoFilter,
735 videoChannelId?: number
738 offset: options.start,
739 limit: options.count,
740 order: getSort(options.sort)
743 const serverActor = await getServerActor()
746 ScopeNames.AVAILABLE_FOR_LIST, {
747 actorId: serverActor.id,
748 hideNSFW: options.hideNSFW,
749 filter: options.filter,
750 withFiles: options.withFiles,
751 accountId: options.accountId,
752 videoChannelId: options.videoChannelId
757 return VideoModel.scope(scopes)
758 .findAndCountAll(query)
759 .then(({ rows, count }) => {
767 static async searchAndPopulateAccountAndServer (value: string, start: number, count: number, sort: string, hideNSFW: boolean) {
768 const query: IFindOptions<VideoModel> = {
771 order: getSort(sort),
776 [ Sequelize.Op.iLike ]: '%' + value + '%'
780 preferredUsernameChannel: Sequelize.where(Sequelize.col('VideoChannel->Actor.preferredUsername'), {
781 [ Sequelize.Op.iLike ]: '%' + value + '%'
785 preferredUsernameAccount: Sequelize.where(Sequelize.col('VideoChannel->Account->Actor.preferredUsername'), {
786 [ Sequelize.Op.iLike ]: '%' + value + '%'
790 host: Sequelize.where(Sequelize.col('VideoChannel->Account->Actor->Server.host'), {
791 [ Sequelize.Op.iLike ]: '%' + value + '%'
798 const serverActor = await getServerActor()
801 ScopeNames.AVAILABLE_FOR_LIST, {
802 actorId: serverActor.id,
808 return VideoModel.scope(scopes)
809 .findAndCountAll(query)
810 .then(({ rows, count }) => {
818 static load (id: number) {
819 return VideoModel.findById(id)
822 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
823 const query: IFindOptions<VideoModel> = {
829 if (t !== undefined) query.transaction = t
831 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
834 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
835 const query: IFindOptions<VideoModel> = {
844 if (t !== undefined) query.transaction = t
846 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
849 static loadAndPopulateAccountAndServerAndTags (id: number) {
851 order: [ [ 'Tags', 'name', 'ASC' ] ]
855 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_SCHEDULED_UPDATE ])
856 .findById(id, options)
859 static loadByUUID (uuid: string) {
867 .scope([ ScopeNames.WITH_FILES ])
871 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string, t?: Sequelize.Transaction) {
873 order: [ [ 'Tags', 'name', 'ASC' ] ],
881 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_SCHEDULED_UPDATE ])
885 static async getStats () {
886 const totalLocalVideos = await VideoModel.count({
891 const totalVideos = await VideoModel.count()
893 let totalLocalVideoViews = await VideoModel.sum('views', {
898 // Sequelize could return null...
899 if (!totalLocalVideoViews) totalLocalVideoViews = 0
903 totalLocalVideoViews,
908 private static buildActorWhereWithFilter (filter?: VideoFilter) {
909 if (filter && filter === 'local') {
918 private static getCategoryLabel (id: number) {
919 return VIDEO_CATEGORIES[id] || 'Misc'
922 private static getLicenceLabel (id: number) {
923 return VIDEO_LICENCES[id] || 'Unknown'
926 private static getLanguageLabel (id: string) {
927 return VIDEO_LANGUAGES[id] || 'Unknown'
930 private static getPrivacyLabel (id: number) {
931 return VIDEO_PRIVACIES[id] || 'Unknown'
934 private static getStateLabel (id: number) {
935 return VIDEO_STATES[id] || 'Unknown'
939 if (Array.isArray(this.VideoFiles) === false) return undefined
941 // The original file is the file that have the higher resolution
942 return maxBy(this.VideoFiles, file => file.resolution)
945 getVideoFilename (videoFile: VideoFileModel) {
946 return this.uuid + '-' + videoFile.resolution + videoFile.extname
949 getThumbnailName () {
950 // We always have a copy of the thumbnail
951 const extension = '.jpg'
952 return this.uuid + extension
956 const extension = '.jpg'
957 return this.uuid + extension
960 getTorrentFileName (videoFile: VideoFileModel) {
961 const extension = '.torrent'
962 return this.uuid + '-' + videoFile.resolution + extension
966 return this.remote === false
969 createPreview (videoFile: VideoFileModel) {
970 return generateImageFromVideoFile(
971 this.getVideoFilePath(videoFile),
972 CONFIG.STORAGE.PREVIEWS_DIR,
973 this.getPreviewName(),
978 createThumbnail (videoFile: VideoFileModel) {
979 return generateImageFromVideoFile(
980 this.getVideoFilePath(videoFile),
981 CONFIG.STORAGE.THUMBNAILS_DIR,
982 this.getThumbnailName(),
987 getTorrentFilePath (videoFile: VideoFileModel) {
988 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
991 getVideoFilePath (videoFile: VideoFileModel) {
992 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
995 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
997 // Keep the extname, it's used by the client to stream the file inside a web browser
998 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
999 createdBy: 'PeerTube',
1001 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1002 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1005 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1009 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1011 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1012 logger.info('Creating torrent %s.', filePath)
1014 await writeFilePromise(filePath, torrent)
1016 const parsedTorrent = parseTorrent(torrent)
1017 videoFile.infoHash = parsedTorrent.infoHash
1021 return '/videos/embed/' + this.uuid
1024 getThumbnailPath () {
1025 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1029 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1032 toFormattedJSON (options?: {
1033 additionalAttributes: {
1035 waitTranscoding?: boolean,
1036 scheduledUpdate?: boolean
1039 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1040 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1042 const videoObject: Video = {
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 id: formattedAccount.id,
1077 uuid: formattedAccount.uuid,
1078 name: formattedAccount.name,
1079 displayName: formattedAccount.displayName,
1080 url: formattedAccount.url,
1081 host: formattedAccount.host,
1082 avatar: formattedAccount.avatar
1085 id: formattedVideoChannel.id,
1086 uuid: formattedVideoChannel.uuid,
1087 name: formattedVideoChannel.name,
1088 displayName: formattedVideoChannel.displayName,
1089 url: formattedVideoChannel.url,
1090 host: formattedVideoChannel.host,
1091 avatar: formattedVideoChannel.avatar
1096 if (options.additionalAttributes.state === true) {
1097 videoObject.state = {
1099 label: VideoModel.getStateLabel(this.state)
1103 if (options.additionalAttributes.waitTranscoding === true) {
1104 videoObject.waitTranscoding = this.waitTranscoding
1107 if (options.additionalAttributes.scheduledUpdate === true && this.ScheduleVideoUpdate) {
1108 videoObject.scheduledUpdate = {
1109 updateAt: this.ScheduleVideoUpdate.updateAt,
1110 privacy: this.ScheduleVideoUpdate.privacy || undefined
1118 toFormattedDetailsJSON (): VideoDetails {
1119 const formattedJson = this.toFormattedJSON({
1120 additionalAttributes: {
1121 scheduledUpdate: true
1125 const detailsJson = {
1126 support: this.support,
1127 descriptionPath: this.getDescriptionPath(),
1128 channel: this.VideoChannel.toFormattedJSON(),
1129 account: this.VideoChannel.Account.toFormattedJSON(),
1130 tags: map(this.Tags, 'name'),
1131 commentsEnabled: this.commentsEnabled,
1132 waitTranscoding: this.waitTranscoding,
1135 label: VideoModel.getStateLabel(this.state)
1140 // Format and sort video files
1141 detailsJson.files = this.getFormattedVideoFilesJSON()
1143 return Object.assign(formattedJson, detailsJson)
1146 getFormattedVideoFilesJSON (): VideoFile[] {
1147 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1149 return this.VideoFiles
1151 let resolutionLabel = videoFile.resolution + 'p'
1155 id: videoFile.resolution,
1156 label: resolutionLabel
1158 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1159 size: videoFile.size,
1160 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1161 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1162 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1163 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
1167 if (a.resolution.id < b.resolution.id) return 1
1168 if (a.resolution.id === b.resolution.id) return 0
1173 toActivityPubObject (): VideoTorrentObject {
1174 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1175 if (!this.Tags) this.Tags = []
1177 const tag = this.Tags.map(t => ({
1178 type: 'Hashtag' as 'Hashtag',
1183 if (this.language) {
1185 identifier: this.language,
1186 name: VideoModel.getLanguageLabel(this.language)
1191 if (this.category) {
1193 identifier: this.category + '',
1194 name: VideoModel.getCategoryLabel(this.category)
1201 identifier: this.licence + '',
1202 name: VideoModel.getLicenceLabel(this.licence)
1207 for (const file of this.VideoFiles) {
1210 mimeType: VIDEO_EXT_MIMETYPE[file.extname],
1211 href: this.getVideoFileUrl(file, baseUrlHttp),
1212 width: file.resolution,
1218 mimeType: 'application/x-bittorrent',
1219 href: this.getTorrentUrl(file, baseUrlHttp),
1220 width: file.resolution
1225 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1226 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1227 width: file.resolution
1231 // Add video url too
1234 mimeType: 'text/html',
1235 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1239 type: 'Video' as 'Video',
1242 duration: this.getActivityStreamDuration(),
1249 sensitive: this.nsfw,
1250 waitTranscoding: this.waitTranscoding,
1252 commentsEnabled: this.commentsEnabled,
1253 published: this.publishedAt.toISOString(),
1254 updated: this.updatedAt.toISOString(),
1255 mediaType: 'text/markdown',
1256 content: this.getTruncatedDescription(),
1257 support: this.support,
1260 url: this.getThumbnailUrl(baseUrlHttp),
1261 mediaType: 'image/jpeg',
1262 width: THUMBNAILS_SIZE.width,
1263 height: THUMBNAILS_SIZE.height
1266 likes: getVideoLikesActivityPubUrl(this),
1267 dislikes: getVideoDislikesActivityPubUrl(this),
1268 shares: getVideoSharesActivityPubUrl(this),
1269 comments: getVideoCommentsActivityPubUrl(this),
1273 id: this.VideoChannel.Account.Actor.url
1277 id: this.VideoChannel.Actor.url
1283 getTruncatedDescription () {
1284 if (!this.description) return null
1286 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1287 return peertubeTruncate(this.description, maxLength)
1290 async optimizeOriginalVideofile () {
1291 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1292 const newExtname = '.mp4'
1293 const inputVideoFile = this.getOriginalFile()
1294 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1295 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1297 const transcodeOptions = {
1298 inputPath: videoInputPath,
1299 outputPath: videoOutputPath
1302 // Could be very long!
1303 await transcode(transcodeOptions)
1306 await unlinkPromise(videoInputPath)
1308 // Important to do this before getVideoFilename() to take in account the new file extension
1309 inputVideoFile.set('extname', newExtname)
1311 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1312 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1314 inputVideoFile.set('size', stats.size)
1316 await this.createTorrentAndSetInfoHash(inputVideoFile)
1317 await inputVideoFile.save()
1320 // Auto destruction...
1321 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1327 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1328 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1329 const extname = '.mp4'
1331 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1332 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1334 const newVideoFile = new VideoFileModel({
1340 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1342 const transcodeOptions = {
1343 inputPath: videoInputPath,
1344 outputPath: videoOutputPath,
1349 await transcode(transcodeOptions)
1351 const stats = await statPromise(videoOutputPath)
1353 newVideoFile.set('size', stats.size)
1355 await this.createTorrentAndSetInfoHash(newVideoFile)
1357 await newVideoFile.save()
1359 this.VideoFiles.push(newVideoFile)
1362 async importVideoFile (inputFilePath: string) {
1363 let updatedVideoFile = new VideoFileModel({
1364 resolution: (await getVideoFileResolution(inputFilePath)).videoFileResolution,
1365 extname: extname(inputFilePath),
1366 size: (await statPromise(inputFilePath)).size,
1370 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
1372 if (currentVideoFile) {
1373 // Remove old file and old torrent
1374 await this.removeFile(currentVideoFile)
1375 await this.removeTorrent(currentVideoFile)
1376 // Remove the old video file from the array
1377 this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile)
1379 // Update the database
1380 currentVideoFile.set('extname', updatedVideoFile.extname)
1381 currentVideoFile.set('size', updatedVideoFile.size)
1383 updatedVideoFile = currentVideoFile
1386 const outputPath = this.getVideoFilePath(updatedVideoFile)
1387 await copyFilePromise(inputFilePath, outputPath)
1389 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1391 await updatedVideoFile.save()
1393 this.VideoFiles.push(updatedVideoFile)
1396 getOriginalFileResolution () {
1397 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1399 return getVideoFileResolution(originalFilePath)
1402 getDescriptionPath () {
1403 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1406 removeThumbnail () {
1407 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1408 return unlinkPromise(thumbnailPath)
1412 // Same name than video thumbnail
1413 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1416 removeFile (videoFile: VideoFileModel) {
1417 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1418 return unlinkPromise(filePath)
1421 removeTorrent (videoFile: VideoFileModel) {
1422 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1423 return unlinkPromise(torrentPath)
1426 getActivityStreamDuration () {
1427 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1428 return 'PT' + this.duration + 'S'
1431 private getBaseUrls () {
1435 if (this.isOwned()) {
1436 baseUrlHttp = CONFIG.WEBSERVER.URL
1437 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1439 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1440 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1443 return { baseUrlHttp, baseUrlWs }
1446 private getThumbnailUrl (baseUrlHttp: string) {
1447 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1450 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1451 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1454 private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1455 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1458 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1459 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1462 private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1463 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1466 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1467 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1468 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1469 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1471 const magnetHash = {
1475 infoHash: videoFile.infoHash,
1479 return magnetUtil.encode(magnetHash)