1 import { VideoTorrentObject } from '../../../shared'
2 import { ActivityAdd } from '../../../shared/models/activitypub/activity'
3 import { generateThumbnailFromUrl, logger, retryTransactionWrapper, getOrCreateAccount } from '../../helpers'
4 import { database as db } from '../../initializers'
5 import { AccountInstance } from '../../models/account/account-interface'
6 import { videoActivityObjectToDBAttributes, videoFileActivityUrlToDBAttributes } from './misc'
7 import Bluebird = require('bluebird')
9 async function processAddActivity (activity: ActivityAdd) {
10 const activityObject = activity.object
11 const activityType = activityObject.type
12 const account = await getOrCreateAccount(activity.actor)
14 if (activityType === 'Video') {
15 return processAddVideo(account, activity.id, activityObject as VideoTorrentObject)
18 logger.warn('Unknown activity object type %s when creating activity.', activityType, { activity: activity.id })
19 return Promise.resolve(undefined)
22 // ---------------------------------------------------------------------------
28 // ---------------------------------------------------------------------------
30 function processAddVideo (account: AccountInstance, videoChannelUrl: string, video: VideoTorrentObject) {
32 arguments: [ account, videoChannelUrl, video ],
33 errorMessage: 'Cannot insert the remote video with many retries.'
36 return retryTransactionWrapper(addRemoteVideo, options)
39 async function addRemoteVideo (account: AccountInstance, videoChannelUrl: string, videoToCreateData: VideoTorrentObject) {
40 logger.debug('Adding remote video %s.', videoToCreateData.url)
42 await db.sequelize.transaction(async t => {
43 const sequelizeOptions = {
47 const videoChannel = await db.VideoChannel.loadByUrl(videoChannelUrl, t)
48 if (!videoChannel) throw new Error('Video channel not found.')
50 if (videoChannel.Account.id !== account.id) throw new Error('Video channel is not owned by this account.')
52 const videoData = await videoActivityObjectToDBAttributes(videoChannel, videoToCreateData, t)
53 const video = db.Video.build(videoData)
55 // Don't block on request
56 generateThumbnailFromUrl(video, videoToCreateData.icon)
57 .catch(err => logger.warning('Cannot generate thumbnail of %s.', videoToCreateData.id, err))
59 const videoCreated = await video.save(sequelizeOptions)
61 const videoFileAttributes = await videoFileActivityUrlToDBAttributes(videoCreated, videoToCreateData)
63 const tasks: Bluebird<any>[] = videoFileAttributes.map(f => db.VideoFile.create(f))
64 await Promise.all(tasks)
66 const tags = videoToCreateData.tag.map(t => t.name)
67 const tagInstances = await db.Tag.findOrCreateTags(tags, t)
68 await videoCreated.setTags(tagInstances, sequelizeOptions)
71 logger.info('Remote video with uuid %s inserted.', videoToCreateData.uuid)