]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/video-playlist.ts
e026b4d16dc5dbba5b54d2c54715325bc113c8d8
[github/Chocobozzz/PeerTube.git] / server / controllers / api / video-playlist.ts
1 import * as express from 'express'
2 import { getFormattedObjects, getServerActor } from '../../helpers/utils'
3 import {
4 asyncMiddleware,
5 asyncRetryTransactionMiddleware,
6 authenticate,
7 commonVideosFiltersValidator, optionalAuthenticate,
8 paginationValidator,
9 setDefaultPagination,
10 setDefaultSort
11 } from '../../middlewares'
12 import { VideoChannelModel } from '../../models/video/video-channel'
13 import { videoPlaylistsSortValidator } from '../../middlewares/validators'
14 import { buildNSFWFilter, createReqFiles, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils'
15 import { CONFIG, MIMETYPES, sequelizeTypescript, THUMBNAILS_SIZE } from '../../initializers'
16 import { logger } from '../../helpers/logger'
17 import { resetSequelizeInstance } from '../../helpers/database-utils'
18 import { VideoPlaylistModel } from '../../models/video/video-playlist'
19 import {
20 videoPlaylistsAddValidator,
21 videoPlaylistsAddVideoValidator,
22 videoPlaylistsDeleteValidator,
23 videoPlaylistsGetValidator,
24 videoPlaylistsReorderVideosValidator,
25 videoPlaylistsUpdateOrRemoveVideoValidator,
26 videoPlaylistsUpdateValidator
27 } from '../../middlewares/validators/videos/video-playlists'
28 import { VideoPlaylistCreate } from '../../../shared/models/videos/playlist/video-playlist-create.model'
29 import { VideoPlaylistPrivacy } from '../../../shared/models/videos/playlist/video-playlist-privacy.model'
30 import { processImage } from '../../helpers/image-utils'
31 import { join } from 'path'
32 import { UserModel } from '../../models/account/user'
33 import {
34 sendCreateVideoPlaylist,
35 sendDeleteVideoPlaylist,
36 sendUpdateVideoPlaylist
37 } from '../../lib/activitypub/send'
38 import {
39 getVideoPlaylistActivityPubUrl,
40 getVideoPlaylistElementActivityPubUrl
41 } from '../../lib/activitypub/url'
42 import { VideoPlaylistUpdate } from '../../../shared/models/videos/playlist/video-playlist-update.model'
43 import { VideoModel } from '../../models/video/video'
44 import { VideoPlaylistElementModel } from '../../models/video/video-playlist-element'
45 import { VideoPlaylistElementCreate } from '../../../shared/models/videos/playlist/video-playlist-element-create.model'
46 import { VideoPlaylistElementUpdate } from '../../../shared/models/videos/playlist/video-playlist-element-update.model'
47 import { copy, pathExists } from 'fs-extra'
48
49 const reqThumbnailFile = createReqFiles([ 'thumbnailfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { thumbnailfile: CONFIG.STORAGE.TMP_DIR })
50
51 const videoPlaylistRouter = express.Router()
52
53 videoPlaylistRouter.get('/',
54 paginationValidator,
55 videoPlaylistsSortValidator,
56 setDefaultSort,
57 setDefaultPagination,
58 asyncMiddleware(listVideoPlaylists)
59 )
60
61 videoPlaylistRouter.get('/:playlistId',
62 asyncMiddleware(videoPlaylistsGetValidator),
63 getVideoPlaylist
64 )
65
66 videoPlaylistRouter.post('/',
67 authenticate,
68 reqThumbnailFile,
69 asyncMiddleware(videoPlaylistsAddValidator),
70 asyncRetryTransactionMiddleware(addVideoPlaylist)
71 )
72
73 videoPlaylistRouter.put('/:playlistId',
74 authenticate,
75 reqThumbnailFile,
76 asyncMiddleware(videoPlaylistsUpdateValidator),
77 asyncRetryTransactionMiddleware(updateVideoPlaylist)
78 )
79
80 videoPlaylistRouter.delete('/:playlistId',
81 authenticate,
82 asyncMiddleware(videoPlaylistsDeleteValidator),
83 asyncRetryTransactionMiddleware(removeVideoPlaylist)
84 )
85
86 videoPlaylistRouter.get('/:playlistId/videos',
87 asyncMiddleware(videoPlaylistsGetValidator),
88 paginationValidator,
89 setDefaultPagination,
90 optionalAuthenticate,
91 commonVideosFiltersValidator,
92 asyncMiddleware(getVideoPlaylistVideos)
93 )
94
95 videoPlaylistRouter.post('/:playlistId/videos',
96 authenticate,
97 asyncMiddleware(videoPlaylistsAddVideoValidator),
98 asyncRetryTransactionMiddleware(addVideoInPlaylist)
99 )
100
101 videoPlaylistRouter.post('/:playlistId/videos/reorder',
102 authenticate,
103 asyncMiddleware(videoPlaylistsReorderVideosValidator),
104 asyncRetryTransactionMiddleware(reorderVideosPlaylist)
105 )
106
107 videoPlaylistRouter.put('/:playlistId/videos/:videoId',
108 authenticate,
109 asyncMiddleware(videoPlaylistsUpdateOrRemoveVideoValidator),
110 asyncRetryTransactionMiddleware(updateVideoPlaylistElement)
111 )
112
113 videoPlaylistRouter.delete('/:playlistId/videos/:videoId',
114 authenticate,
115 asyncMiddleware(videoPlaylistsUpdateOrRemoveVideoValidator),
116 asyncRetryTransactionMiddleware(removeVideoFromPlaylist)
117 )
118
119 // ---------------------------------------------------------------------------
120
121 export {
122 videoPlaylistRouter
123 }
124
125 // ---------------------------------------------------------------------------
126
127 async function listVideoPlaylists (req: express.Request, res: express.Response) {
128 const serverActor = await getServerActor()
129 const resultList = await VideoPlaylistModel.listForApi({
130 followerActorId: serverActor.id,
131 start: req.query.start,
132 count: req.query.count,
133 sort: req.query.sort
134 })
135
136 return res.json(getFormattedObjects(resultList.data, resultList.total))
137 }
138
139 function getVideoPlaylist (req: express.Request, res: express.Response) {
140 const videoPlaylist = res.locals.videoPlaylist as VideoPlaylistModel
141
142 return res.json(videoPlaylist.toFormattedJSON())
143 }
144
145 async function addVideoPlaylist (req: express.Request, res: express.Response) {
146 const videoPlaylistInfo: VideoPlaylistCreate = req.body
147 const user: UserModel = res.locals.oauth.token.User
148
149 const videoPlaylist = new VideoPlaylistModel({
150 name: videoPlaylistInfo.displayName,
151 description: videoPlaylistInfo.description,
152 privacy: videoPlaylistInfo.privacy || VideoPlaylistPrivacy.PRIVATE,
153 ownerAccountId: user.Account.id
154 })
155
156 videoPlaylist.url = getVideoPlaylistActivityPubUrl(videoPlaylist) // We use the UUID, so set the URL after building the object
157
158 if (videoPlaylistInfo.videoChannelId !== undefined) {
159 const videoChannel = res.locals.videoChannel as VideoChannelModel
160
161 videoPlaylist.videoChannelId = videoChannel.id
162 videoPlaylist.VideoChannel = videoChannel
163 }
164
165 const thumbnailField = req.files['thumbnailfile']
166 if (thumbnailField) {
167 const thumbnailPhysicalFile = thumbnailField[ 0 ]
168 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoPlaylist.getThumbnailName()), THUMBNAILS_SIZE)
169 }
170
171 const videoPlaylistCreated: VideoPlaylistModel = await sequelizeTypescript.transaction(async t => {
172 const videoPlaylistCreated = await videoPlaylist.save({ transaction: t })
173
174 videoPlaylistCreated.OwnerAccount = user.Account
175 await sendCreateVideoPlaylist(videoPlaylistCreated, t)
176
177 return videoPlaylistCreated
178 })
179
180 logger.info('Video playlist with uuid %s created.', videoPlaylist.uuid)
181
182 return res.json({
183 videoPlaylist: {
184 id: videoPlaylistCreated.id,
185 uuid: videoPlaylistCreated.uuid
186 }
187 }).end()
188 }
189
190 async function updateVideoPlaylist (req: express.Request, res: express.Response) {
191 const videoPlaylistInstance = res.locals.videoPlaylist as VideoPlaylistModel
192 const videoPlaylistFieldsSave = videoPlaylistInstance.toJSON()
193 const videoPlaylistInfoToUpdate = req.body as VideoPlaylistUpdate
194 const wasPrivatePlaylist = videoPlaylistInstance.privacy === VideoPlaylistPrivacy.PRIVATE
195
196 const thumbnailField = req.files['thumbnailfile']
197 if (thumbnailField) {
198 const thumbnailPhysicalFile = thumbnailField[ 0 ]
199 await processImage(
200 thumbnailPhysicalFile,
201 join(CONFIG.STORAGE.THUMBNAILS_DIR, videoPlaylistInstance.getThumbnailName()),
202 THUMBNAILS_SIZE
203 )
204 }
205
206 try {
207 await sequelizeTypescript.transaction(async t => {
208 const sequelizeOptions = {
209 transaction: t
210 }
211
212 if (videoPlaylistInfoToUpdate.videoChannelId !== undefined) {
213 if (videoPlaylistInfoToUpdate.videoChannelId === null) {
214 videoPlaylistInstance.videoChannelId = null
215 } else {
216 const videoChannel = res.locals.videoChannel as VideoChannelModel
217
218 videoPlaylistInstance.videoChannelId = videoChannel.id
219 }
220 }
221
222 if (videoPlaylistInfoToUpdate.displayName !== undefined) videoPlaylistInstance.name = videoPlaylistInfoToUpdate.displayName
223 if (videoPlaylistInfoToUpdate.description !== undefined) videoPlaylistInstance.description = videoPlaylistInfoToUpdate.description
224
225 if (videoPlaylistInfoToUpdate.privacy !== undefined) {
226 videoPlaylistInstance.privacy = parseInt(videoPlaylistInfoToUpdate.privacy.toString(), 10)
227 }
228
229 const playlistUpdated = await videoPlaylistInstance.save(sequelizeOptions)
230
231 const isNewPlaylist = wasPrivatePlaylist && playlistUpdated.privacy !== VideoPlaylistPrivacy.PRIVATE
232
233 if (isNewPlaylist) {
234 await sendCreateVideoPlaylist(playlistUpdated, t)
235 } else {
236 await sendUpdateVideoPlaylist(playlistUpdated, t)
237 }
238
239 logger.info('Video playlist %s updated.', videoPlaylistInstance.uuid)
240
241 return playlistUpdated
242 })
243 } catch (err) {
244 logger.debug('Cannot update the video playlist.', { err })
245
246 // Force fields we want to update
247 // If the transaction is retried, sequelize will think the object has not changed
248 // So it will skip the SQL request, even if the last one was ROLLBACKed!
249 resetSequelizeInstance(videoPlaylistInstance, videoPlaylistFieldsSave)
250
251 throw err
252 }
253
254 return res.type('json').status(204).end()
255 }
256
257 async function removeVideoPlaylist (req: express.Request, res: express.Response) {
258 const videoPlaylistInstance: VideoPlaylistModel = res.locals.videoPlaylist
259
260 await sequelizeTypescript.transaction(async t => {
261 await videoPlaylistInstance.destroy({ transaction: t })
262
263 await sendDeleteVideoPlaylist(videoPlaylistInstance, t)
264
265 logger.info('Video playlist %s deleted.', videoPlaylistInstance.uuid)
266 })
267
268 return res.type('json').status(204).end()
269 }
270
271 async function addVideoInPlaylist (req: express.Request, res: express.Response) {
272 const body: VideoPlaylistElementCreate = req.body
273 const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
274 const video: VideoModel = res.locals.video
275
276 const playlistElement: VideoPlaylistElementModel = await sequelizeTypescript.transaction(async t => {
277 const position = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id, t)
278
279 const playlistElement = await VideoPlaylistElementModel.create({
280 url: getVideoPlaylistElementActivityPubUrl(videoPlaylist, video),
281 position,
282 startTimestamp: body.startTimestamp || null,
283 stopTimestamp: body.stopTimestamp || null,
284 videoPlaylistId: videoPlaylist.id,
285 videoId: video.id
286 }, { transaction: t })
287
288 // If the user did not set a thumbnail, automatically take the video thumbnail
289 if (playlistElement.position === 1) {
290 const playlistThumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, videoPlaylist.getThumbnailName())
291
292 if (await pathExists(playlistThumbnailPath) === false) {
293 const videoThumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName())
294 await copy(videoThumbnailPath, playlistThumbnailPath)
295 }
296 }
297
298 await sendUpdateVideoPlaylist(videoPlaylist, t)
299
300 return playlistElement
301 })
302
303 logger.info('Video added in playlist %s at position %d.', videoPlaylist.uuid, playlistElement.position)
304
305 return res.json({
306 videoPlaylistElement: {
307 id: playlistElement.id
308 }
309 }).end()
310 }
311
312 async function updateVideoPlaylistElement (req: express.Request, res: express.Response) {
313 const body: VideoPlaylistElementUpdate = req.body
314 const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
315 const videoPlaylistElement: VideoPlaylistElementModel = res.locals.videoPlaylistElement
316
317 const playlistElement: VideoPlaylistElementModel = await sequelizeTypescript.transaction(async t => {
318 if (body.startTimestamp !== undefined) videoPlaylistElement.startTimestamp = body.startTimestamp
319 if (body.stopTimestamp !== undefined) videoPlaylistElement.stopTimestamp = body.stopTimestamp
320
321 const element = await videoPlaylistElement.save({ transaction: t })
322
323 await sendUpdateVideoPlaylist(videoPlaylist, t)
324
325 return element
326 })
327
328 logger.info('Element of position %d of playlist %s updated.', playlistElement.position, videoPlaylist.uuid)
329
330 return res.type('json').status(204).end()
331 }
332
333 async function removeVideoFromPlaylist (req: express.Request, res: express.Response) {
334 const videoPlaylistElement: VideoPlaylistElementModel = res.locals.videoPlaylistElement
335 const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
336 const positionToDelete = videoPlaylistElement.position
337
338 await sequelizeTypescript.transaction(async t => {
339 await videoPlaylistElement.destroy({ transaction: t })
340
341 // Decrease position of the next elements
342 await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, positionToDelete, null, -1, t)
343
344 await sendUpdateVideoPlaylist(videoPlaylist, t)
345
346 logger.info('Video playlist element %d of playlist %s deleted.', videoPlaylistElement.position, videoPlaylist.uuid)
347 })
348
349 return res.type('json').status(204).end()
350 }
351
352 async function reorderVideosPlaylist (req: express.Request, res: express.Response) {
353 const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
354
355 const start: number = req.body.startPosition
356 const insertAfter: number = req.body.insertAfterPosition
357 const reorderLength: number = req.body.reorderLength || 1
358
359 if (start === insertAfter) {
360 return res.status(204).end()
361 }
362
363 // Example: if we reorder position 2 and insert after position 5 (so at position 6): # 1 2 3 4 5 6 7 8 9
364 // * increase position when position > 5 # 1 2 3 4 5 7 8 9 10
365 // * update position 2 -> position 6 # 1 3 4 5 6 7 8 9 10
366 // * decrease position when position position > 2 # 1 2 3 4 5 6 7 8 9
367 await sequelizeTypescript.transaction(async t => {
368 const newPosition = insertAfter + 1
369
370 // Add space after the position when we want to insert our reordered elements (increase)
371 await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, newPosition, null, reorderLength, t)
372
373 let oldPosition = start
374
375 // We incremented the position of the elements we want to reorder
376 if (start >= newPosition) oldPosition += reorderLength
377
378 const endOldPosition = oldPosition + reorderLength - 1
379 // Insert our reordered elements in their place (update)
380 await VideoPlaylistElementModel.reassignPositionOf(videoPlaylist.id, oldPosition, endOldPosition, newPosition, t)
381
382 // Decrease positions of elements after the old position of our ordered elements (decrease)
383 await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, oldPosition, null, -reorderLength, t)
384
385 await sendUpdateVideoPlaylist(videoPlaylist, t)
386 })
387
388 logger.info(
389 'Reordered playlist %s (inserted after %d elements %d - %d).',
390 videoPlaylist.uuid, insertAfter, start, start + reorderLength - 1
391 )
392
393 return res.type('json').status(204).end()
394 }
395
396 async function getVideoPlaylistVideos (req: express.Request, res: express.Response) {
397 const videoPlaylistInstance: VideoPlaylistModel = res.locals.videoPlaylist
398 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
399
400 const resultList = await VideoModel.listForApi({
401 followerActorId,
402 start: req.query.start,
403 count: req.query.count,
404 sort: 'VideoPlaylistElements.position',
405 includeLocalVideos: true,
406 categoryOneOf: req.query.categoryOneOf,
407 licenceOneOf: req.query.licenceOneOf,
408 languageOneOf: req.query.languageOneOf,
409 tagsOneOf: req.query.tagsOneOf,
410 tagsAllOf: req.query.tagsAllOf,
411 filter: req.query.filter,
412 nsfw: buildNSFWFilter(res, req.query.nsfw),
413 withFiles: false,
414 videoPlaylistId: videoPlaylistInstance.id,
415 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
416 })
417
418 return res.json(getFormattedObjects(resultList.data, resultList.total))
419 }