]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/activitypub/videos.ts
Update data in DB when regenerate thumbnails
[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 5import { Transaction } from 'sequelize/types'
a0eeb45f 6import { ActorImageModel } from '@server/models/account/actor-image'
d9a2a031 7import { TrackerModel } from '@server/models/server/tracker'
053aed43 8import { VideoLiveModel } from '@server/models/video/video-live'
a8b1b404 9import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
09209296 10import {
d7a25329
C
11 ActivityHashTagObject,
12 ActivityMagnetUrlObject,
09209296 13 ActivityPlaylistSegmentHashesObject,
30bc55c8
C
14 ActivityPlaylistUrlObject,
15 ActivitypubHttpFetcherPayload,
ca6d3622 16 ActivityTagObject,
09209296 17 ActivityUrlObject,
053aed43 18 ActivityVideoUrlObject
09209296 19} from '../../../shared/index'
d9a2a031 20import { ActivityIconObject, ActivityTrackerUrlObject, VideoObject } from '../../../shared/models/activitypub/objects'
1297eb5d 21import { VideoPrivacy } from '../../../shared/models/videos'
30bc55c8
C
22import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
23import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
24import { buildRemoteVideoBaseUrl, checkUrlsSameHost, getAPId } from '../../helpers/activitypub'
d9a2a031
C
25import {
26 isAPVideoFileUrlMetadataObject,
27 isAPVideoTrackerUrlObject,
28 sanitizeAndCheckVideoTorrentObject
29} from '../../helpers/custom-validators/activitypub/videos'
30bc55c8 30import { isArray } from '../../helpers/custom-validators/misc'
2ccaeeb3 31import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
d7a25329 32import { deleteNonExistingModels, resetSequelizeInstance, retryTransactionWrapper } from '../../helpers/database-utils'
2ccaeeb3 33import { logger } from '../../helpers/logger'
b5c36108 34import { doJSONRequest, PeerTubeRequestError } from '../../helpers/requests'
30bc55c8 35import { fetchVideoByUrl, getExtFromMimetype, VideoFetchByUrlType } from '../../helpers/video'
e8bafea3
C
36import {
37 ACTIVITY_PUB,
90a8bd30 38 LAZY_STATIC_PATHS,
e8bafea3
C
39 MIMETYPES,
40 P2P_MEDIA_LOADER_PEER_VERSION,
41 PREVIEWS_SIZE,
42 REMOTE_SCHEME,
7b81edc8 43 THUMBNAILS_SIZE
e8bafea3 44} from '../../initializers/constants'
30bc55c8
C
45import { sequelizeTypescript } from '../../initializers/database'
46import { AccountVideoRateModel } from '../../models/account/account-video-rate'
3fd3ab2d 47import { VideoModel } from '../../models/video/video'
40e87e9e 48import { VideoCaptionModel } from '../../models/video/video-caption'
2ba92871 49import { VideoCommentModel } from '../../models/video/video-comment'
30bc55c8
C
50import { VideoFileModel } from '../../models/video/video-file'
51import { VideoShareModel } from '../../models/video/video-share'
52import { VideoStreamingPlaylistModel } from '../../models/video/video-streaming-playlist'
453e83ea 53import {
f92e7f76 54 MAccountIdActor,
453e83ea
C
55 MChannelAccountLight,
56 MChannelDefault,
57 MChannelId,
d7a25329 58 MStreamingPlaylist,
90a8bd30
C
59 MStreamingPlaylistFilesVideo,
60 MStreamingPlaylistVideo,
453e83ea 61 MVideo,
453e83ea 62 MVideoAccountLight,
f92e7f76 63 MVideoAccountLightBlacklistAllFiles,
453e83ea
C
64 MVideoAP,
65 MVideoAPWithoutCaption,
6302d599 66 MVideoCaption,
453e83ea
C
67 MVideoFile,
68 MVideoFullLight,
7b81edc8
C
69 MVideoId,
70 MVideoImmutable,
90a8bd30
C
71 MVideoThumbnail,
72 MVideoWithHost
26d6bf65
C
73} from '../../types/models'
74import { MThumbnail } from '../../types/models/video/thumbnail'
30bc55c8
C
75import { FilteredModelAttributes } from '../../types/sequelize'
76import { ActorFollowScoreCache } from '../files-cache'
77import { JobQueue } from '../job-queue'
78import { Notifier } from '../notifier'
a5cf76af 79import { PeerTubeSocket } from '../peertube-socket'
30bc55c8 80import { createPlaceholderThumbnail, createVideoMiniatureFromUrl } from '../thumbnail'
1ef65f4c 81import { setVideoTags } from '../video'
30bc55c8 82import { autoBlacklistVideoIfNeeded } from '../video-blacklist'
90a8bd30 83import { generateTorrentFileName } from '../video-paths'
30bc55c8
C
84import { getOrCreateActorAndServerAndModel } from './actor'
85import { crawlCollectionPage } from './crawl'
86import { sendCreateVideo, sendUpdateVideo } from './send'
87import { addVideoShares, shareVideoByServerAndChannel } from './share'
88import { addVideoComments } from './video-comments'
89import { createRates } from './video-rates'
453e83ea 90
d9a2a031 91async function federateVideoIfNeeded (videoArg: MVideoAPWithoutCaption, isNewVideo: boolean, transaction?: Transaction) {
453e83ea 92 const video = videoArg as MVideoAP
2186386c 93
5b77537c
C
94 if (
95 // Check this is not a blacklisted video, or unfederated blacklisted video
96 (video.isBlacklisted() === false || (isNewVideo === false && video.VideoBlacklist.unfederated === false)) &&
97 // Check the video is public/unlisted and published
68e70a74 98 video.hasPrivacyForFederation() && video.hasStateForFederation()
5b77537c 99 ) {
40e87e9e
C
100 // Fetch more attributes that we will need to serialize in AP object
101 if (isArray(video.VideoCaptions) === false) {
102 video.VideoCaptions = await video.$get('VideoCaptions', {
6302d599 103 attributes: [ 'filename', 'language' ],
40e87e9e 104 transaction
e6122097 105 })
40e87e9e
C
106 }
107
2cebd797 108 if (isNewVideo) {
2186386c
C
109 // Now we'll add the video's meta data to our followers
110 await sendCreateVideo(video, transaction)
111 await shareVideoByServerAndChannel(video, transaction)
112 } else {
113 await sendUpdateVideo(video, transaction)
114 }
115 }
116}
892211e8 117
db4b15f2 118async function fetchRemoteVideo (videoUrl: string): Promise<{ statusCode: number, videoObject: VideoObject }> {
4157cdb1
C
119 logger.info('Fetching remote video %s.', videoUrl)
120
db4b15f2 121 const { statusCode, body } = await doJSONRequest<any>(videoUrl, { activityPub: true })
4157cdb1 122
5c6d985f 123 if (sanitizeAndCheckVideoTorrentObject(body) === false || checkUrlsSameHost(body.id, videoUrl) !== true) {
4157cdb1 124 logger.debug('Remote video JSON is not valid.', { body })
db4b15f2 125 return { statusCode, videoObject: undefined }
4157cdb1
C
126 }
127
db4b15f2 128 return { statusCode, videoObject: body }
892211e8
C
129}
130
453e83ea 131async function fetchRemoteVideoDescription (video: MVideoAccountLight) {
50d6de9c 132 const host = video.VideoChannel.Account.Actor.Server.host
96f29c0f 133 const path = video.getDescriptionAPIPath()
db4b15f2 134 const url = REMOTE_SCHEME.HTTP + '://' + host + path
892211e8 135
db4b15f2
C
136 const { body } = await doJSONRequest<any>(url)
137 return body.description || ''
892211e8
C
138}
139
de6310b2 140function getOrCreateVideoChannelFromVideoObject (videoObject: VideoObject) {
0f320037
C
141 const channel = videoObject.attributedTo.find(a => a.type === 'Group')
142 if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
143
5c6d985f
C
144 if (checkUrlsSameHost(channel.id, videoObject.id) !== true) {
145 throw new Error(`Video channel url ${channel.id} does not have the same host than video object id ${videoObject.id}`)
146 }
147
e587e0ec 148 return getOrCreateActorAndServerAndModel(channel.id, 'all')
0f320037
C
149}
150
f6eebcb3 151type SyncParam = {
1297eb5d
C
152 likes: boolean
153 dislikes: boolean
154 shares: boolean
155 comments: boolean
f6eebcb3 156 thumbnail: boolean
04b8c3fb 157 refreshVideo?: boolean
f6eebcb3 158}
de6310b2 159async function syncVideoExternalAttributes (video: MVideo, fetchedVideo: VideoObject, syncParam: SyncParam) {
f6eebcb3 160 logger.info('Adding likes/dislikes/shares/comments of video %s.', video.uuid)
2ccaeeb3 161
f6eebcb3 162 const jobPayloads: ActivitypubHttpFetcherPayload[] = []
2ccaeeb3 163
f6eebcb3 164 if (syncParam.likes === true) {
2ba92871
C
165 const handler = items => createRates(items, video, 'like')
166 const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'like' as 'like', crawlStartDate)
167
168 await crawlCollectionPage<string>(fetchedVideo.likes, handler, cleaner)
ca6d3622 169 .catch(err => logger.error('Cannot add likes of video %s.', video.uuid, { err, rootUrl: fetchedVideo.likes }))
f6eebcb3
C
170 } else {
171 jobPayloads.push({ uri: fetchedVideo.likes, videoId: video.id, type: 'video-likes' as 'video-likes' })
172 }
7acee6f1 173
f6eebcb3 174 if (syncParam.dislikes === true) {
2ba92871
C
175 const handler = items => createRates(items, video, 'dislike')
176 const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'dislike' as 'dislike', crawlStartDate)
177
178 await crawlCollectionPage<string>(fetchedVideo.dislikes, handler, cleaner)
ca6d3622 179 .catch(err => logger.error('Cannot add dislikes of video %s.', video.uuid, { err, rootUrl: fetchedVideo.dislikes }))
f6eebcb3
C
180 } else {
181 jobPayloads.push({ uri: fetchedVideo.dislikes, videoId: video.id, type: 'video-dislikes' as 'video-dislikes' })
182 }
183
184 if (syncParam.shares === true) {
2ba92871
C
185 const handler = items => addVideoShares(items, video)
186 const cleaner = crawlStartDate => VideoShareModel.cleanOldSharesOf(video.id, crawlStartDate)
187
188 await crawlCollectionPage<string>(fetchedVideo.shares, handler, cleaner)
ca6d3622 189 .catch(err => logger.error('Cannot add shares of video %s.', video.uuid, { err, rootUrl: fetchedVideo.shares }))
f6eebcb3
C
190 } else {
191 jobPayloads.push({ uri: fetchedVideo.shares, videoId: video.id, type: 'video-shares' as 'video-shares' })
192 }
7acee6f1 193
f6eebcb3 194 if (syncParam.comments === true) {
6b9c966f 195 const handler = items => addVideoComments(items)
2ba92871
C
196 const cleaner = crawlStartDate => VideoCommentModel.cleanOldCommentsOf(video.id, crawlStartDate)
197
198 await crawlCollectionPage<string>(fetchedVideo.comments, handler, cleaner)
ca6d3622 199 .catch(err => logger.error('Cannot add comments of video %s.', video.uuid, { err, rootUrl: fetchedVideo.comments }))
f6eebcb3 200 } else {
2ba92871 201 jobPayloads.push({ uri: fetchedVideo.comments, videoId: video.id, type: 'video-comments' as 'video-comments' })
f6eebcb3 202 }
7acee6f1 203
a1587156 204 await Bluebird.map(jobPayloads, payload => JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload }))
2ccaeeb3
C
205}
206
943e5193
C
207type GetVideoResult <T> = Promise<{
208 video: T
209 created: boolean
210 autoBlacklisted?: boolean
211}>
212
213type GetVideoParamAll = {
a1587156
C
214 videoObject: { id: string } | string
215 syncParam?: SyncParam
216 fetchType?: 'all'
453e83ea 217 allowRefresh?: boolean
943e5193
C
218}
219
220type GetVideoParamImmutable = {
a1587156
C
221 videoObject: { id: string } | string
222 syncParam?: SyncParam
943e5193
C
223 fetchType: 'only-immutable-attributes'
224 allowRefresh: false
225}
226
227type GetVideoParamOther = {
a1587156
C
228 videoObject: { id: string } | string
229 syncParam?: SyncParam
943e5193
C
230 fetchType?: 'all' | 'only-video'
231 allowRefresh?: boolean
232}
233
234function getOrCreateVideoAndAccountAndChannel (options: GetVideoParamAll): GetVideoResult<MVideoAccountLightBlacklistAllFiles>
235function getOrCreateVideoAndAccountAndChannel (options: GetVideoParamImmutable): GetVideoResult<MVideoImmutable>
236function getOrCreateVideoAndAccountAndChannel (
237 options: GetVideoParamOther
238): GetVideoResult<MVideoAccountLightBlacklistAllFiles | MVideoThumbnail>
239async function getOrCreateVideoAndAccountAndChannel (
240 options: GetVideoParamAll | GetVideoParamImmutable | GetVideoParamOther
241): GetVideoResult<MVideoAccountLightBlacklistAllFiles | MVideoThumbnail | MVideoImmutable> {
4157cdb1
C
242 // Default params
243 const syncParam = options.syncParam || { likes: true, dislikes: true, shares: true, comments: true, thumbnail: true, refreshVideo: false }
244 const fetchType = options.fetchType || 'all'
74577825 245 const allowRefresh = options.allowRefresh !== false
1297eb5d 246
4157cdb1 247 // Get video url
848f499d 248 const videoUrl = getAPId(options.videoObject)
4157cdb1 249 let videoFromDatabase = await fetchVideoByUrl(videoUrl, fetchType)
943e5193 250
4157cdb1 251 if (videoFromDatabase) {
943e5193
C
252 // If allowRefresh is true, we could not call this function using 'only-immutable-attributes' fetch type
253 if (allowRefresh === true && (videoFromDatabase as MVideoThumbnail).isOutdated()) {
74577825 254 const refreshOptions = {
943e5193 255 video: videoFromDatabase as MVideoThumbnail,
74577825
C
256 fetchedType: fetchType,
257 syncParam
258 }
259
a1587156
C
260 if (syncParam.refreshVideo === true) {
261 videoFromDatabase = await refreshVideoIfNeeded(refreshOptions)
262 } else {
263 await JobQueue.Instance.createJobWithPromise({
264 type: 'activitypub-refresher',
265 payload: { type: 'video', url: videoFromDatabase.url }
266 })
267 }
d4defe07 268 }
1297eb5d 269
cef534ed 270 return { video: videoFromDatabase, created: false }
1297eb5d
C
271 }
272
4157cdb1
C
273 const { videoObject: fetchedVideo } = await fetchRemoteVideo(videoUrl)
274 if (!fetchedVideo) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
7acee6f1 275
453e83ea
C
276 const actor = await getOrCreateVideoChannelFromVideoObject(fetchedVideo)
277 const videoChannel = actor.VideoChannel
7acee6f1 278
5fb2e288
C
279 try {
280 const { autoBlacklisted, videoCreated } = await retryTransactionWrapper(createVideo, fetchedVideo, videoChannel, syncParam.thumbnail)
281
282 await syncVideoExternalAttributes(videoCreated, fetchedVideo, syncParam)
7acee6f1 283
5fb2e288
C
284 return { video: videoCreated, created: true, autoBlacklisted }
285 } catch (err) {
286 // Maybe a concurrent getOrCreateVideoAndAccountAndChannel call created this video
287 if (err.name === 'SequelizeUniqueConstraintError') {
288 const fallbackVideo = await fetchVideoByUrl(videoUrl, fetchType)
289 if (fallbackVideo) return { video: fallbackVideo, created: false }
290 }
291
292 throw err
293 }
7acee6f1
C
294}
295
d4defe07 296async function updateVideoFromAP (options: {
a1587156 297 video: MVideoAccountLightBlacklistAllFiles
de6310b2 298 videoObject: VideoObject
a1587156
C
299 account: MAccountIdActor
300 channel: MChannelDefault
1297eb5d 301 overrideTo?: string[]
d4defe07 302}) {
b4055e1c
C
303 const { video, videoObject, account, channel, overrideTo } = options
304
68e70a74 305 logger.debug('Updating remote video "%s".', options.videoObject.uuid, { videoObject: options.videoObject, account, channel })
e8d246d5 306
1297eb5d 307 let videoFieldsSave: any
b4055e1c
C
308 const wasPrivateVideo = video.privacy === VideoPrivacy.PRIVATE
309 const wasUnlistedVideo = video.privacy === VideoPrivacy.UNLISTED
1297eb5d
C
310
311 try {
453e83ea 312 let thumbnailModel: MThumbnail
e8bafea3
C
313
314 try {
a35a2279
C
315 thumbnailModel = await createVideoMiniatureFromUrl({
316 downloadUrl: getThumbnailFromIcons(videoObject).url,
317 video,
318 type: ThumbnailType.MINIATURE
319 })
e8bafea3 320 } catch (err) {
b4055e1c 321 logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err })
e8bafea3
C
322 }
323
453e83ea 324 const videoUpdated = await sequelizeTypescript.transaction(async t => {
e8d246d5 325 const sequelizeOptions = { transaction: t }
2ccaeeb3 326
b4055e1c 327 videoFieldsSave = video.toJSON()
2ccaeeb3 328
92315d97
C
329 // Check we can update the channel: we trust the remote server
330 const oldVideoChannel = video.VideoChannel
331
332 if (!oldVideoChannel.Actor.serverId || !channel.Actor.serverId) {
333 throw new Error('Cannot check old channel/new channel validity because `serverId` is null')
334 }
335
336 if (oldVideoChannel.Actor.serverId !== channel.Actor.serverId) {
337 throw new Error('New channel ' + channel.Actor.url + ' is not on the same server than new channel ' + oldVideoChannel.Actor.url)
f6eebcb3
C
338 }
339
a1587156 340 const to = overrideTo || videoObject.to
b4055e1c
C
341 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, to)
342 video.name = videoData.name
343 video.uuid = videoData.uuid
344 video.url = videoData.url
345 video.category = videoData.category
346 video.licence = videoData.licence
347 video.language = videoData.language
348 video.description = videoData.description
349 video.support = videoData.support
350 video.nsfw = videoData.nsfw
351 video.commentsEnabled = videoData.commentsEnabled
352 video.downloadEnabled = videoData.downloadEnabled
353 video.waitTranscoding = videoData.waitTranscoding
354 video.state = videoData.state
355 video.duration = videoData.duration
356 video.createdAt = videoData.createdAt
357 video.publishedAt = videoData.publishedAt
358 video.originallyPublishedAt = videoData.originallyPublishedAt
359 video.privacy = videoData.privacy
360 video.channelId = videoData.channelId
361 video.views = videoData.views
a5cf76af 362 video.isLive = videoData.isLive
b4055e1c 363
b49f22d8
C
364 // Ensures we update the updated video attribute
365 video.changed('updatedAt', true)
366
453e83ea 367 const videoUpdated = await video.save(sequelizeOptions) as MVideoFullLight
b4055e1c 368
453e83ea 369 if (thumbnailModel) await videoUpdated.addAndSaveThumbnail(thumbnailModel, t)
e8bafea3 370
6872996d 371 if (videoUpdated.getPreview()) {
a8b1b404 372 const previewUrl = getPreviewUrl(getPreviewFromIcons(videoObject), video)
a35a2279
C
373 const previewModel = createPlaceholderThumbnail({
374 fileUrl: previewUrl,
375 video,
376 type: ThumbnailType.PREVIEW,
377 size: PREVIEWS_SIZE
378 })
6872996d
C
379 await videoUpdated.addAndSaveThumbnail(previewModel, t)
380 }
e8bafea3 381
e5565833 382 {
d7a25329 383 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoUpdated, videoObject.url)
e5565833 384 const newVideoFiles = videoFileAttributes.map(a => new VideoFileModel(a))
0032ebe9 385
e5565833 386 // Remove video files that do not exist anymore
d7a25329 387 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoFiles, newVideoFiles, t)
e5565833 388 await Promise.all(destroyTasks)
2ccaeeb3 389
e5565833 390 // Update or add other one
d7a25329 391 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'video', t))
453e83ea 392 videoUpdated.VideoFiles = await Promise.all(upsertTasks)
e5565833 393 }
2ccaeeb3 394
09209296 395 {
453e83ea 396 const streamingPlaylistAttributes = streamingPlaylistActivityUrlToDBAttributes(videoUpdated, videoObject, videoUpdated.VideoFiles)
09209296
C
397 const newStreamingPlaylists = streamingPlaylistAttributes.map(a => new VideoStreamingPlaylistModel(a))
398
d7a25329
C
399 // Remove video playlists that do not exist anymore
400 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoStreamingPlaylists, newStreamingPlaylists, t)
09209296
C
401 await Promise.all(destroyTasks)
402
d7a25329
C
403 let oldStreamingPlaylistFiles: MVideoFile[] = []
404 for (const videoStreamingPlaylist of videoUpdated.VideoStreamingPlaylists) {
405 oldStreamingPlaylistFiles = oldStreamingPlaylistFiles.concat(videoStreamingPlaylist.VideoFiles)
406 }
407
408 videoUpdated.VideoStreamingPlaylists = []
409
410 for (const playlistAttributes of streamingPlaylistAttributes) {
411 const streamingPlaylistModel = await VideoStreamingPlaylistModel.upsert(playlistAttributes, { returning: true, transaction: t })
90a8bd30
C
412 .then(([ streamingPlaylist ]) => streamingPlaylist as MStreamingPlaylistFilesVideo)
413 streamingPlaylistModel.Video = videoUpdated
09209296 414
d7a25329
C
415 const newVideoFiles: MVideoFile[] = videoFileActivityUrlToDBAttributes(streamingPlaylistModel, playlistAttributes.tagAPObject)
416 .map(a => new VideoFileModel(a))
417 const destroyTasks = deleteNonExistingModels(oldStreamingPlaylistFiles, newVideoFiles, t)
418 await Promise.all(destroyTasks)
419
420 // Update or add other one
421 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'streaming-playlist', t))
422 streamingPlaylistModel.VideoFiles = await Promise.all(upsertTasks)
423
424 videoUpdated.VideoStreamingPlaylists.push(streamingPlaylistModel)
425 }
09209296
C
426 }
427
e5565833
C
428 {
429 // Update Tags
d7a25329
C
430 const tags = videoObject.tag
431 .filter(isAPHashTagObject)
432 .map(tag => tag.name)
6c9c3b7b 433 await setVideoTags({ video: videoUpdated, tags, transaction: t })
e5565833 434 }
2ccaeeb3 435
d9a2a031
C
436 // Update trackers
437 {
438 const trackers = getTrackerUrls(videoObject, videoUpdated)
439 await setVideoTrackers({ video: videoUpdated, trackers, transaction: t })
440 }
441
e5565833
C
442 {
443 // Update captions
453e83ea 444 await VideoCaptionModel.deleteAllCaptionsOfRemoteVideo(videoUpdated.id, t)
e5565833 445
b4055e1c 446 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
6302d599
C
447 const caption = new VideoCaptionModel({
448 videoId: videoUpdated.id,
449 filename: VideoCaptionModel.generateCaptionName(c.identifier),
450 language: c.identifier,
451 fileUrl: c.url
452 }) as MVideoCaption
453
454 return VideoCaptionModel.insertOrReplaceLanguage(caption, t)
e5565833 455 })
453e83ea 456 await Promise.all(videoCaptionsPromises)
e5565833 457 }
453e83ea 458
af4ae64f
C
459 {
460 // Create or update existing live
461 if (video.isLive) {
462 const [ videoLive ] = await VideoLiveModel.upsert({
463 saveReplay: videoObject.liveSaveReplay,
bb4ba6d9 464 permanentLive: videoObject.permanentLive,
af4ae64f
C
465 videoId: video.id
466 }, { transaction: t, returning: true })
467
468 videoUpdated.VideoLive = videoLive
469 } else { // Delete existing live if it exists
470 await VideoLiveModel.destroy({
471 where: {
472 videoId: video.id
473 },
474 transaction: t
475 })
476
477 videoUpdated.VideoLive = null
478 }
479 }
480
453e83ea 481 return videoUpdated
1297eb5d
C
482 })
483
5b77537c 484 await autoBlacklistVideoIfNeeded({
453e83ea 485 video: videoUpdated,
6691c522
C
486 user: undefined,
487 isRemote: true,
488 isNew: false,
489 transaction: undefined
490 })
b4055e1c 491
a800dbf3
C
492 // Notify our users?
493 if (wasPrivateVideo || wasUnlistedVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoUpdated)
494
495 if (videoUpdated.isLive) {
496 PeerTubeSocket.Instance.sendVideoLiveNewState(videoUpdated)
497 PeerTubeSocket.Instance.sendVideoViewsUpdate(videoUpdated)
498 }
e8d246d5 499
b4055e1c 500 logger.info('Remote video with uuid %s updated', videoObject.uuid)
453e83ea
C
501
502 return videoUpdated
1297eb5d 503 } catch (err) {
b4055e1c
C
504 if (video !== undefined && videoFieldsSave !== undefined) {
505 resetSequelizeInstance(video, videoFieldsSave)
1297eb5d
C
506 }
507
508 // This is just a debug because we will retry the insert
509 logger.debug('Cannot update the remote video.', { err })
510 throw err
511 }
892211e8 512}
2186386c 513
04b8c3fb 514async function refreshVideoIfNeeded (options: {
a1587156
C
515 video: MVideoThumbnail
516 fetchedType: VideoFetchByUrlType
04b8c3fb 517 syncParam: SyncParam
453e83ea 518}): Promise<MVideoThumbnail> {
04b8c3fb
C
519 if (!options.video.isOutdated()) return options.video
520
521 // We need more attributes if the argument video was fetched with not enough joints
b4055e1c 522 const video = options.fetchedType === 'all'
0283eaac 523 ? options.video as MVideoAccountLightBlacklistAllFiles
b4055e1c 524 : await VideoModel.loadByUrlAndPopulateAccount(options.video.url)
04b8c3fb
C
525
526 try {
b5c36108 527 const { videoObject } = await fetchRemoteVideo(video.url)
04b8c3fb
C
528
529 if (videoObject === undefined) {
530 logger.warn('Cannot refresh remote video %s: invalid body.', video.url)
531
532 await video.setAsRefreshed()
533 return video
534 }
535
536 const channelActor = await getOrCreateVideoChannelFromVideoObject(videoObject)
04b8c3fb
C
537
538 const updateOptions = {
539 video,
540 videoObject,
453e83ea 541 account: channelActor.VideoChannel.Account,
04b8c3fb
C
542 channel: channelActor.VideoChannel
543 }
544 await retryTransactionWrapper(updateVideoFromAP, updateOptions)
545 await syncVideoExternalAttributes(video, videoObject, options.syncParam)
546
6b9c966f
C
547 ActorFollowScoreCache.Instance.addGoodServerId(video.VideoChannel.Actor.serverId)
548
04b8c3fb
C
549 return video
550 } catch (err) {
b5c36108
C
551 if ((err as PeerTubeRequestError).statusCode === HttpStatusCode.NOT_FOUND_404) {
552 logger.info('Cannot refresh remote video %s: video does not exist anymore. Deleting it.', video.url)
553
554 // Video does not exist anymore
555 await video.destroy()
556 return undefined
557 }
558
04b8c3fb
C
559 logger.warn('Cannot refresh video %s.', options.video.url, { err })
560
6b9c966f
C
561 ActorFollowScoreCache.Instance.addBadServerId(video.VideoChannel.Actor.serverId)
562
04b8c3fb
C
563 // Don't refresh in loop
564 await video.setAsRefreshed()
565 return video
566 }
892211e8 567}
2186386c
C
568
569export {
1297eb5d 570 updateVideoFromAP,
04b8c3fb 571 refreshVideoIfNeeded,
2186386c
C
572 federateVideoIfNeeded,
573 fetchRemoteVideo,
1297eb5d 574 getOrCreateVideoAndAccountAndChannel,
2186386c 575 fetchRemoteVideoDescription,
4157cdb1 576 getOrCreateVideoChannelFromVideoObject
2186386c 577}
c48e82b5
C
578
579// ---------------------------------------------------------------------------
580
d7a25329 581function isAPVideoUrlObject (url: any): url is ActivityVideoUrlObject {
d7a25329 582 const urlMediaType = url.mediaType
30bc55c8
C
583
584 return MIMETYPES.VIDEO.MIMETYPE_EXT[urlMediaType] && urlMediaType.startsWith('video/')
c48e82b5 585}
4157cdb1 586
d9a2a031 587function isAPStreamingPlaylistUrlObject (url: any): url is ActivityPlaylistUrlObject {
d7a25329 588 return url && url.mediaType === 'application/x-mpegURL'
09209296
C
589}
590
591function isAPPlaylistSegmentHashesUrlObject (tag: any): tag is ActivityPlaylistSegmentHashesObject {
d7a25329
C
592 return tag && tag.name === 'sha256' && tag.type === 'Link' && tag.mediaType === 'application/json'
593}
594
595function isAPMagnetUrlObject (url: any): url is ActivityMagnetUrlObject {
596 return url && url.mediaType === 'application/x-bittorrent;x-scheme-handler/magnet'
597}
09209296 598
d7a25329
C
599function isAPHashTagObject (url: any): url is ActivityHashTagObject {
600 return url && url.type === 'Hashtag'
c48e82b5 601}
4157cdb1 602
de6310b2 603async function createVideo (videoObject: VideoObject, channel: MChannelAccountLight, waitThumbnail = false) {
4157cdb1
C
604 logger.debug('Adding remote video %s.', videoObject.id)
605
453e83ea
C
606 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, videoObject.to)
607 const video = VideoModel.build(videoData) as MVideoThumbnail
e8bafea3 608
a35a2279
C
609 const promiseThumbnail = createVideoMiniatureFromUrl({
610 downloadUrl: getThumbnailFromIcons(videoObject).url,
611 video,
612 type: ThumbnailType.MINIATURE
613 }).catch(err => {
614 logger.error('Cannot create miniature from url.', { err })
615 return undefined
616 })
e8bafea3 617
453e83ea 618 let thumbnailModel: MThumbnail
e8bafea3
C
619 if (waitThumbnail === true) {
620 thumbnailModel = await promiseThumbnail
621 }
622
6691c522 623 const { autoBlacklisted, videoCreated } = await sequelizeTypescript.transaction(async t => {
a35a2279
C
624 try {
625 const sequelizeOptions = { transaction: t }
4157cdb1 626
a35a2279
C
627 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
628 videoCreated.VideoChannel = channel
e8bafea3 629
a35a2279 630 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
e8bafea3 631
a35a2279
C
632 const previewUrl = getPreviewUrl(getPreviewFromIcons(videoObject), videoCreated)
633 const previewModel = createPlaceholderThumbnail({
634 fileUrl: previewUrl,
635 video: videoCreated,
636 type: ThumbnailType.PREVIEW,
637 size: PREVIEWS_SIZE
638 })
ca6d3622 639
a35a2279 640 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
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
90a8bd30 900function getPreviewUrl (previewIcon: ActivityIconObject, video: MVideoWithHost) {
a8b1b404
C
901 return previewIcon
902 ? previewIcon.url
a0eeb45f 903 : buildRemoteVideoBaseUrl(video, join(LAZY_STATIC_PATHS.PREVIEWS, ActorImageModel.generateFilename()))
a8b1b404 904}
d9a2a031
C
905
906function getTrackerUrls (object: VideoObject, video: MVideoWithHost) {
907 let wsFound = false
908
909 const trackers = object.url.filter(u => isAPVideoTrackerUrlObject(u))
910 .map((u: ActivityTrackerUrlObject) => {
8efc27bf 911 if (isArray(u.rel) && u.rel.includes('websocket')) wsFound = true
d9a2a031
C
912
913 return u.href
914 })
915
916 if (wsFound) return trackers
917
918 return [
919 buildRemoteVideoBaseUrl(video, '/tracker/socket', REMOTE_SCHEME.WS),
920 buildRemoteVideoBaseUrl(video, '/tracker/announce')
921 ]
922}
923
924async function setVideoTrackers (options: {
925 video: MVideo
926 trackers: string[]
927 transaction?: Transaction
928}) {
929 const { video, trackers, transaction } = options
930
931 const trackerInstances = await TrackerModel.findOrCreateTrackers(trackers, transaction)
932
933 await video.$set('Trackers', trackerInstances, { transaction })
934}