]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/activitypub/videos.ts
Bumped to version v1.0.0-beta.7
[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 { sanitizeAndCheckVideoTorrentObject } 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 import { crawlCollectionPage } from './crawl'
24
25 function fetchRemoteVideoPreview (video: VideoModel, reject: Function) {
26 const host = video.VideoChannel.Account.Actor.Server.host
27 const path = join(STATIC_PATHS.PREVIEWS, video.getPreviewName())
28
29 // We need to provide a callback, if no we could have an uncaught exception
30 return request.get(REMOTE_SCHEME.HTTP + '://' + host + path, err => {
31 if (err) reject(err)
32 })
33 }
34
35 async function fetchRemoteVideoDescription (video: VideoModel) {
36 const host = video.VideoChannel.Account.Actor.Server.host
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
47 function generateThumbnailFromUrl (video: VideoModel, icon: ActivityIconObject) {
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
58 async function videoActivityObjectToDBAttributes (videoChannel: VideoChannelModel,
59 videoObject: VideoTorrentObject,
60 to: string[] = []) {
61 const privacy = to.indexOf(ACTIVITY_PUB.PUBLIC) !== -1 ? VideoPrivacy.PUBLIC : VideoPrivacy.UNLISTED
62 const duration = videoObject.duration.replace(/[^\d]+/, '')
63
64 let language: string = null
65 if (videoObject.language) {
66 language = videoObject.language.identifier
67 }
68
69 let category: number = null
70 if (videoObject.category) {
71 category = parseInt(videoObject.category.identifier, 10)
72 }
73
74 let licence: number = null
75 if (videoObject.licence) {
76 licence = parseInt(videoObject.licence.identifier, 10)
77 }
78
79 const description = videoObject.content || null
80 const support = videoObject.support || null
81
82 return {
83 name: videoObject.name,
84 uuid: videoObject.uuid,
85 url: videoObject.id,
86 category,
87 licence,
88 language,
89 description,
90 support,
91 nsfw: videoObject.sensitive,
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
106 function 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
123 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
124
125 const parsed = magnetUtil.decode(magnet.href)
126 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) throw new Error('Cannot parse magnet URI ' + magnet.href)
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
141 function 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
148 async 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
158 const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to)
159 const video = VideoModel.build(videoData)
160
161 // Don't block on request
162 generateThumbnailFromUrl(video, videoObject.icon)
163 .catch(err => logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err }))
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
172 const tasks = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
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 })
184 }
185
186 async function getOrCreateAccountAndVideoAndChannel (videoObject: VideoTorrentObject | string, actor?: ActorModel) {
187 if (typeof videoObject === 'string') {
188 const videoUrl = videoObject
189
190 const videoFromDatabase = await VideoModel.loadByUrlAndPopulateAccount(videoUrl)
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(videoUrl)
200 if (!videoObject) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
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 channelActor = await getOrCreateVideoChannel(videoObject)
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
219 // Process outside the transaction because we could fetch remote data
220 logger.info('Adding likes of video %s.', video.uuid)
221 await crawlCollectionPage<string>(videoObject.likes, (items) => createRates(items, video, 'like'))
222
223 logger.info('Adding dislikes of video %s.', video.uuid)
224 await crawlCollectionPage<string>(videoObject.dislikes, (items) => createRates(items, video, 'dislike'))
225
226 logger.info('Adding shares of video %s.', video.uuid)
227 await crawlCollectionPage<string>(videoObject.shares, (items) => addVideoShares(items, video))
228
229 logger.info('Adding comments of video %s.', video.uuid)
230 await crawlCollectionPage<string>(videoObject.comments, (items) => addVideoComments(items, video))
231
232 return { actor, channelActor, video }
233 }
234
235 async 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
262 async function addVideoShares (shareUrls: string[], instance: VideoModel) {
263 for (const shareUrl of shareUrls) {
264 // Fetch url
265 const { body } = await doRequest({
266 uri: shareUrl,
267 json: true,
268 activityPub: true
269 })
270 if (!body || !body.actor) {
271 logger.warn('Cannot add remote share with url: %s, skipping...', shareUrl)
272 continue
273 }
274
275 const actorUrl = body.actor
276 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
277
278 const entry = {
279 actorId: actor.id,
280 videoId: instance.id,
281 url: shareUrl
282 }
283
284 await VideoShareModel.findOrCreate({
285 where: {
286 url: shareUrl
287 },
288 defaults: entry
289 })
290 }
291 }
292
293 export {
294 getOrCreateAccountAndVideoAndChannel,
295 fetchRemoteVideoPreview,
296 fetchRemoteVideoDescription,
297 generateThumbnailFromUrl,
298 videoActivityObjectToDBAttributes,
299 videoFileActivityUrlToDBAttributes,
300 getOrCreateVideo,
301 getOrCreateVideoChannel,
302 addVideoShares
303 }
304
305 // ---------------------------------------------------------------------------
306
307 async 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
319 if (sanitizeAndCheckVideoTorrentObject(body) === false) {
320 logger.debug('Remote video JSON is not valid.', { body })
321 return undefined
322 }
323
324 return body
325 }