PageRenderTime 52ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/src/Server/DeviceHive.API/Controllers/DeviceNotificationPollController.cs

https://github.com/oryol/devicehive-.net
C# | 57 lines | 38 code | 6 blank | 13 comment | 4 complexity | 63e81627b7f39f05d0d186752f701bfb MD5 | raw file
Possible License(s): MIT
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Http;
  6. using System.Web.Http;
  7. using DeviceHive.API.Business;
  8. using DeviceHive.API.Filters;
  9. using DeviceHive.API.Mapping;
  10. using DeviceHive.Data.Model;
  11. using Newtonsoft.Json.Linq;
  12. using Ninject;
  13. namespace DeviceHive.API.Controllers
  14. {
  15. /// <resource cref="DeviceNotification" />
  16. public class DeviceNotificationPollController : BaseController
  17. {
  18. private ObjectWaiter<DeviceNotification> _notificationWaiter;
  19. private static readonly TimeSpan _timeout = TimeSpan.FromSeconds(30);
  20. public DeviceNotificationPollController(ObjectWaiter<DeviceNotification> notificationWaiter)
  21. {
  22. _notificationWaiter = notificationWaiter;
  23. }
  24. /// <name>poll</name>
  25. /// <summary>
  26. /// <para>Polls new device notifications.</para>
  27. /// <para>This method returns all device notifications that were created after specified timestamp.</para>
  28. /// <para>In the case when no notifications were found, the method blocks until new notification is received.
  29. /// The blocking period is limited (currently 30 seconds), and the server returns empty response if no notifications are received.
  30. /// In this case, to continue polling, the client should repeat the call with the same timestamp value.
  31. /// </para>
  32. /// </summary>
  33. /// <param name="deviceGuid">Device unique identifier.</param>
  34. /// <param name="timestamp">Timestamp of the last received notification (UTC). If not specified, the server's timestamp is taken instead.</param>
  35. /// <returns cref="DeviceNotification">If successful, this method returns array of <see cref="DeviceNotification"/> resources in the response body.</returns>
  36. [AuthorizeUser]
  37. public JArray Get(Guid deviceGuid, DateTime? timestamp = null)
  38. {
  39. var device = DataContext.Device.Get(deviceGuid);
  40. if (device == null || !IsNetworkAccessible(device.NetworkID))
  41. ThrowHttpResponse(HttpStatusCode.NotFound, "Device not found!");
  42. var start = timestamp != null ? timestamp.Value.AddTicks(10) : DateTime.UtcNow;
  43. var result = _notificationWaiter.WaitForObjects(device.ID, () => DataContext.DeviceNotification.GetByDevice(device.ID, start, null), _timeout);
  44. return new JArray(result.Select(n => Mapper.Map(n)));
  45. }
  46. private IJsonMapper<DeviceNotification> Mapper
  47. {
  48. get { return GetMapper<DeviceNotification>(); }
  49. }
  50. }
  51. }