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