]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/activitypub/videos.ts
Fix publishedAt value after following a new instance
[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),
53a61317 96 publishedAt: new Date(videoObject.published),
2ccaeeb3
C
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
107function 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
9fb3abfd 124 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
2ccaeeb3 125
9fb3abfd
C
126 const parsed = magnetUtil.decode(magnet.href)
127 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) throw new Error('Cannot parse magnet URI ' + magnet.href)
2ccaeeb3
C
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
0f320037
C
142function 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
2ccaeeb3
C
149async 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
276d03ed 159 const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to)
2ccaeeb3
C
160 const video = VideoModel.build(videoData)
161
162 // Don't block on request
163 generateThumbnailFromUrl(video, videoObject.icon)
d5b7d911 164 .catch(err => logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err }))
2ccaeeb3
C
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
1f7ab4f3 173 const tasks = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
2ccaeeb3
C
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 })
0032ebe9
C
185}
186
2ccaeeb3
C
187async function getOrCreateAccountAndVideoAndChannel (videoObject: VideoTorrentObject | string, actor?: ActorModel) {
188 if (typeof videoObject === 'string') {
8e8234ab
C
189 const videoUrl = videoObject
190
191 const videoFromDatabase = await VideoModel.loadByUrlAndPopulateAccount(videoUrl)
2ccaeeb3
C
192 if (videoFromDatabase) {
193 return {
194 video: videoFromDatabase,
195 actor: videoFromDatabase.VideoChannel.Account.Actor,
196 channelActor: videoFromDatabase.VideoChannel.Actor
197 }
198 }
199
8e8234ab
C
200 videoObject = await fetchRemoteVideo(videoUrl)
201 if (!videoObject) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
2ccaeeb3
C
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
0f320037 211 const channelActor = await getOrCreateVideoChannel(videoObject)
2ccaeeb3
C
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
7acee6f1 220 // Process outside the transaction because we could fetch remote data
8fffe21a
C
221 logger.info('Adding likes of video %s.', video.uuid)
222 await crawlCollectionPage<string>(videoObject.likes, (items) => createRates(items, video, 'like'))
7acee6f1 223
8fffe21a
C
224 logger.info('Adding dislikes of video %s.', video.uuid)
225 await crawlCollectionPage<string>(videoObject.dislikes, (items) => createRates(items, video, 'dislike'))
7acee6f1 226
8fffe21a
C
227 logger.info('Adding shares of video %s.', video.uuid)
228 await crawlCollectionPage<string>(videoObject.shares, (items) => addVideoShares(items, video))
7acee6f1 229
8fffe21a
C
230 logger.info('Adding comments of video %s.', video.uuid)
231 await crawlCollectionPage<string>(videoObject.comments, (items) => addVideoComments(items, video))
7acee6f1 232
2ccaeeb3
C
233 return { actor, channelActor, video }
234}
235
7acee6f1
C
236async 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
8fffe21a 263async function addVideoShares (shareUrls: string[], instance: VideoModel) {
2ccaeeb3
C
264 for (const shareUrl of shareUrls) {
265 // Fetch url
266 const { body } = await doRequest({
267 uri: shareUrl,
268 json: true,
269 activityPub: true
270 })
8e8234ab
C
271 if (!body || !body.actor) {
272 logger.warn('Cannot add remote share with url: %s, skipping...', shareUrl)
273 continue
274 }
2ccaeeb3 275
8e8234ab 276 const actorUrl = body.actor
2ccaeeb3
C
277 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
278
279 const entry = {
280 actorId: actor.id,
8dfd8fd7
C
281 videoId: instance.id,
282 url: shareUrl
2ccaeeb3
C
283 }
284
285 await VideoShareModel.findOrCreate({
8dfd8fd7
C
286 where: {
287 url: shareUrl
288 },
2ccaeeb3
C
289 defaults: entry
290 })
291 }
0032ebe9
C
292}
293
892211e8 294export {
2ccaeeb3 295 getOrCreateAccountAndVideoAndChannel,
892211e8
C
296 fetchRemoteVideoPreview,
297 fetchRemoteVideoDescription,
0032ebe9 298 generateThumbnailFromUrl,
2ccaeeb3
C
299 videoActivityObjectToDBAttributes,
300 videoFileActivityUrlToDBAttributes,
301 getOrCreateVideo,
0f320037 302 getOrCreateVideoChannel,
938d3fa0
C
303 addVideoShares
304}
2ccaeeb3
C
305
306// ---------------------------------------------------------------------------
307
308async 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
1d6e5dfc 320 if (sanitizeAndCheckVideoTorrentObject(body) === false) {
2ccaeeb3
C
321 logger.debug('Remote video JSON is not valid.', { body })
322 return undefined
323 }
324
325 return body
892211e8 326}