]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/activitypub/videos.ts
Add ability to search a video with an URL
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / videos.ts
1 import * as Bluebird from 'bluebird'
2 import * as sequelize from 'sequelize'
3 import * as magnetUtil from 'magnet-uri'
4 import { join } from 'path'
5 import * as request from 'request'
6 import { ActivityIconObject, VideoState } from '../../../shared/index'
7 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
8 import { VideoPrivacy, VideoRateType } from '../../../shared/models/videos'
9 import { sanitizeAndCheckVideoTorrentObject } from '../../helpers/custom-validators/activitypub/videos'
10 import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
11 import { retryTransactionWrapper } from '../../helpers/database-utils'
12 import { logger } from '../../helpers/logger'
13 import { doRequest, doRequestAndSaveToFile } from '../../helpers/requests'
14 import { ACTIVITY_PUB, CONFIG, CRAWL_REQUEST_CONCURRENCY, REMOTE_SCHEME, sequelizeTypescript, VIDEO_MIMETYPE_EXT } from '../../initializers'
15 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
16 import { ActorModel } from '../../models/activitypub/actor'
17 import { TagModel } from '../../models/video/tag'
18 import { VideoModel } from '../../models/video/video'
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'
23 import { addVideoComments } from './video-comments'
24 import { crawlCollectionPage } from './crawl'
25 import { sendCreateVideo, sendUpdateVideo } from './send'
26 import { shareVideoByServerAndChannel } from './index'
27 import { isArray } from '../../helpers/custom-validators/misc'
28 import { VideoCaptionModel } from '../../models/video/video-caption'
29 import { JobQueue } from '../job-queue'
30 import { ActivitypubHttpFetcherPayload } from '../job-queue/handlers/activitypub-http-fetcher'
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) {
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
43 if (isNewVideo) {
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 }
52
53 function fetchRemoteVideoStaticFile (video: VideoModel, path: string, reject: Function) {
54 const host = video.VideoChannel.Account.Actor.Server.host
55
56 // We need to provide a callback, if no we could have an uncaught exception
57 return request.get(REMOTE_SCHEME.HTTP + '://' + host + path, err => {
58 if (err) reject(err)
59 })
60 }
61
62 async function fetchRemoteVideoDescription (video: VideoModel) {
63 const host = video.VideoChannel.Account.Actor.Server.host
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
74 function generateThumbnailFromUrl (video: VideoModel, icon: ActivityIconObject) {
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
85 async function videoActivityObjectToDBAttributes (
86 videoChannel: VideoChannelModel,
87 videoObject: VideoTorrentObject,
88 to: string[] = []
89 ) {
90 const privacy = to.indexOf(ACTIVITY_PUB.PUBLIC) !== -1 ? VideoPrivacy.PUBLIC : VideoPrivacy.UNLISTED
91 const duration = videoObject.duration.replace(/[^\d]+/, '')
92
93 let language: string | undefined
94 if (videoObject.language) {
95 language = videoObject.language.identifier
96 }
97
98 let category: number | undefined
99 if (videoObject.category) {
100 category = parseInt(videoObject.category.identifier, 10)
101 }
102
103 let licence: number | undefined
104 if (videoObject.licence) {
105 licence = parseInt(videoObject.licence.identifier, 10)
106 }
107
108 const description = videoObject.content || null
109 const support = videoObject.support || null
110
111 return {
112 name: videoObject.name,
113 uuid: videoObject.uuid,
114 url: videoObject.id,
115 category,
116 licence,
117 language,
118 description,
119 support,
120 nsfw: videoObject.sensitive,
121 commentsEnabled: videoObject.commentsEnabled,
122 waitTranscoding: videoObject.waitTranscoding,
123 state: videoObject.state,
124 channelId: videoChannel.id,
125 duration: parseInt(duration, 10),
126 createdAt: new Date(videoObject.published),
127 publishedAt: new Date(videoObject.published),
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
148 const attributes: VideoFileModel[] = []
149 for (const fileUrl of fileUrls) {
150 // Fetch associated magnet uri
151 const magnet = videoObject.url.find(u => {
152 return u.mimeType === 'application/x-bittorrent;x-scheme-handler/magnet' && u.height === fileUrl.height
153 })
154
155 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
156
157 const parsed = magnetUtil.decode(magnet.href)
158 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) {
159 throw new Error('Cannot parse magnet URI ' + magnet.href)
160 }
161
162 const attribute = {
163 extname: VIDEO_MIMETYPE_EXT[ fileUrl.mimeType ],
164 infoHash: parsed.infoHash,
165 resolution: fileUrl.height,
166 size: fileUrl.size,
167 videoId: videoCreated.id,
168 fps: fileUrl.fps
169 } as VideoFileModel
170 attributes.push(attribute)
171 }
172
173 return attributes
174 }
175
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
183 async function getOrCreateVideo (videoObject: VideoTorrentObject, channelActor: ActorModel, waitThumbnail = false) {
184 logger.debug('Adding remote video %s.', videoObject.id)
185
186 const videoCreated: VideoModel = await sequelizeTypescript.transaction(async t => {
187 const sequelizeOptions = {
188 transaction: t
189 }
190 const videoFromDatabase = await VideoModel.loadByUUIDOrURLAndPopulateAccount(videoObject.uuid, videoObject.id, t)
191 if (videoFromDatabase) return videoFromDatabase
192
193 const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to)
194 const video = VideoModel.build(videoData)
195
196 const videoCreated = await video.save(sequelizeOptions)
197
198 // Process files
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
204 const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
205 await Promise.all(videoFilePromises)
206
207 // Process tags
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
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
218 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
219
220 videoCreated.VideoChannel = channelActor.VideoChannel
221 return videoCreated
222 })
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
230 }
231
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 ) {
243 const videoUrl = typeof videoObject === 'string' ? videoObject : videoObject.id
244
245 const videoFromDatabase = await VideoModel.loadByUrlAndPopulateAccount(videoUrl)
246 if (videoFromDatabase) return { video: videoFromDatabase }
247
248 const fetchedVideo = await fetchRemoteVideo(videoUrl)
249 if (!fetchedVideo) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
250
251 const channelActor = await getOrCreateVideoChannel(fetchedVideo)
252 const video = await retryTransactionWrapper(getOrCreateVideo, fetchedVideo, channelActor, syncParam.thumbnail)
253
254 // Process outside the transaction because we could fetch remote data
255
256 logger.info('Adding likes/dislikes/shares/comments of video %s.', video.uuid)
257
258 const jobPayloads: ActivitypubHttpFetcherPayload[] = []
259
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 }
266
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 }
280
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 }
287
288 await Bluebird.map(jobPayloads, payload => JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload }))
289
290 return { video }
291 }
292
293 async function createRates (actorUrls: string[], video: VideoModel, rate: VideoRateType) {
294 let rateCounts = 0
295
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 })
317
318 logger.info('Adding %d %s to video %s.', rateCounts, rate, video.uuid)
319
320 // This is "likes" and "dislikes"
321 if (rateCounts !== 0) await video.increment(rate + 's', { by: rateCounts })
322
323 return
324 }
325
326 async function addVideoShares (shareUrls: string[], instance: VideoModel) {
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')
336
337 const actorUrl = body.actor
338 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
339
340 const entry = {
341 actorId: actor.id,
342 videoId: instance.id,
343 url: shareUrl
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 })
356 }
357
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
370 if (sanitizeAndCheckVideoTorrentObject(body) === false) {
371 logger.debug('Remote video JSON is not valid.', { body })
372 return undefined
373 }
374
375 return body
376 }
377
378 export {
379 federateVideoIfNeeded,
380 fetchRemoteVideo,
381 getOrCreateAccountAndVideoAndChannel,
382 fetchRemoteVideoStaticFile,
383 fetchRemoteVideoDescription,
384 generateThumbnailFromUrl,
385 videoActivityObjectToDBAttributes,
386 videoFileActivityUrlToDBAttributes,
387 getOrCreateVideo,
388 getOrCreateVideoChannel,
389 addVideoShares,
390 createRates
391 }