]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/activitypub/videos.ts
Use sensitive instead of nsfw in activitypub
[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'
2ccaeeb3
C
8import { isVideoTorrentObjectValid } from '../../helpers/custom-validators/activitypub/videos'
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,
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,
0a67e28b 94 nsfw: videoObject.sensitive,
2ccaeeb3
C
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
109function 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
9fb3abfd 126 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
2ccaeeb3 127
9fb3abfd
C
128 const parsed = magnetUtil.decode(magnet.href)
129 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) throw new Error('Cannot parse magnet URI ' + magnet.href)
2ccaeeb3
C
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
144async 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
1f7ab4f3 168 const tasks = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
2ccaeeb3
C
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 })
0032ebe9
C
180}
181
2ccaeeb3
C
182async 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
7acee6f1
C
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
2ccaeeb3
C
237 return { actor, channelActor, video }
238}
239
7acee6f1
C
240async 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
2ccaeeb3
C
267async 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 }
284
285 await VideoShareModel.findOrCreate({
286 where: entry,
287 defaults: entry
288 })
289 }
0032ebe9
C
290}
291
892211e8 292export {
2ccaeeb3 293 getOrCreateAccountAndVideoAndChannel,
892211e8
C
294 fetchRemoteVideoPreview,
295 fetchRemoteVideoDescription,
0032ebe9 296 generateThumbnailFromUrl,
2ccaeeb3
C
297 videoActivityObjectToDBAttributes,
298 videoFileActivityUrlToDBAttributes,
299 getOrCreateVideo,
300 addVideoShares}
301
302// ---------------------------------------------------------------------------
303
304async function fetchRemoteVideo (videoUrl: string): Promise<VideoTorrentObject> {
305 const options = {
306 uri: videoUrl,
307 method: 'GET',
308 json: true,
309 activityPub: true
310 }
311
312 logger.info('Fetching remote video %s.', videoUrl)
313
314 const { body } = await doRequest(options)
315
316 if (isVideoTorrentObjectValid(body) === false) {
317 logger.debug('Remote video JSON is not valid.', { body })
318 return undefined
319 }
320
321 return body
892211e8 322}