]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos.js
Server: use binary data instead of base64 to send thumbnails
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos.js
1 'use strict'
2
3 const each = require('async/each')
4 const express = require('express')
5 const fs = require('fs')
6 const multer = require('multer')
7 const path = require('path')
8 const waterfall = require('async/waterfall')
9
10 const constants = require('../../initializers/constants')
11 const db = require('../../initializers/database')
12 const logger = require('../../helpers/logger')
13 const friends = require('../../lib/friends')
14 const middlewares = require('../../middlewares')
15 const oAuth = middlewares.oauth
16 const pagination = middlewares.pagination
17 const validators = middlewares.validators
18 const validatorsPagination = validators.pagination
19 const validatorsSort = validators.sort
20 const validatorsVideos = validators.videos
21 const search = middlewares.search
22 const sort = middlewares.sort
23 const utils = require('../../helpers/utils')
24
25 const router = express.Router()
26
27 // multer configuration
28 const storage = multer.diskStorage({
29 destination: function (req, file, cb) {
30 cb(null, constants.CONFIG.STORAGE.VIDEOS_DIR)
31 },
32
33 filename: function (req, file, cb) {
34 let extension = ''
35 if (file.mimetype === 'video/webm') extension = 'webm'
36 else if (file.mimetype === 'video/mp4') extension = 'mp4'
37 else if (file.mimetype === 'video/ogg') extension = 'ogv'
38 utils.generateRandomString(16, function (err, randomString) {
39 const fieldname = err ? undefined : randomString
40 cb(null, fieldname + '.' + extension)
41 })
42 }
43 })
44
45 const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
46
47 router.get('/',
48 validatorsPagination.pagination,
49 validatorsSort.videosSort,
50 sort.setVideosSort,
51 pagination.setPagination,
52 listVideos
53 )
54 router.post('/',
55 oAuth.authenticate,
56 reqFiles,
57 validatorsVideos.videosAdd,
58 addVideo
59 )
60 router.get('/:id',
61 validatorsVideos.videosGet,
62 getVideo
63 )
64 router.delete('/:id',
65 oAuth.authenticate,
66 validatorsVideos.videosRemove,
67 removeVideo
68 )
69 router.get('/search/:value',
70 validatorsVideos.videosSearch,
71 validatorsPagination.pagination,
72 validatorsSort.videosSort,
73 sort.setVideosSort,
74 pagination.setPagination,
75 search.setVideosSearch,
76 searchVideos
77 )
78
79 // ---------------------------------------------------------------------------
80
81 module.exports = router
82
83 // ---------------------------------------------------------------------------
84
85 function addVideo (req, res, next) {
86 const videoFile = req.files.videofile[0]
87 const videoInfos = req.body
88
89 waterfall([
90
91 function startTransaction (callback) {
92 db.sequelize.transaction().asCallback(function (err, t) {
93 return callback(err, t)
94 })
95 },
96
97 function findOrCreateAuthor (t, callback) {
98 const user = res.locals.oauth.token.User
99
100 const query = {
101 where: {
102 name: user.username,
103 podId: null,
104 userId: user.id
105 },
106 defaults: {
107 name: user.username,
108 podId: null, // null because it is OUR pod
109 userId: user.id
110 },
111 transaction: t
112 }
113
114 db.Author.findOrCreate(query).asCallback(function (err, result) {
115 const authorInstance = result[0]
116
117 return callback(err, t, authorInstance)
118 })
119 },
120
121 function findOrCreateTags (t, author, callback) {
122 const tags = videoInfos.tags
123 const tagInstances = []
124
125 each(tags, function (tag, callbackEach) {
126 const query = {
127 where: {
128 name: tag
129 },
130 defaults: {
131 name: tag
132 },
133 transaction: t
134 }
135
136 db.Tag.findOrCreate(query).asCallback(function (err, res) {
137 if (err) return callbackEach(err)
138
139 // res = [ tag, isCreated ]
140 const tag = res[0]
141 tagInstances.push(tag)
142 return callbackEach()
143 })
144 }, function (err) {
145 return callback(err, t, author, tagInstances)
146 })
147 },
148
149 function createVideoObject (t, author, tagInstances, callback) {
150 const videoData = {
151 name: videoInfos.name,
152 remoteId: null,
153 extname: path.extname(videoFile.filename),
154 description: videoInfos.description,
155 duration: videoFile.duration,
156 authorId: author.id
157 }
158
159 const video = db.Video.build(videoData)
160
161 return callback(null, t, author, tagInstances, video)
162 },
163
164 // Set the videoname the same as the id
165 function renameVideoFile (t, author, tagInstances, video, callback) {
166 const videoDir = constants.CONFIG.STORAGE.VIDEOS_DIR
167 const source = path.join(videoDir, videoFile.filename)
168 const destination = path.join(videoDir, video.getVideoFilename())
169
170 fs.rename(source, destination, function (err) {
171 return callback(err, t, author, tagInstances, video)
172 })
173 },
174
175 function insertVideoIntoDB (t, author, tagInstances, video, callback) {
176 const options = { transaction: t }
177
178 // Add tags association
179 video.save(options).asCallback(function (err, videoCreated) {
180 if (err) return callback(err)
181
182 // Do not forget to add Author informations to the created video
183 videoCreated.Author = author
184
185 return callback(err, t, tagInstances, videoCreated)
186 })
187 },
188
189 function associateTagsToVideo (t, tagInstances, video, callback) {
190 const options = { transaction: t }
191
192 video.setTags(tagInstances, options).asCallback(function (err) {
193 video.Tags = tagInstances
194
195 return callback(err, t, video)
196 })
197 },
198
199 function sendToFriends (t, video, callback) {
200 video.toRemoteJSON(function (err, remoteVideo) {
201 if (err) return callback(err)
202
203 // Now we'll add the video's meta data to our friends
204 friends.addVideoToFriends(remoteVideo)
205
206 return callback(null, t)
207 })
208 }
209
210 ], function andFinally (err, t) {
211 if (err) {
212 logger.error('Cannot insert the video.')
213
214 // Abort transaction?
215 if (t) t.rollback()
216
217 return next(err)
218 }
219
220 // Commit transaction
221 t.commit()
222
223 // TODO : include Location of the new video -> 201
224 return res.type('json').status(204).end()
225 })
226 }
227
228 function getVideo (req, res, next) {
229 db.Video.loadAndPopulateAuthorAndPodAndTags(req.params.id, function (err, video) {
230 if (err) return next(err)
231
232 if (!video) {
233 return res.type('json').status(204).end()
234 }
235
236 res.json(video.toFormatedJSON())
237 })
238 }
239
240 function listVideos (req, res, next) {
241 db.Video.listForApi(req.query.start, req.query.count, req.query.sort, function (err, videosList, videosTotal) {
242 if (err) return next(err)
243
244 res.json(getFormatedVideos(videosList, videosTotal))
245 })
246 }
247
248 function removeVideo (req, res, next) {
249 const videoId = req.params.id
250
251 waterfall([
252 function loadVideo (callback) {
253 db.Video.load(videoId, function (err, video) {
254 return callback(err, video)
255 })
256 },
257
258 function deleteVideo (video, callback) {
259 // Informations to other pods will be sent by the afterDestroy video hook
260 video.destroy().asCallback(callback)
261 }
262 ], function andFinally (err) {
263 if (err) {
264 logger.error('Errors when removed the video.', { error: err })
265 return next(err)
266 }
267
268 return res.type('json').status(204).end()
269 })
270 }
271
272 function searchVideos (req, res, next) {
273 db.Video.searchAndPopulateAuthorAndPodAndTags(
274 req.params.value, req.query.field, req.query.start, req.query.count, req.query.sort,
275 function (err, videosList, videosTotal) {
276 if (err) return next(err)
277
278 res.json(getFormatedVideos(videosList, videosTotal))
279 }
280 )
281 }
282
283 // ---------------------------------------------------------------------------
284
285 function getFormatedVideos (videos, videosTotal) {
286 const formatedVideos = []
287
288 videos.forEach(function (video) {
289 formatedVideos.push(video.toFormatedJSON())
290 })
291
292 return {
293 total: videosTotal,
294 data: formatedVideos
295 }
296 }