Fix last commit
[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     } as VideoFileModel
167     attributes.push(attribute)
168   }
169
170   return attributes
171 }
172
173 function getOrCreateVideoChannel (videoObject: VideoTorrentObject) {
174   const channel = videoObject.attributedTo.find(a => a.type === 'Group')
175   if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
176
177   return getOrCreateActorAndServerAndModel(channel.id)
178 }
179
180 async function getOrCreateVideo (videoObject: VideoTorrentObject, channelActor: ActorModel) {
181   logger.debug('Adding remote video %s.', videoObject.id)
182
183   return sequelizeTypescript.transaction(async t => {
184     const sequelizeOptions = {
185       transaction: t
186     }
187     const videoFromDatabase = await VideoModel.loadByUUIDOrURLAndPopulateAccount(videoObject.uuid, videoObject.id, t)
188     if (videoFromDatabase) return videoFromDatabase
189
190     const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to)
191     const video = VideoModel.build(videoData)
192
193     // Don't block on remote HTTP request (we are in a transaction!)
194     generateThumbnailFromUrl(video, videoObject.icon)
195       .catch(err => logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err }))
196
197     const videoCreated = await video.save(sequelizeOptions)
198
199     // Process files
200     const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject)
201     if (videoFileAttributes.length === 0) {
202       throw new Error('Cannot find valid files for video %s ' + videoObject.url)
203     }
204
205     const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
206     await Promise.all(videoFilePromises)
207
208     // Process tags
209     const tags = videoObject.tag.map(t => t.name)
210     const tagInstances = await TagModel.findOrCreateTags(tags, t)
211     await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
212
213     // Process captions
214     const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
215       return VideoCaptionModel.insertOrReplaceLanguage(videoCreated.id, c.identifier, t)
216     })
217     await Promise.all(videoCaptionsPromises)
218
219     logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
220
221     videoCreated.VideoChannel = channelActor.VideoChannel
222     return videoCreated
223   })
224 }
225
226 async function getOrCreateAccountAndVideoAndChannel (videoObject: VideoTorrentObject | string, actor?: ActorModel) {
227   const videoUrl = typeof videoObject === 'string' ? videoObject : videoObject.id
228
229   const videoFromDatabase = await VideoModel.loadByUrlAndPopulateAccount(videoUrl)
230   if (videoFromDatabase) {
231     return {
232       video: videoFromDatabase,
233       actor: videoFromDatabase.VideoChannel.Account.Actor,
234       channelActor: videoFromDatabase.VideoChannel.Actor
235     }
236   }
237
238   videoObject = await fetchRemoteVideo(videoUrl)
239   if (!videoObject) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
240
241   if (!actor) {
242     const actorObj = videoObject.attributedTo.find(a => a.type === 'Person')
243     if (!actorObj) throw new Error('Cannot find associated actor to video ' + videoObject.url)
244
245     actor = await getOrCreateActorAndServerAndModel(actorObj.id)
246   }
247
248   const channelActor = await getOrCreateVideoChannel(videoObject)
249
250   const video = await retryTransactionWrapper(getOrCreateVideo, videoObject, channelActor)
251
252   // Process outside the transaction because we could fetch remote data
253   logger.info('Adding likes of video %s.', video.uuid)
254   await crawlCollectionPage<string>(videoObject.likes, (items) => createRates(items, video, 'like'))
255
256   logger.info('Adding dislikes of video %s.', video.uuid)
257   await crawlCollectionPage<string>(videoObject.dislikes, (items) => createRates(items, video, 'dislike'))
258
259   logger.info('Adding shares of video %s.', video.uuid)
260   await crawlCollectionPage<string>(videoObject.shares, (items) => addVideoShares(items, video))
261
262   logger.info('Adding comments of video %s.', video.uuid)
263   await crawlCollectionPage<string>(videoObject.comments, (items) => addVideoComments(items, video))
264
265   return { actor, channelActor, video }
266 }
267
268 async function createRates (actorUrls: string[], video: VideoModel, rate: VideoRateType) {
269   let rateCounts = 0
270   const tasks: Bluebird<number>[] = []
271
272   for (const actorUrl of actorUrls) {
273     const actor = await getOrCreateActorAndServerAndModel(actorUrl)
274     const p = AccountVideoRateModel
275       .create({
276         videoId: video.id,
277         accountId: actor.Account.id,
278         type: rate
279       })
280       .then(() => rateCounts += 1)
281
282     tasks.push(p)
283   }
284
285   await Promise.all(tasks)
286
287   logger.info('Adding %d %s to video %s.', rateCounts, rate, video.uuid)
288
289   // This is "likes" and "dislikes"
290   await video.increment(rate + 's', { by: rateCounts })
291
292   return
293 }
294
295 async function addVideoShares (shareUrls: string[], instance: VideoModel) {
296   for (const shareUrl of shareUrls) {
297     // Fetch url
298     const { body } = await doRequest({
299       uri: shareUrl,
300       json: true,
301       activityPub: true
302     })
303     if (!body || !body.actor) {
304       logger.warn('Cannot add remote share with url: %s, skipping...', shareUrl)
305       continue
306     }
307
308     const actorUrl = body.actor
309     const actor = await getOrCreateActorAndServerAndModel(actorUrl)
310
311     const entry = {
312       actorId: actor.id,
313       videoId: instance.id,
314       url: shareUrl
315     }
316
317     await VideoShareModel.findOrCreate({
318       where: {
319         url: shareUrl
320       },
321       defaults: entry
322     })
323   }
324 }
325
326 async function fetchRemoteVideo (videoUrl: string): Promise<VideoTorrentObject> {
327   const options = {
328     uri: videoUrl,
329     method: 'GET',
330     json: true,
331     activityPub: true
332   }
333
334   logger.info('Fetching remote video %s.', videoUrl)
335
336   const { body } = await doRequest(options)
337
338   if (sanitizeAndCheckVideoTorrentObject(body) === false) {
339     logger.debug('Remote video JSON is not valid.', { body })
340     return undefined
341   }
342
343   return body
344 }
345
346 export {
347   federateVideoIfNeeded,
348   fetchRemoteVideo,
349   getOrCreateAccountAndVideoAndChannel,
350   fetchRemoteVideoStaticFile,
351   fetchRemoteVideoDescription,
352   generateThumbnailFromUrl,
353   videoActivityObjectToDBAttributes,
354   videoFileActivityUrlToDBAttributes,
355   getOrCreateVideo,
356   getOrCreateVideoChannel,
357   addVideoShares
358 }