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 { 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 { 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,
61 let privacy = VideoPrivacy.PRIVATE
62 if (to.indexOf(ACTIVITY_PUB.PUBLIC) !== -1) privacy = VideoPrivacy.PUBLIC
63 else if (cc.indexOf(ACTIVITY_PUB.PUBLIC) !== -1) privacy = VideoPrivacy.UNLISTED
65 const duration = videoObject.duration.replace(/[^\d]+/, '')
67 if (videoObject.language) {
68 language = parseInt(videoObject.language.identifier, 10)
72 if (videoObject.category) {
73 category = parseInt(videoObject.category.identifier, 10)
77 if (videoObject.licence) {
78 licence = parseInt(videoObject.licence.identifier, 10)
81 let description = null
82 if (videoObject.content) {
83 description = videoObject.content
87 if (videoObject.support) {
88 support = videoObject.support
92 name: videoObject.name,
93 uuid: videoObject.uuid,
100 nsfw: videoObject.sensitive,
101 commentsEnabled: videoObject.commentsEnabled,
102 channelId: videoChannel.id,
103 duration: parseInt(duration, 10),
104 createdAt: new Date(videoObject.published),
105 // FIXME: updatedAt does not seems to be considered by Sequelize
106 updatedAt: new Date(videoObject.updated),
107 views: videoObject.views,
115 function videoFileActivityUrlToDBAttributes (videoCreated: VideoModel, videoObject: VideoTorrentObject) {
116 const mimeTypes = Object.keys(VIDEO_MIMETYPE_EXT)
117 const fileUrls = videoObject.url.filter(u => {
118 return mimeTypes.indexOf(u.mimeType) !== -1 && u.mimeType.startsWith('video/')
121 if (fileUrls.length === 0) {
122 throw new Error('Cannot find video files for ' + videoCreated.url)
125 const attributes = []
126 for (const fileUrl of fileUrls) {
127 // Fetch associated magnet uri
128 const magnet = videoObject.url.find(u => {
129 return u.mimeType === 'application/x-bittorrent;x-scheme-handler/magnet' && u.width === fileUrl.width
132 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
134 const parsed = magnetUtil.decode(magnet.href)
135 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) throw new Error('Cannot parse magnet URI ' + magnet.href)
138 extname: VIDEO_MIMETYPE_EXT[ fileUrl.mimeType ],
139 infoHash: parsed.infoHash,
140 resolution: fileUrl.width,
142 videoId: videoCreated.id
144 attributes.push(attribute)
150 async function getOrCreateVideo (videoObject: VideoTorrentObject, channelActor: ActorModel) {
151 logger.debug('Adding remote video %s.', videoObject.id)
153 return sequelizeTypescript.transaction(async t => {
154 const sequelizeOptions = {
157 const videoFromDatabase = await VideoModel.loadByUUIDOrURLAndPopulateAccount(videoObject.uuid, videoObject.id, t)
158 if (videoFromDatabase) return videoFromDatabase
160 const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to, videoObject.cc)
161 const video = VideoModel.build(videoData)
163 // Don't block on request
164 generateThumbnailFromUrl(video, videoObject.icon)
165 .catch(err => logger.warn('Cannot generate thumbnail of %s.', videoObject.id, err))
167 const videoCreated = await video.save(sequelizeOptions)
169 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject)
170 if (videoFileAttributes.length === 0) {
171 throw new Error('Cannot find valid files for video %s ' + videoObject.url)
174 const tasks = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
175 await Promise.all(tasks)
177 const tags = videoObject.tag.map(t => t.name)
178 const tagInstances = await TagModel.findOrCreateTags(tags, t)
179 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
181 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
183 videoCreated.VideoChannel = channelActor.VideoChannel
188 async function getOrCreateAccountAndVideoAndChannel (videoObject: VideoTorrentObject | string, actor?: ActorModel) {
189 if (typeof videoObject === 'string') {
190 const videoFromDatabase = await VideoModel.loadByUrlAndPopulateAccount(videoObject)
191 if (videoFromDatabase) {
193 video: videoFromDatabase,
194 actor: videoFromDatabase.VideoChannel.Account.Actor,
195 channelActor: videoFromDatabase.VideoChannel.Actor
199 videoObject = await fetchRemoteVideo(videoObject)
200 if (!videoObject) throw new Error('Cannot fetch remote video')
204 const actorObj = videoObject.attributedTo.find(a => a.type === 'Person')
205 if (!actorObj) throw new Error('Cannot find associated actor to video ' + videoObject.url)
207 actor = await getOrCreateActorAndServerAndModel(actorObj.id)
210 const channel = videoObject.attributedTo.find(a => a.type === 'Group')
211 if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
213 const channelActor = await getOrCreateActorAndServerAndModel(channel.id)
216 arguments: [ videoObject, channelActor ],
217 errorMessage: 'Cannot insert the remote video with many retries.'
220 const video = await retryTransactionWrapper(getOrCreateVideo, options)
222 // Process outside the transaction because we could fetch remote data
223 if (videoObject.likes && Array.isArray(videoObject.likes.orderedItems)) {
224 logger.info('Adding likes of video %s.', video.uuid)
225 await createRates(videoObject.likes.orderedItems, video, 'like')
228 if (videoObject.dislikes && Array.isArray(videoObject.dislikes.orderedItems)) {
229 logger.info('Adding dislikes of video %s.', video.uuid)
230 await createRates(videoObject.dislikes.orderedItems, video, 'dislike')
233 if (videoObject.shares && Array.isArray(videoObject.shares.orderedItems)) {
234 logger.info('Adding shares of video %s.', video.uuid)
235 await addVideoShares(video, videoObject.shares.orderedItems)
238 if (videoObject.comments && Array.isArray(videoObject.comments.orderedItems)) {
239 logger.info('Adding comments of video %s.', video.uuid)
240 await addVideoComments(video, videoObject.comments.orderedItems)
243 return { actor, channelActor, video }
246 async function createRates (actorUrls: string[], video: VideoModel, rate: VideoRateType) {
248 const tasks: Bluebird<number>[] = []
250 for (const actorUrl of actorUrls) {
251 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
252 const p = AccountVideoRateModel
255 accountId: actor.Account.id,
258 .then(() => rateCounts += 1)
263 await Promise.all(tasks)
265 logger.info('Adding %d %s to video %s.', rateCounts, rate, video.uuid)
267 // This is "likes" and "dislikes"
268 await video.increment(rate + 's', { by: rateCounts })
273 async function addVideoShares (instance: VideoModel, shareUrls: string[]) {
274 for (const shareUrl of shareUrls) {
276 const { body } = await doRequest({
281 const actorUrl = body.actor
282 if (!actorUrl) continue
284 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
288 videoId: instance.id,
292 await VideoShareModel.findOrCreate({
302 getOrCreateAccountAndVideoAndChannel,
303 fetchRemoteVideoPreview,
304 fetchRemoteVideoDescription,
305 generateThumbnailFromUrl,
306 videoActivityObjectToDBAttributes,
307 videoFileActivityUrlToDBAttributes,
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 (isVideoTorrentObjectValid(body) === false) {
326 logger.debug('Remote video JSON is not valid.', { body })