]>
Commit | Line | Data |
---|---|---|
7acee6f1 | 1 | import * as Bluebird from 'bluebird' |
2ccaeeb3 | 2 | import * as magnetUtil from 'magnet-uri' |
892211e8 C |
3 | import { join } from 'path' |
4 | import * as request from 'request' | |
5 | import { ActivityIconObject } from '../../../shared/index' | |
2ccaeeb3 | 6 | import { VideoTorrentObject } from '../../../shared/models/activitypub/objects' |
7acee6f1 | 7 | import { VideoPrivacy, VideoRateType } from '../../../shared/models/videos' |
2ccaeeb3 C |
8 | import { isVideoTorrentObjectValid } from '../../helpers/custom-validators/activitypub/videos' |
9 | import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos' | |
10 | import { retryTransactionWrapper } from '../../helpers/database-utils' | |
11 | import { logger } from '../../helpers/logger' | |
da854ddd | 12 | import { doRequest, doRequestAndSaveToFile } from '../../helpers/requests' |
2ccaeeb3 | 13 | import { ACTIVITY_PUB, CONFIG, REMOTE_SCHEME, sequelizeTypescript, STATIC_PATHS, VIDEO_MIMETYPE_EXT } from '../../initializers' |
7acee6f1 | 14 | import { AccountVideoRateModel } from '../../models/account/account-video-rate' |
2ccaeeb3 C |
15 | import { ActorModel } from '../../models/activitypub/actor' |
16 | import { TagModel } from '../../models/video/tag' | |
3fd3ab2d | 17 | import { VideoModel } from '../../models/video/video' |
2ccaeeb3 C |
18 | import { VideoChannelModel } from '../../models/video/video-channel' |
19 | import { VideoFileModel } from '../../models/video/video-file' | |
20 | import { VideoShareModel } from '../../models/video/video-share' | |
21 | import { getOrCreateActorAndServerAndModel } from './actor' | |
7acee6f1 | 22 | import { addVideoComments } from './video-comments' |
892211e8 | 23 | |
d50acfab | 24 | function fetchRemoteVideoPreview (video: VideoModel, reject: Function) { |
50d6de9c | 25 | const host = video.VideoChannel.Account.Actor.Server.host |
892211e8 C |
26 | const path = join(STATIC_PATHS.PREVIEWS, video.getPreviewName()) |
27 | ||
f05a1c30 | 28 | // We need to provide a callback, if no we could have an uncaught exception |
f40bbe31 C |
29 | return request.get(REMOTE_SCHEME.HTTP + '://' + host + path, err => { |
30 | if (err) reject(err) | |
31 | }) | |
892211e8 C |
32 | } |
33 | ||
3fd3ab2d | 34 | async function fetchRemoteVideoDescription (video: VideoModel) { |
50d6de9c | 35 | const host = video.VideoChannel.Account.Actor.Server.host |
892211e8 C |
36 | const path = video.getDescriptionPath() |
37 | const options = { | |
38 | uri: REMOTE_SCHEME.HTTP + '://' + host + path, | |
39 | json: true | |
40 | } | |
41 | ||
42 | const { body } = await doRequest(options) | |
43 | return body.description ? body.description : '' | |
44 | } | |
45 | ||
3fd3ab2d | 46 | function generateThumbnailFromUrl (video: VideoModel, icon: ActivityIconObject) { |
892211e8 C |
47 | const thumbnailName = video.getThumbnailName() |
48 | const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName) | |
49 | ||
50 | const options = { | |
51 | method: 'GET', | |
52 | uri: icon.url | |
53 | } | |
54 | return doRequestAndSaveToFile(options, thumbnailPath) | |
55 | } | |
56 | ||
2ccaeeb3 C |
57 | async function videoActivityObjectToDBAttributes (videoChannel: VideoChannelModel, |
58 | videoObject: VideoTorrentObject, | |
276d03ed C |
59 | to: string[] = []) { |
60 | const privacy = to.indexOf(ACTIVITY_PUB.PUBLIC) !== -1 ? VideoPrivacy.PUBLIC : VideoPrivacy.UNLISTED | |
2ccaeeb3 | 61 | const duration = videoObject.duration.replace(/[^\d]+/, '') |
9d3ef9fe C |
62 | |
63 | let language: string = null | |
2ccaeeb3 | 64 | if (videoObject.language) { |
9d3ef9fe | 65 | language = videoObject.language.identifier |
2ccaeeb3 C |
66 | } |
67 | ||
9d3ef9fe | 68 | let category: number = null |
2ccaeeb3 C |
69 | if (videoObject.category) { |
70 | category = parseInt(videoObject.category.identifier, 10) | |
71 | } | |
72 | ||
9d3ef9fe | 73 | let licence: number = null |
2ccaeeb3 C |
74 | if (videoObject.licence) { |
75 | licence = parseInt(videoObject.licence.identifier, 10) | |
76 | } | |
77 | ||
276d03ed C |
78 | const description = videoObject.content || null |
79 | const support = videoObject.support || null | |
2422c46b | 80 | |
2ccaeeb3 C |
81 | return { |
82 | name: videoObject.name, | |
83 | uuid: videoObject.uuid, | |
84 | url: videoObject.id, | |
85 | category, | |
86 | licence, | |
87 | language, | |
88 | description, | |
2422c46b | 89 | support, |
0a67e28b | 90 | nsfw: videoObject.sensitive, |
2ccaeeb3 C |
91 | commentsEnabled: videoObject.commentsEnabled, |
92 | channelId: videoChannel.id, | |
93 | duration: parseInt(duration, 10), | |
94 | createdAt: new Date(videoObject.published), | |
95 | // FIXME: updatedAt does not seems to be considered by Sequelize | |
96 | updatedAt: new Date(videoObject.updated), | |
97 | views: videoObject.views, | |
98 | likes: 0, | |
99 | dislikes: 0, | |
100 | remote: true, | |
101 | privacy | |
102 | } | |
103 | } | |
104 | ||
105 | function videoFileActivityUrlToDBAttributes (videoCreated: VideoModel, videoObject: VideoTorrentObject) { | |
106 | const mimeTypes = Object.keys(VIDEO_MIMETYPE_EXT) | |
107 | const fileUrls = videoObject.url.filter(u => { | |
108 | return mimeTypes.indexOf(u.mimeType) !== -1 && u.mimeType.startsWith('video/') | |
109 | }) | |
110 | ||
111 | if (fileUrls.length === 0) { | |
112 | throw new Error('Cannot find video files for ' + videoCreated.url) | |
113 | } | |
114 | ||
115 | const attributes = [] | |
116 | for (const fileUrl of fileUrls) { | |
117 | // Fetch associated magnet uri | |
118 | const magnet = videoObject.url.find(u => { | |
119 | return u.mimeType === 'application/x-bittorrent;x-scheme-handler/magnet' && u.width === fileUrl.width | |
120 | }) | |
121 | ||
9fb3abfd | 122 | if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href) |
2ccaeeb3 | 123 | |
9fb3abfd C |
124 | const parsed = magnetUtil.decode(magnet.href) |
125 | if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) throw new Error('Cannot parse magnet URI ' + magnet.href) | |
2ccaeeb3 C |
126 | |
127 | const attribute = { | |
128 | extname: VIDEO_MIMETYPE_EXT[ fileUrl.mimeType ], | |
129 | infoHash: parsed.infoHash, | |
130 | resolution: fileUrl.width, | |
131 | size: fileUrl.size, | |
132 | videoId: videoCreated.id | |
133 | } | |
134 | attributes.push(attribute) | |
135 | } | |
136 | ||
137 | return attributes | |
138 | } | |
139 | ||
140 | async function getOrCreateVideo (videoObject: VideoTorrentObject, channelActor: ActorModel) { | |
141 | logger.debug('Adding remote video %s.', videoObject.id) | |
142 | ||
143 | return sequelizeTypescript.transaction(async t => { | |
144 | const sequelizeOptions = { | |
145 | transaction: t | |
146 | } | |
147 | const videoFromDatabase = await VideoModel.loadByUUIDOrURLAndPopulateAccount(videoObject.uuid, videoObject.id, t) | |
148 | if (videoFromDatabase) return videoFromDatabase | |
149 | ||
276d03ed | 150 | const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to) |
2ccaeeb3 C |
151 | const video = VideoModel.build(videoData) |
152 | ||
153 | // Don't block on request | |
154 | generateThumbnailFromUrl(video, videoObject.icon) | |
d5b7d911 | 155 | .catch(err => logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err })) |
2ccaeeb3 C |
156 | |
157 | const videoCreated = await video.save(sequelizeOptions) | |
158 | ||
159 | const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject) | |
160 | if (videoFileAttributes.length === 0) { | |
161 | throw new Error('Cannot find valid files for video %s ' + videoObject.url) | |
162 | } | |
163 | ||
1f7ab4f3 | 164 | const tasks = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t })) |
2ccaeeb3 C |
165 | await Promise.all(tasks) |
166 | ||
167 | const tags = videoObject.tag.map(t => t.name) | |
168 | const tagInstances = await TagModel.findOrCreateTags(tags, t) | |
169 | await videoCreated.$set('Tags', tagInstances, sequelizeOptions) | |
170 | ||
171 | logger.info('Remote video with uuid %s inserted.', videoObject.uuid) | |
172 | ||
173 | videoCreated.VideoChannel = channelActor.VideoChannel | |
174 | return videoCreated | |
175 | }) | |
0032ebe9 C |
176 | } |
177 | ||
2ccaeeb3 C |
178 | async function getOrCreateAccountAndVideoAndChannel (videoObject: VideoTorrentObject | string, actor?: ActorModel) { |
179 | if (typeof videoObject === 'string') { | |
8e8234ab C |
180 | const videoUrl = videoObject |
181 | ||
182 | const videoFromDatabase = await VideoModel.loadByUrlAndPopulateAccount(videoUrl) | |
2ccaeeb3 C |
183 | if (videoFromDatabase) { |
184 | return { | |
185 | video: videoFromDatabase, | |
186 | actor: videoFromDatabase.VideoChannel.Account.Actor, | |
187 | channelActor: videoFromDatabase.VideoChannel.Actor | |
188 | } | |
189 | } | |
190 | ||
8e8234ab C |
191 | videoObject = await fetchRemoteVideo(videoUrl) |
192 | if (!videoObject) throw new Error('Cannot fetch remote video with url: ' + videoUrl) | |
2ccaeeb3 C |
193 | } |
194 | ||
195 | if (!actor) { | |
196 | const actorObj = videoObject.attributedTo.find(a => a.type === 'Person') | |
197 | if (!actorObj) throw new Error('Cannot find associated actor to video ' + videoObject.url) | |
198 | ||
199 | actor = await getOrCreateActorAndServerAndModel(actorObj.id) | |
200 | } | |
201 | ||
202 | const channel = videoObject.attributedTo.find(a => a.type === 'Group') | |
203 | if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url) | |
204 | ||
205 | const channelActor = await getOrCreateActorAndServerAndModel(channel.id) | |
206 | ||
207 | const options = { | |
208 | arguments: [ videoObject, channelActor ], | |
209 | errorMessage: 'Cannot insert the remote video with many retries.' | |
210 | } | |
211 | ||
212 | const video = await retryTransactionWrapper(getOrCreateVideo, options) | |
213 | ||
7acee6f1 C |
214 | // Process outside the transaction because we could fetch remote data |
215 | if (videoObject.likes && Array.isArray(videoObject.likes.orderedItems)) { | |
216 | logger.info('Adding likes of video %s.', video.uuid) | |
217 | await createRates(videoObject.likes.orderedItems, video, 'like') | |
218 | } | |
219 | ||
220 | if (videoObject.dislikes && Array.isArray(videoObject.dislikes.orderedItems)) { | |
221 | logger.info('Adding dislikes of video %s.', video.uuid) | |
222 | await createRates(videoObject.dislikes.orderedItems, video, 'dislike') | |
223 | } | |
224 | ||
225 | if (videoObject.shares && Array.isArray(videoObject.shares.orderedItems)) { | |
226 | logger.info('Adding shares of video %s.', video.uuid) | |
227 | await addVideoShares(video, videoObject.shares.orderedItems) | |
228 | } | |
229 | ||
230 | if (videoObject.comments && Array.isArray(videoObject.comments.orderedItems)) { | |
231 | logger.info('Adding comments of video %s.', video.uuid) | |
232 | await addVideoComments(video, videoObject.comments.orderedItems) | |
233 | } | |
234 | ||
2ccaeeb3 C |
235 | return { actor, channelActor, video } |
236 | } | |
237 | ||
7acee6f1 C |
238 | async function createRates (actorUrls: string[], video: VideoModel, rate: VideoRateType) { |
239 | let rateCounts = 0 | |
240 | const tasks: Bluebird<number>[] = [] | |
241 | ||
242 | for (const actorUrl of actorUrls) { | |
243 | const actor = await getOrCreateActorAndServerAndModel(actorUrl) | |
244 | const p = AccountVideoRateModel | |
245 | .create({ | |
246 | videoId: video.id, | |
247 | accountId: actor.Account.id, | |
248 | type: rate | |
249 | }) | |
250 | .then(() => rateCounts += 1) | |
251 | ||
252 | tasks.push(p) | |
253 | } | |
254 | ||
255 | await Promise.all(tasks) | |
256 | ||
257 | logger.info('Adding %d %s to video %s.', rateCounts, rate, video.uuid) | |
258 | ||
259 | // This is "likes" and "dislikes" | |
260 | await video.increment(rate + 's', { by: rateCounts }) | |
261 | ||
262 | return | |
263 | } | |
264 | ||
2ccaeeb3 C |
265 | async function addVideoShares (instance: VideoModel, shareUrls: string[]) { |
266 | for (const shareUrl of shareUrls) { | |
267 | // Fetch url | |
268 | const { body } = await doRequest({ | |
269 | uri: shareUrl, | |
270 | json: true, | |
271 | activityPub: true | |
272 | }) | |
8e8234ab C |
273 | if (!body || !body.actor) { |
274 | logger.warn('Cannot add remote share with url: %s, skipping...', shareUrl) | |
275 | continue | |
276 | } | |
2ccaeeb3 | 277 | |
8e8234ab | 278 | const actorUrl = body.actor |
2ccaeeb3 C |
279 | const actor = await getOrCreateActorAndServerAndModel(actorUrl) |
280 | ||
281 | const entry = { | |
282 | actorId: actor.id, | |
8dfd8fd7 C |
283 | videoId: instance.id, |
284 | url: shareUrl | |
2ccaeeb3 C |
285 | } |
286 | ||
287 | await VideoShareModel.findOrCreate({ | |
8dfd8fd7 C |
288 | where: { |
289 | url: shareUrl | |
290 | }, | |
2ccaeeb3 C |
291 | defaults: entry |
292 | }) | |
293 | } | |
0032ebe9 C |
294 | } |
295 | ||
892211e8 | 296 | export { |
2ccaeeb3 | 297 | getOrCreateAccountAndVideoAndChannel, |
892211e8 C |
298 | fetchRemoteVideoPreview, |
299 | fetchRemoteVideoDescription, | |
0032ebe9 | 300 | generateThumbnailFromUrl, |
2ccaeeb3 C |
301 | videoActivityObjectToDBAttributes, |
302 | videoFileActivityUrlToDBAttributes, | |
303 | getOrCreateVideo, | |
304 | addVideoShares} | |
305 | ||
306 | // --------------------------------------------------------------------------- | |
307 | ||
308 | async function fetchRemoteVideo (videoUrl: string): Promise<VideoTorrentObject> { | |
309 | const options = { | |
310 | uri: videoUrl, | |
311 | method: 'GET', | |
312 | json: true, | |
313 | activityPub: true | |
314 | } | |
315 | ||
316 | logger.info('Fetching remote video %s.', videoUrl) | |
317 | ||
318 | const { body } = await doRequest(options) | |
319 | ||
320 | if (isVideoTorrentObjectValid(body) === false) { | |
321 | logger.debug('Remote video JSON is not valid.', { body }) | |
322 | return undefined | |
323 | } | |
324 | ||
325 | return body | |
892211e8 | 326 | } |