1 import * as Bluebird from 'bluebird'
2 import { map, maxBy } from 'lodash'
3 import * as magnetUtil from 'magnet-uri'
4 import * as parseTorrent from 'parse-torrent'
5 import { join } from 'path'
6 import * as Sequelize from 'sequelize'
28 } from 'sequelize-typescript'
29 import { VideoPrivacy, VideoResolution } from '../../../shared'
30 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
31 import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos'
32 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
33 import { activityPubCollection } from '../../helpers/activitypub'
35 createTorrentPromise, peertubeTruncate, renamePromise, statPromise, unlinkPromise,
37 } from '../../helpers/core-utils'
38 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
39 import { isBooleanValid } from '../../helpers/custom-validators/misc'
42 isVideoDescriptionValid,
49 } from '../../helpers/custom-validators/videos'
50 import { generateImageFromVideoFile, getVideoFileResolution, transcode } from '../../helpers/ffmpeg-utils'
51 import { logger } from '../../helpers/logger'
52 import { getServerActor } from '../../helpers/utils'
65 } from '../../initializers'
67 getVideoCommentsActivityPubUrl,
68 getVideoDislikesActivityPubUrl,
69 getVideoLikesActivityPubUrl,
70 getVideoSharesActivityPubUrl
71 } from '../../lib/activitypub'
72 import { sendDeleteVideo } from '../../lib/activitypub/send'
73 import { AccountModel } from '../account/account'
74 import { AccountVideoRateModel } from '../account/account-video-rate'
75 import { ActorModel } from '../activitypub/actor'
76 import { AvatarModel } from '../avatar/avatar'
77 import { ServerModel } from '../server/server'
78 import { getSort, throwIfNotValid } from '../utils'
79 import { TagModel } from './tag'
80 import { VideoAbuseModel } from './video-abuse'
81 import { VideoChannelModel } from './video-channel'
82 import { VideoCommentModel } from './video-comment'
83 import { VideoFileModel } from './video-file'
84 import { VideoShareModel } from './video-share'
85 import { VideoTagModel } from './video-tag'
88 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
89 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
90 WITH_TAGS = 'WITH_TAGS',
91 WITH_FILES = 'WITH_FILES',
92 WITH_SHARES = 'WITH_SHARES',
93 WITH_RATES = 'WITH_RATES',
94 WITH_COMMENTS = 'WITH_COMMENTS'
98 [ScopeNames.AVAILABLE_FOR_LIST]: (options: {
101 filter?: VideoFilter,
104 videoChannelId?: number
106 const accountInclude = {
107 attributes: [ 'id', 'name' ],
108 model: AccountModel.unscoped(),
113 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
114 model: ActorModel.unscoped(),
116 where: VideoModel.buildActorWhereWithFilter(options.filter),
119 attributes: [ 'host' ],
120 model: ServerModel.unscoped(),
124 model: AvatarModel.unscoped(),
132 const videoChannelInclude = {
133 attributes: [ 'name', 'description', 'id' ],
134 model: VideoChannelModel.unscoped(),
139 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
140 model: ActorModel.unscoped(),
144 attributes: [ 'host' ],
145 model: ServerModel.unscoped(),
149 model: AvatarModel.unscoped(),
158 // Force actorId to be a number to avoid SQL injections
159 const actorIdNumber = parseInt(options.actorId.toString(), 10)
160 const query: IFindOptions<VideoModel> = {
163 [Sequelize.Op.notIn]: Sequelize.literal(
164 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
166 [ Sequelize.Op.in ]: Sequelize.literal(
168 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
169 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
170 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
172 'SELECT "video"."id" AS "id" FROM "video" ' +
173 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
174 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
175 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
176 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
177 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + actorIdNumber +
181 privacy: VideoPrivacy.PUBLIC
183 include: [ videoChannelInclude ]
186 if (options.withFiles === true) {
188 model: VideoFileModel.unscoped(),
194 if (options.hideNSFW === true) {
195 query.where['nsfw'] = false
198 if (options.accountId) {
199 accountInclude.where = {
200 id: options.accountId
204 if (options.videoChannelId) {
205 videoChannelInclude.where = {
206 id: options.videoChannelId
212 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
215 model: () => VideoChannelModel.unscoped(),
220 exclude: [ 'privateKey', 'publicKey' ]
222 model: () => ActorModel.unscoped(),
226 attributes: [ 'host' ],
227 model: () => ServerModel.unscoped(),
233 model: () => AccountModel.unscoped(),
237 model: () => ActorModel.unscoped(),
239 exclude: [ 'privateKey', 'publicKey' ]
244 attributes: [ 'host' ],
245 model: () => ServerModel.unscoped(),
249 model: () => AvatarModel.unscoped(),
260 [ScopeNames.WITH_TAGS]: {
261 include: [ () => TagModel ]
263 [ScopeNames.WITH_FILES]: {
266 model: () => VideoFileModel.unscoped(),
271 [ScopeNames.WITH_SHARES]: {
274 model: () => VideoShareModel.unscoped()
278 [ScopeNames.WITH_RATES]: {
281 model: () => AccountVideoRateModel,
284 model: () => AccountModel.unscoped(),
288 attributes: [ 'url' ],
289 model: () => ActorModel.unscoped()
297 [ScopeNames.WITH_COMMENTS]: {
300 model: () => VideoCommentModel.unscoped()
312 fields: [ 'createdAt' ]
315 fields: [ 'duration' ]
327 fields: [ 'channelId' ]
330 fields: [ 'id', 'privacy' ]
338 export class VideoModel extends Model<VideoModel> {
341 @Default(DataType.UUIDV4)
343 @Column(DataType.UUID)
347 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
353 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
359 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
365 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
366 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
370 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
375 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
381 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
382 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
387 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
388 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
392 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
422 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
423 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
428 commentsEnabled: boolean
437 @Default(Sequelize.NOW)
441 @ForeignKey(() => VideoChannelModel)
445 @BelongsTo(() => VideoChannelModel, {
451 VideoChannel: VideoChannelModel
453 @BelongsToMany(() => TagModel, {
454 foreignKey: 'videoId',
455 through: () => VideoTagModel,
460 @HasMany(() => VideoAbuseModel, {
467 VideoAbuses: VideoAbuseModel[]
469 @HasMany(() => VideoFileModel, {
476 VideoFiles: VideoFileModel[]
478 @HasMany(() => VideoShareModel, {
485 VideoShares: VideoShareModel[]
487 @HasMany(() => AccountVideoRateModel, {
494 AccountVideoRates: AccountVideoRateModel[]
496 @HasMany(() => VideoCommentModel, {
504 VideoComments: VideoCommentModel[]
507 static async sendDelete (instance: VideoModel, options) {
508 if (instance.isOwned()) {
509 if (!instance.VideoChannel) {
510 instance.VideoChannel = await instance.$get('VideoChannel', {
514 include: [ ActorModel ]
517 transaction: options.transaction
518 }) as VideoChannelModel
521 logger.debug('Sending delete of video %s.', instance.url)
523 return sendDeleteVideo(instance, options.transaction)
530 static async removeFilesAndSendDelete (instance: VideoModel) {
531 const tasks: Promise<any>[] = []
533 logger.debug('Removing files of video %s.', instance.url)
535 tasks.push(instance.removeThumbnail())
537 if (instance.isOwned()) {
538 if (!Array.isArray(instance.VideoFiles)) {
539 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
542 tasks.push(instance.removePreview())
544 // Remove physical files and torrents
545 instance.VideoFiles.forEach(file => {
546 tasks.push(instance.removeFile(file))
547 tasks.push(instance.removeTorrent(file))
551 // Do not wait video deletion because we could be in a transaction
554 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
561 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
564 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
565 function getRawQuery (select: string) {
566 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
567 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
568 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
569 'WHERE "Account"."actorId" = ' + actorId
570 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
571 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
572 'WHERE "VideoShare"."actorId" = ' + actorId
574 return `(${queryVideo}) UNION (${queryVideoShare})`
577 const rawQuery = getRawQuery('"Video"."id"')
578 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
584 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
587 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
590 { privacy: VideoPrivacy.PUBLIC },
591 { privacy: VideoPrivacy.UNLISTED }
596 attributes: [ 'id', 'url' ],
597 model: VideoShareModel.unscoped(),
600 [Sequelize.Op.and]: [
603 [Sequelize.Op.not]: null
613 attributes: [ 'id', 'url' ],
614 model: ActorModel.unscoped()
619 model: VideoChannelModel.unscoped(),
623 attributes: [ 'name' ],
624 model: AccountModel.unscoped(),
628 attributes: [ 'id', 'url' ],
629 model: ActorModel.unscoped(),
635 attributes: [ 'id', 'url' ],
636 model: ActorModel.unscoped(),
642 attributes: [ 'type' ],
643 model: AccountVideoRateModel,
647 attributes: [ 'id' ],
648 model: AccountModel.unscoped(),
651 attributes: [ 'url' ],
652 model: ActorModel.unscoped(),
655 attributes: [ 'host' ],
666 attributes: [ 'url' ],
667 model: VideoCommentModel,
675 return Bluebird.all([
676 // FIXME: typing issue
677 VideoModel.findAll(query as any),
678 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
679 ]).then(([ rows, totals ]) => {
680 // totals: totalVideos + totalVideoShares
682 let totalVideoShares = 0
683 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
684 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
686 const total = totalVideos + totalVideoShares
694 static listAccountVideosForApi (accountId: number, start: number, count: number, sort: string, hideNSFW: boolean, withFiles = false) {
695 const query: IFindOptions<VideoModel> = {
698 order: getSort(sort),
701 model: VideoChannelModel,
716 if (withFiles === true) {
718 model: VideoFileModel.unscoped(),
723 if (hideNSFW === true) {
729 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
737 static async listForApi (options: {
743 filter?: VideoFilter,
745 videoChannelId?: number
748 offset: options.start,
749 limit: options.count,
750 order: getSort(options.sort)
753 const serverActor = await getServerActor()
756 ScopeNames.AVAILABLE_FOR_LIST, {
757 actorId: serverActor.id,
758 hideNSFW: options.hideNSFW,
759 filter: options.filter,
760 withFiles: options.withFiles,
761 accountId: options.accountId,
762 videoChannelId: options.videoChannelId
767 return VideoModel.scope(scopes)
768 .findAndCountAll(query)
769 .then(({ rows, count }) => {
777 static async searchAndPopulateAccountAndServer (value: string, start: number, count: number, sort: string, hideNSFW: boolean) {
778 const query: IFindOptions<VideoModel> = {
781 order: getSort(sort),
786 [ Sequelize.Op.iLike ]: '%' + value + '%'
790 preferredUsernameChannel: Sequelize.where(Sequelize.col('VideoChannel->Actor.preferredUsername'), {
791 [ Sequelize.Op.iLike ]: '%' + value + '%'
795 preferredUsernameAccount: Sequelize.where(Sequelize.col('VideoChannel->Account->Actor.preferredUsername'), {
796 [ Sequelize.Op.iLike ]: '%' + value + '%'
800 host: Sequelize.where(Sequelize.col('VideoChannel->Account->Actor->Server.host'), {
801 [ Sequelize.Op.iLike ]: '%' + 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 ])
866 .findById(id, options)
869 static loadByUUID (uuid: string) {
877 .scope([ ScopeNames.WITH_FILES ])
881 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
883 order: [ [ 'Tags', 'name', 'ASC' ] ],
890 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
894 static loadAndPopulateAll (id: number) {
896 order: [ [ 'Tags', 'name', 'ASC' ] ],
904 ScopeNames.WITH_RATES,
905 ScopeNames.WITH_SHARES,
906 ScopeNames.WITH_TAGS,
907 ScopeNames.WITH_FILES,
908 ScopeNames.WITH_ACCOUNT_DETAILS,
909 ScopeNames.WITH_COMMENTS
914 static async getStats () {
915 const totalLocalVideos = await VideoModel.count({
920 const totalVideos = await VideoModel.count()
922 let totalLocalVideoViews = await VideoModel.sum('views', {
927 // Sequelize could return null...
928 if (!totalLocalVideoViews) totalLocalVideoViews = 0
932 totalLocalVideoViews,
937 private static buildActorWhereWithFilter (filter?: VideoFilter) {
938 if (filter && filter === 'local') {
947 private static getCategoryLabel (id: number) {
948 let categoryLabel = VIDEO_CATEGORIES[id]
949 if (!categoryLabel) categoryLabel = 'Misc'
954 private static getLicenceLabel (id: number) {
955 let licenceLabel = VIDEO_LICENCES[id]
956 if (!licenceLabel) licenceLabel = 'Unknown'
961 private static getLanguageLabel (id: string) {
962 let languageLabel = VIDEO_LANGUAGES[id]
963 if (!languageLabel) languageLabel = 'Unknown'
968 private static getPrivacyLabel (id: number) {
969 let privacyLabel = VIDEO_PRIVACIES[id]
970 if (!privacyLabel) privacyLabel = 'Unknown'
976 if (Array.isArray(this.VideoFiles) === false) return undefined
978 // The original file is the file that have the higher resolution
979 return maxBy(this.VideoFiles, file => file.resolution)
982 getVideoFilename (videoFile: VideoFileModel) {
983 return this.uuid + '-' + videoFile.resolution + videoFile.extname
986 getThumbnailName () {
987 // We always have a copy of the thumbnail
988 const extension = '.jpg'
989 return this.uuid + extension
993 const extension = '.jpg'
994 return this.uuid + extension
997 getTorrentFileName (videoFile: VideoFileModel) {
998 const extension = '.torrent'
999 return this.uuid + '-' + videoFile.resolution + extension
1003 return this.remote === false
1006 createPreview (videoFile: VideoFileModel) {
1007 return generateImageFromVideoFile(
1008 this.getVideoFilePath(videoFile),
1009 CONFIG.STORAGE.PREVIEWS_DIR,
1010 this.getPreviewName(),
1015 createThumbnail (videoFile: VideoFileModel) {
1016 return generateImageFromVideoFile(
1017 this.getVideoFilePath(videoFile),
1018 CONFIG.STORAGE.THUMBNAILS_DIR,
1019 this.getThumbnailName(),
1024 getVideoFilePath (videoFile: VideoFileModel) {
1025 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1028 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1030 // Keep the extname, it's used by the client to stream the file inside a web browser
1031 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1032 createdBy: 'PeerTube',
1034 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1035 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1038 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1042 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1044 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1045 logger.info('Creating torrent %s.', filePath)
1047 await writeFilePromise(filePath, torrent)
1049 const parsedTorrent = parseTorrent(torrent)
1050 videoFile.infoHash = parsedTorrent.infoHash
1054 return '/videos/embed/' + this.uuid
1057 getThumbnailPath () {
1058 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1062 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1065 toFormattedJSON (): Video {
1066 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1067 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1075 label: VideoModel.getCategoryLabel(this.category)
1079 label: VideoModel.getLicenceLabel(this.licence)
1083 label: VideoModel.getLanguageLabel(this.language)
1087 label: VideoModel.getPrivacyLabel(this.privacy)
1090 description: this.getTruncatedDescription(),
1091 isLocal: this.isOwned(),
1092 duration: this.duration,
1095 dislikes: this.dislikes,
1096 thumbnailPath: this.getThumbnailPath(),
1097 previewPath: this.getPreviewPath(),
1098 embedPath: this.getEmbedPath(),
1099 createdAt: this.createdAt,
1100 updatedAt: this.updatedAt,
1101 publishedAt: this.publishedAt,
1103 id: formattedAccount.id,
1104 uuid: formattedAccount.uuid,
1105 name: formattedAccount.name,
1106 displayName: formattedAccount.displayName,
1107 url: formattedAccount.url,
1108 host: formattedAccount.host,
1109 avatar: formattedAccount.avatar
1112 id: formattedVideoChannel.id,
1113 uuid: formattedVideoChannel.uuid,
1114 name: formattedVideoChannel.name,
1115 displayName: formattedVideoChannel.displayName,
1116 url: formattedVideoChannel.url,
1117 host: formattedVideoChannel.host,
1118 avatar: formattedVideoChannel.avatar
1123 toFormattedDetailsJSON (): VideoDetails {
1124 const formattedJson = this.toFormattedJSON()
1126 const detailsJson = {
1127 support: this.support,
1128 descriptionPath: this.getDescriptionPath(),
1129 channel: this.VideoChannel.toFormattedJSON(),
1130 account: this.VideoChannel.Account.toFormattedJSON(),
1131 tags: map(this.Tags, 'name'),
1132 commentsEnabled: this.commentsEnabled,
1136 // Format and sort video files
1137 detailsJson.files = this.getFormattedVideoFilesJSON()
1139 return Object.assign(formattedJson, detailsJson)
1142 getFormattedVideoFilesJSON (): VideoFile[] {
1143 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1145 return this.VideoFiles
1147 let resolutionLabel = videoFile.resolution + 'p'
1151 id: videoFile.resolution,
1152 label: resolutionLabel
1154 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1155 size: videoFile.size,
1156 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1157 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
1161 if (a.resolution.id < b.resolution.id) return 1
1162 if (a.resolution.id === b.resolution.id) return 0
1167 toActivityPubObject (): VideoTorrentObject {
1168 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1169 if (!this.Tags) this.Tags = []
1171 const tag = this.Tags.map(t => ({
1172 type: 'Hashtag' as 'Hashtag',
1177 if (this.language) {
1179 identifier: this.language,
1180 name: VideoModel.getLanguageLabel(this.language)
1185 if (this.category) {
1187 identifier: this.category + '',
1188 name: VideoModel.getCategoryLabel(this.category)
1195 identifier: this.licence + '',
1196 name: VideoModel.getLicenceLabel(this.licence)
1203 if (Array.isArray(this.AccountVideoRates)) {
1204 const res = this.toRatesActivityPubObjects()
1205 likesObject = res.likesObject
1206 dislikesObject = res.dislikesObject
1210 if (Array.isArray(this.VideoShares)) {
1211 sharesObject = this.toAnnouncesActivityPubObject()
1215 if (Array.isArray(this.VideoComments)) {
1216 commentsObject = this.toCommentsActivityPubObject()
1220 for (const file of this.VideoFiles) {
1223 mimeType: 'video/' + file.extname.replace('.', ''),
1224 href: this.getVideoFileUrl(file, baseUrlHttp),
1225 width: file.resolution,
1231 mimeType: 'application/x-bittorrent',
1232 href: this.getTorrentUrl(file, baseUrlHttp),
1233 width: file.resolution
1238 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1239 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1240 width: file.resolution
1244 // Add video url too
1247 mimeType: 'text/html',
1248 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1252 type: 'Video' as 'Video',
1255 duration: this.getActivityStreamDuration(),
1262 sensitive: this.nsfw,
1263 commentsEnabled: this.commentsEnabled,
1264 published: this.publishedAt.toISOString(),
1265 updated: this.updatedAt.toISOString(),
1266 mediaType: 'text/markdown',
1267 content: this.getTruncatedDescription(),
1268 support: this.support,
1271 url: this.getThumbnailUrl(baseUrlHttp),
1272 mediaType: 'image/jpeg',
1273 width: THUMBNAILS_SIZE.width,
1274 height: THUMBNAILS_SIZE.height
1278 dislikes: dislikesObject,
1279 shares: sharesObject,
1280 comments: commentsObject,
1284 id: this.VideoChannel.Account.Actor.url
1288 id: this.VideoChannel.Actor.url
1294 toAnnouncesActivityPubObject () {
1295 const shares: string[] = []
1297 for (const videoShare of this.VideoShares) {
1298 shares.push(videoShare.url)
1301 return activityPubCollection(getVideoSharesActivityPubUrl(this), shares)
1304 toCommentsActivityPubObject () {
1305 const comments: string[] = []
1307 for (const videoComment of this.VideoComments) {
1308 comments.push(videoComment.url)
1311 return activityPubCollection(getVideoCommentsActivityPubUrl(this), comments)
1314 toRatesActivityPubObjects () {
1315 const likes: string[] = []
1316 const dislikes: string[] = []
1318 for (const rate of this.AccountVideoRates) {
1319 if (rate.type === 'like') {
1320 likes.push(rate.Account.Actor.url)
1321 } else if (rate.type === 'dislike') {
1322 dislikes.push(rate.Account.Actor.url)
1326 const likesObject = activityPubCollection(getVideoLikesActivityPubUrl(this), likes)
1327 const dislikesObject = activityPubCollection(getVideoDislikesActivityPubUrl(this), dislikes)
1329 return { likesObject, dislikesObject }
1332 getTruncatedDescription () {
1333 if (!this.description) return null
1335 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1336 return peertubeTruncate(this.description, maxLength)
1339 async optimizeOriginalVideofile () {
1340 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1341 const newExtname = '.mp4'
1342 const inputVideoFile = this.getOriginalFile()
1343 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1344 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1346 const transcodeOptions = {
1347 inputPath: videoInputPath,
1348 outputPath: videoOutputPath
1351 // Could be very long!
1352 await transcode(transcodeOptions)
1355 await unlinkPromise(videoInputPath)
1357 // Important to do this before getVideoFilename() to take in account the new file extension
1358 inputVideoFile.set('extname', newExtname)
1360 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1361 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1363 inputVideoFile.set('size', stats.size)
1365 await this.createTorrentAndSetInfoHash(inputVideoFile)
1366 await inputVideoFile.save()
1369 // Auto destruction...
1370 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1376 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1377 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1378 const extname = '.mp4'
1380 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1381 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1383 const newVideoFile = new VideoFileModel({
1389 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1391 const transcodeOptions = {
1392 inputPath: videoInputPath,
1393 outputPath: videoOutputPath,
1398 await transcode(transcodeOptions)
1400 const stats = await statPromise(videoOutputPath)
1402 newVideoFile.set('size', stats.size)
1404 await this.createTorrentAndSetInfoHash(newVideoFile)
1406 await newVideoFile.save()
1408 this.VideoFiles.push(newVideoFile)
1411 getOriginalFileResolution () {
1412 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1414 return getVideoFileResolution(originalFilePath)
1417 getDescriptionPath () {
1418 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1421 removeThumbnail () {
1422 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1423 return unlinkPromise(thumbnailPath)
1427 // Same name than video thumbnail
1428 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1431 removeFile (videoFile: VideoFileModel) {
1432 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1433 return unlinkPromise(filePath)
1436 removeTorrent (videoFile: VideoFileModel) {
1437 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1438 return unlinkPromise(torrentPath)
1441 getActivityStreamDuration () {
1442 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1443 return 'PT' + this.duration + 'S'
1446 private getBaseUrls () {
1450 if (this.isOwned()) {
1451 baseUrlHttp = CONFIG.WEBSERVER.URL
1452 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1454 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1455 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1458 return { baseUrlHttp, baseUrlWs }
1461 private getThumbnailUrl (baseUrlHttp: string) {
1462 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1465 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1466 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1469 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1470 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1473 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1474 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1475 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1476 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1478 const magnetHash = {
1482 infoHash: videoFile.infoHash,
1486 return magnetUtil.encode(magnetHash)