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' ],
134 model: VideoChannelModel.unscoped(),
142 // Force actorId to be a number to avoid SQL injections
143 const actorIdNumber = parseInt(options.actorId.toString(), 10)
144 const query: IFindOptions<VideoModel> = {
147 [Sequelize.Op.notIn]: Sequelize.literal(
148 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
150 [ Sequelize.Op.in ]: Sequelize.literal(
152 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
153 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
154 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
156 'SELECT "video"."id" AS "id" FROM "video" ' +
157 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
158 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
159 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
160 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
161 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + actorIdNumber +
165 privacy: VideoPrivacy.PUBLIC
167 include: [ videoChannelInclude ]
170 if (options.withFiles === true) {
172 model: VideoFileModel.unscoped(),
178 if (options.hideNSFW === true) {
179 query.where['nsfw'] = false
182 if (options.accountId) {
183 accountInclude.where = {
184 id: options.accountId
188 if (options.videoChannelId) {
189 videoChannelInclude.where = {
190 id: options.videoChannelId
196 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
199 model: () => VideoChannelModel.unscoped(),
204 exclude: [ 'privateKey', 'publicKey' ]
206 model: () => ActorModel.unscoped(),
210 attributes: [ 'host' ],
211 model: () => ServerModel.unscoped(),
217 model: () => AccountModel.unscoped(),
221 model: () => ActorModel.unscoped(),
223 exclude: [ 'privateKey', 'publicKey' ]
228 attributes: [ 'host' ],
229 model: () => ServerModel.unscoped(),
233 model: () => AvatarModel.unscoped(),
244 [ScopeNames.WITH_TAGS]: {
245 include: [ () => TagModel ]
247 [ScopeNames.WITH_FILES]: {
250 model: () => VideoFileModel.unscoped(),
255 [ScopeNames.WITH_SHARES]: {
258 model: () => VideoShareModel.unscoped()
262 [ScopeNames.WITH_RATES]: {
265 model: () => AccountVideoRateModel,
268 model: () => AccountModel.unscoped(),
272 attributes: [ 'url' ],
273 model: () => ActorModel.unscoped()
281 [ScopeNames.WITH_COMMENTS]: {
284 model: () => VideoCommentModel.unscoped()
296 fields: [ 'createdAt' ]
299 fields: [ 'duration' ]
311 fields: [ 'channelId' ]
314 fields: [ 'id', 'privacy' ]
322 export class VideoModel extends Model<VideoModel> {
325 @Default(DataType.UUIDV4)
327 @Column(DataType.UUID)
331 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
337 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
343 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
349 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
350 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
354 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
359 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
365 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
366 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
371 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
372 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
376 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
406 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
407 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
412 commentsEnabled: boolean
421 @Default(Sequelize.NOW)
425 @ForeignKey(() => VideoChannelModel)
429 @BelongsTo(() => VideoChannelModel, {
435 VideoChannel: VideoChannelModel
437 @BelongsToMany(() => TagModel, {
438 foreignKey: 'videoId',
439 through: () => VideoTagModel,
444 @HasMany(() => VideoAbuseModel, {
451 VideoAbuses: VideoAbuseModel[]
453 @HasMany(() => VideoFileModel, {
460 VideoFiles: VideoFileModel[]
462 @HasMany(() => VideoShareModel, {
469 VideoShares: VideoShareModel[]
471 @HasMany(() => AccountVideoRateModel, {
478 AccountVideoRates: AccountVideoRateModel[]
480 @HasMany(() => VideoCommentModel, {
488 VideoComments: VideoCommentModel[]
491 static async sendDelete (instance: VideoModel, options) {
492 if (instance.isOwned()) {
493 if (!instance.VideoChannel) {
494 instance.VideoChannel = await instance.$get('VideoChannel', {
498 include: [ ActorModel ]
501 transaction: options.transaction
502 }) as VideoChannelModel
505 logger.debug('Sending delete of video %s.', instance.url)
507 return sendDeleteVideo(instance, options.transaction)
514 static async removeFilesAndSendDelete (instance: VideoModel) {
515 const tasks: Promise<any>[] = []
517 logger.debug('Removing files of video %s.', instance.url)
519 tasks.push(instance.removeThumbnail())
521 if (instance.isOwned()) {
522 if (!Array.isArray(instance.VideoFiles)) {
523 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
526 tasks.push(instance.removePreview())
528 // Remove physical files and torrents
529 instance.VideoFiles.forEach(file => {
530 tasks.push(instance.removeFile(file))
531 tasks.push(instance.removeTorrent(file))
535 // Do not wait video deletion because we could be in a transaction
538 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
545 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
548 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
549 function getRawQuery (select: string) {
550 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
551 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
552 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
553 'WHERE "Account"."actorId" = ' + actorId
554 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
555 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
556 'WHERE "VideoShare"."actorId" = ' + actorId
558 return `(${queryVideo}) UNION (${queryVideoShare})`
561 const rawQuery = getRawQuery('"Video"."id"')
562 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
568 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
571 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
574 { privacy: VideoPrivacy.PUBLIC },
575 { privacy: VideoPrivacy.UNLISTED }
580 attributes: [ 'id', 'url' ],
581 model: VideoShareModel.unscoped(),
584 [Sequelize.Op.and]: [
587 [Sequelize.Op.not]: null
597 attributes: [ 'id', 'url' ],
598 model: ActorModel.unscoped()
603 model: VideoChannelModel.unscoped(),
607 attributes: [ 'name' ],
608 model: AccountModel.unscoped(),
612 attributes: [ 'id', 'url' ],
613 model: ActorModel.unscoped(),
619 attributes: [ 'id', 'url' ],
620 model: ActorModel.unscoped(),
626 attributes: [ 'type' ],
627 model: AccountVideoRateModel,
631 attributes: [ 'id' ],
632 model: AccountModel.unscoped(),
635 attributes: [ 'url' ],
636 model: ActorModel.unscoped(),
639 attributes: [ 'host' ],
650 attributes: [ 'url' ],
651 model: VideoCommentModel,
659 return Bluebird.all([
660 // FIXME: typing issue
661 VideoModel.findAll(query as any),
662 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
663 ]).then(([ rows, totals ]) => {
664 // totals: totalVideos + totalVideoShares
666 let totalVideoShares = 0
667 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
668 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
670 const total = totalVideos + totalVideoShares
678 static listAccountVideosForApi (accountId: number, start: number, count: number, sort: string, hideNSFW: boolean, withFiles = false) {
679 const query: IFindOptions<VideoModel> = {
682 order: getSort(sort),
685 model: VideoChannelModel,
700 if (withFiles === true) {
702 model: VideoFileModel.unscoped(),
707 if (hideNSFW === true) {
713 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
721 static async listForApi (options: {
727 filter?: VideoFilter,
729 videoChannelId?: number
732 offset: options.start,
733 limit: options.count,
734 order: getSort(options.sort)
737 const serverActor = await getServerActor()
740 ScopeNames.AVAILABLE_FOR_LIST, {
741 actorId: serverActor.id,
742 hideNSFW: options.hideNSFW,
743 filter: options.filter,
744 withFiles: options.withFiles,
745 accountId: options.accountId,
746 videoChannelId: options.videoChannelId
751 return VideoModel.scope(scopes)
752 .findAndCountAll(query)
753 .then(({ rows, count }) => {
761 static async searchAndPopulateAccountAndServer (value: string, start: number, count: number, sort: string, hideNSFW: boolean) {
762 const query: IFindOptions<VideoModel> = {
765 order: getSort(sort),
770 [ Sequelize.Op.iLike ]: '%' + value + '%'
774 preferredUsername: Sequelize.where(Sequelize.col('preferredUsername'), {
775 [ Sequelize.Op.iLike ]: '%' + value + '%'
779 host: Sequelize.where(Sequelize.col('host'), {
780 [ Sequelize.Op.iLike ]: '%' + value + '%'
787 const serverActor = await getServerActor()
790 ScopeNames.AVAILABLE_FOR_LIST, {
791 actorId: serverActor.id,
797 return VideoModel.scope(scopes)
798 .findAndCountAll(query)
799 .then(({ rows, count }) => {
807 static load (id: number) {
808 return VideoModel.findById(id)
811 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
812 const query: IFindOptions<VideoModel> = {
818 if (t !== undefined) query.transaction = t
820 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
823 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
824 const query: IFindOptions<VideoModel> = {
833 if (t !== undefined) query.transaction = t
835 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
838 static loadAndPopulateAccountAndServerAndTags (id: number) {
840 order: [ [ 'Tags', 'name', 'ASC' ] ]
844 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
845 .findById(id, options)
848 static loadByUUID (uuid: string) {
856 .scope([ ScopeNames.WITH_FILES ])
860 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
862 order: [ [ 'Tags', 'name', 'ASC' ] ],
869 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
873 static loadAndPopulateAll (id: number) {
875 order: [ [ 'Tags', 'name', 'ASC' ] ],
883 ScopeNames.WITH_RATES,
884 ScopeNames.WITH_SHARES,
885 ScopeNames.WITH_TAGS,
886 ScopeNames.WITH_FILES,
887 ScopeNames.WITH_ACCOUNT_DETAILS,
888 ScopeNames.WITH_COMMENTS
893 static async getStats () {
894 const totalLocalVideos = await VideoModel.count({
899 const totalVideos = await VideoModel.count()
901 let totalLocalVideoViews = await VideoModel.sum('views', {
906 // Sequelize could return null...
907 if (!totalLocalVideoViews) totalLocalVideoViews = 0
911 totalLocalVideoViews,
916 private static buildActorWhereWithFilter (filter?: VideoFilter) {
917 if (filter && filter === 'local') {
926 private static getCategoryLabel (id: number) {
927 let categoryLabel = VIDEO_CATEGORIES[id]
928 if (!categoryLabel) categoryLabel = 'Misc'
933 private static getLicenceLabel (id: number) {
934 let licenceLabel = VIDEO_LICENCES[id]
935 if (!licenceLabel) licenceLabel = 'Unknown'
940 private static getLanguageLabel (id: string) {
941 let languageLabel = VIDEO_LANGUAGES[id]
942 if (!languageLabel) languageLabel = 'Unknown'
947 private static getPrivacyLabel (id: number) {
948 let privacyLabel = VIDEO_PRIVACIES[id]
949 if (!privacyLabel) privacyLabel = 'Unknown'
955 if (Array.isArray(this.VideoFiles) === false) return undefined
957 // The original file is the file that have the higher resolution
958 return maxBy(this.VideoFiles, file => file.resolution)
961 getVideoFilename (videoFile: VideoFileModel) {
962 return this.uuid + '-' + videoFile.resolution + videoFile.extname
965 getThumbnailName () {
966 // We always have a copy of the thumbnail
967 const extension = '.jpg'
968 return this.uuid + extension
972 const extension = '.jpg'
973 return this.uuid + extension
976 getTorrentFileName (videoFile: VideoFileModel) {
977 const extension = '.torrent'
978 return this.uuid + '-' + videoFile.resolution + extension
982 return this.remote === false
985 createPreview (videoFile: VideoFileModel) {
986 return generateImageFromVideoFile(
987 this.getVideoFilePath(videoFile),
988 CONFIG.STORAGE.PREVIEWS_DIR,
989 this.getPreviewName(),
994 createThumbnail (videoFile: VideoFileModel) {
995 return generateImageFromVideoFile(
996 this.getVideoFilePath(videoFile),
997 CONFIG.STORAGE.THUMBNAILS_DIR,
998 this.getThumbnailName(),
1003 getVideoFilePath (videoFile: VideoFileModel) {
1004 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1007 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1009 // Keep the extname, it's used by the client to stream the file inside a web browser
1010 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1011 createdBy: 'PeerTube',
1013 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1014 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1017 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1021 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1023 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1024 logger.info('Creating torrent %s.', filePath)
1026 await writeFilePromise(filePath, torrent)
1028 const parsedTorrent = parseTorrent(torrent)
1029 videoFile.infoHash = parsedTorrent.infoHash
1033 return '/videos/embed/' + this.uuid
1036 getThumbnailPath () {
1037 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1041 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1044 toFormattedJSON (): Video {
1045 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1053 label: VideoModel.getCategoryLabel(this.category)
1057 label: VideoModel.getLicenceLabel(this.licence)
1061 label: VideoModel.getLanguageLabel(this.language)
1065 label: VideoModel.getPrivacyLabel(this.privacy)
1068 description: this.getTruncatedDescription(),
1069 isLocal: this.isOwned(),
1070 duration: this.duration,
1073 dislikes: this.dislikes,
1074 thumbnailPath: this.getThumbnailPath(),
1075 previewPath: this.getPreviewPath(),
1076 embedPath: this.getEmbedPath(),
1077 createdAt: this.createdAt,
1078 updatedAt: this.updatedAt,
1079 publishedAt: this.publishedAt,
1081 id: formattedAccount.id,
1082 uuid: formattedAccount.uuid,
1083 name: formattedAccount.name,
1084 displayName: formattedAccount.displayName,
1085 url: formattedAccount.url,
1086 host: formattedAccount.host,
1087 avatar: formattedAccount.avatar
1092 toFormattedDetailsJSON (): VideoDetails {
1093 const formattedJson = this.toFormattedJSON()
1095 const detailsJson = {
1096 support: this.support,
1097 descriptionPath: this.getDescriptionPath(),
1098 channel: this.VideoChannel.toFormattedJSON(),
1099 account: this.VideoChannel.Account.toFormattedJSON(),
1100 tags: map(this.Tags, 'name'),
1101 commentsEnabled: this.commentsEnabled,
1105 // Format and sort video files
1106 detailsJson.files = this.getFormattedVideoFilesJSON()
1108 return Object.assign(formattedJson, detailsJson)
1111 getFormattedVideoFilesJSON (): VideoFile[] {
1112 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1114 return this.VideoFiles
1116 let resolutionLabel = videoFile.resolution + 'p'
1120 id: videoFile.resolution,
1121 label: resolutionLabel
1123 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1124 size: videoFile.size,
1125 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1126 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
1130 if (a.resolution.id < b.resolution.id) return 1
1131 if (a.resolution.id === b.resolution.id) return 0
1136 toActivityPubObject (): VideoTorrentObject {
1137 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1138 if (!this.Tags) this.Tags = []
1140 const tag = this.Tags.map(t => ({
1141 type: 'Hashtag' as 'Hashtag',
1146 if (this.language) {
1148 identifier: this.language,
1149 name: VideoModel.getLanguageLabel(this.language)
1154 if (this.category) {
1156 identifier: this.category + '',
1157 name: VideoModel.getCategoryLabel(this.category)
1164 identifier: this.licence + '',
1165 name: VideoModel.getLicenceLabel(this.licence)
1172 if (Array.isArray(this.AccountVideoRates)) {
1173 const res = this.toRatesActivityPubObjects()
1174 likesObject = res.likesObject
1175 dislikesObject = res.dislikesObject
1179 if (Array.isArray(this.VideoShares)) {
1180 sharesObject = this.toAnnouncesActivityPubObject()
1184 if (Array.isArray(this.VideoComments)) {
1185 commentsObject = this.toCommentsActivityPubObject()
1189 for (const file of this.VideoFiles) {
1192 mimeType: 'video/' + file.extname.replace('.', ''),
1193 href: this.getVideoFileUrl(file, baseUrlHttp),
1194 width: file.resolution,
1200 mimeType: 'application/x-bittorrent',
1201 href: this.getTorrentUrl(file, baseUrlHttp),
1202 width: file.resolution
1207 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1208 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1209 width: file.resolution
1213 // Add video url too
1216 mimeType: 'text/html',
1217 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1221 type: 'Video' as 'Video',
1224 duration: this.getActivityStreamDuration(),
1231 sensitive: this.nsfw,
1232 commentsEnabled: this.commentsEnabled,
1233 published: this.publishedAt.toISOString(),
1234 updated: this.updatedAt.toISOString(),
1235 mediaType: 'text/markdown',
1236 content: this.getTruncatedDescription(),
1237 support: this.support,
1240 url: this.getThumbnailUrl(baseUrlHttp),
1241 mediaType: 'image/jpeg',
1242 width: THUMBNAILS_SIZE.width,
1243 height: THUMBNAILS_SIZE.height
1247 dislikes: dislikesObject,
1248 shares: sharesObject,
1249 comments: commentsObject,
1253 id: this.VideoChannel.Account.Actor.url
1257 id: this.VideoChannel.Actor.url
1263 toAnnouncesActivityPubObject () {
1264 const shares: string[] = []
1266 for (const videoShare of this.VideoShares) {
1267 shares.push(videoShare.url)
1270 return activityPubCollection(getVideoSharesActivityPubUrl(this), shares)
1273 toCommentsActivityPubObject () {
1274 const comments: string[] = []
1276 for (const videoComment of this.VideoComments) {
1277 comments.push(videoComment.url)
1280 return activityPubCollection(getVideoCommentsActivityPubUrl(this), comments)
1283 toRatesActivityPubObjects () {
1284 const likes: string[] = []
1285 const dislikes: string[] = []
1287 for (const rate of this.AccountVideoRates) {
1288 if (rate.type === 'like') {
1289 likes.push(rate.Account.Actor.url)
1290 } else if (rate.type === 'dislike') {
1291 dislikes.push(rate.Account.Actor.url)
1295 const likesObject = activityPubCollection(getVideoLikesActivityPubUrl(this), likes)
1296 const dislikesObject = activityPubCollection(getVideoDislikesActivityPubUrl(this), dislikes)
1298 return { likesObject, dislikesObject }
1301 getTruncatedDescription () {
1302 if (!this.description) return null
1304 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1305 return peertubeTruncate(this.description, maxLength)
1308 async optimizeOriginalVideofile () {
1309 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1310 const newExtname = '.mp4'
1311 const inputVideoFile = this.getOriginalFile()
1312 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1313 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1315 const transcodeOptions = {
1316 inputPath: videoInputPath,
1317 outputPath: videoOutputPath
1320 // Could be very long!
1321 await transcode(transcodeOptions)
1324 await unlinkPromise(videoInputPath)
1326 // Important to do this before getVideoFilename() to take in account the new file extension
1327 inputVideoFile.set('extname', newExtname)
1329 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1330 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1332 inputVideoFile.set('size', stats.size)
1334 await this.createTorrentAndSetInfoHash(inputVideoFile)
1335 await inputVideoFile.save()
1338 // Auto destruction...
1339 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1345 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1346 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1347 const extname = '.mp4'
1349 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1350 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1352 const newVideoFile = new VideoFileModel({
1358 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1360 const transcodeOptions = {
1361 inputPath: videoInputPath,
1362 outputPath: videoOutputPath,
1367 await transcode(transcodeOptions)
1369 const stats = await statPromise(videoOutputPath)
1371 newVideoFile.set('size', stats.size)
1373 await this.createTorrentAndSetInfoHash(newVideoFile)
1375 await newVideoFile.save()
1377 this.VideoFiles.push(newVideoFile)
1380 getOriginalFileResolution () {
1381 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1383 return getVideoFileResolution(originalFilePath)
1386 getDescriptionPath () {
1387 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1390 removeThumbnail () {
1391 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1392 return unlinkPromise(thumbnailPath)
1396 // Same name than video thumbnail
1397 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1400 removeFile (videoFile: VideoFileModel) {
1401 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1402 return unlinkPromise(filePath)
1405 removeTorrent (videoFile: VideoFileModel) {
1406 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1407 return unlinkPromise(torrentPath)
1410 getActivityStreamDuration () {
1411 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1412 return 'PT' + this.duration + 'S'
1415 private getBaseUrls () {
1419 if (this.isOwned()) {
1420 baseUrlHttp = CONFIG.WEBSERVER.URL
1421 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1423 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1424 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1427 return { baseUrlHttp, baseUrlWs }
1430 private getThumbnailUrl (baseUrlHttp: string) {
1431 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1434 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1435 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1438 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1439 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1442 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1443 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1444 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1445 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1447 const magnetHash = {
1451 infoHash: videoFile.infoHash,
1455 return magnetUtil.encode(magnetHash)