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 name: videoObject.name,
88 uuid: videoObject.uuid,
94 nsfw: videoObject.sensitive,
95 commentsEnabled: videoObject.commentsEnabled,
96 channelId: videoChannel.id,
97 duration: parseInt(duration, 10),
98 createdAt: new Date(videoObject.published),
99 // FIXME: updatedAt does not seems to be considered by Sequelize
100 updatedAt: new Date(videoObject.updated),
101 views: videoObject.views,
109 function videoFileActivityUrlToDBAttributes (videoCreated: VideoModel, videoObject: VideoTorrentObject) {
110 const mimeTypes = Object.keys(VIDEO_MIMETYPE_EXT)
111 const fileUrls = videoObject.url.filter(u => {
112 return mimeTypes.indexOf(u.mimeType) !== -1 && u.mimeType.startsWith('video/')
115 if (fileUrls.length === 0) {
116 throw new Error('Cannot find video files for ' + videoCreated.url)
119 const attributes = []
120 for (const fileUrl of fileUrls) {
121 // Fetch associated magnet uri
122 const magnet = videoObject.url.find(u => {
123 return u.mimeType === 'application/x-bittorrent;x-scheme-handler/magnet' && u.width === fileUrl.width
126 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
128 const parsed = magnetUtil.decode(magnet.href)
129 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) throw new Error('Cannot parse magnet URI ' + magnet.href)
132 extname: VIDEO_MIMETYPE_EXT[ fileUrl.mimeType ],
133 infoHash: parsed.infoHash,
134 resolution: fileUrl.width,
136 videoId: videoCreated.id
138 attributes.push(attribute)
144 async function getOrCreateVideo (videoObject: VideoTorrentObject, channelActor: ActorModel) {
145 logger.debug('Adding remote video %s.', videoObject.id)
147 return sequelizeTypescript.transaction(async t => {
148 const sequelizeOptions = {
151 const videoFromDatabase = await VideoModel.loadByUUIDOrURLAndPopulateAccount(videoObject.uuid, videoObject.id, t)
152 if (videoFromDatabase) return videoFromDatabase
154 const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to, videoObject.cc)
155 const video = VideoModel.build(videoData)
157 // Don't block on request
158 generateThumbnailFromUrl(video, videoObject.icon)
159 .catch(err => logger.warn('Cannot generate thumbnail of %s.', videoObject.id, err))
161 const videoCreated = await video.save(sequelizeOptions)
163 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject)
164 if (videoFileAttributes.length === 0) {
165 throw new Error('Cannot find valid files for video %s ' + videoObject.url)
168 const tasks = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
169 await Promise.all(tasks)
171 const tags = videoObject.tag.map(t => t.name)
172 const tagInstances = await TagModel.findOrCreateTags(tags, t)
173 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
175 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
177 videoCreated.VideoChannel = channelActor.VideoChannel
182 async function getOrCreateAccountAndVideoAndChannel (videoObject: VideoTorrentObject | string, actor?: ActorModel) {
183 if (typeof videoObject === 'string') {
184 const videoFromDatabase = await VideoModel.loadByUrlAndPopulateAccount(videoObject)
185 if (videoFromDatabase) {
187 video: videoFromDatabase,
188 actor: videoFromDatabase.VideoChannel.Account.Actor,
189 channelActor: videoFromDatabase.VideoChannel.Actor
193 videoObject = await fetchRemoteVideo(videoObject)
194 if (!videoObject) throw new Error('Cannot fetch remote video')
198 const actorObj = videoObject.attributedTo.find(a => a.type === 'Person')
199 if (!actorObj) throw new Error('Cannot find associated actor to video ' + videoObject.url)
201 actor = await getOrCreateActorAndServerAndModel(actorObj.id)
204 const channel = videoObject.attributedTo.find(a => a.type === 'Group')
205 if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
207 const channelActor = await getOrCreateActorAndServerAndModel(channel.id)
210 arguments: [ videoObject, channelActor ],
211 errorMessage: 'Cannot insert the remote video with many retries.'
214 const video = await retryTransactionWrapper(getOrCreateVideo, options)
216 // Process outside the transaction because we could fetch remote data
217 if (videoObject.likes && Array.isArray(videoObject.likes.orderedItems)) {
218 logger.info('Adding likes of video %s.', video.uuid)
219 await createRates(videoObject.likes.orderedItems, video, 'like')
222 if (videoObject.dislikes && Array.isArray(videoObject.dislikes.orderedItems)) {
223 logger.info('Adding dislikes of video %s.', video.uuid)
224 await createRates(videoObject.dislikes.orderedItems, video, 'dislike')
227 if (videoObject.shares && Array.isArray(videoObject.shares.orderedItems)) {
228 logger.info('Adding shares of video %s.', video.uuid)
229 await addVideoShares(video, videoObject.shares.orderedItems)
232 if (videoObject.comments && Array.isArray(videoObject.comments.orderedItems)) {
233 logger.info('Adding comments of video %s.', video.uuid)
234 await addVideoComments(video, videoObject.comments.orderedItems)
237 return { actor, channelActor, video }
240 async function createRates (actorUrls: string[], video: VideoModel, rate: VideoRateType) {
242 const tasks: Bluebird<number>[] = []
244 for (const actorUrl of actorUrls) {
245 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
246 const p = AccountVideoRateModel
249 accountId: actor.Account.id,
252 .then(() => rateCounts += 1)
257 await Promise.all(tasks)
259 logger.info('Adding %d %s to video %s.', rateCounts, rate, video.uuid)
261 // This is "likes" and "dislikes"
262 await video.increment(rate + 's', { by: rateCounts })
267 async function addVideoShares (instance: VideoModel, shareUrls: string[]) {
268 for (const shareUrl of shareUrls) {
270 const { body } = await doRequest({
275 const actorUrl = body.actor
276 if (!actorUrl) continue
278 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
282 videoId: instance.id,
286 await VideoShareModel.findOrCreate({
296 getOrCreateAccountAndVideoAndChannel,
297 fetchRemoteVideoPreview,
298 fetchRemoteVideoDescription,
299 generateThumbnailFromUrl,
300 videoActivityObjectToDBAttributes,
301 videoFileActivityUrlToDBAttributes,
305 // ---------------------------------------------------------------------------
307 async function fetchRemoteVideo (videoUrl: string): Promise<VideoTorrentObject> {
315 logger.info('Fetching remote video %s.', videoUrl)
317 const { body } = await doRequest(options)
319 if (isVideoTorrentObjectValid(body) === false) {
320 logger.debug('Remote video JSON is not valid.', { body })