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