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