]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/controllers/api/videos/index.ts
Fix public video we set to public or unlisted
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / index.ts
index 9e233a8cc3eafb5674bd4cb8c25e1b9b9eea2168..22a88620a8ac12fa75cb8d14ac8fefa07c8b7306 100644 (file)
@@ -1,53 +1,41 @@
 import * as express from 'express'
 import * as multer from 'multer'
 import { extname, join } from 'path'
-
-import { database as db } from '../../../initializers/database'
+import { VideoCreate, VideoPrivacy, VideoUpdate } from '../../../../shared'
 import {
-  CONFIG,
-  REQUEST_VIDEO_QADU_TYPES,
-  REQUEST_VIDEO_EVENT_TYPES,
-  VIDEO_CATEGORIES,
-  VIDEO_LICENCES,
-  VIDEO_LANGUAGES
-} from '../../../initializers'
-import {
-  addEventToRemoteVideo,
-  quickAndDirtyUpdateVideoToFriends,
-  addVideoToFriends,
-  updateVideoToFriends,
-  JobScheduler
-} from '../../../lib'
+  fetchRemoteVideoDescription,
+  generateRandomString,
+  getFormattedObjects,
+  getVideoFileHeight,
+  logger,
+  renamePromise,
+  resetSequelizeInstance,
+  retryTransactionWrapper
+} from '../../../helpers'
+import { getActivityPubUrl, shareVideoByServer } from '../../../helpers/activitypub'
+import { CONFIG, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_MIMETYPE_EXT, VIDEO_PRIVACIES } from '../../../initializers'
+import { database as db } from '../../../initializers/database'
+import { sendAddVideo, sendUpdateVideo } from '../../../lib/activitypub/send-request'
+import { transcodingJobScheduler } from '../../../lib/jobs/transcoding-job-scheduler/transcoding-job-scheduler'
 import {
+  asyncMiddleware,
   authenticate,
   paginationValidator,
-  videosSortValidator,
-  setVideosSort,
   setPagination,
   setVideosSearch,
-  videosUpdateValidator,
-  videosSearchValidator,
+  setVideosSort,
   videosAddValidator,
   videosGetValidator,
   videosRemoveValidator,
-  asyncMiddleware
+  videosSearchValidator,
+  videosSortValidator,
+  videosUpdateValidator
 } from '../../../middlewares'
-import {
-  logger,
-  retryTransactionWrapper,
-  generateRandomString,
-  getFormattedObjects,
-  renamePromise,
-  getVideoFileHeight,
-  resetSequelizeInstance
-} from '../../../helpers'
 import { VideoInstance } from '../../../models'
-import { VideoCreate, VideoUpdate } from '../../../../shared'
-
 import { abuseVideoRouter } from './abuse'
 import { blacklistRouter } from './blacklist'
-import { rateVideoRouter } from './rate'
 import { videoChannelRouter } from './channel'
+import { rateVideoRouter } from './rate'
 
 const videosRouter = express.Router()
 
@@ -57,19 +45,18 @@ const storage = multer.diskStorage({
     cb(null, CONFIG.STORAGE.VIDEOS_DIR)
   },
 
-  filename: (req, file, cb) => {
-    let extension = ''
-    if (file.mimetype === 'video/webm') extension = 'webm'
-    else if (file.mimetype === 'video/mp4') extension = 'mp4'
-    else if (file.mimetype === 'video/ogg') extension = 'ogv'
-    generateRandomString(16)
-      .then(randomString => {
-        cb(null, randomString + '.' + extension)
-      })
-      .catch(err => {
-        logger.error('Cannot generate random string for file name.', err)
-        throw err
-      })
+  filename: async (req, file, cb) => {
+    const extension = VIDEO_MIMETYPE_EXT[file.mimetype]
+    let randomString = ''
+
+    try {
+      randomString = await generateRandomString(16)
+    } catch (err) {
+      logger.error('Cannot generate random string for file name.', err)
+      randomString = 'fake-random-string'
+    }
+
+    cb(null, randomString + extension)
   }
 })
 
@@ -83,6 +70,7 @@ videosRouter.use('/', videoChannelRouter)
 videosRouter.get('/categories', listVideoCategories)
 videosRouter.get('/licences', listVideoLicences)
 videosRouter.get('/languages', listVideoLanguages)
+videosRouter.get('/privacies', listVideoPrivacies)
 
 videosRouter.get('/',
   paginationValidator,
@@ -102,6 +90,11 @@ videosRouter.post('/upload',
   videosAddValidator,
   asyncMiddleware(addVideoRetryWrapper)
 )
+
+videosRouter.get('/:id/description',
+  videosGetValidator,
+  asyncMiddleware(getVideoDescription)
+)
 videosRouter.get('/:id',
   videosGetValidator,
   getVideo
@@ -143,6 +136,10 @@ function listVideoLanguages (req: express.Request, res: express.Response) {
   res.json(VIDEO_LANGUAGES)
 }
 
+function listVideoPrivacies (req: express.Request, res: express.Response) {
+  res.json(VIDEO_PRIVACIES)
+}
+
 // Wrapper to video add that retry the function if there is a database error
 // We need this because we run the transaction in SERIALIZABLE isolation that can fail
 async function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
@@ -173,10 +170,12 @@ async function addVideo (req: express.Request, res: express.Response, videoPhysi
       language: videoInfo.language,
       nsfw: videoInfo.nsfw,
       description: videoInfo.description,
+      privacy: videoInfo.privacy,
       duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
       channelId: res.locals.videoChannel.id
     }
     const video = db.Video.build(videoData)
+    video.url = getActivityPubUrl('video', video.uuid)
 
     const videoFilePath = join(CONFIG.STORAGE.VIDEOS_DIR, videoPhysicalFile.filename)
     const videoFileHeight = await getVideoFileHeight(videoFilePath)
@@ -210,7 +209,7 @@ async function addVideo (req: express.Request, res: express.Response, videoPhysi
       }
 
       tasks.push(
-        JobScheduler.Instance.createJob(t, 'videoFileOptimizer', dataInput)
+        transcodingJobScheduler.createJob(t, 'videoFileOptimizer', dataInput)
       )
     }
     await Promise.all(tasks)
@@ -234,10 +233,11 @@ async function addVideo (req: express.Request, res: express.Response, videoPhysi
 
     // Let transcoding job send the video to friends because the video file extension might change
     if (CONFIG.TRANSCODING.ENABLED === true) return undefined
+    // Don't send video to remote servers, it is private
+    if (video.privacy === VideoPrivacy.PRIVATE) return undefined
 
-    const remoteVideo = await video.toAddRemoteJSON()
-    // Now we'll add the video's meta data to our friends
-    return addVideoToFriends(remoteVideo, t)
+    await sendAddVideo(video, t)
+    await shareVideoByServer(video, t)
   })
 
   logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoUUID)
@@ -255,9 +255,10 @@ async function updateVideoRetryWrapper (req: express.Request, res: express.Respo
 }
 
 async function updateVideo (req: express.Request, res: express.Response) {
-  const videoInstance = res.locals.video
+  const videoInstance: VideoInstance = res.locals.video
   const videoFieldsSave = videoInstance.toJSON()
   const videoInfoToUpdate: VideoUpdate = req.body
+  const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
 
   try {
     await db.sequelize.transaction(async t => {
@@ -270,6 +271,7 @@ async function updateVideo (req: express.Request, res: express.Response) {
       if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
       if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
       if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
+      if (videoInfoToUpdate.privacy !== undefined) videoInstance.set('privacy', videoInfoToUpdate.privacy)
       if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
 
       await videoInstance.save(sequelizeOptions)
@@ -281,10 +283,16 @@ async function updateVideo (req: express.Request, res: express.Response) {
         videoInstance.Tags = tagInstances
       }
 
-      const json = videoInstance.toUpdateRemoteJSON()
-
       // Now we'll update the video's meta data to our friends
-      return updateVideoToFriends(json, t)
+      if (wasPrivateVideo === false) {
+        await sendUpdateVideo(videoInstance, t)
+      }
+
+      // Video is not private anymore, send a create action to remote servers
+      if (wasPrivateVideo === true && videoInstance.privacy !== VideoPrivacy.PRIVATE) {
+        await sendAddVideo(videoInstance, t)
+        await shareVideoByServer(videoInstance, t)
+      }
     })
 
     logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
@@ -298,7 +306,7 @@ async function updateVideo (req: express.Request, res: express.Response) {
   }
 }
 
-function getVideo (req: express.Request, res: express.Response) {
+async function getVideo (req: express.Request, res: express.Response) {
   const videoInstance = res.locals.video
 
   if (videoInstance.isOwned()) {
@@ -307,27 +315,30 @@ function getVideo (req: express.Request, res: express.Response) {
     // For example, only add a view when a user watch a video during 30s etc
     videoInstance.increment('views')
       .then(() => {
-        const qaduParams = {
-          videoId: videoInstance.id,
-          type: REQUEST_VIDEO_QADU_TYPES.VIEWS
-        }
-        return quickAndDirtyUpdateVideoToFriends(qaduParams)
+        // TODO: send to followers a notification
       })
       .catch(err => logger.error('Cannot add view to video %s.', videoInstance.uuid, err))
   } else {
-    // Just send the event to our friends
-    const eventParams = {
-      videoId: videoInstance.id,
-      type: REQUEST_VIDEO_EVENT_TYPES.VIEWS
-    }
-    addEventToRemoteVideo(eventParams)
-      .catch(err => logger.error('Cannot add event to remote video %s.', videoInstance.uuid, err))
+    // TODO: send view event to followers
   }
 
   // Do not wait the view system
   return res.json(videoInstance.toFormattedDetailsJSON())
 }
 
+async function getVideoDescription (req: express.Request, res: express.Response) {
+  const videoInstance = res.locals.video
+  let description = ''
+
+  if (videoInstance.isOwned()) {
+    description = videoInstance.description
+  } else {
+    description = await fetchRemoteVideoDescription(videoInstance)
+  }
+
+  return res.json({ description })
+}
+
 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
   const resultList = await db.Video.listForApi(req.query.start, req.query.count, req.query.sort)
 
@@ -356,7 +367,7 @@ async function removeVideo (req: express.Request, res: express.Response) {
 }
 
 async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
-  const resultList = await db.Video.searchAndPopulateAuthorAndPodAndTags(
+  const resultList = await db.Video.searchAndPopulateAccountAndServerAndTags(
     req.params.value,
     req.query.field,
     req.query.start,