1 import * as Bluebird from 'bluebird'
2 import * as sequelize from 'sequelize'
3 import * as magnetUtil from 'magnet-uri'
4 import { join } from 'path'
5 import * as request from 'request'
6 import { ActivityIconObject, VideoState } from '../../../shared/index'
7 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
8 import { VideoPrivacy, VideoRateType } from '../../../shared/models/videos'
9 import { sanitizeAndCheckVideoTorrentObject } from '../../helpers/custom-validators/activitypub/videos'
10 import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
11 import { retryTransactionWrapper } from '../../helpers/database-utils'
12 import { logger } from '../../helpers/logger'
13 import { doRequest, doRequestAndSaveToFile } from '../../helpers/requests'
14 import { ACTIVITY_PUB, CONFIG, REMOTE_SCHEME, sequelizeTypescript, STATIC_PATHS, VIDEO_MIMETYPE_EXT } from '../../initializers'
15 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
16 import { ActorModel } from '../../models/activitypub/actor'
17 import { TagModel } from '../../models/video/tag'
18 import { VideoModel } from '../../models/video/video'
19 import { VideoChannelModel } from '../../models/video/video-channel'
20 import { VideoFileModel } from '../../models/video/video-file'
21 import { VideoShareModel } from '../../models/video/video-share'
22 import { getOrCreateActorAndServerAndModel } from './actor'
23 import { addVideoComments } from './video-comments'
24 import { crawlCollectionPage } from './crawl'
25 import { sendCreateVideo, sendUpdateVideo } from './send'
26 import { shareVideoByServerAndChannel } from './index'
27 import { isArray } from '../../helpers/custom-validators/misc'
28 import { VideoCaptionModel } from '../../models/video/video-caption'
30 async function federateVideoIfNeeded (video: VideoModel, isNewVideo: boolean, transaction?: sequelize.Transaction) {
31 // If the video is not private and published, we federate it
32 if (video.privacy !== VideoPrivacy.PRIVATE && video.state === VideoState.PUBLISHED) {
33 // Fetch more attributes that we will need to serialize in AP object
34 if (isArray(video.VideoCaptions) === false) {
35 video.VideoCaptions = await video.$get('VideoCaptions', {
36 attributes: [ 'language' ],
38 }) as VideoCaptionModel[]
41 if (isNewVideo === true) {
42 // Now we'll add the video's meta data to our followers
43 await sendCreateVideo(video, transaction)
44 await shareVideoByServerAndChannel(video, transaction)
46 await sendUpdateVideo(video, transaction)
51 function fetchRemoteVideoStaticFile (video: VideoModel, path: string, reject: Function) {
52 const host = video.VideoChannel.Account.Actor.Server.host
54 // We need to provide a callback, if no we could have an uncaught exception
55 return request.get(REMOTE_SCHEME.HTTP + '://' + host + path, err => {
60 async function fetchRemoteVideoDescription (video: VideoModel) {
61 const host = video.VideoChannel.Account.Actor.Server.host
62 const path = video.getDescriptionPath()
64 uri: REMOTE_SCHEME.HTTP + '://' + host + path,
68 const { body } = await doRequest(options)
69 return body.description ? body.description : ''
72 function generateThumbnailFromUrl (video: VideoModel, icon: ActivityIconObject) {
73 const thumbnailName = video.getThumbnailName()
74 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName)
80 return doRequestAndSaveToFile(options, thumbnailPath)
83 async function videoActivityObjectToDBAttributes (
84 videoChannel: VideoChannelModel,
85 videoObject: VideoTorrentObject,
88 const privacy = to.indexOf(ACTIVITY_PUB.PUBLIC) !== -1 ? VideoPrivacy.PUBLIC : VideoPrivacy.UNLISTED
89 const duration = videoObject.duration.replace(/[^\d]+/, '')
91 let language: string = null
92 if (videoObject.language) {
93 language = videoObject.language.identifier
96 let category: number = null
97 if (videoObject.category) {
98 category = parseInt(videoObject.category.identifier, 10)
101 let licence: number = null
102 if (videoObject.licence) {
103 licence = parseInt(videoObject.licence.identifier, 10)
106 const description = videoObject.content || null
107 const support = videoObject.support || null
110 name: videoObject.name,
111 uuid: videoObject.uuid,
118 nsfw: videoObject.sensitive,
119 commentsEnabled: videoObject.commentsEnabled,
120 waitTranscoding: videoObject.waitTranscoding,
121 state: videoObject.state,
122 channelId: videoChannel.id,
123 duration: parseInt(duration, 10),
124 createdAt: new Date(videoObject.published),
125 publishedAt: new Date(videoObject.published),
126 // FIXME: updatedAt does not seems to be considered by Sequelize
127 updatedAt: new Date(videoObject.updated),
128 views: videoObject.views,
136 function videoFileActivityUrlToDBAttributes (videoCreated: VideoModel, videoObject: VideoTorrentObject) {
137 const mimeTypes = Object.keys(VIDEO_MIMETYPE_EXT)
138 const fileUrls = videoObject.url.filter(u => {
139 return mimeTypes.indexOf(u.mimeType) !== -1 && u.mimeType.startsWith('video/')
142 if (fileUrls.length === 0) {
143 throw new Error('Cannot find video files for ' + videoCreated.url)
146 const attributes = []
147 for (const fileUrl of fileUrls) {
148 // Fetch associated magnet uri
149 const magnet = videoObject.url.find(u => {
150 return u.mimeType === 'application/x-bittorrent;x-scheme-handler/magnet' && u.width === fileUrl.width
153 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
155 const parsed = magnetUtil.decode(magnet.href)
156 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) throw new Error('Cannot parse magnet URI ' + magnet.href)
159 extname: VIDEO_MIMETYPE_EXT[ fileUrl.mimeType ],
160 infoHash: parsed.infoHash,
161 resolution: fileUrl.width,
163 videoId: videoCreated.id
165 attributes.push(attribute)
171 function getOrCreateVideoChannel (videoObject: VideoTorrentObject) {
172 const channel = videoObject.attributedTo.find(a => a.type === 'Group')
173 if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
175 return getOrCreateActorAndServerAndModel(channel.id)
178 async function getOrCreateVideo (videoObject: VideoTorrentObject, channelActor: ActorModel) {
179 logger.debug('Adding remote video %s.', videoObject.id)
181 return sequelizeTypescript.transaction(async t => {
182 const sequelizeOptions = {
185 const videoFromDatabase = await VideoModel.loadByUUIDOrURLAndPopulateAccount(videoObject.uuid, videoObject.id, t)
186 if (videoFromDatabase) return videoFromDatabase
188 const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to)
189 const video = VideoModel.build(videoData)
191 // Don't block on remote HTTP request (we are in a transaction!)
192 generateThumbnailFromUrl(video, videoObject.icon)
193 .catch(err => logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err }))
195 const videoCreated = await video.save(sequelizeOptions)
198 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject)
199 if (videoFileAttributes.length === 0) {
200 throw new Error('Cannot find valid files for video %s ' + videoObject.url)
203 const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
204 await Promise.all(videoFilePromises)
207 const tags = videoObject.tag.map(t => t.name)
208 const tagInstances = await TagModel.findOrCreateTags(tags, t)
209 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
212 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
213 return VideoCaptionModel.insertOrReplaceLanguage(videoCreated.id, c.identifier, t)
215 await Promise.all(videoCaptionsPromises)
217 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
219 videoCreated.VideoChannel = channelActor.VideoChannel
224 async function getOrCreateAccountAndVideoAndChannel (videoObject: VideoTorrentObject | string, actor?: ActorModel) {
225 const videoUrl = typeof videoObject === 'string' ? videoObject : videoObject.id
227 const videoFromDatabase = await VideoModel.loadByUrlAndPopulateAccount(videoUrl)
228 if (videoFromDatabase) {
230 video: videoFromDatabase,
231 actor: videoFromDatabase.VideoChannel.Account.Actor,
232 channelActor: videoFromDatabase.VideoChannel.Actor
236 videoObject = await fetchRemoteVideo(videoUrl)
237 if (!videoObject) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
240 const actorObj = videoObject.attributedTo.find(a => a.type === 'Person')
241 if (!actorObj) throw new Error('Cannot find associated actor to video ' + videoObject.url)
243 actor = await getOrCreateActorAndServerAndModel(actorObj.id)
246 const channelActor = await getOrCreateVideoChannel(videoObject)
248 const video = await retryTransactionWrapper(getOrCreateVideo, videoObject, channelActor)
250 // Process outside the transaction because we could fetch remote data
251 logger.info('Adding likes of video %s.', video.uuid)
252 await crawlCollectionPage<string>(videoObject.likes, (items) => createRates(items, video, 'like'))
254 logger.info('Adding dislikes of video %s.', video.uuid)
255 await crawlCollectionPage<string>(videoObject.dislikes, (items) => createRates(items, video, 'dislike'))
257 logger.info('Adding shares of video %s.', video.uuid)
258 await crawlCollectionPage<string>(videoObject.shares, (items) => addVideoShares(items, video))
260 logger.info('Adding comments of video %s.', video.uuid)
261 await crawlCollectionPage<string>(videoObject.comments, (items) => addVideoComments(items, video))
263 return { actor, channelActor, video }
266 async function createRates (actorUrls: string[], video: VideoModel, rate: VideoRateType) {
268 const tasks: Bluebird<number>[] = []
270 for (const actorUrl of actorUrls) {
271 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
272 const p = AccountVideoRateModel
275 accountId: actor.Account.id,
278 .then(() => rateCounts += 1)
283 await Promise.all(tasks)
285 logger.info('Adding %d %s to video %s.', rateCounts, rate, video.uuid)
287 // This is "likes" and "dislikes"
288 await video.increment(rate + 's', { by: rateCounts })
293 async function addVideoShares (shareUrls: string[], instance: VideoModel) {
294 for (const shareUrl of shareUrls) {
296 const { body } = await doRequest({
301 if (!body || !body.actor) {
302 logger.warn('Cannot add remote share with url: %s, skipping...', shareUrl)
306 const actorUrl = body.actor
307 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
311 videoId: instance.id,
315 await VideoShareModel.findOrCreate({
324 async function fetchRemoteVideo (videoUrl: string): Promise<VideoTorrentObject> {
332 logger.info('Fetching remote video %s.', videoUrl)
334 const { body } = await doRequest(options)
336 if (sanitizeAndCheckVideoTorrentObject(body) === false) {
337 logger.debug('Remote video JSON is not valid.', { body })
345 federateVideoIfNeeded,
347 getOrCreateAccountAndVideoAndChannel,
348 fetchRemoteVideoStaticFile,
349 fetchRemoteVideoDescription,
350 generateThumbnailFromUrl,
351 videoActivityObjectToDBAttributes,
352 videoFileActivityUrlToDBAttributes,
354 getOrCreateVideoChannel,