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