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