]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/activitypub/videos.ts
Improve AP validation for Notes
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / videos.ts
CommitLineData
7acee6f1 1import * as Bluebird from 'bluebird'
2ccaeeb3 2import * as magnetUtil from 'magnet-uri'
892211e8
C
3import { join } from 'path'
4import * as request from 'request'
5import { ActivityIconObject } from '../../../shared/index'
2ccaeeb3 6import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
7acee6f1 7import { VideoPrivacy, VideoRateType } from '../../../shared/models/videos'
1d6e5dfc 8import { sanitizeAndCheckVideoTorrentObject } from '../../helpers/custom-validators/activitypub/videos'
2ccaeeb3
C
9import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
10import { retryTransactionWrapper } from '../../helpers/database-utils'
11import { logger } from '../../helpers/logger'
da854ddd 12import { doRequest, doRequestAndSaveToFile } from '../../helpers/requests'
2ccaeeb3 13import { ACTIVITY_PUB, CONFIG, REMOTE_SCHEME, sequelizeTypescript, STATIC_PATHS, VIDEO_MIMETYPE_EXT } from '../../initializers'
7acee6f1 14import { AccountVideoRateModel } from '../../models/account/account-video-rate'
2ccaeeb3
C
15import { ActorModel } from '../../models/activitypub/actor'
16import { TagModel } from '../../models/video/tag'
3fd3ab2d 17import { VideoModel } from '../../models/video/video'
2ccaeeb3
C
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'
7acee6f1 22import { addVideoComments } from './video-comments'
892211e8 23
d50acfab 24function fetchRemoteVideoPreview (video: VideoModel, reject: Function) {
50d6de9c 25 const host = video.VideoChannel.Account.Actor.Server.host
892211e8
C
26 const path = join(STATIC_PATHS.PREVIEWS, video.getPreviewName())
27
f05a1c30 28 // We need to provide a callback, if no we could have an uncaught exception
f40bbe31
C
29 return request.get(REMOTE_SCHEME.HTTP + '://' + host + path, err => {
30 if (err) reject(err)
31 })
892211e8
C
32}
33
3fd3ab2d 34async function fetchRemoteVideoDescription (video: VideoModel) {
50d6de9c 35 const host = video.VideoChannel.Account.Actor.Server.host
892211e8
C
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
3fd3ab2d 46function generateThumbnailFromUrl (video: VideoModel, icon: ActivityIconObject) {
892211e8
C
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
2ccaeeb3
C
57async function videoActivityObjectToDBAttributes (videoChannel: VideoChannelModel,
58 videoObject: VideoTorrentObject,
276d03ed
C
59 to: string[] = []) {
60 const privacy = to.indexOf(ACTIVITY_PUB.PUBLIC) !== -1 ? VideoPrivacy.PUBLIC : VideoPrivacy.UNLISTED
2ccaeeb3 61 const duration = videoObject.duration.replace(/[^\d]+/, '')
9d3ef9fe
C
62
63 let language: string = null
2ccaeeb3 64 if (videoObject.language) {
9d3ef9fe 65 language = videoObject.language.identifier
2ccaeeb3
C
66 }
67
9d3ef9fe 68 let category: number = null
2ccaeeb3
C
69 if (videoObject.category) {
70 category = parseInt(videoObject.category.identifier, 10)
71 }
72
9d3ef9fe 73 let licence: number = null
2ccaeeb3
C
74 if (videoObject.licence) {
75 licence = parseInt(videoObject.licence.identifier, 10)
76 }
77
276d03ed
C
78 const description = videoObject.content || null
79 const support = videoObject.support || null
2422c46b 80
2ccaeeb3
C
81 return {
82 name: videoObject.name,
83 uuid: videoObject.uuid,
84 url: videoObject.id,
85 category,
86 licence,
87 language,
88 description,
2422c46b 89 support,
0a67e28b 90 nsfw: videoObject.sensitive,
2ccaeeb3
C
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
9fb3abfd 122 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
2ccaeeb3 123
9fb3abfd
C
124 const parsed = magnetUtil.decode(magnet.href)
125 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) throw new Error('Cannot parse magnet URI ' + magnet.href)
2ccaeeb3
C
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
0f320037
C
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
2ccaeeb3
C
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
276d03ed 157 const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to)
2ccaeeb3
C
158 const video = VideoModel.build(videoData)
159
160 // Don't block on request
161 generateThumbnailFromUrl(video, videoObject.icon)
d5b7d911 162 .catch(err => logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err }))
2ccaeeb3
C
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
1f7ab4f3 171 const tasks = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
2ccaeeb3
C
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 })
0032ebe9
C
183}
184
2ccaeeb3
C
185async function getOrCreateAccountAndVideoAndChannel (videoObject: VideoTorrentObject | string, actor?: ActorModel) {
186 if (typeof videoObject === 'string') {
8e8234ab
C
187 const videoUrl = videoObject
188
189 const videoFromDatabase = await VideoModel.loadByUrlAndPopulateAccount(videoUrl)
2ccaeeb3
C
190 if (videoFromDatabase) {
191 return {
192 video: videoFromDatabase,
193 actor: videoFromDatabase.VideoChannel.Account.Actor,
194 channelActor: videoFromDatabase.VideoChannel.Actor
195 }
196 }
197
8e8234ab
C
198 videoObject = await fetchRemoteVideo(videoUrl)
199 if (!videoObject) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
2ccaeeb3
C
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
0f320037 209 const channelActor = await getOrCreateVideoChannel(videoObject)
2ccaeeb3
C
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
7acee6f1
C
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
2ccaeeb3
C
239 return { actor, channelActor, video }
240}
241
7acee6f1
C
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
2ccaeeb3
C
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 })
8e8234ab
C
277 if (!body || !body.actor) {
278 logger.warn('Cannot add remote share with url: %s, skipping...', shareUrl)
279 continue
280 }
2ccaeeb3 281
8e8234ab 282 const actorUrl = body.actor
2ccaeeb3
C
283 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
284
285 const entry = {
286 actorId: actor.id,
8dfd8fd7
C
287 videoId: instance.id,
288 url: shareUrl
2ccaeeb3
C
289 }
290
291 await VideoShareModel.findOrCreate({
8dfd8fd7
C
292 where: {
293 url: shareUrl
294 },
2ccaeeb3
C
295 defaults: entry
296 })
297 }
0032ebe9
C
298}
299
892211e8 300export {
2ccaeeb3 301 getOrCreateAccountAndVideoAndChannel,
892211e8
C
302 fetchRemoteVideoPreview,
303 fetchRemoteVideoDescription,
0032ebe9 304 generateThumbnailFromUrl,
2ccaeeb3
C
305 videoActivityObjectToDBAttributes,
306 videoFileActivityUrlToDBAttributes,
307 getOrCreateVideo,
0f320037 308 getOrCreateVideoChannel,
2ccaeeb3
C
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
1d6e5dfc 325 if (sanitizeAndCheckVideoTorrentObject(body) === false) {
2ccaeeb3
C
326 logger.debug('Remote video JSON is not valid.', { body })
327 return undefined
328 }
329
330 return body
892211e8 331}