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