public async Task <ActionResult <MessageResponse> > CreateMessages(CreateChatMessageRequest model)
        {
            var sender = Account;

            if (sender == null)
            {
                return(BadRequest("Not authorized"));
            }
            if (sender.Id == model.RecipientId)
            {
                return(BadRequest("Cannot send mesage to yourself"));
            }

            var recipient = _accountService.GetById(model.RecipientId);

            if (recipient == null)
            {
                return(NotFound());
            }

            model.SenderId = Account.Id;
            model.Created  = DateTime.Now;

            var message = _messageService.AddMessage(model);

            if (await _messageService.SaveAllAsync())
            {
                return(Ok(_mapper.Map <MessageResponse>(message)));
            }
            return(BadRequest("send message failed"));
        }
Esempio n. 2
0
        public async Task <ActionResult> SendMessage([FromBody] MessageViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new { error = "Message should have all props" }));
            }
            model.Id = Guid.NewGuid().ToString();

            //Add message async to Db
            //TODO:
            //Check time format!!!!
            MessageViewModel responseModel = await messageService.AddMessage(model);

            var senderId  = User.Identity.Name;
            var reciverId = this.userSercvice.GetOponentIdByTheadId(senderId, model.ThreadId);

            responseModel.Username = model.Username;
            responseModel.Date     = responseModel.Time.Date;
            responseModel.SenderId = senderId;
            var listOfConnections = new List <string>()
            {
                senderId, reciverId
            };

            await hubContext.Clients.Users(listOfConnections).SendAsync("ReciveMessage", responseModel);

            return(Created("", responseModel));
        }
Esempio n. 3
0
        public async Task <IActionResult> Create(MessageViewModel model)
        {
            if (ModelState.IsValid)
            {
                var ids = model.RecipientIds
                          .Split(new[] { ' ', ',', ';', '\n', '\r', '.' }, StringSplitOptions.RemoveEmptyEntries);

                var mesage = new MessageDto
                {
                    Subject    = model.Subject,
                    Body       = model.Body,
                    Recipients = ids.Select(id => new RecipientDto {
                        RecipientId = id
                    }).ToList()
                };

                var result = await _messageService.AddMessage(mesage, model.MessageServiceUrl);

                model.MessageId = result;

                if (ids != null && ids.Length > 0)
                {
                    // TODO: notify all
                    var res = await _notifyRecipientService.Notify(ids.First(), model.NotificationServiceUrl);
                }

                return(View(model));
            }

            return(View());
        }
Esempio n. 4
0
        public async Task SendPrivateMessage(MessageDto messageDto)
        {
            _messageService.AddMessage(messageDto);

            List <MessageVm> msgs = _messageService.GetAllMessagesForThisConversation(messageDto.StudentId, messageDto.DeansOfficeId);

            JsonSerializerOptions options = new JsonSerializerOptions()
            {
                WriteIndented        = true,
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };

            JsonDocument jsonResult = JsonDocument.Parse(JsonSerializer.Serialize(msgs, options));

            var employeeRoleId = _context.Roles.FirstOrDefault(r => r.NormalizedName == "EMPLOYEE").Id;

            if (employeeRoleId == Guid.Empty)
            {
                employeeRoleId = Guid.Parse("11D14A89-3A93-4D39-A94F-82B823F0D4CE");
            }

            //var destinationUserId = _context.Users.Include(r => r.UserRoles)
            //    .Where(u => u.DeansOfficeId == messageDto.DeansOfficeId &&
            //                u.UserRoles.Any(ur => ur.RoleId == employeeRoleId)).Select(u=>u.Id).ToString();

            await Clients.Group(messageDto.StudentId + "-" + messageDto.DeansOfficeId).SendAsync("ReceiveMessage", jsonResult);
        }
Esempio n. 5
0
        public async Task <IEnumerable <MessageViewModel> > SharePost(SharePostRequest request)
        {
            var currentUser            = Feature.CurrentUser(httpContextAccessor, userRepository);
            var addConversationRequest = new AddConversationRequest();

            addConversationRequest.Participants.AddRange(
                new List <ConversationMember>()
            {
                new ConversationMember()
                {
                    MemberId = request.UserId
                }
            });

            var conversation = await conversationService.AddConversation(addConversationRequest);

            var addMessageRequest = new AddMessageRequest()
            {
                PostId         = request.PostId,
                MessageType    = MessageBaseType.PostThumbnail,
                ConversationId = conversation.OId
            };
            await messageService.AddMessage(addMessageRequest);

            var messageByConversationRequest = new GetMessageByConversationIdRequest()
            {
                ConversationId = conversation.OId,
                Skip           = request.Skip,
                Count          = request.Count
            };

            var result = await messageService.GetMessageByConversationId(messageByConversationRequest);

            return(result);
        }
        public async Task <ActionResult <MessageDto> > CreateMessage(CreateMessageDto createMessageDto)
        {
            var userId = User.GetUserId();

            if (userId == createMessageDto.RecipentId)
            {
                return(BadRequest("you cannot send message to yourself"));
            }
            var senderId = await _userService.GetByIdAsync(userId);

            var receipentId = await _userService.GetByIdAsync(createMessageDto.RecipentId);

            if (receipentId == null)
            {
                return(NotFound());
            }
            var message = new Messages
            {
                Sender     = senderId,
                Receipent  = receipentId,
                SenderId   = senderId.Id,
                RecipentId = receipentId.Id,
                Content    = createMessageDto.Content
            };

            _messageService.AddMessage(message);
            if (await _messageService.SaveAllAsync())
            {
                return(Ok(_mapper.Map <MessageDto>(message)));
            }
            return(BadRequest("Failed to send Message"));
        }
Esempio n. 7
0
        public async Task <ResultReturn> SendMessage(
            //[FromServices]MessageService message,
            //[FromServices]SessionService session,
            //[FromServices]IMemoryCache cache,
            long sessionId,
            string content,
            int contentType
            )
        {
            var messageId = await _message.AddMessage(Context.UserIdentifier, sessionId, content, MessageTypeEnum.User,
                                                      (MessageContentTypeEnum)contentType);

            var sessionInfo = await _session.GetSessionById(sessionId);

            if (sessionInfo.Type == SessionTypeEnum.OneToOne)
            {
                var s = await _session.GetSessionUserIds(sessionId);

                var friendUserId = s.FirstOrDefault(x => x != Context.UserIdentifier);

                if (await _connManager.IsUserOnline(friendUserId))
                {
                    await Clients.User(friendUserId).SendAsync("ReceivedMessage", sessionId, content, contentType, messageId);
                }
            }
            else if (sessionInfo.Type == SessionTypeEnum.Group)
            {
                await Clients.Group(sessionInfo.SessionId.ToStringEx()).SendAsync("SendMessage", content);
            }

            return(new SuccessResultReturn(messageId));
        }
        public void Start()
        {
            // 1. legyen egy adatforrásunk
            ///////////////////////////////
            //ehelyett
            //var list = new List<string> { "*****@*****.**" };

            //egyik nagy előny, ha tervezési mintákat használunk
            //a KÖZÖS NYELV
            //ezért: az adatokat szolgáltató osztály neve: Repository
            //De már kívülről megkapom DI-vel (Dependency Injection)
            //var repo = new AddressRepository();

            // 2. legyen egy e-mail megoldásunk (=üzenetküldő megoldás)
            ///////////////////////////////////////////////////////////

            //var message = new MailMessage();
            //message.To.Add(new MailAddress("email cím"));
            //stb.

            //Ha ezzel a megoldással szeretnénk e-mailt küldeni, akkor
            //hozzákötjük magunkat az SMTP küldéshez .NET megoldással.

            //Pedig van sendgrid/mailchimp
            //lehet, hogy sms-t akarunk majd később küldeni
            //stb.

            //a kód újrafelhasználhatóságának feltétele és biztosítéka,
            //ha az osztályaink/objektumainkra ez igaz_
            //High cohesion - low coupling

            // erős kohézió
            // gyenge csatolás

            //csatolás: két objektum akkor van csatolásban
            //ha az egyik módosítása NEM ZÁRJA KI a másik megváltozását.
            //minél erősebb a csatolás, annál valószínűbb, hogy meg is változik a második objektum.

            // [egyik objektum] ------ (csatolás) ------> [másik objektum]

            //mit lehet ellene tenni: indirekció:

            // [egyik objektum] ------ (csatolás) ------> [koztes objektum] ------ (csatolás) ------> [másik objektum]

            //így a két szélső objektum, ha jól csináljuk, akkor már nincs egymással kapcsolatban

            //Tehát indirekció: készítünk egy köztes osztályt
            //De már kívülről megkapom DI-vel (Dependency Injection)
            //var messageService = new MessageService();

            //és ezeket kössük össze
            var addressList = repository.GetAddresses();

            foreach (var address in addressList)
            {
                service.AddMessage(to: address.EMail, subject: "Ez az üzenet címe", text: "Ez az üzenet szövege");
            }

            service.SendMessages();
        }
Esempio n. 9
0
        /// <summary>
        /// Method to broadcast message to all connected clients
        /// </summary>
        /// <param name="chatMessage">Message object with text and Writter</param>
        public async void SendAll(ChatMessage chatMessage)
        {
            if (_commandService.IsCommand(chatMessage.Text))
            {
                CommandInfos infos = _commandService.GetCommandInfos(chatMessage.Text);

                /* Im broadcasting user command, but not saving it to database */
                await Broadcast(chatMessage);

                if (infos.Error != null)
                {
                    await Broadcast(AdminMessage(infos.Error));
                }
                else
                {
                    _userBotQueueProducer.SearchStock(infos.Parameter);
                }
            }
            else
            {
                /* If is not a command, save to database and broadcast */
                string   userId   = chatMessage.UserID;
                ChatUser chatUser = _userService.GetUser(userId);
                Message  message  = new Message(chatMessage.Text, chatUser);
                _messageService.AddMessage(message);
                chatMessage.SentAt = message.SentAt;
                await Broadcast(chatMessage);
            }
        }
Esempio n. 10
0
        public void Start()
        {
            // datasource
            // var list = new List<string>() { "mailAddress1", "mailAddress2" };

            // email solution
            //var message = new MailMessage();
            //message.To.Add(new MailAddress("email address"));

            // két objektum erős csatolásban van, ha az egyik módosítása nem zárja ki
            // a másik megváltoztatását, minnél erősebb a csatolás annál valószínűbb, hogy a
            // meg is változik a második objektum.

            // [Egyik objektum]---(csatolás)---[Másik objektum]

            // mit lehet tenni? INDIREKCIÓ
            // ADAPTER DESING MINTA

            // [Egyik objektum]---(csatolás)---[köztes ADAPTER objektum]---(csatolás)---[Másik objektum]

            var addressList = repository.GetAddresses();

            foreach (var address in addressList)
            {
                service.AddMessage(to: address.Email, subject: "Ez az uzenet cime", text: "Uzenet szovege");
            }

            service.SendMessages();
        }
Esempio n. 11
0
        public ActionResult SendMessage(int id, string chatMessage = null)
        {
            var myUser = userService.GetUserByEmail(HttpContext.User.Identity.Name);

            if (chatMessage != null)
            {
                messageService.AddMessage(new BllMessage()
                {
                    Date          = DateTime.Now,
                    ProfileIdFrom = myUser.Id,
                    ProfileIdTo   = id,
                    Text          = chatMessage
                });
            }
            var context   = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext <NotificationHub>();
            var t         = context.Clients.All;
            var messages  = messageService.GetMessages(myUser.Id, id);
            var viewModel = new SendMessageModel()
            {
                Messages  = messages,
                I         = profileService.Get(myUser.Id).ToViewProfileModel(),
                Companion = profileService.Get(id).ToViewProfileModel()
            };

            if (!Request.IsAjaxRequest())
            {
                return(View(viewModel));
            }
            return(PartialView("_History", viewModel));
        }
Esempio n. 12
0
        private DispatchNotificationResult SendNotificationsAndSetDispatchDate(IEnumerable <Notification> notifications)
        {
            var factory = new SenderFactory(_configuration, _logger, _smsService);
            var respone = new DispatchNotificationResult();

            foreach (var notification in notifications)
            {
                var message = _messageService.CreateMessage(notification);
                var sender  = new MessageSender(factory.CreateSenderObject(notification.MessageType), message);
                var result  = sender.Send();
                if (result)
                {
                    var dateOfDisptach = SystemTime.Now;
                    notification.DateOfLastDispatch = dateOfDisptach;
                    respone.sentNotifications.Add(Mapper.Map <NotificationDto>(notification));
                    message.DateOfSending = dateOfDisptach;
                    _messageService.AddMessage(message);
                    continue;
                }
                respone.notSentNotifications.Add(Mapper.Map <NotificationDto>(notification));
            }

            _notificationRepository.Save();

            return(respone);
        }
Esempio n. 13
0
        // ReSharper disable once UnusedParameter.Global
        public static void Main(string[] args)
        {
            Greeting();
            try
            {
                InitialiseConfiguration();
                InitialiseLogger();
                InitialiseUser();
                InitialiseMessenger();

                Console.WriteLine("Please enter your messages:");
                while (true)
                {
                    var input = Console.ReadLine();
                    if (string.IsNullOrEmpty(input))
                    {
                        continue;
                    }
                    _messageService.AddMessage(new Message(input));
                }
            }
            catch (Exception e)
            {
                Log.Fatal(e, "Fatal error");
                Console.WriteLine($"Something went wrong: {e.Message}");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Esempio n. 14
0
        public async Task <IActionResult> Post(MessagePostDto message)
        {
            var currentUserId = await _userService.GetUserIdByLogin(User.Identity.Name);

            var targetUser = await _userService.GetUserById(message.ReceiverId);

            if (targetUser == null)
            {
                return(BadRequest("Target user doesnt exist !"));
            }

            if (currentUserId.Value == targetUser.Id)
            {
                return(BadRequest("Cannot send message to yourself!"));
            }

            var result = await _messageService.AddMessage(currentUserId.Value, message);

            if (result.IsSuccessful)
            {
                var connectionId = MessagesHub.TryGetUserConnection(targetUser.Login);
                if (!string.IsNullOrEmpty(connectionId))
                {
                    await _hubContext.Clients.Client(connectionId).SendAsync("Recieve", message);
                }
                return(Ok());
            }

            return(StatusCode(500, result.Message));
        }
Esempio n. 15
0
        public async Task SendDirect(string targetId, string text)
        {
            var message = await _messageService.AddMessage(Context.UserIdentifier, targetId, text);

            await Clients.Caller.SendAsync("MessageSent", message);

            await Clients.User(targetId).SendAsync("UpdateDialog", message);
        }
Esempio n. 16
0
        public HttpResponseMessage AddMessage([FromBody] AddMessageRequest request)
        {
            _logAppInfo.Info(string.Format("添加消息接口请求串:{0},参数:{1}", Request.RequestUri, request.ToJson()));
            var response = _messageService.AddMessage(request, Request.GetQueryNameValuePairs());

            _logAppInfo.Info(string.Format("添加消息接口返回值:{0}", response.ToJson()));
            return(response.ResponseToJson());
        }
Esempio n. 17
0
 public ActionResult Create(MessageDto model)
 {
     if (!ModelState.IsValid)
     {
         return(View(model));
     }
     _messageService.AddMessage(model);
     return(RedirectToAction("Index"));
 }
Esempio n. 18
0
        public async Task <IActionResult> CreateMessage([FromBody] ApiInputMessage message)
        {
            var entity = _mapper.Map <Message>(message);
            var result = _messageService.AddMessage(entity);

            await SendToChat("Message", GenerateText(result.Content, result.DateTime, result.Number));

            return(Ok(_mapper.Map <ApiOutputMessage>(result)));
        }
Esempio n. 19
0
        //public async Task SendMessage(string user, string message)
        //{
        //    await Clients.All.SendAsync("ReceiveMessage", user, message);
        //}
        public async Task SendMessage(string message, string username)
        {
            UserDto user   = userService.GetUserByName(username);
            bool    result = _messageService.AddMessage(Int32.Parse(Context.UserIdentifier), user.Id, message, user.ProfileImage);

            await Clients.User(user.Id.ToString()).SendAsync("ReceiveMessage", message, Context.User.Identity.Name, user.ProfileImage);

            //await Clients.Caller.SendAsync("ReceiveMessage", message);
        }
Esempio n. 20
0
        public async Task <IActionResult> AddMessage(MessageViewModel messageViewModel)
        {
            var message = _mapper.Map <MessageModel>(messageViewModel);

            messageViewModel.PersonId = User.GetPersonId();
            await _messageService.AddMessage(message);

            return(Ok());
        }
Esempio n. 21
0
 public MainModel(IMessageService messageService)
 {
     MessageService = messageService;
     MessageService.PropertyChanged += (sender, args) => OnPropertyChanged(args.PropertyName);
     MessageService.AddMessage(new MessageData
     {
         Message = "Main Model has been Initialized."
     });
 }
Esempio n. 22
0
        public async Task SendMessage(CreateChatMessageRequest model)
        {
            var senderId = Context.User.GetUserId();

            if (senderId == model.RecipientId)
            {
                throw new HubException("Cannot send mesage to yourself");
            }
            var sender = await _accountService.GetById(senderId);

            var recipient = await _accountService.GetById(model.RecipientId);

            if (recipient == null)
            {
                throw new HubException("User not found");
            }

            model.SenderId = sender.Id;
            model.Created  = DateTime.Now;
            var groupName = GetGroupName(sender.Id, recipient.Id);
            var group     = await _messageService.GetMessageGroup(groupName);


            if (group.Connections.Any(x => x.UserId == recipient.Id))
            {
                model.Read = DateTime.Now;
            }

            var message = await _messageService.AddMessage(model);

            if (await _messageService.SaveAllAsync())
            {
                var response = _mapper.Map <MessageResponse>(message);

                if (sender != null && recipient != null)
                {
                    response.SenderName          = sender.Name;
                    response.SenderAvatarPath    = sender.AvatarPath;
                    response.RecipientName       = recipient.Name;
                    response.RecipientAvatarPath = recipient.AvatarPath;
                }
                var connections = await _tracker.GetConnectionForUser(recipient.Id);

                var curentUserConnections = await _tracker.GetConnectionForUser(sender.Id);

                if (connections != null)
                {
                    await _presenceHub.Clients.Clients(connections).SendAsync("NewMessageReceived", response);
                }
                if (curentUserConnections != null)
                {
                    await _presenceHub.Clients.Clients(curentUserConnections).SendAsync("NewMessageReceived", response);
                }
                await Clients.Group(groupName).SendAsync("NewMessage", response);
            }
        }
        public IActionResult Post(MessageModel message)
        {
            var messageResult = _messageService.AddMessage(message);

            if (messageResult.ResponseCode != ResponseCode.Success)
            {
                return(BadRequest(messageResult.Error));
            }
            return(Ok(messageResult.Result));
        }
Esempio n. 24
0
        public override async Task UpdateAsync(int id, int?parentId, CountryEntity entity, IRelationContainer?relations)
        {
            _messageService.AddMessage(MessageType.Success, $"Country '{entity.Name}' saved.");

            var dbEntity = await _dbContext.Countries.FirstOrDefaultAsync(x => x._Id == id);

            dbEntity.Name = entity.Name;

            _dbContext.Countries.Update(dbEntity);
            await _dbContext.SaveChangesAsync();
        }
        public void Start()
        {
            var addressList = repo.GetAddresses();

            foreach (var address in addressList)
            {
                messageService.AddMessage(to: address.Email, subject: "subject", text: "Uzenet szovege...");
            }

            messageService.SendMessages();
        }
Esempio n. 26
0
 public async Task AddMessage([FromBody] AddMessageDto addMessageDto)
 {
     try
     {
         await _messageService.AddMessage(addMessageDto);
     }
     catch (Exception e)
     {
         throw new ApplicationException(e.Message);
     }
 }
Esempio n. 27
0
 public IActionResult Post([FromBody] Message message)
 {
     if (_service.AddMessage(message))
     {
         _hubContext.Clients.All.SendAsync("ReceiveMessage", message.AuthorName, message.Text);
         return(NoContent());
     }
     else
     {
         return(StatusCode(500));
     }
 }
Esempio n. 28
0
        public async Task <IActionResult> SendMessage([FromBody] MessageViewModel messageViewModel)
        {
            await _hubContext.Clients.User(messageViewModel.SenderId).SendAsync("GetMessage", messageViewModel);

            await _hubContext.Clients.User(messageViewModel.ReceiverId).SendAsync("GetMessage", messageViewModel);

            var mapper     = new MapperConfiguration(cfg => cfg.CreateMap <MessageViewModel, MessageDTO>()).CreateMapper();
            var messageDTO = mapper.Map <MessageViewModel, MessageDTO>(messageViewModel);
            await _messageService.AddMessage(messageDTO);

            return(Ok());
        }
Esempio n. 29
0
        public IActionResult AddPostMessage([FromBody] MessageModel message)
        {
            if (!_workContext.CurrentCustomer.IsRegistered())
            {
                return(RedirectToRoute("/Login", new { returnUrl = "Harag" }));
            }

            if (!ModelState.IsValid)
            {
                return(Ok(new { stat = false, errors = ModelState.Values }));
            }

            var currentUserId = _workContext.CurrentCustomer.Id;

            ViewBag.UserName = _workContext.CurrentCustomer.Username;

            var msg = new Z_Harag_Message
            {
                Message     = message.Message,
                CreatedTime = DateTime.Now,
                ToUserId    = message.ToUserId,
                FromUserId  = currentUserId,
                MessageType = message.Type
            };

            if (message.PostId != 0)
            {
                msg.PostId = message.PostId;
            }

            var mes = _messageService.AddMessage(msg);

            var model = new MessageOutputModel {
                Message    = mes.Message,
                DateTime   = (DateTime)mes.CreatedTime,
                FromUser   = mes.Customer.Username,
                FromUserId = (int)mes.ToUserId,
                Type       = (MessageType)mes.MessageType
            };

            if (message.PostId != 0)
            {
                model.postId = (int)mes.PostId;
            }

            if (mes != null)
            {
                return(PartialView("~/Themes/Pavilion/Views/Harag/Message/_MessageTemplatePartial.cshtml", model));
            }

            return(BadRequest());
        }
Esempio n. 30
0
        public async Task <IActionResult> AddMeesage([FromBody] Message message)
        {
            var response = await _messageService.AddMessage(message);

            if (!response.status)
            {
                return(NotFound(response.message));
            }
            else
            {
                return(Ok(response.message));
            }
        }