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