]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/video-playlist.ts
8605f3dfc1e752b436f4a44adf48809a7b149fa1
[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, optionalAuthenticate,
8 paginationValidator,
9 setDefaultPagination,
10 setDefaultSort
11 } from '../../middlewares'
12 import { VideoChannelModel } from '../../models/video/video-channel'
13 import { videoPlaylistsSortValidator } from '../../middlewares/validators'
14 import { buildNSFWFilter, createReqFiles, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils'
15 import { CONFIG, MIMETYPES, sequelizeTypescript, THUMBNAILS_SIZE } from '../../initializers'
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 { UserModel } from '../../models/account/user'
34 import {
35 sendCreateVideoPlaylist,
36 sendDeleteVideoPlaylist,
37 sendUpdateVideoPlaylist
38 } from '../../lib/activitypub/send'
39 import {
40 getVideoPlaylistActivityPubUrl,
41 getVideoPlaylistElementActivityPubUrl
42 } from '../../lib/activitypub/url'
43 import { VideoPlaylistUpdate } from '../../../shared/models/videos/playlist/video-playlist-update.model'
44 import { VideoModel } from '../../models/video/video'
45 import { VideoPlaylistElementModel } from '../../models/video/video-playlist-element'
46 import { VideoPlaylistElementCreate } from '../../../shared/models/videos/playlist/video-playlist-element-create.model'
47 import { VideoPlaylistElementUpdate } from '../../../shared/models/videos/playlist/video-playlist-element-update.model'
48 import { copy, pathExists } from 'fs-extra'
49 import { AccountModel } from '../../models/account/account'
50
51 const reqThumbnailFile = createReqFiles([ 'thumbnailfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { thumbnailfile: CONFIG.STORAGE.TMP_DIR })
52
53 const videoPlaylistRouter = express.Router()
54
55 videoPlaylistRouter.get('/',
56 paginationValidator,
57 videoPlaylistsSortValidator,
58 setDefaultSort,
59 setDefaultPagination,
60 commonVideoPlaylistFiltersValidator,
61 asyncMiddleware(listVideoPlaylists)
62 )
63
64 videoPlaylistRouter.get('/:playlistId',
65 asyncMiddleware(videoPlaylistsGetValidator),
66 getVideoPlaylist
67 )
68
69 videoPlaylistRouter.post('/',
70 authenticate,
71 reqThumbnailFile,
72 asyncMiddleware(videoPlaylistsAddValidator),
73 asyncRetryTransactionMiddleware(addVideoPlaylist)
74 )
75
76 videoPlaylistRouter.put('/:playlistId',
77 authenticate,
78 reqThumbnailFile,
79 asyncMiddleware(videoPlaylistsUpdateValidator),
80 asyncRetryTransactionMiddleware(updateVideoPlaylist)
81 )
82
83 videoPlaylistRouter.delete('/:playlistId',
84 authenticate,
85 asyncMiddleware(videoPlaylistsDeleteValidator),
86 asyncRetryTransactionMiddleware(removeVideoPlaylist)
87 )
88
89 videoPlaylistRouter.get('/:playlistId/videos',
90 asyncMiddleware(videoPlaylistsGetValidator),
91 paginationValidator,
92 setDefaultPagination,
93 optionalAuthenticate,
94 commonVideosFiltersValidator,
95 asyncMiddleware(getVideoPlaylistVideos)
96 )
97
98 videoPlaylistRouter.post('/:playlistId/videos',
99 authenticate,
100 asyncMiddleware(videoPlaylistsAddVideoValidator),
101 asyncRetryTransactionMiddleware(addVideoInPlaylist)
102 )
103
104 videoPlaylistRouter.post('/:playlistId/videos/reorder',
105 authenticate,
106 asyncMiddleware(videoPlaylistsReorderVideosValidator),
107 asyncRetryTransactionMiddleware(reorderVideosPlaylist)
108 )
109
110 videoPlaylistRouter.put('/:playlistId/videos/:videoId',
111 authenticate,
112 asyncMiddleware(videoPlaylistsUpdateOrRemoveVideoValidator),
113 asyncRetryTransactionMiddleware(updateVideoPlaylistElement)
114 )
115
116 videoPlaylistRouter.delete('/:playlistId/videos/:videoId',
117 authenticate,
118 asyncMiddleware(videoPlaylistsUpdateOrRemoveVideoValidator),
119 asyncRetryTransactionMiddleware(removeVideoFromPlaylist)
120 )
121
122 // ---------------------------------------------------------------------------
123
124 export {
125 videoPlaylistRouter
126 }
127
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 !== undefined) {
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 // We need more attributes for the federation
237 playlistUpdated.OwnerAccount = await AccountModel.load(playlistUpdated.OwnerAccount.id, t)
238
239 const isNewPlaylist = wasPrivatePlaylist && playlistUpdated.privacy !== VideoPlaylistPrivacy.PRIVATE
240
241 if (isNewPlaylist) {
242 await sendCreateVideoPlaylist(playlistUpdated, t)
243 } else {
244 await sendUpdateVideoPlaylist(playlistUpdated, t)
245 }
246
247 logger.info('Video playlist %s updated.', videoPlaylistInstance.uuid)
248
249 return playlistUpdated
250 })
251 } catch (err) {
252 logger.debug('Cannot update the video playlist.', { err })
253
254 // Force fields we want to update
255 // If the transaction is retried, sequelize will think the object has not changed
256 // So it will skip the SQL request, even if the last one was ROLLBACKed!
257 resetSequelizeInstance(videoPlaylistInstance, videoPlaylistFieldsSave)
258
259 throw err
260 }
261
262 return res.type('json').status(204).end()
263 }
264
265 async function removeVideoPlaylist (req: express.Request, res: express.Response) {
266 const videoPlaylistInstance: VideoPlaylistModel = res.locals.videoPlaylist
267
268 await sequelizeTypescript.transaction(async t => {
269 await videoPlaylistInstance.destroy({ transaction: t })
270
271 await sendDeleteVideoPlaylist(videoPlaylistInstance, t)
272
273 logger.info('Video playlist %s deleted.', videoPlaylistInstance.uuid)
274 })
275
276 return res.type('json').status(204).end()
277 }
278
279 async function addVideoInPlaylist (req: express.Request, res: express.Response) {
280 const body: VideoPlaylistElementCreate = req.body
281 const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
282 const video: VideoModel = res.locals.video
283
284 const playlistElement: VideoPlaylistElementModel = await sequelizeTypescript.transaction(async t => {
285 const position = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id, t)
286
287 const playlistElement = await VideoPlaylistElementModel.create({
288 url: getVideoPlaylistElementActivityPubUrl(videoPlaylist, video),
289 position,
290 startTimestamp: body.startTimestamp || null,
291 stopTimestamp: body.stopTimestamp || null,
292 videoPlaylistId: videoPlaylist.id,
293 videoId: video.id
294 }, { transaction: t })
295
296 // If the user did not set a thumbnail, automatically take the video thumbnail
297 if (playlistElement.position === 1) {
298 const playlistThumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, videoPlaylist.getThumbnailName())
299
300 if (await pathExists(playlistThumbnailPath) === false) {
301 logger.info('Generating default thumbnail to playlist %s.', videoPlaylist.url)
302
303 const videoThumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName())
304 await copy(videoThumbnailPath, playlistThumbnailPath)
305 }
306 }
307
308 // We need more attributes for the federation
309 videoPlaylist.OwnerAccount = await AccountModel.load(videoPlaylist.OwnerAccount.id, t)
310 await sendUpdateVideoPlaylist(videoPlaylist, t)
311
312 return playlistElement
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 // We need more attributes for the federation
336 videoPlaylist.OwnerAccount = await AccountModel.load(videoPlaylist.OwnerAccount.id, t)
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 // We need more attributes for the federation
359 videoPlaylist.OwnerAccount = await AccountModel.load(videoPlaylist.OwnerAccount.id, t)
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
368 async function reorderVideosPlaylist (req: express.Request, res: express.Response) {
369 const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
370
371 const start: number = req.body.startPosition
372 const insertAfter: number = req.body.insertAfterPosition
373 const reorderLength: number = req.body.reorderLength || 1
374
375 if (start === insertAfter) {
376 return res.status(204).end()
377 }
378
379 // Example: if we reorder position 2 and insert after position 5 (so at position 6): # 1 2 3 4 5 6 7 8 9
380 // * increase position when position > 5 # 1 2 3 4 5 7 8 9 10
381 // * update position 2 -> position 6 # 1 3 4 5 6 7 8 9 10
382 // * decrease position when position position > 2 # 1 2 3 4 5 6 7 8 9
383 await sequelizeTypescript.transaction(async t => {
384 const newPosition = insertAfter + 1
385
386 // Add space after the position when we want to insert our reordered elements (increase)
387 await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, newPosition, null, reorderLength, t)
388
389 let oldPosition = start
390
391 // We incremented the position of the elements we want to reorder
392 if (start >= newPosition) oldPosition += reorderLength
393
394 const endOldPosition = oldPosition + reorderLength - 1
395 // Insert our reordered elements in their place (update)
396 await VideoPlaylistElementModel.reassignPositionOf(videoPlaylist.id, oldPosition, endOldPosition, newPosition, t)
397
398 // Decrease positions of elements after the old position of our ordered elements (decrease)
399 await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, oldPosition, null, -reorderLength, t)
400
401 // We need more attributes for the federation
402 videoPlaylist.OwnerAccount = await AccountModel.load(videoPlaylist.OwnerAccount.id, t)
403 await sendUpdateVideoPlaylist(videoPlaylist, t)
404 })
405
406 logger.info(
407 'Reordered playlist %s (inserted after %d elements %d - %d).',
408 videoPlaylist.uuid, insertAfter, start, start + reorderLength - 1
409 )
410
411 return res.type('json').status(204).end()
412 }
413
414 async function getVideoPlaylistVideos (req: express.Request, res: express.Response) {
415 const videoPlaylistInstance: VideoPlaylistModel = res.locals.videoPlaylist
416 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
417
418 const resultList = await VideoModel.listForApi({
419 followerActorId,
420 start: req.query.start,
421 count: req.query.count,
422 sort: 'VideoPlaylistElements.position',
423 includeLocalVideos: true,
424 categoryOneOf: req.query.categoryOneOf,
425 licenceOneOf: req.query.licenceOneOf,
426 languageOneOf: req.query.languageOneOf,
427 tagsOneOf: req.query.tagsOneOf,
428 tagsAllOf: req.query.tagsAllOf,
429 filter: req.query.filter,
430 nsfw: buildNSFWFilter(res, req.query.nsfw),
431 withFiles: false,
432 videoPlaylistId: videoPlaylistInstance.id,
433 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
434 })
435
436 const additionalAttributes = { playlistInfo: true }
437 return res.json(getFormattedObjects(resultList.data, resultList.total, { additionalAttributes }))
438 }