Fix fps federation
[oweals/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, REMOTE_SCHEME, sequelizeTypescript, STATIC_PATHS, 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
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) {
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
41     if (isNewVideo) {
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 }
50
51 function fetchRemoteVideoStaticFile (video: VideoModel, path: string, reject: Function) {
52   const host = video.VideoChannel.Account.Actor.Server.host
53
54   // We need to provide a callback, if no we could have an uncaught exception
55   return request.get(REMOTE_SCHEME.HTTP + '://' + host + path, err => {
56     if (err) reject(err)
57   })
58 }
59
60 async function fetchRemoteVideoDescription (video: VideoModel) {
61   const host = video.VideoChannel.Account.Actor.Server.host
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
72 function generateThumbnailFromUrl (video: VideoModel, icon: ActivityIconObject) {
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
83 async function videoActivityObjectToDBAttributes (
84   videoChannel: VideoChannelModel,
85   videoObject: VideoTorrentObject,
86   to: string[] = []
87 ) {
88   const privacy = to.indexOf(ACTIVITY_PUB.PUBLIC) !== -1 ? VideoPrivacy.PUBLIC : VideoPrivacy.UNLISTED
89   const duration = videoObject.duration.replace(/[^\d]+/, '')
90
91   let language: string | undefined
92   if (videoObject.language) {
93     language = videoObject.language.identifier
94   }
95
96   let category: number | undefined
97   if (videoObject.category) {
98     category = parseInt(videoObject.category.identifier, 10)
99   }
100
101   let licence: number | undefined
102   if (videoObject.licence) {
103     licence = parseInt(videoObject.licence.identifier, 10)
104   }
105
106   const description = videoObject.content || null
107   const support = videoObject.support || null
108
109   return {
110     name: videoObject.name,
111     uuid: videoObject.uuid,
112     url: videoObject.id,
113     category,
114     licence,
115     language,
116     description,
117     support,
118     nsfw: videoObject.sensitive,
119     commentsEnabled: videoObject.commentsEnabled,
120     waitTranscoding: videoObject.waitTranscoding,
121     state: videoObject.state,
122     channelId: videoChannel.id,
123     duration: parseInt(duration, 10),
124     createdAt: new Date(videoObject.published),
125     publishedAt: new Date(videoObject.published),
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
146   const attributes: VideoFileModel[] = []
147   for (const fileUrl of fileUrls) {
148     // Fetch associated magnet uri
149     const magnet = videoObject.url.find(u => {
150       return u.mimeType === 'application/x-bittorrent;x-scheme-handler/magnet' && u.width === fileUrl.width
151     })
152
153     if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
154
155     const parsed = magnetUtil.decode(magnet.href)
156     if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) {
157       throw new Error('Cannot parse magnet URI ' + magnet.href)
158     }
159
160     const attribute = {
161       extname: VIDEO_MIMETYPE_EXT[ fileUrl.mimeType ],
162       infoHash: parsed.infoHash,
163       resolution: fileUrl.width,
164       size: fileUrl.size,
165       videoId: videoCreated.id,
166       fps: fileUrl.fps
167     } as VideoFileModel
168     attributes.push(attribute)
169   }
170
171   return attributes
172 }
173
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
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
191     const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to)
192     const video = VideoModel.build(videoData)
193
194     // Don't block on remote HTTP request (we are in a transaction!)
195     generateThumbnailFromUrl(video, videoObject.icon)
196       .catch(err => logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err }))
197
198     const videoCreated = await video.save(sequelizeOptions)
199
200     // Process files
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
206     const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
207     await Promise.all(videoFilePromises)
208
209     // Process tags
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
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
220     logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
221
222     videoCreated.VideoChannel = channelActor.VideoChannel
223     return videoCreated
224   })
225 }
226
227 async function getOrCreateAccountAndVideoAndChannel (videoObject: VideoTorrentObject | string, actor?: ActorModel) {
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
236     }
237   }
238
239   videoObject = await fetchRemoteVideo(videoUrl)
240   if (!videoObject) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
241
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
249   const channelActor = await getOrCreateVideoChannel(videoObject)
250
251   const video = await retryTransactionWrapper(getOrCreateVideo, videoObject, channelActor)
252
253   // Process outside the transaction because we could fetch remote data
254   logger.info('Adding likes of video %s.', video.uuid)
255   await crawlCollectionPage<string>(videoObject.likes, (items) => createRates(items, video, 'like'))
256
257   logger.info('Adding dislikes of video %s.', video.uuid)
258   await crawlCollectionPage<string>(videoObject.dislikes, (items) => createRates(items, video, 'dislike'))
259
260   logger.info('Adding shares of video %s.', video.uuid)
261   await crawlCollectionPage<string>(videoObject.shares, (items) => addVideoShares(items, video))
262
263   logger.info('Adding comments of video %s.', video.uuid)
264   await crawlCollectionPage<string>(videoObject.comments, (items) => addVideoComments(items, video))
265
266   return { actor, channelActor, video }
267 }
268
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"
291   if (rateCounts !== 0) await video.increment(rate + 's', { by: rateCounts })
292
293   return
294 }
295
296 async function addVideoShares (shareUrls: string[], instance: VideoModel) {
297   for (const shareUrl of shareUrls) {
298     // Fetch url
299     const { body } = await doRequest({
300       uri: shareUrl,
301       json: true,
302       activityPub: true
303     })
304     if (!body || !body.actor) {
305       logger.warn('Cannot add remote share with url: %s, skipping...', shareUrl)
306       continue
307     }
308
309     const actorUrl = body.actor
310     const actor = await getOrCreateActorAndServerAndModel(actorUrl)
311
312     const entry = {
313       actorId: actor.id,
314       videoId: instance.id,
315       url: shareUrl
316     }
317
318     await VideoShareModel.findOrCreate({
319       where: {
320         url: shareUrl
321       },
322       defaults: entry
323     })
324   }
325 }
326
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
339   if (sanitizeAndCheckVideoTorrentObject(body) === false) {
340     logger.debug('Remote video JSON is not valid.', { body })
341     return undefined
342   }
343
344   return body
345 }
346
347 export {
348   federateVideoIfNeeded,
349   fetchRemoteVideo,
350   getOrCreateAccountAndVideoAndChannel,
351   fetchRemoteVideoStaticFile,
352   fetchRemoteVideoDescription,
353   generateThumbnailFromUrl,
354   videoActivityObjectToDBAttributes,
355   videoFileActivityUrlToDBAttributes,
356   getOrCreateVideo,
357   getOrCreateVideoChannel,
358   addVideoShares
359 }