]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/activitypub/videos.ts
Fix publishedAt value after following a new instance
[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 publishedAt: new Date(videoObject.published),
97 // FIXME: updatedAt does not seems to be considered by Sequelize
98 updatedAt: new Date(videoObject.updated),
99 views: videoObject.views,
100 likes: 0,
101 dislikes: 0,
102 remote: true,
103 privacy
104 }
105 }
106
107 function videoFileActivityUrlToDBAttributes (videoCreated: VideoModel, videoObject: VideoTorrentObject) {
108 const mimeTypes = Object.keys(VIDEO_MIMETYPE_EXT)
109 const fileUrls = videoObject.url.filter(u => {
110 return mimeTypes.indexOf(u.mimeType) !== -1 && u.mimeType.startsWith('video/')
111 })
112
113 if (fileUrls.length === 0) {
114 throw new Error('Cannot find video files for ' + videoCreated.url)
115 }
116
117 const attributes = []
118 for (const fileUrl of fileUrls) {
119 // Fetch associated magnet uri
120 const magnet = videoObject.url.find(u => {
121 return u.mimeType === 'application/x-bittorrent;x-scheme-handler/magnet' && u.width === fileUrl.width
122 })
123
124 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
125
126 const parsed = magnetUtil.decode(magnet.href)
127 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) throw new Error('Cannot parse magnet URI ' + magnet.href)
128
129 const attribute = {
130 extname: VIDEO_MIMETYPE_EXT[ fileUrl.mimeType ],
131 infoHash: parsed.infoHash,
132 resolution: fileUrl.width,
133 size: fileUrl.size,
134 videoId: videoCreated.id
135 }
136 attributes.push(attribute)
137 }
138
139 return attributes
140 }
141
142 function getOrCreateVideoChannel (videoObject: VideoTorrentObject) {
143 const channel = videoObject.attributedTo.find(a => a.type === 'Group')
144 if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
145
146 return getOrCreateActorAndServerAndModel(channel.id)
147 }
148
149 async function getOrCreateVideo (videoObject: VideoTorrentObject, channelActor: ActorModel) {
150 logger.debug('Adding remote video %s.', videoObject.id)
151
152 return sequelizeTypescript.transaction(async t => {
153 const sequelizeOptions = {
154 transaction: t
155 }
156 const videoFromDatabase = await VideoModel.loadByUUIDOrURLAndPopulateAccount(videoObject.uuid, videoObject.id, t)
157 if (videoFromDatabase) return videoFromDatabase
158
159 const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to)
160 const video = VideoModel.build(videoData)
161
162 // Don't block on request
163 generateThumbnailFromUrl(video, videoObject.icon)
164 .catch(err => logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err }))
165
166 const videoCreated = await video.save(sequelizeOptions)
167
168 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject)
169 if (videoFileAttributes.length === 0) {
170 throw new Error('Cannot find valid files for video %s ' + videoObject.url)
171 }
172
173 const tasks = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
174 await Promise.all(tasks)
175
176 const tags = videoObject.tag.map(t => t.name)
177 const tagInstances = await TagModel.findOrCreateTags(tags, t)
178 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
179
180 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
181
182 videoCreated.VideoChannel = channelActor.VideoChannel
183 return videoCreated
184 })
185 }
186
187 async function getOrCreateAccountAndVideoAndChannel (videoObject: VideoTorrentObject | string, actor?: ActorModel) {
188 if (typeof videoObject === 'string') {
189 const videoUrl = videoObject
190
191 const videoFromDatabase = await VideoModel.loadByUrlAndPopulateAccount(videoUrl)
192 if (videoFromDatabase) {
193 return {
194 video: videoFromDatabase,
195 actor: videoFromDatabase.VideoChannel.Account.Actor,
196 channelActor: videoFromDatabase.VideoChannel.Actor
197 }
198 }
199
200 videoObject = await fetchRemoteVideo(videoUrl)
201 if (!videoObject) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
202 }
203
204 if (!actor) {
205 const actorObj = videoObject.attributedTo.find(a => a.type === 'Person')
206 if (!actorObj) throw new Error('Cannot find associated actor to video ' + videoObject.url)
207
208 actor = await getOrCreateActorAndServerAndModel(actorObj.id)
209 }
210
211 const channelActor = await getOrCreateVideoChannel(videoObject)
212
213 const options = {
214 arguments: [ videoObject, channelActor ],
215 errorMessage: 'Cannot insert the remote video with many retries.'
216 }
217
218 const video = await retryTransactionWrapper(getOrCreateVideo, options)
219
220 // Process outside the transaction because we could fetch remote data
221 logger.info('Adding likes of video %s.', video.uuid)
222 await crawlCollectionPage<string>(videoObject.likes, (items) => createRates(items, video, 'like'))
223
224 logger.info('Adding dislikes of video %s.', video.uuid)
225 await crawlCollectionPage<string>(videoObject.dislikes, (items) => createRates(items, video, 'dislike'))
226
227 logger.info('Adding shares of video %s.', video.uuid)
228 await crawlCollectionPage<string>(videoObject.shares, (items) => addVideoShares(items, video))
229
230 logger.info('Adding comments of video %s.', video.uuid)
231 await crawlCollectionPage<string>(videoObject.comments, (items) => addVideoComments(items, video))
232
233 return { actor, channelActor, video }
234 }
235
236 async function createRates (actorUrls: string[], video: VideoModel, rate: VideoRateType) {
237 let rateCounts = 0
238 const tasks: Bluebird<number>[] = []
239
240 for (const actorUrl of actorUrls) {
241 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
242 const p = AccountVideoRateModel
243 .create({
244 videoId: video.id,
245 accountId: actor.Account.id,
246 type: rate
247 })
248 .then(() => rateCounts += 1)
249
250 tasks.push(p)
251 }
252
253 await Promise.all(tasks)
254
255 logger.info('Adding %d %s to video %s.', rateCounts, rate, video.uuid)
256
257 // This is "likes" and "dislikes"
258 await video.increment(rate + 's', { by: rateCounts })
259
260 return
261 }
262
263 async function addVideoShares (shareUrls: string[], instance: VideoModel) {
264 for (const shareUrl of shareUrls) {
265 // Fetch url
266 const { body } = await doRequest({
267 uri: shareUrl,
268 json: true,
269 activityPub: true
270 })
271 if (!body || !body.actor) {
272 logger.warn('Cannot add remote share with url: %s, skipping...', shareUrl)
273 continue
274 }
275
276 const actorUrl = body.actor
277 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
278
279 const entry = {
280 actorId: actor.id,
281 videoId: instance.id,
282 url: shareUrl
283 }
284
285 await VideoShareModel.findOrCreate({
286 where: {
287 url: shareUrl
288 },
289 defaults: entry
290 })
291 }
292 }
293
294 export {
295 getOrCreateAccountAndVideoAndChannel,
296 fetchRemoteVideoPreview,
297 fetchRemoteVideoDescription,
298 generateThumbnailFromUrl,
299 videoActivityObjectToDBAttributes,
300 videoFileActivityUrlToDBAttributes,
301 getOrCreateVideo,
302 getOrCreateVideoChannel,
303 addVideoShares
304 }
305
306 // ---------------------------------------------------------------------------
307
308 async function fetchRemoteVideo (videoUrl: string): Promise<VideoTorrentObject> {
309 const options = {
310 uri: videoUrl,
311 method: 'GET',
312 json: true,
313 activityPub: true
314 }
315
316 logger.info('Fetching remote video %s.', videoUrl)
317
318 const { body } = await doRequest(options)
319
320 if (sanitizeAndCheckVideoTorrentObject(body) === false) {
321 logger.debug('Remote video JSON is not valid.', { body })
322 return undefined
323 }
324
325 return body
326 }