]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/activitypub/videos.ts
Live streaming implementation first step
[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'
09209296 7import {
d7a25329
C
8 ActivityHashTagObject,
9 ActivityMagnetUrlObject,
09209296 10 ActivityPlaylistSegmentHashesObject,
30bc55c8
C
11 ActivityPlaylistUrlObject,
12 ActivitypubHttpFetcherPayload,
ca6d3622 13 ActivityTagObject,
09209296 14 ActivityUrlObject,
1735c825 15 ActivityVideoUrlObject,
7b81edc8 16 VideoState
09209296 17} from '../../../shared/index'
2ccaeeb3 18import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
1297eb5d 19import { VideoPrivacy } from '../../../shared/models/videos'
30bc55c8
C
20import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
21import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
22import { buildRemoteVideoBaseUrl, checkUrlsSameHost, getAPId } from '../../helpers/activitypub'
ac940348 23import { isAPVideoFileMetadataObject, sanitizeAndCheckVideoTorrentObject } from '../../helpers/custom-validators/activitypub/videos'
30bc55c8 24import { isArray } from '../../helpers/custom-validators/misc'
2ccaeeb3 25import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
d7a25329 26import { deleteNonExistingModels, resetSequelizeInstance, retryTransactionWrapper } from '../../helpers/database-utils'
2ccaeeb3 27import { logger } from '../../helpers/logger'
ca6d3622 28import { doRequest } from '../../helpers/requests'
30bc55c8 29import { fetchVideoByUrl, getExtFromMimetype, VideoFetchByUrlType } from '../../helpers/video'
e8bafea3
C
30import {
31 ACTIVITY_PUB,
32 MIMETYPES,
33 P2P_MEDIA_LOADER_PEER_VERSION,
34 PREVIEWS_SIZE,
35 REMOTE_SCHEME,
7b81edc8
C
36 STATIC_PATHS,
37 THUMBNAILS_SIZE
e8bafea3 38} from '../../initializers/constants'
30bc55c8
C
39import { sequelizeTypescript } from '../../initializers/database'
40import { AccountVideoRateModel } from '../../models/account/account-video-rate'
2ccaeeb3 41import { TagModel } from '../../models/video/tag'
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,
59 MVideoFile,
60 MVideoFullLight,
7b81edc8
C
61 MVideoId,
62 MVideoImmutable,
96ca24f0 63 MVideoThumbnail
26d6bf65
C
64} from '../../types/models'
65import { MThumbnail } from '../../types/models/video/thumbnail'
30bc55c8
C
66import { FilteredModelAttributes } from '../../types/sequelize'
67import { ActorFollowScoreCache } from '../files-cache'
68import { JobQueue } from '../job-queue'
69import { Notifier } from '../notifier'
70import { createPlaceholderThumbnail, createVideoMiniatureFromUrl } from '../thumbnail'
71import { autoBlacklistVideoIfNeeded } from '../video-blacklist'
72import { getOrCreateActorAndServerAndModel } from './actor'
73import { crawlCollectionPage } from './crawl'
74import { sendCreateVideo, sendUpdateVideo } from './send'
75import { addVideoShares, shareVideoByServerAndChannel } from './share'
76import { addVideoComments } from './video-comments'
77import { createRates } from './video-rates'
453e83ea
C
78
79async function federateVideoIfNeeded (videoArg: MVideoAPWithoutCaption, isNewVideo: boolean, transaction?: sequelize.Transaction) {
80 const video = videoArg as MVideoAP
2186386c 81
5b77537c
C
82 if (
83 // Check this is not a blacklisted video, or unfederated blacklisted video
84 (video.isBlacklisted() === false || (isNewVideo === false && video.VideoBlacklist.unfederated === false)) &&
85 // Check the video is public/unlisted and published
22a73cb8 86 video.hasPrivacyForFederation() && video.state === VideoState.PUBLISHED
5b77537c 87 ) {
40e87e9e
C
88 // Fetch more attributes that we will need to serialize in AP object
89 if (isArray(video.VideoCaptions) === false) {
90 video.VideoCaptions = await video.$get('VideoCaptions', {
91 attributes: [ 'language' ],
92 transaction
e6122097 93 })
40e87e9e
C
94 }
95
2cebd797 96 if (isNewVideo) {
2186386c
C
97 // Now we'll add the video's meta data to our followers
98 await sendCreateVideo(video, transaction)
99 await shareVideoByServerAndChannel(video, transaction)
100 } else {
101 await sendUpdateVideo(video, transaction)
102 }
103 }
104}
892211e8 105
4157cdb1
C
106async function fetchRemoteVideo (videoUrl: string): Promise<{ response: request.RequestResponse, videoObject: VideoTorrentObject }> {
107 const options = {
108 uri: videoUrl,
109 method: 'GET',
110 json: true,
111 activityPub: true
112 }
892211e8 113
4157cdb1
C
114 logger.info('Fetching remote video %s.', videoUrl)
115
bdd428a6 116 const { response, body } = await doRequest<any>(options)
4157cdb1 117
5c6d985f 118 if (sanitizeAndCheckVideoTorrentObject(body) === false || checkUrlsSameHost(body.id, videoUrl) !== true) {
4157cdb1
C
119 logger.debug('Remote video JSON is not valid.', { body })
120 return { response, videoObject: undefined }
121 }
122
123 return { response, videoObject: body }
892211e8
C
124}
125
453e83ea 126async function fetchRemoteVideoDescription (video: MVideoAccountLight) {
50d6de9c 127 const host = video.VideoChannel.Account.Actor.Server.host
96f29c0f 128 const path = video.getDescriptionAPIPath()
892211e8
C
129 const options = {
130 uri: REMOTE_SCHEME.HTTP + '://' + host + path,
131 json: true
132 }
133
bdd428a6 134 const { body } = await doRequest<any>(options)
892211e8
C
135 return body.description ? body.description : ''
136}
137
f37dc0dd 138function getOrCreateVideoChannelFromVideoObject (videoObject: VideoTorrentObject) {
0f320037
C
139 const channel = videoObject.attributedTo.find(a => a.type === 'Group')
140 if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
141
5c6d985f
C
142 if (checkUrlsSameHost(channel.id, videoObject.id) !== true) {
143 throw new Error(`Video channel url ${channel.id} does not have the same host than video object id ${videoObject.id}`)
144 }
145
e587e0ec 146 return getOrCreateActorAndServerAndModel(channel.id, 'all')
0f320037
C
147}
148
f6eebcb3 149type SyncParam = {
1297eb5d
C
150 likes: boolean
151 dislikes: boolean
152 shares: boolean
153 comments: boolean
f6eebcb3 154 thumbnail: boolean
04b8c3fb 155 refreshVideo?: boolean
f6eebcb3 156}
453e83ea 157async function syncVideoExternalAttributes (video: MVideo, fetchedVideo: VideoTorrentObject, syncParam: SyncParam) {
f6eebcb3 158 logger.info('Adding likes/dislikes/shares/comments of video %s.', video.uuid)
2ccaeeb3 159
f6eebcb3 160 const jobPayloads: ActivitypubHttpFetcherPayload[] = []
2ccaeeb3 161
f6eebcb3 162 if (syncParam.likes === true) {
2ba92871
C
163 const handler = items => createRates(items, video, 'like')
164 const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'like' as 'like', crawlStartDate)
165
166 await crawlCollectionPage<string>(fetchedVideo.likes, handler, cleaner)
ca6d3622 167 .catch(err => logger.error('Cannot add likes of video %s.', video.uuid, { err, rootUrl: fetchedVideo.likes }))
f6eebcb3
C
168 } else {
169 jobPayloads.push({ uri: fetchedVideo.likes, videoId: video.id, type: 'video-likes' as 'video-likes' })
170 }
7acee6f1 171
f6eebcb3 172 if (syncParam.dislikes === true) {
2ba92871
C
173 const handler = items => createRates(items, video, 'dislike')
174 const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'dislike' as 'dislike', crawlStartDate)
175
176 await crawlCollectionPage<string>(fetchedVideo.dislikes, handler, cleaner)
ca6d3622 177 .catch(err => logger.error('Cannot add dislikes of video %s.', video.uuid, { err, rootUrl: fetchedVideo.dislikes }))
f6eebcb3
C
178 } else {
179 jobPayloads.push({ uri: fetchedVideo.dislikes, videoId: video.id, type: 'video-dislikes' as 'video-dislikes' })
180 }
181
182 if (syncParam.shares === true) {
2ba92871
C
183 const handler = items => addVideoShares(items, video)
184 const cleaner = crawlStartDate => VideoShareModel.cleanOldSharesOf(video.id, crawlStartDate)
185
186 await crawlCollectionPage<string>(fetchedVideo.shares, handler, cleaner)
ca6d3622 187 .catch(err => logger.error('Cannot add shares of video %s.', video.uuid, { err, rootUrl: fetchedVideo.shares }))
f6eebcb3
C
188 } else {
189 jobPayloads.push({ uri: fetchedVideo.shares, videoId: video.id, type: 'video-shares' as 'video-shares' })
190 }
7acee6f1 191
f6eebcb3 192 if (syncParam.comments === true) {
6b9c966f 193 const handler = items => addVideoComments(items)
2ba92871
C
194 const cleaner = crawlStartDate => VideoCommentModel.cleanOldCommentsOf(video.id, crawlStartDate)
195
196 await crawlCollectionPage<string>(fetchedVideo.comments, handler, cleaner)
ca6d3622 197 .catch(err => logger.error('Cannot add comments of video %s.', video.uuid, { err, rootUrl: fetchedVideo.comments }))
f6eebcb3 198 } else {
2ba92871 199 jobPayloads.push({ uri: fetchedVideo.comments, videoId: video.id, type: 'video-comments' as 'video-comments' })
f6eebcb3 200 }
7acee6f1 201
a1587156 202 await Bluebird.map(jobPayloads, payload => JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload }))
2ccaeeb3
C
203}
204
943e5193
C
205type GetVideoResult <T> = Promise<{
206 video: T
207 created: boolean
208 autoBlacklisted?: boolean
209}>
210
211type GetVideoParamAll = {
a1587156
C
212 videoObject: { id: string } | string
213 syncParam?: SyncParam
214 fetchType?: 'all'
453e83ea 215 allowRefresh?: boolean
943e5193
C
216}
217
218type GetVideoParamImmutable = {
a1587156
C
219 videoObject: { id: string } | string
220 syncParam?: SyncParam
943e5193
C
221 fetchType: 'only-immutable-attributes'
222 allowRefresh: false
223}
224
225type GetVideoParamOther = {
a1587156
C
226 videoObject: { id: string } | string
227 syncParam?: SyncParam
943e5193
C
228 fetchType?: 'all' | 'only-video'
229 allowRefresh?: boolean
230}
231
232function getOrCreateVideoAndAccountAndChannel (options: GetVideoParamAll): GetVideoResult<MVideoAccountLightBlacklistAllFiles>
233function getOrCreateVideoAndAccountAndChannel (options: GetVideoParamImmutable): GetVideoResult<MVideoImmutable>
234function getOrCreateVideoAndAccountAndChannel (
235 options: GetVideoParamOther
236): GetVideoResult<MVideoAccountLightBlacklistAllFiles | MVideoThumbnail>
237async function getOrCreateVideoAndAccountAndChannel (
238 options: GetVideoParamAll | GetVideoParamImmutable | GetVideoParamOther
239): GetVideoResult<MVideoAccountLightBlacklistAllFiles | MVideoThumbnail | MVideoImmutable> {
4157cdb1
C
240 // Default params
241 const syncParam = options.syncParam || { likes: true, dislikes: true, shares: true, comments: true, thumbnail: true, refreshVideo: false }
242 const fetchType = options.fetchType || 'all'
74577825 243 const allowRefresh = options.allowRefresh !== false
1297eb5d 244
4157cdb1 245 // Get video url
848f499d 246 const videoUrl = getAPId(options.videoObject)
4157cdb1 247 let videoFromDatabase = await fetchVideoByUrl(videoUrl, fetchType)
943e5193 248
4157cdb1 249 if (videoFromDatabase) {
943e5193
C
250 // If allowRefresh is true, we could not call this function using 'only-immutable-attributes' fetch type
251 if (allowRefresh === true && (videoFromDatabase as MVideoThumbnail).isOutdated()) {
74577825 252 const refreshOptions = {
943e5193 253 video: videoFromDatabase as MVideoThumbnail,
74577825
C
254 fetchedType: fetchType,
255 syncParam
256 }
257
a1587156
C
258 if (syncParam.refreshVideo === true) {
259 videoFromDatabase = await refreshVideoIfNeeded(refreshOptions)
260 } else {
261 await JobQueue.Instance.createJobWithPromise({
262 type: 'activitypub-refresher',
263 payload: { type: 'video', url: videoFromDatabase.url }
264 })
265 }
d4defe07 266 }
1297eb5d 267
cef534ed 268 return { video: videoFromDatabase, created: false }
1297eb5d
C
269 }
270
4157cdb1
C
271 const { videoObject: fetchedVideo } = await fetchRemoteVideo(videoUrl)
272 if (!fetchedVideo) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
7acee6f1 273
453e83ea
C
274 const actor = await getOrCreateVideoChannelFromVideoObject(fetchedVideo)
275 const videoChannel = actor.VideoChannel
7acee6f1 276
5fb2e288
C
277 try {
278 const { autoBlacklisted, videoCreated } = await retryTransactionWrapper(createVideo, fetchedVideo, videoChannel, syncParam.thumbnail)
279
280 await syncVideoExternalAttributes(videoCreated, fetchedVideo, syncParam)
7acee6f1 281
5fb2e288
C
282 return { video: videoCreated, created: true, autoBlacklisted }
283 } catch (err) {
284 // Maybe a concurrent getOrCreateVideoAndAccountAndChannel call created this video
285 if (err.name === 'SequelizeUniqueConstraintError') {
286 const fallbackVideo = await fetchVideoByUrl(videoUrl, fetchType)
287 if (fallbackVideo) return { video: fallbackVideo, created: false }
288 }
289
290 throw err
291 }
7acee6f1
C
292}
293
d4defe07 294async function updateVideoFromAP (options: {
a1587156
C
295 video: MVideoAccountLightBlacklistAllFiles
296 videoObject: VideoTorrentObject
297 account: MAccountIdActor
298 channel: MChannelDefault
1297eb5d 299 overrideTo?: string[]
d4defe07 300}) {
b4055e1c
C
301 const { video, videoObject, account, channel, overrideTo } = options
302
453e83ea 303 logger.debug('Updating remote video "%s".', options.videoObject.uuid, { account, channel })
e8d246d5 304
1297eb5d 305 let videoFieldsSave: any
b4055e1c
C
306 const wasPrivateVideo = video.privacy === VideoPrivacy.PRIVATE
307 const wasUnlistedVideo = video.privacy === VideoPrivacy.UNLISTED
1297eb5d
C
308
309 try {
453e83ea 310 let thumbnailModel: MThumbnail
e8bafea3
C
311
312 try {
ca6d3622 313 thumbnailModel = await createVideoMiniatureFromUrl(getThumbnailFromIcons(videoObject).url, video, ThumbnailType.MINIATURE)
e8bafea3 314 } catch (err) {
b4055e1c 315 logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err })
e8bafea3
C
316 }
317
453e83ea 318 const videoUpdated = await sequelizeTypescript.transaction(async t => {
e8d246d5 319 const sequelizeOptions = { transaction: t }
2ccaeeb3 320
b4055e1c 321 videoFieldsSave = video.toJSON()
2ccaeeb3 322
1297eb5d 323 // Check actor has the right to update the video
b4055e1c
C
324 const videoChannel = video.VideoChannel
325 if (videoChannel.Account.id !== account.id) {
326 throw new Error('Account ' + account.Actor.url + ' does not own video channel ' + videoChannel.Actor.url)
f6eebcb3
C
327 }
328
a1587156 329 const to = overrideTo || videoObject.to
b4055e1c
C
330 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, to)
331 video.name = videoData.name
332 video.uuid = videoData.uuid
333 video.url = videoData.url
334 video.category = videoData.category
335 video.licence = videoData.licence
336 video.language = videoData.language
337 video.description = videoData.description
338 video.support = videoData.support
339 video.nsfw = videoData.nsfw
340 video.commentsEnabled = videoData.commentsEnabled
341 video.downloadEnabled = videoData.downloadEnabled
342 video.waitTranscoding = videoData.waitTranscoding
343 video.state = videoData.state
344 video.duration = videoData.duration
345 video.createdAt = videoData.createdAt
346 video.publishedAt = videoData.publishedAt
347 video.originallyPublishedAt = videoData.originallyPublishedAt
348 video.privacy = videoData.privacy
349 video.channelId = videoData.channelId
350 video.views = videoData.views
351
453e83ea 352 const videoUpdated = await video.save(sequelizeOptions) as MVideoFullLight
b4055e1c 353
453e83ea 354 if (thumbnailModel) await videoUpdated.addAndSaveThumbnail(thumbnailModel, t)
e8bafea3 355
6872996d
C
356 if (videoUpdated.getPreview()) {
357 const previewUrl = videoUpdated.getPreview().getFileUrl(videoUpdated)
358 const previewModel = createPlaceholderThumbnail(previewUrl, video, ThumbnailType.PREVIEW, PREVIEWS_SIZE)
359 await videoUpdated.addAndSaveThumbnail(previewModel, t)
360 }
e8bafea3 361
e5565833 362 {
d7a25329 363 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoUpdated, videoObject.url)
e5565833 364 const newVideoFiles = videoFileAttributes.map(a => new VideoFileModel(a))
0032ebe9 365
e5565833 366 // Remove video files that do not exist anymore
d7a25329 367 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoFiles, newVideoFiles, t)
e5565833 368 await Promise.all(destroyTasks)
2ccaeeb3 369
e5565833 370 // Update or add other one
d7a25329 371 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'video', t))
453e83ea 372 videoUpdated.VideoFiles = await Promise.all(upsertTasks)
e5565833 373 }
2ccaeeb3 374
09209296 375 {
453e83ea 376 const streamingPlaylistAttributes = streamingPlaylistActivityUrlToDBAttributes(videoUpdated, videoObject, videoUpdated.VideoFiles)
09209296
C
377 const newStreamingPlaylists = streamingPlaylistAttributes.map(a => new VideoStreamingPlaylistModel(a))
378
d7a25329
C
379 // Remove video playlists that do not exist anymore
380 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoStreamingPlaylists, newStreamingPlaylists, t)
09209296
C
381 await Promise.all(destroyTasks)
382
d7a25329
C
383 let oldStreamingPlaylistFiles: MVideoFile[] = []
384 for (const videoStreamingPlaylist of videoUpdated.VideoStreamingPlaylists) {
385 oldStreamingPlaylistFiles = oldStreamingPlaylistFiles.concat(videoStreamingPlaylist.VideoFiles)
386 }
387
388 videoUpdated.VideoStreamingPlaylists = []
389
390 for (const playlistAttributes of streamingPlaylistAttributes) {
391 const streamingPlaylistModel = await VideoStreamingPlaylistModel.upsert(playlistAttributes, { returning: true, transaction: t })
392 .then(([ streamingPlaylist ]) => streamingPlaylist)
09209296 393
d7a25329
C
394 const newVideoFiles: MVideoFile[] = videoFileActivityUrlToDBAttributes(streamingPlaylistModel, playlistAttributes.tagAPObject)
395 .map(a => new VideoFileModel(a))
396 const destroyTasks = deleteNonExistingModels(oldStreamingPlaylistFiles, newVideoFiles, t)
397 await Promise.all(destroyTasks)
398
399 // Update or add other one
400 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'streaming-playlist', t))
401 streamingPlaylistModel.VideoFiles = await Promise.all(upsertTasks)
402
403 videoUpdated.VideoStreamingPlaylists.push(streamingPlaylistModel)
404 }
09209296
C
405 }
406
e5565833
C
407 {
408 // Update Tags
d7a25329
C
409 const tags = videoObject.tag
410 .filter(isAPHashTagObject)
411 .map(tag => tag.name)
e5565833 412 const tagInstances = await TagModel.findOrCreateTags(tags, t)
453e83ea 413 await videoUpdated.$set('Tags', tagInstances, sequelizeOptions)
e5565833 414 }
2ccaeeb3 415
e5565833
C
416 {
417 // Update captions
453e83ea 418 await VideoCaptionModel.deleteAllCaptionsOfRemoteVideo(videoUpdated.id, t)
e5565833 419
b4055e1c 420 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
ca6d3622 421 return VideoCaptionModel.insertOrReplaceLanguage(videoUpdated.id, c.identifier, c.url, t)
e5565833 422 })
453e83ea 423 await Promise.all(videoCaptionsPromises)
e5565833 424 }
453e83ea
C
425
426 return videoUpdated
1297eb5d
C
427 })
428
5b77537c 429 await autoBlacklistVideoIfNeeded({
453e83ea 430 video: videoUpdated,
6691c522
C
431 user: undefined,
432 isRemote: true,
433 isNew: false,
434 transaction: undefined
435 })
b4055e1c 436
453e83ea 437 if (wasPrivateVideo || wasUnlistedVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoUpdated) // Notify our users?
e8d246d5 438
b4055e1c 439 logger.info('Remote video with uuid %s updated', videoObject.uuid)
453e83ea
C
440
441 return videoUpdated
1297eb5d 442 } catch (err) {
b4055e1c
C
443 if (video !== undefined && videoFieldsSave !== undefined) {
444 resetSequelizeInstance(video, videoFieldsSave)
1297eb5d
C
445 }
446
447 // This is just a debug because we will retry the insert
448 logger.debug('Cannot update the remote video.', { err })
449 throw err
450 }
892211e8 451}
2186386c 452
04b8c3fb 453async function refreshVideoIfNeeded (options: {
a1587156
C
454 video: MVideoThumbnail
455 fetchedType: VideoFetchByUrlType
04b8c3fb 456 syncParam: SyncParam
453e83ea 457}): Promise<MVideoThumbnail> {
04b8c3fb
C
458 if (!options.video.isOutdated()) return options.video
459
460 // We need more attributes if the argument video was fetched with not enough joints
b4055e1c 461 const video = options.fetchedType === 'all'
0283eaac 462 ? options.video as MVideoAccountLightBlacklistAllFiles
b4055e1c 463 : await VideoModel.loadByUrlAndPopulateAccount(options.video.url)
04b8c3fb
C
464
465 try {
466 const { response, videoObject } = await fetchRemoteVideo(video.url)
467 if (response.statusCode === 404) {
468 logger.info('Cannot refresh remote video %s: video does not exist anymore. Deleting it.', video.url)
469
470 // Video does not exist anymore
471 await video.destroy()
472 return undefined
473 }
474
475 if (videoObject === undefined) {
476 logger.warn('Cannot refresh remote video %s: invalid body.', video.url)
477
478 await video.setAsRefreshed()
479 return video
480 }
481
482 const channelActor = await getOrCreateVideoChannelFromVideoObject(videoObject)
04b8c3fb
C
483
484 const updateOptions = {
485 video,
486 videoObject,
453e83ea 487 account: channelActor.VideoChannel.Account,
04b8c3fb
C
488 channel: channelActor.VideoChannel
489 }
490 await retryTransactionWrapper(updateVideoFromAP, updateOptions)
491 await syncVideoExternalAttributes(video, videoObject, options.syncParam)
492
6b9c966f
C
493 ActorFollowScoreCache.Instance.addGoodServerId(video.VideoChannel.Actor.serverId)
494
04b8c3fb
C
495 return video
496 } catch (err) {
497 logger.warn('Cannot refresh video %s.', options.video.url, { err })
498
6b9c966f
C
499 ActorFollowScoreCache.Instance.addBadServerId(video.VideoChannel.Actor.serverId)
500
04b8c3fb
C
501 // Don't refresh in loop
502 await video.setAsRefreshed()
503 return video
504 }
892211e8 505}
2186386c
C
506
507export {
1297eb5d 508 updateVideoFromAP,
04b8c3fb 509 refreshVideoIfNeeded,
2186386c
C
510 federateVideoIfNeeded,
511 fetchRemoteVideo,
1297eb5d 512 getOrCreateVideoAndAccountAndChannel,
2186386c 513 fetchRemoteVideoDescription,
4157cdb1 514 getOrCreateVideoChannelFromVideoObject
2186386c 515}
c48e82b5
C
516
517// ---------------------------------------------------------------------------
518
d7a25329 519function isAPVideoUrlObject (url: any): url is ActivityVideoUrlObject {
d7a25329 520 const urlMediaType = url.mediaType
30bc55c8
C
521
522 return MIMETYPES.VIDEO.MIMETYPE_EXT[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 = {
30bc55c8 719 extname: getExtFromMimetype(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}