]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/activitypub/videos.ts
e65362190cb481814a936070b853af34c3aab7f1
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / videos.ts
1 import * as Bluebird from 'bluebird'
2 import * as magnetUtil from 'magnet-uri'
3 import { join } from 'path'
4 import * as request from 'request'
5 import { ActivityIconObject } from '../../../shared/index'
6 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
7 import { VideoPrivacy, VideoRateType } from '../../../shared/models/videos'
8 import { isVideoTorrentObjectValid } from '../../helpers/custom-validators/activitypub/videos'
9 import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
10 import { retryTransactionWrapper } from '../../helpers/database-utils'
11 import { logger } from '../../helpers/logger'
12 import { doRequest, doRequestAndSaveToFile } from '../../helpers/requests'
13 import { ACTIVITY_PUB, CONFIG, REMOTE_SCHEME, sequelizeTypescript, STATIC_PATHS, VIDEO_MIMETYPE_EXT } from '../../initializers'
14 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
15 import { ActorModel } from '../../models/activitypub/actor'
16 import { TagModel } from '../../models/video/tag'
17 import { VideoModel } from '../../models/video/video'
18 import { VideoChannelModel } from '../../models/video/video-channel'
19 import { VideoFileModel } from '../../models/video/video-file'
20 import { VideoShareModel } from '../../models/video/video-share'
21 import { getOrCreateActorAndServerAndModel } from './actor'
22 import { addVideoComments } from './video-comments'
23
24 function 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
34 async 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
46 function 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
57 async 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 let support = null
87 if (videoObject.support) {
88 support = videoObject.support
89 }
90
91 return {
92 name: videoObject.name,
93 uuid: videoObject.uuid,
94 url: videoObject.id,
95 category,
96 licence,
97 language,
98 description,
99 support,
100 nsfw: videoObject.sensitive,
101 commentsEnabled: videoObject.commentsEnabled,
102 channelId: videoChannel.id,
103 duration: parseInt(duration, 10),
104 createdAt: new Date(videoObject.published),
105 // FIXME: updatedAt does not seems to be considered by Sequelize
106 updatedAt: new Date(videoObject.updated),
107 views: videoObject.views,
108 likes: 0,
109 dislikes: 0,
110 remote: true,
111 privacy
112 }
113 }
114
115 function videoFileActivityUrlToDBAttributes (videoCreated: VideoModel, videoObject: VideoTorrentObject) {
116 const mimeTypes = Object.keys(VIDEO_MIMETYPE_EXT)
117 const fileUrls = videoObject.url.filter(u => {
118 return mimeTypes.indexOf(u.mimeType) !== -1 && u.mimeType.startsWith('video/')
119 })
120
121 if (fileUrls.length === 0) {
122 throw new Error('Cannot find video files for ' + videoCreated.url)
123 }
124
125 const attributes = []
126 for (const fileUrl of fileUrls) {
127 // Fetch associated magnet uri
128 const magnet = videoObject.url.find(u => {
129 return u.mimeType === 'application/x-bittorrent;x-scheme-handler/magnet' && u.width === fileUrl.width
130 })
131
132 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
133
134 const parsed = magnetUtil.decode(magnet.href)
135 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) throw new Error('Cannot parse magnet URI ' + magnet.href)
136
137 const attribute = {
138 extname: VIDEO_MIMETYPE_EXT[ fileUrl.mimeType ],
139 infoHash: parsed.infoHash,
140 resolution: fileUrl.width,
141 size: fileUrl.size,
142 videoId: videoCreated.id
143 }
144 attributes.push(attribute)
145 }
146
147 return attributes
148 }
149
150 async function getOrCreateVideo (videoObject: VideoTorrentObject, channelActor: ActorModel) {
151 logger.debug('Adding remote video %s.', videoObject.id)
152
153 return sequelizeTypescript.transaction(async t => {
154 const sequelizeOptions = {
155 transaction: t
156 }
157 const videoFromDatabase = await VideoModel.loadByUUIDOrURLAndPopulateAccount(videoObject.uuid, videoObject.id, t)
158 if (videoFromDatabase) return videoFromDatabase
159
160 const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to, videoObject.cc)
161 const video = VideoModel.build(videoData)
162
163 // Don't block on request
164 generateThumbnailFromUrl(video, videoObject.icon)
165 .catch(err => logger.warn('Cannot generate thumbnail of %s.', videoObject.id, err))
166
167 const videoCreated = await video.save(sequelizeOptions)
168
169 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject)
170 if (videoFileAttributes.length === 0) {
171 throw new Error('Cannot find valid files for video %s ' + videoObject.url)
172 }
173
174 const tasks = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
175 await Promise.all(tasks)
176
177 const tags = videoObject.tag.map(t => t.name)
178 const tagInstances = await TagModel.findOrCreateTags(tags, t)
179 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
180
181 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
182
183 videoCreated.VideoChannel = channelActor.VideoChannel
184 return videoCreated
185 })
186 }
187
188 async function getOrCreateAccountAndVideoAndChannel (videoObject: VideoTorrentObject | string, actor?: ActorModel) {
189 if (typeof videoObject === 'string') {
190 const videoFromDatabase = await VideoModel.loadByUrlAndPopulateAccount(videoObject)
191 if (videoFromDatabase) {
192 return {
193 video: videoFromDatabase,
194 actor: videoFromDatabase.VideoChannel.Account.Actor,
195 channelActor: videoFromDatabase.VideoChannel.Actor
196 }
197 }
198
199 videoObject = await fetchRemoteVideo(videoObject)
200 if (!videoObject) throw new Error('Cannot fetch remote video')
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
210 const channel = videoObject.attributedTo.find(a => a.type === 'Group')
211 if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
212
213 const channelActor = await getOrCreateActorAndServerAndModel(channel.id)
214
215 const options = {
216 arguments: [ videoObject, channelActor ],
217 errorMessage: 'Cannot insert the remote video with many retries.'
218 }
219
220 const video = await retryTransactionWrapper(getOrCreateVideo, options)
221
222 // Process outside the transaction because we could fetch remote data
223 if (videoObject.likes && Array.isArray(videoObject.likes.orderedItems)) {
224 logger.info('Adding likes of video %s.', video.uuid)
225 await createRates(videoObject.likes.orderedItems, video, 'like')
226 }
227
228 if (videoObject.dislikes && Array.isArray(videoObject.dislikes.orderedItems)) {
229 logger.info('Adding dislikes of video %s.', video.uuid)
230 await createRates(videoObject.dislikes.orderedItems, video, 'dislike')
231 }
232
233 if (videoObject.shares && Array.isArray(videoObject.shares.orderedItems)) {
234 logger.info('Adding shares of video %s.', video.uuid)
235 await addVideoShares(video, videoObject.shares.orderedItems)
236 }
237
238 if (videoObject.comments && Array.isArray(videoObject.comments.orderedItems)) {
239 logger.info('Adding comments of video %s.', video.uuid)
240 await addVideoComments(video, videoObject.comments.orderedItems)
241 }
242
243 return { actor, channelActor, video }
244 }
245
246 async function createRates (actorUrls: string[], video: VideoModel, rate: VideoRateType) {
247 let rateCounts = 0
248 const tasks: Bluebird<number>[] = []
249
250 for (const actorUrl of actorUrls) {
251 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
252 const p = AccountVideoRateModel
253 .create({
254 videoId: video.id,
255 accountId: actor.Account.id,
256 type: rate
257 })
258 .then(() => rateCounts += 1)
259
260 tasks.push(p)
261 }
262
263 await Promise.all(tasks)
264
265 logger.info('Adding %d %s to video %s.', rateCounts, rate, video.uuid)
266
267 // This is "likes" and "dislikes"
268 await video.increment(rate + 's', { by: rateCounts })
269
270 return
271 }
272
273 async function addVideoShares (instance: VideoModel, shareUrls: string[]) {
274 for (const shareUrl of shareUrls) {
275 // Fetch url
276 const { body } = await doRequest({
277 uri: shareUrl,
278 json: true,
279 activityPub: true
280 })
281 const actorUrl = body.actor
282 if (!actorUrl) continue
283
284 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
285
286 const entry = {
287 actorId: actor.id,
288 videoId: instance.id,
289 url: shareUrl
290 }
291
292 await VideoShareModel.findOrCreate({
293 where: {
294 url: shareUrl
295 },
296 defaults: entry
297 })
298 }
299 }
300
301 export {
302 getOrCreateAccountAndVideoAndChannel,
303 fetchRemoteVideoPreview,
304 fetchRemoteVideoDescription,
305 generateThumbnailFromUrl,
306 videoActivityObjectToDBAttributes,
307 videoFileActivityUrlToDBAttributes,
308 getOrCreateVideo,
309 addVideoShares}
310
311 // ---------------------------------------------------------------------------
312
313 async 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 (isVideoTorrentObjectValid(body) === false) {
326 logger.debug('Remote video JSON is not valid.', { body })
327 return undefined
328 }
329
330 return body
331 }