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