1 import * as Bluebird from 'bluebird'
2 import * as sequelize from 'sequelize'
3 import * as magnetUtil from 'magnet-uri'
4 import { join } from 'path'
5 import * as request from 'request'
6 import { ActivityIconObject, VideoState } from '../../../shared/index'
7 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
8 import { VideoPrivacy, VideoRateType } from '../../../shared/models/videos'
9 import { sanitizeAndCheckVideoTorrentObject } from '../../helpers/custom-validators/activitypub/videos'
10 import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
11 import { retryTransactionWrapper } from '../../helpers/database-utils'
12 import { logger } from '../../helpers/logger'
13 import { doRequest, doRequestAndSaveToFile } from '../../helpers/requests'
14 import { ACTIVITY_PUB, CONFIG, CRAWL_REQUEST_CONCURRENCY, REMOTE_SCHEME, sequelizeTypescript, VIDEO_MIMETYPE_EXT } from '../../initializers'
15 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
16 import { ActorModel } from '../../models/activitypub/actor'
17 import { TagModel } from '../../models/video/tag'
18 import { VideoModel } from '../../models/video/video'
19 import { VideoChannelModel } from '../../models/video/video-channel'
20 import { VideoFileModel } from '../../models/video/video-file'
21 import { VideoShareModel } from '../../models/video/video-share'
22 import { getOrCreateActorAndServerAndModel } from './actor'
23 import { addVideoComments } from './video-comments'
24 import { crawlCollectionPage } from './crawl'
25 import { sendCreateVideo, sendUpdateVideo } from './send'
26 import { shareVideoByServerAndChannel } from './index'
27 import { isArray } from '../../helpers/custom-validators/misc'
28 import { VideoCaptionModel } from '../../models/video/video-caption'
29 import { JobQueue } from '../job-queue'
30 import { ActivitypubHttpFetcherPayload } from '../job-queue/handlers/activitypub-http-fetcher'
32 async function federateVideoIfNeeded (video: VideoModel, isNewVideo: boolean, transaction?: sequelize.Transaction) {
33 // If the video is not private and published, we federate it
34 if (video.privacy !== VideoPrivacy.PRIVATE && video.state === VideoState.PUBLISHED) {
35 // Fetch more attributes that we will need to serialize in AP object
36 if (isArray(video.VideoCaptions) === false) {
37 video.VideoCaptions = await video.$get('VideoCaptions', {
38 attributes: [ 'language' ],
40 }) as VideoCaptionModel[]
44 // Now we'll add the video's meta data to our followers
45 await sendCreateVideo(video, transaction)
46 await shareVideoByServerAndChannel(video, transaction)
48 await sendUpdateVideo(video, transaction)
53 function fetchRemoteVideoStaticFile (video: VideoModel, path: string, reject: Function) {
54 const host = video.VideoChannel.Account.Actor.Server.host
56 // We need to provide a callback, if no we could have an uncaught exception
57 return request.get(REMOTE_SCHEME.HTTP + '://' + host + path, err => {
62 async function fetchRemoteVideoDescription (video: VideoModel) {
63 const host = video.VideoChannel.Account.Actor.Server.host
64 const path = video.getDescriptionPath()
66 uri: REMOTE_SCHEME.HTTP + '://' + host + path,
70 const { body } = await doRequest(options)
71 return body.description ? body.description : ''
74 function generateThumbnailFromUrl (video: VideoModel, icon: ActivityIconObject) {
75 const thumbnailName = video.getThumbnailName()
76 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName)
82 return doRequestAndSaveToFile(options, thumbnailPath)
85 async function videoActivityObjectToDBAttributes (
86 videoChannel: VideoChannelModel,
87 videoObject: VideoTorrentObject,
90 const privacy = to.indexOf(ACTIVITY_PUB.PUBLIC) !== -1 ? VideoPrivacy.PUBLIC : VideoPrivacy.UNLISTED
91 const duration = videoObject.duration.replace(/[^\d]+/, '')
93 let language: string | undefined
94 if (videoObject.language) {
95 language = videoObject.language.identifier
98 let category: number | undefined
99 if (videoObject.category) {
100 category = parseInt(videoObject.category.identifier, 10)
103 let licence: number | undefined
104 if (videoObject.licence) {
105 licence = parseInt(videoObject.licence.identifier, 10)
108 const description = videoObject.content || null
109 const support = videoObject.support || null
112 name: videoObject.name,
113 uuid: videoObject.uuid,
120 nsfw: videoObject.sensitive,
121 commentsEnabled: videoObject.commentsEnabled,
122 waitTranscoding: videoObject.waitTranscoding,
123 state: videoObject.state,
124 channelId: videoChannel.id,
125 duration: parseInt(duration, 10),
126 createdAt: new Date(videoObject.published),
127 publishedAt: new Date(videoObject.published),
128 // FIXME: updatedAt does not seems to be considered by Sequelize
129 updatedAt: new Date(videoObject.updated),
130 views: videoObject.views,
138 function videoFileActivityUrlToDBAttributes (videoCreated: VideoModel, videoObject: VideoTorrentObject) {
139 const mimeTypes = Object.keys(VIDEO_MIMETYPE_EXT)
140 const fileUrls = videoObject.url.filter(u => {
141 return mimeTypes.indexOf(u.mimeType) !== -1 && u.mimeType.startsWith('video/')
144 if (fileUrls.length === 0) {
145 throw new Error('Cannot find video files for ' + videoCreated.url)
148 const attributes: VideoFileModel[] = []
149 for (const fileUrl of fileUrls) {
150 // Fetch associated magnet uri
151 const magnet = videoObject.url.find(u => {
152 return u.mimeType === 'application/x-bittorrent;x-scheme-handler/magnet' && u.height === fileUrl.height
155 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
157 const parsed = magnetUtil.decode(magnet.href)
158 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) {
159 throw new Error('Cannot parse magnet URI ' + magnet.href)
163 extname: VIDEO_MIMETYPE_EXT[ fileUrl.mimeType ],
164 infoHash: parsed.infoHash,
165 resolution: fileUrl.height,
167 videoId: videoCreated.id,
170 attributes.push(attribute)
176 function getOrCreateVideoChannel (videoObject: VideoTorrentObject) {
177 const channel = videoObject.attributedTo.find(a => a.type === 'Group')
178 if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
180 return getOrCreateActorAndServerAndModel(channel.id)
183 async function getOrCreateVideo (videoObject: VideoTorrentObject, channelActor: ActorModel, waitThumbnail = false) {
184 logger.debug('Adding remote video %s.', videoObject.id)
186 const videoCreated: VideoModel = await sequelizeTypescript.transaction(async t => {
187 const sequelizeOptions = {
190 const videoFromDatabase = await VideoModel.loadByUUIDOrURLAndPopulateAccount(videoObject.uuid, videoObject.id, t)
191 if (videoFromDatabase) return videoFromDatabase
193 const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to)
194 const video = VideoModel.build(videoData)
196 const videoCreated = await video.save(sequelizeOptions)
199 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject)
200 if (videoFileAttributes.length === 0) {
201 throw new Error('Cannot find valid files for video %s ' + videoObject.url)
204 const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
205 await Promise.all(videoFilePromises)
208 const tags = videoObject.tag.map(t => t.name)
209 const tagInstances = await TagModel.findOrCreateTags(tags, t)
210 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
213 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
214 return VideoCaptionModel.insertOrReplaceLanguage(videoCreated.id, c.identifier, t)
216 await Promise.all(videoCaptionsPromises)
218 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
220 videoCreated.VideoChannel = channelActor.VideoChannel
224 const p = generateThumbnailFromUrl(videoCreated, videoObject.icon)
225 .catch(err => logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err }))
227 if (waitThumbnail === true) await p
239 async function getOrCreateAccountAndVideoAndChannel (
240 videoObject: VideoTorrentObject | string,
241 syncParam: SyncParam = { likes: true, dislikes: true, shares: true, comments: true, thumbnail: true }
243 const videoUrl = typeof videoObject === 'string' ? videoObject : videoObject.id
245 const videoFromDatabase = await VideoModel.loadByUrlAndPopulateAccount(videoUrl)
246 if (videoFromDatabase) return { video: videoFromDatabase }
248 const fetchedVideo = await fetchRemoteVideo(videoUrl)
249 if (!fetchedVideo) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
251 const channelActor = await getOrCreateVideoChannel(fetchedVideo)
252 const video = await retryTransactionWrapper(getOrCreateVideo, fetchedVideo, channelActor, syncParam.thumbnail)
254 // Process outside the transaction because we could fetch remote data
256 logger.info('Adding likes/dislikes/shares/comments of video %s.', video.uuid)
258 const jobPayloads: ActivitypubHttpFetcherPayload[] = []
260 if (syncParam.likes === true) {
261 await crawlCollectionPage<string>(fetchedVideo.likes, items => createRates(items, video, 'like'))
262 .catch(err => logger.error('Cannot add likes of video %s.', video.uuid, { err }))
264 jobPayloads.push({ uri: fetchedVideo.likes, videoId: video.id, type: 'video-likes' as 'video-likes' })
267 if (syncParam.dislikes === true) {
268 await crawlCollectionPage<string>(fetchedVideo.dislikes, items => createRates(items, video, 'dislike'))
269 .catch(err => logger.error('Cannot add dislikes of video %s.', video.uuid, { err }))
271 jobPayloads.push({ uri: fetchedVideo.dislikes, videoId: video.id, type: 'video-dislikes' as 'video-dislikes' })
274 if (syncParam.shares === true) {
275 await crawlCollectionPage<string>(fetchedVideo.shares, items => addVideoShares(items, video))
276 .catch(err => logger.error('Cannot add shares of video %s.', video.uuid, { err }))
278 jobPayloads.push({ uri: fetchedVideo.shares, videoId: video.id, type: 'video-shares' as 'video-shares' })
281 if (syncParam.comments === true) {
282 await crawlCollectionPage<string>(fetchedVideo.comments, items => addVideoComments(items, video))
283 .catch(err => logger.error('Cannot add comments of video %s.', video.uuid, { err }))
285 jobPayloads.push({ uri: fetchedVideo.shares, videoId: video.id, type: 'video-shares' as 'video-shares' })
288 await Bluebird.map(jobPayloads, payload => JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload }))
293 async function createRates (actorUrls: string[], video: VideoModel, rate: VideoRateType) {
296 await Bluebird.map(actorUrls, async actorUrl => {
298 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
299 const [ , created ] = await AccountVideoRateModel
303 accountId: actor.Account.id
307 accountId: actor.Account.id,
312 if (created) rateCounts += 1
314 logger.warn('Cannot add rate %s for actor %s.', rate, actorUrl, { err })
316 }, { concurrency: CRAWL_REQUEST_CONCURRENCY })
318 logger.info('Adding %d %s to video %s.', rateCounts, rate, video.uuid)
320 // This is "likes" and "dislikes"
321 if (rateCounts !== 0) await video.increment(rate + 's', { by: rateCounts })
326 async function addVideoShares (shareUrls: string[], instance: VideoModel) {
327 await Bluebird.map(shareUrls, async shareUrl => {
330 const { body } = await doRequest({
335 if (!body || !body.actor) throw new Error('Body of body actor is invalid')
337 const actorUrl = body.actor
338 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
342 videoId: instance.id,
346 await VideoShareModel.findOrCreate({
353 logger.warn('Cannot add share %s.', shareUrl, { err })
355 }, { concurrency: CRAWL_REQUEST_CONCURRENCY })
358 async function fetchRemoteVideo (videoUrl: string): Promise<VideoTorrentObject> {
366 logger.info('Fetching remote video %s.', videoUrl)
368 const { body } = await doRequest(options)
370 if (sanitizeAndCheckVideoTorrentObject(body) === false) {
371 logger.debug('Remote video JSON is not valid.', { body })
379 federateVideoIfNeeded,
381 getOrCreateAccountAndVideoAndChannel,
382 fetchRemoteVideoStaticFile,
383 fetchRemoteVideoDescription,
384 generateThumbnailFromUrl,
385 videoActivityObjectToDBAttributes,
386 videoFileActivityUrlToDBAttributes,
388 getOrCreateVideoChannel,