]>
Commit | Line | Data |
---|---|---|
1 | import * as express from 'express' | |
2 | import { getFormattedObjects, getServerActor } from '../../helpers/utils' | |
3 | import { | |
4 | asyncMiddleware, | |
5 | asyncRetryTransactionMiddleware, | |
6 | authenticate, | |
7 | optionalAuthenticate, | |
8 | paginationValidator, | |
9 | setDefaultPagination, | |
10 | setDefaultSort | |
11 | } from '../../middlewares' | |
12 | import { videoPlaylistsSortValidator } from '../../middlewares/validators' | |
13 | import { buildNSFWFilter, createReqFiles } from '../../helpers/express-utils' | |
14 | import { MIMETYPES, VIDEO_PLAYLIST_PRIVACIES } from '../../initializers/constants' | |
15 | import { logger } from '../../helpers/logger' | |
16 | import { resetSequelizeInstance } from '../../helpers/database-utils' | |
17 | import { VideoPlaylistModel } from '../../models/video/video-playlist' | |
18 | import { | |
19 | commonVideoPlaylistFiltersValidator, | |
20 | videoPlaylistsAddValidator, | |
21 | videoPlaylistsAddVideoValidator, | |
22 | videoPlaylistsDeleteValidator, | |
23 | videoPlaylistsGetValidator, | |
24 | videoPlaylistsReorderVideosValidator, | |
25 | videoPlaylistsUpdateOrRemoveVideoValidator, | |
26 | videoPlaylistsUpdateValidator | |
27 | } from '../../middlewares/validators/videos/video-playlists' | |
28 | import { VideoPlaylistCreate } from '../../../shared/models/videos/playlist/video-playlist-create.model' | |
29 | import { VideoPlaylistPrivacy } from '../../../shared/models/videos/playlist/video-playlist-privacy.model' | |
30 | import { join } from 'path' | |
31 | import { sendCreateVideoPlaylist, sendDeleteVideoPlaylist, sendUpdateVideoPlaylist } from '../../lib/activitypub/send' | |
32 | import { getVideoPlaylistActivityPubUrl, getVideoPlaylistElementActivityPubUrl } from '../../lib/activitypub/url' | |
33 | import { VideoPlaylistUpdate } from '../../../shared/models/videos/playlist/video-playlist-update.model' | |
34 | import { VideoPlaylistElementModel } from '../../models/video/video-playlist-element' | |
35 | import { VideoPlaylistElementCreate } from '../../../shared/models/videos/playlist/video-playlist-element-create.model' | |
36 | import { VideoPlaylistElementUpdate } from '../../../shared/models/videos/playlist/video-playlist-element-update.model' | |
37 | import { AccountModel } from '../../models/account/account' | |
38 | import { VideoPlaylistReorder } from '../../../shared/models/videos/playlist/video-playlist-reorder.model' | |
39 | import { JobQueue } from '../../lib/job-queue' | |
40 | import { CONFIG } from '../../initializers/config' | |
41 | import { sequelizeTypescript } from '../../initializers/database' | |
42 | import { createPlaylistMiniatureFromExisting } from '../../lib/thumbnail' | |
43 | import { MVideoPlaylistFull, MVideoPlaylistThumbnail, MVideoThumbnail } from '@server/typings/models' | |
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('summary')), | |
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('summary')), | |
87 | paginationValidator, | |
88 | setDefaultPagination, | |
89 | optionalAuthenticate, | |
90 | asyncMiddleware(getVideoPlaylistVideos) | |
91 | ) | |
92 | ||
93 | videoPlaylistRouter.post('/:playlistId/videos', | |
94 | authenticate, | |
95 | asyncMiddleware(videoPlaylistsAddVideoValidator), | |
96 | asyncRetryTransactionMiddleware(addVideoInPlaylist) | |
97 | ) | |
98 | ||
99 | videoPlaylistRouter.post('/:playlistId/videos/reorder', | |
100 | authenticate, | |
101 | asyncMiddleware(videoPlaylistsReorderVideosValidator), | |
102 | asyncRetryTransactionMiddleware(reorderVideosPlaylist) | |
103 | ) | |
104 | ||
105 | videoPlaylistRouter.put('/:playlistId/videos/:playlistElementId', | |
106 | authenticate, | |
107 | asyncMiddleware(videoPlaylistsUpdateOrRemoveVideoValidator), | |
108 | asyncRetryTransactionMiddleware(updateVideoPlaylistElement) | |
109 | ) | |
110 | ||
111 | videoPlaylistRouter.delete('/:playlistId/videos/:playlistElementId', | |
112 | authenticate, | |
113 | asyncMiddleware(videoPlaylistsUpdateOrRemoveVideoValidator), | |
114 | asyncRetryTransactionMiddleware(removeVideoFromPlaylist) | |
115 | ) | |
116 | ||
117 | // --------------------------------------------------------------------------- | |
118 | ||
119 | export { | |
120 | videoPlaylistRouter | |
121 | } | |
122 | ||
123 | // --------------------------------------------------------------------------- | |
124 | ||
125 | function listVideoPlaylistPrivacies (req: express.Request, res: express.Response) { | |
126 | res.json(VIDEO_PLAYLIST_PRIVACIES) | |
127 | } | |
128 | ||
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, | |
136 | type: req.query.type | |
137 | }) | |
138 | ||
139 | return res.json(getFormattedObjects(resultList.data, resultList.total)) | |
140 | } | |
141 | ||
142 | function getVideoPlaylist (req: express.Request, res: express.Response) { | |
143 | const videoPlaylist = res.locals.videoPlaylistSummary | |
144 | ||
145 | if (videoPlaylist.isOutdated()) { | |
146 | JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video-playlist', url: videoPlaylist.url } }) | |
147 | } | |
148 | ||
149 | return res.json(videoPlaylist.toFormattedJSON()) | |
150 | } | |
151 | ||
152 | async function addVideoPlaylist (req: express.Request, res: express.Response) { | |
153 | const videoPlaylistInfo: VideoPlaylistCreate = req.body | |
154 | const user = res.locals.oauth.token.User | |
155 | ||
156 | const videoPlaylist = new VideoPlaylistModel({ | |
157 | name: videoPlaylistInfo.displayName, | |
158 | description: videoPlaylistInfo.description, | |
159 | privacy: videoPlaylistInfo.privacy || VideoPlaylistPrivacy.PRIVATE, | |
160 | ownerAccountId: user.Account.id | |
161 | }) as MVideoPlaylistFull | |
162 | ||
163 | videoPlaylist.url = getVideoPlaylistActivityPubUrl(videoPlaylist) // We use the UUID, so set the URL after building the object | |
164 | ||
165 | if (videoPlaylistInfo.videoChannelId) { | |
166 | const videoChannel = res.locals.videoChannel | |
167 | ||
168 | videoPlaylist.videoChannelId = videoChannel.id | |
169 | videoPlaylist.VideoChannel = videoChannel | |
170 | } | |
171 | ||
172 | const thumbnailField = req.files['thumbnailfile'] | |
173 | const thumbnailModel = thumbnailField | |
174 | ? await createPlaylistMiniatureFromExisting(thumbnailField[0].path, videoPlaylist, false) | |
175 | : undefined | |
176 | ||
177 | const videoPlaylistCreated = await sequelizeTypescript.transaction(async t => { | |
178 | const videoPlaylistCreated = await videoPlaylist.save({ transaction: t }) as MVideoPlaylistFull | |
179 | ||
180 | if (thumbnailModel) { | |
181 | thumbnailModel.automaticallyGenerated = false | |
182 | await videoPlaylistCreated.setAndSaveThumbnail(thumbnailModel, t) | |
183 | } | |
184 | ||
185 | // We need more attributes for the federation | |
186 | videoPlaylistCreated.OwnerAccount = await AccountModel.load(user.Account.id, t) | |
187 | await sendCreateVideoPlaylist(videoPlaylistCreated, t) | |
188 | ||
189 | return videoPlaylistCreated | |
190 | }) | |
191 | ||
192 | logger.info('Video playlist with uuid %s created.', videoPlaylist.uuid) | |
193 | ||
194 | return res.json({ | |
195 | videoPlaylist: { | |
196 | id: videoPlaylistCreated.id, | |
197 | uuid: videoPlaylistCreated.uuid | |
198 | } | |
199 | }).end() | |
200 | } | |
201 | ||
202 | async function updateVideoPlaylist (req: express.Request, res: express.Response) { | |
203 | const videoPlaylistInstance = res.locals.videoPlaylistFull | |
204 | const videoPlaylistFieldsSave = videoPlaylistInstance.toJSON() | |
205 | const videoPlaylistInfoToUpdate = req.body as VideoPlaylistUpdate | |
206 | ||
207 | const wasPrivatePlaylist = videoPlaylistInstance.privacy === VideoPlaylistPrivacy.PRIVATE | |
208 | const wasNotPrivatePlaylist = videoPlaylistInstance.privacy !== VideoPlaylistPrivacy.PRIVATE | |
209 | ||
210 | const thumbnailField = req.files['thumbnailfile'] | |
211 | const thumbnailModel = thumbnailField | |
212 | ? await createPlaylistMiniatureFromExisting(thumbnailField[0].path, videoPlaylistInstance, false) | |
213 | : undefined | |
214 | ||
215 | try { | |
216 | await sequelizeTypescript.transaction(async t => { | |
217 | const sequelizeOptions = { | |
218 | transaction: t | |
219 | } | |
220 | ||
221 | if (videoPlaylistInfoToUpdate.videoChannelId !== undefined) { | |
222 | if (videoPlaylistInfoToUpdate.videoChannelId === null) { | |
223 | videoPlaylistInstance.videoChannelId = null | |
224 | } else { | |
225 | const videoChannel = res.locals.videoChannel | |
226 | ||
227 | videoPlaylistInstance.videoChannelId = videoChannel.id | |
228 | videoPlaylistInstance.VideoChannel = videoChannel | |
229 | } | |
230 | } | |
231 | ||
232 | if (videoPlaylistInfoToUpdate.displayName !== undefined) videoPlaylistInstance.name = videoPlaylistInfoToUpdate.displayName | |
233 | if (videoPlaylistInfoToUpdate.description !== undefined) videoPlaylistInstance.description = videoPlaylistInfoToUpdate.description | |
234 | ||
235 | if (videoPlaylistInfoToUpdate.privacy !== undefined) { | |
236 | videoPlaylistInstance.privacy = parseInt(videoPlaylistInfoToUpdate.privacy.toString(), 10) | |
237 | ||
238 | if (wasNotPrivatePlaylist === true && videoPlaylistInstance.privacy === VideoPlaylistPrivacy.PRIVATE) { | |
239 | await sendDeleteVideoPlaylist(videoPlaylistInstance, t) | |
240 | } | |
241 | } | |
242 | ||
243 | const playlistUpdated = await videoPlaylistInstance.save(sequelizeOptions) | |
244 | ||
245 | if (thumbnailModel) { | |
246 | thumbnailModel.automaticallyGenerated = false | |
247 | await playlistUpdated.setAndSaveThumbnail(thumbnailModel, t) | |
248 | } | |
249 | ||
250 | const isNewPlaylist = wasPrivatePlaylist && playlistUpdated.privacy !== VideoPlaylistPrivacy.PRIVATE | |
251 | ||
252 | if (isNewPlaylist) { | |
253 | await sendCreateVideoPlaylist(playlistUpdated, t) | |
254 | } else { | |
255 | await sendUpdateVideoPlaylist(playlistUpdated, t) | |
256 | } | |
257 | ||
258 | logger.info('Video playlist %s updated.', videoPlaylistInstance.uuid) | |
259 | ||
260 | return playlistUpdated | |
261 | }) | |
262 | } catch (err) { | |
263 | logger.debug('Cannot update the video playlist.', { err }) | |
264 | ||
265 | // Force fields we want to update | |
266 | // If the transaction is retried, sequelize will think the object has not changed | |
267 | // So it will skip the SQL request, even if the last one was ROLLBACKed! | |
268 | resetSequelizeInstance(videoPlaylistInstance, videoPlaylistFieldsSave) | |
269 | ||
270 | throw err | |
271 | } | |
272 | ||
273 | return res.type('json').status(204).end() | |
274 | } | |
275 | ||
276 | async function removeVideoPlaylist (req: express.Request, res: express.Response) { | |
277 | const videoPlaylistInstance = res.locals.videoPlaylistSummary | |
278 | ||
279 | await sequelizeTypescript.transaction(async t => { | |
280 | await videoPlaylistInstance.destroy({ transaction: t }) | |
281 | ||
282 | await sendDeleteVideoPlaylist(videoPlaylistInstance, t) | |
283 | ||
284 | logger.info('Video playlist %s deleted.', videoPlaylistInstance.uuid) | |
285 | }) | |
286 | ||
287 | return res.type('json').status(204).end() | |
288 | } | |
289 | ||
290 | async function addVideoInPlaylist (req: express.Request, res: express.Response) { | |
291 | const body: VideoPlaylistElementCreate = req.body | |
292 | const videoPlaylist = res.locals.videoPlaylistFull | |
293 | const video = res.locals.onlyVideo | |
294 | ||
295 | const playlistElement = await sequelizeTypescript.transaction(async t => { | |
296 | const position = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id, t) | |
297 | ||
298 | const playlistElement = await VideoPlaylistElementModel.create({ | |
299 | url: getVideoPlaylistElementActivityPubUrl(videoPlaylist, video), | |
300 | position, | |
301 | startTimestamp: body.startTimestamp || null, | |
302 | stopTimestamp: body.stopTimestamp || null, | |
303 | videoPlaylistId: videoPlaylist.id, | |
304 | videoId: video.id | |
305 | }, { transaction: t }) | |
306 | ||
307 | videoPlaylist.changed('updatedAt', true) | |
308 | await videoPlaylist.save({ transaction: t }) | |
309 | ||
310 | return playlistElement | |
311 | }) | |
312 | ||
313 | // If the user did not set a thumbnail, automatically take the video thumbnail | |
314 | if (videoPlaylist.hasThumbnail() === false || (videoPlaylist.hasGeneratedThumbnail() && playlistElement.position === 1)) { | |
315 | await generateThumbnailForPlaylist(videoPlaylist, video) | |
316 | } | |
317 | ||
318 | sendUpdateVideoPlaylist(videoPlaylist, undefined) | |
319 | .catch(err => logger.error('Cannot send video playlist update.', { err })) | |
320 | ||
321 | logger.info('Video added in playlist %s at position %d.', videoPlaylist.uuid, playlistElement.position) | |
322 | ||
323 | return res.json({ | |
324 | videoPlaylistElement: { | |
325 | id: playlistElement.id | |
326 | } | |
327 | }).end() | |
328 | } | |
329 | ||
330 | async function updateVideoPlaylistElement (req: express.Request, res: express.Response) { | |
331 | const body: VideoPlaylistElementUpdate = req.body | |
332 | const videoPlaylist = res.locals.videoPlaylistFull | |
333 | const videoPlaylistElement = res.locals.videoPlaylistElement | |
334 | ||
335 | const playlistElement: VideoPlaylistElementModel = await sequelizeTypescript.transaction(async t => { | |
336 | if (body.startTimestamp !== undefined) videoPlaylistElement.startTimestamp = body.startTimestamp | |
337 | if (body.stopTimestamp !== undefined) videoPlaylistElement.stopTimestamp = body.stopTimestamp | |
338 | ||
339 | const element = await videoPlaylistElement.save({ transaction: t }) | |
340 | ||
341 | videoPlaylist.changed('updatedAt', true) | |
342 | await videoPlaylist.save({ transaction: t }) | |
343 | ||
344 | await sendUpdateVideoPlaylist(videoPlaylist, t) | |
345 | ||
346 | return element | |
347 | }) | |
348 | ||
349 | logger.info('Element of position %d of playlist %s updated.', playlistElement.position, videoPlaylist.uuid) | |
350 | ||
351 | return res.type('json').status(204).end() | |
352 | } | |
353 | ||
354 | async function removeVideoFromPlaylist (req: express.Request, res: express.Response) { | |
355 | const videoPlaylistElement = res.locals.videoPlaylistElement | |
356 | const videoPlaylist = res.locals.videoPlaylistFull | |
357 | const positionToDelete = videoPlaylistElement.position | |
358 | ||
359 | await sequelizeTypescript.transaction(async t => { | |
360 | await videoPlaylistElement.destroy({ transaction: t }) | |
361 | ||
362 | // Decrease position of the next elements | |
363 | await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, positionToDelete, null, -1, t) | |
364 | ||
365 | videoPlaylist.changed('updatedAt', true) | |
366 | await videoPlaylist.save({ transaction: t }) | |
367 | ||
368 | logger.info('Video playlist element %d of playlist %s deleted.', videoPlaylistElement.position, videoPlaylist.uuid) | |
369 | }) | |
370 | ||
371 | // Do we need to regenerate the default thumbnail? | |
372 | if (positionToDelete === 1 && videoPlaylist.hasGeneratedThumbnail()) { | |
373 | await regeneratePlaylistThumbnail(videoPlaylist) | |
374 | } | |
375 | ||
376 | sendUpdateVideoPlaylist(videoPlaylist, undefined) | |
377 | .catch(err => logger.error('Cannot send video playlist update.', { err })) | |
378 | ||
379 | return res.type('json').status(204).end() | |
380 | } | |
381 | ||
382 | async function reorderVideosPlaylist (req: express.Request, res: express.Response) { | |
383 | const videoPlaylist = res.locals.videoPlaylistFull | |
384 | const body: VideoPlaylistReorder = req.body | |
385 | ||
386 | const start: number = body.startPosition | |
387 | const insertAfter: number = body.insertAfterPosition | |
388 | const reorderLength: number = body.reorderLength || 1 | |
389 | ||
390 | if (start === insertAfter) { | |
391 | return res.status(204).end() | |
392 | } | |
393 | ||
394 | // Example: if we reorder position 2 and insert after position 5 (so at position 6): # 1 2 3 4 5 6 7 8 9 | |
395 | // * increase position when position > 5 # 1 2 3 4 5 7 8 9 10 | |
396 | // * update position 2 -> position 6 # 1 3 4 5 6 7 8 9 10 | |
397 | // * decrease position when position position > 2 # 1 2 3 4 5 6 7 8 9 | |
398 | await sequelizeTypescript.transaction(async t => { | |
399 | const newPosition = insertAfter + 1 | |
400 | ||
401 | // Add space after the position when we want to insert our reordered elements (increase) | |
402 | await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, newPosition, null, reorderLength, t) | |
403 | ||
404 | let oldPosition = start | |
405 | ||
406 | // We incremented the position of the elements we want to reorder | |
407 | if (start >= newPosition) oldPosition += reorderLength | |
408 | ||
409 | const endOldPosition = oldPosition + reorderLength - 1 | |
410 | // Insert our reordered elements in their place (update) | |
411 | await VideoPlaylistElementModel.reassignPositionOf(videoPlaylist.id, oldPosition, endOldPosition, newPosition, t) | |
412 | ||
413 | // Decrease positions of elements after the old position of our ordered elements (decrease) | |
414 | await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, oldPosition, null, -reorderLength, t) | |
415 | ||
416 | videoPlaylist.changed('updatedAt', true) | |
417 | await videoPlaylist.save({ transaction: t }) | |
418 | ||
419 | await sendUpdateVideoPlaylist(videoPlaylist, t) | |
420 | }) | |
421 | ||
422 | // The first element changed | |
423 | if ((start === 1 || insertAfter === 0) && videoPlaylist.hasGeneratedThumbnail()) { | |
424 | await regeneratePlaylistThumbnail(videoPlaylist) | |
425 | } | |
426 | ||
427 | logger.info( | |
428 | 'Reordered playlist %s (inserted after position %d elements %d - %d).', | |
429 | videoPlaylist.uuid, insertAfter, start, start + reorderLength - 1 | |
430 | ) | |
431 | ||
432 | return res.type('json').status(204).end() | |
433 | } | |
434 | ||
435 | async function getVideoPlaylistVideos (req: express.Request, res: express.Response) { | |
436 | const videoPlaylistInstance = res.locals.videoPlaylistSummary | |
437 | const user = res.locals.oauth ? res.locals.oauth.token.User : undefined | |
438 | const server = await getServerActor() | |
439 | ||
440 | const resultList = await VideoPlaylistElementModel.listForApi({ | |
441 | start: req.query.start, | |
442 | count: req.query.count, | |
443 | videoPlaylistId: videoPlaylistInstance.id, | |
444 | serverAccount: server.Account, | |
445 | user | |
446 | }) | |
447 | ||
448 | const options = { | |
449 | displayNSFW: buildNSFWFilter(res, req.query.nsfw), | |
450 | accountId: user ? user.Account.id : undefined | |
451 | } | |
452 | return res.json(getFormattedObjects(resultList.data, resultList.total, options)) | |
453 | } | |
454 | ||
455 | async function regeneratePlaylistThumbnail (videoPlaylist: MVideoPlaylistThumbnail) { | |
456 | await videoPlaylist.Thumbnail.destroy() | |
457 | videoPlaylist.Thumbnail = null | |
458 | ||
459 | const firstElement = await VideoPlaylistElementModel.loadFirstElementWithVideoThumbnail(videoPlaylist.id) | |
460 | if (firstElement) await generateThumbnailForPlaylist(videoPlaylist, firstElement.Video) | |
461 | } | |
462 | ||
463 | async function generateThumbnailForPlaylist (videoPlaylist: MVideoPlaylistThumbnail, video: MVideoThumbnail) { | |
464 | logger.info('Generating default thumbnail to playlist %s.', videoPlaylist.url) | |
465 | ||
466 | const inputPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getMiniature().filename) | |
467 | const thumbnailModel = await createPlaylistMiniatureFromExisting(inputPath, videoPlaylist, true, true) | |
468 | ||
469 | thumbnailModel.videoPlaylistId = videoPlaylist.id | |
470 | ||
471 | videoPlaylist.Thumbnail = await thumbnailModel.save() | |
472 | } |