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