]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/activitypub/videos.ts
Add next branch to CI
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / videos.ts
CommitLineData
7acee6f1 1import * as Bluebird from 'bluebird'
30bc55c8 2import { maxBy, minBy } from 'lodash'
2ccaeeb3 3import * as magnetUtil from 'magnet-uri'
90a8bd30 4import { basename, join } from 'path'
d9a2a031
C
5import { Transaction } from 'sequelize/types'
6import { TrackerModel } from '@server/models/server/tracker'
053aed43 7import { VideoLiveModel } from '@server/models/video/video-live'
a8b1b404 8import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
09209296 9import {
d7a25329
C
10 ActivityHashTagObject,
11 ActivityMagnetUrlObject,
09209296 12 ActivityPlaylistSegmentHashesObject,
30bc55c8
C
13 ActivityPlaylistUrlObject,
14 ActivitypubHttpFetcherPayload,
ca6d3622 15 ActivityTagObject,
09209296 16 ActivityUrlObject,
053aed43 17 ActivityVideoUrlObject
09209296 18} from '../../../shared/index'
d9a2a031 19import { ActivityIconObject, ActivityTrackerUrlObject, VideoObject } from '../../../shared/models/activitypub/objects'
1297eb5d 20import { VideoPrivacy } from '../../../shared/models/videos'
30bc55c8
C
21import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
22import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
23import { buildRemoteVideoBaseUrl, checkUrlsSameHost, getAPId } from '../../helpers/activitypub'
d9a2a031
C
24import {
25 isAPVideoFileUrlMetadataObject,
26 isAPVideoTrackerUrlObject,
27 sanitizeAndCheckVideoTorrentObject
28} from '../../helpers/custom-validators/activitypub/videos'
30bc55c8 29import { isArray } from '../../helpers/custom-validators/misc'
2ccaeeb3 30import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
d7a25329 31import { deleteNonExistingModels, resetSequelizeInstance, retryTransactionWrapper } from '../../helpers/database-utils'
2ccaeeb3 32import { logger } from '../../helpers/logger'
db4b15f2 33import { doJSONRequest } from '../../helpers/requests'
30bc55c8 34import { fetchVideoByUrl, getExtFromMimetype, VideoFetchByUrlType } from '../../helpers/video'
e8bafea3
C
35import {
36 ACTIVITY_PUB,
90a8bd30 37 LAZY_STATIC_PATHS,
e8bafea3
C
38 MIMETYPES,
39 P2P_MEDIA_LOADER_PEER_VERSION,
40 PREVIEWS_SIZE,
41 REMOTE_SCHEME,
7b81edc8 42 THUMBNAILS_SIZE
e8bafea3 43} from '../../initializers/constants'
30bc55c8
C
44import { sequelizeTypescript } from '../../initializers/database'
45import { AccountVideoRateModel } from '../../models/account/account-video-rate'
3fd3ab2d 46import { VideoModel } from '../../models/video/video'
40e87e9e 47import { VideoCaptionModel } from '../../models/video/video-caption'
2ba92871 48import { VideoCommentModel } from '../../models/video/video-comment'
30bc55c8
C
49import { VideoFileModel } from '../../models/video/video-file'
50import { VideoShareModel } from '../../models/video/video-share'
51import { VideoStreamingPlaylistModel } from '../../models/video/video-streaming-playlist'
453e83ea 52import {
f92e7f76 53 MAccountIdActor,
453e83ea
C
54 MChannelAccountLight,
55 MChannelDefault,
56 MChannelId,
d7a25329 57 MStreamingPlaylist,
90a8bd30
C
58 MStreamingPlaylistFilesVideo,
59 MStreamingPlaylistVideo,
453e83ea 60 MVideo,
453e83ea 61 MVideoAccountLight,
f92e7f76 62 MVideoAccountLightBlacklistAllFiles,
453e83ea
C
63 MVideoAP,
64 MVideoAPWithoutCaption,
6302d599 65 MVideoCaption,
453e83ea
C
66 MVideoFile,
67 MVideoFullLight,
7b81edc8
C
68 MVideoId,
69 MVideoImmutable,
90a8bd30
C
70 MVideoThumbnail,
71 MVideoWithHost
26d6bf65
C
72} from '../../types/models'
73import { MThumbnail } from '../../types/models/video/thumbnail'
30bc55c8
C
74import { FilteredModelAttributes } from '../../types/sequelize'
75import { ActorFollowScoreCache } from '../files-cache'
76import { JobQueue } from '../job-queue'
77import { Notifier } from '../notifier'
a5cf76af 78import { PeerTubeSocket } from '../peertube-socket'
30bc55c8 79import { createPlaceholderThumbnail, createVideoMiniatureFromUrl } from '../thumbnail'
1ef65f4c 80import { setVideoTags } from '../video'
30bc55c8 81import { autoBlacklistVideoIfNeeded } from '../video-blacklist'
90a8bd30 82import { generateTorrentFileName } from '../video-paths'
30bc55c8
C
83import { getOrCreateActorAndServerAndModel } from './actor'
84import { crawlCollectionPage } from './crawl'
85import { sendCreateVideo, sendUpdateVideo } from './send'
86import { addVideoShares, shareVideoByServerAndChannel } from './share'
87import { addVideoComments } from './video-comments'
88import { createRates } from './video-rates'
453e83ea 89
d9a2a031 90async function federateVideoIfNeeded (videoArg: MVideoAPWithoutCaption, isNewVideo: boolean, transaction?: Transaction) {
453e83ea 91 const video = videoArg as MVideoAP
2186386c 92
5b77537c
C
93 if (
94 // Check this is not a blacklisted video, or unfederated blacklisted video
95 (video.isBlacklisted() === false || (isNewVideo === false && video.VideoBlacklist.unfederated === false)) &&
96 // Check the video is public/unlisted and published
68e70a74 97 video.hasPrivacyForFederation() && video.hasStateForFederation()
5b77537c 98 ) {
40e87e9e
C
99 // Fetch more attributes that we will need to serialize in AP object
100 if (isArray(video.VideoCaptions) === false) {
101 video.VideoCaptions = await video.$get('VideoCaptions', {
6302d599 102 attributes: [ 'filename', 'language' ],
40e87e9e 103 transaction
e6122097 104 })
40e87e9e
C
105 }
106
2cebd797 107 if (isNewVideo) {
2186386c
C
108 // Now we'll add the video's meta data to our followers
109 await sendCreateVideo(video, transaction)
110 await shareVideoByServerAndChannel(video, transaction)
111 } else {
112 await sendUpdateVideo(video, transaction)
113 }
114 }
115}
892211e8 116
db4b15f2 117async function fetchRemoteVideo (videoUrl: string): Promise<{ statusCode: number, videoObject: VideoObject }> {
4157cdb1
C
118 logger.info('Fetching remote video %s.', videoUrl)
119
db4b15f2 120 const { statusCode, body } = await doJSONRequest<any>(videoUrl, { activityPub: true })
4157cdb1 121
5c6d985f 122 if (sanitizeAndCheckVideoTorrentObject(body) === false || checkUrlsSameHost(body.id, videoUrl) !== true) {
4157cdb1 123 logger.debug('Remote video JSON is not valid.', { body })
db4b15f2 124 return { statusCode, videoObject: undefined }
4157cdb1
C
125 }
126
db4b15f2 127 return { statusCode, videoObject: body }
892211e8
C
128}
129
453e83ea 130async function fetchRemoteVideoDescription (video: MVideoAccountLight) {
50d6de9c 131 const host = video.VideoChannel.Account.Actor.Server.host
96f29c0f 132 const path = video.getDescriptionAPIPath()
db4b15f2 133 const url = REMOTE_SCHEME.HTTP + '://' + host + path
892211e8 134
db4b15f2
C
135 const { body } = await doJSONRequest<any>(url)
136 return body.description || ''
892211e8
C
137}
138
de6310b2 139function getOrCreateVideoChannelFromVideoObject (videoObject: VideoObject) {
0f320037
C
140 const channel = videoObject.attributedTo.find(a => a.type === 'Group')
141 if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
142
5c6d985f
C
143 if (checkUrlsSameHost(channel.id, videoObject.id) !== true) {
144 throw new Error(`Video channel url ${channel.id} does not have the same host than video object id ${videoObject.id}`)
145 }
146
e587e0ec 147 return getOrCreateActorAndServerAndModel(channel.id, 'all')
0f320037
C
148}
149
f6eebcb3 150type SyncParam = {
1297eb5d
C
151 likes: boolean
152 dislikes: boolean
153 shares: boolean
154 comments: boolean
f6eebcb3 155 thumbnail: boolean
04b8c3fb 156 refreshVideo?: boolean
f6eebcb3 157}
de6310b2 158async function syncVideoExternalAttributes (video: MVideo, fetchedVideo: VideoObject, syncParam: SyncParam) {
f6eebcb3 159 logger.info('Adding likes/dislikes/shares/comments of video %s.', video.uuid)
2ccaeeb3 160
f6eebcb3 161 const jobPayloads: ActivitypubHttpFetcherPayload[] = []
2ccaeeb3 162
f6eebcb3 163 if (syncParam.likes === true) {
2ba92871
C
164 const handler = items => createRates(items, video, 'like')
165 const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'like' as 'like', crawlStartDate)
166
167 await crawlCollectionPage<string>(fetchedVideo.likes, handler, cleaner)
ca6d3622 168 .catch(err => logger.error('Cannot add likes of video %s.', video.uuid, { err, rootUrl: fetchedVideo.likes }))
f6eebcb3
C
169 } else {
170 jobPayloads.push({ uri: fetchedVideo.likes, videoId: video.id, type: 'video-likes' as 'video-likes' })
171 }
7acee6f1 172
f6eebcb3 173 if (syncParam.dislikes === true) {
2ba92871
C
174 const handler = items => createRates(items, video, 'dislike')
175 const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'dislike' as 'dislike', crawlStartDate)
176
177 await crawlCollectionPage<string>(fetchedVideo.dislikes, handler, cleaner)
ca6d3622 178 .catch(err => logger.error('Cannot add dislikes of video %s.', video.uuid, { err, rootUrl: fetchedVideo.dislikes }))
f6eebcb3
C
179 } else {
180 jobPayloads.push({ uri: fetchedVideo.dislikes, videoId: video.id, type: 'video-dislikes' as 'video-dislikes' })
181 }
182
183 if (syncParam.shares === true) {
2ba92871
C
184 const handler = items => addVideoShares(items, video)
185 const cleaner = crawlStartDate => VideoShareModel.cleanOldSharesOf(video.id, crawlStartDate)
186
187 await crawlCollectionPage<string>(fetchedVideo.shares, handler, cleaner)
ca6d3622 188 .catch(err => logger.error('Cannot add shares of video %s.', video.uuid, { err, rootUrl: fetchedVideo.shares }))
f6eebcb3
C
189 } else {
190 jobPayloads.push({ uri: fetchedVideo.shares, videoId: video.id, type: 'video-shares' as 'video-shares' })
191 }
7acee6f1 192
f6eebcb3 193 if (syncParam.comments === true) {
6b9c966f 194 const handler = items => addVideoComments(items)
2ba92871
C
195 const cleaner = crawlStartDate => VideoCommentModel.cleanOldCommentsOf(video.id, crawlStartDate)
196
197 await crawlCollectionPage<string>(fetchedVideo.comments, handler, cleaner)
ca6d3622 198 .catch(err => logger.error('Cannot add comments of video %s.', video.uuid, { err, rootUrl: fetchedVideo.comments }))
f6eebcb3 199 } else {
2ba92871 200 jobPayloads.push({ uri: fetchedVideo.comments, videoId: video.id, type: 'video-comments' as 'video-comments' })
f6eebcb3 201 }
7acee6f1 202
a1587156 203 await Bluebird.map(jobPayloads, payload => JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload }))
2ccaeeb3
C
204}
205
943e5193
C
206type GetVideoResult <T> = Promise<{
207 video: T
208 created: boolean
209 autoBlacklisted?: boolean
210}>
211
212type GetVideoParamAll = {
a1587156
C
213 videoObject: { id: string } | string
214 syncParam?: SyncParam
215 fetchType?: 'all'
453e83ea 216 allowRefresh?: boolean
943e5193
C
217}
218
219type GetVideoParamImmutable = {
a1587156
C
220 videoObject: { id: string } | string
221 syncParam?: SyncParam
943e5193
C
222 fetchType: 'only-immutable-attributes'
223 allowRefresh: false
224}
225
226type GetVideoParamOther = {
a1587156
C
227 videoObject: { id: string } | string
228 syncParam?: SyncParam
943e5193
C
229 fetchType?: 'all' | 'only-video'
230 allowRefresh?: boolean
231}
232
233function getOrCreateVideoAndAccountAndChannel (options: GetVideoParamAll): GetVideoResult<MVideoAccountLightBlacklistAllFiles>
234function getOrCreateVideoAndAccountAndChannel (options: GetVideoParamImmutable): GetVideoResult<MVideoImmutable>
235function getOrCreateVideoAndAccountAndChannel (
236 options: GetVideoParamOther
237): GetVideoResult<MVideoAccountLightBlacklistAllFiles | MVideoThumbnail>
238async function getOrCreateVideoAndAccountAndChannel (
239 options: GetVideoParamAll | GetVideoParamImmutable | GetVideoParamOther
240): GetVideoResult<MVideoAccountLightBlacklistAllFiles | MVideoThumbnail | MVideoImmutable> {
4157cdb1
C
241 // Default params
242 const syncParam = options.syncParam || { likes: true, dislikes: true, shares: true, comments: true, thumbnail: true, refreshVideo: false }
243 const fetchType = options.fetchType || 'all'
74577825 244 const allowRefresh = options.allowRefresh !== false
1297eb5d 245
4157cdb1 246 // Get video url
848f499d 247 const videoUrl = getAPId(options.videoObject)
4157cdb1 248 let videoFromDatabase = await fetchVideoByUrl(videoUrl, fetchType)
943e5193 249
4157cdb1 250 if (videoFromDatabase) {
943e5193
C
251 // If allowRefresh is true, we could not call this function using 'only-immutable-attributes' fetch type
252 if (allowRefresh === true && (videoFromDatabase as MVideoThumbnail).isOutdated()) {
74577825 253 const refreshOptions = {
943e5193 254 video: videoFromDatabase as MVideoThumbnail,
74577825
C
255 fetchedType: fetchType,
256 syncParam
257 }
258
a1587156
C
259 if (syncParam.refreshVideo === true) {
260 videoFromDatabase = await refreshVideoIfNeeded(refreshOptions)
261 } else {
262 await JobQueue.Instance.createJobWithPromise({
263 type: 'activitypub-refresher',
264 payload: { type: 'video', url: videoFromDatabase.url }
265 })
266 }
d4defe07 267 }
1297eb5d 268
cef534ed 269 return { video: videoFromDatabase, created: false }
1297eb5d
C
270 }
271
4157cdb1
C
272 const { videoObject: fetchedVideo } = await fetchRemoteVideo(videoUrl)
273 if (!fetchedVideo) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
7acee6f1 274
453e83ea
C
275 const actor = await getOrCreateVideoChannelFromVideoObject(fetchedVideo)
276 const videoChannel = actor.VideoChannel
7acee6f1 277
5fb2e288
C
278 try {
279 const { autoBlacklisted, videoCreated } = await retryTransactionWrapper(createVideo, fetchedVideo, videoChannel, syncParam.thumbnail)
280
281 await syncVideoExternalAttributes(videoCreated, fetchedVideo, syncParam)
7acee6f1 282
5fb2e288
C
283 return { video: videoCreated, created: true, autoBlacklisted }
284 } catch (err) {
285 // Maybe a concurrent getOrCreateVideoAndAccountAndChannel call created this video
286 if (err.name === 'SequelizeUniqueConstraintError') {
287 const fallbackVideo = await fetchVideoByUrl(videoUrl, fetchType)
288 if (fallbackVideo) return { video: fallbackVideo, created: false }
289 }
290
291 throw err
292 }
7acee6f1
C
293}
294
d4defe07 295async function updateVideoFromAP (options: {
a1587156 296 video: MVideoAccountLightBlacklistAllFiles
de6310b2 297 videoObject: VideoObject
a1587156
C
298 account: MAccountIdActor
299 channel: MChannelDefault
1297eb5d 300 overrideTo?: string[]
d4defe07 301}) {
b4055e1c
C
302 const { video, videoObject, account, channel, overrideTo } = options
303
68e70a74 304 logger.debug('Updating remote video "%s".', options.videoObject.uuid, { videoObject: options.videoObject, account, channel })
e8d246d5 305
1297eb5d 306 let videoFieldsSave: any
b4055e1c
C
307 const wasPrivateVideo = video.privacy === VideoPrivacy.PRIVATE
308 const wasUnlistedVideo = video.privacy === VideoPrivacy.UNLISTED
1297eb5d
C
309
310 try {
453e83ea 311 let thumbnailModel: MThumbnail
e8bafea3
C
312
313 try {
a35a2279
C
314 thumbnailModel = await createVideoMiniatureFromUrl({
315 downloadUrl: getThumbnailFromIcons(videoObject).url,
316 video,
317 type: ThumbnailType.MINIATURE
318 })
e8bafea3 319 } catch (err) {
b4055e1c 320 logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err })
e8bafea3
C
321 }
322
453e83ea 323 const videoUpdated = await sequelizeTypescript.transaction(async t => {
e8d246d5 324 const sequelizeOptions = { transaction: t }
2ccaeeb3 325
b4055e1c 326 videoFieldsSave = video.toJSON()
2ccaeeb3 327
92315d97
C
328 // Check we can update the channel: we trust the remote server
329 const oldVideoChannel = video.VideoChannel
330
331 if (!oldVideoChannel.Actor.serverId || !channel.Actor.serverId) {
332 throw new Error('Cannot check old channel/new channel validity because `serverId` is null')
333 }
334
335 if (oldVideoChannel.Actor.serverId !== channel.Actor.serverId) {
336 throw new Error('New channel ' + channel.Actor.url + ' is not on the same server than new channel ' + oldVideoChannel.Actor.url)
f6eebcb3
C
337 }
338
a1587156 339 const to = overrideTo || videoObject.to
b4055e1c
C
340 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, to)
341 video.name = videoData.name
342 video.uuid = videoData.uuid
343 video.url = videoData.url
344 video.category = videoData.category
345 video.licence = videoData.licence
346 video.language = videoData.language
347 video.description = videoData.description
348 video.support = videoData.support
349 video.nsfw = videoData.nsfw
350 video.commentsEnabled = videoData.commentsEnabled
351 video.downloadEnabled = videoData.downloadEnabled
352 video.waitTranscoding = videoData.waitTranscoding
353 video.state = videoData.state
354 video.duration = videoData.duration
355 video.createdAt = videoData.createdAt
356 video.publishedAt = videoData.publishedAt
357 video.originallyPublishedAt = videoData.originallyPublishedAt
358 video.privacy = videoData.privacy
359 video.channelId = videoData.channelId
360 video.views = videoData.views
a5cf76af 361 video.isLive = videoData.isLive
b4055e1c 362
b49f22d8
C
363 // Ensures we update the updated video attribute
364 video.changed('updatedAt', true)
365
453e83ea 366 const videoUpdated = await video.save(sequelizeOptions) as MVideoFullLight
b4055e1c 367
453e83ea 368 if (thumbnailModel) await videoUpdated.addAndSaveThumbnail(thumbnailModel, t)
e8bafea3 369
6872996d 370 if (videoUpdated.getPreview()) {
a8b1b404 371 const previewUrl = getPreviewUrl(getPreviewFromIcons(videoObject), video)
a35a2279
C
372 const previewModel = createPlaceholderThumbnail({
373 fileUrl: previewUrl,
374 video,
375 type: ThumbnailType.PREVIEW,
376 size: PREVIEWS_SIZE
377 })
6872996d
C
378 await videoUpdated.addAndSaveThumbnail(previewModel, t)
379 }
e8bafea3 380
e5565833 381 {
d7a25329 382 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoUpdated, videoObject.url)
e5565833 383 const newVideoFiles = videoFileAttributes.map(a => new VideoFileModel(a))
0032ebe9 384
e5565833 385 // Remove video files that do not exist anymore
d7a25329 386 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoFiles, newVideoFiles, t)
e5565833 387 await Promise.all(destroyTasks)
2ccaeeb3 388
e5565833 389 // Update or add other one
d7a25329 390 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'video', t))
453e83ea 391 videoUpdated.VideoFiles = await Promise.all(upsertTasks)
e5565833 392 }
2ccaeeb3 393
09209296 394 {
453e83ea 395 const streamingPlaylistAttributes = streamingPlaylistActivityUrlToDBAttributes(videoUpdated, videoObject, videoUpdated.VideoFiles)
09209296
C
396 const newStreamingPlaylists = streamingPlaylistAttributes.map(a => new VideoStreamingPlaylistModel(a))
397
d7a25329
C
398 // Remove video playlists that do not exist anymore
399 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoStreamingPlaylists, newStreamingPlaylists, t)
09209296
C
400 await Promise.all(destroyTasks)
401
d7a25329
C
402 let oldStreamingPlaylistFiles: MVideoFile[] = []
403 for (const videoStreamingPlaylist of videoUpdated.VideoStreamingPlaylists) {
404 oldStreamingPlaylistFiles = oldStreamingPlaylistFiles.concat(videoStreamingPlaylist.VideoFiles)
405 }
406
407 videoUpdated.VideoStreamingPlaylists = []
408
409 for (const playlistAttributes of streamingPlaylistAttributes) {
410 const streamingPlaylistModel = await VideoStreamingPlaylistModel.upsert(playlistAttributes, { returning: true, transaction: t })
90a8bd30
C
411 .then(([ streamingPlaylist ]) => streamingPlaylist as MStreamingPlaylistFilesVideo)
412 streamingPlaylistModel.Video = videoUpdated
09209296 413
d7a25329
C
414 const newVideoFiles: MVideoFile[] = videoFileActivityUrlToDBAttributes(streamingPlaylistModel, playlistAttributes.tagAPObject)
415 .map(a => new VideoFileModel(a))
416 const destroyTasks = deleteNonExistingModels(oldStreamingPlaylistFiles, newVideoFiles, t)
417 await Promise.all(destroyTasks)
418
419 // Update or add other one
420 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'streaming-playlist', t))
421 streamingPlaylistModel.VideoFiles = await Promise.all(upsertTasks)
422
423 videoUpdated.VideoStreamingPlaylists.push(streamingPlaylistModel)
424 }
09209296
C
425 }
426
e5565833
C
427 {
428 // Update Tags
d7a25329
C
429 const tags = videoObject.tag
430 .filter(isAPHashTagObject)
431 .map(tag => tag.name)
6c9c3b7b 432 await setVideoTags({ video: videoUpdated, tags, transaction: t })
e5565833 433 }
2ccaeeb3 434
d9a2a031
C
435 // Update trackers
436 {
437 const trackers = getTrackerUrls(videoObject, videoUpdated)
438 await setVideoTrackers({ video: videoUpdated, trackers, transaction: t })
439 }
440
e5565833
C
441 {
442 // Update captions
453e83ea 443 await VideoCaptionModel.deleteAllCaptionsOfRemoteVideo(videoUpdated.id, t)
e5565833 444
b4055e1c 445 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
6302d599
C
446 const caption = new VideoCaptionModel({
447 videoId: videoUpdated.id,
448 filename: VideoCaptionModel.generateCaptionName(c.identifier),
449 language: c.identifier,
450 fileUrl: c.url
451 }) as MVideoCaption
452
453 return VideoCaptionModel.insertOrReplaceLanguage(caption, t)
e5565833 454 })
453e83ea 455 await Promise.all(videoCaptionsPromises)
e5565833 456 }
453e83ea 457
af4ae64f
C
458 {
459 // Create or update existing live
460 if (video.isLive) {
461 const [ videoLive ] = await VideoLiveModel.upsert({
462 saveReplay: videoObject.liveSaveReplay,
bb4ba6d9 463 permanentLive: videoObject.permanentLive,
af4ae64f
C
464 videoId: video.id
465 }, { transaction: t, returning: true })
466
467 videoUpdated.VideoLive = videoLive
468 } else { // Delete existing live if it exists
469 await VideoLiveModel.destroy({
470 where: {
471 videoId: video.id
472 },
473 transaction: t
474 })
475
476 videoUpdated.VideoLive = null
477 }
478 }
479
453e83ea 480 return videoUpdated
1297eb5d
C
481 })
482
5b77537c 483 await autoBlacklistVideoIfNeeded({
453e83ea 484 video: videoUpdated,
6691c522
C
485 user: undefined,
486 isRemote: true,
487 isNew: false,
488 transaction: undefined
489 })
b4055e1c 490
a800dbf3
C
491 // Notify our users?
492 if (wasPrivateVideo || wasUnlistedVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoUpdated)
493
494 if (videoUpdated.isLive) {
495 PeerTubeSocket.Instance.sendVideoLiveNewState(videoUpdated)
496 PeerTubeSocket.Instance.sendVideoViewsUpdate(videoUpdated)
497 }
e8d246d5 498
b4055e1c 499 logger.info('Remote video with uuid %s updated', videoObject.uuid)
453e83ea
C
500
501 return videoUpdated
1297eb5d 502 } catch (err) {
b4055e1c
C
503 if (video !== undefined && videoFieldsSave !== undefined) {
504 resetSequelizeInstance(video, videoFieldsSave)
1297eb5d
C
505 }
506
507 // This is just a debug because we will retry the insert
508 logger.debug('Cannot update the remote video.', { err })
509 throw err
510 }
892211e8 511}
2186386c 512
04b8c3fb 513async function refreshVideoIfNeeded (options: {
a1587156
C
514 video: MVideoThumbnail
515 fetchedType: VideoFetchByUrlType
04b8c3fb 516 syncParam: SyncParam
453e83ea 517}): Promise<MVideoThumbnail> {
04b8c3fb
C
518 if (!options.video.isOutdated()) return options.video
519
520 // We need more attributes if the argument video was fetched with not enough joints
b4055e1c 521 const video = options.fetchedType === 'all'
0283eaac 522 ? options.video as MVideoAccountLightBlacklistAllFiles
b4055e1c 523 : await VideoModel.loadByUrlAndPopulateAccount(options.video.url)
04b8c3fb
C
524
525 try {
db4b15f2
C
526 const { statusCode, videoObject } = await fetchRemoteVideo(video.url)
527 if (statusCode === HttpStatusCode.NOT_FOUND_404) {
04b8c3fb
C
528 logger.info('Cannot refresh remote video %s: video does not exist anymore. Deleting it.', video.url)
529
530 // Video does not exist anymore
531 await video.destroy()
532 return undefined
533 }
534
535 if (videoObject === undefined) {
536 logger.warn('Cannot refresh remote video %s: invalid body.', video.url)
537
538 await video.setAsRefreshed()
539 return video
540 }
541
542 const channelActor = await getOrCreateVideoChannelFromVideoObject(videoObject)
04b8c3fb
C
543
544 const updateOptions = {
545 video,
546 videoObject,
453e83ea 547 account: channelActor.VideoChannel.Account,
04b8c3fb
C
548 channel: channelActor.VideoChannel
549 }
550 await retryTransactionWrapper(updateVideoFromAP, updateOptions)
551 await syncVideoExternalAttributes(video, videoObject, options.syncParam)
552
6b9c966f
C
553 ActorFollowScoreCache.Instance.addGoodServerId(video.VideoChannel.Actor.serverId)
554
04b8c3fb
C
555 return video
556 } catch (err) {
557 logger.warn('Cannot refresh video %s.', options.video.url, { err })
558
6b9c966f
C
559 ActorFollowScoreCache.Instance.addBadServerId(video.VideoChannel.Actor.serverId)
560
04b8c3fb
C
561 // Don't refresh in loop
562 await video.setAsRefreshed()
563 return video
564 }
892211e8 565}
2186386c
C
566
567export {
1297eb5d 568 updateVideoFromAP,
04b8c3fb 569 refreshVideoIfNeeded,
2186386c
C
570 federateVideoIfNeeded,
571 fetchRemoteVideo,
1297eb5d 572 getOrCreateVideoAndAccountAndChannel,
2186386c 573 fetchRemoteVideoDescription,
4157cdb1 574 getOrCreateVideoChannelFromVideoObject
2186386c 575}
c48e82b5
C
576
577// ---------------------------------------------------------------------------
578
d7a25329 579function isAPVideoUrlObject (url: any): url is ActivityVideoUrlObject {
d7a25329 580 const urlMediaType = url.mediaType
30bc55c8
C
581
582 return MIMETYPES.VIDEO.MIMETYPE_EXT[urlMediaType] && urlMediaType.startsWith('video/')
c48e82b5 583}
4157cdb1 584
d9a2a031 585function isAPStreamingPlaylistUrlObject (url: any): url is ActivityPlaylistUrlObject {
d7a25329 586 return url && url.mediaType === 'application/x-mpegURL'
09209296
C
587}
588
589function isAPPlaylistSegmentHashesUrlObject (tag: any): tag is ActivityPlaylistSegmentHashesObject {
d7a25329
C
590 return tag && tag.name === 'sha256' && tag.type === 'Link' && tag.mediaType === 'application/json'
591}
592
593function isAPMagnetUrlObject (url: any): url is ActivityMagnetUrlObject {
594 return url && url.mediaType === 'application/x-bittorrent;x-scheme-handler/magnet'
595}
09209296 596
d7a25329
C
597function isAPHashTagObject (url: any): url is ActivityHashTagObject {
598 return url && url.type === 'Hashtag'
c48e82b5 599}
4157cdb1 600
de6310b2 601async function createVideo (videoObject: VideoObject, channel: MChannelAccountLight, waitThumbnail = false) {
4157cdb1
C
602 logger.debug('Adding remote video %s.', videoObject.id)
603
453e83ea
C
604 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, videoObject.to)
605 const video = VideoModel.build(videoData) as MVideoThumbnail
e8bafea3 606
a35a2279
C
607 const promiseThumbnail = createVideoMiniatureFromUrl({
608 downloadUrl: getThumbnailFromIcons(videoObject).url,
609 video,
610 type: ThumbnailType.MINIATURE
611 }).catch(err => {
612 logger.error('Cannot create miniature from url.', { err })
613 return undefined
614 })
e8bafea3 615
453e83ea 616 let thumbnailModel: MThumbnail
e8bafea3
C
617 if (waitThumbnail === true) {
618 thumbnailModel = await promiseThumbnail
619 }
620
6691c522 621 const { autoBlacklisted, videoCreated } = await sequelizeTypescript.transaction(async t => {
a35a2279
C
622 try {
623 const sequelizeOptions = { transaction: t }
4157cdb1 624
a35a2279
C
625 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
626 videoCreated.VideoChannel = channel
e8bafea3 627
a35a2279 628 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
e8bafea3 629
a35a2279
C
630 const previewUrl = getPreviewUrl(getPreviewFromIcons(videoObject), videoCreated)
631 const previewModel = createPlaceholderThumbnail({
632 fileUrl: previewUrl,
633 video: videoCreated,
634 type: ThumbnailType.PREVIEW,
635 size: PREVIEWS_SIZE
636 })
ca6d3622 637
a35a2279 638 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
4157cdb1 639
a35a2279
C
640 // Process files
641 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject.url)
4157cdb1 642
a35a2279
C
643 const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
644 const videoFiles = await Promise.all(videoFilePromises)
4157cdb1 645
a35a2279
C
646 const streamingPlaylistsAttributes = streamingPlaylistActivityUrlToDBAttributes(videoCreated, videoObject, videoFiles)
647 videoCreated.VideoStreamingPlaylists = []
d7a25329 648
a35a2279 649 for (const playlistAttributes of streamingPlaylistsAttributes) {
90a8bd30
C
650 const playlist = await VideoStreamingPlaylistModel.create(playlistAttributes, { transaction: t }) as MStreamingPlaylistFilesVideo
651 playlist.Video = videoCreated
d7a25329 652
90a8bd30 653 const playlistFiles = videoFileActivityUrlToDBAttributes(playlist, playlistAttributes.tagAPObject)
a35a2279 654 const videoFilePromises = playlistFiles.map(f => VideoFileModel.create(f, { transaction: t }))
90a8bd30 655 playlist.VideoFiles = await Promise.all(videoFilePromises)
d7a25329 656
90a8bd30 657 videoCreated.VideoStreamingPlaylists.push(playlist)
a35a2279 658 }
09209296 659
a35a2279
C
660 // Process tags
661 const tags = videoObject.tag
662 .filter(isAPHashTagObject)
663 .map(t => t.name)
664 await setVideoTags({ video: videoCreated, tags, transaction: t })
665
666 // Process captions
667 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
668 const caption = new VideoCaptionModel({
669 videoId: videoCreated.id,
670 filename: VideoCaptionModel.generateCaptionName(c.identifier),
671 language: c.identifier,
672 fileUrl: c.url
673 }) as MVideoCaption
674
675 return VideoCaptionModel.insertOrReplaceLanguage(caption, t)
676 })
677 await Promise.all(videoCaptionsPromises)
6b9c966f 678
d9a2a031
C
679 // Process trackers
680 {
681 const trackers = getTrackerUrls(videoObject, videoCreated)
682 await setVideoTrackers({ video: videoCreated, trackers, transaction: t })
683 }
684
a35a2279 685 videoCreated.VideoFiles = videoFiles
4157cdb1 686
a35a2279
C
687 if (videoCreated.isLive) {
688 const videoLive = new VideoLiveModel({
689 streamKey: null,
690 saveReplay: videoObject.liveSaveReplay,
691 permanentLive: videoObject.permanentLive,
692 videoId: videoCreated.id
693 })
af4ae64f 694
a35a2279
C
695 videoCreated.VideoLive = await videoLive.save({ transaction: t })
696 }
af4ae64f 697
a35a2279
C
698 const autoBlacklisted = await autoBlacklistVideoIfNeeded({
699 video: videoCreated,
700 user: undefined,
701 isRemote: true,
702 isNew: true,
703 transaction: t
704 })
6691c522 705
a35a2279 706 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
4157cdb1 707
a35a2279
C
708 return { autoBlacklisted, videoCreated }
709 } catch (err) {
710 // FIXME: Use rollback hook when https://github.com/sequelize/sequelize/pull/13038 is released
711 // Remove thumbnail
712 if (thumbnailModel) await thumbnailModel.removeThumbnail()
713
714 throw err
715 }
4157cdb1
C
716 })
717
e8bafea3 718 if (waitThumbnail === false) {
6872996d
C
719 // Error is already caught above
720 // eslint-disable-next-line @typescript-eslint/no-floating-promises
e8bafea3 721 promiseThumbnail.then(thumbnailModel => {
6872996d
C
722 if (!thumbnailModel) return
723
e8bafea3 724 thumbnailModel = videoCreated.id
4157cdb1 725
e8bafea3 726 return thumbnailModel.save()
6872996d 727 })
e8bafea3 728 }
4157cdb1 729
6691c522 730 return { autoBlacklisted, videoCreated }
4157cdb1
C
731}
732
de6310b2 733function videoActivityObjectToDBAttributes (videoChannel: MChannelId, videoObject: VideoObject, to: string[] = []) {
bdd428a6
C
734 const privacy = to.includes(ACTIVITY_PUB.PUBLIC)
735 ? VideoPrivacy.PUBLIC
736 : VideoPrivacy.UNLISTED
4157cdb1 737
bdd428a6 738 const duration = videoObject.duration.replace(/[^\d]+/, '')
58b6fdca 739 const language = videoObject.language?.identifier
4157cdb1 740
58b6fdca
C
741 const category = videoObject.category
742 ? parseInt(videoObject.category.identifier, 10)
743 : undefined
4157cdb1 744
58b6fdca
C
745 const licence = videoObject.licence
746 ? parseInt(videoObject.licence.identifier, 10)
747 : undefined
4157cdb1
C
748
749 const description = videoObject.content || null
750 const support = videoObject.support || null
751
752 return {
753 name: videoObject.name,
754 uuid: videoObject.uuid,
755 url: videoObject.id,
756 category,
757 licence,
758 language,
759 description,
760 support,
761 nsfw: videoObject.sensitive,
762 commentsEnabled: videoObject.commentsEnabled,
7f2cfe3a 763 downloadEnabled: videoObject.downloadEnabled,
4157cdb1 764 waitTranscoding: videoObject.waitTranscoding,
de6310b2 765 isLive: videoObject.isLiveBroadcast,
4157cdb1
C
766 state: videoObject.state,
767 channelId: videoChannel.id,
768 duration: parseInt(duration, 10),
769 createdAt: new Date(videoObject.published),
770 publishedAt: new Date(videoObject.published),
58b6fdca
C
771
772 originallyPublishedAt: videoObject.originallyPublishedAt
773 ? new Date(videoObject.originallyPublishedAt)
774 : null,
775
4157cdb1
C
776 updatedAt: new Date(videoObject.updated),
777 views: videoObject.views,
778 likes: 0,
779 dislikes: 0,
780 remote: true,
781 privacy
782 }
783}
784
d7a25329 785function videoFileActivityUrlToDBAttributes (
90a8bd30 786 videoOrPlaylist: MVideo | MStreamingPlaylistVideo,
d7a25329
C
787 urls: (ActivityTagObject | ActivityUrlObject)[]
788) {
789 const fileUrls = urls.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
4157cdb1 790
d7a25329 791 if (fileUrls.length === 0) return []
4157cdb1 792
3acc5084 793 const attributes: FilteredModelAttributes<VideoFileModel>[] = []
4157cdb1
C
794 for (const fileUrl of fileUrls) {
795 // Fetch associated magnet uri
d7a25329
C
796 const magnet = urls.filter(isAPMagnetUrlObject)
797 .find(u => u.height === fileUrl.height)
4157cdb1
C
798
799 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
800
801 const parsed = magnetUtil.decode(magnet.href)
802 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) {
803 throw new Error('Cannot parse magnet URI ' + magnet.href)
804 }
805
90a8bd30
C
806 const torrentUrl = Array.isArray(parsed.xs)
807 ? parsed.xs[0]
808 : parsed.xs
809
8319d6ae 810 // Fetch associated metadata url, if any
d9a2a031 811 const metadata = urls.filter(isAPVideoFileUrlMetadataObject)
7b81edc8
C
812 .find(u => {
813 return u.height === fileUrl.height &&
814 u.fps === fileUrl.fps &&
815 u.rel.includes(fileUrl.mediaType)
816 })
8319d6ae 817
90a8bd30
C
818 const extname = getExtFromMimetype(MIMETYPES.VIDEO.MIMETYPE_EXT, fileUrl.mediaType)
819 const resolution = fileUrl.height
820 const videoId = (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? null : videoOrPlaylist.id
821 const videoStreamingPlaylistId = (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? videoOrPlaylist.id : null
822
4157cdb1 823 const attribute = {
90a8bd30 824 extname,
4157cdb1 825 infoHash: parsed.infoHash,
90a8bd30 826 resolution,
4157cdb1 827 size: fileUrl.size,
d7a25329 828 fps: fileUrl.fps || -1,
8319d6ae 829 metadataUrl: metadata?.href,
d7a25329 830
90a8bd30
C
831 // Use the name of the remote file because we don't proxify video file requests
832 filename: basename(fileUrl.href),
833 fileUrl: fileUrl.href,
834
835 torrentUrl,
836 // Use our own torrent name since we proxify torrent requests
837 torrentFilename: generateTorrentFileName(videoOrPlaylist, resolution),
838
d7a25329 839 // This is a video file owned by a video or by a streaming playlist
90a8bd30
C
840 videoId,
841 videoStreamingPlaylistId
09209296
C
842 }
843
844 attributes.push(attribute)
845 }
846
847 return attributes
848}
849
de6310b2 850function streamingPlaylistActivityUrlToDBAttributes (video: MVideoId, videoObject: VideoObject, videoFiles: MVideoFile[]) {
09209296
C
851 const playlistUrls = videoObject.url.filter(u => isAPStreamingPlaylistUrlObject(u)) as ActivityPlaylistUrlObject[]
852 if (playlistUrls.length === 0) return []
853
d7a25329 854 const attributes: (FilteredModelAttributes<VideoStreamingPlaylistModel> & { tagAPObject?: ActivityTagObject[] })[] = []
09209296 855 for (const playlistUrlObject of playlistUrls) {
d7a25329
C
856 const segmentsSha256UrlObject = playlistUrlObject.tag.find(isAPPlaylistSegmentHashesUrlObject)
857
858 let files: unknown[] = playlistUrlObject.tag.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
859
860 // FIXME: backward compatibility introduced in v2.1.0
861 if (files.length === 0) files = videoFiles
862
09209296
C
863 if (!segmentsSha256UrlObject) {
864 logger.warn('No segment sha256 URL found in AP playlist object.', { playlistUrl: playlistUrlObject })
865 continue
866 }
867
868 const attribute = {
869 type: VideoStreamingPlaylistType.HLS,
870 playlistUrl: playlistUrlObject.href,
871 segmentsSha256Url: segmentsSha256UrlObject.href,
d7a25329 872 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrlObject.href, files),
594d0c6a 873 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
d7a25329
C
874 videoId: video.id,
875 tagAPObject: playlistUrlObject.tag
09209296
C
876 }
877
4157cdb1
C
878 attributes.push(attribute)
879 }
880
881 return attributes
882}
ca6d3622 883
de6310b2 884function getThumbnailFromIcons (videoObject: VideoObject) {
ca6d3622
C
885 let validIcons = videoObject.icon.filter(i => i.width > THUMBNAILS_SIZE.minWidth)
886 // Fallback if there are not valid icons
887 if (validIcons.length === 0) validIcons = videoObject.icon
888
889 return minBy(validIcons, 'width')
890}
891
de6310b2 892function getPreviewFromIcons (videoObject: VideoObject) {
ca6d3622
C
893 const validIcons = videoObject.icon.filter(i => i.width > PREVIEWS_SIZE.minWidth)
894
ca6d3622
C
895 return maxBy(validIcons, 'width')
896}
a8b1b404 897
90a8bd30 898function getPreviewUrl (previewIcon: ActivityIconObject, video: MVideoWithHost) {
a8b1b404
C
899 return previewIcon
900 ? previewIcon.url
90a8bd30 901 : buildRemoteVideoBaseUrl(video, join(LAZY_STATIC_PATHS.PREVIEWS, video.generatePreviewName()))
a8b1b404 902}
d9a2a031
C
903
904function getTrackerUrls (object: VideoObject, video: MVideoWithHost) {
905 let wsFound = false
906
907 const trackers = object.url.filter(u => isAPVideoTrackerUrlObject(u))
908 .map((u: ActivityTrackerUrlObject) => {
8efc27bf 909 if (isArray(u.rel) && u.rel.includes('websocket')) wsFound = true
d9a2a031
C
910
911 return u.href
912 })
913
914 if (wsFound) return trackers
915
916 return [
917 buildRemoteVideoBaseUrl(video, '/tracker/socket', REMOTE_SCHEME.WS),
918 buildRemoteVideoBaseUrl(video, '/tracker/announce')
919 ]
920}
921
922async function setVideoTrackers (options: {
923 video: MVideo
924 trackers: string[]
925 transaction?: Transaction
926}) {
927 const { video, trackers, transaction } = options
928
929 const trackerInstances = await TrackerModel.findOrCreateTrackers(trackers, transaction)
930
931 await video.$set('Trackers', trackerInstances, { transaction })
932}