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