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