]>
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' | |
6dd9de95 | 15 | import { 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' |
6dd9de95 | 44 | import { CONFIG } from '../../initializers/config' |
418d092a C |
45 | |
46 | const reqThumbnailFile = createReqFiles([ 'thumbnailfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { thumbnailfile: CONFIG.STORAGE.TMP_DIR }) | |
47 | ||
48 | const videoPlaylistRouter = express.Router() | |
49 | ||
d4c9f45b C |
50 | videoPlaylistRouter.get('/privacies', listVideoPlaylistPrivacies) |
51 | ||
418d092a C |
52 | videoPlaylistRouter.get('/', |
53 | paginationValidator, | |
54 | videoPlaylistsSortValidator, | |
55 | setDefaultSort, | |
56 | setDefaultPagination, | |
df0b219d | 57 | commonVideoPlaylistFiltersValidator, |
418d092a C |
58 | asyncMiddleware(listVideoPlaylists) |
59 | ) | |
60 | ||
61 | videoPlaylistRouter.get('/:playlistId', | |
62 | asyncMiddleware(videoPlaylistsGetValidator), | |
63 | getVideoPlaylist | |
64 | ) | |
65 | ||
66 | videoPlaylistRouter.post('/', | |
67 | authenticate, | |
68 | reqThumbnailFile, | |
69 | asyncMiddleware(videoPlaylistsAddValidator), | |
70 | asyncRetryTransactionMiddleware(addVideoPlaylist) | |
71 | ) | |
72 | ||
73 | videoPlaylistRouter.put('/:playlistId', | |
74 | authenticate, | |
75 | reqThumbnailFile, | |
76 | asyncMiddleware(videoPlaylistsUpdateValidator), | |
77 | asyncRetryTransactionMiddleware(updateVideoPlaylist) | |
78 | ) | |
79 | ||
80 | videoPlaylistRouter.delete('/:playlistId', | |
81 | authenticate, | |
82 | asyncMiddleware(videoPlaylistsDeleteValidator), | |
83 | asyncRetryTransactionMiddleware(removeVideoPlaylist) | |
84 | ) | |
85 | ||
86 | videoPlaylistRouter.get('/:playlistId/videos', | |
87 | asyncMiddleware(videoPlaylistsGetValidator), | |
88 | paginationValidator, | |
89 | setDefaultPagination, | |
07b1a18a | 90 | optionalAuthenticate, |
418d092a C |
91 | commonVideosFiltersValidator, |
92 | asyncMiddleware(getVideoPlaylistVideos) | |
93 | ) | |
94 | ||
95 | videoPlaylistRouter.post('/:playlistId/videos', | |
96 | authenticate, | |
97 | asyncMiddleware(videoPlaylistsAddVideoValidator), | |
98 | asyncRetryTransactionMiddleware(addVideoInPlaylist) | |
99 | ) | |
100 | ||
07b1a18a | 101 | videoPlaylistRouter.post('/:playlistId/videos/reorder', |
418d092a C |
102 | authenticate, |
103 | asyncMiddleware(videoPlaylistsReorderVideosValidator), | |
104 | asyncRetryTransactionMiddleware(reorderVideosPlaylist) | |
105 | ) | |
106 | ||
107 | videoPlaylistRouter.put('/:playlistId/videos/:videoId', | |
108 | authenticate, | |
109 | asyncMiddleware(videoPlaylistsUpdateOrRemoveVideoValidator), | |
110 | asyncRetryTransactionMiddleware(updateVideoPlaylistElement) | |
111 | ) | |
112 | ||
113 | videoPlaylistRouter.delete('/:playlistId/videos/:videoId', | |
114 | authenticate, | |
115 | asyncMiddleware(videoPlaylistsUpdateOrRemoveVideoValidator), | |
116 | asyncRetryTransactionMiddleware(removeVideoFromPlaylist) | |
117 | ) | |
118 | ||
119 | // --------------------------------------------------------------------------- | |
120 | ||
121 | export { | |
122 | videoPlaylistRouter | |
123 | } | |
124 | ||
125 | // --------------------------------------------------------------------------- | |
126 | ||
d4c9f45b C |
127 | function listVideoPlaylistPrivacies (req: express.Request, res: express.Response) { |
128 | res.json(VIDEO_PLAYLIST_PRIVACIES) | |
129 | } | |
130 | ||
418d092a C |
131 | async function listVideoPlaylists (req: express.Request, res: express.Response) { |
132 | const serverActor = await getServerActor() | |
133 | const resultList = await VideoPlaylistModel.listForApi({ | |
134 | followerActorId: serverActor.id, | |
135 | start: req.query.start, | |
136 | count: req.query.count, | |
df0b219d C |
137 | sort: req.query.sort, |
138 | type: req.query.type | |
418d092a C |
139 | }) |
140 | ||
141 | return res.json(getFormattedObjects(resultList.data, resultList.total)) | |
142 | } | |
143 | ||
144 | function getVideoPlaylist (req: express.Request, res: express.Response) { | |
dae86118 | 145 | const videoPlaylist = res.locals.videoPlaylist |
418d092a | 146 | |
9f79ade6 C |
147 | if (videoPlaylist.isOutdated()) { |
148 | JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video-playlist', url: videoPlaylist.url } }) | |
149 | .catch(err => logger.error('Cannot create AP refresher job for playlist %s.', videoPlaylist.url, { err })) | |
150 | } | |
151 | ||
418d092a C |
152 | return res.json(videoPlaylist.toFormattedJSON()) |
153 | } | |
154 | ||
155 | async function addVideoPlaylist (req: express.Request, res: express.Response) { | |
156 | const videoPlaylistInfo: VideoPlaylistCreate = req.body | |
dae86118 | 157 | const user = res.locals.oauth.token.User |
418d092a C |
158 | |
159 | const videoPlaylist = new VideoPlaylistModel({ | |
160 | name: videoPlaylistInfo.displayName, | |
161 | description: videoPlaylistInfo.description, | |
162 | privacy: videoPlaylistInfo.privacy || VideoPlaylistPrivacy.PRIVATE, | |
163 | ownerAccountId: user.Account.id | |
164 | }) | |
165 | ||
166 | videoPlaylist.url = getVideoPlaylistActivityPubUrl(videoPlaylist) // We use the UUID, so set the URL after building the object | |
167 | ||
d4c9f45b | 168 | if (videoPlaylistInfo.videoChannelId) { |
dae86118 | 169 | const videoChannel = res.locals.videoChannel |
418d092a C |
170 | |
171 | videoPlaylist.videoChannelId = videoChannel.id | |
172 | videoPlaylist.VideoChannel = videoChannel | |
173 | } | |
174 | ||
175 | const thumbnailField = req.files['thumbnailfile'] | |
176 | if (thumbnailField) { | |
177 | const thumbnailPhysicalFile = thumbnailField[ 0 ] | |
178 | await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoPlaylist.getThumbnailName()), THUMBNAILS_SIZE) | |
179 | } | |
180 | ||
181 | const videoPlaylistCreated: VideoPlaylistModel = await sequelizeTypescript.transaction(async t => { | |
182 | const videoPlaylistCreated = await videoPlaylist.save({ transaction: t }) | |
183 | ||
df0b219d C |
184 | // We need more attributes for the federation |
185 | videoPlaylistCreated.OwnerAccount = await AccountModel.load(user.Account.id, t) | |
418d092a C |
186 | await sendCreateVideoPlaylist(videoPlaylistCreated, t) |
187 | ||
188 | return videoPlaylistCreated | |
189 | }) | |
190 | ||
191 | logger.info('Video playlist with uuid %s created.', videoPlaylist.uuid) | |
192 | ||
193 | return res.json({ | |
194 | videoPlaylist: { | |
195 | id: videoPlaylistCreated.id, | |
196 | uuid: videoPlaylistCreated.uuid | |
197 | } | |
198 | }).end() | |
199 | } | |
200 | ||
201 | async function updateVideoPlaylist (req: express.Request, res: express.Response) { | |
dae86118 | 202 | const videoPlaylistInstance = res.locals.videoPlaylist |
418d092a C |
203 | const videoPlaylistFieldsSave = videoPlaylistInstance.toJSON() |
204 | const videoPlaylistInfoToUpdate = req.body as VideoPlaylistUpdate | |
205 | const wasPrivatePlaylist = videoPlaylistInstance.privacy === VideoPlaylistPrivacy.PRIVATE | |
206 | ||
207 | const thumbnailField = req.files['thumbnailfile'] | |
208 | if (thumbnailField) { | |
209 | const thumbnailPhysicalFile = thumbnailField[ 0 ] | |
210 | await processImage( | |
211 | thumbnailPhysicalFile, | |
212 | join(CONFIG.STORAGE.THUMBNAILS_DIR, videoPlaylistInstance.getThumbnailName()), | |
213 | THUMBNAILS_SIZE | |
214 | ) | |
215 | } | |
216 | ||
217 | try { | |
218 | await sequelizeTypescript.transaction(async t => { | |
219 | const sequelizeOptions = { | |
220 | transaction: t | |
221 | } | |
222 | ||
223 | if (videoPlaylistInfoToUpdate.videoChannelId !== undefined) { | |
224 | if (videoPlaylistInfoToUpdate.videoChannelId === null) { | |
225 | videoPlaylistInstance.videoChannelId = null | |
226 | } else { | |
dae86118 | 227 | const videoChannel = res.locals.videoChannel |
418d092a C |
228 | |
229 | videoPlaylistInstance.videoChannelId = videoChannel.id | |
df0b219d | 230 | videoPlaylistInstance.VideoChannel = videoChannel |
418d092a C |
231 | } |
232 | } | |
233 | ||
234 | if (videoPlaylistInfoToUpdate.displayName !== undefined) videoPlaylistInstance.name = videoPlaylistInfoToUpdate.displayName | |
235 | if (videoPlaylistInfoToUpdate.description !== undefined) videoPlaylistInstance.description = videoPlaylistInfoToUpdate.description | |
236 | ||
237 | if (videoPlaylistInfoToUpdate.privacy !== undefined) { | |
238 | videoPlaylistInstance.privacy = parseInt(videoPlaylistInfoToUpdate.privacy.toString(), 10) | |
239 | } | |
240 | ||
241 | const playlistUpdated = await videoPlaylistInstance.save(sequelizeOptions) | |
242 | ||
243 | const isNewPlaylist = wasPrivatePlaylist && playlistUpdated.privacy !== VideoPlaylistPrivacy.PRIVATE | |
244 | ||
245 | if (isNewPlaylist) { | |
246 | await sendCreateVideoPlaylist(playlistUpdated, t) | |
247 | } else { | |
248 | await sendUpdateVideoPlaylist(playlistUpdated, t) | |
249 | } | |
250 | ||
251 | logger.info('Video playlist %s updated.', videoPlaylistInstance.uuid) | |
252 | ||
253 | return playlistUpdated | |
254 | }) | |
255 | } catch (err) { | |
256 | logger.debug('Cannot update the video playlist.', { err }) | |
257 | ||
258 | // Force fields we want to update | |
259 | // If the transaction is retried, sequelize will think the object has not changed | |
260 | // So it will skip the SQL request, even if the last one was ROLLBACKed! | |
261 | resetSequelizeInstance(videoPlaylistInstance, videoPlaylistFieldsSave) | |
262 | ||
263 | throw err | |
264 | } | |
265 | ||
266 | return res.type('json').status(204).end() | |
267 | } | |
268 | ||
269 | async function removeVideoPlaylist (req: express.Request, res: express.Response) { | |
dae86118 | 270 | const videoPlaylistInstance = res.locals.videoPlaylist |
418d092a C |
271 | |
272 | await sequelizeTypescript.transaction(async t => { | |
273 | await videoPlaylistInstance.destroy({ transaction: t }) | |
274 | ||
275 | await sendDeleteVideoPlaylist(videoPlaylistInstance, t) | |
276 | ||
277 | logger.info('Video playlist %s deleted.', videoPlaylistInstance.uuid) | |
278 | }) | |
279 | ||
280 | return res.type('json').status(204).end() | |
281 | } | |
282 | ||
283 | async function addVideoInPlaylist (req: express.Request, res: express.Response) { | |
284 | const body: VideoPlaylistElementCreate = req.body | |
dae86118 C |
285 | const videoPlaylist = res.locals.videoPlaylist |
286 | const video = res.locals.video | |
418d092a C |
287 | |
288 | const playlistElement: VideoPlaylistElementModel = await sequelizeTypescript.transaction(async t => { | |
289 | const position = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id, t) | |
290 | ||
291 | const playlistElement = await VideoPlaylistElementModel.create({ | |
292 | url: getVideoPlaylistElementActivityPubUrl(videoPlaylist, video), | |
293 | position, | |
294 | startTimestamp: body.startTimestamp || null, | |
295 | stopTimestamp: body.stopTimestamp || null, | |
296 | videoPlaylistId: videoPlaylist.id, | |
297 | videoId: video.id | |
298 | }, { transaction: t }) | |
299 | ||
2a10aab3 | 300 | videoPlaylist.changed('updatedAt', true) |
f0a39880 | 301 | await videoPlaylist.save({ transaction: t }) |
418d092a C |
302 | |
303 | await sendUpdateVideoPlaylist(videoPlaylist, t) | |
304 | ||
305 | return playlistElement | |
306 | }) | |
307 | ||
f0a39880 C |
308 | // If the user did not set a thumbnail, automatically take the video thumbnail |
309 | if (playlistElement.position === 1) { | |
310 | const playlistThumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, videoPlaylist.getThumbnailName()) | |
311 | ||
312 | if (await pathExists(playlistThumbnailPath) === false) { | |
313 | logger.info('Generating default thumbnail to playlist %s.', videoPlaylist.url) | |
314 | ||
315 | const videoThumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()) | |
316 | await copy(videoThumbnailPath, playlistThumbnailPath) | |
317 | } | |
318 | } | |
319 | ||
418d092a C |
320 | logger.info('Video added in playlist %s at position %d.', videoPlaylist.uuid, playlistElement.position) |
321 | ||
322 | return res.json({ | |
323 | videoPlaylistElement: { | |
324 | id: playlistElement.id | |
325 | } | |
326 | }).end() | |
327 | } | |
328 | ||
329 | async function updateVideoPlaylistElement (req: express.Request, res: express.Response) { | |
330 | const body: VideoPlaylistElementUpdate = req.body | |
dae86118 C |
331 | const videoPlaylist = res.locals.videoPlaylist |
332 | const videoPlaylistElement = res.locals.videoPlaylistElement | |
418d092a C |
333 | |
334 | const playlistElement: VideoPlaylistElementModel = await sequelizeTypescript.transaction(async t => { | |
335 | if (body.startTimestamp !== undefined) videoPlaylistElement.startTimestamp = body.startTimestamp | |
336 | if (body.stopTimestamp !== undefined) videoPlaylistElement.stopTimestamp = body.stopTimestamp | |
337 | ||
338 | const element = await videoPlaylistElement.save({ transaction: t }) | |
339 | ||
2a10aab3 | 340 | videoPlaylist.changed('updatedAt', true) |
f0a39880 C |
341 | await videoPlaylist.save({ transaction: t }) |
342 | ||
418d092a C |
343 | await sendUpdateVideoPlaylist(videoPlaylist, t) |
344 | ||
345 | return element | |
346 | }) | |
347 | ||
348 | logger.info('Element of position %d of playlist %s updated.', playlistElement.position, videoPlaylist.uuid) | |
349 | ||
350 | return res.type('json').status(204).end() | |
351 | } | |
352 | ||
353 | async function removeVideoFromPlaylist (req: express.Request, res: express.Response) { | |
dae86118 C |
354 | const videoPlaylistElement = res.locals.videoPlaylistElement |
355 | const videoPlaylist = res.locals.videoPlaylist | |
418d092a C |
356 | const positionToDelete = videoPlaylistElement.position |
357 | ||
358 | await sequelizeTypescript.transaction(async t => { | |
359 | await videoPlaylistElement.destroy({ transaction: t }) | |
360 | ||
361 | // Decrease position of the next elements | |
362 | await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, positionToDelete, null, -1, t) | |
363 | ||
2a10aab3 | 364 | videoPlaylist.changed('updatedAt', true) |
f0a39880 C |
365 | await videoPlaylist.save({ transaction: t }) |
366 | ||
418d092a C |
367 | await sendUpdateVideoPlaylist(videoPlaylist, t) |
368 | ||
369 | logger.info('Video playlist element %d of playlist %s deleted.', videoPlaylistElement.position, videoPlaylist.uuid) | |
370 | }) | |
371 | ||
372 | return res.type('json').status(204).end() | |
373 | } | |
374 | ||
375 | async function reorderVideosPlaylist (req: express.Request, res: express.Response) { | |
dae86118 | 376 | const videoPlaylist = res.locals.videoPlaylist |
15e9d5ca | 377 | const body: VideoPlaylistReorder = req.body |
418d092a | 378 | |
15e9d5ca C |
379 | const start: number = body.startPosition |
380 | const insertAfter: number = body.insertAfterPosition | |
381 | const reorderLength: number = body.reorderLength || 1 | |
418d092a C |
382 | |
383 | if (start === insertAfter) { | |
384 | return res.status(204).end() | |
385 | } | |
386 | ||
387 | // Example: if we reorder position 2 and insert after position 5 (so at position 6): # 1 2 3 4 5 6 7 8 9 | |
388 | // * increase position when position > 5 # 1 2 3 4 5 7 8 9 10 | |
389 | // * update position 2 -> position 6 # 1 3 4 5 6 7 8 9 10 | |
390 | // * decrease position when position position > 2 # 1 2 3 4 5 6 7 8 9 | |
391 | await sequelizeTypescript.transaction(async t => { | |
392 | const newPosition = insertAfter + 1 | |
393 | ||
394 | // Add space after the position when we want to insert our reordered elements (increase) | |
395 | await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, newPosition, null, reorderLength, t) | |
396 | ||
397 | let oldPosition = start | |
398 | ||
399 | // We incremented the position of the elements we want to reorder | |
400 | if (start >= newPosition) oldPosition += reorderLength | |
401 | ||
402 | const endOldPosition = oldPosition + reorderLength - 1 | |
403 | // Insert our reordered elements in their place (update) | |
404 | await VideoPlaylistElementModel.reassignPositionOf(videoPlaylist.id, oldPosition, endOldPosition, newPosition, t) | |
405 | ||
406 | // Decrease positions of elements after the old position of our ordered elements (decrease) | |
407 | await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, oldPosition, null, -reorderLength, t) | |
408 | ||
2a10aab3 | 409 | videoPlaylist.changed('updatedAt', true) |
f0a39880 C |
410 | await videoPlaylist.save({ transaction: t }) |
411 | ||
418d092a C |
412 | await sendUpdateVideoPlaylist(videoPlaylist, t) |
413 | }) | |
414 | ||
415 | logger.info( | |
416 | 'Reordered playlist %s (inserted after %d elements %d - %d).', | |
417 | videoPlaylist.uuid, insertAfter, start, start + reorderLength - 1 | |
418 | ) | |
419 | ||
420 | return res.type('json').status(204).end() | |
421 | } | |
422 | ||
423 | async function getVideoPlaylistVideos (req: express.Request, res: express.Response) { | |
dae86118 | 424 | const videoPlaylistInstance = res.locals.videoPlaylist |
418d092a C |
425 | const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined |
426 | ||
427 | const resultList = await VideoModel.listForApi({ | |
428 | followerActorId, | |
429 | start: req.query.start, | |
430 | count: req.query.count, | |
431 | sort: 'VideoPlaylistElements.position', | |
432 | includeLocalVideos: true, | |
433 | categoryOneOf: req.query.categoryOneOf, | |
434 | licenceOneOf: req.query.licenceOneOf, | |
435 | languageOneOf: req.query.languageOneOf, | |
436 | tagsOneOf: req.query.tagsOneOf, | |
437 | tagsAllOf: req.query.tagsAllOf, | |
438 | filter: req.query.filter, | |
439 | nsfw: buildNSFWFilter(res, req.query.nsfw), | |
440 | withFiles: false, | |
441 | videoPlaylistId: videoPlaylistInstance.id, | |
442 | user: res.locals.oauth ? res.locals.oauth.token.User : undefined | |
443 | }) | |
444 | ||
df0b219d C |
445 | const additionalAttributes = { playlistInfo: true } |
446 | return res.json(getFormattedObjects(resultList.data, resultList.total, { additionalAttributes })) | |
418d092a | 447 | } |