aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/controllers/api/video-channel-sync.ts
blob: 03c54b59cb15b668cae2a46b11448527d2c4eae9 (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
import express from 'express'
import { auditLoggerFactory, getAuditIdFromRes, VideoChannelSyncAuditView } from '@server/helpers/audit-logger'
import { logger } from '@server/helpers/logger'
import {
  asyncMiddleware,
  asyncRetryTransactionMiddleware,
  authenticate,
  ensureCanManageChannelOrAccount,
  ensureSyncExists,
  ensureSyncIsEnabled,
  videoChannelSyncValidator
} from '@server/middlewares'
import { VideoChannelSyncModel } from '@server/models/video/video-channel-sync'
import { MChannelSyncFormattable } from '@server/types/models'
import { HttpStatusCode, VideoChannelSyncState } from '@shared/models'

const videoChannelSyncRouter = express.Router()
const auditLogger = auditLoggerFactory('channel-syncs')

videoChannelSyncRouter.post('/',
  authenticate,
  ensureSyncIsEnabled,
  asyncMiddleware(videoChannelSyncValidator),
  ensureCanManageChannelOrAccount,
  asyncRetryTransactionMiddleware(createVideoChannelSync)
)

videoChannelSyncRouter.delete('/:id',
  authenticate,
  asyncMiddleware(ensureSyncExists),
  ensureCanManageChannelOrAccount,
  asyncRetryTransactionMiddleware(removeVideoChannelSync)
)

export { videoChannelSyncRouter }

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

async function createVideoChannelSync (req: express.Request, res: express.Response) {
  const syncCreated: MChannelSyncFormattable = new VideoChannelSyncModel({
    externalChannelUrl: req.body.externalChannelUrl,
    videoChannelId: req.body.videoChannelId,
    state: VideoChannelSyncState.WAITING_FIRST_RUN
  })

  await syncCreated.save()
  syncCreated.VideoChannel = res.locals.videoChannel

  auditLogger.create(getAuditIdFromRes(res), new VideoChannelSyncAuditView(syncCreated.toFormattedJSON()))

  logger.info(
    'Video synchronization for channel "%s" with external channel "%s" created.',
    syncCreated.VideoChannel.name,
    syncCreated.externalChannelUrl
  )

  return res.json({
    videoChannelSync: syncCreated.toFormattedJSON()
  })
}

async function removeVideoChannelSync (req: express.Request, res: express.Response) {
  const syncInstance = res.locals.videoChannelSync

  await syncInstance.destroy()

  auditLogger.delete(getAuditIdFromRes(res), new VideoChannelSyncAuditView(syncInstance.toFormattedJSON()))

  logger.info(
    'Video synchronization for channel "%s" with external channel "%s" deleted.',
    syncInstance.VideoChannel.name,
    syncInstance.externalChannelUrl
  )

  return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
}