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