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]: (actorId: number, hideNSFW: boolean, filter?: VideoFilter, withFiles?: boolean) => {
99 const query: IFindOptions<VideoModel> = {
102 [Sequelize.Op.notIn]: Sequelize.literal(
103 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
105 [ Sequelize.Op.in ]: Sequelize.literal(
107 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
108 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
109 'WHERE "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
111 'SELECT "video"."id" AS "id" FROM "video" ' +
112 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
113 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
114 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
115 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
116 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
120 privacy: VideoPrivacy.PUBLIC
124 attributes: [ 'name', 'description' ],
125 model: VideoChannelModel.unscoped(),
129 attributes: [ 'name' ],
130 model: AccountModel.unscoped(),
134 attributes: [ 'preferredUsername', 'url', 'serverId', 'avatarId' ],
135 model: ActorModel.unscoped(),
137 where: VideoModel.buildActorWhereWithFilter(filter),
140 attributes: [ 'host' ],
141 model: ServerModel.unscoped(),
145 model: AvatarModel.unscoped(),
157 if (withFiles === true) {
159 model: VideoFileModel.unscoped(),
165 if (hideNSFW === true) {
166 query.where['nsfw'] = false
171 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
174 model: () => VideoChannelModel.unscoped(),
179 exclude: [ 'privateKey', 'publicKey' ]
181 model: () => ActorModel.unscoped(),
185 attributes: [ 'host' ],
186 model: () => ServerModel.unscoped(),
192 model: () => AccountModel.unscoped(),
196 model: () => ActorModel.unscoped(),
198 exclude: [ 'privateKey', 'publicKey' ]
203 attributes: [ 'host' ],
204 model: () => ServerModel.unscoped(),
208 model: () => AvatarModel.unscoped(),
219 [ScopeNames.WITH_TAGS]: {
220 include: [ () => TagModel ]
222 [ScopeNames.WITH_FILES]: {
225 model: () => VideoFileModel.unscoped(),
230 [ScopeNames.WITH_SHARES]: {
233 model: () => VideoShareModel.unscoped()
237 [ScopeNames.WITH_RATES]: {
240 model: () => AccountVideoRateModel,
243 model: () => AccountModel.unscoped(),
247 attributes: [ 'url' ],
248 model: () => ActorModel.unscoped()
256 [ScopeNames.WITH_COMMENTS]: {
259 model: () => VideoCommentModel.unscoped()
271 fields: [ 'createdAt' ]
274 fields: [ 'duration' ]
286 fields: [ 'channelId' ]
289 fields: [ 'id', 'privacy' ]
297 export class VideoModel extends Model<VideoModel> {
300 @Default(DataType.UUIDV4)
302 @Column(DataType.UUID)
306 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
312 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
318 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
324 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
329 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
334 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
340 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
341 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
346 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
347 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
351 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
381 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
382 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
387 commentsEnabled: boolean
396 @Default(Sequelize.NOW)
400 @ForeignKey(() => VideoChannelModel)
404 @BelongsTo(() => VideoChannelModel, {
410 VideoChannel: VideoChannelModel
412 @BelongsToMany(() => TagModel, {
413 foreignKey: 'videoId',
414 through: () => VideoTagModel,
419 @HasMany(() => VideoAbuseModel, {
426 VideoAbuses: VideoAbuseModel[]
428 @HasMany(() => VideoFileModel, {
435 VideoFiles: VideoFileModel[]
437 @HasMany(() => VideoShareModel, {
444 VideoShares: VideoShareModel[]
446 @HasMany(() => AccountVideoRateModel, {
453 AccountVideoRates: AccountVideoRateModel[]
455 @HasMany(() => VideoCommentModel, {
463 VideoComments: VideoCommentModel[]
466 static async sendDelete (instance: VideoModel, options) {
467 if (instance.isOwned()) {
468 if (!instance.VideoChannel) {
469 instance.VideoChannel = await instance.$get('VideoChannel', {
473 include: [ ActorModel ]
476 transaction: options.transaction
477 }) as VideoChannelModel
480 logger.debug('Sending delete of video %s.', instance.url)
482 return sendDeleteVideo(instance, options.transaction)
489 static async removeFilesAndSendDelete (instance: VideoModel) {
490 const tasks: Promise<any>[] = []
492 tasks.push(instance.removeThumbnail())
494 if (instance.isOwned()) {
495 if (!Array.isArray(instance.VideoFiles)) {
496 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
499 tasks.push(instance.removePreview())
501 // Remove physical files and torrents
502 instance.VideoFiles.forEach(file => {
503 tasks.push(instance.removeFile(file))
504 tasks.push(instance.removeTorrent(file))
508 return Promise.all(tasks)
510 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
515 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
518 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
519 function getRawQuery (select: string) {
520 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
521 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
522 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
523 'WHERE "Account"."actorId" = ' + actorId
524 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
525 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
526 'WHERE "VideoShare"."actorId" = ' + actorId
528 return `(${queryVideo}) UNION (${queryVideoShare})`
531 const rawQuery = getRawQuery('"Video"."id"')
532 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
538 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
541 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
544 { privacy: VideoPrivacy.PUBLIC },
545 { privacy: VideoPrivacy.UNLISTED }
550 attributes: [ 'id', 'url' ],
551 model: VideoShareModel.unscoped(),
554 [Sequelize.Op.and]: [
557 [Sequelize.Op.not]: null
567 attributes: [ 'id', 'url' ],
568 model: ActorModel.unscoped()
573 model: VideoChannelModel.unscoped(),
577 attributes: [ 'name' ],
578 model: AccountModel.unscoped(),
582 attributes: [ 'id', 'url' ],
583 model: ActorModel.unscoped(),
589 attributes: [ 'id', 'url' ],
590 model: ActorModel.unscoped(),
596 attributes: [ 'type' ],
597 model: AccountVideoRateModel,
601 attributes: [ 'id' ],
602 model: AccountModel.unscoped(),
605 attributes: [ 'url' ],
606 model: ActorModel.unscoped(),
609 attributes: [ 'host' ],
620 attributes: [ 'url' ],
621 model: VideoCommentModel,
629 return Bluebird.all([
630 // FIXME: typing issue
631 VideoModel.findAll(query as any),
632 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
633 ]).then(([ rows, totals ]) => {
634 // totals: totalVideos + totalVideoShares
636 let totalVideoShares = 0
637 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
638 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
640 const total = totalVideos + totalVideoShares
648 static listAccountVideosForApi (accountId: number, start: number, count: number, sort: string, hideNSFW: boolean, withFiles = false) {
649 const query: IFindOptions<VideoModel> = {
652 order: getSort(sort),
655 model: VideoChannelModel,
670 if (withFiles === true) {
672 model: VideoFileModel.unscoped(),
677 if (hideNSFW === true) {
683 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
691 static async listForApi (start: number, count: number, sort: string, hideNSFW: boolean, filter?: VideoFilter, withFiles = false) {
698 const serverActor = await getServerActor()
699 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id, hideNSFW, filter, withFiles ] })
700 .findAndCountAll(query)
701 .then(({ rows, count }) => {
709 static async searchAndPopulateAccountAndServer (value: string, start: number, count: number, sort: string, hideNSFW: boolean) {
710 const query: IFindOptions<VideoModel> = {
713 order: getSort(sort),
718 [ Sequelize.Op.iLike ]: '%' + value + '%'
722 preferredUsername: Sequelize.where(Sequelize.col('preferredUsername'), {
723 [ Sequelize.Op.iLike ]: '%' + value + '%'
727 host: Sequelize.where(Sequelize.col('host'), {
728 [ Sequelize.Op.iLike ]: '%' + value + '%'
735 const serverActor = await getServerActor()
737 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id, hideNSFW ] })
738 .findAndCountAll(query)
739 .then(({ rows, count }) => {
747 static load (id: number) {
748 return VideoModel.findById(id)
751 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
752 const query: IFindOptions<VideoModel> = {
758 if (t !== undefined) query.transaction = t
760 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
763 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
764 const query: IFindOptions<VideoModel> = {
773 if (t !== undefined) query.transaction = t
775 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
778 static loadAndPopulateAccountAndServerAndTags (id: number) {
780 order: [ [ 'Tags', 'name', 'ASC' ] ]
784 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
785 .findById(id, options)
788 static loadByUUID (uuid: string) {
796 .scope([ ScopeNames.WITH_FILES ])
800 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
802 order: [ [ 'Tags', 'name', 'ASC' ] ],
809 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
813 static loadAndPopulateAll (id: number) {
815 order: [ [ 'Tags', 'name', 'ASC' ] ],
823 ScopeNames.WITH_RATES,
824 ScopeNames.WITH_SHARES,
825 ScopeNames.WITH_TAGS,
826 ScopeNames.WITH_FILES,
827 ScopeNames.WITH_ACCOUNT_DETAILS,
828 ScopeNames.WITH_COMMENTS
833 static async getStats () {
834 const totalLocalVideos = await VideoModel.count({
839 const totalVideos = await VideoModel.count()
841 let totalLocalVideoViews = await VideoModel.sum('views', {
846 // Sequelize could return null...
847 if (!totalLocalVideoViews) totalLocalVideoViews = 0
851 totalLocalVideoViews,
856 private static buildActorWhereWithFilter (filter?: VideoFilter) {
857 if (filter && filter === 'local') {
866 private static getCategoryLabel (id: number) {
867 let categoryLabel = VIDEO_CATEGORIES[id]
868 if (!categoryLabel) categoryLabel = 'Misc'
873 private static getLicenceLabel (id: number) {
874 let licenceLabel = VIDEO_LICENCES[id]
875 if (!licenceLabel) licenceLabel = 'Unknown'
880 private static getLanguageLabel (id: number) {
881 let languageLabel = VIDEO_LANGUAGES[id]
882 if (!languageLabel) languageLabel = 'Unknown'
887 private static getPrivacyLabel (id: number) {
888 let privacyLabel = VIDEO_PRIVACIES[id]
889 if (!privacyLabel) privacyLabel = 'Unknown'
895 if (Array.isArray(this.VideoFiles) === false) return undefined
897 // The original file is the file that have the higher resolution
898 return maxBy(this.VideoFiles, file => file.resolution)
901 getVideoFilename (videoFile: VideoFileModel) {
902 return this.uuid + '-' + videoFile.resolution + videoFile.extname
905 getThumbnailName () {
906 // We always have a copy of the thumbnail
907 const extension = '.jpg'
908 return this.uuid + extension
912 const extension = '.jpg'
913 return this.uuid + extension
916 getTorrentFileName (videoFile: VideoFileModel) {
917 const extension = '.torrent'
918 return this.uuid + '-' + videoFile.resolution + extension
922 return this.remote === false
925 createPreview (videoFile: VideoFileModel) {
926 return generateImageFromVideoFile(
927 this.getVideoFilePath(videoFile),
928 CONFIG.STORAGE.PREVIEWS_DIR,
929 this.getPreviewName(),
934 createThumbnail (videoFile: VideoFileModel) {
935 return generateImageFromVideoFile(
936 this.getVideoFilePath(videoFile),
937 CONFIG.STORAGE.THUMBNAILS_DIR,
938 this.getThumbnailName(),
943 getVideoFilePath (videoFile: VideoFileModel) {
944 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
947 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
949 // Keep the extname, it's used by the client to stream the file inside a web browser
950 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
951 createdBy: 'PeerTube',
953 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
954 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
957 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
961 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
963 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
964 logger.info('Creating torrent %s.', filePath)
966 await writeFilePromise(filePath, torrent)
968 const parsedTorrent = parseTorrent(torrent)
969 videoFile.infoHash = parsedTorrent.infoHash
973 return '/videos/embed/' + this.uuid
976 getThumbnailPath () {
977 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
981 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
984 toFormattedJSON (): Video {
985 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
993 label: VideoModel.getCategoryLabel(this.category)
997 label: VideoModel.getLicenceLabel(this.licence)
1001 label: VideoModel.getLanguageLabel(this.language)
1005 label: VideoModel.getPrivacyLabel(this.privacy)
1008 description: this.getTruncatedDescription(),
1009 isLocal: this.isOwned(),
1010 duration: this.duration,
1013 dislikes: this.dislikes,
1014 thumbnailPath: this.getThumbnailPath(),
1015 previewPath: this.getPreviewPath(),
1016 embedPath: this.getEmbedPath(),
1017 createdAt: this.createdAt,
1018 updatedAt: this.updatedAt,
1019 publishedAt: this.publishedAt,
1021 name: formattedAccount.name,
1022 displayName: formattedAccount.displayName,
1023 url: formattedAccount.url,
1024 host: formattedAccount.host,
1025 avatar: formattedAccount.avatar
1030 toFormattedDetailsJSON (): VideoDetails {
1031 const formattedJson = this.toFormattedJSON()
1033 const detailsJson = {
1034 support: this.support,
1035 descriptionPath: this.getDescriptionPath(),
1036 channel: this.VideoChannel.toFormattedJSON(),
1037 account: this.VideoChannel.Account.toFormattedJSON(),
1038 tags: map(this.Tags, 'name'),
1039 commentsEnabled: this.commentsEnabled,
1043 // Format and sort video files
1044 detailsJson.files = this.getFormattedVideoFilesJSON()
1046 return Object.assign(formattedJson, detailsJson)
1049 getFormattedVideoFilesJSON (): VideoFile[] {
1050 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1052 return this.VideoFiles
1054 let resolutionLabel = videoFile.resolution + 'p'
1058 id: videoFile.resolution,
1059 label: resolutionLabel
1061 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1062 size: videoFile.size,
1063 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1064 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
1068 if (a.resolution.id < b.resolution.id) return 1
1069 if (a.resolution.id === b.resolution.id) return 0
1074 toActivityPubObject (): VideoTorrentObject {
1075 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1076 if (!this.Tags) this.Tags = []
1078 const tag = this.Tags.map(t => ({
1079 type: 'Hashtag' as 'Hashtag',
1084 if (this.language) {
1086 identifier: this.language + '',
1087 name: VideoModel.getLanguageLabel(this.language)
1092 if (this.category) {
1094 identifier: this.category + '',
1095 name: VideoModel.getCategoryLabel(this.category)
1102 identifier: this.licence + '',
1103 name: VideoModel.getLicenceLabel(this.licence)
1110 if (Array.isArray(this.AccountVideoRates)) {
1111 const res = this.toRatesActivityPubObjects()
1112 likesObject = res.likesObject
1113 dislikesObject = res.dislikesObject
1117 if (Array.isArray(this.VideoShares)) {
1118 sharesObject = this.toAnnouncesActivityPubObject()
1122 if (Array.isArray(this.VideoComments)) {
1123 commentsObject = this.toCommentsActivityPubObject()
1127 for (const file of this.VideoFiles) {
1130 mimeType: 'video/' + file.extname.replace('.', ''),
1131 href: this.getVideoFileUrl(file, baseUrlHttp),
1132 width: file.resolution,
1138 mimeType: 'application/x-bittorrent',
1139 href: this.getTorrentUrl(file, baseUrlHttp),
1140 width: file.resolution
1145 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1146 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1147 width: file.resolution
1151 // Add video url too
1154 mimeType: 'text/html',
1155 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1159 type: 'Video' as 'Video',
1162 duration: this.getActivityStreamDuration(),
1169 sensitive: this.nsfw,
1170 commentsEnabled: this.commentsEnabled,
1171 published: this.publishedAt.toISOString(),
1172 updated: this.updatedAt.toISOString(),
1173 mediaType: 'text/markdown',
1174 content: this.getTruncatedDescription(),
1175 support: this.support,
1178 url: this.getThumbnailUrl(baseUrlHttp),
1179 mediaType: 'image/jpeg',
1180 width: THUMBNAILS_SIZE.width,
1181 height: THUMBNAILS_SIZE.height
1185 dislikes: dislikesObject,
1186 shares: sharesObject,
1187 comments: commentsObject,
1191 id: this.VideoChannel.Account.Actor.url
1195 id: this.VideoChannel.Actor.url
1201 toAnnouncesActivityPubObject () {
1202 const shares: string[] = []
1204 for (const videoShare of this.VideoShares) {
1205 shares.push(videoShare.url)
1208 return activityPubCollection(getVideoSharesActivityPubUrl(this), shares)
1211 toCommentsActivityPubObject () {
1212 const comments: string[] = []
1214 for (const videoComment of this.VideoComments) {
1215 comments.push(videoComment.url)
1218 return activityPubCollection(getVideoCommentsActivityPubUrl(this), comments)
1221 toRatesActivityPubObjects () {
1222 const likes: string[] = []
1223 const dislikes: string[] = []
1225 for (const rate of this.AccountVideoRates) {
1226 if (rate.type === 'like') {
1227 likes.push(rate.Account.Actor.url)
1228 } else if (rate.type === 'dislike') {
1229 dislikes.push(rate.Account.Actor.url)
1233 const likesObject = activityPubCollection(getVideoLikesActivityPubUrl(this), likes)
1234 const dislikesObject = activityPubCollection(getVideoDislikesActivityPubUrl(this), dislikes)
1236 return { likesObject, dislikesObject }
1239 getTruncatedDescription () {
1240 if (!this.description) return null
1242 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1243 return peertubeTruncate(this.description, maxLength)
1246 async optimizeOriginalVideofile () {
1247 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1248 const newExtname = '.mp4'
1249 const inputVideoFile = this.getOriginalFile()
1250 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1251 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1253 const transcodeOptions = {
1254 inputPath: videoInputPath,
1255 outputPath: videoOutputPath
1258 // Could be very long!
1259 await transcode(transcodeOptions)
1262 await unlinkPromise(videoInputPath)
1264 // Important to do this before getVideoFilename() to take in account the new file extension
1265 inputVideoFile.set('extname', newExtname)
1267 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1268 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1270 inputVideoFile.set('size', stats.size)
1272 await this.createTorrentAndSetInfoHash(inputVideoFile)
1273 await inputVideoFile.save()
1276 // Auto destruction...
1277 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1283 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1284 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1285 const extname = '.mp4'
1287 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1288 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1290 const newVideoFile = new VideoFileModel({
1296 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1298 const transcodeOptions = {
1299 inputPath: videoInputPath,
1300 outputPath: videoOutputPath,
1305 await transcode(transcodeOptions)
1307 const stats = await statPromise(videoOutputPath)
1309 newVideoFile.set('size', stats.size)
1311 await this.createTorrentAndSetInfoHash(newVideoFile)
1313 await newVideoFile.save()
1315 this.VideoFiles.push(newVideoFile)
1318 getOriginalFileResolution () {
1319 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1321 return getVideoFileResolution(originalFilePath)
1324 getDescriptionPath () {
1325 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1328 removeThumbnail () {
1329 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1330 return unlinkPromise(thumbnailPath)
1334 // Same name than video thumbnail
1335 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1338 removeFile (videoFile: VideoFileModel) {
1339 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1340 return unlinkPromise(filePath)
1343 removeTorrent (videoFile: VideoFileModel) {
1344 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1345 return unlinkPromise(torrentPath)
1348 getActivityStreamDuration () {
1349 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1350 return 'PT' + this.duration + 'S'
1353 private getBaseUrls () {
1357 if (this.isOwned()) {
1358 baseUrlHttp = CONFIG.WEBSERVER.URL
1359 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1361 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1362 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1365 return { baseUrlHttp, baseUrlWs }
1368 private getThumbnailUrl (baseUrlHttp: string) {
1369 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1372 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1373 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1376 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1377 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1380 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1381 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1382 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1383 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1385 const magnetHash = {
1389 infoHash: videoFile.infoHash,
1393 return magnetUtil.encode(magnetHash)