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