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