]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/lib/activitypub/videos.ts
Improve AP validation for Notes
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / videos.ts
... / ...
CommitLineData
1import * as Bluebird from 'bluebird'
2import * as magnetUtil from 'magnet-uri'
3import { join } from 'path'
4import * as request from 'request'
5import { ActivityIconObject } from '../../../shared/index'
6import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
7import { VideoPrivacy, VideoRateType } from '../../../shared/models/videos'
8import { sanitizeAndCheckVideoTorrentObject } from '../../helpers/custom-validators/activitypub/videos'
9import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
10import { retryTransactionWrapper } from '../../helpers/database-utils'
11import { logger } from '../../helpers/logger'
12import { doRequest, doRequestAndSaveToFile } from '../../helpers/requests'
13import { ACTIVITY_PUB, CONFIG, REMOTE_SCHEME, sequelizeTypescript, STATIC_PATHS, VIDEO_MIMETYPE_EXT } from '../../initializers'
14import { AccountVideoRateModel } from '../../models/account/account-video-rate'
15import { ActorModel } from '../../models/activitypub/actor'
16import { TagModel } from '../../models/video/tag'
17import { VideoModel } from '../../models/video/video'
18import { VideoChannelModel } from '../../models/video/video-channel'
19import { VideoFileModel } from '../../models/video/video-file'
20import { VideoShareModel } from '../../models/video/video-share'
21import { getOrCreateActorAndServerAndModel } from './actor'
22import { addVideoComments } from './video-comments'
23
24function 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
34async 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
46function 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
57async function videoActivityObjectToDBAttributes (videoChannel: VideoChannelModel,
58 videoObject: VideoTorrentObject,
59 to: string[] = []) {
60 const privacy = to.indexOf(ACTIVITY_PUB.PUBLIC) !== -1 ? VideoPrivacy.PUBLIC : VideoPrivacy.UNLISTED
61 const duration = videoObject.duration.replace(/[^\d]+/, '')
62
63 let language: string = null
64 if (videoObject.language) {
65 language = videoObject.language.identifier
66 }
67
68 let category: number = null
69 if (videoObject.category) {
70 category = parseInt(videoObject.category.identifier, 10)
71 }
72
73 let licence: number = null
74 if (videoObject.licence) {
75 licence = parseInt(videoObject.licence.identifier, 10)
76 }
77
78 const description = videoObject.content || null
79 const support = videoObject.support || null
80
81 return {
82 name: videoObject.name,
83 uuid: videoObject.uuid,
84 url: videoObject.id,
85 category,
86 licence,
87 language,
88 description,
89 support,
90 nsfw: videoObject.sensitive,
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
105function 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
122 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
123
124 const parsed = magnetUtil.decode(magnet.href)
125 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) throw new Error('Cannot parse magnet URI ' + magnet.href)
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
140function getOrCreateVideoChannel (videoObject: VideoTorrentObject) {
141 const channel = videoObject.attributedTo.find(a => a.type === 'Group')
142 if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
143
144 return getOrCreateActorAndServerAndModel(channel.id)
145}
146
147async function getOrCreateVideo (videoObject: VideoTorrentObject, channelActor: ActorModel) {
148 logger.debug('Adding remote video %s.', videoObject.id)
149
150 return sequelizeTypescript.transaction(async t => {
151 const sequelizeOptions = {
152 transaction: t
153 }
154 const videoFromDatabase = await VideoModel.loadByUUIDOrURLAndPopulateAccount(videoObject.uuid, videoObject.id, t)
155 if (videoFromDatabase) return videoFromDatabase
156
157 const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to)
158 const video = VideoModel.build(videoData)
159
160 // Don't block on request
161 generateThumbnailFromUrl(video, videoObject.icon)
162 .catch(err => logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err }))
163
164 const videoCreated = await video.save(sequelizeOptions)
165
166 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject)
167 if (videoFileAttributes.length === 0) {
168 throw new Error('Cannot find valid files for video %s ' + videoObject.url)
169 }
170
171 const tasks = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
172 await Promise.all(tasks)
173
174 const tags = videoObject.tag.map(t => t.name)
175 const tagInstances = await TagModel.findOrCreateTags(tags, t)
176 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
177
178 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
179
180 videoCreated.VideoChannel = channelActor.VideoChannel
181 return videoCreated
182 })
183}
184
185async function getOrCreateAccountAndVideoAndChannel (videoObject: VideoTorrentObject | string, actor?: ActorModel) {
186 if (typeof videoObject === 'string') {
187 const videoUrl = videoObject
188
189 const videoFromDatabase = await VideoModel.loadByUrlAndPopulateAccount(videoUrl)
190 if (videoFromDatabase) {
191 return {
192 video: videoFromDatabase,
193 actor: videoFromDatabase.VideoChannel.Account.Actor,
194 channelActor: videoFromDatabase.VideoChannel.Actor
195 }
196 }
197
198 videoObject = await fetchRemoteVideo(videoUrl)
199 if (!videoObject) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
200 }
201
202 if (!actor) {
203 const actorObj = videoObject.attributedTo.find(a => a.type === 'Person')
204 if (!actorObj) throw new Error('Cannot find associated actor to video ' + videoObject.url)
205
206 actor = await getOrCreateActorAndServerAndModel(actorObj.id)
207 }
208
209 const channelActor = await getOrCreateVideoChannel(videoObject)
210
211 const options = {
212 arguments: [ videoObject, channelActor ],
213 errorMessage: 'Cannot insert the remote video with many retries.'
214 }
215
216 const video = await retryTransactionWrapper(getOrCreateVideo, options)
217
218 // Process outside the transaction because we could fetch remote data
219 if (videoObject.likes && Array.isArray(videoObject.likes.orderedItems)) {
220 logger.info('Adding likes of video %s.', video.uuid)
221 await createRates(videoObject.likes.orderedItems, video, 'like')
222 }
223
224 if (videoObject.dislikes && Array.isArray(videoObject.dislikes.orderedItems)) {
225 logger.info('Adding dislikes of video %s.', video.uuid)
226 await createRates(videoObject.dislikes.orderedItems, video, 'dislike')
227 }
228
229 if (videoObject.shares && Array.isArray(videoObject.shares.orderedItems)) {
230 logger.info('Adding shares of video %s.', video.uuid)
231 await addVideoShares(video, videoObject.shares.orderedItems)
232 }
233
234 if (videoObject.comments && Array.isArray(videoObject.comments.orderedItems)) {
235 logger.info('Adding comments of video %s.', video.uuid)
236 await addVideoComments(video, videoObject.comments.orderedItems)
237 }
238
239 return { actor, channelActor, video }
240}
241
242async function createRates (actorUrls: string[], video: VideoModel, rate: VideoRateType) {
243 let rateCounts = 0
244 const tasks: Bluebird<number>[] = []
245
246 for (const actorUrl of actorUrls) {
247 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
248 const p = AccountVideoRateModel
249 .create({
250 videoId: video.id,
251 accountId: actor.Account.id,
252 type: rate
253 })
254 .then(() => rateCounts += 1)
255
256 tasks.push(p)
257 }
258
259 await Promise.all(tasks)
260
261 logger.info('Adding %d %s to video %s.', rateCounts, rate, video.uuid)
262
263 // This is "likes" and "dislikes"
264 await video.increment(rate + 's', { by: rateCounts })
265
266 return
267}
268
269async function addVideoShares (instance: VideoModel, shareUrls: string[]) {
270 for (const shareUrl of shareUrls) {
271 // Fetch url
272 const { body } = await doRequest({
273 uri: shareUrl,
274 json: true,
275 activityPub: true
276 })
277 if (!body || !body.actor) {
278 logger.warn('Cannot add remote share with url: %s, skipping...', shareUrl)
279 continue
280 }
281
282 const actorUrl = body.actor
283 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
284
285 const entry = {
286 actorId: actor.id,
287 videoId: instance.id,
288 url: shareUrl
289 }
290
291 await VideoShareModel.findOrCreate({
292 where: {
293 url: shareUrl
294 },
295 defaults: entry
296 })
297 }
298}
299
300export {
301 getOrCreateAccountAndVideoAndChannel,
302 fetchRemoteVideoPreview,
303 fetchRemoteVideoDescription,
304 generateThumbnailFromUrl,
305 videoActivityObjectToDBAttributes,
306 videoFileActivityUrlToDBAttributes,
307 getOrCreateVideo,
308 getOrCreateVideoChannel,
309 addVideoShares}
310
311// ---------------------------------------------------------------------------
312
313async function fetchRemoteVideo (videoUrl: string): Promise<VideoTorrentObject> {
314 const options = {
315 uri: videoUrl,
316 method: 'GET',
317 json: true,
318 activityPub: true
319 }
320
321 logger.info('Fetching remote video %s.', videoUrl)
322
323 const { body } = await doRequest(options)
324
325 if (sanitizeAndCheckVideoTorrentObject(body) === false) {
326 logger.debug('Remote video JSON is not valid.', { body })
327 return undefined
328 }
329
330 return body
331}