]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/controllers/api/v1/videos.js
Refractoring and add thumbnails support (without tests)
[github/Chocobozzz/PeerTube.git] / server / controllers / api / v1 / videos.js
index 4384724c144b793c7d260facd305e48e8413ad1e..98f17ac6c7e07cc8d2135770c0b8d3f5a0ef8331 100644 (file)
@@ -1,15 +1,19 @@
 'use strict'
 
 const config = require('config')
-const crypto = require('crypto')
 const express = require('express')
+const fs = require('fs')
+const path = require('path')
 const multer = require('multer')
 
+const constants = require('../../../initializers/constants')
 const logger = require('../../../helpers/logger')
 const friends = require('../../../lib/friends')
 const middleware = require('../../../middlewares')
+const oAuth2 = require('../../../middlewares/oauth2')
 const cacheMiddleware = middleware.cache
 const reqValidator = middleware.reqValidators.videos
+const utils = require('../../../helpers/utils')
 const Videos = require('../../../models/videos') // model
 const videos = require('../../../lib/videos')
 const webtorrent = require('../../../lib/webtorrent')
@@ -28,19 +32,20 @@ const storage = multer.diskStorage({
     if (file.mimetype === 'video/webm') extension = 'webm'
     else if (file.mimetype === 'video/mp4') extension = 'mp4'
     else if (file.mimetype === 'video/ogg') extension = 'ogv'
-    crypto.pseudoRandomBytes(16, function (err, raw) {
-      const fieldname = err ? undefined : raw.toString('hex')
+    utils.generateRandomString(16, function (err, random_string) {
+      const fieldname = err ? undefined : random_string
       cb(null, fieldname + '.' + extension)
     })
   }
 })
 
-const reqFiles = multer({ storage: storage }).fields([{ name: 'input_video', maxCount: 1 }])
+const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
+const thumbnailsDir = path.join(__dirname, '..', '..', '..', '..', config.get('storage.thumbnails'))
 
 router.get('/', cacheMiddleware.cache(false), listVideos)
-router.post('/', reqFiles, reqValidator.videosAdd, cacheMiddleware.cache(false), addVideo)
+router.post('/', oAuth2.authenticate, reqFiles, reqValidator.videosAdd, cacheMiddleware.cache(false), addVideo)
 router.get('/:id', reqValidator.videosGet, cacheMiddleware.cache(false), getVideos)
-router.delete('/:id', reqValidator.videosRemove, cacheMiddleware.cache(false), removeVideo)
+router.delete('/:id', oAuth2.authenticate, reqValidator.videosRemove, cacheMiddleware.cache(false), removeVideo)
 router.get('/search/:name', reqValidator.videosSearch, cacheMiddleware.cache(false), searchVideos)
 
 // ---------------------------------------------------------------------------
@@ -50,7 +55,7 @@ module.exports = router
 // ---------------------------------------------------------------------------
 
 function addVideo (req, res, next) {
-  const video_file = req.files.input_video[0]
+  const video_file = req.files.videofile[0]
   const video_infos = req.body
 
   videos.seed(video_file.path, function (err, torrent) {
@@ -59,25 +64,54 @@ function addVideo (req, res, next) {
       return next(err)
     }
 
-    const video_data = {
-      name: video_infos.name,
-      namePath: video_file.filename,
-      description: video_infos.description,
-      magnetUri: torrent.magnetURI
-    }
-
-    Videos.add(video_data, function (err) {
+    videos.getVideoDuration(video_file.path, function (err, duration) {
       if (err) {
-        // TODO unseed the video
-        logger.error('Cannot insert this video in the database.')
+        // TODO: unseed the video
+        logger.error('Cannot retrieve metadata of the file.')
         return next(err)
       }
 
-      // Now we'll add the video's meta data to our friends
-      friends.addVideoToFriends(video_data)
+      videos.getVideoThumbnail(video_file.path, function (err, thumbnail_name) {
+        if (err) {
+          // TODO: unseed the video
+          logger.error('Cannot make a thumbnail of the video file.')
+          return next(err)
+        }
+
+        const video_data = {
+          name: video_infos.name,
+          namePath: video_file.filename,
+          description: video_infos.description,
+          magnetUri: torrent.magnetURI,
+          author: res.locals.oauth.token.user.username,
+          duration: duration,
+          thumbnail: thumbnail_name
+        }
 
-      // TODO : include Location of the new video -> 201
-      res.type('json').status(204).end()
+        Videos.add(video_data, function (err) {
+          if (err) {
+            // TODO unseed the video
+            logger.error('Cannot insert this video in the database.')
+            return next(err)
+          }
+
+          fs.readFile(thumbnailsDir + thumbnail_name, function (err, data) {
+            if (err) {
+              // TODO: remove video?
+              logger.error('Cannot read the thumbnail of the video')
+              return next(err)
+            }
+
+            // Set the image in base64
+            video_data.thumbnail_base64 = new Buffer(data).toString('base64')
+            // Now we'll add the video's meta data to our friends
+            friends.addVideoToFriends(video_data)
+
+            // TODO : include Location of the new video -> 201
+            res.type('json').status(204).end()
+          })
+        })
+      })
     })
   })
 }
@@ -112,13 +146,17 @@ function removeVideo (req, res, next) {
       Videos.removeOwned(req.params.id, function (err) {
         if (err) return next(err)
 
-        const params = {
-          name: video.name,
-          magnetUri: video.magnetUri
-        }
+        videos.removeVideosDataFromDisk([ video ], function (err) {
+          if (err) logger.error('Cannot remove video data from disk.', { video: video })
+
+          const params = {
+            name: video.name,
+            magnetUri: video.magnetUri
+          }
 
-        friends.removeVideoToFriends(params)
-        res.type('json').status(204).end()
+          friends.removeVideoToFriends(params)
+          res.type('json').status(204).end()
+        })
       })
     })
   })
@@ -141,7 +179,10 @@ function getFormatedVideo (video_obj) {
     description: video_obj.description,
     podUrl: video_obj.podUrl,
     isLocal: videos.getVideoState(video_obj).owned,
-    magnetUri: video_obj.magnetUri
+    magnetUri: video_obj.magnetUri,
+    author: video_obj.author,
+    duration: video_obj.duration,
+    thumbnail_path: constants.THUMBNAILS_STATIC_PATH + '/' + video_obj.thumbnail
   }
 
   return formated_video