]>
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 C |
4 | import { join } from 'path' |
5 | import * as request from 'request' | |
2186386c | 6 | import { ActivityIconObject, VideoState } from '../../../shared/index' |
2ccaeeb3 | 7 | import { VideoTorrentObject } from '../../../shared/models/activitypub/objects' |
7acee6f1 | 8 | import { VideoPrivacy, VideoRateType } from '../../../shared/models/videos' |
1d6e5dfc | 9 | import { sanitizeAndCheckVideoTorrentObject } from '../../helpers/custom-validators/activitypub/videos' |
2ccaeeb3 C |
10 | import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos' |
11 | import { retryTransactionWrapper } from '../../helpers/database-utils' | |
12 | import { logger } from '../../helpers/logger' | |
da854ddd | 13 | import { doRequest, doRequestAndSaveToFile } from '../../helpers/requests' |
f6eebcb3 | 14 | import { ACTIVITY_PUB, CONFIG, CRAWL_REQUEST_CONCURRENCY, REMOTE_SCHEME, sequelizeTypescript, VIDEO_MIMETYPE_EXT } from '../../initializers' |
7acee6f1 | 15 | import { AccountVideoRateModel } from '../../models/account/account-video-rate' |
2ccaeeb3 C |
16 | import { ActorModel } from '../../models/activitypub/actor' |
17 | import { TagModel } from '../../models/video/tag' | |
3fd3ab2d | 18 | import { VideoModel } from '../../models/video/video' |
2ccaeeb3 C |
19 | import { VideoChannelModel } from '../../models/video/video-channel' |
20 | import { VideoFileModel } from '../../models/video/video-file' | |
21 | import { VideoShareModel } from '../../models/video/video-share' | |
22 | import { getOrCreateActorAndServerAndModel } from './actor' | |
7acee6f1 | 23 | import { addVideoComments } from './video-comments' |
8fffe21a | 24 | import { crawlCollectionPage } from './crawl' |
2186386c C |
25 | import { sendCreateVideo, sendUpdateVideo } from './send' |
26 | import { shareVideoByServerAndChannel } from './index' | |
40e87e9e C |
27 | import { isArray } from '../../helpers/custom-validators/misc' |
28 | import { VideoCaptionModel } from '../../models/video/video-caption' | |
f6eebcb3 C |
29 | import { JobQueue } from '../job-queue' |
30 | import { ActivitypubHttpFetcherPayload } from '../job-queue/handlers/activitypub-http-fetcher' | |
2186386c C |
31 | |
32 | async function federateVideoIfNeeded (video: VideoModel, isNewVideo: boolean, transaction?: sequelize.Transaction) { | |
33 | // If the video is not private and published, we federate it | |
34 | if (video.privacy !== VideoPrivacy.PRIVATE && video.state === VideoState.PUBLISHED) { | |
40e87e9e C |
35 | // Fetch more attributes that we will need to serialize in AP object |
36 | if (isArray(video.VideoCaptions) === false) { | |
37 | video.VideoCaptions = await video.$get('VideoCaptions', { | |
38 | attributes: [ 'language' ], | |
39 | transaction | |
40 | }) as VideoCaptionModel[] | |
41 | } | |
42 | ||
2cebd797 | 43 | if (isNewVideo) { |
2186386c C |
44 | // Now we'll add the video's meta data to our followers |
45 | await sendCreateVideo(video, transaction) | |
46 | await shareVideoByServerAndChannel(video, transaction) | |
47 | } else { | |
48 | await sendUpdateVideo(video, transaction) | |
49 | } | |
50 | } | |
51 | } | |
892211e8 | 52 | |
40e87e9e | 53 | function fetchRemoteVideoStaticFile (video: VideoModel, path: string, reject: Function) { |
50d6de9c | 54 | const host = video.VideoChannel.Account.Actor.Server.host |
892211e8 | 55 | |
f05a1c30 | 56 | // We need to provide a callback, if no we could have an uncaught exception |
f40bbe31 C |
57 | return request.get(REMOTE_SCHEME.HTTP + '://' + host + path, err => { |
58 | if (err) reject(err) | |
59 | }) | |
892211e8 C |
60 | } |
61 | ||
3fd3ab2d | 62 | async function fetchRemoteVideoDescription (video: VideoModel) { |
50d6de9c | 63 | const host = video.VideoChannel.Account.Actor.Server.host |
892211e8 C |
64 | const path = video.getDescriptionPath() |
65 | const options = { | |
66 | uri: REMOTE_SCHEME.HTTP + '://' + host + path, | |
67 | json: true | |
68 | } | |
69 | ||
70 | const { body } = await doRequest(options) | |
71 | return body.description ? body.description : '' | |
72 | } | |
73 | ||
3fd3ab2d | 74 | function generateThumbnailFromUrl (video: VideoModel, icon: ActivityIconObject) { |
892211e8 C |
75 | const thumbnailName = video.getThumbnailName() |
76 | const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName) | |
77 | ||
78 | const options = { | |
79 | method: 'GET', | |
80 | uri: icon.url | |
81 | } | |
82 | return doRequestAndSaveToFile(options, thumbnailPath) | |
83 | } | |
84 | ||
2186386c C |
85 | async function videoActivityObjectToDBAttributes ( |
86 | videoChannel: VideoChannelModel, | |
87 | videoObject: VideoTorrentObject, | |
88 | to: string[] = [] | |
89 | ) { | |
276d03ed | 90 | const privacy = to.indexOf(ACTIVITY_PUB.PUBLIC) !== -1 ? VideoPrivacy.PUBLIC : VideoPrivacy.UNLISTED |
2ccaeeb3 | 91 | const duration = videoObject.duration.replace(/[^\d]+/, '') |
9d3ef9fe | 92 | |
c1e791ba | 93 | let language: string | undefined |
2ccaeeb3 | 94 | if (videoObject.language) { |
9d3ef9fe | 95 | language = videoObject.language.identifier |
2ccaeeb3 C |
96 | } |
97 | ||
c1e791ba | 98 | let category: number | undefined |
2ccaeeb3 C |
99 | if (videoObject.category) { |
100 | category = parseInt(videoObject.category.identifier, 10) | |
101 | } | |
102 | ||
c1e791ba | 103 | let licence: number | undefined |
2ccaeeb3 C |
104 | if (videoObject.licence) { |
105 | licence = parseInt(videoObject.licence.identifier, 10) | |
106 | } | |
107 | ||
276d03ed C |
108 | const description = videoObject.content || null |
109 | const support = videoObject.support || null | |
2422c46b | 110 | |
2ccaeeb3 C |
111 | return { |
112 | name: videoObject.name, | |
113 | uuid: videoObject.uuid, | |
114 | url: videoObject.id, | |
115 | category, | |
116 | licence, | |
117 | language, | |
118 | description, | |
2422c46b | 119 | support, |
0a67e28b | 120 | nsfw: videoObject.sensitive, |
2ccaeeb3 | 121 | commentsEnabled: videoObject.commentsEnabled, |
2186386c C |
122 | waitTranscoding: videoObject.waitTranscoding, |
123 | state: videoObject.state, | |
2ccaeeb3 C |
124 | channelId: videoChannel.id, |
125 | duration: parseInt(duration, 10), | |
126 | createdAt: new Date(videoObject.published), | |
53a61317 | 127 | publishedAt: new Date(videoObject.published), |
2ccaeeb3 C |
128 | // FIXME: updatedAt does not seems to be considered by Sequelize |
129 | updatedAt: new Date(videoObject.updated), | |
130 | views: videoObject.views, | |
131 | likes: 0, | |
132 | dislikes: 0, | |
133 | remote: true, | |
134 | privacy | |
135 | } | |
136 | } | |
137 | ||
138 | function videoFileActivityUrlToDBAttributes (videoCreated: VideoModel, videoObject: VideoTorrentObject) { | |
139 | const mimeTypes = Object.keys(VIDEO_MIMETYPE_EXT) | |
140 | const fileUrls = videoObject.url.filter(u => { | |
141 | return mimeTypes.indexOf(u.mimeType) !== -1 && u.mimeType.startsWith('video/') | |
142 | }) | |
143 | ||
144 | if (fileUrls.length === 0) { | |
145 | throw new Error('Cannot find video files for ' + videoCreated.url) | |
146 | } | |
147 | ||
c1e791ba | 148 | const attributes: VideoFileModel[] = [] |
2ccaeeb3 C |
149 | for (const fileUrl of fileUrls) { |
150 | // Fetch associated magnet uri | |
151 | const magnet = videoObject.url.find(u => { | |
965c4b22 | 152 | return u.mimeType === 'application/x-bittorrent;x-scheme-handler/magnet' && u.height === fileUrl.height |
2ccaeeb3 C |
153 | }) |
154 | ||
9fb3abfd | 155 | if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href) |
2ccaeeb3 | 156 | |
9fb3abfd | 157 | const parsed = magnetUtil.decode(magnet.href) |
2cebd797 | 158 | if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) { |
c1e791ba RK |
159 | throw new Error('Cannot parse magnet URI ' + magnet.href) |
160 | } | |
2ccaeeb3 C |
161 | |
162 | const attribute = { | |
163 | extname: VIDEO_MIMETYPE_EXT[ fileUrl.mimeType ], | |
164 | infoHash: parsed.infoHash, | |
965c4b22 | 165 | resolution: fileUrl.height, |
2ccaeeb3 | 166 | size: fileUrl.size, |
b2977eec C |
167 | videoId: videoCreated.id, |
168 | fps: fileUrl.fps | |
c1e791ba | 169 | } as VideoFileModel |
2ccaeeb3 C |
170 | attributes.push(attribute) |
171 | } | |
172 | ||
173 | return attributes | |
174 | } | |
175 | ||
0f320037 C |
176 | function getOrCreateVideoChannel (videoObject: VideoTorrentObject) { |
177 | const channel = videoObject.attributedTo.find(a => a.type === 'Group') | |
178 | if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url) | |
179 | ||
180 | return getOrCreateActorAndServerAndModel(channel.id) | |
181 | } | |
182 | ||
f6eebcb3 | 183 | async function getOrCreateVideo (videoObject: VideoTorrentObject, channelActor: ActorModel, waitThumbnail = false) { |
2ccaeeb3 C |
184 | logger.debug('Adding remote video %s.', videoObject.id) |
185 | ||
f6eebcb3 | 186 | const videoCreated: VideoModel = await sequelizeTypescript.transaction(async t => { |
2ccaeeb3 C |
187 | const sequelizeOptions = { |
188 | transaction: t | |
189 | } | |
190 | const videoFromDatabase = await VideoModel.loadByUUIDOrURLAndPopulateAccount(videoObject.uuid, videoObject.id, t) | |
191 | if (videoFromDatabase) return videoFromDatabase | |
192 | ||
276d03ed | 193 | const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to) |
2ccaeeb3 C |
194 | const video = VideoModel.build(videoData) |
195 | ||
2ccaeeb3 C |
196 | const videoCreated = await video.save(sequelizeOptions) |
197 | ||
40e87e9e | 198 | // Process files |
2ccaeeb3 C |
199 | const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject) |
200 | if (videoFileAttributes.length === 0) { | |
201 | throw new Error('Cannot find valid files for video %s ' + videoObject.url) | |
202 | } | |
203 | ||
40e87e9e C |
204 | const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t })) |
205 | await Promise.all(videoFilePromises) | |
2ccaeeb3 | 206 | |
40e87e9e | 207 | // Process tags |
2ccaeeb3 C |
208 | const tags = videoObject.tag.map(t => t.name) |
209 | const tagInstances = await TagModel.findOrCreateTags(tags, t) | |
210 | await videoCreated.$set('Tags', tagInstances, sequelizeOptions) | |
211 | ||
40e87e9e C |
212 | // Process captions |
213 | const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => { | |
214 | return VideoCaptionModel.insertOrReplaceLanguage(videoCreated.id, c.identifier, t) | |
215 | }) | |
216 | await Promise.all(videoCaptionsPromises) | |
217 | ||
2ccaeeb3 C |
218 | logger.info('Remote video with uuid %s inserted.', videoObject.uuid) |
219 | ||
220 | videoCreated.VideoChannel = channelActor.VideoChannel | |
221 | return videoCreated | |
222 | }) | |
f6eebcb3 C |
223 | |
224 | const p = generateThumbnailFromUrl(videoCreated, videoObject.icon) | |
225 | .catch(err => logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err })) | |
226 | ||
227 | if (waitThumbnail === true) await p | |
228 | ||
229 | return videoCreated | |
0032ebe9 C |
230 | } |
231 | ||
f6eebcb3 C |
232 | type SyncParam = { |
233 | likes: boolean, | |
234 | dislikes: boolean, | |
235 | shares: boolean, | |
236 | comments: boolean, | |
237 | thumbnail: boolean | |
238 | } | |
239 | async function getOrCreateAccountAndVideoAndChannel ( | |
240 | videoObject: VideoTorrentObject | string, | |
241 | syncParam: SyncParam = { likes: true, dislikes: true, shares: true, comments: true, thumbnail: true } | |
242 | ) { | |
2186386c C |
243 | const videoUrl = typeof videoObject === 'string' ? videoObject : videoObject.id |
244 | ||
245 | const videoFromDatabase = await VideoModel.loadByUrlAndPopulateAccount(videoUrl) | |
f6eebcb3 | 246 | if (videoFromDatabase) return { video: videoFromDatabase } |
2ccaeeb3 | 247 | |
f6eebcb3 C |
248 | const fetchedVideo = await fetchRemoteVideo(videoUrl) |
249 | if (!fetchedVideo) throw new Error('Cannot fetch remote video with url: ' + videoUrl) | |
2186386c | 250 | |
f6eebcb3 C |
251 | const channelActor = await getOrCreateVideoChannel(fetchedVideo) |
252 | const video = await retryTransactionWrapper(getOrCreateVideo, fetchedVideo, channelActor, syncParam.thumbnail) | |
2ccaeeb3 | 253 | |
f6eebcb3 | 254 | // Process outside the transaction because we could fetch remote data |
2ccaeeb3 | 255 | |
f6eebcb3 | 256 | logger.info('Adding likes/dislikes/shares/comments of video %s.', video.uuid) |
2ccaeeb3 | 257 | |
f6eebcb3 | 258 | const jobPayloads: ActivitypubHttpFetcherPayload[] = [] |
2ccaeeb3 | 259 | |
f6eebcb3 C |
260 | if (syncParam.likes === true) { |
261 | await crawlCollectionPage<string>(fetchedVideo.likes, items => createRates(items, video, 'like')) | |
262 | .catch(err => logger.error('Cannot add likes of video %s.', video.uuid, { err })) | |
263 | } else { | |
264 | jobPayloads.push({ uri: fetchedVideo.likes, videoId: video.id, type: 'video-likes' as 'video-likes' }) | |
265 | } | |
7acee6f1 | 266 | |
f6eebcb3 C |
267 | if (syncParam.dislikes === true) { |
268 | await crawlCollectionPage<string>(fetchedVideo.dislikes, items => createRates(items, video, 'dislike')) | |
269 | .catch(err => logger.error('Cannot add dislikes of video %s.', video.uuid, { err })) | |
270 | } else { | |
271 | jobPayloads.push({ uri: fetchedVideo.dislikes, videoId: video.id, type: 'video-dislikes' as 'video-dislikes' }) | |
272 | } | |
273 | ||
274 | if (syncParam.shares === true) { | |
275 | await crawlCollectionPage<string>(fetchedVideo.shares, items => addVideoShares(items, video)) | |
276 | .catch(err => logger.error('Cannot add shares of video %s.', video.uuid, { err })) | |
277 | } else { | |
278 | jobPayloads.push({ uri: fetchedVideo.shares, videoId: video.id, type: 'video-shares' as 'video-shares' }) | |
279 | } | |
7acee6f1 | 280 | |
f6eebcb3 C |
281 | if (syncParam.comments === true) { |
282 | await crawlCollectionPage<string>(fetchedVideo.comments, items => addVideoComments(items, video)) | |
283 | .catch(err => logger.error('Cannot add comments of video %s.', video.uuid, { err })) | |
284 | } else { | |
285 | jobPayloads.push({ uri: fetchedVideo.shares, videoId: video.id, type: 'video-shares' as 'video-shares' }) | |
286 | } | |
7acee6f1 | 287 | |
f6eebcb3 | 288 | await Bluebird.map(jobPayloads, payload => JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload })) |
7acee6f1 | 289 | |
f6eebcb3 | 290 | return { video } |
2ccaeeb3 C |
291 | } |
292 | ||
7acee6f1 C |
293 | async function createRates (actorUrls: string[], video: VideoModel, rate: VideoRateType) { |
294 | let rateCounts = 0 | |
7acee6f1 | 295 | |
f6eebcb3 C |
296 | await Bluebird.map(actorUrls, async actorUrl => { |
297 | try { | |
298 | const actor = await getOrCreateActorAndServerAndModel(actorUrl) | |
299 | const [ , created ] = await AccountVideoRateModel | |
300 | .findOrCreate({ | |
301 | where: { | |
302 | videoId: video.id, | |
303 | accountId: actor.Account.id | |
304 | }, | |
305 | defaults: { | |
306 | videoId: video.id, | |
307 | accountId: actor.Account.id, | |
308 | type: rate | |
309 | } | |
310 | }) | |
311 | ||
312 | if (created) rateCounts += 1 | |
313 | } catch (err) { | |
314 | logger.warn('Cannot add rate %s for actor %s.', rate, actorUrl, { err }) | |
315 | } | |
316 | }, { concurrency: CRAWL_REQUEST_CONCURRENCY }) | |
7acee6f1 C |
317 | |
318 | logger.info('Adding %d %s to video %s.', rateCounts, rate, video.uuid) | |
319 | ||
320 | // This is "likes" and "dislikes" | |
3ac046e2 | 321 | if (rateCounts !== 0) await video.increment(rate + 's', { by: rateCounts }) |
7acee6f1 C |
322 | |
323 | return | |
324 | } | |
325 | ||
8fffe21a | 326 | async function addVideoShares (shareUrls: string[], instance: VideoModel) { |
f6eebcb3 C |
327 | await Bluebird.map(shareUrls, async shareUrl => { |
328 | try { | |
329 | // Fetch url | |
330 | const { body } = await doRequest({ | |
331 | uri: shareUrl, | |
332 | json: true, | |
333 | activityPub: true | |
334 | }) | |
335 | if (!body || !body.actor) throw new Error('Body of body actor is invalid') | |
2ccaeeb3 | 336 | |
f6eebcb3 C |
337 | const actorUrl = body.actor |
338 | const actor = await getOrCreateActorAndServerAndModel(actorUrl) | |
2ccaeeb3 | 339 | |
f6eebcb3 C |
340 | const entry = { |
341 | actorId: actor.id, | |
342 | videoId: instance.id, | |
8dfd8fd7 | 343 | url: shareUrl |
f6eebcb3 C |
344 | } |
345 | ||
346 | await VideoShareModel.findOrCreate({ | |
347 | where: { | |
348 | url: shareUrl | |
349 | }, | |
350 | defaults: entry | |
351 | }) | |
352 | } catch (err) { | |
353 | logger.warn('Cannot add share %s.', shareUrl, { err }) | |
354 | } | |
355 | }, { concurrency: CRAWL_REQUEST_CONCURRENCY }) | |
0032ebe9 C |
356 | } |
357 | ||
2ccaeeb3 C |
358 | async function fetchRemoteVideo (videoUrl: string): Promise<VideoTorrentObject> { |
359 | const options = { | |
360 | uri: videoUrl, | |
361 | method: 'GET', | |
362 | json: true, | |
363 | activityPub: true | |
364 | } | |
365 | ||
366 | logger.info('Fetching remote video %s.', videoUrl) | |
367 | ||
368 | const { body } = await doRequest(options) | |
369 | ||
1d6e5dfc | 370 | if (sanitizeAndCheckVideoTorrentObject(body) === false) { |
2ccaeeb3 C |
371 | logger.debug('Remote video JSON is not valid.', { body }) |
372 | return undefined | |
373 | } | |
374 | ||
375 | return body | |
892211e8 | 376 | } |
2186386c C |
377 | |
378 | export { | |
379 | federateVideoIfNeeded, | |
380 | fetchRemoteVideo, | |
381 | getOrCreateAccountAndVideoAndChannel, | |
40e87e9e | 382 | fetchRemoteVideoStaticFile, |
2186386c C |
383 | fetchRemoteVideoDescription, |
384 | generateThumbnailFromUrl, | |
385 | videoActivityObjectToDBAttributes, | |
386 | videoFileActivityUrlToDBAttributes, | |
387 | getOrCreateVideo, | |
388 | getOrCreateVideoChannel, | |
f6eebcb3 C |
389 | addVideoShares, |
390 | createRates | |
2186386c | 391 | } |