private async Task <PushoverUserResponse> PushoverPost(Uri uri, MultipartFormDataContent parameters) { using var Trace = new Trace(); //This c# 8.0 using feature will auto dispose when the function is done. PushoverUserResponse ret = new PushoverUserResponse(); if (this.httpClient == null) { this.httpClient = new HttpClient(); this.httpClient.Timeout = TimeSpan.FromSeconds(AppSettings.Settings.HTTPClientRemoteTimeoutSeconds); } // Remove content type that is not in the docs //foreach (HttpContent param in parameters) // param.Headers.ContentType = null; try { HttpResponseMessage response = null; string json = ""; response = await httpClient.PostAsync(uri, parameters); json = await response.Content.ReadAsStringAsync(); json = json.CleanString(); if (response.IsSuccessStatusCode && !string.IsNullOrWhiteSpace(json)) { //var json = this.Encoding.GetString(await wc.UploadValuesTaskAsync(uri, parameters).ConfigureAwait(false)); ret = await ParseResponse <PushoverUserResponse>(json, response.Headers); } else { if (response.StatusCode.ToString().Contains("TooLarge")) { ret.Errors = new string[] { $"StatusCode='{response.StatusCode}', Reason='{response.ReasonPhrase}' (Max pushover attachment size is 2.5MB), ResponseText='{json}'" }; } else { ret.Errors = new string[] { $"StatusCode='{response.StatusCode}', Reason='{response.ReasonPhrase}', ResponseText='{json}'" }; } } } catch (Exception ex) { AITOOL.Log($"Error: {ex.Msg()}"); ret.Errors = new string[] { ex.Msg() }; } return(ret); }
/// <summary> /// When Pushover returns an error it is returned in a (sort of...) structured format; this method tries to /// parse the result and extract possible information from it. /// </summary> private PushoverUserResponse ParseErrorResponse(HttpWebResponse response) { PushoverUserResponse errorresponse = null; try { using (var s = response.GetResponseStream()) using (var r = new StreamReader(s, this.Encoding)) { var json = r.ReadToEnd(); errorresponse = JsonConvert.DeserializeObject <PushoverUserResponse>(json); } errorresponse.RateLimitInfo = ParseRateLimitInfo(response.Headers); } catch { //NOP } return(errorresponse); }
/// <summary> /// Sends, asynchronously, the specified <see cref="Message"/> using Pushover to the specified device(s) of the /// specified user or group. /// </summary> /// <param name="message">The <see cref="Message"/> to send.</param> /// <param name="userOrGroup">The user or group id to send the message to.</param> /// <param name="deviceNames">The devicenames to send the message to.</param> /// <returns>Returns the <see cref="PushoverUserResponse"/> returned by the server.</returns> /// <seealso href="https://pushover.net/api#messages">Pushover API documentation</seealso> /// <exception cref="ArgumentNullException">Thrown when message or user/group arguments are null.</exception> /// <exception cref="InvalidKeyException">Thrown when an invalid user/group is specified.</exception> public async Task <PushoverUserResponse> SendPushoverMessageAsync(Message message, string userOrGroup, string[] deviceNames, ClsImageQueueItem CurImg) { using var Trace = new Trace(); //This c# 8.0 using feature will auto dispose when the function is done. PushoverUserResponse ret = new PushoverUserResponse(); try { (this.MessageValidator ?? new DefaultMessageValidator()).Validate("message", message); (this.UserOrGroupKeyValidator ?? new UserOrGroupKeyValidator()).Validate("userOrGroup", userOrGroup); if (deviceNames != null && deviceNames.Length > 0) { foreach (var device in deviceNames) { if (!string.IsNullOrWhiteSpace(device)) { (this.DeviceNameValidator ?? new DeviceNameValidator()).Validate("device", device); } } } MultipartFormDataContent parameters = new MultipartFormDataContent(); parameters.AddConditional("token", this.ApplicationKey); parameters.AddConditional("user", userOrGroup); parameters.AddConditional("message", message.Body); parameters.Add("priority", (int)message.Priority); parameters.AddConditional("device", deviceNames); parameters.AddConditional("title", message.Title); parameters.AddConditional("sound", message.Sound); parameters.AddConditional("html", message.IsHtmlBody); if (message.SupplementaryUrl != null) { parameters.Add("url", message.SupplementaryUrl.Uri); parameters.AddConditional("url_title", message.SupplementaryUrl.Title); } if (message.Priority == Priority.Emergency) { parameters.Add("retry", message.RetryOptions.RetryEvery); parameters.Add("expire", message.RetryOptions.RetryPeriod); parameters.Add("callback", message.RetryOptions.CallBackUrl); } if (message.Timestamp != null) { parameters.Add("timestamp", (int)(TimeZoneInfo.ConvertTimeToUtc(message.Timestamp.Value).Subtract(EPOCH).TotalSeconds)); } if (CurImg != null && CurImg.IsValid()) { StreamContent imageParameter = new StreamContent(CurImg.ToStream()); imageParameter.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg"); parameters.Add(imageParameter, "attachment", Path.GetFileName(CurImg.image_path)); } ret = await this.PushoverPost(GetV1APIUriFromBase("messages.json"), parameters); } catch (Exception ex) { AITOOL.Log($"Error: {ex.Msg()}"); ret.Errors = new string[] { ex.Msg() }; } return(ret); }