]>
Commit | Line | Data |
---|---|---|
418d092a C |
1 | import * as express from 'express' |
2 | import { getFormattedObjects, getServerActor } from '../../helpers/utils' | |
3 | import { | |
4 | asyncMiddleware, | |
5 | asyncRetryTransactionMiddleware, | |
6 | authenticate, | |
09979f89 C |
7 | commonVideosFiltersValidator, |
8 | optionalAuthenticate, | |
418d092a C |
9 | paginationValidator, |
10 | setDefaultPagination, | |
11 | setDefaultSort | |
12 | } from '../../middlewares' | |
418d092a C |
13 | import { videoPlaylistsSortValidator } from '../../middlewares/validators' |
14 | import { buildNSFWFilter, createReqFiles, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils' | |
d4c9f45b | 15 | import { CONFIG, MIMETYPES, sequelizeTypescript, THUMBNAILS_SIZE, VIDEO_PLAYLIST_PRIVACIES } from '../../initializers' |
418d092a C |
16 | import { logger } from '../../helpers/logger' |
17 | import { resetSequelizeInstance } from '../../helpers/database-utils' | |
18 | import { VideoPlaylistModel } from '../../models/video/video-playlist' | |
19 | import { | |
df0b219d | 20 | commonVideoPlaylistFiltersValidator, |
418d092a C |
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' | |
09979f89 C |
33 | import { sendCreateVideoPlaylist, sendDeleteVideoPlaylist, sendUpdateVideoPlaylist } from '../../lib/activitypub/send' |
34 | import { getVideoPlaylistActivityPubUrl, getVideoPlaylistElementActivityPubUrl } from '../../lib/activitypub/url' | |
418d092a C |
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' | |
df0b219d | 41 | import { AccountModel } from '../../models/account/account' |
15e9d5ca | 42 | import { VideoPlaylistReorder } from '../../../shared/models/videos/playlist/video-playlist-reorder.model' |
9f79ade6 | 43 | import { JobQueue } from '../../lib/job-queue' |
418d092a C |
44 | |
45 | const reqThumbnailFile = createReqFiles([ 'thumbnailfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { thumbnailfile: CONFIG.STORAGE.TMP_DIR }) | |
46 | ||
47 | const videoPlaylistRouter = express.Router() | |
48 | ||
d4c9f45b C |
49 | videoPlaylistRouter.get('/privacies', listVideoPlaylistPrivacies) |
50 | ||
418d092a C |
51 | videoPlaylistRouter.get('/', |
52 | paginationValidator, | |
53 | videoPlaylistsSortValidator, | |
54 | setDefaultSort, | |
55 | setDefaultPagination, | |
df0b219d | 56 | commonVideoPlaylistFiltersValidator, |
418d092a C |
57 | asyncMiddleware(listVideoPlaylists) |
58 | ) | |
59 | ||
60 | videoPlaylistRouter.get('/:playlistId', | |
61 | asyncMiddleware(videoPlaylistsGetValidator), | |
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), | |
87 | paginationValidator, | |
88 | setDefaultPagination, | |
07b1a18a | 89 | optionalAuthenticate, |
418d092a C |
90 | commonVideosFiltersValidator, |
91 | asyncMiddleware(getVideoPlaylistVideos) | |
92 | ) | |
93 | ||
94 | videoPlaylistRouter.post('/:playlistId/videos', | |
95 | authenticate, | |
96 | asyncMiddleware(videoPlaylistsAddVideoValidator), | |
97 | asyncRetryTransactionMiddleware(addVideoInPlaylist) | |
98 | ) | |
99 | ||
07b1a18a | 100 | videoPlaylistRouter.post('/:playlistId/videos/reorder', |
418d092a C |
101 | authenticate, |
102 | asyncMiddleware(videoPlaylistsReorderVideosValidator), | |
103 | asyncRetryTransactionMiddleware(reorderVideosPlaylist) | |
104 | ) | |
105 | ||
106 | videoPlaylistRouter.put('/:playlistId/videos/:videoId', | |
107 | authenticate, | |
108 | asyncMiddleware(videoPlaylistsUpdateOrRemoveVideoValidator), | |
109 | asyncRetryTransactionMiddleware(updateVideoPlaylistElement) | |
110 | ) | |
111 | ||
112 | videoPlaylistRouter.delete('/:playlistId/videos/:videoId', | |
113 | authenticate, | |
114 | asyncMiddleware(videoPlaylistsUpdateOrRemoveVideoValidator), | |
115 | asyncRetryTransactionMiddleware(removeVideoFromPlaylist) | |
116 | ) | |
117 | ||
118 | // --------------------------------------------------------------------------- | |
119 | ||
120 | export { | |
121 | videoPlaylistRouter | |
122 | } | |
123 | ||
124 | // --------------------------------------------------------------------------- | |
125 | ||
d4c9f45b C |
126 | function listVideoPlaylistPrivacies (req: express.Request, res: express.Response) { |
127 | res.json(VIDEO_PLAYLIST_PRIVACIES) | |
128 | } | |
129 | ||
418d092a C |
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, | |
df0b219d C |
136 | sort: req.query.sort, |
137 | type: req.query.type | |
418d092a C |
138 | }) |
139 | ||
140 | return res.json(getFormattedObjects(resultList.data, resultList.total)) | |
141 | } | |
142 | ||
143 | function getVideoPlaylist (req: express.Request, res: express.Response) { | |
dae86118 | 144 | const videoPlaylist = res.locals.videoPlaylist |
418d092a | 145 | |
9f79ade6 C |
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 })) | |
149 | } | |
150 | ||
418d092a C |
151 | return res.json(videoPlaylist.toFormattedJSON()) |
152 | } | |
153 | ||
154 | async function addVideoPlaylist (req: express.Request, res: express.Response) { | |
155 | const videoPlaylistInfo: VideoPlaylistCreate = req.body | |
dae86118 | 156 | const user = res.locals.oauth.token.User |
418d092a C |
157 | |
158 | const videoPlaylist = new VideoPlaylistModel({ | |
159 | name: videoPlaylistInfo.displayName, | |
160 | description: videoPlaylistInfo.description, | |
161 | privacy: videoPlaylistInfo.privacy || VideoPlaylistPrivacy.PRIVATE, | |
162 | ownerAccountId: user.Account.id | |
163 | }) | |
164 | ||
165 | videoPlaylist.url = getVideoPlaylistActivityPubUrl(videoPlaylist) // We use the UUID, so set the URL after building the object | |
166 | ||
d4c9f45b | 167 | if (videoPlaylistInfo.videoChannelId) { |
dae86118 | 168 | const videoChannel = res.locals.videoChannel |
418d092a C |
169 | |
170 | videoPlaylist.videoChannelId = videoChannel.id | |
171 | videoPlaylist.VideoChannel = videoChannel | |
172 | } | |
173 | ||
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) | |
178 | } | |
179 | ||
180 | const videoPlaylistCreated: VideoPlaylistModel = await sequelizeTypescript.transaction(async t => { | |
181 | const videoPlaylistCreated = await videoPlaylist.save({ transaction: t }) | |
182 | ||
df0b219d C |
183 | // We need more attributes for the federation |
184 | videoPlaylistCreated.OwnerAccount = await AccountModel.load(user.Account.id, t) | |
418d092a C |
185 | await sendCreateVideoPlaylist(videoPlaylistCreated, t) |
186 | ||
187 | return videoPlaylistCreated | |
188 | }) | |
189 | ||
190 | logger.info('Video playlist with uuid %s created.', videoPlaylist.uuid) | |
191 | ||
192 | return res.json({ | |
193 | videoPlaylist: { | |
194 | id: videoPlaylistCreated.id, | |
195 | uuid: videoPlaylistCreated.uuid | |
196 | } | |
197 | }).end() | |
198 | } | |
199 | ||
200 | async function updateVideoPlaylist (req: express.Request, res: express.Response) { | |
dae86118 | 201 | const videoPlaylistInstance = res.locals.videoPlaylist |
418d092a C |
202 | const videoPlaylistFieldsSave = videoPlaylistInstance.toJSON() |
203 | const videoPlaylistInfoToUpdate = req.body as VideoPlaylistUpdate | |
204 | const wasPrivatePlaylist = videoPlaylistInstance.privacy === VideoPlaylistPrivacy.PRIVATE | |
205 | ||
206 | const thumbnailField = req.files['thumbnailfile'] | |
207 | if (thumbnailField) { | |
208 | const thumbnailPhysicalFile = thumbnailField[ 0 ] | |
209 | await processImage( | |
210 | thumbnailPhysicalFile, | |
211 | join(CONFIG.STORAGE.THUMBNAILS_DIR, videoPlaylistInstance.getThumbnailName()), | |
212 | THUMBNAILS_SIZE | |
213 | ) | |
214 | } | |
215 | ||
216 | try { | |
217 | await sequelizeTypescript.transaction(async t => { | |
218 | const sequelizeOptions = { | |
219 | transaction: t | |
220 | } | |
221 | ||
222 | if (videoPlaylistInfoToUpdate.videoChannelId !== undefined) { | |
223 | if (videoPlaylistInfoToUpdate.videoChannelId === null) { | |
224 | videoPlaylistInstance.videoChannelId = null | |
225 | } else { | |
dae86118 | 226 | const videoChannel = res.locals.videoChannel |
418d092a C |
227 | |
228 | videoPlaylistInstance.videoChannelId = videoChannel.id | |
df0b219d | 229 | videoPlaylistInstance.VideoChannel = videoChannel |
418d092a C |
230 | } |
231 | } | |
232 | ||
233 | if (videoPlaylistInfoToUpdate.displayName !== undefined) videoPlaylistInstance.name = videoPlaylistInfoToUpdate.displayName | |
234 | if (videoPlaylistInfoToUpdate.description !== undefined) videoPlaylistInstance.description = videoPlaylistInfoToUpdate.description | |
235 | ||
236 | if (videoPlaylistInfoToUpdate.privacy !== undefined) { | |
237 | videoPlaylistInstance.privacy = parseInt(videoPlaylistInfoToUpdate.privacy.toString(), 10) | |
238 | } | |
239 | ||
240 | const playlistUpdated = await videoPlaylistInstance.save(sequelizeOptions) | |
241 | ||
242 | const isNewPlaylist = wasPrivatePlaylist && playlistUpdated.privacy !== VideoPlaylistPrivacy.PRIVATE | |
243 | ||
244 | if (isNewPlaylist) { | |
245 | await sendCreateVideoPlaylist(playlistUpdated, t) | |
246 | } else { | |
247 | await sendUpdateVideoPlaylist(playlistUpdated, t) | |
248 | } | |
249 | ||
250 | logger.info('Video playlist %s updated.', videoPlaylistInstance.uuid) | |
251 | ||
252 | return playlistUpdated | |
253 | }) | |
254 | } catch (err) { | |
255 | logger.debug('Cannot update the video playlist.', { err }) | |
256 | ||
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) | |
261 | ||
262 | throw err | |
263 | } | |
264 | ||
265 | return res.type('json').status(204).end() | |
266 | } | |
267 | ||
268 | async function removeVideoPlaylist (req: express.Request, res: express.Response) { | |
dae86118 | 269 | const videoPlaylistInstance = res.locals.videoPlaylist |
418d092a C |
270 | |
271 | await sequelizeTypescript.transaction(async t => { | |
272 | await videoPlaylistInstance.destroy({ transaction: t }) | |
273 | ||
274 | await sendDeleteVideoPlaylist(videoPlaylistInstance, t) | |
275 | ||
276 | logger.info('Video playlist %s deleted.', videoPlaylistInstance.uuid) | |
277 | }) | |
278 | ||
279 | return res.type('json').status(204).end() | |
280 | } | |
281 | ||
282 | async function addVideoInPlaylist (req: express.Request, res: express.Response) { | |
283 | const body: VideoPlaylistElementCreate = req.body | |
dae86118 C |
284 | const videoPlaylist = res.locals.videoPlaylist |
285 | const video = res.locals.video | |
418d092a C |
286 | |
287 | const playlistElement: VideoPlaylistElementModel = await sequelizeTypescript.transaction(async t => { | |
288 | const position = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id, t) | |
289 | ||
290 | const playlistElement = await VideoPlaylistElementModel.create({ | |
291 | url: getVideoPlaylistElementActivityPubUrl(videoPlaylist, video), | |
292 | position, | |
293 | startTimestamp: body.startTimestamp || null, | |
294 | stopTimestamp: body.stopTimestamp || null, | |
295 | videoPlaylistId: videoPlaylist.id, | |
296 | videoId: video.id | |
297 | }, { transaction: t }) | |
298 | ||
2a10aab3 | 299 | videoPlaylist.changed('updatedAt', true) |
f0a39880 | 300 | await videoPlaylist.save({ transaction: t }) |
418d092a C |
301 | |
302 | await sendUpdateVideoPlaylist(videoPlaylist, t) | |
303 | ||
304 | return playlistElement | |
305 | }) | |
306 | ||
f0a39880 C |
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()) | |
310 | ||
311 | if (await pathExists(playlistThumbnailPath) === false) { | |
312 | logger.info('Generating default thumbnail to playlist %s.', videoPlaylist.url) | |
313 | ||
314 | const videoThumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()) | |
315 | await copy(videoThumbnailPath, playlistThumbnailPath) | |
316 | } | |
317 | } | |
318 | ||
418d092a C |
319 | logger.info('Video added in playlist %s at position %d.', videoPlaylist.uuid, playlistElement.position) |
320 | ||
321 | return res.json({ | |
322 | videoPlaylistElement: { | |
323 | id: playlistElement.id | |
324 | } | |
325 | }).end() | |
326 | } | |
327 | ||
328 | async function updateVideoPlaylistElement (req: express.Request, res: express.Response) { | |
329 | const body: VideoPlaylistElementUpdate = req.body | |
dae86118 C |
330 | const videoPlaylist = res.locals.videoPlaylist |
331 | const videoPlaylistElement = res.locals.videoPlaylistElement | |
418d092a C |
332 | |
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 | |
336 | ||
337 | const element = await videoPlaylistElement.save({ transaction: t }) | |
338 | ||
2a10aab3 | 339 | videoPlaylist.changed('updatedAt', true) |
f0a39880 C |
340 | await videoPlaylist.save({ transaction: t }) |
341 | ||
418d092a C |
342 | await sendUpdateVideoPlaylist(videoPlaylist, t) |
343 | ||
344 | return element | |
345 | }) | |
346 | ||
347 | logger.info('Element of position %d of playlist %s updated.', playlistElement.position, videoPlaylist.uuid) | |
348 | ||
349 | return res.type('json').status(204).end() | |
350 | } | |
351 | ||
352 | async function removeVideoFromPlaylist (req: express.Request, res: express.Response) { | |
dae86118 C |
353 | const videoPlaylistElement = res.locals.videoPlaylistElement |
354 | const videoPlaylist = res.locals.videoPlaylist | |
418d092a C |
355 | const positionToDelete = videoPlaylistElement.position |
356 | ||
357 | await sequelizeTypescript.transaction(async t => { | |
358 | await videoPlaylistElement.destroy({ transaction: t }) | |
359 | ||
360 | // Decrease position of the next elements | |
361 | await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, positionToDelete, null, -1, t) | |
362 | ||
2a10aab3 | 363 | videoPlaylist.changed('updatedAt', true) |
f0a39880 C |
364 | await videoPlaylist.save({ transaction: t }) |
365 | ||
418d092a C |
366 | await sendUpdateVideoPlaylist(videoPlaylist, t) |
367 | ||
368 | logger.info('Video playlist element %d of playlist %s deleted.', videoPlaylistElement.position, videoPlaylist.uuid) | |
369 | }) | |
370 | ||
371 | return res.type('json').status(204).end() | |
372 | } | |
373 | ||
374 | async function reorderVideosPlaylist (req: express.Request, res: express.Response) { | |
dae86118 | 375 | const videoPlaylist = res.locals.videoPlaylist |
15e9d5ca | 376 | const body: VideoPlaylistReorder = req.body |
418d092a | 377 | |
15e9d5ca C |
378 | const start: number = body.startPosition |
379 | const insertAfter: number = body.insertAfterPosition | |
380 | const reorderLength: number = body.reorderLength || 1 | |
418d092a C |
381 | |
382 | if (start === insertAfter) { | |
383 | return res.status(204).end() | |
384 | } | |
385 | ||
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 | |
392 | ||
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) | |
395 | ||
396 | let oldPosition = start | |
397 | ||
398 | // We incremented the position of the elements we want to reorder | |
399 | if (start >= newPosition) oldPosition += reorderLength | |
400 | ||
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) | |
404 | ||
405 | // Decrease positions of elements after the old position of our ordered elements (decrease) | |
406 | await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, oldPosition, null, -reorderLength, t) | |
407 | ||
2a10aab3 | 408 | videoPlaylist.changed('updatedAt', true) |
f0a39880 C |
409 | await videoPlaylist.save({ transaction: t }) |
410 | ||
418d092a C |
411 | await sendUpdateVideoPlaylist(videoPlaylist, t) |
412 | }) | |
413 | ||
414 | logger.info( | |
415 | 'Reordered playlist %s (inserted after %d elements %d - %d).', | |
416 | videoPlaylist.uuid, insertAfter, start, start + reorderLength - 1 | |
417 | ) | |
418 | ||
419 | return res.type('json').status(204).end() | |
420 | } | |
421 | ||
422 | async function getVideoPlaylistVideos (req: express.Request, res: express.Response) { | |
dae86118 | 423 | const videoPlaylistInstance = res.locals.videoPlaylist |
418d092a C |
424 | const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined |
425 | ||
426 | const resultList = await VideoModel.listForApi({ | |
427 | followerActorId, | |
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), | |
439 | withFiles: false, | |
440 | videoPlaylistId: videoPlaylistInstance.id, | |
441 | user: res.locals.oauth ? res.locals.oauth.token.User : undefined | |
442 | }) | |
443 | ||
df0b219d C |
444 | const additionalAttributes = { playlistInfo: true } |
445 | return res.json(getFormattedObjects(resultList.data, resultList.total, { additionalAttributes })) | |
418d092a | 446 | } |