Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initiala ändringar för övergången från Firebase till Expo. #161

Draft
wants to merge 3 commits into
base: development
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 58 additions & 40 deletions Nexpo/Controllers/NotificationsController.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using FirebaseAdmin.Messaging;
//using FirebaseAdmin.Messaging;
using Google.Apis.Auth.OAuth2;
using FirebaseAdmin;
using Microsoft.AspNetCore.Mvc;
Expand All @@ -9,20 +9,34 @@
using Microsoft.AspNetCore.Http;
using Nexpo.DTO;
using Nexpo.Models;

using Nexpo.Repositories;
using System.Net.Http;
using System.Text;
using System.Text.Json;
namespace Nexpo.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class NotificationController : ControllerBase
{
private readonly INotificationRepository _notificationRepo;
private readonly IUserRepository _userRepo;

public NotificationController(
INotificationRepository iNotificationRepo,
IUserRepository iUserRepo
)
{
_notificationRepo = iNotificationRepo;
_userRepo = iUserRepo;
}

private static Queue<NotificationDTO> history;

static NotificationController()
{
history = new Queue<NotificationDTO>(10);
history.Enqueue(new NotificationDTO { Title = "Welcome", Message = "Welcome to the app", Topic = "all" });
history.Enqueue(new NotificationDTO { Title = "Welcome", Message = "Welcome to the app"});
}

/// <summary>
Expand All @@ -33,7 +47,7 @@ static NotificationController()
[HttpPost("register")]
[Authorize]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IActionResult> RegisterUser(RegisterUserDTO dto)
public async Task<IActionResult> RegisterUser(int id, RegisterUserDTO dto)
{
if (string.IsNullOrEmpty(dto.Token))
{
Expand All @@ -42,13 +56,11 @@ public async Task<IActionResult> RegisterUser(RegisterUserDTO dto)

try
{
var messaging = FirebaseMessaging.DefaultInstance;

var registrationTokens = new List<string> { dto.Token };

TopicManagementResponse response = await messaging.SubscribeToTopicAsync(registrationTokens, dto.Topic);


await _userRepo.AddToken(dto.Token, await _userRepo.Get(id));

return Ok(new { success = true, detail = "Successfully registered for topic" });

}
catch (Exception)
{
Expand All @@ -65,43 +77,49 @@ public async Task<IActionResult> RegisterUser(RegisterUserDTO dto)
[HttpPut]
[Authorize(Roles = nameof(Role.Administrator))]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IActionResult> NotifyAll(NotificationDTO dto)
{
if (string.IsNullOrEmpty(dto.Topic))
{
return BadRequest("Topic is required input.");
}
public async Task<IActionResult> Notify(NotificationDTO dto, Role role)
{

if (string.IsNullOrEmpty(dto.Message))
{
return BadRequest("Message is required input.");
}
if (string.IsNullOrEmpty(dto.Message))
{
return BadRequest("Message is required input.");
}

try
{
var messaging = FirebaseMessaging.DefaultInstance;
var message = new Message
{
Notification = new Notification { Title = dto.Title, Body = dto.Message },
Topic = dto.Topic
};
try
{
var client = new HttpClient();
var payload = new
{
to = dto.Token,
title = dto.Title,
body = dto.Message,
};

var result = await messaging.SendAsync(message);
var jsonPayload = JsonSerializer.Serialize(payload);
var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");

if (history.Count >= 10)
{
history.Dequeue();
}
history.Enqueue(dto);
var response = await client.PostAsync("https://exp.host/--/api/v2/push/send", content);

return Ok(new { success = true, detail = "Successfully sent notification" });
}
catch (Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError, new { success = false, detail = "An error occurred while sending notification" });
}
if (!response.IsSuccessStatusCode)
{
return StatusCode(StatusCodes.Status500InternalServerError, new { success = false, detail = "An error occurred while sending notification" });
}

if (history.Count >= 10)
{
history.Dequeue();
}
history.Enqueue(dto);

return Ok(new { success = true, detail = "Successfully sent notification" });

}
catch (Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError, new { success = false, detail = "An error occurred while sending notification" });
}
}

/// <summary>
/// Returns the past few notifications
/// At most 10 notifications will be stored at once
Expand Down
6 changes: 4 additions & 2 deletions Nexpo/DTO/Notifications/NotificationDTO.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.ComponentModel.DataAnnotations;

namespace Nexpo.DTO
Expand All @@ -8,10 +9,11 @@ public class NotificationDTO
public string Title { get; set; }

[Required]
public string Message { get; set; }
public string Token { get; set; }

[Required]
public string Topic { get; set; }
public string Message { get; set; }



}
Expand Down
2 changes: 1 addition & 1 deletion Nexpo/DTO/Notifications/RegisterUserDTO.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ public class RegisterUserDTO
public string Token { get; set; }

[Required]
public string Topic { get; set; }
public int UserId { get; set; }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Se: careerfairsystems/nexpo-app#351 (review)

tl;dr, att skicka upp UserId:t såhär, nog inte bästa idéen.

}
2 changes: 2 additions & 0 deletions Nexpo/Models/ApplicationDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ public class ApplicationDbContext : DbContext
public DbSet<Contact> Contacts { get; set; }
public DbSet<FrequentAskedQuestion> FrequentAskedQuestion { get; set; }

public DbSet<Notification> Notification { get; set; }
public DbSet<UserNotification> UserNotification { get; set; }
#pragma warning restore format

private readonly PasswordService _passwordService;
Expand Down
37 changes: 37 additions & 0 deletions Nexpo/Models/Notification.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json.Serialization;

namespace Nexpo.Models
{
/// <summary>
/// Represents a notification topic
/// </summary>
public class Notification
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int? Id { get; set; }

[Required]
public string Message { get; set; }
[Required]
public DateTime ScheduledTime { get; set; }
[Required]
public NotificationType Type { get; set; }
[Required]
public int? EventId { get; set; }




public enum NotificationType
{
General,
EventReminder,
InternalMessage,
}

}
}

2 changes: 2 additions & 0 deletions Nexpo/Models/User.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ public class User
public bool hasCv { get; set; }

public string profilePictureUrl { get; set; }

public string notificationToken { get; set; }
}

public enum Role
Expand Down
25 changes: 25 additions & 0 deletions Nexpo/Models/UserNotification.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json.Serialization;

namespace Nexpo.Models
{
/// <summary>
/// Represents a notification topic
/// </summary>
public class UserNotification
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
[Required]
[JsonIgnore]
public User User { get; set; }
[Required]
public int NotificationId { get; set; }
[Required]
[JsonIgnore]
public Notification Notification { get; set; }

}
}

64 changes: 64 additions & 0 deletions Nexpo/Repositories/NotificationRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
using Nexpo.Models;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System;

namespace Nexpo.Repositories
{
public interface INotificationRepository
{
public Task<Notification> Get(int id);
public Task Add(Notification _notification);
public Task Update(Notification _notification);
public Task Remove(Notification _notification);
public Task<List<Notification>> GetAllNotExpired(DateTime date, Notification.NotificationType type);
}

public class NotificationRepository : INotificationRepository
{
private readonly ApplicationDbContext _context;

public NotificationRepository(ApplicationDbContext context)
{
_context = context;
}

public Task<Notification> Get(int id)
{
return _context.Notification.FirstOrDefaultAsync(_notification => _notification.Id == id);
}
public async Task Add(Notification _notification)
{
_context.Notification.Add(_notification);
await _context.SaveChangesAsync();
}
public async Task Remove(Notification _notification)
{
_context.Notification.Remove(_notification);
await _context.SaveChangesAsync();
}
public Task Update(Notification _notification){
_context.Entry(_notification).State = EntityState.Modified;
return _context.SaveChangesAsync();

}
public async Task<List<Notification>> GetAllNotExpired(DateTime date, Notification.NotificationType type)
{
return await _context.Notification.Where(_notification => _notification.ScheduledTime > date && _notification.Type == type).ToListAsync();
}












}
}
52 changes: 52 additions & 0 deletions Nexpo/Repositories/UserNotificationRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using Nexpo.Models;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System;

namespace Nexpo.Repositories
{
public interface IUserNotificationRepository
{
public Task<UserNotification> Get(int userId, int notificationId);
public Task Add(UserNotification _userNotification);
public Task Update(UserNotification _userNotification);
public Task Remove(UserNotification _userNotification);

}

public class UserNotificationRepository : IUserNotificationRepository
{
private readonly ApplicationDbContext _context;

public UserNotificationRepository(ApplicationDbContext context)
{
_context = context;
}

public Task<UserNotification> Get(int userId, int notificationId)
{
return _context.UserNotification.FirstOrDefaultAsync(_userNotification => _userNotification.UserId == userId
&& _userNotification.NotificationId == notificationId);
}
public async Task Add(UserNotification _userNotification)
{
_context.UserNotification.Add(_userNotification);
await _context.SaveChangesAsync();
}
public async Task Remove(UserNotification _userNotification)
{
_context.UserNotification.Remove(_userNotification);
await _context.SaveChangesAsync();
}

public Task Update(UserNotification _userNotification){
_context.Entry(_userNotification).State = EntityState.Modified;
return _context.SaveChangesAsync();

}


}
}
7 changes: 7 additions & 0 deletions Nexpo/Repositories/UserRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public interface IUserRepository
public Task Add(User user);
public Task Remove(User user);
public Task Update(User user);
public Task AddToken(string Token, User user);
}

public class UserRepository : IUserRepository
Expand Down Expand Up @@ -66,5 +67,11 @@ public async Task Update(User user)
_context.Entry(user).State = EntityState.Modified;
await _context.SaveChangesAsync();
}

public async Task AddToken(string Token, User user)
{
user.notificationToken = Token;
await Update(user);
}
}
}
Loading