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