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