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