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