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