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