Beispiel #1
0
        public async Task <IActionResult> Compose(ComposeMessageModel model, IFormCollection collection, CancellationToken cancellationToken)
        {
            var roles  = new List <string>();
            var groups = new List <string>();
            var users  = new List <string>();
            var shifts = new List <string>();

            if (collection.ContainsKey("roles"))
            {
                roles.AddRange(collection["roles"].ToString().Split(char.Parse(",")));
            }

            if (collection.ContainsKey("groups"))
            {
                groups.AddRange(collection["groups"].ToString().Split(char.Parse(",")));
            }

            if (collection.ContainsKey("users"))
            {
                users.AddRange(collection["users"].ToString().Split(char.Parse(",")));
            }

            if (collection.ContainsKey("exludedShifts"))
            {
                shifts.AddRange(collection["exludedShifts"].ToString().Split(char.Parse(",")));
            }

            if (!model.SendToAll && (roles.Count + groups.Count + users.Count) == 0)
            {
                ModelState.AddModelError("", "You must specify at least one Recipient.");
            }

            if (model.SendToMatchOnly && (roles.Count + groups.Count) == 0)
            {
                ModelState.AddModelError("", "You must specify at least one Group or Role to send to.");
            }

            if (ModelState.IsValid)
            {
                var excludedUsers = new List <string>();

                if (shifts.Any())
                {
                    foreach (var shiftId in shifts)
                    {
                        var shift = await _shiftsService.GetShiftByIdAsync(int.Parse(shiftId));

                        excludedUsers.AddRange(shift.Personnel.Select(x => x.UserId));
                    }
                }

                model.Message.Type = (int)model.MessageType;
                if (model.SendToAll)
                {
                    var allUsers = await _departmentsService.GetAllUsersForDepartmentAsync(DepartmentId);

                    foreach (var user in allUsers)
                    {
                        if (user.UserId != UserId && (!excludedUsers.Any() || !excludedUsers.Contains(user.UserId)))
                        {
                            model.Message.AddRecipient(user.UserId);
                        }
                    }
                }
                else if (model.SendToMatchOnly)
                {
                    var usersInRoles = new Dictionary <int, List <string> >();

                    foreach (var role in roles)
                    {
                        var roleMembers = await _personnelRolesService.GetAllMembersOfRoleAsync(int.Parse(role));

                        usersInRoles.Add(int.Parse(role), roleMembers.Select(x => x.UserId).ToList());
                    }

                    foreach (var group in groups)
                    {
                        var members = await _departmentGroupsService.GetAllMembersForGroupAsync(int.Parse(group));

                        foreach (var member in members)
                        {
                            bool isInRoles = false;
                            if (model.Message.GetRecipients().All(x => x != member.UserId) && member.UserId != UserId &&
                                (!excludedUsers.Any() || !excludedUsers.Contains(member.UserId)))
                            {
                                foreach (var key in usersInRoles)
                                {
                                    if (key.Value.Any(x => x == member.UserId))
                                    {
                                        isInRoles = true;
                                        break;
                                    }
                                }

                                if (isInRoles)
                                {
                                    model.Message.AddRecipient(member.UserId);
                                }
                            }
                        }
                    }
                }
                else
                {
                    foreach (var user in users)
                    {
                        model.Message.AddRecipient(user);
                    }

                    // Add all members of the group
                    foreach (var group in groups)
                    {
                        var members = await _departmentGroupsService.GetAllMembersForGroupAsync(int.Parse(group));

                        foreach (var member in members)
                        {
                            if (model.Message.GetRecipients().All(x => x != member.UserId) && member.UserId != UserId && (!excludedUsers.Any() || !excludedUsers.Contains(member.UserId)))
                            {
                                model.Message.AddRecipient(member.UserId);
                            }
                        }
                    }

                    // Add all the users of a specific role
                    foreach (var role in roles)
                    {
                        var roleMembers = await _personnelRolesService.GetAllMembersOfRoleAsync(int.Parse(role));

                        foreach (var member in roleMembers)
                        {
                            if (model.Message.GetRecipients().All(x => x != member.UserId) && member.UserId != UserId && (!excludedUsers.Any() || !excludedUsers.Contains(member.UserId)))
                            {
                                model.Message.AddRecipient(member.UserId);
                            }
                        }
                    }
                }

                model.Message.SentOn        = DateTime.UtcNow;
                model.Message.SendingUserId = UserId;
                model.Message.Body          = System.Net.WebUtility.HtmlDecode(model.Message.Body);
                model.Message.IsBroadcast   = true;

                var savedMessage = await _messageService.SaveMessageAsync(model.Message, cancellationToken);

                await _messageService.SendMessageAsync(savedMessage, "", DepartmentId, false, cancellationToken);

                return(RedirectToAction("Inbox"));
            }

            model.Department = await _departmentsService.GetDepartmentByIdAsync(DepartmentId);

            model.User  = _usersService.GetUserById(UserId);
            model.Types = model.MessageType.ToSelectList();

            var savedShifts = await _shiftsService.GetAllShiftsByDepartmentAsync(DepartmentId);

            model.Shifts       = new SelectList(savedShifts, "ShiftId", "Name");
            model.Message.Body = System.Net.WebUtility.HtmlDecode(model.Message.Body);

            return(View(await FillComposeMessageModel(model)));
        }
Beispiel #2
0
        public async Task <IActionResult> New(NewTrainingModel model, IFormCollection form, ICollection <IFormFile> attachments)
        {
            model.Training.CreatedByUserId = UserId;

            if (attachments != null)
            {
                model.Training.Attachments = new Collection <TrainingAttachment>();
                foreach (var file in attachments)
                {
                    if (file != null && file.Length > 0)
                    {
                        var extenion = file.FileName.Substring(file.FileName.IndexOf(char.Parse(".")) + 1,
                                                               file.FileName.Length - file.FileName.IndexOf(char.Parse(".")) - 1);

                        if (!String.IsNullOrWhiteSpace(extenion))
                        {
                            extenion = extenion.ToLower();
                        }

                        if (extenion != "jpg" && extenion != "jpeg" && extenion != "png" && extenion != "gif" && extenion != "gif" &&
                            extenion != "pdf" && extenion != "doc" &&
                            extenion != "docx" && extenion != "ppt" && extenion != "pptx" && extenion != "pps" && extenion != "ppsx" &&
                            extenion != "odt" &&
                            extenion != "xls" && extenion != "xlsx" && extenion != "txt" && extenion != "mpg" && extenion != "avi" &&
                            extenion != "mpeg")
                        {
                            ModelState.AddModelError("fileToUpload", string.Format("File type ({0}) is not importable.", extenion));
                        }

                        if (file.Length > 30000000)
                        {
                            ModelState.AddModelError("fileToUpload", "Attachment is too large, must be smaller then 30MB.");
                        }

                        var attachment = new TrainingAttachment();
                        attachment.FileType = file.ContentType;
                        attachment.FileName = file.FileName;

                        var uploadedFile = new byte[file.OpenReadStream().Length];
                        file.OpenReadStream().Read(uploadedFile, 0, uploadedFile.Length);

                        attachment.Data = uploadedFile;
                        model.Training.Attachments.Add(attachment);
                    }
                }
            }

            var roles  = new List <string>();
            var groups = new List <string>();
            var users  = new List <string>();

            if (form.ContainsKey("rolesToAdd"))
            {
                roles.AddRange(form["rolesToAdd"].ToString().Split(char.Parse(",")));
            }

            if (form.ContainsKey("groupsToAdd"))
            {
                groups.AddRange(form["groupsToAdd"].ToString().Split(char.Parse(",")));
            }

            if (form.ContainsKey("usersToAdd"))
            {
                users.AddRange(form["usersToAdd"].ToString().Split(char.Parse(",")));
            }

            model.Training.Users = new List <TrainingUser>();

            if (model.SendToAll)
            {
                var allUsers = await _departmentsService.GetAllUsersForDepartmentAsync(DepartmentId);

                foreach (var user in allUsers)
                {
                    var trainingUser = new TrainingUser();
                    trainingUser.UserId = user.UserId;

                    model.Training.Users.Add(trainingUser);
                }
            }
            else
            {
                foreach (var user in users)
                {
                    var trainingUser = new TrainingUser();
                    trainingUser.UserId = user;

                    model.Training.Users.Add(trainingUser);
                }

                foreach (var group in groups)
                {
                    var members = await _departmentGroupsService.GetAllMembersForGroupAsync(int.Parse(group));

                    foreach (var member in members)
                    {
                        var trainingUser = new TrainingUser();
                        trainingUser.UserId = member.UserId;

                        if (model.Training.Users.All(x => x.UserId != member.UserId))
                        {
                            model.Training.Users.Add(trainingUser);
                        }
                    }
                }

                foreach (var role in roles)
                {
                    var roleMembers = await _personnelRolesService.GetAllMembersOfRoleAsync(int.Parse(role));

                    foreach (var member in roleMembers)
                    {
                        var trainingUser = new TrainingUser();
                        trainingUser.UserId = member.UserId;

                        if (model.Training.Users.All(x => x.UserId != member.UserId))
                        {
                            model.Training.Users.Add(trainingUser);
                        }
                    }
                }
            }

            if (!model.Training.Users.Any())
            {
                ModelState.AddModelError("", "You have not selected any personnel, roles or groups to assign this training to.");
            }

            if (ModelState.IsValid)
            {
                List <int> questions = (from object key in form.Keys where key.ToString().StartsWith("question_") select int.Parse(key.ToString().Replace("question_", ""))).ToList();

                if (questions.Count > 0)
                {
                    model.Training.Questions = new Collection <TrainingQuestion>();
                }

                model.Training.DepartmentId    = DepartmentId;
                model.Training.CreatedOn       = DateTime.UtcNow;
                model.Training.CreatedByUserId = UserId;
                model.Training.GroupsToAdd     = form["groupsToAdd"];
                model.Training.RolesToAdd      = form["rolesToAdd"];
                model.Training.UsersToAdd      = form["usersToAdd"];
                model.Training.Description     = System.Net.WebUtility.HtmlDecode(model.Training.Description);
                model.Training.TrainingText    = System.Net.WebUtility.HtmlDecode(model.Training.TrainingText);


                foreach (var i in questions)
                {
                    if (form.ContainsKey("question_" + i))
                    {
                        var questionText = form["question_" + i];
                        var question     = new TrainingQuestion();
                        question.Question = questionText;

                        List <int> answers = (from object key in form.Keys where key.ToString().StartsWith("answerForQuestion_" + i + "_") select int.Parse(key.ToString().Replace("answerForQuestion_" + i + "_", ""))).ToList();

                        if (answers.Count > 0)
                        {
                            question.Answers = new Collection <TrainingQuestionAnswer>();
                        }

                        foreach (var answer in answers)
                        {
                            var trainingQuestionAnswer = new TrainingQuestionAnswer();
                            var answerForQuestion      = form["answerForQuestion_" + i + "_" + answer];

                            var possibleAnswer = form["answer_" + i];
                            trainingQuestionAnswer.Answer = answerForQuestion;

                            if (!string.IsNullOrWhiteSpace(possibleAnswer))
                            {
                                if ("answerForQuestion_" + i + "_" + answer == possibleAnswer)
                                {
                                    trainingQuestionAnswer.Correct = true;
                                }
                            }

                            question.Answers.Add(trainingQuestionAnswer);
                        }

                        model.Training.Questions.Add(question);
                    }
                }

                await _trainingService.SaveAsync(model.Training);

                return(RedirectToAction("Index"));
            }

            return(View(model));
        }
Beispiel #3
0
        public static async Task <bool> ProcessCallQueueItem(CallQueueItem cqi)
        {
            try
            {
                if (cqi != null && cqi.Call != null && cqi.Call.HasAnyDispatches())
                {
                    if (_communicationService == null)
                    {
                        _communicationService = Bootstrapper.GetKernel().Resolve <ICommunicationService>();
                    }

                    if (_callsService == null)
                    {
                        _callsService = Bootstrapper.GetKernel().Resolve <ICallsService>();
                    }

                    List <int> groupIds = new List <int>();

                    /* Trying to see if I can eek out a little perf here now that profiles are in Redis. Previously the
                     * the parallel operation would cause EF errors. This shouldn't be the case now because profiles are
                     * cached and GetProfileForUser operations will hit that first.
                     */
                    if (cqi.Profiles == null || !cqi.Profiles.Any())
                    {
                        if (_userProfilesService == null)
                        {
                            _userProfilesService = Bootstrapper.GetKernel().Resolve <IUserProfileService>();
                        }

                        cqi.Profiles = (await _userProfilesService.GetAllProfilesForDepartmentAsync(cqi.Call.DepartmentId)).Select(x => x.Value).ToList();
                    }

                    if (cqi.CallDispatchAttachmentId > 0)
                    {
                        //var callsService = Bootstrapper.GetKernel().Resolve<ICallsService>();
                        cqi.Call.ShortenedAudioUrl = await _callsService.GetShortenedAudioUrlAsync(cqi.Call.CallId, cqi.CallDispatchAttachmentId);
                    }

                    cqi.Call.ShortenedCallUrl = await _callsService.GetShortenedCallLinkUrl(cqi.Call.CallId);

                    try
                    {
                        cqi.Call.CallPriority = await _callsService.GetCallPrioritiesByIdAsync(cqi.Call.DepartmentId, cqi.Call.Priority, false);
                    }
                    catch { /* Doesn't matter */ }

                    var dispatchedUsers = new HashSet <string>();

                    // Dispatch Personnel
                    if (cqi.Call.Dispatches != null && cqi.Call.Dispatches.Any())
                    {
                        Parallel.ForEach(cqi.Call.Dispatches, d =>
                        {
                            dispatchedUsers.Add(d.UserId);

                            try
                            {
                                var profile = cqi.Profiles.FirstOrDefault(x => x.UserId == d.UserId);

                                if (profile != null)
                                {
                                    _communicationService.SendCallAsync(cqi.Call, d, cqi.DepartmentTextNumber, cqi.Call.DepartmentId, profile, cqi.Address);
                                }
                            }
                            catch (SocketException sex)
                            {
                            }
                        });
                    }

                    if (_departmentGroupsService == null)
                    {
                        _departmentGroupsService = Bootstrapper.GetKernel().Resolve <IDepartmentGroupsService>();
                    }

                    // Dispatch Groups
                    if (cqi.Call.GroupDispatches != null && cqi.Call.GroupDispatches.Any())
                    {
                        foreach (var d in cqi.Call.GroupDispatches)
                        {
                            if (!groupIds.Contains(d.DepartmentGroupId))
                            {
                                groupIds.Add(d.DepartmentGroupId);
                            }

                            var members = await _departmentGroupsService.GetAllMembersForGroupAsync(d.DepartmentGroupId);

                            foreach (var member in members)
                            {
                                if (!dispatchedUsers.Contains(member.UserId))
                                {
                                    dispatchedUsers.Add(member.UserId);
                                    try
                                    {
                                        var profile = cqi.Profiles.FirstOrDefault(x => x.UserId == member.UserId);
                                        await _communicationService.SendCallAsync(cqi.Call, new CallDispatch()
                                        {
                                            UserId = member.UserId
                                        }, cqi.DepartmentTextNumber, cqi.Call.DepartmentId, profile, cqi.Address);
                                    }
                                    catch (SocketException sex)
                                    {
                                    }
                                    catch (Exception ex)
                                    {
                                        Logging.LogException(ex);
                                    }
                                }
                            }
                        }
                    }

                    // Dispatch Units
                    if (cqi.Call.UnitDispatches != null && cqi.Call.UnitDispatches.Any())
                    {
                        if (_unitsService == null)
                        {
                            _unitsService = Bootstrapper.GetKernel().Resolve <IUnitsService>();
                        }

                        foreach (var d in cqi.Call.UnitDispatches)
                        {
                            var unit = await _unitsService.GetUnitByIdAsync(d.UnitId);

                            if (unit != null && unit.StationGroupId.HasValue)
                            {
                                if (!groupIds.Contains(unit.StationGroupId.Value))
                                {
                                    groupIds.Add(unit.StationGroupId.Value);
                                }
                            }

                            await _communicationService.SendUnitCallAsync(cqi.Call, d, cqi.DepartmentTextNumber, cqi.Address);

                            var unitAssignedMembers = await _unitsService.GetCurrentRolesForUnitAsync(d.UnitId);

                            if (unitAssignedMembers != null && unitAssignedMembers.Count() > 0)
                            {
                                foreach (var member in unitAssignedMembers)
                                {
                                    if (!dispatchedUsers.Contains(member.UserId))
                                    {
                                        dispatchedUsers.Add(member.UserId);
                                        try
                                        {
                                            var profile = cqi.Profiles.FirstOrDefault(x => x.UserId == member.UserId);
                                            await _communicationService.SendCallAsync(cqi.Call, new CallDispatch()
                                            {
                                                UserId = member.UserId
                                            }, cqi.DepartmentTextNumber, cqi.Call.DepartmentId, profile, cqi.Address);
                                        }
                                        catch (SocketException sex)
                                        {
                                        }
                                        catch (Exception ex)
                                        {
                                            Logging.LogException(ex);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (unit.StationGroupId.HasValue)
                                {
                                    var members = await _departmentGroupsService.GetAllMembersForGroupAsync(unit.StationGroupId.Value);

                                    foreach (var member in members)
                                    {
                                        if (!dispatchedUsers.Contains(member.UserId))
                                        {
                                            dispatchedUsers.Add(member.UserId);
                                            try
                                            {
                                                var profile = cqi.Profiles.FirstOrDefault(x => x.UserId == member.UserId);
                                                await _communicationService.SendCallAsync(cqi.Call, new CallDispatch()
                                                {
                                                    UserId = member.UserId
                                                }, cqi.DepartmentTextNumber, cqi.Call.DepartmentId, profile, cqi.Address);
                                            }
                                            catch (SocketException sex)
                                            {
                                            }
                                            catch (Exception ex)
                                            {
                                                Logging.LogException(ex);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // Dispatch Roles
                    if (cqi.Call.RoleDispatches != null && cqi.Call.RoleDispatches.Any())
                    {
                        if (_rolesService == null)
                        {
                            _rolesService = Bootstrapper.GetKernel().Resolve <IPersonnelRolesService>();
                        }

                        foreach (var d in cqi.Call.RoleDispatches)
                        {
                            var members = await _rolesService.GetAllMembersOfRoleAsync(d.RoleId);

                            foreach (var member in members)
                            {
                                if (!dispatchedUsers.Contains(member.UserId))
                                {
                                    dispatchedUsers.Add(member.UserId);
                                    try
                                    {
                                        var profile = cqi.Profiles.FirstOrDefault(x => x.UserId == member.UserId);
                                        await _communicationService.SendCallAsync(cqi.Call, new CallDispatch()
                                        {
                                            UserId = member.UserId
                                        }, cqi.DepartmentTextNumber, cqi.Call.DepartmentId, profile, cqi.Address);
                                    }
                                    catch (SocketException sex)
                                    {
                                    }
                                    catch (Exception ex)
                                    {
                                        Logging.LogException(ex);
                                    }
                                }
                            }
                        }
                    }

                    // Send Call Print to Printer
                    if (_printerProvider == null)
                    {
                        _printerProvider = Bootstrapper.GetKernel().Resolve <IPrinterProvider>();
                    }

                    Dictionary <int, DepartmentGroup> fetchedGroups = new Dictionary <int, DepartmentGroup>();
                    if (cqi.Call.Dispatches != null && cqi.Call.Dispatches.Any())
                    {
                        foreach (var d in cqi.Call.Dispatches)
                        {
                            var group = await _departmentGroupsService.GetGroupForUserAsync(d.UserId, cqi.Call.DepartmentId);

                            if (group != null)
                            {
                                if (!groupIds.Contains(group.DepartmentGroupId))
                                {
                                    groupIds.Add(group.DepartmentGroupId);
                                }

                                if (!fetchedGroups.ContainsKey(group.DepartmentGroupId))
                                {
                                    fetchedGroups.Add(group.DepartmentGroupId, group);
                                }
                            }
                        }
                    }

                    foreach (var groupId in groupIds)
                    {
                        try
                        {
                            DepartmentGroup group = null;

                            if (fetchedGroups.ContainsKey(groupId))
                            {
                                group = fetchedGroups[groupId];
                            }
                            else
                            {
                                group = await _departmentGroupsService.GetGroupByIdAsync(groupId);
                            }

                            if (!String.IsNullOrWhiteSpace(group.PrinterData) && group.DispatchToPrinter)
                            {
                                var printerData = JsonConvert.DeserializeObject <DepartmentGroupPrinter>(group.PrinterData);
                                var apiKey      = SymmetricEncryption.Decrypt(printerData.ApiKey, Config.SystemBehaviorConfig.ExternalLinkUrlParamPassphrase);
                                var callUrl     = await _callsService.GetShortenedCallPdfUrl(cqi.Call.CallId, true, groupId);

                                var printJob = _printerProvider.SubmitPrintJob(apiKey, printerData.PrinterId, "CallPrint", callUrl);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                        }
                    }
                }
            }
            finally
            {
                _communicationService = null;
            }

            return(true);
        }
Beispiel #4
0
        public async Task <ActionResult> SendMessage([FromBody] NewMessageInput newMessageInput, CancellationToken cancellationToken)
        {
            if (newMessageInput.Rcps == null || newMessageInput.Rcps.Count <= 0)
            {
                return(BadRequest());
            }

            Message savedMessage = null;

            try
            {
                var message = new Message();
                message.Subject       = newMessageInput.Ttl;
                message.Body          = System.Net.WebUtility.HtmlDecode(newMessageInput.Bdy);
                message.IsBroadcast   = true;
                message.SendingUserId = UserId;
                message.Type          = newMessageInput.Typ;
                message.SentOn        = DateTime.UtcNow;

                var usersToSendTo = new List <string>();

                if (newMessageInput.Rcps.Any(x => x.Nme == "Everyone"))
                {
                    var departmentUsers = await _departmentsService.GetAllMembersForDepartmentAsync(DepartmentId);

                    foreach (var departmentMember in departmentUsers)
                    {
                        message.AddRecipient(departmentMember.UserId);
                    }
                }
                else
                {
                    // Add all the explict people
                    foreach (var person in newMessageInput.Rcps.Where(x => x.Typ == 1))
                    {
                        if (usersToSendTo.All(x => x != person.Id) && person.Id != UserId)
                        {
                            usersToSendTo.Add(person.Id);
                            message.AddRecipient(person.Id);
                        }
                    }

                    // Add all memebers of the group
                    foreach (var group in newMessageInput.Rcps.Where(x => x.Typ == 2))
                    {
                        if (!String.IsNullOrWhiteSpace(group.Id))
                        {
                            int groupId = 0;
                            if (int.TryParse(group.Id.Trim(), out groupId))
                            {
                                var members = await _departmentGroupsService.GetAllMembersForGroupAsync(groupId);

                                foreach (var member in members)
                                {
                                    if (usersToSendTo.All(x => x != member.UserId) && member.UserId != UserId)
                                    {
                                        usersToSendTo.Add(member.UserId);
                                        message.AddRecipient(member.UserId);
                                    }
                                }
                            }
                        }
                    }

                    // Add all the users of a specific role
                    foreach (var role in newMessageInput.Rcps.Where(x => x.Typ == 3))
                    {
                        var roleMembers = await _personnelRolesService.GetAllMembersOfRoleAsync(int.Parse(role.Id));

                        foreach (var member in roleMembers)
                        {
                            if (usersToSendTo.All(x => x != member.UserId) && member.UserId != UserId)
                            {
                                usersToSendTo.Add(member.UserId);
                                message.AddRecipient(member.UserId);
                            }
                        }
                    }
                }

                savedMessage = await _messageService.SaveMessageAsync(message, cancellationToken);

                await _messageService.SendMessageAsync(savedMessage, "", DepartmentId, false, cancellationToken);
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
                return(BadRequest());
            }

            return(CreatedAtAction(nameof(SendMessage), new { id = savedMessage.MessageId }, savedMessage));
        }