]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/v1/videos.js
Add ability to sort videos list
[github/Chocobozzz/PeerTube.git] / server / controllers / api / v1 / videos.js
1 'use strict'
2
3 const async = require('async')
4 const config = require('config')
5 const express = require('express')
6 const fs = require('fs')
7 const path = require('path')
8 const multer = require('multer')
9
10 const constants = require('../../../initializers/constants')
11 const logger = require('../../../helpers/logger')
12 const friends = require('../../../lib/friends')
13 const middlewares = require('../../../middlewares')
14 const oAuth2 = middlewares.oauth2
15 const pagination = middlewares.pagination
16 const reqValidator = middlewares.reqValidators
17 const reqValidatorPagination = reqValidator.pagination
18 const reqValidatorSort = reqValidator.sort
19 const reqValidatorVideos = reqValidator.videos
20 const sort = middlewares.sort
21 const utils = require('../../../helpers/utils')
22 const Videos = require('../../../models/videos') // model
23 const videos = require('../../../lib/videos')
24 const webtorrent = require('../../../lib/webtorrent')
25
26 const router = express.Router()
27 const uploads = config.get('storage.uploads')
28
29 // multer configuration
30 const storage = multer.diskStorage({
31 destination: function (req, file, cb) {
32 cb(null, uploads)
33 },
34
35 filename: function (req, file, cb) {
36 let extension = ''
37 if (file.mimetype === 'video/webm') extension = 'webm'
38 else if (file.mimetype === 'video/mp4') extension = 'mp4'
39 else if (file.mimetype === 'video/ogg') extension = 'ogv'
40 utils.generateRandomString(16, function (err, randomString) {
41 const fieldname = err ? undefined : randomString
42 cb(null, fieldname + '.' + extension)
43 })
44 }
45 })
46
47 const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
48 const thumbnailsDir = path.join(__dirname, '..', '..', '..', '..', config.get('storage.thumbnails'))
49
50 router.get('/',
51 reqValidatorPagination.pagination,
52 reqValidatorSort.videosSort,
53 sort.setVideosSort,
54 pagination.setPagination,
55 listVideos
56 )
57 router.post('/',
58 oAuth2.authenticate,
59 reqFiles,
60 reqValidatorVideos.videosAdd,
61 addVideo
62 )
63 router.get('/:id',
64 reqValidatorVideos.videosGet,
65 getVideos
66 )
67 router.delete('/:id',
68 oAuth2.authenticate,
69 reqValidatorVideos.videosRemove,
70 removeVideo
71 )
72 router.get('/search/:name',
73 reqValidatorVideos.videosSearch,
74 reqValidatorPagination.pagination,
75 reqValidatorSort.videosSort,
76 sort.setVideosSort,
77 pagination.setPagination,
78 searchVideos
79 )
80
81 // ---------------------------------------------------------------------------
82
83 module.exports = router
84
85 // ---------------------------------------------------------------------------
86
87 function addVideo (req, res, next) {
88 const videoFile = req.files.videofile[0]
89 const videoInfos = req.body
90
91 async.waterfall([
92 function seedTheVideo (callback) {
93 videos.seed(videoFile.path, callback)
94 },
95
96 function createThumbnail (torrent, callback) {
97 videos.createVideoThumbnail(videoFile.path, function (err, thumbnailName) {
98 if (err) {
99 // TODO: unseed the video
100 logger.error('Cannot make a thumbnail of the video file.')
101 return callback(err)
102 }
103
104 callback(null, torrent, thumbnailName)
105 })
106 },
107
108 function insertIntoDB (torrent, thumbnailName, callback) {
109 const videoData = {
110 name: videoInfos.name,
111 namePath: videoFile.filename,
112 description: videoInfos.description,
113 magnetUri: torrent.magnetURI,
114 author: res.locals.oauth.token.user.username,
115 duration: videoFile.duration,
116 thumbnail: thumbnailName
117 }
118
119 Videos.add(videoData, function (err, insertedVideo) {
120 if (err) {
121 // TODO unseed the video
122 // TODO remove thumbnail
123 logger.error('Cannot insert this video in the database.')
124 return callback(err)
125 }
126
127 return callback(null, torrent, thumbnailName, videoData, insertedVideo)
128 })
129 },
130
131 function getThumbnailBase64 (torrent, thumbnailName, videoData, insertedVideo, callback) {
132 videoData.createdDate = insertedVideo.createdDate
133
134 fs.readFile(thumbnailsDir + thumbnailName, function (err, thumbnailData) {
135 if (err) {
136 // TODO unseed the video
137 // TODO remove thumbnail
138 // TODO: remove video
139 logger.error('Cannot read the thumbnail of the video')
140 return callback(err)
141 }
142
143 return callback(null, videoData, thumbnailData)
144 })
145 },
146
147 function sendToFriends (videoData, thumbnailData, callback) {
148 // Set the image in base64
149 videoData.thumbnailBase64 = new Buffer(thumbnailData).toString('base64')
150
151 // Now we'll add the video's meta data to our friends
152 friends.addVideoToFriends(videoData)
153
154 return callback(null)
155 }
156
157 ], function (err) {
158 if (err) {
159 logger.error('Cannot insert the video.')
160 return next(err)
161 }
162
163 // TODO : include Location of the new video -> 201
164 return res.type('json').status(204).end()
165 })
166 }
167
168 function getVideos (req, res, next) {
169 Videos.get(req.params.id, function (err, videoObj) {
170 if (err) return next(err)
171
172 const state = videos.getVideoState(videoObj)
173 if (state.exist === false) {
174 return res.type('json').status(204).end()
175 }
176
177 res.json(getFormatedVideo(videoObj))
178 })
179 }
180
181 function listVideos (req, res, next) {
182 Videos.list(req.query.start, req.query.count, req.query.sort, function (err, videosList) {
183 if (err) return next(err)
184
185 res.json(getFormatedVideos(videosList))
186 })
187 }
188
189 function removeVideo (req, res, next) {
190 const videoId = req.params.id
191
192 async.waterfall([
193 function getVideo (callback) {
194 Videos.get(videoId, callback)
195 },
196
197 function removeVideoTorrent (video, callback) {
198 removeTorrent(video.magnetUri, function () {
199 return callback(null, video)
200 })
201 },
202
203 function removeFromDB (video, callback) {
204 Videos.removeOwned(req.params.id, function (err) {
205 if (err) return callback(err)
206
207 return callback(null, video)
208 })
209 },
210
211 function removeVideoData (video, callback) {
212 videos.removeVideosDataFromDisk([ video ], function (err) {
213 if (err) logger.error('Cannot remove video data from disk.', { video: video })
214
215 return callback(null, video)
216 })
217 },
218
219 function sendInformationToFriends (video, callback) {
220 const params = {
221 name: video.name,
222 magnetUri: video.magnetUri
223 }
224
225 friends.removeVideoToFriends(params)
226
227 return callback(null)
228 }
229 ], function (err) {
230 if (err) {
231 logger.error('Errors when removed the video.', { error: err })
232 return next(err)
233 }
234
235 return res.type('json').status(204).end()
236 })
237 }
238
239 function searchVideos (req, res, next) {
240 Videos.search(req.params.name, req.query.start, req.query.count, req.query.sort, function (err, videosList) {
241 if (err) return next(err)
242
243 res.json(getFormatedVideos(videosList))
244 })
245 }
246
247 // ---------------------------------------------------------------------------
248
249 function getFormatedVideo (videoObj) {
250 const formatedVideo = {
251 id: videoObj._id,
252 name: videoObj.name,
253 description: videoObj.description,
254 podUrl: videoObj.podUrl,
255 isLocal: videos.getVideoState(videoObj).owned,
256 magnetUri: videoObj.magnetUri,
257 author: videoObj.author,
258 duration: videoObj.duration,
259 thumbnailPath: constants.THUMBNAILS_STATIC_PATH + '/' + videoObj.thumbnail,
260 createdDate: videoObj.createdDate
261 }
262
263 return formatedVideo
264 }
265
266 function getFormatedVideos (videosObj) {
267 const formatedVideos = []
268
269 videosObj.forEach(function (videoObj) {
270 formatedVideos.push(getFormatedVideo(videoObj))
271 })
272
273 return formatedVideos
274 }
275
276 // Maybe the torrent is not seeded, but we catch the error to don't stop the removing process
277 function removeTorrent (magnetUri, callback) {
278 try {
279 webtorrent.remove(magnetUri, callback)
280 } catch (err) {
281 logger.warn('Cannot remove the torrent from WebTorrent', { err: err })
282 return callback(null)
283 }
284 }