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 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,
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/')
113 if (fileUrls.length === 0) {
114 throw new Error('Cannot find video files for ' + videoCreated.url)
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
124 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
126 const parsed = magnetUtil.decode(magnet.href)
127 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) throw new Error('Cannot parse magnet URI ' + magnet.href)
130 extname: VIDEO_MIMETYPE_EXT[ fileUrl.mimeType ],
131 infoHash: parsed.infoHash,
132 resolution: fileUrl.width,
134 videoId: videoCreated.id
136 attributes.push(attribute)
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)
146 return getOrCreateActorAndServerAndModel(channel.id)
149 async function getOrCreateVideo (videoObject: VideoTorrentObject, channelActor: ActorModel) {
150 logger.debug('Adding remote video %s.', videoObject.id)
152 return sequelizeTypescript.transaction(async t => {
153 const sequelizeOptions = {
156 const videoFromDatabase = await VideoModel.loadByUUIDOrURLAndPopulateAccount(videoObject.uuid, videoObject.id, t)
157 if (videoFromDatabase) return videoFromDatabase
159 const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to)
160 const video = VideoModel.build(videoData)
162 // Don't block on request
163 generateThumbnailFromUrl(video, videoObject.icon)
164 .catch(err => logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err }))
166 const videoCreated = await video.save(sequelizeOptions)
168 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject)
169 if (videoFileAttributes.length === 0) {
170 throw new Error('Cannot find valid files for video %s ' + videoObject.url)
173 const tasks = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
174 await Promise.all(tasks)
176 const tags = videoObject.tag.map(t => t.name)
177 const tagInstances = await TagModel.findOrCreateTags(tags, t)
178 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
180 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
182 videoCreated.VideoChannel = channelActor.VideoChannel
187 async function getOrCreateAccountAndVideoAndChannel (videoObject: VideoTorrentObject | string, actor?: ActorModel) {
188 if (typeof videoObject === 'string') {
189 const videoUrl = videoObject
191 const videoFromDatabase = await VideoModel.loadByUrlAndPopulateAccount(videoUrl)
192 if (videoFromDatabase) {
194 video: videoFromDatabase,
195 actor: videoFromDatabase.VideoChannel.Account.Actor,
196 channelActor: videoFromDatabase.VideoChannel.Actor
200 videoObject = await fetchRemoteVideo(videoUrl)
201 if (!videoObject) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
205 const actorObj = videoObject.attributedTo.find(a => a.type === 'Person')
206 if (!actorObj) throw new Error('Cannot find associated actor to video ' + videoObject.url)
208 actor = await getOrCreateActorAndServerAndModel(actorObj.id)
211 const channelActor = await getOrCreateVideoChannel(videoObject)
214 arguments: [ videoObject, channelActor ],
215 errorMessage: 'Cannot insert the remote video with many retries.'
218 const video = await retryTransactionWrapper(getOrCreateVideo, options)
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'))
224 logger.info('Adding dislikes of video %s.', video.uuid)
225 await crawlCollectionPage<string>(videoObject.dislikes, (items) => createRates(items, video, 'dislike'))
227 logger.info('Adding shares of video %s.', video.uuid)
228 await crawlCollectionPage<string>(videoObject.shares, (items) => addVideoShares(items, video))
230 logger.info('Adding comments of video %s.', video.uuid)
231 await crawlCollectionPage<string>(videoObject.comments, (items) => addVideoComments(items, video))
233 return { actor, channelActor, video }
236 async function createRates (actorUrls: string[], video: VideoModel, rate: VideoRateType) {
238 const tasks: Bluebird<number>[] = []
240 for (const actorUrl of actorUrls) {
241 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
242 const p = AccountVideoRateModel
245 accountId: actor.Account.id,
248 .then(() => rateCounts += 1)
253 await Promise.all(tasks)
255 logger.info('Adding %d %s to video %s.', rateCounts, rate, video.uuid)
257 // This is "likes" and "dislikes"
258 await video.increment(rate + 's', { by: rateCounts })
263 async function addVideoShares (shareUrls: string[], instance: VideoModel) {
264 for (const shareUrl of shareUrls) {
266 const { body } = await doRequest({
271 if (!body || !body.actor) {
272 logger.warn('Cannot add remote share with url: %s, skipping...', shareUrl)
276 const actorUrl = body.actor
277 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
281 videoId: instance.id,
285 await VideoShareModel.findOrCreate({
295 getOrCreateAccountAndVideoAndChannel,
296 fetchRemoteVideoPreview,
297 fetchRemoteVideoDescription,
298 generateThumbnailFromUrl,
299 videoActivityObjectToDBAttributes,
300 videoFileActivityUrlToDBAttributes,
302 getOrCreateVideoChannel,
306 // ---------------------------------------------------------------------------
308 async function fetchRemoteVideo (videoUrl: string): Promise<VideoTorrentObject> {
316 logger.info('Fetching remote video %s.', videoUrl)
318 const { body } = await doRequest(options)
320 if (sanitizeAndCheckVideoTorrentObject(body) === false) {
321 logger.debug('Remote video JSON is not valid.', { body })