Add server migrations
[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, 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
45 const reqThumbnailFile = createReqFiles([ 'thumbnailfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { thumbnailfile: CONFIG.STORAGE.TMP_DIR })
46
47 const videoPlaylistRouter = express.Router()
48
49 videoPlaylistRouter.get('/privacies', listVideoPlaylistPrivacies)
50
51 videoPlaylistRouter.get('/',
52   paginationValidator,
53   videoPlaylistsSortValidator,
54   setDefaultSort,
55   setDefaultPagination,
56   commonVideoPlaylistFiltersValidator,
57   asyncMiddleware(listVideoPlaylists)
58 )
59
60 videoPlaylistRouter.get('/:playlistId',
61   asyncMiddleware(videoPlaylistsGetValidator),
62   getVideoPlaylist
63 )
64
65 videoPlaylistRouter.post('/',
66   authenticate,
67   reqThumbnailFile,
68   asyncMiddleware(videoPlaylistsAddValidator),
69   asyncRetryTransactionMiddleware(addVideoPlaylist)
70 )
71
72 videoPlaylistRouter.put('/:playlistId',
73   authenticate,
74   reqThumbnailFile,
75   asyncMiddleware(videoPlaylistsUpdateValidator),
76   asyncRetryTransactionMiddleware(updateVideoPlaylist)
77 )
78
79 videoPlaylistRouter.delete('/:playlistId',
80   authenticate,
81   asyncMiddleware(videoPlaylistsDeleteValidator),
82   asyncRetryTransactionMiddleware(removeVideoPlaylist)
83 )
84
85 videoPlaylistRouter.get('/:playlistId/videos',
86   asyncMiddleware(videoPlaylistsGetValidator),
87   paginationValidator,
88   setDefaultPagination,
89   optionalAuthenticate,
90   commonVideosFiltersValidator,
91   asyncMiddleware(getVideoPlaylistVideos)
92 )
93
94 videoPlaylistRouter.post('/:playlistId/videos',
95   authenticate,
96   asyncMiddleware(videoPlaylistsAddVideoValidator),
97   asyncRetryTransactionMiddleware(addVideoInPlaylist)
98 )
99
100 videoPlaylistRouter.post('/:playlistId/videos/reorder',
101   authenticate,
102   asyncMiddleware(videoPlaylistsReorderVideosValidator),
103   asyncRetryTransactionMiddleware(reorderVideosPlaylist)
104 )
105
106 videoPlaylistRouter.put('/:playlistId/videos/:videoId',
107   authenticate,
108   asyncMiddleware(videoPlaylistsUpdateOrRemoveVideoValidator),
109   asyncRetryTransactionMiddleware(updateVideoPlaylistElement)
110 )
111
112 videoPlaylistRouter.delete('/:playlistId/videos/:videoId',
113   authenticate,
114   asyncMiddleware(videoPlaylistsUpdateOrRemoveVideoValidator),
115   asyncRetryTransactionMiddleware(removeVideoFromPlaylist)
116 )
117
118 // ---------------------------------------------------------------------------
119
120 export {
121   videoPlaylistRouter
122 }
123
124 // ---------------------------------------------------------------------------
125
126 function listVideoPlaylistPrivacies (req: express.Request, res: express.Response) {
127   res.json(VIDEO_PLAYLIST_PRIVACIES)
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) {
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
237       const isNewPlaylist = wasPrivatePlaylist && playlistUpdated.privacy !== VideoPlaylistPrivacy.PRIVATE
238
239       if (isNewPlaylist) {
240         await sendCreateVideoPlaylist(playlistUpdated, t)
241       } else {
242         await sendUpdateVideoPlaylist(playlistUpdated, t)
243       }
244
245       logger.info('Video playlist %s updated.', videoPlaylistInstance.uuid)
246
247       return playlistUpdated
248     })
249   } catch (err) {
250     logger.debug('Cannot update the video playlist.', { err })
251
252     // Force fields we want to update
253     // If the transaction is retried, sequelize will think the object has not changed
254     // So it will skip the SQL request, even if the last one was ROLLBACKed!
255     resetSequelizeInstance(videoPlaylistInstance, videoPlaylistFieldsSave)
256
257     throw err
258   }
259
260   return res.type('json').status(204).end()
261 }
262
263 async function removeVideoPlaylist (req: express.Request, res: express.Response) {
264   const videoPlaylistInstance: VideoPlaylistModel = res.locals.videoPlaylist
265
266   await sequelizeTypescript.transaction(async t => {
267     await videoPlaylistInstance.destroy({ transaction: t })
268
269     await sendDeleteVideoPlaylist(videoPlaylistInstance, t)
270
271     logger.info('Video playlist %s deleted.', videoPlaylistInstance.uuid)
272   })
273
274   return res.type('json').status(204).end()
275 }
276
277 async function addVideoInPlaylist (req: express.Request, res: express.Response) {
278   const body: VideoPlaylistElementCreate = req.body
279   const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
280   const video: VideoModel = res.locals.video
281
282   const playlistElement: VideoPlaylistElementModel = await sequelizeTypescript.transaction(async t => {
283     const position = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id, t)
284
285     const playlistElement = await VideoPlaylistElementModel.create({
286       url: getVideoPlaylistElementActivityPubUrl(videoPlaylist, video),
287       position,
288       startTimestamp: body.startTimestamp || null,
289       stopTimestamp: body.stopTimestamp || null,
290       videoPlaylistId: videoPlaylist.id,
291       videoId: video.id
292     }, { transaction: t })
293
294     // If the user did not set a thumbnail, automatically take the video thumbnail
295     if (playlistElement.position === 1) {
296       const playlistThumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, videoPlaylist.getThumbnailName())
297
298       if (await pathExists(playlistThumbnailPath) === false) {
299         logger.info('Generating default thumbnail to playlist %s.', videoPlaylist.url)
300
301         const videoThumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName())
302         await copy(videoThumbnailPath, playlistThumbnailPath)
303       }
304     }
305
306     await sendUpdateVideoPlaylist(videoPlaylist, t)
307
308     return playlistElement
309   })
310
311   logger.info('Video added in playlist %s at position %d.', videoPlaylist.uuid, playlistElement.position)
312
313   return res.json({
314     videoPlaylistElement: {
315       id: playlistElement.id
316     }
317   }).end()
318 }
319
320 async function updateVideoPlaylistElement (req: express.Request, res: express.Response) {
321   const body: VideoPlaylistElementUpdate = req.body
322   const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
323   const videoPlaylistElement: VideoPlaylistElementModel = res.locals.videoPlaylistElement
324
325   const playlistElement: VideoPlaylistElementModel = await sequelizeTypescript.transaction(async t => {
326     if (body.startTimestamp !== undefined) videoPlaylistElement.startTimestamp = body.startTimestamp
327     if (body.stopTimestamp !== undefined) videoPlaylistElement.stopTimestamp = body.stopTimestamp
328
329     const element = await videoPlaylistElement.save({ transaction: t })
330
331     await sendUpdateVideoPlaylist(videoPlaylist, t)
332
333     return element
334   })
335
336   logger.info('Element of position %d of playlist %s updated.', playlistElement.position, videoPlaylist.uuid)
337
338   return res.type('json').status(204).end()
339 }
340
341 async function removeVideoFromPlaylist (req: express.Request, res: express.Response) {
342   const videoPlaylistElement: VideoPlaylistElementModel = res.locals.videoPlaylistElement
343   const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
344   const positionToDelete = videoPlaylistElement.position
345
346   await sequelizeTypescript.transaction(async t => {
347     await videoPlaylistElement.destroy({ transaction: t })
348
349     // Decrease position of the next elements
350     await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, positionToDelete, null, -1, t)
351
352     await sendUpdateVideoPlaylist(videoPlaylist, t)
353
354     logger.info('Video playlist element %d of playlist %s deleted.', videoPlaylistElement.position, videoPlaylist.uuid)
355   })
356
357   return res.type('json').status(204).end()
358 }
359
360 async function reorderVideosPlaylist (req: express.Request, res: express.Response) {
361   const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
362
363   const start: number = req.body.startPosition
364   const insertAfter: number = req.body.insertAfterPosition
365   const reorderLength: number = req.body.reorderLength || 1
366
367   if (start === insertAfter) {
368     return res.status(204).end()
369   }
370
371   // Example: if we reorder position 2 and insert after position 5 (so at position 6): # 1 2 3 4 5 6 7 8 9
372   //  * increase position when position > 5 # 1 2 3 4 5 7 8 9 10
373   //  * update position 2 -> position 6 # 1 3 4 5 6 7 8 9 10
374   //  * decrease position when position position > 2 # 1 2 3 4 5 6 7 8 9
375   await sequelizeTypescript.transaction(async t => {
376     const newPosition = insertAfter + 1
377
378     // Add space after the position when we want to insert our reordered elements (increase)
379     await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, newPosition, null, reorderLength, t)
380
381     let oldPosition = start
382
383     // We incremented the position of the elements we want to reorder
384     if (start >= newPosition) oldPosition += reorderLength
385
386     const endOldPosition = oldPosition + reorderLength - 1
387     // Insert our reordered elements in their place (update)
388     await VideoPlaylistElementModel.reassignPositionOf(videoPlaylist.id, oldPosition, endOldPosition, newPosition, t)
389
390     // Decrease positions of elements after the old position of our ordered elements (decrease)
391     await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, oldPosition, null, -reorderLength, t)
392
393     await sendUpdateVideoPlaylist(videoPlaylist, t)
394   })
395
396   logger.info(
397     'Reordered playlist %s (inserted after %d elements %d - %d).',
398     videoPlaylist.uuid, insertAfter, start, start + reorderLength - 1
399   )
400
401   return res.type('json').status(204).end()
402 }
403
404 async function getVideoPlaylistVideos (req: express.Request, res: express.Response) {
405   const videoPlaylistInstance: VideoPlaylistModel = res.locals.videoPlaylist
406   const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
407
408   const resultList = await VideoModel.listForApi({
409     followerActorId,
410     start: req.query.start,
411     count: req.query.count,
412     sort: 'VideoPlaylistElements.position',
413     includeLocalVideos: true,
414     categoryOneOf: req.query.categoryOneOf,
415     licenceOneOf: req.query.licenceOneOf,
416     languageOneOf: req.query.languageOneOf,
417     tagsOneOf: req.query.tagsOneOf,
418     tagsAllOf: req.query.tagsAllOf,
419     filter: req.query.filter,
420     nsfw: buildNSFWFilter(res, req.query.nsfw),
421     withFiles: false,
422     videoPlaylistId: videoPlaylistInstance.id,
423     user: res.locals.oauth ? res.locals.oauth.token.User : undefined
424   })
425
426   const additionalAttributes = { playlistInfo: true }
427   return res.json(getFormattedObjects(resultList.data, resultList.total, { additionalAttributes }))
428 }