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 } from '../../../shared/models/videos'
8 import { isVideoTorrentObjectValid } 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 { ActorModel } from '../../models/activitypub/actor'
15 import { TagModel } from '../../models/video/tag'
16 import { VideoModel } from '../../models/video/video'
17 import { VideoChannelModel } from '../../models/video/video-channel'
18 import { VideoFileModel } from '../../models/video/video-file'
19 import { VideoShareModel } from '../../models/video/video-share'
20 import { getOrCreateActorAndServerAndModel } from './actor'
22 function fetchRemoteVideoPreview (video: VideoModel, reject: Function) {
23 const host = video.VideoChannel.Account.Actor.Server.host
24 const path = join(STATIC_PATHS.PREVIEWS, video.getPreviewName())
26 // We need to provide a callback, if no we could have an uncaught exception
27 return request.get(REMOTE_SCHEME.HTTP + '://' + host + path, err => {
32 async function fetchRemoteVideoDescription (video: VideoModel) {
33 const host = video.VideoChannel.Account.Actor.Server.host
34 const path = video.getDescriptionPath()
36 uri: REMOTE_SCHEME.HTTP + '://' + host + path,
40 const { body } = await doRequest(options)
41 return body.description ? body.description : ''
44 function generateThumbnailFromUrl (video: VideoModel, icon: ActivityIconObject) {
45 const thumbnailName = video.getThumbnailName()
46 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName)
52 return doRequestAndSaveToFile(options, thumbnailPath)
55 async function videoActivityObjectToDBAttributes (videoChannel: VideoChannelModel,
56 videoObject: VideoTorrentObject,
59 let privacy = VideoPrivacy.PRIVATE
60 if (to.indexOf(ACTIVITY_PUB.PUBLIC) !== -1) privacy = VideoPrivacy.PUBLIC
61 else if (cc.indexOf(ACTIVITY_PUB.PUBLIC) !== -1) privacy = VideoPrivacy.UNLISTED
63 const duration = videoObject.duration.replace(/[^\d]+/, '')
65 if (videoObject.language) {
66 language = parseInt(videoObject.language.identifier, 10)
70 if (videoObject.category) {
71 category = parseInt(videoObject.category.identifier, 10)
75 if (videoObject.licence) {
76 licence = parseInt(videoObject.licence.identifier, 10)
79 let description = null
80 if (videoObject.content) {
81 description = videoObject.content
85 name: videoObject.name,
86 uuid: videoObject.uuid,
92 nsfw: videoObject.nsfw,
93 commentsEnabled: videoObject.commentsEnabled,
94 channelId: videoChannel.id,
95 duration: parseInt(duration, 10),
96 createdAt: 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 async function getOrCreateVideo (videoObject: VideoTorrentObject, channelActor: ActorModel) {
143 logger.debug('Adding remote video %s.', videoObject.id)
145 return sequelizeTypescript.transaction(async t => {
146 const sequelizeOptions = {
149 const videoFromDatabase = await VideoModel.loadByUUIDOrURLAndPopulateAccount(videoObject.uuid, videoObject.id, t)
150 if (videoFromDatabase) return videoFromDatabase
152 const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to, videoObject.cc)
153 const video = VideoModel.build(videoData)
155 // Don't block on request
156 generateThumbnailFromUrl(video, videoObject.icon)
157 .catch(err => logger.warn('Cannot generate thumbnail of %s.', videoObject.id, err))
159 const videoCreated = await video.save(sequelizeOptions)
161 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject)
162 if (videoFileAttributes.length === 0) {
163 throw new Error('Cannot find valid files for video %s ' + videoObject.url)
166 const tasks = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
167 await Promise.all(tasks)
169 const tags = videoObject.tag.map(t => t.name)
170 const tagInstances = await TagModel.findOrCreateTags(tags, t)
171 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
173 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
175 videoCreated.VideoChannel = channelActor.VideoChannel
180 async function getOrCreateAccountAndVideoAndChannel (videoObject: VideoTorrentObject | string, actor?: ActorModel) {
181 if (typeof videoObject === 'string') {
182 const videoFromDatabase = await VideoModel.loadByUrlAndPopulateAccount(videoObject)
183 if (videoFromDatabase) {
185 video: videoFromDatabase,
186 actor: videoFromDatabase.VideoChannel.Account.Actor,
187 channelActor: videoFromDatabase.VideoChannel.Actor
191 videoObject = await fetchRemoteVideo(videoObject)
192 if (!videoObject) throw new Error('Cannot fetch remote video')
196 const actorObj = videoObject.attributedTo.find(a => a.type === 'Person')
197 if (!actorObj) throw new Error('Cannot find associated actor to video ' + videoObject.url)
199 actor = await getOrCreateActorAndServerAndModel(actorObj.id)
202 const channel = videoObject.attributedTo.find(a => a.type === 'Group')
203 if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
205 const channelActor = await getOrCreateActorAndServerAndModel(channel.id)
208 arguments: [ videoObject, channelActor ],
209 errorMessage: 'Cannot insert the remote video with many retries.'
212 const video = await retryTransactionWrapper(getOrCreateVideo, options)
214 return { actor, channelActor, video }
217 async function addVideoShares (instance: VideoModel, shareUrls: string[]) {
218 for (const shareUrl of shareUrls) {
220 const { body } = await doRequest({
225 const actorUrl = body.actor
226 if (!actorUrl) continue
228 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
235 await VideoShareModel.findOrCreate({
243 getOrCreateAccountAndVideoAndChannel,
244 fetchRemoteVideoPreview,
245 fetchRemoteVideoDescription,
246 generateThumbnailFromUrl,
247 videoActivityObjectToDBAttributes,
248 videoFileActivityUrlToDBAttributes,
252 // ---------------------------------------------------------------------------
254 async function fetchRemoteVideo (videoUrl: string): Promise<VideoTorrentObject> {
262 logger.info('Fetching remote video %s.', videoUrl)
264 const { body } = await doRequest(options)
266 if (isVideoTorrentObjectValid(body) === false) {
267 logger.debug('Remote video JSON is not valid.', { body })