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'
45 const reqThumbnailFile = createReqFiles([ 'thumbnailfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { thumbnailfile: CONFIG.STORAGE.TMP_DIR })
47 const videoPlaylistRouter = express.Router()
49 videoPlaylistRouter.get('/privacies', listVideoPlaylistPrivacies)
51 videoPlaylistRouter.get('/',
53 videoPlaylistsSortValidator,
56 commonVideoPlaylistFiltersValidator,
57 asyncMiddleware(listVideoPlaylists)
60 videoPlaylistRouter.get('/:playlistId',
61 asyncMiddleware(videoPlaylistsGetValidator),
65 videoPlaylistRouter.post('/',
68 asyncMiddleware(videoPlaylistsAddValidator),
69 asyncRetryTransactionMiddleware(addVideoPlaylist)
72 videoPlaylistRouter.put('/:playlistId',
75 asyncMiddleware(videoPlaylistsUpdateValidator),
76 asyncRetryTransactionMiddleware(updateVideoPlaylist)
79 videoPlaylistRouter.delete('/:playlistId',
81 asyncMiddleware(videoPlaylistsDeleteValidator),
82 asyncRetryTransactionMiddleware(removeVideoPlaylist)
85 videoPlaylistRouter.get('/:playlistId/videos',
86 asyncMiddleware(videoPlaylistsGetValidator),
90 commonVideosFiltersValidator,
91 asyncMiddleware(getVideoPlaylistVideos)
94 videoPlaylistRouter.post('/:playlistId/videos',
96 asyncMiddleware(videoPlaylistsAddVideoValidator),
97 asyncRetryTransactionMiddleware(addVideoInPlaylist)
100 videoPlaylistRouter.post('/:playlistId/videos/reorder',
102 asyncMiddleware(videoPlaylistsReorderVideosValidator),
103 asyncRetryTransactionMiddleware(reorderVideosPlaylist)
106 videoPlaylistRouter.put('/:playlistId/videos/:videoId',
108 asyncMiddleware(videoPlaylistsUpdateOrRemoveVideoValidator),
109 asyncRetryTransactionMiddleware(updateVideoPlaylistElement)
112 videoPlaylistRouter.delete('/:playlistId/videos/:videoId',
114 asyncMiddleware(videoPlaylistsUpdateOrRemoveVideoValidator),
115 asyncRetryTransactionMiddleware(removeVideoFromPlaylist)
118 // ---------------------------------------------------------------------------
124 // ---------------------------------------------------------------------------
126 function listVideoPlaylistPrivacies (req: express.Request, res: express.Response) {
127 res.json(VIDEO_PLAYLIST_PRIVACIES)
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,
140 return res.json(getFormattedObjects(resultList.data, resultList.total))
143 function getVideoPlaylist (req: express.Request, res: express.Response) {
144 const videoPlaylist = res.locals.videoPlaylist as VideoPlaylistModel
146 return res.json(videoPlaylist.toFormattedJSON())
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
153 const videoPlaylist = new VideoPlaylistModel({
154 name: videoPlaylistInfo.displayName,
155 description: videoPlaylistInfo.description,
156 privacy: videoPlaylistInfo.privacy || VideoPlaylistPrivacy.PRIVATE,
157 ownerAccountId: user.Account.id
160 videoPlaylist.url = getVideoPlaylistActivityPubUrl(videoPlaylist) // We use the UUID, so set the URL after building the object
162 if (videoPlaylistInfo.videoChannelId) {
163 const videoChannel = res.locals.videoChannel as VideoChannelModel
165 videoPlaylist.videoChannelId = videoChannel.id
166 videoPlaylist.VideoChannel = videoChannel
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)
175 const videoPlaylistCreated: VideoPlaylistModel = await sequelizeTypescript.transaction(async t => {
176 const videoPlaylistCreated = await videoPlaylist.save({ transaction: t })
178 // We need more attributes for the federation
179 videoPlaylistCreated.OwnerAccount = await AccountModel.load(user.Account.id, t)
180 await sendCreateVideoPlaylist(videoPlaylistCreated, t)
182 return videoPlaylistCreated
185 logger.info('Video playlist with uuid %s created.', videoPlaylist.uuid)
189 id: videoPlaylistCreated.id,
190 uuid: videoPlaylistCreated.uuid
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
201 const thumbnailField = req.files['thumbnailfile']
202 if (thumbnailField) {
203 const thumbnailPhysicalFile = thumbnailField[ 0 ]
205 thumbnailPhysicalFile,
206 join(CONFIG.STORAGE.THUMBNAILS_DIR, videoPlaylistInstance.getThumbnailName()),
212 await sequelizeTypescript.transaction(async t => {
213 const sequelizeOptions = {
217 if (videoPlaylistInfoToUpdate.videoChannelId !== undefined) {
218 if (videoPlaylistInfoToUpdate.videoChannelId === null) {
219 videoPlaylistInstance.videoChannelId = null
221 const videoChannel = res.locals.videoChannel as VideoChannelModel
223 videoPlaylistInstance.videoChannelId = videoChannel.id
224 videoPlaylistInstance.VideoChannel = videoChannel
228 if (videoPlaylistInfoToUpdate.displayName !== undefined) videoPlaylistInstance.name = videoPlaylistInfoToUpdate.displayName
229 if (videoPlaylistInfoToUpdate.description !== undefined) videoPlaylistInstance.description = videoPlaylistInfoToUpdate.description
231 if (videoPlaylistInfoToUpdate.privacy !== undefined) {
232 videoPlaylistInstance.privacy = parseInt(videoPlaylistInfoToUpdate.privacy.toString(), 10)
235 const playlistUpdated = await videoPlaylistInstance.save(sequelizeOptions)
237 const isNewPlaylist = wasPrivatePlaylist && playlistUpdated.privacy !== VideoPlaylistPrivacy.PRIVATE
240 await sendCreateVideoPlaylist(playlistUpdated, t)
242 await sendUpdateVideoPlaylist(playlistUpdated, t)
245 logger.info('Video playlist %s updated.', videoPlaylistInstance.uuid)
247 return playlistUpdated
250 logger.debug('Cannot update the video playlist.', { err })
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)
260 return res.type('json').status(204).end()
263 async function removeVideoPlaylist (req: express.Request, res: express.Response) {
264 const videoPlaylistInstance: VideoPlaylistModel = res.locals.videoPlaylist
266 await sequelizeTypescript.transaction(async t => {
267 await videoPlaylistInstance.destroy({ transaction: t })
269 await sendDeleteVideoPlaylist(videoPlaylistInstance, t)
271 logger.info('Video playlist %s deleted.', videoPlaylistInstance.uuid)
274 return res.type('json').status(204).end()
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
282 const playlistElement: VideoPlaylistElementModel = await sequelizeTypescript.transaction(async t => {
283 const position = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id, t)
285 const playlistElement = await VideoPlaylistElementModel.create({
286 url: getVideoPlaylistElementActivityPubUrl(videoPlaylist, video),
288 startTimestamp: body.startTimestamp || null,
289 stopTimestamp: body.stopTimestamp || null,
290 videoPlaylistId: videoPlaylist.id,
292 }, { transaction: t })
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())
298 if (await pathExists(playlistThumbnailPath) === false) {
299 logger.info('Generating default thumbnail to playlist %s.', videoPlaylist.url)
301 const videoThumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName())
302 await copy(videoThumbnailPath, playlistThumbnailPath)
306 await sendUpdateVideoPlaylist(videoPlaylist, t)
308 return playlistElement
311 logger.info('Video added in playlist %s at position %d.', videoPlaylist.uuid, playlistElement.position)
314 videoPlaylistElement: {
315 id: playlistElement.id
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
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
329 const element = await videoPlaylistElement.save({ transaction: t })
331 await sendUpdateVideoPlaylist(videoPlaylist, t)
336 logger.info('Element of position %d of playlist %s updated.', playlistElement.position, videoPlaylist.uuid)
338 return res.type('json').status(204).end()
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
346 await sequelizeTypescript.transaction(async t => {
347 await videoPlaylistElement.destroy({ transaction: t })
349 // Decrease position of the next elements
350 await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, positionToDelete, null, -1, t)
352 await sendUpdateVideoPlaylist(videoPlaylist, t)
354 logger.info('Video playlist element %d of playlist %s deleted.', videoPlaylistElement.position, videoPlaylist.uuid)
357 return res.type('json').status(204).end()
360 async function reorderVideosPlaylist (req: express.Request, res: express.Response) {
361 const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
363 const start: number = req.body.startPosition
364 const insertAfter: number = req.body.insertAfterPosition
365 const reorderLength: number = req.body.reorderLength || 1
367 if (start === insertAfter) {
368 return res.status(204).end()
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
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)
381 let oldPosition = start
383 // We incremented the position of the elements we want to reorder
384 if (start >= newPosition) oldPosition += reorderLength
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)
390 // Decrease positions of elements after the old position of our ordered elements (decrease)
391 await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, oldPosition, null, -reorderLength, t)
393 await sendUpdateVideoPlaylist(videoPlaylist, t)
397 'Reordered playlist %s (inserted after %d elements %d - %d).',
398 videoPlaylist.uuid, insertAfter, start, start + reorderLength - 1
401 return res.type('json').status(204).end()
404 async function getVideoPlaylistVideos (req: express.Request, res: express.Response) {
405 const videoPlaylistInstance: VideoPlaylistModel = res.locals.videoPlaylist
406 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
408 const resultList = await VideoModel.listForApi({
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),
422 videoPlaylistId: videoPlaylistInstance.id,
423 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
426 const additionalAttributes = { playlistInfo: true }
427 return res.json(getFormattedObjects(resultList.data, resultList.total, { additionalAttributes }))