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