|
| 1 | +using Newtonsoft.Json.Linq; |
| 2 | +using System; |
| 3 | +using System.Collections.Generic; |
| 4 | +using System.Linq; |
| 5 | +using System.Net; |
| 6 | +using System.Net.Http; |
| 7 | +using System.Text; |
| 8 | +using System.Threading; |
| 9 | +using System.Threading.Tasks; |
| 10 | + |
| 11 | +namespace WebUntisAPI.Client |
| 12 | +{ |
| 13 | + public partial class WebUntisClient |
| 14 | + { |
| 15 | + /// <summary> |
| 16 | + /// Get the count of unread messages |
| 17 | + /// </summary> |
| 18 | + /// <param name="ct">Cancellation token</param> |
| 19 | + /// <returns>The count of unread messages</returns> |
| 20 | + /// <exception cref="ObjectDisposedException">Thrown when the instance was disposed</exception> |
| 21 | + /// <exception cref="UnauthorizedAccessException">Thrown when you're logged in</exception> |
| 22 | + /// <exception cref="HttpRequestException">Thrown when an error happened while the http request</exception> |
| 23 | + public async Task<int> GetUnreadMessagesCountAsync(CancellationToken ct = default) |
| 24 | + { |
| 25 | + // Check for disposing |
| 26 | + if (_disposedValue) |
| 27 | + throw new ObjectDisposedException(GetType().FullName); |
| 28 | + |
| 29 | + // Check if you logged in |
| 30 | + if (!LoggedIn) |
| 31 | + throw new UnauthorizedAccessException("You're not logged in"); |
| 32 | + |
| 33 | + HttpRequestMessage request = new HttpRequestMessage() |
| 34 | + { |
| 35 | + Method = HttpMethod.Get, |
| 36 | + RequestUri = new Uri(ServerUrl + "/WebUntis/api/rest/view/v1/messages/status") |
| 37 | + }; |
| 38 | + SetRequestHeader(request.Headers, true); |
| 39 | + |
| 40 | + HttpResponseMessage response = await _client.SendAsync(request, ct); |
| 41 | + |
| 42 | + // Check cancellation token |
| 43 | + if (ct.IsCancellationRequested) |
| 44 | + return default; |
| 45 | + |
| 46 | + // Verify response |
| 47 | + if (response.StatusCode != HttpStatusCode.OK) |
| 48 | + throw new HttpRequestException($"There was an error while the http request (Code: {response.StatusCode})."); |
| 49 | + |
| 50 | + return JObject.Parse(await response.Content.ReadAsStringAsync()).Value<int>("unreadMessagesCount"); |
| 51 | + } |
| 52 | + } |
| 53 | +} |
0 commit comments