Skip to content

Commit

Permalink
Work in support of #381.
Browse files Browse the repository at this point in the history
  • Loading branch information
uncheckederror committed Aug 7, 2023
1 parent 7c62bf7 commit 643278e
Show file tree
Hide file tree
Showing 5 changed files with 202 additions and 28 deletions.
2 changes: 1 addition & 1 deletion Messaging.Tests/UnitTest1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ public async Task CorrectlyFormattedButInvalidMessage()
Assert.False(response.IsSuccessStatusCode);
Assert.True(response.StatusCode is System.Net.HttpStatusCode.BadRequest);
var message = await response.Content.ReadAsStringAsync();
Assert.Equal("\"To 14445556543 could not be parsed as valid NANP (North American Numbering Plan) numbers. msisdn:15555551212, ,to:14445556543, ,message:Your Lyft code is 12345, \"", message);
Assert.Equal("\"To 14445556543 could not be parsed as valid NANP (North American Numbering Plan) numbers. msisdn:15555551212,to:14445556543,message:Your Lyft code is 12345\"", message);
}

[Fact]
Expand Down
109 changes: 109 additions & 0 deletions Messaging/Migrations/20230807220201_ToFoward.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 29 additions & 0 deletions Messaging/Migrations/20230807220201_ToFoward.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace Messaging.Migrations
{
/// <inheritdoc />
public partial class ToFoward : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "ToForward",
table: "Messages",
type: "TEXT",
nullable: false,
defaultValue: "");
}

/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "ToForward",
table: "Messages");
}
}
}
4 changes: 4 additions & 0 deletions Messaging/Migrations/MessagingContextModelSnapshot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,10 @@ protected override void BuildModel(ModelBuilder modelBuilder)
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ToForward")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Messages");
Expand Down
86 changes: 59 additions & 27 deletions Messaging/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,18 @@

using Models;

using Org.BouncyCastle.Ocsp;

using Prometheus;

using Serilog;
using Serilog.Events;

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Security.Cryptography;
using System.ServiceModel.Channels;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.RateLimiting;

using static System.Runtime.InteropServices.JavaScript.JSType;

Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
Expand Down Expand Up @@ -560,6 +554,37 @@
});
await db.SaveChangesAsync();
}
// Forward failed incoming messages for this number.
var inboundMMS = await db.Messages.Where(x => x.To.Contains(asDialedNumber.DialedNumber) && x.MessageSource == MessageSource.Incoming && x.MessageType == MessageType.MMS).ToListAsync();
var inboundSMS = await db.Messages.Where(x => x.To.Contains(asDialedNumber.DialedNumber) && x.MessageSource == MessageSource.Incoming && x.MessageType == MessageType.SMS).ToListAsync();
inboundMMS.AddRange(inboundSMS);
foreach (var failedMessage in inboundMMS)
{
try
{
// Forward to the newly registered callback URL.
var messageToForward = System.Text.Json.JsonSerializer.Deserialize<ForwardedMessage>(failedMessage.ToForward);
if (messageToForward is not null && !string.IsNullOrWhiteSpace(messageToForward.Content))
{
messageToForward.ClientSecret = registration.ClientSecret;
var response = await registration.CallbackUrl.PostJsonAsync(messageToForward);
string responseText = await response.GetStringAsync();
Log.Information(responseText);
Log.Information(System.Text.Json.JsonSerializer.Serialize(messageToForward));
failedMessage.RawResponse = responseText;
failedMessage.Succeeded = true;
await db.SaveChangesAsync();
}
}
catch (Exception ex)
{
Log.Error(ex.Message);
Log.Error(ex.StackTrace ?? "No stack trace found.");
}
}
}
catch (Exception ex)
{
Expand Down Expand Up @@ -647,25 +672,25 @@

app.MapGet("/message/all/failed", async Task<Results<Ok<MessageRecord[]>, NotFound<string>, BadRequest<string>>> (MessagingContext db, DateTime start, DateTime end) =>
{
try
{
var messages = await db.Messages.Where(x => !x.Succeeded && x.DateReceivedUTC > start && x.DateReceivedUTC <= end).OrderByDescending(x => x.DateReceivedUTC).ToArrayAsync();
try
{
var messages = await db.Messages.Where(x => !x.Succeeded && x.DateReceivedUTC > start && x.DateReceivedUTC <= end).OrderByDescending(x => x.DateReceivedUTC).ToArrayAsync();
if (messages is not null && messages.Any())
{
return TypedResults.Ok(messages);
}
else
{
return TypedResults.NotFound($"No failed messages have been recorded between {start} and {end}.");
}
if (messages is not null && messages.Any())
{
return TypedResults.Ok(messages);
}
catch (Exception ex)
else
{
Log.Error(ex.Message);
Log.Error(ex.StackTrace ?? "No stack trace found.");
return TypedResults.BadRequest(ex.Message);
return TypedResults.NotFound($"No failed messages have been recorded between {start} and {end}.");
}
}
catch (Exception ex)
{
Log.Error(ex.Message);
Log.Error(ex.StackTrace ?? "No stack trace found.");
return TypedResults.BadRequest(ex.Message);
}
})
.RequireAuthorization().WithOpenApi(x => new(x) { Summary = "View all sent and received messages that failed.", Description = "This is intended to help you debug problems with message sending and delivery so you can see if it's this API or the upstream vendor that is causing problems." });

Expand Down Expand Up @@ -999,7 +1024,7 @@
//string timezone = context.Request.Form["timezone"].ToString();
//string origtime = context.Request.Form["origtime"].ToString();
string fullrecipientlist = context.Request.Form["FullRecipientList"].ToString();
string incomingRequest = string.Join(',', context.Request.Form.Select(x => $"{x.Key}:{x.Value}, "));
string incomingRequest = string.Join(',', context.Request.Form.Select(x => $"{x.Key}:{x.Value}"));
// The message field is a JSON object.
var MMSDescription = System.Text.Json.JsonSerializer.Deserialize<FirstPointMMSMessage>(message);
Expand Down Expand Up @@ -1156,9 +1181,11 @@
{
toForward.ClientSecret = client.ClientSecret;
var response = await client.CallbackUrl.PostJsonAsync(toForward);
Log.Information(await response.GetStringAsync());
string responseText = await response.GetStringAsync();
Log.Information(responseText);
Log.Information(System.Text.Json.JsonSerializer.Serialize(toForward));
messageRecord.RawResponse = System.Text.Json.JsonSerializer.Serialize(toForward);
messageRecord.ToForward = System.Text.Json.JsonSerializer.Serialize(toForward);
messageRecord.RawResponse = responseText;
messageRecord.Succeeded = true;
}
catch (FlurlHttpException ex)
Expand Down Expand Up @@ -1190,6 +1217,7 @@
messageRecord.To = toForward.To;
messageRecord.From = toForward.From;
messageRecord.ToForward = System.Text.Json.JsonSerializer.Serialize(toForward);
messageRecord.RawResponse = $"{toForward.To} is not registered as a client.";
db.Messages.Add(messageRecord);
await db.SaveChangesAsync();
Expand Down Expand Up @@ -1227,7 +1255,7 @@
//string timezone = context.Request.Form["timezone"].ToString();
//string origtime = context.Request.Form["origtime"].ToString();
string fullrecipientlist = context.Request.Form["FullRecipientList"].ToString();
string incomingRequest = string.Join(',', context.Request.Form.Select(x => $"{x.Key}:{x.Value}, "));
string incomingRequest = string.Join(',', context.Request.Form.Select(x => $"{x.Key}:{x.Value}"));
// Disabled because this secret value changes whenever.
//if (serversecret != firstPointIncomingSMSSecret)
Expand Down Expand Up @@ -1347,9 +1375,11 @@
{
toForward.ClientSecret = client.ClientSecret;
var response = await client.CallbackUrl.PostJsonAsync(toForward);
Log.Information(await response.GetStringAsync());
string responseText = await response.GetStringAsync();
Log.Information(responseText);
Log.Information(System.Text.Json.JsonSerializer.Serialize(toForward));
messageRecord.RawResponse = System.Text.Json.JsonSerializer.Serialize(toForward);
messageRecord.ToForward = System.Text.Json.JsonSerializer.Serialize(toForward);
messageRecord.RawResponse = responseText;
messageRecord.Succeeded = true;
}
catch (FlurlHttpException ex)
Expand Down Expand Up @@ -1380,6 +1410,7 @@
messageRecord.To = toForward.To;
messageRecord.From = toForward.From;
messageRecord.ToForward = System.Text.Json.JsonSerializer.Serialize(toForward);
messageRecord.RawResponse = $"{toForward.To} is not registered as a client.";
db.Messages.Add(messageRecord);
await db.SaveChangesAsync();
Expand Down Expand Up @@ -1568,6 +1599,7 @@ public class MessageRecord
public string RawRequest { get; set; } = string.Empty;
public string RawResponse { get; set; } = string.Empty;
public bool Succeeded { get; set; } = false;
public string ToForward { get; set; } = string.Empty;
}

// Format forward to client apps as JSON.
Expand Down

0 comments on commit 643278e

Please sign in to comment.