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