]>
Commit | Line | Data |
---|---|---|
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 { ActorModel } from '../../models/activitypub/actor' | |
28 | import { TagModel } from '../../models/video/tag' | |
29 | import { VideoModel } from '../../models/video/video' | |
30 | import { VideoChannelModel } from '../../models/video/video-channel' | |
31 | import { VideoFileModel } from '../../models/video/video-file' | |
32 | import { getOrCreateActorAndServerAndModel } from './actor' | |
33 | import { addVideoComments } from './video-comments' | |
34 | import { crawlCollectionPage } from './crawl' | |
35 | import { sendCreateVideo, sendUpdateVideo } from './send' | |
36 | import { isArray } from '../../helpers/custom-validators/misc' | |
37 | import { VideoCaptionModel } from '../../models/video/video-caption' | |
38 | import { JobQueue } from '../job-queue' | |
39 | import { ActivitypubHttpFetcherPayload } from '../job-queue/handlers/activitypub-http-fetcher' | |
40 | import { createRates } from './video-rates' | |
41 | import { addVideoShares, shareVideoByServerAndChannel } from './share' | |
42 | import { AccountModel } from '../../models/account/account' | |
43 | import { fetchVideoByUrl, VideoFetchByUrlType } from '../../helpers/video' | |
44 | import { checkUrlsSameHost, getAPId } from '../../helpers/activitypub' | |
45 | import { Notifier } from '../notifier' | |
46 | import { VideoStreamingPlaylistModel } from '../../models/video/video-streaming-playlist' | |
47 | import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type' | |
48 | import { AccountVideoRateModel } from '../../models/account/account-video-rate' | |
49 | import { VideoShareModel } from '../../models/video/video-share' | |
50 | import { VideoCommentModel } from '../../models/video/video-comment' | |
51 | import { sequelizeTypescript } from '../../initializers/database' | |
52 | import { createPlaceholderThumbnail, createVideoMiniatureFromUrl } from '../thumbnail' | |
53 | import { ThumbnailModel } from '../../models/video/thumbnail' | |
54 | import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type' | |
55 | import { join } from 'path' | |
56 | import { FilteredModelAttributes } from '../../typings/sequelize' | |
57 | import { Hooks } from '../plugins/hooks' | |
58 | import { autoBlacklistVideoIfNeeded } from '../video-blacklist' | |
59 | ||
60 | async 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 | ||
85 | async 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 | ||
105 | async 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 | ||
117 | function 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 | ||
124 | function buildRemoteBaseUrl (video: VideoModel, path: string) { | |
125 | const host = video.VideoChannel.Account.Actor.Server.host | |
126 | ||
127 | return REMOTE_SCHEME.HTTP + '://' + host + path | |
128 | } | |
129 | ||
130 | function 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 | ||
141 | type SyncParam = { | |
142 | likes: boolean | |
143 | dislikes: boolean | |
144 | shares: boolean | |
145 | comments: boolean | |
146 | thumbnail: boolean | |
147 | refreshVideo?: boolean | |
148 | } | |
149 | async 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, video) | |
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 | ||
197 | async 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 | ||
238 | async function updateVideoFromAP (options: { | |
239 | video: VideoModel, | |
240 | videoObject: VideoTorrentObject, | |
241 | account: AccountModel, | |
242 | channel: VideoChannelModel, | |
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 | ||
383 | async 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 | return video | |
425 | } catch (err) { | |
426 | logger.warn('Cannot refresh video %s.', options.video.url, { err }) | |
427 | ||
428 | // Don't refresh in loop | |
429 | await video.setAsRefreshed() | |
430 | return video | |
431 | } | |
432 | } | |
433 | ||
434 | export { | |
435 | updateVideoFromAP, | |
436 | refreshVideoIfNeeded, | |
437 | federateVideoIfNeeded, | |
438 | fetchRemoteVideo, | |
439 | getOrCreateVideoAndAccountAndChannel, | |
440 | fetchRemoteVideoStaticFile, | |
441 | fetchRemoteVideoDescription, | |
442 | getOrCreateVideoChannelFromVideoObject | |
443 | } | |
444 | ||
445 | // --------------------------------------------------------------------------- | |
446 | ||
447 | function isAPVideoUrlObject (url: ActivityUrlObject): url is ActivityVideoUrlObject { | |
448 | const mimeTypes = Object.keys(MIMETYPES.VIDEO.MIMETYPE_EXT) | |
449 | ||
450 | const urlMediaType = url.mediaType || url.mimeType | |
451 | return mimeTypes.indexOf(urlMediaType) !== -1 && urlMediaType.startsWith('video/') | |
452 | } | |
453 | ||
454 | function isAPStreamingPlaylistUrlObject (url: ActivityUrlObject): url is ActivityPlaylistUrlObject { | |
455 | const urlMediaType = url.mediaType || url.mimeType | |
456 | ||
457 | return urlMediaType === 'application/x-mpegURL' | |
458 | } | |
459 | ||
460 | function isAPPlaylistSegmentHashesUrlObject (tag: any): tag is ActivityPlaylistSegmentHashesObject { | |
461 | const urlMediaType = tag.mediaType || tag.mimeType | |
462 | ||
463 | return tag.name === 'sha256' && tag.type === 'Link' && urlMediaType === 'application/json' | |
464 | } | |
465 | ||
466 | async function createVideo (videoObject: VideoTorrentObject, channelActor: ActorModel, waitThumbnail = false) { | |
467 | logger.debug('Adding remote video %s.', videoObject.id) | |
468 | ||
469 | const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to) | |
470 | const video = VideoModel.build(videoData) | |
471 | ||
472 | const promiseThumbnail = createVideoMiniatureFromUrl(videoObject.icon.url, video, ThumbnailType.MINIATURE) | |
473 | ||
474 | let thumbnailModel: ThumbnailModel | |
475 | if (waitThumbnail === true) { | |
476 | thumbnailModel = await promiseThumbnail | |
477 | } | |
478 | ||
479 | const { autoBlacklisted, videoCreated } = await sequelizeTypescript.transaction(async t => { | |
480 | const sequelizeOptions = { transaction: t } | |
481 | ||
482 | const videoCreated = await video.save(sequelizeOptions) | |
483 | videoCreated.VideoChannel = channelActor.VideoChannel | |
484 | ||
485 | if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t) | |
486 | ||
487 | // FIXME: use icon URL instead | |
488 | const previewUrl = buildRemoteBaseUrl(videoCreated, join(STATIC_PATHS.PREVIEWS, video.generatePreviewName())) | |
489 | const previewModel = createPlaceholderThumbnail(previewUrl, video, ThumbnailType.PREVIEW, PREVIEWS_SIZE) | |
490 | if (thumbnailModel) await videoCreated.addAndSaveThumbnail(previewModel, t) | |
491 | ||
492 | // Process files | |
493 | const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject) | |
494 | if (videoFileAttributes.length === 0) { | |
495 | throw new Error('Cannot find valid files for video %s ' + videoObject.url) | |
496 | } | |
497 | ||
498 | const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t })) | |
499 | const videoFiles = await Promise.all(videoFilePromises) | |
500 | ||
501 | const videoStreamingPlaylists = streamingPlaylistActivityUrlToDBAttributes(videoCreated, videoObject, videoFiles) | |
502 | const playlistPromises = videoStreamingPlaylists.map(p => VideoStreamingPlaylistModel.create(p, { transaction: t })) | |
503 | await Promise.all(playlistPromises) | |
504 | ||
505 | // Process tags | |
506 | const tags = videoObject.tag | |
507 | .filter(t => t.type === 'Hashtag') | |
508 | .map(t => t.name) | |
509 | const tagInstances = await TagModel.findOrCreateTags(tags, t) | |
510 | await videoCreated.$set('Tags', tagInstances, sequelizeOptions) | |
511 | ||
512 | // Process captions | |
513 | const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => { | |
514 | return VideoCaptionModel.insertOrReplaceLanguage(videoCreated.id, c.identifier, t) | |
515 | }) | |
516 | await Promise.all(videoCaptionsPromises) | |
517 | ||
518 | const autoBlacklisted = await autoBlacklistVideoIfNeeded({ | |
519 | video, | |
520 | user: undefined, | |
521 | isRemote: true, | |
522 | isNew: true, | |
523 | transaction: t | |
524 | }) | |
525 | ||
526 | logger.info('Remote video with uuid %s inserted.', videoObject.uuid) | |
527 | ||
528 | return { autoBlacklisted, videoCreated } | |
529 | }) | |
530 | ||
531 | if (waitThumbnail === false) { | |
532 | promiseThumbnail.then(thumbnailModel => { | |
533 | thumbnailModel = videoCreated.id | |
534 | ||
535 | return thumbnailModel.save() | |
536 | }) | |
537 | } | |
538 | ||
539 | return { autoBlacklisted, videoCreated } | |
540 | } | |
541 | ||
542 | async function videoActivityObjectToDBAttributes ( | |
543 | videoChannel: VideoChannelModel, | |
544 | videoObject: VideoTorrentObject, | |
545 | to: string[] = [] | |
546 | ) { | |
547 | const privacy = to.indexOf(ACTIVITY_PUB.PUBLIC) !== -1 ? VideoPrivacy.PUBLIC : VideoPrivacy.UNLISTED | |
548 | const duration = videoObject.duration.replace(/[^\d]+/, '') | |
549 | ||
550 | let language: string | undefined | |
551 | if (videoObject.language) { | |
552 | language = videoObject.language.identifier | |
553 | } | |
554 | ||
555 | let category: number | undefined | |
556 | if (videoObject.category) { | |
557 | category = parseInt(videoObject.category.identifier, 10) | |
558 | } | |
559 | ||
560 | let licence: number | undefined | |
561 | if (videoObject.licence) { | |
562 | licence = parseInt(videoObject.licence.identifier, 10) | |
563 | } | |
564 | ||
565 | const description = videoObject.content || null | |
566 | const support = videoObject.support || null | |
567 | ||
568 | return { | |
569 | name: videoObject.name, | |
570 | uuid: videoObject.uuid, | |
571 | url: videoObject.id, | |
572 | category, | |
573 | licence, | |
574 | language, | |
575 | description, | |
576 | support, | |
577 | nsfw: videoObject.sensitive, | |
578 | commentsEnabled: videoObject.commentsEnabled, | |
579 | downloadEnabled: videoObject.downloadEnabled, | |
580 | waitTranscoding: videoObject.waitTranscoding, | |
581 | state: videoObject.state, | |
582 | channelId: videoChannel.id, | |
583 | duration: parseInt(duration, 10), | |
584 | createdAt: new Date(videoObject.published), | |
585 | publishedAt: new Date(videoObject.published), | |
586 | originallyPublishedAt: videoObject.originallyPublishedAt ? new Date(videoObject.originallyPublishedAt) : null, | |
587 | // FIXME: updatedAt does not seems to be considered by Sequelize | |
588 | updatedAt: new Date(videoObject.updated), | |
589 | views: videoObject.views, | |
590 | likes: 0, | |
591 | dislikes: 0, | |
592 | remote: true, | |
593 | privacy | |
594 | } | |
595 | } | |
596 | ||
597 | function videoFileActivityUrlToDBAttributes (video: VideoModel, videoObject: VideoTorrentObject) { | |
598 | const fileUrls = videoObject.url.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[] | |
599 | ||
600 | if (fileUrls.length === 0) { | |
601 | throw new Error('Cannot find video files for ' + video.url) | |
602 | } | |
603 | ||
604 | const attributes: FilteredModelAttributes<VideoFileModel>[] = [] | |
605 | for (const fileUrl of fileUrls) { | |
606 | // Fetch associated magnet uri | |
607 | const magnet = videoObject.url.find(u => { | |
608 | const mediaType = u.mediaType || u.mimeType | |
609 | return mediaType === 'application/x-bittorrent;x-scheme-handler/magnet' && (u as any).height === fileUrl.height | |
610 | }) | |
611 | ||
612 | if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href) | |
613 | ||
614 | const parsed = magnetUtil.decode(magnet.href) | |
615 | if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) { | |
616 | throw new Error('Cannot parse magnet URI ' + magnet.href) | |
617 | } | |
618 | ||
619 | const mediaType = fileUrl.mediaType || fileUrl.mimeType | |
620 | const attribute = { | |
621 | extname: MIMETYPES.VIDEO.MIMETYPE_EXT[ mediaType ], | |
622 | infoHash: parsed.infoHash, | |
623 | resolution: fileUrl.height, | |
624 | size: fileUrl.size, | |
625 | videoId: video.id, | |
626 | fps: fileUrl.fps || -1 | |
627 | } | |
628 | ||
629 | attributes.push(attribute) | |
630 | } | |
631 | ||
632 | return attributes | |
633 | } | |
634 | ||
635 | function streamingPlaylistActivityUrlToDBAttributes (video: VideoModel, videoObject: VideoTorrentObject, videoFiles: VideoFileModel[]) { | |
636 | const playlistUrls = videoObject.url.filter(u => isAPStreamingPlaylistUrlObject(u)) as ActivityPlaylistUrlObject[] | |
637 | if (playlistUrls.length === 0) return [] | |
638 | ||
639 | const attributes: FilteredModelAttributes<VideoStreamingPlaylistModel>[] = [] | |
640 | for (const playlistUrlObject of playlistUrls) { | |
641 | const segmentsSha256UrlObject = playlistUrlObject.tag | |
642 | .find(t => { | |
643 | return isAPPlaylistSegmentHashesUrlObject(t) | |
644 | }) as ActivityPlaylistSegmentHashesObject | |
645 | if (!segmentsSha256UrlObject) { | |
646 | logger.warn('No segment sha256 URL found in AP playlist object.', { playlistUrl: playlistUrlObject }) | |
647 | continue | |
648 | } | |
649 | ||
650 | const attribute = { | |
651 | type: VideoStreamingPlaylistType.HLS, | |
652 | playlistUrl: playlistUrlObject.href, | |
653 | segmentsSha256Url: segmentsSha256UrlObject.href, | |
654 | p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrlObject.href, videoFiles), | |
655 | p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION, | |
656 | videoId: video.id | |
657 | } | |
658 | ||
659 | attributes.push(attribute) | |
660 | } | |
661 | ||
662 | return attributes | |
663 | } |