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'
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())
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 => {
35 async function fetchRemoteVideoDescription (video: VideoModel) {
36 const host = video.VideoChannel.Account.Actor.Server.host
37 const path = video.getDescriptionPath()
39 uri: REMOTE_SCHEME.HTTP + '://' + host + path,
43 const { body } = await doRequest(options)
44 return body.description ? body.description : ''
47 function generateThumbnailFromUrl (video: VideoModel, icon: ActivityIconObject) {
48 const thumbnailName = video.getThumbnailName()
49 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName)
55 return doRequestAndSaveToFile(options, thumbnailPath)
58 async function videoActivityObjectToDBAttributes (videoChannel: VideoChannelModel,
59 videoObject: VideoTorrentObject,
61 const privacy = to.indexOf(ACTIVITY_PUB.PUBLIC) !== -1 ? VideoPrivacy.PUBLIC : VideoPrivacy.UNLISTED
62 const duration = videoObject.duration.replace(/[^\d]+/, '')
64 let language: string = null
65 if (videoObject.language) {
66 language = videoObject.language.identifier
69 let category: number = null
70 if (videoObject.category) {
71 category = parseInt(videoObject.category.identifier, 10)
74 let licence: number = null
75 if (videoObject.licence) {
76 licence = parseInt(videoObject.licence.identifier, 10)
79 const description = videoObject.content || null
80 const support = videoObject.support || null
83 name: videoObject.name,
84 uuid: videoObject.uuid,
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,
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/')
112 if (fileUrls.length === 0) {
113 throw new Error('Cannot find video files for ' + videoCreated.url)
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
123 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
125 const parsed = magnetUtil.decode(magnet.href)
126 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) throw new Error('Cannot parse magnet URI ' + magnet.href)
129 extname: VIDEO_MIMETYPE_EXT[ fileUrl.mimeType ],
130 infoHash: parsed.infoHash,
131 resolution: fileUrl.width,
133 videoId: videoCreated.id
135 attributes.push(attribute)
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)
145 return getOrCreateActorAndServerAndModel(channel.id)
148 async function getOrCreateVideo (videoObject: VideoTorrentObject, channelActor: ActorModel) {
149 logger.debug('Adding remote video %s.', videoObject.id)
151 return sequelizeTypescript.transaction(async t => {
152 const sequelizeOptions = {
155 const videoFromDatabase = await VideoModel.loadByUUIDOrURLAndPopulateAccount(videoObject.uuid, videoObject.id, t)
156 if (videoFromDatabase) return videoFromDatabase
158 const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to)
159 const video = VideoModel.build(videoData)
161 // Don't block on request
162 generateThumbnailFromUrl(video, videoObject.icon)
163 .catch(err => logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err }))
165 const videoCreated = await video.save(sequelizeOptions)
167 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject)
168 if (videoFileAttributes.length === 0) {
169 throw new Error('Cannot find valid files for video %s ' + videoObject.url)
172 const tasks = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
173 await Promise.all(tasks)
175 const tags = videoObject.tag.map(t => t.name)
176 const tagInstances = await TagModel.findOrCreateTags(tags, t)
177 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
179 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
181 videoCreated.VideoChannel = channelActor.VideoChannel
186 async function getOrCreateAccountAndVideoAndChannel (videoObject: VideoTorrentObject | string, actor?: ActorModel) {
187 if (typeof videoObject === 'string') {
188 const videoUrl = videoObject
190 const videoFromDatabase = await VideoModel.loadByUrlAndPopulateAccount(videoUrl)
191 if (videoFromDatabase) {
193 video: videoFromDatabase,
194 actor: videoFromDatabase.VideoChannel.Account.Actor,
195 channelActor: videoFromDatabase.VideoChannel.Actor
199 videoObject = await fetchRemoteVideo(videoUrl)
200 if (!videoObject) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
204 const actorObj = videoObject.attributedTo.find(a => a.type === 'Person')
205 if (!actorObj) throw new Error('Cannot find associated actor to video ' + videoObject.url)
207 actor = await getOrCreateActorAndServerAndModel(actorObj.id)
210 const channelActor = await getOrCreateVideoChannel(videoObject)
213 arguments: [ videoObject, channelActor ],
214 errorMessage: 'Cannot insert the remote video with many retries.'
217 const video = await retryTransactionWrapper(getOrCreateVideo, options)
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'))
223 logger.info('Adding dislikes of video %s.', video.uuid)
224 await crawlCollectionPage<string>(videoObject.dislikes, (items) => createRates(items, video, 'dislike'))
226 logger.info('Adding shares of video %s.', video.uuid)
227 await crawlCollectionPage<string>(videoObject.shares, (items) => addVideoShares(items, video))
229 logger.info('Adding comments of video %s.', video.uuid)
230 await crawlCollectionPage<string>(videoObject.comments, (items) => addVideoComments(items, video))
232 return { actor, channelActor, video }
235 async function createRates (actorUrls: string[], video: VideoModel, rate: VideoRateType) {
237 const tasks: Bluebird<number>[] = []
239 for (const actorUrl of actorUrls) {
240 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
241 const p = AccountVideoRateModel
244 accountId: actor.Account.id,
247 .then(() => rateCounts += 1)
252 await Promise.all(tasks)
254 logger.info('Adding %d %s to video %s.', rateCounts, rate, video.uuid)
256 // This is "likes" and "dislikes"
257 await video.increment(rate + 's', { by: rateCounts })
262 async function addVideoShares (shareUrls: string[], instance: VideoModel) {
263 for (const shareUrl of shareUrls) {
265 const { body } = await doRequest({
270 if (!body || !body.actor) {
271 logger.warn('Cannot add remote share with url: %s, skipping...', shareUrl)
275 const actorUrl = body.actor
276 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
280 videoId: instance.id,
284 await VideoShareModel.findOrCreate({
294 getOrCreateAccountAndVideoAndChannel,
295 fetchRemoteVideoPreview,
296 fetchRemoteVideoDescription,
297 generateThumbnailFromUrl,
298 videoActivityObjectToDBAttributes,
299 videoFileActivityUrlToDBAttributes,
301 getOrCreateVideoChannel,
305 // ---------------------------------------------------------------------------
307 async function fetchRemoteVideo (videoUrl: string): Promise<VideoTorrentObject> {
315 logger.info('Fetching remote video %s.', videoUrl)
317 const { body } = await doRequest(options)
319 if (sanitizeAndCheckVideoTorrentObject(body) === false) {
320 logger.debug('Remote video JSON is not valid.', { body })