/// <summary> /// Takes messages out of a queue and sends them to the server. /// </summary> public async Task ProcessSendQueue() { Logger.Log(Logger.Level.Debug, "Send process started"); // Create a variable to store messages to send PackedMessage SendData = null; try { //// Don't run this time if there aren't any messages to acknowledge //if (PendingAcks.Any()) //{ // // Take all the required acks out of the bag // var acks = new List<long>(); // while (PendingAcks.TryTake(out var ack)) acks.Add(ack); // Logger.Log(Logger.Level.Debug, $"Found {acks.Count} messages that need acknowledgement. Adding them to the payload."); // // Create a request that contains the list of acks // var Acks_Request = new RequestState(Schema.msgs_ack(new { msg_ids = acks })); // // Add the request to both the send queue (to be sent to the server) and // // the sent acks queue (in case we need to resend. We don't want to place // // in pending since there shouldn't be a response. // SendQueue.Add(Acks_Request); // SentAcks.Put(Acks_Request); //} // Get messages if possible if ((SendData = SendQueue.Get()) == null) { // If not, stop processing Logger.Log(Logger.Level.Debug, $"There are no requests to send."); return; } // Add all non-ack messages to a queue // Note: The queue contains messages that require a response // from the server. Acks do not and, if added, would sit forever // ToDo: add support for AddRange SendData.Batch .Where(x => (string)x.Request["_"] != "msgs_ack") .ToList().ForEach(x => PendingQueue[x.MessageID] = x); var encrypted = State.EncryptMessageData(SendData.Data); var decrypted = State.DecryptMessageData(encrypted, true); // Send the messages to the server await Connection.Send(encrypted); Logger.Log(Logger.Level.Debug, $"There are now {PendingQueue.Count} pending requests"); } catch (Exception ex) { var sad = new RequestFailedException("Sending the requests to Telegram failed", ex); Logger.Log(sad); // Determine if there were messages in context if (SendData != null) { // If so, fail them with the same exception Logger.Log(Logger.Level.Error, $"Failing the current requests\n\n{ex.Message}"); SendData.Batch.ToList().ForEach(x => x.Response.TrySetException(sad)); } } }