Skip to content

Commit 6b6ee73

Browse files
committed
Polishing
Delete scheduled notifications on deletion and completion of task
1 parent 3a1ecab commit 6b6ee73

6 files changed

Lines changed: 37 additions & 133 deletions

File tree

RequestTests.paw

0 Bytes
Binary file not shown.

src/SimpleToDoService/Common/PushNotificationScheduler.cs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,15 +32,17 @@ bool HasEqualDueDatest(Task task, PushNotification notification)
3232
return false;
3333
}
3434

35-
public async System.Threading.Tasks.Task SchedulePushNotification(Task task)
35+
public async System.Threading.Tasks.Task SchedulePushNotifications(Task task)
3636
{
3737
var currentNotification = task.PushNotifications.FirstOrDefault();
3838

39-
if (HasEqualDueDatest(task, currentNotification))
39+
if (!task.Completed && HasEqualDueDatest(task, currentNotification))
4040
return;
4141

4242
await DeletePushNotification(currentNotification);
43-
await CreatePushNotification(task);
43+
44+
if (!task.Completed)
45+
await CreatePushNotification(task);
4446
}
4547

4648
async System.Threading.Tasks.Task DeletePushNotification(PushNotification notification)

src/SimpleToDoService/Controllers/RootController.cs

Lines changed: 0 additions & 122 deletions
Original file line numberDiff line numberDiff line change
@@ -28,127 +28,5 @@ public IActionResult Get()
2828
{
2929
return Ok();
3030
}
31-
32-
[HttpPost("push2")]
33-
public async Task<IActionResult> Push2()
34-
{
35-
var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;
36-
37-
request.Method = "POST";
38-
request.ContentType = "application/json; charset=utf-8";
39-
request.Headers["authorization"] = "Basic NTNmZWI0MjktOWI2My00M2FiLTk1ZDQtMDljYjBhMjhhM2Vh";
40-
41-
var sendJson = JObject.FromObject(new {
42-
app_id = "ffe9789a-e9bc-4789-9cbb-4552664ba3fe",
43-
contents = new { en = "Test message" },
44-
filters = new [] { new { field = "tag", key = "custom", relation = "=", value = "tag" } },
45-
send_after = "2018-04-23 17:58:00 GMT+0300"
46-
});
47-
48-
var byteArray = Encoding.UTF8.GetBytes(sendJson.ToString());
49-
50-
try
51-
{
52-
using (var writer = await request.GetRequestStreamAsync())
53-
{
54-
writer.Write(byteArray, 0, byteArray.Length);
55-
}
56-
57-
using (var response = await request.GetResponseAsync())
58-
using (var reader = new StreamReader(response.GetResponseStream()))
59-
{
60-
var json = JObject.Parse(reader.ReadToEnd());
61-
System.Diagnostics.Debug.WriteLine(String.Format("id = {0}", json["id"]));
62-
}
63-
}
64-
catch (WebException ex)
65-
{
66-
System.Diagnostics.Debug.WriteLine(ex.Message);
67-
System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
68-
}
69-
70-
return Ok();
71-
}
72-
73-
[HttpGet("push")]
74-
public async Task<IActionResult> Push()
75-
{
76-
var deviceId = "LySqbodo7WMqWO24vEULM1x4na/sm43fYuNs9/eZHCs=";
77-
int port = 2195;
78-
string hostname = "gateway.sandbox.push.apple.com";
79-
//var hostname = "gateway.push.apple.com";
80-
81-
//I have removed certificate. Keep your certificate in wwwroot/certificate location. This location is not mandatory
82-
string certificatePath = "/Users/AntonEfimenko/Documents/Programming/todo-cert/cert-prod.pfx";
83-
//var clientCertificate = new X509Certificate2(certificatePath, "11", X509KeyStorageFlags.PersistKeySet);
84-
X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(certificatePath), "");
85-
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
86-
87-
TcpClient client = new TcpClient(AddressFamily.InterNetwork);
88-
await client.ConnectAsync(hostname, port);
89-
90-
91-
//SslStream sslStream = new SslStream(client.GetStream(), false);
92-
SslStream sslStream = new SslStream(
93-
client.GetStream(), false,
94-
new RemoteCertificateValidationCallback(ValidateServerCertificate),
95-
null);
96-
97-
try
98-
{
99-
await sslStream.AuthenticateAsClientAsync(hostname, certificatesCollection, SslProtocols.Tls, false);
100-
MemoryStream memoryStream = new MemoryStream();
101-
BinaryWriter writer = new BinaryWriter(memoryStream);
102-
writer.Write((byte)0);
103-
writer.Write((byte)0);
104-
writer.Write((byte)32);
105-
106-
writer.Write(Convert.FromBase64String(deviceId));
107-
string payload = "{\"aps\":{\"alert\":\"" + "Test message" + "\",\"badge\":0,\"sound\":\"default\"}}";
108-
writer.Write((byte)0);
109-
writer.Write((byte)payload.Length);
110-
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
111-
writer.Write(b1);
112-
writer.Flush();
113-
byte[] array = memoryStream.ToArray();
114-
sslStream.Write(array);
115-
sslStream.Flush();
116-
client.Dispose();
117-
}
118-
catch (Exception ex)
119-
{
120-
var m = ex.Message;
121-
throw ex;
122-
}
123-
finally
124-
{
125-
client.Dispose();
126-
}
127-
//catch// (AuthenticationException ex)
128-
//{
129-
// client.Dispose();
130-
//}
131-
//catch// (Exception e)
132-
//{
133-
// client.Dispose();
134-
//}
135-
136-
return Content("Notification sent. Check your device.");
137-
}
138-
139-
private static bool ValidateServerCertificate(
140-
object sender,
141-
X509Certificate certificate,
142-
X509Chain chain,
143-
SslPolicyErrors sslPolicyErrors)
144-
{
145-
if (sslPolicyErrors == SslPolicyErrors.None)
146-
return true;
147-
148-
Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
149-
150-
// Do not allow this client to communicate with unauthenticated servers.
151-
return false;
152-
}
15331
}
15432
}

src/SimpleToDoService/Controllers/TasksController.cs

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ public async System.Threading.Tasks.Task<IActionResult> Post([FromBody] Task ent
7171

7272
var created = repository.CreateTask(entry);
7373

74-
await new PushNotificationScheduler(repository).SchedulePushNotification(created);
74+
await new PushNotificationScheduler(repository).SchedulePushNotifications(created);
7575

7676
return CreatedAtRoute("GetTask", new { Uuid = created.Uuid }, created);
7777
}
@@ -95,27 +95,30 @@ public async System.Threading.Tasks.Task<IActionResult> Put(Guid? uuid, [FromBod
9595

9696
var reloaded = repository.Task(CurrentUserUuid, entry.Uuid);
9797

98-
await new PushNotificationScheduler(repository).SchedulePushNotification(reloaded);
98+
await new PushNotificationScheduler(repository).SchedulePushNotifications(reloaded);
9999

100100
return Ok(updated);
101101
}
102102

103103
[HttpDelete("{uuid:Guid?}")]
104-
public IActionResult Delete(Guid? uuid)
104+
public async System.Threading.Tasks.Task<IActionResult> Delete(Guid? uuid)
105105
{
106106
if (!uuid.HasValue)
107107
return BadRequest(new ServiceError() { Message = "Object Uuid not specified" });
108108

109-
var deleted = repository.DeleteTask(uuid.Value);
109+
var toDelete = repository.Task(CurrentUserUuid, uuid.Value);
110+
if(toDelete == null)
111+
return new NotFoundResult();
110112

111-
if (deleted)
112-
return new StatusCodeResult(204);
113+
toDelete.TargetDate = null;
114+
await new PushNotificationScheduler(repository).SchedulePushNotifications(toDelete);
113115

114-
return new NotFoundResult();
116+
repository.DeleteTask(toDelete);
117+
return new StatusCodeResult(204);
115118
}
116119

117120
[HttpPost("{uuid:Guid}/ChangeCompletionStatus/")]
118-
public IActionResult ChangeCompletionStatus(Guid uuid, [FromQuery] bool completed)
121+
public async System.Threading.Tasks.Task<IActionResult> ChangeCompletionStatus(Guid uuid, [FromQuery] bool completed)
119122
{
120123
var entry = repository.Task(CurrentUserUuid, uuid);
121124

@@ -125,6 +128,8 @@ public IActionResult ChangeCompletionStatus(Guid uuid, [FromQuery] bool complete
125128
entry.Completed = completed;
126129
repository.UpdateTask(entry);
127130

131+
await new PushNotificationScheduler(repository).SchedulePushNotifications(entry);
132+
128133
return Ok(entry);
129134
}
130135
}

src/SimpleToDoService/Database/Entities.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,9 @@ public class Task
9393
[ForeignKey("UserUuid")]
9494
public User User { get; set; }
9595

96+
[XmlIgnore]
97+
[JsonIgnore]
98+
[IgnoreDataMember]
9699
public IEnumerable<PushNotification> PushNotifications { get; set; }
97100
}
98101

src/SimpleToDoService/Database/Repositiory.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ public interface IToDoRepository
1616
Task CreateTask(Task task);
1717
Task UpdateTask(Task task);
1818
bool DeleteTask(Guid uuid);
19+
bool DeleteTask(Task task);
1920
User CreateUser(User user);
2021
bool DeleteUser(User user);
2122
User UpdateUser(User user);
@@ -96,6 +97,21 @@ public bool DeleteTask(Guid uuid)
9697
return true;
9798
}
9899

100+
public bool DeleteTask(Task task)
101+
{
102+
context.Tasks.Remove(task);
103+
try
104+
{
105+
context.SaveChanges();
106+
}
107+
catch (DbUpdateConcurrencyException)
108+
{
109+
// entity doesn't exists in this case
110+
return false;
111+
}
112+
return true;
113+
}
114+
99115
public User CreateUser(User user)
100116
{
101117
user.Uuid = new Guid();

0 commit comments

Comments
 (0)