1 import * as magnetUtil from 'magnet-uri'
2 import { join } from 'path'
3 import * as request from 'request'
4 import { ActivityIconObject } from '../../../shared/index'
5 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
6 import { VideoPrivacy } from '../../../shared/models/videos'
7 import { isVideoTorrentObjectValid } from '../../helpers/custom-validators/activitypub/videos'
8 import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
9 import { retryTransactionWrapper } from '../../helpers/database-utils'
10 import { logger } from '../../helpers/logger'
11 import { doRequest, doRequestAndSaveToFile } from '../../helpers/requests'
12 import { ACTIVITY_PUB, CONFIG, REMOTE_SCHEME, sequelizeTypescript, STATIC_PATHS, VIDEO_MIMETYPE_EXT } from '../../initializers'
13 import { ActorModel } from '../../models/activitypub/actor'
14 import { TagModel } from '../../models/video/tag'
15 import { VideoModel } from '../../models/video/video'
16 import { VideoChannelModel } from '../../models/video/video-channel'
17 import { VideoFileModel } from '../../models/video/video-file'
18 import { VideoShareModel } from '../../models/video/video-share'
19 import { getOrCreateActorAndServerAndModel } from './actor'
21 function fetchRemoteVideoPreview (video: VideoModel, reject: Function) {
22 const host = video.VideoChannel.Account.Actor.Server.host
23 const path = join(STATIC_PATHS.PREVIEWS, video.getPreviewName())
25 // We need to provide a callback, if no we could have an uncaught exception
26 return request.get(REMOTE_SCHEME.HTTP + '://' + host + path, err => {
31 async function fetchRemoteVideoDescription (video: VideoModel) {
32 const host = video.VideoChannel.Account.Actor.Server.host
33 const path = video.getDescriptionPath()
35 uri: REMOTE_SCHEME.HTTP + '://' + host + path,
39 const { body } = await doRequest(options)
40 return body.description ? body.description : ''
43 function generateThumbnailFromUrl (video: VideoModel, icon: ActivityIconObject) {
44 const thumbnailName = video.getThumbnailName()
45 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName)
51 return doRequestAndSaveToFile(options, thumbnailPath)
54 async function videoActivityObjectToDBAttributes (videoChannel: VideoChannelModel,
55 videoObject: VideoTorrentObject,
58 let privacy = VideoPrivacy.PRIVATE
59 if (to.indexOf(ACTIVITY_PUB.PUBLIC) !== -1) privacy = VideoPrivacy.PUBLIC
60 else if (cc.indexOf(ACTIVITY_PUB.PUBLIC) !== -1) privacy = VideoPrivacy.UNLISTED
62 const duration = videoObject.duration.replace(/[^\d]+/, '')
64 if (videoObject.language) {
65 language = parseInt(videoObject.language.identifier, 10)
69 if (videoObject.category) {
70 category = parseInt(videoObject.category.identifier, 10)
74 if (videoObject.licence) {
75 licence = parseInt(videoObject.licence.identifier, 10)
78 let description = null
79 if (videoObject.content) {
80 description = videoObject.content
84 name: videoObject.name,
85 uuid: videoObject.uuid,
91 nsfw: videoObject.nsfw,
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 async function getOrCreateVideo (videoObject: VideoTorrentObject, channelActor: ActorModel) {
142 logger.debug('Adding remote video %s.', videoObject.id)
144 return sequelizeTypescript.transaction(async t => {
145 const sequelizeOptions = {
148 const videoFromDatabase = await VideoModel.loadByUUIDOrURLAndPopulateAccount(videoObject.uuid, videoObject.id, t)
149 if (videoFromDatabase) return videoFromDatabase
151 const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to, videoObject.cc)
152 const video = VideoModel.build(videoData)
154 // Don't block on request
155 generateThumbnailFromUrl(video, videoObject.icon)
156 .catch(err => logger.warn('Cannot generate thumbnail of %s.', videoObject.id, err))
158 const videoCreated = await video.save(sequelizeOptions)
160 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject)
161 if (videoFileAttributes.length === 0) {
162 throw new Error('Cannot find valid files for video %s ' + videoObject.url)
165 const tasks = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
166 await Promise.all(tasks)
168 const tags = videoObject.tag.map(t => t.name)
169 const tagInstances = await TagModel.findOrCreateTags(tags, t)
170 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
172 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
174 videoCreated.VideoChannel = channelActor.VideoChannel
179 async function getOrCreateAccountAndVideoAndChannel (videoObject: VideoTorrentObject | string, actor?: ActorModel) {
180 if (typeof videoObject === 'string') {
181 const videoFromDatabase = await VideoModel.loadByUrlAndPopulateAccount(videoObject)
182 if (videoFromDatabase) {
184 video: videoFromDatabase,
185 actor: videoFromDatabase.VideoChannel.Account.Actor,
186 channelActor: videoFromDatabase.VideoChannel.Actor
190 videoObject = await fetchRemoteVideo(videoObject)
191 if (!videoObject) throw new Error('Cannot fetch remote video')
195 const actorObj = videoObject.attributedTo.find(a => a.type === 'Person')
196 if (!actorObj) throw new Error('Cannot find associated actor to video ' + videoObject.url)
198 actor = await getOrCreateActorAndServerAndModel(actorObj.id)
201 const channel = videoObject.attributedTo.find(a => a.type === 'Group')
202 if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
204 const channelActor = await getOrCreateActorAndServerAndModel(channel.id)
207 arguments: [ videoObject, channelActor ],
208 errorMessage: 'Cannot insert the remote video with many retries.'
211 const video = await retryTransactionWrapper(getOrCreateVideo, options)
213 return { actor, channelActor, video }
216 async function addVideoShares (instance: VideoModel, shareUrls: string[]) {
217 for (const shareUrl of shareUrls) {
219 const { body } = await doRequest({
224 const actorUrl = body.actor
225 if (!actorUrl) continue
227 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
234 await VideoShareModel.findOrCreate({
242 getOrCreateAccountAndVideoAndChannel,
243 fetchRemoteVideoPreview,
244 fetchRemoteVideoDescription,
245 generateThumbnailFromUrl,
246 videoActivityObjectToDBAttributes,
247 videoFileActivityUrlToDBAttributes,
251 // ---------------------------------------------------------------------------
253 async function fetchRemoteVideo (videoUrl: string): Promise<VideoTorrentObject> {
261 logger.info('Fetching remote video %s.', videoUrl)
263 const { body } = await doRequest(options)
265 if (isVideoTorrentObjectValid(body) === false) {
266 logger.debug('Remote video JSON is not valid.', { body })