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