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'
43 import { JobQueue } from '../../lib/job-queue'
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
146 if (videoPlaylist.isOutdated()) {
147 JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video-playlist', url: videoPlaylist.url } })
148 .catch(err => logger.error('Cannot create AP refresher job for playlist %s.', videoPlaylist.url, { err }))
151 return res.json(videoPlaylist.toFormattedJSON())
154 async function addVideoPlaylist (req: express.Request, res: express.Response) {
155 const videoPlaylistInfo: VideoPlaylistCreate = req.body
156 const user = res.locals.oauth.token.User
158 const videoPlaylist = new VideoPlaylistModel({
159 name: videoPlaylistInfo.displayName,
160 description: videoPlaylistInfo.description,
161 privacy: videoPlaylistInfo.privacy || VideoPlaylistPrivacy.PRIVATE,
162 ownerAccountId: user.Account.id
165 videoPlaylist.url = getVideoPlaylistActivityPubUrl(videoPlaylist) // We use the UUID, so set the URL after building the object
167 if (videoPlaylistInfo.videoChannelId) {
168 const videoChannel = res.locals.videoChannel
170 videoPlaylist.videoChannelId = videoChannel.id
171 videoPlaylist.VideoChannel = videoChannel
174 const thumbnailField = req.files['thumbnailfile']
175 if (thumbnailField) {
176 const thumbnailPhysicalFile = thumbnailField[ 0 ]
177 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoPlaylist.getThumbnailName()), THUMBNAILS_SIZE)
180 const videoPlaylistCreated: VideoPlaylistModel = await sequelizeTypescript.transaction(async t => {
181 const videoPlaylistCreated = await videoPlaylist.save({ transaction: t })
183 // We need more attributes for the federation
184 videoPlaylistCreated.OwnerAccount = await AccountModel.load(user.Account.id, t)
185 await sendCreateVideoPlaylist(videoPlaylistCreated, t)
187 return videoPlaylistCreated
190 logger.info('Video playlist with uuid %s created.', videoPlaylist.uuid)
194 id: videoPlaylistCreated.id,
195 uuid: videoPlaylistCreated.uuid
200 async function updateVideoPlaylist (req: express.Request, res: express.Response) {
201 const videoPlaylistInstance = res.locals.videoPlaylist
202 const videoPlaylistFieldsSave = videoPlaylistInstance.toJSON()
203 const videoPlaylistInfoToUpdate = req.body as VideoPlaylistUpdate
204 const wasPrivatePlaylist = videoPlaylistInstance.privacy === VideoPlaylistPrivacy.PRIVATE
206 const thumbnailField = req.files['thumbnailfile']
207 if (thumbnailField) {
208 const thumbnailPhysicalFile = thumbnailField[ 0 ]
210 thumbnailPhysicalFile,
211 join(CONFIG.STORAGE.THUMBNAILS_DIR, videoPlaylistInstance.getThumbnailName()),
217 await sequelizeTypescript.transaction(async t => {
218 const sequelizeOptions = {
222 if (videoPlaylistInfoToUpdate.videoChannelId !== undefined) {
223 if (videoPlaylistInfoToUpdate.videoChannelId === null) {
224 videoPlaylistInstance.videoChannelId = null
226 const videoChannel = res.locals.videoChannel
228 videoPlaylistInstance.videoChannelId = videoChannel.id
229 videoPlaylistInstance.VideoChannel = videoChannel
233 if (videoPlaylistInfoToUpdate.displayName !== undefined) videoPlaylistInstance.name = videoPlaylistInfoToUpdate.displayName
234 if (videoPlaylistInfoToUpdate.description !== undefined) videoPlaylistInstance.description = videoPlaylistInfoToUpdate.description
236 if (videoPlaylistInfoToUpdate.privacy !== undefined) {
237 videoPlaylistInstance.privacy = parseInt(videoPlaylistInfoToUpdate.privacy.toString(), 10)
240 const playlistUpdated = await videoPlaylistInstance.save(sequelizeOptions)
242 const isNewPlaylist = wasPrivatePlaylist && playlistUpdated.privacy !== VideoPlaylistPrivacy.PRIVATE
245 await sendCreateVideoPlaylist(playlistUpdated, t)
247 await sendUpdateVideoPlaylist(playlistUpdated, t)
250 logger.info('Video playlist %s updated.', videoPlaylistInstance.uuid)
252 return playlistUpdated
255 logger.debug('Cannot update the video playlist.', { err })
257 // Force fields we want to update
258 // If the transaction is retried, sequelize will think the object has not changed
259 // So it will skip the SQL request, even if the last one was ROLLBACKed!
260 resetSequelizeInstance(videoPlaylistInstance, videoPlaylistFieldsSave)
265 return res.type('json').status(204).end()
268 async function removeVideoPlaylist (req: express.Request, res: express.Response) {
269 const videoPlaylistInstance = res.locals.videoPlaylist
271 await sequelizeTypescript.transaction(async t => {
272 await videoPlaylistInstance.destroy({ transaction: t })
274 await sendDeleteVideoPlaylist(videoPlaylistInstance, t)
276 logger.info('Video playlist %s deleted.', videoPlaylistInstance.uuid)
279 return res.type('json').status(204).end()
282 async function addVideoInPlaylist (req: express.Request, res: express.Response) {
283 const body: VideoPlaylistElementCreate = req.body
284 const videoPlaylist = res.locals.videoPlaylist
285 const video = res.locals.video
287 const playlistElement: VideoPlaylistElementModel = await sequelizeTypescript.transaction(async t => {
288 const position = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id, t)
290 const playlistElement = await VideoPlaylistElementModel.create({
291 url: getVideoPlaylistElementActivityPubUrl(videoPlaylist, video),
293 startTimestamp: body.startTimestamp || null,
294 stopTimestamp: body.stopTimestamp || null,
295 videoPlaylistId: videoPlaylist.id,
297 }, { transaction: t })
299 videoPlaylist.changed('updatedAt', true)
300 await videoPlaylist.save({ transaction: t })
302 await sendUpdateVideoPlaylist(videoPlaylist, t)
304 return playlistElement
307 // If the user did not set a thumbnail, automatically take the video thumbnail
308 if (playlistElement.position === 1) {
309 const playlistThumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, videoPlaylist.getThumbnailName())
311 if (await pathExists(playlistThumbnailPath) === false) {
312 logger.info('Generating default thumbnail to playlist %s.', videoPlaylist.url)
314 const videoThumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName())
315 await copy(videoThumbnailPath, playlistThumbnailPath)
319 logger.info('Video added in playlist %s at position %d.', videoPlaylist.uuid, playlistElement.position)
322 videoPlaylistElement: {
323 id: playlistElement.id
328 async function updateVideoPlaylistElement (req: express.Request, res: express.Response) {
329 const body: VideoPlaylistElementUpdate = req.body
330 const videoPlaylist = res.locals.videoPlaylist
331 const videoPlaylistElement = res.locals.videoPlaylistElement
333 const playlistElement: VideoPlaylistElementModel = await sequelizeTypescript.transaction(async t => {
334 if (body.startTimestamp !== undefined) videoPlaylistElement.startTimestamp = body.startTimestamp
335 if (body.stopTimestamp !== undefined) videoPlaylistElement.stopTimestamp = body.stopTimestamp
337 const element = await videoPlaylistElement.save({ transaction: t })
339 videoPlaylist.changed('updatedAt', true)
340 await videoPlaylist.save({ transaction: t })
342 await sendUpdateVideoPlaylist(videoPlaylist, t)
347 logger.info('Element of position %d of playlist %s updated.', playlistElement.position, videoPlaylist.uuid)
349 return res.type('json').status(204).end()
352 async function removeVideoFromPlaylist (req: express.Request, res: express.Response) {
353 const videoPlaylistElement = res.locals.videoPlaylistElement
354 const videoPlaylist = res.locals.videoPlaylist
355 const positionToDelete = videoPlaylistElement.position
357 await sequelizeTypescript.transaction(async t => {
358 await videoPlaylistElement.destroy({ transaction: t })
360 // Decrease position of the next elements
361 await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, positionToDelete, null, -1, t)
363 videoPlaylist.changed('updatedAt', true)
364 await videoPlaylist.save({ transaction: t })
366 await sendUpdateVideoPlaylist(videoPlaylist, t)
368 logger.info('Video playlist element %d of playlist %s deleted.', videoPlaylistElement.position, videoPlaylist.uuid)
371 return res.type('json').status(204).end()
374 async function reorderVideosPlaylist (req: express.Request, res: express.Response) {
375 const videoPlaylist = res.locals.videoPlaylist
376 const body: VideoPlaylistReorder = req.body
378 const start: number = body.startPosition
379 const insertAfter: number = body.insertAfterPosition
380 const reorderLength: number = body.reorderLength || 1
382 if (start === insertAfter) {
383 return res.status(204).end()
386 // Example: if we reorder position 2 and insert after position 5 (so at position 6): # 1 2 3 4 5 6 7 8 9
387 // * increase position when position > 5 # 1 2 3 4 5 7 8 9 10
388 // * update position 2 -> position 6 # 1 3 4 5 6 7 8 9 10
389 // * decrease position when position position > 2 # 1 2 3 4 5 6 7 8 9
390 await sequelizeTypescript.transaction(async t => {
391 const newPosition = insertAfter + 1
393 // Add space after the position when we want to insert our reordered elements (increase)
394 await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, newPosition, null, reorderLength, t)
396 let oldPosition = start
398 // We incremented the position of the elements we want to reorder
399 if (start >= newPosition) oldPosition += reorderLength
401 const endOldPosition = oldPosition + reorderLength - 1
402 // Insert our reordered elements in their place (update)
403 await VideoPlaylistElementModel.reassignPositionOf(videoPlaylist.id, oldPosition, endOldPosition, newPosition, t)
405 // Decrease positions of elements after the old position of our ordered elements (decrease)
406 await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, oldPosition, null, -reorderLength, t)
408 videoPlaylist.changed('updatedAt', true)
409 await videoPlaylist.save({ transaction: t })
411 await sendUpdateVideoPlaylist(videoPlaylist, t)
415 'Reordered playlist %s (inserted after %d elements %d - %d).',
416 videoPlaylist.uuid, insertAfter, start, start + reorderLength - 1
419 return res.type('json').status(204).end()
422 async function getVideoPlaylistVideos (req: express.Request, res: express.Response) {
423 const videoPlaylistInstance = res.locals.videoPlaylist
424 const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
426 const resultList = await VideoModel.listForApi({
428 start: req.query.start,
429 count: req.query.count,
430 sort: 'VideoPlaylistElements.position',
431 includeLocalVideos: true,
432 categoryOneOf: req.query.categoryOneOf,
433 licenceOneOf: req.query.licenceOneOf,
434 languageOneOf: req.query.languageOneOf,
435 tagsOneOf: req.query.tagsOneOf,
436 tagsAllOf: req.query.tagsAllOf,
437 filter: req.query.filter,
438 nsfw: buildNSFWFilter(res, req.query.nsfw),
440 videoPlaylistId: videoPlaylistInstance.id,
441 user: res.locals.oauth ? res.locals.oauth.token.User : undefined
444 const additionalAttributes = { playlistInfo: true }
445 return res.json(getFormattedObjects(resultList.data, resultList.total, { additionalAttributes }))