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