1 import * as express from 'express'
2 import { getFormattedObjects, getServerActor } from '../../helpers/utils'
5 asyncRetryTransactionMiddleware,
7 commonVideosFiltersValidator,
12 } from '../../middlewares'
13 import { videoPlaylistsSortValidator } from '../../middlewares/validators'
14 import { buildNSFWFilter, createReqFiles, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils'
15 import { CONFIG, MIMETYPES, sequelizeTypescript, THUMBNAILS_SIZE, VIDEO_PLAYLIST_PRIVACIES } from '../../initializers'
16 import { logger } from '../../helpers/logger'
17 import { resetSequelizeInstance } from '../../helpers/database-utils'
18 import { VideoPlaylistModel } from '../../models/video/video-playlist'
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'
44 const reqThumbnailFile = createReqFiles([ 'thumbnailfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { thumbnailfile: CONFIG.STORAGE.TMP_DIR })
46 const videoPlaylistRouter = express.Router()
48 videoPlaylistRouter.get('/privacies', listVideoPlaylistPrivacies)
50 videoPlaylistRouter.get('/',
52 videoPlaylistsSortValidator,
55 commonVideoPlaylistFiltersValidator,
56 asyncMiddleware(listVideoPlaylists)
59 videoPlaylistRouter.get('/:playlistId',
60 asyncMiddleware(videoPlaylistsGetValidator),
64 videoPlaylistRouter.post('/',
67 asyncMiddleware(videoPlaylistsAddValidator),
68 asyncRetryTransactionMiddleware(addVideoPlaylist)
71 videoPlaylistRouter.put('/:playlistId',
74 asyncMiddleware(videoPlaylistsUpdateValidator),
75 asyncRetryTransactionMiddleware(updateVideoPlaylist)
78 videoPlaylistRouter.delete('/:playlistId',
80 asyncMiddleware(videoPlaylistsDeleteValidator),
81 asyncRetryTransactionMiddleware(removeVideoPlaylist)
84 videoPlaylistRouter.get('/:playlistId/videos',
85 asyncMiddleware(videoPlaylistsGetValidator),
89 commonVideosFiltersValidator,
90 asyncMiddleware(getVideoPlaylistVideos)
93 videoPlaylistRouter.post('/:playlistId/videos',
95 asyncMiddleware(videoPlaylistsAddVideoValidator),
96 asyncRetryTransactionMiddleware(addVideoInPlaylist)
99 videoPlaylistRouter.post('/:playlistId/videos/reorder',
101 asyncMiddleware(videoPlaylistsReorderVideosValidator),
102 asyncRetryTransactionMiddleware(reorderVideosPlaylist)
105 videoPlaylistRouter.put('/:playlistId/videos/:videoId',
107 asyncMiddleware(videoPlaylistsUpdateOrRemoveVideoValidator),
108 asyncRetryTransactionMiddleware(updateVideoPlaylistElement)
111 videoPlaylistRouter.delete('/:playlistId/videos/:videoId',
113 asyncMiddleware(videoPlaylistsUpdateOrRemoveVideoValidator),
114 asyncRetryTransactionMiddleware(removeVideoFromPlaylist)
117 // ---------------------------------------------------------------------------
123 // ---------------------------------------------------------------------------
125 function listVideoPlaylistPrivacies (req: express.Request, res: express.Response) {
126 res.json(VIDEO_PLAYLIST_PRIVACIES)
129 async function listVideoPlaylists (req: express.Request, res: express.Response) {
130 const serverActor = await getServerActor()
131 const resultList = await VideoPlaylistModel.listForApi({
132 followerActorId: serverActor.id,
133 start: req.query.start,
134 count: req.query.count,
135 sort: req.query.sort,
139 return res.json(getFormattedObjects(resultList.data, resultList.total))
142 function getVideoPlaylist (req: express.Request, res: express.Response) {
143 const videoPlaylist = res.locals.videoPlaylist
145 return res.json(videoPlaylist.toFormattedJSON())
148 async function addVideoPlaylist (req: express.Request, res: express.Response) {
149 const videoPlaylistInfo: VideoPlaylistCreate = req.body
150 const user = res.locals.oauth.token.User
152 const videoPlaylist = new VideoPlaylistModel({
153 name: videoPlaylistInfo.displayName,
154 description: videoPlaylistInfo.description,
155 privacy: videoPlaylistInfo.privacy || VideoPlaylistPrivacy.PRIVATE,
156 ownerAccountId: user.Account.id
159 videoPlaylist.url = getVideoPlaylistActivityPubUrl(videoPlaylist) // We use the UUID, so set the URL after building the object
161 if (videoPlaylistInfo.videoChannelId) {
162 const videoChannel = res.locals.videoChannel
164 videoPlaylist.videoChannelId = videoChannel.id
165 videoPlaylist.VideoChannel = videoChannel
168 const thumbnailField = req.files['thumbnailfile']
169 if (thumbnailField) {
170 const thumbnailPhysicalFile = thumbnailField[ 0 ]
171 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoPlaylist.getThumbnailName()), THUMBNAILS_SIZE)
174 const videoPlaylistCreated: VideoPlaylistModel = await sequelizeTypescript.transaction(async t => {
175 const videoPlaylistCreated = await videoPlaylist.save({ transaction: t })
177 // We need more attributes for the federation
178 videoPlaylistCreated.OwnerAccount = await AccountModel.load(user.Account.id, t)
179 await sendCreateVideoPlaylist(videoPlaylistCreated, t)
181 return videoPlaylistCreated
184 logger.info('Video playlist with uuid %s created.', videoPlaylist.uuid)
188 id: videoPlaylistCreated.id,
189 uuid: videoPlaylistCreated.uuid
194 async function updateVideoPlaylist (req: express.Request, res: express.Response) {
195 const videoPlaylistInstance = res.locals.videoPlaylist
196 const videoPlaylistFieldsSave = videoPlaylistInstance.toJSON()
197 const videoPlaylistInfoToUpdate = req.body as VideoPlaylistUpdate
198 const wasPrivatePlaylist = videoPlaylistInstance.privacy === VideoPlaylistPrivacy.PRIVATE
200 const thumbnailField = req.files['thumbnailfile']
201 if (thumbnailField) {
202 const thumbnailPhysicalFile = thumbnailField[ 0 ]
204 thumbnailPhysicalFile,
205 join(CONFIG.STORAGE.THUMBNAILS_DIR, videoPlaylistInstance.getThumbnailName()),
211 await sequelizeTypescript.transaction(async t => {
212 const sequelizeOptions = {
216 if (videoPlaylistInfoToUpdate.videoChannelId !== undefined) {
217 if (videoPlaylistInfoToUpdate.videoChannelId === null) {
218 videoPlaylistInstance.videoChannelId = null
220 const videoChannel = res.locals.videoChannel
222 videoPlaylistInstance.videoChannelId = videoChannel.id
223 videoPlaylistInstance.VideoChannel = videoChannel
227 if (videoPlaylistInfoToUpdate.displayName !== undefined) videoPlaylistInstance.name = videoPlaylistInfoToUpdate.displayName
228 if (videoPlaylistInfoToUpdate.description !== undefined) videoPlaylistInstance.description = videoPlaylistInfoToUpdate.description
230 if (videoPlaylistInfoToUpdate.privacy !== undefined) {
231 videoPlaylistInstance.privacy = parseInt(videoPlaylistInfoToUpdate.privacy.toString(), 10)
234 const playlistUpdated = await videoPlaylistInstance.save(sequelizeOptions)
236 const isNewPlaylist = wasPrivatePlaylist && playlistUpdated.privacy !== VideoPlaylistPrivacy.PRIVATE
239 await sendCreateVideoPlaylist(playlistUpdated, t)
241 await sendUpdateVideoPlaylist(playlistUpdated, t)
244 logger.info('Video playlist %s updated.', videoPlaylistInstance.uuid)
246 return playlistUpdated
249 logger.debug('Cannot update the video playlist.', { err })
251 // Force fields we want to update
252 // If the transaction is retried, sequelize will think the object has not changed
253 // So it will skip the SQL request, even if the last one was ROLLBACKed!
254 resetSequelizeInstance(videoPlaylistInstance, videoPlaylistFieldsSave)
259 return res.type('json').status(204).end()
262 async function removeVideoPlaylist (req: express.Request, res: express.Response) {
263 const videoPlaylistInstance = res.locals.videoPlaylist
265 await sequelizeTypescript.transaction(async t => {
266 await videoPlaylistInstance.destroy({ transaction: t })
268 await sendDeleteVideoPlaylist(videoPlaylistInstance, t)
270 logger.info('Video playlist %s deleted.', videoPlaylistInstance.uuid)
273 return res.type('json').status(204).end()
276 async function addVideoInPlaylist (req: express.Request, res: express.Response) {
277 const body: VideoPlaylistElementCreate = req.body
278 const videoPlaylist = res.locals.videoPlaylist
279 const video = res.locals.video
281 const playlistElement: VideoPlaylistElementModel = await sequelizeTypescript.transaction(async t => {
282 const position = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id, t)
284 const playlistElement = await VideoPlaylistElementModel.create({
285 url: getVideoPlaylistElementActivityPubUrl(videoPlaylist, video),
287 startTimestamp: body.startTimestamp || null,
288 stopTimestamp: body.stopTimestamp || null,
289 videoPlaylistId: videoPlaylist.id,
291 }, { transaction: t })
293 videoPlaylist.changed('updatedAt', true)
294 await videoPlaylist.save({ transaction: t })
296 await sendUpdateVideoPlaylist(videoPlaylist, t)
298 return playlistElement
301 // If the user did not set a thumbnail, automatically take the video thumbnail
302 if (playlistElement.position === 1) {
303 const playlistThumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, videoPlaylist.getThumbnailName())
305 if (await pathExists(playlistThumbnailPath) === false) {
306 logger.info('Generating default thumbnail to playlist %s.', videoPlaylist.url)
308 const videoThumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName())
309 await copy(videoThumbnailPath, playlistThumbnailPath)
313 logger.info('Video added in playlist %s at position %d.', videoPlaylist.uuid, playlistElement.position)
316 videoPlaylistElement: {
317 id: playlistElement.id
322 async function updateVideoPlaylistElement (req: express.Request, res: express.Response) {
323 const body: VideoPlaylistElementUpdate = req.body
324 const videoPlaylist = res.locals.videoPlaylist
325 const videoPlaylistElement = res.locals.videoPlaylistElement
327 const playlistElement: VideoPlaylistElementModel = await sequelizeTypescript.transaction(async t => {
328 if (body.startTimestamp !== undefined) videoPlaylistElement.startTimestamp = body.startTimestamp
329 if (body.stopTimestamp !== undefined) videoPlaylistElement.stopTimestamp = body.stopTimestamp
331 const element = await videoPlaylistElement.save({ transaction: t })
333 videoPlaylist.changed('updatedAt', true)
334 await videoPlaylist.save({ transaction: t })
336 await sendUpdateVideoPlaylist(videoPlaylist, t)
341 logger.info('Element of position %d of playlist %s updated.', playlistElement.position, videoPlaylist.uuid)
343 return res.type('json').status(204).end()
346 async function removeVideoFromPlaylist (req: express.Request, res: express.Response) {
347 const videoPlaylistElement = res.locals.videoPlaylistElement
348 const videoPlaylist = res.locals.videoPlaylist
349 const positionToDelete = videoPlaylistElement.position
351 await sequelizeTypescript.transaction(async t => {
352 await videoPlaylistElement.destroy({ transaction: t })
354 // Decrease position of the next elements
355 await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, positionToDelete, null, -1, t)
357 videoPlaylist.changed('updatedAt', true)
358 await videoPlaylist.save({ transaction: t })
360 await sendUpdateVideoPlaylist(videoPlaylist, t)
362 logger.info('Video playlist element %d of playlist %s deleted.', videoPlaylistElement.position, videoPlaylist.uuid)
365 return res.type('json').status(204).end()
368 async function reorderVideosPlaylist (req: express.Request, res: express.Response) {
369 const videoPlaylist = res.locals.videoPlaylist
370 const body: VideoPlaylistReorder = req.body
372 const start: number = body.startPosition
373 const insertAfter: number = body.insertAfterPosition
374 const reorderLength: number = body.reorderLength || 1
376 if (start === insertAfter) {
377 return res.status(204).end()
380 // Example: if we reorder position 2 and insert after position 5 (so at position 6): # 1 2 3 4 5 6 7 8 9
381 // * increase position when position > 5 # 1 2 3 4 5 7 8 9 10
382 // * update position 2 -> position 6 # 1 3 4 5 6 7 8 9 10
383 // * decrease position when position position > 2 # 1 2 3 4 5 6 7 8 9
384 await sequelizeTypescript.transaction(async t => {
385 const newPosition = insertAfter + 1
387 // Add space after the position when we want to insert our reordered elements (increase)
388 await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, newPosition, null, reorderLength, t)
390 let oldPosition = start
392 // We incremented the position of the elements we want to reorder
393 if (start >= newPosition) oldPosition += reorderLength
395 const endOldPosition = oldPosition + reorderLength - 1
396 // Insert our reordered elements in their place (update)
397 await VideoPlaylistElementModel.reassignPositionOf(videoPlaylist.id, oldPosition, endOldPosition, newPosition, t)
399 // Decrease positions of elements after the old position of our ordered elements (decrease)
400 await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, oldPosition, null, -reorderLength, t)
402 videoPlaylist.changed('updatedAt', true)
403 await videoPlaylist.save({ transaction: t })
405 await sendUpdateVideoPlaylist(videoPlaylist, t)
409 'Reordered playlist %s (inserted after %d elements %d - %d).',
410 videoPlaylist.uuid, insertAfter, start, start + reorderLength - 1
413 return res.type('json').status(204).end()
416 async function getVideoPlaylistVideos (req: express.Request, res: express.Response) {
417 const videoPlaylistInstance = res.locals.videoPlaylist
418 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
420 const resultList = await VideoModel.listForApi({
422 start: req.query.start,
423 count: req.query.count,
424 sort: 'VideoPlaylistElements.position',
425 includeLocalVideos: true,
426 categoryOneOf: req.query.categoryOneOf,
427 licenceOneOf: req.query.licenceOneOf,
428 languageOneOf: req.query.languageOneOf,
429 tagsOneOf: req.query.tagsOneOf,
430 tagsAllOf: req.query.tagsAllOf,
431 filter: req.query.filter,
432 nsfw: buildNSFWFilter(res, req.query.nsfw),
434 videoPlaylistId: videoPlaylistInstance.id,
435 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
438 const additionalAttributes = { playlistInfo: true }
439 return res.json(getFormattedObjects(resultList.data, resultList.total, { additionalAttributes }))