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