]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/activitypub/videos.ts
Updated travis.yml git depth 1
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / videos.ts
CommitLineData
7acee6f1 1import * as Bluebird from 'bluebird'
2186386c 2import * as sequelize from 'sequelize'
2ccaeeb3 3import * as magnetUtil from 'magnet-uri'
892211e8
C
4import { join } from 'path'
5import * as request from 'request'
2186386c 6import { ActivityIconObject, VideoState } from '../../../shared/index'
2ccaeeb3 7import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
7acee6f1 8import { VideoPrivacy, VideoRateType } from '../../../shared/models/videos'
1d6e5dfc 9import { sanitizeAndCheckVideoTorrentObject } from '../../helpers/custom-validators/activitypub/videos'
2ccaeeb3
C
10import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
11import { retryTransactionWrapper } from '../../helpers/database-utils'
12import { logger } from '../../helpers/logger'
da854ddd 13import { doRequest, doRequestAndSaveToFile } from '../../helpers/requests'
2ccaeeb3 14import { ACTIVITY_PUB, CONFIG, REMOTE_SCHEME, sequelizeTypescript, STATIC_PATHS, VIDEO_MIMETYPE_EXT } from '../../initializers'
7acee6f1 15import { AccountVideoRateModel } from '../../models/account/account-video-rate'
2ccaeeb3
C
16import { ActorModel } from '../../models/activitypub/actor'
17import { TagModel } from '../../models/video/tag'
3fd3ab2d 18import { VideoModel } from '../../models/video/video'
2ccaeeb3
C
19import { VideoChannelModel } from '../../models/video/video-channel'
20import { VideoFileModel } from '../../models/video/video-file'
21import { VideoShareModel } from '../../models/video/video-share'
22import { getOrCreateActorAndServerAndModel } from './actor'
7acee6f1 23import { addVideoComments } from './video-comments'
8fffe21a 24import { crawlCollectionPage } from './crawl'
2186386c
C
25import { sendCreateVideo, sendUpdateVideo } from './send'
26import { shareVideoByServerAndChannel } from './index'
40e87e9e
C
27import { isArray } from '../../helpers/custom-validators/misc'
28import { VideoCaptionModel } from '../../models/video/video-caption'
2186386c
C
29
30async 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) {
40e87e9e
C
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
2186386c
C
41 if (isNewVideo === true) {
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}
892211e8 50
40e87e9e 51function fetchRemoteVideoStaticFile (video: VideoModel, path: string, reject: Function) {
50d6de9c 52 const host = video.VideoChannel.Account.Actor.Server.host
892211e8 53
f05a1c30 54 // We need to provide a callback, if no we could have an uncaught exception
f40bbe31
C
55 return request.get(REMOTE_SCHEME.HTTP + '://' + host + path, err => {
56 if (err) reject(err)
57 })
892211e8
C
58}
59
3fd3ab2d 60async function fetchRemoteVideoDescription (video: VideoModel) {
50d6de9c 61 const host = video.VideoChannel.Account.Actor.Server.host
892211e8
C
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
3fd3ab2d 72function generateThumbnailFromUrl (video: VideoModel, icon: ActivityIconObject) {
892211e8
C
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
2186386c
C
83async function videoActivityObjectToDBAttributes (
84 videoChannel: VideoChannelModel,
85 videoObject: VideoTorrentObject,
86 to: string[] = []
87) {
276d03ed 88 const privacy = to.indexOf(ACTIVITY_PUB.PUBLIC) !== -1 ? VideoPrivacy.PUBLIC : VideoPrivacy.UNLISTED
2ccaeeb3 89 const duration = videoObject.duration.replace(/[^\d]+/, '')
9d3ef9fe
C
90
91 let language: string = null
2ccaeeb3 92 if (videoObject.language) {
9d3ef9fe 93 language = videoObject.language.identifier
2ccaeeb3
C
94 }
95
9d3ef9fe 96 let category: number = null
2ccaeeb3
C
97 if (videoObject.category) {
98 category = parseInt(videoObject.category.identifier, 10)
99 }
100
9d3ef9fe 101 let licence: number = null
2ccaeeb3
C
102 if (videoObject.licence) {
103 licence = parseInt(videoObject.licence.identifier, 10)
104 }
105
276d03ed
C
106 const description = videoObject.content || null
107 const support = videoObject.support || null
2422c46b 108
2ccaeeb3
C
109 return {
110 name: videoObject.name,
111 uuid: videoObject.uuid,
112 url: videoObject.id,
113 category,
114 licence,
115 language,
116 description,
2422c46b 117 support,
0a67e28b 118 nsfw: videoObject.sensitive,
2ccaeeb3 119 commentsEnabled: videoObject.commentsEnabled,
2186386c
C
120 waitTranscoding: videoObject.waitTranscoding,
121 state: videoObject.state,
2ccaeeb3
C
122 channelId: videoChannel.id,
123 duration: parseInt(duration, 10),
124 createdAt: new Date(videoObject.published),
53a61317 125 publishedAt: new Date(videoObject.published),
2ccaeeb3
C
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
136function 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 = []
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
9fb3abfd 153 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
2ccaeeb3 154
9fb3abfd
C
155 const parsed = magnetUtil.decode(magnet.href)
156 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) throw new Error('Cannot parse magnet URI ' + magnet.href)
2ccaeeb3
C
157
158 const attribute = {
159 extname: VIDEO_MIMETYPE_EXT[ fileUrl.mimeType ],
160 infoHash: parsed.infoHash,
161 resolution: fileUrl.width,
162 size: fileUrl.size,
163 videoId: videoCreated.id
164 }
165 attributes.push(attribute)
166 }
167
168 return attributes
169}
170
0f320037
C
171function getOrCreateVideoChannel (videoObject: VideoTorrentObject) {
172 const channel = videoObject.attributedTo.find(a => a.type === 'Group')
173 if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
174
175 return getOrCreateActorAndServerAndModel(channel.id)
176}
177
2ccaeeb3
C
178async function getOrCreateVideo (videoObject: VideoTorrentObject, channelActor: ActorModel) {
179 logger.debug('Adding remote video %s.', videoObject.id)
180
181 return sequelizeTypescript.transaction(async t => {
182 const sequelizeOptions = {
183 transaction: t
184 }
185 const videoFromDatabase = await VideoModel.loadByUUIDOrURLAndPopulateAccount(videoObject.uuid, videoObject.id, t)
186 if (videoFromDatabase) return videoFromDatabase
187
276d03ed 188 const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to)
2ccaeeb3
C
189 const video = VideoModel.build(videoData)
190
40e87e9e 191 // Don't block on remote HTTP request (we are in a transaction!)
2ccaeeb3 192 generateThumbnailFromUrl(video, videoObject.icon)
d5b7d911 193 .catch(err => logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err }))
2ccaeeb3
C
194
195 const videoCreated = await video.save(sequelizeOptions)
196
40e87e9e 197 // Process files
2ccaeeb3
C
198 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject)
199 if (videoFileAttributes.length === 0) {
200 throw new Error('Cannot find valid files for video %s ' + videoObject.url)
201 }
202
40e87e9e
C
203 const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
204 await Promise.all(videoFilePromises)
2ccaeeb3 205
40e87e9e 206 // Process tags
2ccaeeb3
C
207 const tags = videoObject.tag.map(t => t.name)
208 const tagInstances = await TagModel.findOrCreateTags(tags, t)
209 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
210
40e87e9e
C
211 // Process captions
212 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
213 return VideoCaptionModel.insertOrReplaceLanguage(videoCreated.id, c.identifier, t)
214 })
215 await Promise.all(videoCaptionsPromises)
216
2ccaeeb3
C
217 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
218
219 videoCreated.VideoChannel = channelActor.VideoChannel
220 return videoCreated
221 })
0032ebe9
C
222}
223
2ccaeeb3 224async function getOrCreateAccountAndVideoAndChannel (videoObject: VideoTorrentObject | string, actor?: ActorModel) {
2186386c
C
225 const videoUrl = typeof videoObject === 'string' ? videoObject : videoObject.id
226
227 const videoFromDatabase = await VideoModel.loadByUrlAndPopulateAccount(videoUrl)
228 if (videoFromDatabase) {
229 return {
230 video: videoFromDatabase,
231 actor: videoFromDatabase.VideoChannel.Account.Actor,
232 channelActor: videoFromDatabase.VideoChannel.Actor
2ccaeeb3 233 }
2ccaeeb3
C
234 }
235
2186386c
C
236 videoObject = await fetchRemoteVideo(videoUrl)
237 if (!videoObject) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
238
2ccaeeb3
C
239 if (!actor) {
240 const actorObj = videoObject.attributedTo.find(a => a.type === 'Person')
241 if (!actorObj) throw new Error('Cannot find associated actor to video ' + videoObject.url)
242
243 actor = await getOrCreateActorAndServerAndModel(actorObj.id)
244 }
245
0f320037 246 const channelActor = await getOrCreateVideoChannel(videoObject)
2ccaeeb3 247
90d4bb81 248 const video = await retryTransactionWrapper(getOrCreateVideo, videoObject, channelActor)
2ccaeeb3 249
7acee6f1 250 // Process outside the transaction because we could fetch remote data
8fffe21a
C
251 logger.info('Adding likes of video %s.', video.uuid)
252 await crawlCollectionPage<string>(videoObject.likes, (items) => createRates(items, video, 'like'))
7acee6f1 253
8fffe21a
C
254 logger.info('Adding dislikes of video %s.', video.uuid)
255 await crawlCollectionPage<string>(videoObject.dislikes, (items) => createRates(items, video, 'dislike'))
7acee6f1 256
8fffe21a
C
257 logger.info('Adding shares of video %s.', video.uuid)
258 await crawlCollectionPage<string>(videoObject.shares, (items) => addVideoShares(items, video))
7acee6f1 259
8fffe21a
C
260 logger.info('Adding comments of video %s.', video.uuid)
261 await crawlCollectionPage<string>(videoObject.comments, (items) => addVideoComments(items, video))
7acee6f1 262
2ccaeeb3
C
263 return { actor, channelActor, video }
264}
265
7acee6f1
C
266async function createRates (actorUrls: string[], video: VideoModel, rate: VideoRateType) {
267 let rateCounts = 0
268 const tasks: Bluebird<number>[] = []
269
270 for (const actorUrl of actorUrls) {
271 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
272 const p = AccountVideoRateModel
273 .create({
274 videoId: video.id,
275 accountId: actor.Account.id,
276 type: rate
277 })
278 .then(() => rateCounts += 1)
279
280 tasks.push(p)
281 }
282
283 await Promise.all(tasks)
284
285 logger.info('Adding %d %s to video %s.', rateCounts, rate, video.uuid)
286
287 // This is "likes" and "dislikes"
288 await video.increment(rate + 's', { by: rateCounts })
289
290 return
291}
292
8fffe21a 293async function addVideoShares (shareUrls: string[], instance: VideoModel) {
2ccaeeb3
C
294 for (const shareUrl of shareUrls) {
295 // Fetch url
296 const { body } = await doRequest({
297 uri: shareUrl,
298 json: true,
299 activityPub: true
300 })
8e8234ab
C
301 if (!body || !body.actor) {
302 logger.warn('Cannot add remote share with url: %s, skipping...', shareUrl)
303 continue
304 }
2ccaeeb3 305
8e8234ab 306 const actorUrl = body.actor
2ccaeeb3
C
307 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
308
309 const entry = {
310 actorId: actor.id,
8dfd8fd7
C
311 videoId: instance.id,
312 url: shareUrl
2ccaeeb3
C
313 }
314
315 await VideoShareModel.findOrCreate({
8dfd8fd7
C
316 where: {
317 url: shareUrl
318 },
2ccaeeb3
C
319 defaults: entry
320 })
321 }
0032ebe9
C
322}
323
2ccaeeb3
C
324async function fetchRemoteVideo (videoUrl: string): Promise<VideoTorrentObject> {
325 const options = {
326 uri: videoUrl,
327 method: 'GET',
328 json: true,
329 activityPub: true
330 }
331
332 logger.info('Fetching remote video %s.', videoUrl)
333
334 const { body } = await doRequest(options)
335
1d6e5dfc 336 if (sanitizeAndCheckVideoTorrentObject(body) === false) {
2ccaeeb3
C
337 logger.debug('Remote video JSON is not valid.', { body })
338 return undefined
339 }
340
341 return body
892211e8 342}
2186386c
C
343
344export {
345 federateVideoIfNeeded,
346 fetchRemoteVideo,
347 getOrCreateAccountAndVideoAndChannel,
40e87e9e 348 fetchRemoteVideoStaticFile,
2186386c
C
349 fetchRemoteVideoDescription,
350 generateThumbnailFromUrl,
351 videoActivityObjectToDBAttributes,
352 videoFileActivityUrlToDBAttributes,
353 getOrCreateVideo,
354 getOrCreateVideoChannel,
355 addVideoShares
356}