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'
24 function fetchRemoteVideoPreview (video: VideoModel, reject: Function) {
25 const host = video.VideoChannel.Account.Actor.Server.host
26 const path = join(STATIC_PATHS.PREVIEWS, video.getPreviewName())
28 // We need to provide a callback, if no we could have an uncaught exception
29 return request.get(REMOTE_SCHEME.HTTP + '://' + host + path, err => {
34 async function fetchRemoteVideoDescription (video: VideoModel) {
35 const host = video.VideoChannel.Account.Actor.Server.host
36 const path = video.getDescriptionPath()
38 uri: REMOTE_SCHEME.HTTP + '://' + host + path,
42 const { body } = await doRequest(options)
43 return body.description ? body.description : ''
46 function generateThumbnailFromUrl (video: VideoModel, icon: ActivityIconObject) {
47 const thumbnailName = video.getThumbnailName()
48 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName)
54 return doRequestAndSaveToFile(options, thumbnailPath)
57 async function videoActivityObjectToDBAttributes (videoChannel: VideoChannelModel,
58 videoObject: VideoTorrentObject,
60 const privacy = to.indexOf(ACTIVITY_PUB.PUBLIC) !== -1 ? VideoPrivacy.PUBLIC : VideoPrivacy.UNLISTED
61 const duration = videoObject.duration.replace(/[^\d]+/, '')
63 let language: string = null
64 if (videoObject.language) {
65 language = videoObject.language.identifier
68 let category: number = null
69 if (videoObject.category) {
70 category = parseInt(videoObject.category.identifier, 10)
73 let licence: number = null
74 if (videoObject.licence) {
75 licence = parseInt(videoObject.licence.identifier, 10)
78 const description = videoObject.content || null
79 const support = videoObject.support || null
82 name: videoObject.name,
83 uuid: videoObject.uuid,
90 nsfw: videoObject.sensitive,
91 commentsEnabled: videoObject.commentsEnabled,
92 channelId: videoChannel.id,
93 duration: parseInt(duration, 10),
94 createdAt: new Date(videoObject.published),
95 // FIXME: updatedAt does not seems to be considered by Sequelize
96 updatedAt: new Date(videoObject.updated),
97 views: videoObject.views,
105 function videoFileActivityUrlToDBAttributes (videoCreated: VideoModel, videoObject: VideoTorrentObject) {
106 const mimeTypes = Object.keys(VIDEO_MIMETYPE_EXT)
107 const fileUrls = videoObject.url.filter(u => {
108 return mimeTypes.indexOf(u.mimeType) !== -1 && u.mimeType.startsWith('video/')
111 if (fileUrls.length === 0) {
112 throw new Error('Cannot find video files for ' + videoCreated.url)
115 const attributes = []
116 for (const fileUrl of fileUrls) {
117 // Fetch associated magnet uri
118 const magnet = videoObject.url.find(u => {
119 return u.mimeType === 'application/x-bittorrent;x-scheme-handler/magnet' && u.width === fileUrl.width
122 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
124 const parsed = magnetUtil.decode(magnet.href)
125 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) throw new Error('Cannot parse magnet URI ' + magnet.href)
128 extname: VIDEO_MIMETYPE_EXT[ fileUrl.mimeType ],
129 infoHash: parsed.infoHash,
130 resolution: fileUrl.width,
132 videoId: videoCreated.id
134 attributes.push(attribute)
140 function getOrCreateVideoChannel (videoObject: VideoTorrentObject) {
141 const channel = videoObject.attributedTo.find(a => a.type === 'Group')
142 if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
144 return getOrCreateActorAndServerAndModel(channel.id)
147 async function getOrCreateVideo (videoObject: VideoTorrentObject, channelActor: ActorModel) {
148 logger.debug('Adding remote video %s.', videoObject.id)
150 return sequelizeTypescript.transaction(async t => {
151 const sequelizeOptions = {
154 const videoFromDatabase = await VideoModel.loadByUUIDOrURLAndPopulateAccount(videoObject.uuid, videoObject.id, t)
155 if (videoFromDatabase) return videoFromDatabase
157 const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to)
158 const video = VideoModel.build(videoData)
160 // Don't block on request
161 generateThumbnailFromUrl(video, videoObject.icon)
162 .catch(err => logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err }))
164 const videoCreated = await video.save(sequelizeOptions)
166 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject)
167 if (videoFileAttributes.length === 0) {
168 throw new Error('Cannot find valid files for video %s ' + videoObject.url)
171 const tasks = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
172 await Promise.all(tasks)
174 const tags = videoObject.tag.map(t => t.name)
175 const tagInstances = await TagModel.findOrCreateTags(tags, t)
176 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
178 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
180 videoCreated.VideoChannel = channelActor.VideoChannel
185 async function getOrCreateAccountAndVideoAndChannel (videoObject: VideoTorrentObject | string, actor?: ActorModel) {
186 if (typeof videoObject === 'string') {
187 const videoUrl = videoObject
189 const videoFromDatabase = await VideoModel.loadByUrlAndPopulateAccount(videoUrl)
190 if (videoFromDatabase) {
192 video: videoFromDatabase,
193 actor: videoFromDatabase.VideoChannel.Account.Actor,
194 channelActor: videoFromDatabase.VideoChannel.Actor
198 videoObject = await fetchRemoteVideo(videoUrl)
199 if (!videoObject) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
203 const actorObj = videoObject.attributedTo.find(a => a.type === 'Person')
204 if (!actorObj) throw new Error('Cannot find associated actor to video ' + videoObject.url)
206 actor = await getOrCreateActorAndServerAndModel(actorObj.id)
209 const channelActor = await getOrCreateVideoChannel(videoObject)
212 arguments: [ videoObject, channelActor ],
213 errorMessage: 'Cannot insert the remote video with many retries.'
216 const video = await retryTransactionWrapper(getOrCreateVideo, options)
218 // Process outside the transaction because we could fetch remote data
219 if (videoObject.likes && Array.isArray(videoObject.likes.orderedItems)) {
220 logger.info('Adding likes of video %s.', video.uuid)
221 await createRates(videoObject.likes.orderedItems, video, 'like')
224 if (videoObject.dislikes && Array.isArray(videoObject.dislikes.orderedItems)) {
225 logger.info('Adding dislikes of video %s.', video.uuid)
226 await createRates(videoObject.dislikes.orderedItems, video, 'dislike')
229 if (videoObject.shares && Array.isArray(videoObject.shares.orderedItems)) {
230 logger.info('Adding shares of video %s.', video.uuid)
231 await addVideoShares(video, videoObject.shares.orderedItems)
234 if (videoObject.comments && Array.isArray(videoObject.comments.orderedItems)) {
235 logger.info('Adding comments of video %s.', video.uuid)
236 await addVideoComments(video, videoObject.comments.orderedItems)
239 return { actor, channelActor, video }
242 async function createRates (actorUrls: string[], video: VideoModel, rate: VideoRateType) {
244 const tasks: Bluebird<number>[] = []
246 for (const actorUrl of actorUrls) {
247 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
248 const p = AccountVideoRateModel
251 accountId: actor.Account.id,
254 .then(() => rateCounts += 1)
259 await Promise.all(tasks)
261 logger.info('Adding %d %s to video %s.', rateCounts, rate, video.uuid)
263 // This is "likes" and "dislikes"
264 await video.increment(rate + 's', { by: rateCounts })
269 async function addVideoShares (instance: VideoModel, shareUrls: string[]) {
270 for (const shareUrl of shareUrls) {
272 const { body } = await doRequest({
277 if (!body || !body.actor) {
278 logger.warn('Cannot add remote share with url: %s, skipping...', shareUrl)
282 const actorUrl = body.actor
283 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
287 videoId: instance.id,
291 await VideoShareModel.findOrCreate({
301 getOrCreateAccountAndVideoAndChannel,
302 fetchRemoteVideoPreview,
303 fetchRemoteVideoDescription,
304 generateThumbnailFromUrl,
305 videoActivityObjectToDBAttributes,
306 videoFileActivityUrlToDBAttributes,
308 getOrCreateVideoChannel,
311 // ---------------------------------------------------------------------------
313 async function fetchRemoteVideo (videoUrl: string): Promise<VideoTorrentObject> {
321 logger.info('Fetching remote video %s.', videoUrl)
323 const { body } = await doRequest(options)
325 if (sanitizeAndCheckVideoTorrentObject(body) === false) {
326 logger.debug('Remote video JSON is not valid.', { body })