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