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