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