You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SessionsController.cs 2.6 KiB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Threading.Tasks;
  6. using System.Web;
  7. using Microsoft.AspNetCore.Authorization;
  8. using Microsoft.AspNetCore.Mvc;
  9. using MQTTnet.Server.Mqtt;
  10. using MQTTnet.Server.Status;
  11. namespace MQTTnet.Server.Controllers
  12. {
  13. [Authorize]
  14. [ApiController]
  15. public class SessionsController : Controller
  16. {
  17. private readonly MqttServerService _mqttServerService;
  18. public SessionsController(MqttServerService mqttServerService)
  19. {
  20. _mqttServerService = mqttServerService ?? throw new ArgumentNullException(nameof(mqttServerService));
  21. }
  22. [Route("api/v1/sessions")]
  23. [HttpGet]
  24. public async Task<ActionResult<IList<IMqttSessionStatus>>> GetSessions()
  25. {
  26. return new ObjectResult(await _mqttServerService.GetSessionStatusAsync());
  27. }
  28. [Route("api/v1/sessions/{clientId}")]
  29. [HttpGet]
  30. public async Task<ActionResult<IMqttClientStatus>> GetSession(string clientId)
  31. {
  32. clientId = HttpUtility.UrlDecode(clientId);
  33. var session = (await _mqttServerService.GetSessionStatusAsync()).FirstOrDefault(c => c.ClientId == clientId);
  34. if (session == null)
  35. {
  36. return new StatusCodeResult((int)HttpStatusCode.NotFound);
  37. }
  38. return new ObjectResult(session);
  39. }
  40. [Route("api/v1/sessions/{clientId}")]
  41. [HttpDelete]
  42. public async Task<ActionResult> DeleteSession(string clientId)
  43. {
  44. clientId = HttpUtility.UrlDecode(clientId);
  45. var session = (await _mqttServerService.GetSessionStatusAsync()).FirstOrDefault(c => c.ClientId == clientId);
  46. if (session == null)
  47. {
  48. return new StatusCodeResult((int)HttpStatusCode.NotFound);
  49. }
  50. await session.DeleteAsync();
  51. return StatusCode((int)HttpStatusCode.NoContent);
  52. }
  53. [Route("api/v1/sessions/{clientId}/pendingApplicationMessages")]
  54. [HttpDelete]
  55. public async Task<ActionResult> DeletePendingApplicationMessages(string clientId)
  56. {
  57. clientId = HttpUtility.UrlDecode(clientId);
  58. var session = (await _mqttServerService.GetSessionStatusAsync()).FirstOrDefault(c => c.ClientId == clientId);
  59. if (session == null)
  60. {
  61. return new StatusCodeResult((int)HttpStatusCode.NotFound);
  62. }
  63. await session.ClearPendingApplicationMessagesAsync();
  64. return StatusCode((int)HttpStatusCode.NoContent);
  65. }
  66. }
  67. }