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