aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/controllers/api/video-playlist.ts
blob: a17136401095fa521e143477a6c9ccf08df60247 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
import * as express from 'express'
import { getFormattedObjects, getServerActor } from '../../helpers/utils'
import {
  asyncMiddleware,
  asyncRetryTransactionMiddleware,
  authenticate,
  commonVideosFiltersValidator,
  optionalAuthenticate,
  paginationValidator,
  setDefaultPagination,
  setDefaultSort
} from '../../middlewares'
import { videoPlaylistsSortValidator } from '../../middlewares/validators'
import { buildNSFWFilter, createReqFiles, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils'
import { MIMETYPES, VIDEO_PLAYLIST_PRIVACIES } from '../../initializers/constants'
import { logger } from '../../helpers/logger'
import { resetSequelizeInstance } from '../../helpers/database-utils'
import { VideoPlaylistModel } from '../../models/video/video-playlist'
import {
  commonVideoPlaylistFiltersValidator,
  videoPlaylistsAddValidator,
  videoPlaylistsAddVideoValidator,
  videoPlaylistsDeleteValidator,
  videoPlaylistsGetValidator,
  videoPlaylistsReorderVideosValidator,
  videoPlaylistsUpdateOrRemoveVideoValidator,
  videoPlaylistsUpdateValidator
} from '../../middlewares/validators/videos/video-playlists'
import { VideoPlaylistCreate } from '../../../shared/models/videos/playlist/video-playlist-create.model'
import { VideoPlaylistPrivacy } from '../../../shared/models/videos/playlist/video-playlist-privacy.model'
import { join } from 'path'
import { sendCreateVideoPlaylist, sendDeleteVideoPlaylist, sendUpdateVideoPlaylist } from '../../lib/activitypub/send'
import { getVideoPlaylistActivityPubUrl, getVideoPlaylistElementActivityPubUrl } from '../../lib/activitypub/url'
import { VideoPlaylistUpdate } from '../../../shared/models/videos/playlist/video-playlist-update.model'
import { VideoModel } from '../../models/video/video'
import { VideoPlaylistElementModel } from '../../models/video/video-playlist-element'
import { VideoPlaylistElementCreate } from '../../../shared/models/videos/playlist/video-playlist-element-create.model'
import { VideoPlaylistElementUpdate } from '../../../shared/models/videos/playlist/video-playlist-element-update.model'
import { AccountModel } from '../../models/account/account'
import { VideoPlaylistReorder } from '../../../shared/models/videos/playlist/video-playlist-reorder.model'
import { JobQueue } from '../../lib/job-queue'
import { CONFIG } from '../../initializers/config'
import { sequelizeTypescript } from '../../initializers/database'
import { createPlaylistMiniatureFromExisting } from '../../lib/thumbnail'

const reqThumbnailFile = createReqFiles([ 'thumbnailfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { thumbnailfile: CONFIG.STORAGE.TMP_DIR })

const videoPlaylistRouter = express.Router()

videoPlaylistRouter.get('/privacies', listVideoPlaylistPrivacies)

videoPlaylistRouter.get('/',
  paginationValidator,
  videoPlaylistsSortValidator,
  setDefaultSort,
  setDefaultPagination,
  commonVideoPlaylistFiltersValidator,
  asyncMiddleware(listVideoPlaylists)
)

videoPlaylistRouter.get('/:playlistId',
  asyncMiddleware(videoPlaylistsGetValidator),
  getVideoPlaylist
)

videoPlaylistRouter.post('/',
  authenticate,
  reqThumbnailFile,
  asyncMiddleware(videoPlaylistsAddValidator),
  asyncRetryTransactionMiddleware(addVideoPlaylist)
)

videoPlaylistRouter.put('/:playlistId',
  authenticate,
  reqThumbnailFile,
  asyncMiddleware(videoPlaylistsUpdateValidator),
  asyncRetryTransactionMiddleware(updateVideoPlaylist)
)

videoPlaylistRouter.delete('/:playlistId',
  authenticate,
  asyncMiddleware(videoPlaylistsDeleteValidator),
  asyncRetryTransactionMiddleware(removeVideoPlaylist)
)

videoPlaylistRouter.get('/:playlistId/videos',
  asyncMiddleware(videoPlaylistsGetValidator),
  paginationValidator,
  setDefaultPagination,
  optionalAuthenticate,
  commonVideosFiltersValidator,
  asyncMiddleware(getVideoPlaylistVideos)
)

videoPlaylistRouter.post('/:playlistId/videos',
  authenticate,
  asyncMiddleware(videoPlaylistsAddVideoValidator),
  asyncRetryTransactionMiddleware(addVideoInPlaylist)
)

videoPlaylistRouter.post('/:playlistId/videos/reorder',
  authenticate,
  asyncMiddleware(videoPlaylistsReorderVideosValidator),
  asyncRetryTransactionMiddleware(reorderVideosPlaylist)
)

videoPlaylistRouter.put('/:playlistId/videos/:videoId',
  authenticate,
  asyncMiddleware(videoPlaylistsUpdateOrRemoveVideoValidator),
  asyncRetryTransactionMiddleware(updateVideoPlaylistElement)
)

videoPlaylistRouter.delete('/:playlistId/videos/:videoId',
  authenticate,
  asyncMiddleware(videoPlaylistsUpdateOrRemoveVideoValidator),
  asyncRetryTransactionMiddleware(removeVideoFromPlaylist)
)

// ---------------------------------------------------------------------------

export {
  videoPlaylistRouter
}

// ---------------------------------------------------------------------------

function listVideoPlaylistPrivacies (req: express.Request, res: express.Response) {
  res.json(VIDEO_PLAYLIST_PRIVACIES)
}

async function listVideoPlaylists (req: express.Request, res: express.Response) {
  const serverActor = await getServerActor()
  const resultList = await VideoPlaylistModel.listForApi({
    followerActorId: serverActor.id,
    start: req.query.start,
    count: req.query.count,
    sort: req.query.sort,
    type: req.query.type
  })

  return res.json(getFormattedObjects(resultList.data, resultList.total))
}

function getVideoPlaylist (req: express.Request, res: express.Response) {
  const videoPlaylist = res.locals.videoPlaylist

  if (videoPlaylist.isOutdated()) {
    JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video-playlist', url: videoPlaylist.url } })
            .catch(err => logger.error('Cannot create AP refresher job for playlist %s.', videoPlaylist.url, { err }))
  }

  return res.json(videoPlaylist.toFormattedJSON())
}

async function addVideoPlaylist (req: express.Request, res: express.Response) {
  const videoPlaylistInfo: VideoPlaylistCreate = req.body
  const user = res.locals.oauth.token.User

  const videoPlaylist = new VideoPlaylistModel({
    name: videoPlaylistInfo.displayName,
    description: videoPlaylistInfo.description,
    privacy: videoPlaylistInfo.privacy || VideoPlaylistPrivacy.PRIVATE,
    ownerAccountId: user.Account.id
  })

  videoPlaylist.url = getVideoPlaylistActivityPubUrl(videoPlaylist) // We use the UUID, so set the URL after building the object

  if (videoPlaylistInfo.videoChannelId) {
    const videoChannel = res.locals.videoChannel

    videoPlaylist.videoChannelId = videoChannel.id
    videoPlaylist.VideoChannel = videoChannel
  }

  const thumbnailField = req.files['thumbnailfile']
  const thumbnailModel = thumbnailField
    ? await createPlaylistMiniatureFromExisting(thumbnailField[0].path, videoPlaylist)
    : undefined

  const videoPlaylistCreated: VideoPlaylistModel = await sequelizeTypescript.transaction(async t => {
    const videoPlaylistCreated = await videoPlaylist.save({ transaction: t })

    if (thumbnailModel) await videoPlaylistCreated.setAndSaveThumbnail(thumbnailModel, t)

    // We need more attributes for the federation
    videoPlaylistCreated.OwnerAccount = await AccountModel.load(user.Account.id, t)
    await sendCreateVideoPlaylist(videoPlaylistCreated, t)

    return videoPlaylistCreated
  })

  logger.info('Video playlist with uuid %s created.', videoPlaylist.uuid)

  return res.json({
    videoPlaylist: {
      id: videoPlaylistCreated.id,
      uuid: videoPlaylistCreated.uuid
    }
  }).end()
}

async function updateVideoPlaylist (req: express.Request, res: express.Response) {
  const videoPlaylistInstance = res.locals.videoPlaylist
  const videoPlaylistFieldsSave = videoPlaylistInstance.toJSON()
  const videoPlaylistInfoToUpdate = req.body as VideoPlaylistUpdate
  const wasPrivatePlaylist = videoPlaylistInstance.privacy === VideoPlaylistPrivacy.PRIVATE

  const thumbnailField = req.files['thumbnailfile']
  const thumbnailModel = thumbnailField
    ? await createPlaylistMiniatureFromExisting(thumbnailField[0].path, videoPlaylistInstance)
    : undefined

  try {
    await sequelizeTypescript.transaction(async t => {
      const sequelizeOptions = {
        transaction: t
      }

      if (videoPlaylistInfoToUpdate.videoChannelId !== undefined) {
        if (videoPlaylistInfoToUpdate.videoChannelId === null) {
          videoPlaylistInstance.videoChannelId = null
        } else {
          const videoChannel = res.locals.videoChannel

          videoPlaylistInstance.videoChannelId = videoChannel.id
          videoPlaylistInstance.VideoChannel = videoChannel
        }
      }

      if (videoPlaylistInfoToUpdate.displayName !== undefined) videoPlaylistInstance.name = videoPlaylistInfoToUpdate.displayName
      if (videoPlaylistInfoToUpdate.description !== undefined) videoPlaylistInstance.description = videoPlaylistInfoToUpdate.description

      if (videoPlaylistInfoToUpdate.privacy !== undefined) {
        videoPlaylistInstance.privacy = parseInt(videoPlaylistInfoToUpdate.privacy.toString(), 10)
      }

      const playlistUpdated = await videoPlaylistInstance.save(sequelizeOptions)

      if (thumbnailModel) await playlistUpdated.setAndSaveThumbnail(thumbnailModel, t)

      const isNewPlaylist = wasPrivatePlaylist && playlistUpdated.privacy !== VideoPlaylistPrivacy.PRIVATE

      if (isNewPlaylist) {
        await sendCreateVideoPlaylist(playlistUpdated, t)
      } else {
        await sendUpdateVideoPlaylist(playlistUpdated, t)
      }

      logger.info('Video playlist %s updated.', videoPlaylistInstance.uuid)

      return playlistUpdated
    })
  } catch (err) {
    logger.debug('Cannot update the video playlist.', { err })

    // Force fields we want to update
    // If the transaction is retried, sequelize will think the object has not changed
    // So it will skip the SQL request, even if the last one was ROLLBACKed!
    resetSequelizeInstance(videoPlaylistInstance, videoPlaylistFieldsSave)

    throw err
  }

  return res.type('json').status(204).end()
}

async function removeVideoPlaylist (req: express.Request, res: express.Response) {
  const videoPlaylistInstance = res.locals.videoPlaylist

  await sequelizeTypescript.transaction(async t => {
    await videoPlaylistInstance.destroy({ transaction: t })

    await sendDeleteVideoPlaylist(videoPlaylistInstance, t)

    logger.info('Video playlist %s deleted.', videoPlaylistInstance.uuid)
  })

  return res.type('json').status(204).end()
}

async function addVideoInPlaylist (req: express.Request, res: express.Response) {
  const body: VideoPlaylistElementCreate = req.body
  const videoPlaylist = res.locals.videoPlaylist
  const video = res.locals.video

  const playlistElement: VideoPlaylistElementModel = await sequelizeTypescript.transaction(async t => {
    const position = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id, t)

    const playlistElement = await VideoPlaylistElementModel.create({
      url: getVideoPlaylistElementActivityPubUrl(videoPlaylist, video),
      position,
      startTimestamp: body.startTimestamp || null,
      stopTimestamp: body.stopTimestamp || null,
      videoPlaylistId: videoPlaylist.id,
      videoId: video.id
    }, { transaction: t })

    videoPlaylist.changed('updatedAt', true)
    await videoPlaylist.save({ transaction: t })

    await sendUpdateVideoPlaylist(videoPlaylist, t)

    return playlistElement
  })

  // If the user did not set a thumbnail, automatically take the video thumbnail
  if (videoPlaylist.hasThumbnail() === false) {
    logger.info('Generating default thumbnail to playlist %s.', videoPlaylist.url)

    const inputPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getMiniature().filename)
    const thumbnailModel = await createPlaylistMiniatureFromExisting(inputPath, videoPlaylist, true)

    thumbnailModel.videoPlaylistId = videoPlaylist.id

    await thumbnailModel.save()
  }

  logger.info('Video added in playlist %s at position %d.', videoPlaylist.uuid, playlistElement.position)

  return res.json({
    videoPlaylistElement: {
      id: playlistElement.id
    }
  }).end()
}

async function updateVideoPlaylistElement (req: express.Request, res: express.Response) {
  const body: VideoPlaylistElementUpdate = req.body
  const videoPlaylist = res.locals.videoPlaylist
  const videoPlaylistElement = res.locals.videoPlaylistElement

  const playlistElement: VideoPlaylistElementModel = await sequelizeTypescript.transaction(async t => {
    if (body.startTimestamp !== undefined) videoPlaylistElement.startTimestamp = body.startTimestamp
    if (body.stopTimestamp !== undefined) videoPlaylistElement.stopTimestamp = body.stopTimestamp

    const element = await videoPlaylistElement.save({ transaction: t })

    videoPlaylist.changed('updatedAt', true)
    await videoPlaylist.save({ transaction: t })

    await sendUpdateVideoPlaylist(videoPlaylist, t)

    return element
  })

  logger.info('Element of position %d of playlist %s updated.', playlistElement.position, videoPlaylist.uuid)

  return res.type('json').status(204).end()
}

async function removeVideoFromPlaylist (req: express.Request, res: express.Response) {
  const videoPlaylistElement = res.locals.videoPlaylistElement
  const videoPlaylist = res.locals.videoPlaylist
  const positionToDelete = videoPlaylistElement.position

  await sequelizeTypescript.transaction(async t => {
    await videoPlaylistElement.destroy({ transaction: t })

    // Decrease position of the next elements
    await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, positionToDelete, null, -1, t)

    videoPlaylist.changed('updatedAt', true)
    await videoPlaylist.save({ transaction: t })

    await sendUpdateVideoPlaylist(videoPlaylist, t)

    logger.info('Video playlist element %d of playlist %s deleted.', videoPlaylistElement.position, videoPlaylist.uuid)
  })

  return res.type('json').status(204).end()
}

async function reorderVideosPlaylist (req: express.Request, res: express.Response) {
  const videoPlaylist = res.locals.videoPlaylist
  const body: VideoPlaylistReorder = req.body

  const start: number = body.startPosition
  const insertAfter: number = body.insertAfterPosition
  const reorderLength: number = body.reorderLength || 1

  if (start === insertAfter) {
    return res.status(204).end()
  }

  // Example: if we reorder position 2 and insert after position 5 (so at position 6): # 1 2 3 4 5 6 7 8 9
  //  * increase position when position > 5 # 1 2 3 4 5 7 8 9 10
  //  * update position 2 -> position 6 # 1 3 4 5 6 7 8 9 10
  //  * decrease position when position position > 2 # 1 2 3 4 5 6 7 8 9
  await sequelizeTypescript.transaction(async t => {
    const newPosition = insertAfter + 1

    // Add space after the position when we want to insert our reordered elements (increase)
    await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, newPosition, null, reorderLength, t)

    let oldPosition = start

    // We incremented the position of the elements we want to reorder
    if (start >= newPosition) oldPosition += reorderLength

    const endOldPosition = oldPosition + reorderLength - 1
    // Insert our reordered elements in their place (update)
    await VideoPlaylistElementModel.reassignPositionOf(videoPlaylist.id, oldPosition, endOldPosition, newPosition, t)

    // Decrease positions of elements after the old position of our ordered elements (decrease)
    await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, oldPosition, null, -reorderLength, t)

    videoPlaylist.changed('updatedAt', true)
    await videoPlaylist.save({ transaction: t })

    await sendUpdateVideoPlaylist(videoPlaylist, t)
  })

  logger.info(
    'Reordered playlist %s (inserted after %d elements %d - %d).',
    videoPlaylist.uuid, insertAfter, start, start + reorderLength - 1
  )

  return res.type('json').status(204).end()
}

async function getVideoPlaylistVideos (req: express.Request, res: express.Response) {
  const videoPlaylistInstance = res.locals.videoPlaylist
  const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined

  const resultList = await VideoModel.listForApi({
    followerActorId,
    start: req.query.start,
    count: req.query.count,
    sort: 'VideoPlaylistElements.position',
    includeLocalVideos: true,
    categoryOneOf: req.query.categoryOneOf,
    licenceOneOf: req.query.licenceOneOf,
    languageOneOf: req.query.languageOneOf,
    tagsOneOf: req.query.tagsOneOf,
    tagsAllOf: req.query.tagsAllOf,
    filter: req.query.filter,
    nsfw: buildNSFWFilter(res, req.query.nsfw),
    withFiles: false,
    videoPlaylistId: videoPlaylistInstance.id,
    user: res.locals.oauth ? res.locals.oauth.token.User : undefined
  })

  const additionalAttributes = { playlistInfo: true }
  return res.json(getFormattedObjects(resultList.data, resultList.total, { additionalAttributes }))
}