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