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