1 import * as express from 'express'
2 import { getFormattedObjects, getServerActor } from '../../helpers/utils'
5 asyncRetryTransactionMiddleware,
7 commonVideosFiltersValidator,
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'
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 import { VideoPlaylistReorder } from '../../../shared/models/videos/playlist/video-playlist-reorder.model'
46 const reqThumbnailFile = createReqFiles([ 'thumbnailfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { thumbnailfile: CONFIG.STORAGE.TMP_DIR })
48 const videoPlaylistRouter = express.Router()
50 videoPlaylistRouter.get('/privacies', listVideoPlaylistPrivacies)
52 videoPlaylistRouter.get('/',
54 videoPlaylistsSortValidator,
57 commonVideoPlaylistFiltersValidator,
58 asyncMiddleware(listVideoPlaylists)
61 videoPlaylistRouter.get('/:playlistId',
62 asyncMiddleware(videoPlaylistsGetValidator),
66 videoPlaylistRouter.post('/',
69 asyncMiddleware(videoPlaylistsAddValidator),
70 asyncRetryTransactionMiddleware(addVideoPlaylist)
73 videoPlaylistRouter.put('/:playlistId',
76 asyncMiddleware(videoPlaylistsUpdateValidator),
77 asyncRetryTransactionMiddleware(updateVideoPlaylist)
80 videoPlaylistRouter.delete('/:playlistId',
82 asyncMiddleware(videoPlaylistsDeleteValidator),
83 asyncRetryTransactionMiddleware(removeVideoPlaylist)
86 videoPlaylistRouter.get('/:playlistId/videos',
87 asyncMiddleware(videoPlaylistsGetValidator),
91 commonVideosFiltersValidator,
92 asyncMiddleware(getVideoPlaylistVideos)
95 videoPlaylistRouter.post('/:playlistId/videos',
97 asyncMiddleware(videoPlaylistsAddVideoValidator),
98 asyncRetryTransactionMiddleware(addVideoInPlaylist)
101 videoPlaylistRouter.post('/:playlistId/videos/reorder',
103 asyncMiddleware(videoPlaylistsReorderVideosValidator),
104 asyncRetryTransactionMiddleware(reorderVideosPlaylist)
107 videoPlaylistRouter.put('/:playlistId/videos/:videoId',
109 asyncMiddleware(videoPlaylistsUpdateOrRemoveVideoValidator),
110 asyncRetryTransactionMiddleware(updateVideoPlaylistElement)
113 videoPlaylistRouter.delete('/:playlistId/videos/:videoId',
115 asyncMiddleware(videoPlaylistsUpdateOrRemoveVideoValidator),
116 asyncRetryTransactionMiddleware(removeVideoFromPlaylist)
119 // ---------------------------------------------------------------------------
125 // ---------------------------------------------------------------------------
127 function listVideoPlaylistPrivacies (req: express.Request, res: express.Response) {
128 res.json(VIDEO_PLAYLIST_PRIVACIES)
131 async function listVideoPlaylists (req: express.Request, res: express.Response) {
132 const serverActor = await getServerActor()
133 const resultList = await VideoPlaylistModel.listForApi({
134 followerActorId: serverActor.id,
135 start: req.query.start,
136 count: req.query.count,
137 sort: req.query.sort,
141 return res.json(getFormattedObjects(resultList.data, resultList.total))
144 function getVideoPlaylist (req: express.Request, res: express.Response) {
145 const videoPlaylist = res.locals.videoPlaylist as VideoPlaylistModel
147 return res.json(videoPlaylist.toFormattedJSON())
150 async function addVideoPlaylist (req: express.Request, res: express.Response) {
151 const videoPlaylistInfo: VideoPlaylistCreate = req.body
152 const user: UserModel = res.locals.oauth.token.User
154 const videoPlaylist = new VideoPlaylistModel({
155 name: videoPlaylistInfo.displayName,
156 description: videoPlaylistInfo.description,
157 privacy: videoPlaylistInfo.privacy || VideoPlaylistPrivacy.PRIVATE,
158 ownerAccountId: user.Account.id
161 videoPlaylist.url = getVideoPlaylistActivityPubUrl(videoPlaylist) // We use the UUID, so set the URL after building the object
163 if (videoPlaylistInfo.videoChannelId) {
164 const videoChannel = res.locals.videoChannel as VideoChannelModel
166 videoPlaylist.videoChannelId = videoChannel.id
167 videoPlaylist.VideoChannel = videoChannel
170 const thumbnailField = req.files['thumbnailfile']
171 if (thumbnailField) {
172 const thumbnailPhysicalFile = thumbnailField[ 0 ]
173 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoPlaylist.getThumbnailName()), THUMBNAILS_SIZE)
176 const videoPlaylistCreated: VideoPlaylistModel = await sequelizeTypescript.transaction(async t => {
177 const videoPlaylistCreated = await videoPlaylist.save({ transaction: t })
179 // We need more attributes for the federation
180 videoPlaylistCreated.OwnerAccount = await AccountModel.load(user.Account.id, t)
181 await sendCreateVideoPlaylist(videoPlaylistCreated, t)
183 return videoPlaylistCreated
186 logger.info('Video playlist with uuid %s created.', videoPlaylist.uuid)
190 id: videoPlaylistCreated.id,
191 uuid: videoPlaylistCreated.uuid
196 async function updateVideoPlaylist (req: express.Request, res: express.Response) {
197 const videoPlaylistInstance = res.locals.videoPlaylist as VideoPlaylistModel
198 const videoPlaylistFieldsSave = videoPlaylistInstance.toJSON()
199 const videoPlaylistInfoToUpdate = req.body as VideoPlaylistUpdate
200 const wasPrivatePlaylist = videoPlaylistInstance.privacy === VideoPlaylistPrivacy.PRIVATE
202 const thumbnailField = req.files['thumbnailfile']
203 if (thumbnailField) {
204 const thumbnailPhysicalFile = thumbnailField[ 0 ]
206 thumbnailPhysicalFile,
207 join(CONFIG.STORAGE.THUMBNAILS_DIR, videoPlaylistInstance.getThumbnailName()),
213 await sequelizeTypescript.transaction(async t => {
214 const sequelizeOptions = {
218 if (videoPlaylistInfoToUpdate.videoChannelId !== undefined) {
219 if (videoPlaylistInfoToUpdate.videoChannelId === null) {
220 videoPlaylistInstance.videoChannelId = null
222 const videoChannel = res.locals.videoChannel as VideoChannelModel
224 videoPlaylistInstance.videoChannelId = videoChannel.id
225 videoPlaylistInstance.VideoChannel = videoChannel
229 if (videoPlaylistInfoToUpdate.displayName !== undefined) videoPlaylistInstance.name = videoPlaylistInfoToUpdate.displayName
230 if (videoPlaylistInfoToUpdate.description !== undefined) videoPlaylistInstance.description = videoPlaylistInfoToUpdate.description
232 if (videoPlaylistInfoToUpdate.privacy !== undefined) {
233 videoPlaylistInstance.privacy = parseInt(videoPlaylistInfoToUpdate.privacy.toString(), 10)
236 const playlistUpdated = await videoPlaylistInstance.save(sequelizeOptions)
238 const isNewPlaylist = wasPrivatePlaylist && playlistUpdated.privacy !== VideoPlaylistPrivacy.PRIVATE
241 await sendCreateVideoPlaylist(playlistUpdated, t)
243 await sendUpdateVideoPlaylist(playlistUpdated, t)
246 logger.info('Video playlist %s updated.', videoPlaylistInstance.uuid)
248 return playlistUpdated
251 logger.debug('Cannot update the video playlist.', { err })
253 // Force fields we want to update
254 // If the transaction is retried, sequelize will think the object has not changed
255 // So it will skip the SQL request, even if the last one was ROLLBACKed!
256 resetSequelizeInstance(videoPlaylistInstance, videoPlaylistFieldsSave)
261 return res.type('json').status(204).end()
264 async function removeVideoPlaylist (req: express.Request, res: express.Response) {
265 const videoPlaylistInstance: VideoPlaylistModel = res.locals.videoPlaylist
267 await sequelizeTypescript.transaction(async t => {
268 await videoPlaylistInstance.destroy({ transaction: t })
270 await sendDeleteVideoPlaylist(videoPlaylistInstance, t)
272 logger.info('Video playlist %s deleted.', videoPlaylistInstance.uuid)
275 return res.type('json').status(204).end()
278 async function addVideoInPlaylist (req: express.Request, res: express.Response) {
279 const body: VideoPlaylistElementCreate = req.body
280 const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
281 const video: VideoModel = res.locals.video
283 const playlistElement: VideoPlaylistElementModel = await sequelizeTypescript.transaction(async t => {
284 const position = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id, t)
286 const playlistElement = await VideoPlaylistElementModel.create({
287 url: getVideoPlaylistElementActivityPubUrl(videoPlaylist, video),
289 startTimestamp: body.startTimestamp || null,
290 stopTimestamp: body.stopTimestamp || null,
291 videoPlaylistId: videoPlaylist.id,
293 }, { transaction: t })
295 videoPlaylist.updatedAt = new Date()
296 await videoPlaylist.save({ transaction: t })
298 await sendUpdateVideoPlaylist(videoPlaylist, t)
300 return playlistElement
303 // If the user did not set a thumbnail, automatically take the video thumbnail
304 if (playlistElement.position === 1) {
305 const playlistThumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, videoPlaylist.getThumbnailName())
307 if (await pathExists(playlistThumbnailPath) === false) {
308 logger.info('Generating default thumbnail to playlist %s.', videoPlaylist.url)
310 const videoThumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName())
311 await copy(videoThumbnailPath, playlistThumbnailPath)
315 logger.info('Video added in playlist %s at position %d.', videoPlaylist.uuid, playlistElement.position)
318 videoPlaylistElement: {
319 id: playlistElement.id
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
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
333 const element = await videoPlaylistElement.save({ transaction: t })
335 videoPlaylist.updatedAt = new Date()
336 await videoPlaylist.save({ transaction: t })
338 await sendUpdateVideoPlaylist(videoPlaylist, t)
343 logger.info('Element of position %d of playlist %s updated.', playlistElement.position, videoPlaylist.uuid)
345 return res.type('json').status(204).end()
348 async function removeVideoFromPlaylist (req: express.Request, res: express.Response) {
349 const videoPlaylistElement: VideoPlaylistElementModel = res.locals.videoPlaylistElement
350 const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
351 const positionToDelete = videoPlaylistElement.position
353 await sequelizeTypescript.transaction(async t => {
354 await videoPlaylistElement.destroy({ transaction: t })
356 // Decrease position of the next elements
357 await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, positionToDelete, null, -1, t)
359 videoPlaylist.updatedAt = new Date()
360 await videoPlaylist.save({ transaction: t })
362 await sendUpdateVideoPlaylist(videoPlaylist, t)
364 logger.info('Video playlist element %d of playlist %s deleted.', videoPlaylistElement.position, videoPlaylist.uuid)
367 return res.type('json').status(204).end()
370 async function reorderVideosPlaylist (req: express.Request, res: express.Response) {
371 const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
372 const body: VideoPlaylistReorder = req.body
374 const start: number = body.startPosition
375 const insertAfter: number = body.insertAfterPosition
376 const reorderLength: number = body.reorderLength || 1
378 if (start === insertAfter) {
379 return res.status(204).end()
382 // Example: if we reorder position 2 and insert after position 5 (so at position 6): # 1 2 3 4 5 6 7 8 9
383 // * increase position when position > 5 # 1 2 3 4 5 7 8 9 10
384 // * update position 2 -> position 6 # 1 3 4 5 6 7 8 9 10
385 // * decrease position when position position > 2 # 1 2 3 4 5 6 7 8 9
386 await sequelizeTypescript.transaction(async t => {
387 const newPosition = insertAfter + 1
389 // Add space after the position when we want to insert our reordered elements (increase)
390 await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, newPosition, null, reorderLength, t)
392 let oldPosition = start
394 // We incremented the position of the elements we want to reorder
395 if (start >= newPosition) oldPosition += reorderLength
397 const endOldPosition = oldPosition + reorderLength - 1
398 // Insert our reordered elements in their place (update)
399 await VideoPlaylistElementModel.reassignPositionOf(videoPlaylist.id, oldPosition, endOldPosition, newPosition, t)
401 // Decrease positions of elements after the old position of our ordered elements (decrease)
402 await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, oldPosition, null, -reorderLength, t)
404 videoPlaylist.updatedAt = new Date()
405 await videoPlaylist.save({ transaction: t })
407 await sendUpdateVideoPlaylist(videoPlaylist, t)
411 'Reordered playlist %s (inserted after %d elements %d - %d).',
412 videoPlaylist.uuid, insertAfter, start, start + reorderLength - 1
415 return res.type('json').status(204).end()
418 async function getVideoPlaylistVideos (req: express.Request, res: express.Response) {
419 const videoPlaylistInstance: VideoPlaylistModel = res.locals.videoPlaylist
420 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
422 const resultList = await VideoModel.listForApi({
424 start: req.query.start,
425 count: req.query.count,
426 sort: 'VideoPlaylistElements.position',
427 includeLocalVideos: true,
428 categoryOneOf: req.query.categoryOneOf,
429 licenceOneOf: req.query.licenceOneOf,
430 languageOneOf: req.query.languageOneOf,
431 tagsOneOf: req.query.tagsOneOf,
432 tagsAllOf: req.query.tagsAllOf,
433 filter: req.query.filter,
434 nsfw: buildNSFWFilter(res, req.query.nsfw),
436 videoPlaylistId: videoPlaylistInstance.id,
437 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
440 const additionalAttributes = { playlistInfo: true }
441 return res.json(getFormattedObjects(resultList.data, resultList.total, { additionalAttributes }))