push messages are sent upon user ids

This commit is contained in:
2019-05-24 20:17:24 +01:00
parent 00bcf6cd39
commit 04d167fcca
10 changed files with 128 additions and 89 deletions

View File

@ -10,6 +10,5 @@ namespace Yavsc
public const string Error = "error";
public const string ContactRefused = "contact refused";
public const string ExistingUserName ="existing user name";
public const string ServerMessage = "server message";
}
}

View File

@ -1,4 +1,4 @@

using System.Collections.Generic;
using System.Threading.Tasks;
using Yavsc.Interfaces.Workflow;
@ -11,18 +11,18 @@ namespace Yavsc.Services
public interface IYavscMessageSender
{
Task<MessageWithPayloadResponse> NotifyBookQueryAsync(
IEnumerable<string> DeviceIds,
IEnumerable<string> connectionIds,
RdvQueryEvent ev);
Task<MessageWithPayloadResponse> NotifyEstimateAsync(
IEnumerable<string> registrationId,
IEnumerable<string> connectionIds,
EstimationEvent ev);
Task<MessageWithPayloadResponse> NotifyHairCutQueryAsync(
IEnumerable<string> registrationId,
IEnumerable<string> connectionIds,
HairCutQueryEvent ev);
Task<MessageWithPayloadResponse> NotifyAsync(
IEnumerable<string> regids,
IEnumerable<string> connectionIds,
IEvent yaev);
}
}

View File

@ -57,7 +57,7 @@ namespace Yavsc.Models
/// </summary>
/// <returns></returns>
[InverseProperty("DeviceOwner"),JsonIgnore]
public virtual List<DeviceDeclaration> DeviceDeclarations { get; set; }
public virtual List<DeviceDeclaration> DeviceDeclaration { get; set; }
[InverseProperty("Owner"),JsonIgnore]
public virtual List<ChatConnection> Connections { get; set; }

View File

@ -108,7 +108,7 @@ namespace Yavsc.ApiControllers
public async Task<IActionResult> ProSign(string billingCode, long id)
{
var estimate = dbContext.Estimates.
Include(e=>e.Client).Include(e=>e.Client.DeviceDeclarations)
Include(e=>e.Client).Include(e=>e.Client.DeviceDeclaration)
.Include(e=>e.Bill).Include(e=>e.Owner).Include(e=>e.Owner.Performer)
.FirstOrDefault(e=>e.Id == id);
if (estimate == null)
@ -127,12 +127,10 @@ namespace Yavsc.ApiControllers
var yaev = new EstimationEvent(estimate,_localizer);
var regids = estimate.Client.DeviceDeclarations.Select(d => d.DeviceId).ToArray();
var regids = new [] { estimate.Client.Id };
bool gcmSent = false;
if (regids.Length>0) {
var grep = await _GCMSender.NotifyEstimateAsync(regids,yaev);
gcmSent = grep.success>0;
}
return Ok (new { ProviderValidationDate = estimate.ProviderValidationDate, GCMSent = gcmSent });
}

View File

@ -1,14 +1,19 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using System.Threading.Tasks;
using System.Security.Claims;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Identity;
using Yavsc.Models;
using Yavsc.ViewModels.Chat;
namespace Yavsc.Controllers
{
using Microsoft.AspNet.Identity;
using Models;
using ViewModels.Chat;
using System.Threading.Tasks;
[Route("api/chat")]
public class ChatApiController : Controller
{
@ -25,30 +30,63 @@ namespace Yavsc.Controllers
public IEnumerable<ChatUserInfo> GetUserList()
{
List<ChatUserInfo> result = new List<ChatUserInfo>();
var cxsQuery = dbContext.ChatConnection?.Include(c=>c.Owner)
.Where(cx => cx.Connected).GroupBy( c => c.ApplicationUserId );
var cxsQuery = dbContext.ChatConnection?.Include(c => c.Owner)
.Where(cx => cx.Connected).GroupBy(c => c.ApplicationUserId);
if (cxsQuery!=null)
foreach (var g in cxsQuery) {
if (cxsQuery != null)
foreach (var g in cxsQuery)
{
var uid = g.Key;
var cxs = g.ToList();
if (cxs !=null)
if (cxs.Count>0) {
var user = cxs.First().Owner;
if (user!=null ) {
result.Add(new ChatUserInfo { UserName = user.UserName,
UserId = user.Id, Avatar = user.Avatar, Connections = cxs,
Roles = ( userManager.GetRolesAsync(user) ).Result.ToArray() });
var uid = g.Key;
var cxs = g.ToList();
if (cxs != null)
if (cxs.Count > 0)
{
var user = cxs.First().Owner;
if (user != null)
{
result.Add(new ChatUserInfo
{
UserName = user.UserName,
UserId = user.Id,
Avatar = user.Avatar,
Connections = cxs,
Roles = (userManager.GetRolesAsync(user)).Result.ToArray()
});
}
else
{
result.Add(new ChatUserInfo { Connections = cxs });
}
}
else {
result.Add(new ChatUserInfo { Connections = cxs });
}
}
}
}
return result;
}
// GET: api/chat/userName
[HttpGet("{userName}", Name = "uinfo")]
public IActionResult GetUserInfo([FromRoute] string userName)
{
if (!ModelState.IsValid)
// Miguel mech profiler
{
return HttpBadRequest(ModelState);
}
var uid = User.GetUserId();
var user = dbContext.ApplicationUser.Include(u => u.Connections).FirstOrDefault(u => u.UserName == userName);
if (user == null) return HttpNotFound();
return Ok(new ChatUserInfo
{
UserName = user.UserName,
UserId = user.Id,
Avatar = user.Avatar,
Connections = user.Connections,
Roles = (userManager.GetRolesAsync(user)).Result.ToArray()
});
}
}
}

View File

@ -29,12 +29,11 @@ namespace Yavsc.Controllers
protected IStringLocalizer _localizer;
protected SiteSettings _siteSettings;
protected SmtpSettings _smtpSettings;
protected ICalendarManager _calendarManager;
protected readonly ILogger _logger;
public CommandController(ApplicationDbContext context, IOptions<GoogleAuthSettings> googleSettings,
IYavscMessageSender GCMSender,
IYavscMessageSender messageSender,
UserManager<ApplicationUser> userManager,
ICalendarManager calendarManager,
IStringLocalizer<Yavsc.Resources.YavscLocalisation> localizer,
@ -44,7 +43,7 @@ namespace Yavsc.Controllers
ILoggerFactory loggerFactory)
{
_context = context;
_MessageSender = GCMSender;
_MessageSender = messageSender;
_emailSender = emailSender;
_googleSettings = googleSettings.Value;
_userManager = userManager;
@ -136,7 +135,7 @@ namespace Yavsc.Controllers
);
var pro = _context.Performers.Include(
u => u.Performer
).Include(u => u.Performer.DeviceDeclarations)
).Include(u => u.Performer.DeviceDeclaration)
.FirstOrDefault(
x => x.PerformerId == command.PerformerId
);
@ -145,9 +144,6 @@ namespace Yavsc.Controllers
command.ClientId = uid;
command.PerformerProfile = pro;
// FIXME Why!!
// ModelState.ClearValidationState("PerformerProfile.Avatar");
// ModelState.ClearValidationState("Client.Avatar");
// ModelState.ClearValidationState("ClientId");
ModelState.MarkFieldSkipped("ClientId");
if (ModelState.IsValid)
@ -173,8 +169,8 @@ namespace Yavsc.Controllers
try
{
_logger.LogInformation("sending message");
var regids = new [] { command.PerformerProfile.Performer.Id };
nrep = await _MessageSender.NotifyBookQueryAsync(regids, yaev);
var uids = new[] { command.PerformerProfile.PerformerId };
nrep = await _MessageSender.NotifyBookQueryAsync(uids, yaev);
// TODO setup a profile choice to allow notifications
// both on mailbox and mobile
// if (grep==null || grep.success<=0 || grep.failure>0)
@ -182,19 +178,24 @@ namespace Yavsc.Controllers
}
catch (Exception ex)
{
_logger.LogError("Message sending failed with: "+ex.Message);
_logger.LogError("Message sending failed with: " + ex.Message);
throw;
}
}
else {
nrep = new MessageWithPayloadResponse { failure=1, results = new MessageWithPayloadResponse.Result[] {
new MessageWithPayloadResponse.Result
{
error=NotificationTypes.ContactRefused,
registration_id= pro.PerformerId
else
{
nrep = new MessageWithPayloadResponse
{
failure = 1,
results = new MessageWithPayloadResponse.Result[] {
new MessageWithPayloadResponse.Result
{
error=NotificationTypes.ContactRefused,
registration_id= pro.PerformerId
}
} };
}
};
_logger.LogInformation("Command.Create && ( !pro.AcceptNotifications || |pro.AcceptPublicContact ) ");
}
ViewBag.MessagingResponsePayload = nrep;

View File

@ -15,7 +15,7 @@ namespace Yavsc.Controllers
public CommandFormsController(ApplicationDbContext context)
{
_context = context;
_context = context;
}
// GET: CommandForms
@ -48,9 +48,10 @@ namespace Yavsc.Controllers
SetViewBag();
return View();
}
private void SetViewBag(CommandForm commandForm=null) {
private void SetViewBag(CommandForm commandForm = null)
{
ViewBag.ActivityCode = new SelectList(_context.Activities, "Code", "Name", commandForm?.ActivityCode);
ViewBag.ActionName = Startup.Forms.Select( c => new SelectListItem { Value = c, Text = c, Selected = (commandForm?.ActionName == c) } );
ViewBag.ActionName = Startup.Forms.Select(c => new SelectListItem { Value = c, Text = c, Selected = (commandForm?.ActionName == c) });
}
// POST: CommandForms/Create
[HttpPost]

View File

@ -31,8 +31,8 @@ namespace Yavsc.Controllers
{
public HairCutCommandController(ApplicationDbContext context,
IOptions<PayPalSettings> payPalSettings,
IOptions<GoogleAuthSettings> googleSettings,
IYavscMessageSender GCMSender,
IOptions<GoogleAuthSettings> googleSettings,
IYavscMessageSender GCMSender,
UserManager<ApplicationUser> userManager,
IStringLocalizer<Yavsc.Resources.YavscLocalisation> localizer,
IEmailSender emailSender,
@ -53,7 +53,7 @@ namespace Yavsc.Controllers
.Include(x => x.PerformerProfile)
.Include(x => x.Prestation)
.Include(x => x.PerformerProfile.Performer)
.Include(x => x.PerformerProfile.Performer.DeviceDeclarations)
.Include(x => x.PerformerProfile.Performer.DeviceDeclaration)
.Include(x => x.Regularisation)
.SingleAsync(m => m.Id == id);
query.SelectedProfile = await _context.BrusherProfile.SingleAsync(b => b.UserId == query.PerformerId);
@ -100,11 +100,10 @@ namespace Yavsc.Controllers
var yaev = command.CreatePaymentEvent(paymentInfo, _localizer);
if (command.PerformerProfile.AcceptNotifications)
{
if (command.PerformerProfile.Performer.DeviceDeclarations.Count > 0)
if (command.PerformerProfile.Performer.DeviceDeclaration.Count > 0)
{
var regids = command.PerformerProfile.Performer
.DeviceDeclarations.Select(d => d.DeviceId);
grep = await _MessageSender.NotifyAsync(regids, yaev);
var regid = command.PerformerProfile.PerformerId;
grep = await _MessageSender.NotifyAsync(new [] {regid}, yaev);
}
// TODO setup a profile choice to allow notifications
// both on mailbox and mobile
@ -217,7 +216,7 @@ namespace Yavsc.Controllers
_logger.LogInformation("le Model _est_ valide.");
var pro = _context.Performers.Include(
u => u.Performer
).Include(u => u.Performer.DeviceDeclarations)
).Include(u => u.Performer.DeviceDeclaration)
.FirstOrDefault(
x => x.PerformerId == model.PerformerId
);
@ -268,10 +267,10 @@ namespace Yavsc.Controllers
{
if (pro.AcceptNotifications)
{
if (pro.Performer.DeviceDeclarations.Count > 0)
if (pro.Performer.DeviceDeclaration.Count > 0)
{
var regids = pro.Performer.DeviceDeclarations.Select(d => d.DeviceId);
grep = await _MessageSender.NotifyHairCutQueryAsync(regids, yaev);
var uids = new[] { pro.PerformerId };
grep = await _MessageSender.NotifyHairCutQueryAsync(uids, yaev);
}
// TODO setup a profile choice to allow notifications
// both on mailbox and mobile
@ -390,7 +389,7 @@ namespace Yavsc.Controllers
);
var pro = _context.Performers.Include(
u => u.Performer
).Include(u => u.Performer.DeviceDeclarations)
).Include(u => u.Performer.DeviceDeclaration)
.FirstOrDefault(
x => x.PerformerId == command.PerformerId
);
@ -427,11 +426,10 @@ namespace Yavsc.Controllers
if (pro.AcceptNotifications
&& pro.AcceptPublicContact)
{
if (pro.Performer.DeviceDeclarations?.Count > 0)
if (pro.Performer.DeviceDeclaration?.Count > 0)
{
var regids = command.PerformerProfile.Performer
.DeviceDeclarations.Select(d => d.DeviceId);
grep = await _MessageSender.NotifyHairCutQueryAsync(regids, yaev);
var uids = new [] { command.PerformerProfile.PerformerId };
grep = await _MessageSender.NotifyHairCutQueryAsync(uids, yaev);
}
// TODO setup a profile choice to allow notifications
// both on mailbox and mobile, and to allow calendar event insertion.

View File

@ -21,7 +21,7 @@ namespace Yavsc.Helpers
.Include(p=>p.Activity)
.Include(p=>p.Performer)
.Include(p=>p.Performer.Posts)
.Include(p=>p.Performer.DeviceDeclarations)
.Include(p=>p.Performer.DeviceDeclaration)
.Where(p => p.Active && p.Activity.Any(u=>u.DoesCode==actCode)).OrderBy( x => x.Rate )
.ToArray();
List<PerformerProfileViewModel> result = new List<PerformerProfileViewModel> ();

View File

@ -11,6 +11,7 @@ using Yavsc.Models;
using Yavsc.Models.Google.Messaging;
using Yavsc.Models.Haircut;
using Yavsc.Models.Messaging;
using Yavsc.Services;
namespace Yavsc.Services
{
@ -58,11 +59,11 @@ namespace Yavsc.Services
try {
List<MessageWithPayloadResponse.Result> results = new List<MessageWithPayloadResponse.Result>();
foreach(var clientId in raa) {
foreach(var userId in raa) {
MessageWithPayloadResponse.Result result = new MessageWithPayloadResponse.Result();
result.registration_id = clientId;
result.registration_id = userId;
var user = _dbContext.Users.FirstOrDefault(u=> u.Id == clientId);
var user = _dbContext.Users.FirstOrDefault(u=> u.Id == userId);
if (user==null)
{
response.failure++;
@ -82,10 +83,9 @@ namespace Yavsc.Services
var body = ev.CreateBody();
var cxids = ChatHub.ChatUserNames.Where (kv=>kv.Value == user.UserName).Select(kv => kv.Key).ToArray();
var hubClient = hubContext.Clients.User(clientId);
if (hubClient == null)
if (cxids.Length==0)
{
_logger.LogDebug($"Sending to {user.UserName} <{user.Email}> : {body}");
var mailSent = await _emailSender.SendEmailAsync(
@ -107,11 +107,15 @@ namespace Yavsc.Services
}
}
else {
_logger.LogDebug($"Sending signal to {string.Join(" ",raa)} : "+JsonConvert.SerializeObject(ev));
// we assume that each hub connected client will handle this signal
_logger.LogDebug($"Sending signal to {string.Join(" ",cxids)} : "+JsonConvert.SerializeObject(ev));
hubClient.notify(NotificationTypes.ServerMessage,
$"# {ev.Sender} (un client) vous demande un rendez-vous\n"+body);
foreach( var cxid in cxids) {
var hubClient = hubContext.Clients.User(cxid);
var data = new Dictionary<string,object>();
data["event"] = ev;
hubClient.push(ev.Topic, data );
}
result.message_id=MimeKit.Utils.MimeUtils.GenerateMessageId(
siteSettings.Authority
@ -130,25 +134,25 @@ namespace Yavsc.Services
}
}
public async Task<MessageWithPayloadResponse> NotifyBookQueryAsync( IEnumerable<string> registrationIds, RdvQueryEvent ev)
public async Task<MessageWithPayloadResponse> NotifyBookQueryAsync( IEnumerable<string> userIds, RdvQueryEvent ev)
{
return await NotifyEvent<RdvQueryEvent>(registrationIds, ev);
return await NotifyEvent<RdvQueryEvent>(userIds, ev);
}
public async Task<MessageWithPayloadResponse> NotifyEstimateAsync(IEnumerable<string> registrationIds, EstimationEvent ev)
public async Task<MessageWithPayloadResponse> NotifyEstimateAsync(IEnumerable<string> userIds, EstimationEvent ev)
{
return await NotifyEvent<EstimationEvent>(registrationIds, ev);
return await NotifyEvent<EstimationEvent>(userIds, ev);
}
public async Task<MessageWithPayloadResponse> NotifyHairCutQueryAsync(
IEnumerable<string> registrationIds, HairCutQueryEvent ev)
IEnumerable<string> userIds, HairCutQueryEvent ev)
{
return await NotifyEvent<HairCutQueryEvent>(registrationIds, ev);
return await NotifyEvent<HairCutQueryEvent>(userIds, ev);
}
public async Task<MessageWithPayloadResponse> NotifyAsync(IEnumerable<string> regids, IEvent yaev)
public async Task<MessageWithPayloadResponse> NotifyAsync(IEnumerable<string> userIds, IEvent yaev)
{
return await NotifyEvent<IEvent>(regids, yaev);
return await NotifyEvent<IEvent>(userIds, yaev);
}
/* SMS with Twilio: