Compare commits

...

2 Commits

Author SHA1 Message Date
2de5770939 BMC: Save FCM Token 2022-11-24 18:59:33 +05:30
057349ec60 BMC: Implement Firebase SendNotification API 2022-11-24 11:51:04 +05:30
23 changed files with 6750 additions and 4 deletions

View File

@ -18,6 +18,7 @@
<Folder Include="bin\Debug\net6.0\ref\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="FirebaseAdmin" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNet.Mvc" Version="5.2.9" />
<PackageReference Include="Microsoft.AspNet.WebApi.Core" Version="5.2.9" />
</ItemGroup>

View File

@ -172,6 +172,20 @@ namespace BCS.BMC.CompanyMasters
.Where(m => m.Id == input.Id && m.CompanyName.ToLower().Trim() == input.CompanyName.ToLower().Trim() && m.Id != input.Id)
select m;
input.MapTo(entity);
Uri uri = new Uri(input.Url, UriKind.Absolute);
var host = uri.Host;
if (host.Split('.').Length > 2)
{
int lastIndex = host.LastIndexOf(".");
int index = host.LastIndexOf(".", lastIndex - 1);
var subdomain = host.Substring(0, index);
if (subdomain != "www")
{
entity.SubDomainName = subdomain;
}
}
entity.DomainName = host;
if (getclient == null || getclient.Count() == 0)
{
await _companyMaster.UpdateAsync(entity);

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BCS.BMC.FirebaseCloudMessaging.Dto
{
public class FcmNotificationSetting
{
public string SenderId { get; set; }
public string ServerKey { get; set; }
}
}

View File

@ -0,0 +1,17 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BCS.BMC.FirebaseCloudMessaging.Dto
{
public class FireBaseResponseModel
{
[JsonProperty("isSuccess")]
public bool IsSuccess { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
}
}

View File

@ -0,0 +1,38 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BCS.BMC.FirebaseCloudMessaging.Dto
{
public class NotificationModel
{
[JsonProperty("deviceId")]
public string DeviceId { get; set; }
[JsonProperty("isAndroidDevice")]
public bool IsAndroidDevice { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("body")]
public string Body { get; set; }
}
public class GoogleNotification
{
public class DataPayload
{
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("body")]
public string Body { get; set; }
}
[JsonProperty("priority")]
public string Priority { get; set; } = "high";
[JsonProperty("data")]
public DataPayload Data { get; set; }
[JsonProperty("notification")]
public DataPayload Notification { get; set; }
}
}

View File

@ -0,0 +1,44 @@
using FirebaseAdmin.Messaging;
using System.Threading.Tasks;
using FirebaseAdmin;
using Google.Apis.Auth.OAuth2;
using System;
namespace BCS.BMC.FirebaseCloudMessaging
{
public class FirebaseNotificationAppService : IFirebaseNotificationAppService
{
public FirebaseNotificationAppService()
{
if (FirebaseApp.DefaultInstance is null)
{
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile("firechat-57601-firebase-adminsdk-anscp-e04366c4d4.json")
});
}
}
public static async Task<string> SendNotification(string fcmToken, Notification notification)
{
try
{
var message = new Message()
{
Notification = notification,
Token = fcmToken,
};
return await FirebaseMessaging.DefaultInstance.SendAsync(message) ;
}
catch(Exception ex)
{
throw ex;
}
}
}
}

View File

@ -0,0 +1,11 @@
using Abp.Application.Services;
using FirebaseAdmin.Messaging;
using System.Threading.Tasks;
namespace BCS.BMC.FirebaseCloudMessaging
{
public interface IFirebaseNotificationAppService : IApplicationService
{
// Task<string> SendNotification(string fcmToken, Notification notification);
}
}

View File

@ -0,0 +1,30 @@
using Abp.Domain.Entities.Auditing;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BCS.BMC.BMC.FirebaseCloudMessages
{
[Table("FirebaseCloudMessageDetails")]
public class FirebaseCloudMessageDetails : FullAuditedEntity
{
public const int SenderNameMaxLength = 32;
public const int SenderImageurlMaxLength = 256;
public const int FcmTokenMaxLength = 512;
public int Id { get; set; }
public int UserId { get; set; }
[MaxLength(FcmTokenMaxLength)]
public string FcmToken { get; set; }
[MaxLength(SenderImageurlMaxLength)]
public string SenderImageurl { get; set; }
[MaxLength(SenderNameMaxLength)]
public string SenderName { get; set; }
public DateTime? MessageSentDateTime { get; set; }
public bool Status { get; set; }
public string Message { get; set; }
}
}

View File

@ -0,0 +1,21 @@
using Abp.Domain.Entities.Auditing;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BCS.BMC.BMC.FirebaseCloudMessages
{
[Table("FirebaseToken")]
public class FirebaseToken : FullAuditedEntity
{
public const int HostNameMaxLength = 512;
public int? UserId { get; set; }
[MaxLength(HostNameMaxLength)]
public string HostName { get; set; }
public string FcmToken { get; set; }
}
}

View File

@ -4,6 +4,7 @@ using BCS.BMC.Authorization.Roles;
using BCS.BMC.Authorization.Users;
using BCS.BMC.MultiTenancy;
using BCS.BMC.BMC.CompanyMasters;
using BCS.BMC.BMC.FirebaseCloudMessages;
namespace BCS.BMC.EntityFrameworkCore
{
@ -11,7 +12,8 @@ namespace BCS.BMC.EntityFrameworkCore
{
/* Define a DbSet for each entity of the application */
public virtual DbSet<CompanyMaster> CompanyMasters { get; set; }
public virtual DbSet<FirebaseCloudMessageDetails> FirebaseCloudMessageDetail { get; set; }
public virtual DbSet<FirebaseToken> FirebaseTokens { get; set; }
public BMCDbContext(DbContextOptions<BMCDbContext> options)
: base(options)
{

View File

@ -0,0 +1,45 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BCS.BMC.Migrations
{
public partial class FirebaeCloudMessageDetails : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "FirebaseCloudMessageDetails",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
UserId = table.Column<int>(type: "int", nullable: false),
FcmToken = table.Column<string>(type: "nvarchar(512)", maxLength: 512, nullable: true),
SenderImageurl = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
SenderName = table.Column<string>(type: "nvarchar(32)", maxLength: 32, nullable: true),
MessageSentDateTime = table.Column<DateTime>(type: "datetime2", nullable: true),
Status = table.Column<bool>(type: "bit", nullable: false),
Message = table.Column<string>(type: "nvarchar(max)", nullable: true),
CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false),
CreatorUserId = table.Column<long>(type: "bigint", nullable: true),
LastModificationTime = table.Column<DateTime>(type: "datetime2", nullable: true),
LastModifierUserId = table.Column<long>(type: "bigint", nullable: true),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
DeleterUserId = table.Column<long>(type: "bigint", nullable: true),
DeletionTime = table.Column<DateTime>(type: "datetime2", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_FirebaseCloudMessageDetails", x => x.Id);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "FirebaseCloudMessageDetails");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,41 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BCS.BMC.Migrations
{
public partial class FirebaseToken : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "FirebaseToken",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
UserId = table.Column<int>(type: "int", nullable: true),
HostName = table.Column<string>(type: "nvarchar(512)", maxLength: 512, nullable: true),
FcmToken = table.Column<string>(type: "nvarchar(max)", nullable: true),
CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false),
CreatorUserId = table.Column<long>(type: "bigint", nullable: true),
LastModificationTime = table.Column<DateTime>(type: "datetime2", nullable: true),
LastModifierUserId = table.Column<long>(type: "bigint", nullable: true),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
DeleterUserId = table.Column<long>(type: "bigint", nullable: true),
DeletionTime = table.Column<DateTime>(type: "datetime2", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_FirebaseToken", x => x.Id);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "FirebaseToken");
}
}
}

View File

@ -0,0 +1,19 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BCS.BMC.Migrations
{
public partial class RemoveIdFrom_FirebaseToken : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}

View File

@ -1613,6 +1613,108 @@ namespace BCS.BMC.Migrations
b.ToTable("CompanyMaster");
});
modelBuilder.Entity("BCS.BMC.BMC.FirebaseCloudMessages.FirebaseCloudMessageDetails", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("FcmToken")
.HasMaxLength(512)
.HasColumnType("nvarchar(512)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<string>("Message")
.HasColumnType("nvarchar(max)");
b.Property<DateTime?>("MessageSentDateTime")
.HasColumnType("datetime2");
b.Property<string>("SenderImageurl")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("SenderName")
.HasMaxLength(32)
.HasColumnType("nvarchar(32)");
b.Property<bool>("Status")
.HasColumnType("bit");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("FirebaseCloudMessageDetails");
});
modelBuilder.Entity("BCS.BMC.BMC.FirebaseCloudMessages.FirebaseToken", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<long?>("CreatorUserId")
.HasColumnType("bigint");
b.Property<long?>("DeleterUserId")
.HasColumnType("bigint");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<string>("FcmToken")
.HasColumnType("nvarchar(max)");
b.Property<string>("HostName")
.HasMaxLength(512)
.HasColumnType("nvarchar(512)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2");
b.Property<long?>("LastModifierUserId")
.HasColumnType("bigint");
b.Property<int?>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("FirebaseToken");
});
modelBuilder.Entity("BCS.BMC.MultiTenancy.Tenant", b =>
{
b.Property<int>("Id")

View File

@ -29,6 +29,7 @@ using System.Text;
using System.IO;
using Abp.AutoMapper;
using Abp.Domain.Entities;
using BCS.BMC.BMC.FirebaseCloudMessages;
namespace BCS.BMC.Controllers
{
@ -43,6 +44,7 @@ namespace BCS.BMC.Controllers
private readonly IExternalAuthManager _externalAuthManager;
private readonly UserRegistrationManager _userRegistrationManager;
private readonly IRepository<CompanyMaster, int> _companyMaster;
private readonly IRepository<FirebaseToken, int> _firebaseToken;
ResponseMessageModel responsemessage = new ResponseMessageModel();
public TokenAuthController(
LogInManager logInManager,
@ -52,7 +54,8 @@ namespace BCS.BMC.Controllers
IExternalAuthConfiguration externalAuthConfiguration,
IExternalAuthManager externalAuthManager,
UserRegistrationManager userRegistrationManager,
IRepository<CompanyMaster, int> companyMaster)
IRepository<CompanyMaster, int> companyMaster,
IRepository<FirebaseToken, int> firebaseToken)
{
_logInManager = logInManager;
_tenantCache = tenantCache;
@ -62,6 +65,7 @@ namespace BCS.BMC.Controllers
_externalAuthManager = externalAuthManager;
_userRegistrationManager = userRegistrationManager;
_companyMaster = companyMaster;
_firebaseToken = firebaseToken;
}
[HttpPost]
@ -314,6 +318,23 @@ namespace BCS.BMC.Controllers
{
var responseStream = await response.Content.ReadAsStringAsync();
LoginOrRegisterResponseMessageModel result = JsonConvert.DeserializeObject<LoginOrRegisterResponseMessageModel>(responseStream);
var getTokenDetails = _firebaseToken.GetAllList().Where(x => x.HostName == host && x.UserId == int.Parse(result.result.userId)).FirstOrDefault();
if (getTokenDetails is null)
{
FirebaseToken entity = new FirebaseToken();
entity.UserId = int.Parse(result.result.userId);
entity.HostName = host;
entity.FcmToken = input.FcmToken;
await _firebaseToken.InsertAndGetIdAsync(entity);
}
if (getTokenDetails != null)
{
FirebaseToken entity = new FirebaseToken();
getTokenDetails.FcmToken = input.FcmToken;
await _firebaseToken.UpdateAsync(getTokenDetails);
}
return Ok(result);
}
else if (response.StatusCode == HttpStatusCode.InternalServerError)

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BCS.BMC.BMC.CompanyMasters;
using Abp.AutoMapper;
using BCS.BMC.BMC.FirebaseCloudMessages;
namespace BCS.BMC.Models.TokenAuth
{
[AutoMap(typeof(FirebaseToken))]
public class CreateOrUpdateFireBaseModel
{
public int? UserId { get; set; }
public string HostName { get; set; }
public string FcmToken { get; set; }
}
}

View File

@ -11,5 +11,6 @@ namespace BCS.BMC.Models.TokenAuth
public string CompanyUrl { get; set; }
public string UsernameOrEmailAddress { get; set; }
public string Password { get; set; }
public string FcmToken { get; set; }
}
}

View File

@ -42,6 +42,7 @@
<PackageReference Include="Abp.HangFire" Version="7.3.0" />
<PackageReference Include="Abp.RedisCache" Version="7.3.0" />
<PackageReference Include="Abp.Castle.Log4Net" Version="7.3.0" />
<PackageReference Include="FirebaseAdmin" Version="2.3.0" />
</ItemGroup>
<ItemGroup>
<Folder Include="wwwroot\libs\" />

View File

@ -0,0 +1,29 @@
using BCS.BMC.Controllers;
using BCS.BMC.FirebaseCloudMessaging;
using FirebaseAdmin.Messaging;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace BCS.BMC.Web.Controllers
{
//[Route("api/notification")]
//[ApiController]
public class FirebaseNotificationController : BMCControllerBase
{
private readonly FirebaseNotificationAppService _notificationService;
public FirebaseNotificationController(FirebaseNotificationAppService notificationService)
{
_notificationService = notificationService;
}
[Route("send")]
[HttpPost]
public async Task<IActionResult> Notification(string fcmToken, [FromBody] Notification notification)
{
var result = await FirebaseNotificationAppService.SendNotification(fcmToken, notification);
return Ok(result);
}
}
}

View File

@ -0,0 +1,12 @@
{
"type": "service_account",
"project_id": "firechat-57601",
"private_key_id": "e04366c4d4ad7167925421faaf7daf868cd5c686",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCZwdt1kWg3mX8/\nXAdaECug6Kp9d3cfXshJLjZRtzUyeC7nkE10Ld0hhgxUH/5Fopu2vjTM0eq3NSNi\nte2ulpcEf4yObF5ZQEIeBvdf7uhvnvk1T+o/OcldkFyybWxSzCLwHWrS+eNkxKKP\nCbpXQuZ5v5g95p9FGFr9zM29gMB1FH1l0IiOh5UwGpTo39Glsdalw7OFDKYkWl0u\noGQ0qsO+As/MQKyYw4cJqIz6h8CX4WuloZhfKLv+KW8jwjN01UrlRNJQiJazSHYV\nLb9sP9WkGnVRnhXNtUy/vy6Cd5xSmd1wCPByNao04tlXPdBSwydqPsBmFjsSUX9V\nYg9Y5X6dAgMBAAECggEAEPr6x0TJXf04CKxGLOkaQwlO7XpIZTuCIlWAhDfCdTzB\nRADeEkA6ap2zi4WDqaG9UUo3lI3I6SDCNAA5gTgk8hyP+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n7vPIsrfNuONkc13uhWF4YtvANcx2rhLxma84Ey5Ai2kvx6fer+BRRK3Wr36n3AEw\nssODLddJnZESSdlIdsghLw==\n-----END PRIVATE KEY-----\n",
"client_email": "firebase-adminsdk-anscp@firechat-57601.iam.gserviceaccount.com",
"client_id": "101896998053383660888",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-anscp%40firechat-57601.iam.gserviceaccount.com"
}