Exemplo n.º 1
0
        public Rss20FeedFormatter GetActiveCallsAsRSS(string key)
        {
            if (String.IsNullOrWhiteSpace(key))
            {
                return(null);
            }

            var departmentId = _departmentSettingsService.GetDepartmentIdForRssKey(key);

            if (!departmentId.HasValue)
            {
                return(null);
            }

            var department = _departmentsService.GetDepartmentById(departmentId.Value);
            var calls      = _callsService.GetActiveCallsByDepartment(departmentId.Value);

            var feed = new SyndicationFeed(string.Format("{0} Active Calls", department.Name), string.Format("The active calls for the department {0}", department.Name), new Uri(Config.SystemBehaviorConfig.ResgridBaseUrl));

            feed.Authors.Add(new SyndicationPerson("*****@*****.**"));
            feed.Categories.Add(new SyndicationCategory("Resgrid Calls"));
            feed.Description = new TextSyndicationContent(string.Format("The active calls for the department {0}", department.Name));
            feed.Items       = calls.Select(call => new SyndicationItem(call.Name, call.NatureOfCall, new Uri($"{Config.SystemBehaviorConfig.ResgridBaseUrl}/User/Dispatch/ViewCall?callId=" + call.CallId), call.CallId.ToString(), call.LoggedOn)).ToList();

            return(new Rss20FeedFormatter(feed));
        }
Exemplo n.º 2
0
        public List <RespondingOptionResult> GetRespondingOptions()
        {
            var result = new List <RespondingOptionResult>();

            var stations = _departmentGroupsService.GetAllStationGroupsForDepartment(DepartmentId);
            var calls    = _callsService.GetActiveCallsByDepartment(DepartmentId);

            /* Removed the Parallel.ForEach statement here as this data needs to be sorted
             * and there isn't enough sort data (at least for calls) for the client to do it.
             * Also during JMeter testing the perf gains wernt there (10ms average for both).
             */

            foreach (var s in stations.OrderBy(x => x.Name))
            {
                var respondingTo = new RespondingOptionResult();
                respondingTo.Id  = s.DepartmentGroupId;
                respondingTo.Typ = 1;
                respondingTo.Nme = "";

                result.Add(respondingTo);
            }

            foreach (var c in calls.OrderByDescending(x => x.LoggedOn))
            {
                var respondingTo = new RespondingOptionResult();
                respondingTo.Id  = c.CallId;
                respondingTo.Typ = 2;
                respondingTo.Nme = c.Name;

                result.Add(respondingTo);
            }

            return(result);
        }
Exemplo n.º 3
0
        public IActionResult GetActiveCallsList(int linkId)
        {
            var link = _departmentLinksService.GetLinkById(linkId);

            List <CallListJson> callsJson = new List <CallListJson>();

            if (link.DepartmentId != DepartmentId && link.LinkedDepartmentId != DepartmentId)
            {
                Unauthorized();
            }

            if (link.LinkEnabled && link.DepartmentShareCalls)
            {
                var calls      = _callsService.GetActiveCallsByDepartment(link.DepartmentId).OrderByDescending(x => x.LoggedOn);
                var department = _departmentsService.GetDepartmentById(link.DepartmentId, false);

                foreach (var call in calls)
                {
                    var callJson = new CallListJson();
                    callJson.CallId     = call.CallId;
                    callJson.Number     = call.Number;
                    callJson.Name       = call.Name;
                    callJson.State      = _callsService.CallStateToString((CallStates)call.State);
                    callJson.StateColor = _callsService.CallStateToColor((CallStates)call.State);
                    callJson.Timestamp  = call.LoggedOn.TimeConverterToString(department);
                    callJson.Priority   = _callsService.CallPriorityToString(call.Priority, link.DepartmentId);
                    callJson.Color      = _callsService.CallPriorityToColor(call.Priority, link.DepartmentId);

                    if (ClaimsAuthorizationHelper.IsUserDepartmentAdmin() || call.ReportingUserId == UserId)
                    {
                        callJson.CanDeleteCall = true;
                    }
                    else
                    {
                        callJson.CanDeleteCall = false;
                    }

                    callsJson.Add(callJson);
                }
            }

            return(Json(callsJson));
        }
Exemplo n.º 4
0
        public UnitAppPayloadResult GetCommandAppCoreData()
        {
            var results = new UnitAppPayloadResult();

            results.Personnel    = new List <PersonnelInfoResult>();
            results.Groups       = new List <GroupInfoResult>();
            results.Units        = new List <UnitInfoResult>();
            results.Roles        = new List <RoleInfoResult>();
            results.Statuses     = new List <CustomStatusesResult>();
            results.Calls        = new List <CallResult>();
            results.UnitStatuses = new List <UnitStatusCoreResult>();
            results.UnitRoles    = new List <UnitRoleResult>();

            var users  = _departmentsService.GetAllUsersForDepartment(DepartmentId);
            var groups = _departmentGroupsService.GetAllDepartmentGroupsForDepartment(DepartmentId);
            var rolesForUsersInDepartment = _personnelRolesService.GetAllRolesForUsersInDepartment(DepartmentId);
            var allRoles    = _personnelRolesService.GetRolesForDepartment(DepartmentId);
            var allProfiles = _userProfileService.GetAllProfilesForDepartment(DepartmentId);
            var allGroups   = _departmentGroupsService.GetAllGroupsForDepartment(DepartmentId);
            var units       = _unitsService.GetUnitsForDepartment(DepartmentId);
            var unitTypes   = _unitsService.GetUnitTypesForDepartment(DepartmentId);


            foreach (var user in users)
            {
                //var profile = _userProfileService.GetProfileByUserId(user.UserId);
                //var group = _departmentGroupsService.GetGroupForUser(user.UserId);

                UserProfile profile = null;
                if (allProfiles.ContainsKey(user.UserId))
                {
                    profile = allProfiles[user.UserId];
                }

                DepartmentGroup group = null;
                if (groups.ContainsKey(user.UserId))
                {
                    group = groups[user.UserId];
                }

                //var roles = _personnelRolesService.GetRolesForUser(user.UserId);

                List <PersonnelRole> roles = null;
                if (rolesForUsersInDepartment.ContainsKey(user.UserId))
                {
                    roles = rolesForUsersInDepartment[user.UserId];
                }

                var result = new PersonnelInfoResult();

                if (profile != null)
                {
                    result.Fnm = profile.FirstName;
                    result.Lnm = profile.LastName;
                    result.Id  = profile.IdentificationNumber;
                    result.Mnu = profile.MobileNumber;
                }
                else
                {
                    result.Fnm = "Unknown";
                    result.Lnm = "Check Profile";
                    result.Id  = "";
                    result.Mnu = "";
                }

                result.Eml = user.Email;
                result.Did = DepartmentId;
                result.Uid = user.UserId.ToString();

                if (group != null)
                {
                    result.Gid = group.DepartmentGroupId;
                    result.Gnm = group.Name;
                }

                result.Roles = new List <string>();
                if (roles != null && roles.Count > 0)
                {
                    foreach (var role in roles)
                    {
                        if (role != null)
                        {
                            result.Roles.Add(role.Name);
                        }
                    }
                }

                results.Personnel.Add(result);
            }


            results.Rights = new DepartmentRightsResult();
            var currentUser = _usersService.GetUserByName(UserName);

            if (currentUser == null)
            {
                throw HttpStatusCode.Unauthorized.AsException();
            }

            var department = _departmentsService.GetDepartmentById(DepartmentId, false);

            results.Rights.Adm  = department.IsUserAnAdmin(currentUser.UserId);
            results.Rights.Grps = new List <GroupRight>();

            var currentGroup = _departmentGroupsService.GetGroupForUser(currentUser.UserId, DepartmentId);

            if (currentGroup != null)
            {
                var groupRight = new GroupRight();
                groupRight.Gid = currentGroup.DepartmentGroupId;
                groupRight.Adm = currentGroup.IsUserGroupAdmin(currentUser.UserId);

                results.Rights.Grps.Add(groupRight);
            }

            foreach (var group in allGroups)
            {
                var groupInfo = new GroupInfoResult();
                groupInfo.Gid = group.DepartmentGroupId;
                groupInfo.Nme = group.Name;

                if (group.Type.HasValue)
                {
                    groupInfo.Typ = group.Type.Value;
                }

                if (group.Address != null)
                {
                    groupInfo.Add = group.Address.FormatAddress();
                }

                results.Groups.Add(groupInfo);
            }

            foreach (var unit in units)
            {
                var unitResult = new UnitInfoResult();
                unitResult.Uid = unit.UnitId;
                unitResult.Did = DepartmentId;
                unitResult.Nme = unit.Name;
                unitResult.Typ = unit.Type;

                if (!string.IsNullOrWhiteSpace(unit.Type))
                {
                    var unitType = unitTypes.FirstOrDefault(x => x.Type == unit.Type);

                    if (unitType != null)
                    {
                        unitResult.Cid = unitType.CustomStatesId.GetValueOrDefault();
                    }
                }
                else
                {
                    unitResult.Cid = 0;
                }

                if (unit.StationGroup != null)
                {
                    unitResult.Sid = unit.StationGroup.DepartmentGroupId;
                    unitResult.Snm = unit.StationGroup.Name;
                }

                results.Units.Add(unitResult);

                // Add unit roles for this unit
                var roles = _unitsService.GetRolesForUnit(unit.UnitId);
                foreach (var role in roles)
                {
                    var roleResult = new UnitRoleResult();
                    roleResult.Name       = role.Name;
                    roleResult.UnitId     = role.UnitId;
                    roleResult.UnitRoleId = role.UnitRoleId;

                    results.UnitRoles.Add(roleResult);
                }
            }

            var unitStatuses = _unitsService.GetAllLatestStatusForUnitsByDepartmentId(DepartmentId);

            foreach (var us in unitStatuses)
            {
                var unitStatus = new UnitStatusCoreResult();
                unitStatus.UnitId      = us.UnitId;
                unitStatus.StateType   = (UnitStateTypes)us.State;
                unitStatus.StateTypeId = us.State;
                unitStatus.Type        = us.Unit.Type;
                unitStatus.Timestamp   = us.Timestamp.TimeConverter(department);
                unitStatus.Name        = us.Unit.Name;

                if (us.DestinationId.HasValue)
                {
                    unitStatus.DestinationId = us.DestinationId.Value;
                }

                results.UnitStatuses.Add(unitStatus);
            }

            foreach (var role in allRoles)
            {
                var roleResult = new RoleInfoResult();
                roleResult.Rid = role.PersonnelRoleId;
                roleResult.Nme = role.Name;

                results.Roles.Add(roleResult);
            }

            var customStates = _customStateService.GetAllActiveCustomStatesForDepartment(DepartmentId);

            foreach (var customState in customStates)
            {
                if (customState.IsDeleted)
                {
                    continue;
                }

                foreach (var stateDetail in customState.GetActiveDetails())
                {
                    if (stateDetail.IsDeleted)
                    {
                        continue;
                    }

                    var customStateResult = new CustomStatusesResult();
                    customStateResult.Id      = stateDetail.CustomStateDetailId;
                    customStateResult.Type    = customState.Type;
                    customStateResult.StateId = stateDetail.CustomStateId;
                    customStateResult.Text    = stateDetail.ButtonText;
                    customStateResult.BColor  = stateDetail.ButtonColor;
                    customStateResult.Color   = stateDetail.TextColor;
                    customStateResult.Gps     = stateDetail.GpsRequired;
                    customStateResult.Note    = stateDetail.NoteType;
                    customStateResult.Detail  = stateDetail.DetailType;

                    results.Statuses.Add(customStateResult);
                }
            }

            var calls = _callsService.GetActiveCallsByDepartment(DepartmentId).OrderByDescending(x => x.LoggedOn);

            if (calls != null && calls.Any())
            {
                foreach (var c in calls)
                {
                    var call = new CallResult();

                    call.Cid = c.CallId;
                    call.Pri = c.Priority;
                    call.Ctl = c.IsCritical;
                    call.Nme = c.Name;
                    call.Noc = c.NatureOfCall;
                    call.Map = c.MapPage;
                    call.Not = c.Notes;

                    if (String.IsNullOrWhiteSpace(c.Address) && !String.IsNullOrWhiteSpace(c.GeoLocationData))
                    {
                        var geo = c.GeoLocationData.Split(char.Parse(","));

                        if (geo.Length == 2)
                        {
                            call.Add = _geoLocationProvider.GetAddressFromLatLong(double.Parse(geo[0]), double.Parse(geo[1]));
                        }
                    }
                    else
                    {
                        call.Add = c.Address;
                    }

                    call.Add = c.Address;
                    call.Geo = c.GeoLocationData;
                    call.Lon = c.LoggedOn.TimeConverter(department);
                    call.Ste = c.State;
                    call.Num = c.Number;

                    results.Calls.Add(call);
                }
            }
            else
            {
                // This is a hack due to a bug in the current units app! -SJ 1-31-2016
                var call = new CallResult();
                call.Cid = 0;
                call.Pri = 0;
                call.Ctl = false;
                call.Nme = "No Call";
                call.Noc = "";
                call.Map = "";
                call.Not = "";
                call.Add = "";
                call.Geo = "";
                call.Lon = DateTime.UtcNow;
                call.Ste = 0;
                call.Num = "";

                results.Calls.Add(call);
            }


            return(results);
        }
Exemplo n.º 5
0
        public List <CallResult> GetActiveCalls()
        {
            var result = new List <CallResult>();

            var calls      = _callsService.GetActiveCallsByDepartment(DepartmentId).OrderByDescending(x => x.LoggedOn);
            var department = _departmentsService.GetDepartmentById(DepartmentId, false);

            foreach (var c in calls)
            {
                var call = new CallResult();

                call.Cid = c.CallId;
                call.Pri = c.Priority;
                call.Ctl = c.IsCritical;
                call.Nme = StringHelpers.SanitizeHtmlInString(c.Name);

                if (!String.IsNullOrWhiteSpace(c.NatureOfCall))
                {
                    call.Noc = StringHelpers.SanitizeHtmlInString(c.NatureOfCall);
                }

                call.Map = c.MapPage;

                if (!String.IsNullOrWhiteSpace(c.Notes))
                {
                    call.Not = StringHelpers.SanitizeHtmlInString(c.Notes);
                }

                if (c.CallNotes != null)
                {
                    call.Nts = c.CallNotes.Count();
                }
                else
                {
                    call.Nts = 0;
                }

                if (c.Attachments != null)
                {
                    call.Aud = c.Attachments.Count(x => x.CallAttachmentType == (int)CallAttachmentTypes.DispatchAudio);
                    call.Img = c.Attachments.Count(x => x.CallAttachmentType == (int)CallAttachmentTypes.Image);
                    call.Fls = c.Attachments.Count(x => x.CallAttachmentType == (int)CallAttachmentTypes.File);
                }
                else
                {
                    call.Aud = 0;
                    call.Img = 0;
                    call.Fls = 0;
                }

                if (String.IsNullOrWhiteSpace(c.Address) && !String.IsNullOrWhiteSpace(c.GeoLocationData))
                {
                    var geo = c.GeoLocationData.Split(char.Parse(","));

                    if (geo.Length == 2)
                    {
                        call.Add = _geoLocationProvider.GetAddressFromLatLong(double.Parse(geo[0]), double.Parse(geo[1]));
                    }
                }
                else
                {
                    call.Add = c.Address;
                }

                call.Geo = c.GeoLocationData;
                call.Lon = c.LoggedOn.TimeConverter(department);
                call.Utc = c.LoggedOn;
                call.Ste = c.State;
                call.Num = c.Number;

                result.Add(call);
            }

            return(result);
        }
Exemplo n.º 6
0
        public HttpResponseMessage IncomingMessage([FromUri] TwilioMessage request)
        {
            if (request == null || string.IsNullOrWhiteSpace(request.To) || string.IsNullOrWhiteSpace(request.From) || string.IsNullOrWhiteSpace(request.Body))
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }

            var response = new TwilioResponse();

            var textMessage = new TextMessage();

            textMessage.To        = request.To.Replace("+", "");
            textMessage.Msisdn    = request.From.Replace("+", "");
            textMessage.MessageId = request.MessageSid;
            textMessage.Timestamp = DateTime.UtcNow.ToLongDateString();
            textMessage.Data      = request.Body;
            textMessage.Text      = request.Body;

            var messageEvent = new InboundMessageEvent();

            messageEvent.MessageType = (int)InboundMessageTypes.TextMessage;
            messageEvent.RecievedOn  = DateTime.UtcNow;
            messageEvent.Type        = typeof(InboundMessageEvent).FullName;
            messageEvent.Data        = JsonConvert.SerializeObject(textMessage);
            messageEvent.Processed   = false;
            messageEvent.CustomerId  = "";

            try
            {
                var departmentId = _departmentSettingsService.GetDepartmentIdByTextToCallNumber(textMessage.To);

                if (departmentId.HasValue)
                {
                    var department         = _departmentsService.GetDepartmentById(departmentId.Value);
                    var textToCallEnabled  = _departmentSettingsService.GetDepartmentIsTextCallImportEnabled(departmentId.Value);
                    var textCommandEnabled = _departmentSettingsService.GetDepartmentIsTextCommandEnabled(departmentId.Value);
                    var dispatchNumbers    = _departmentSettingsService.GetTextToCallSourceNumbersForDepartment(departmentId.Value);
                    var authroized         = _limitsService.CanDepartmentProvisionNumber(departmentId.Value);
                    var customStates       = _customStateService.GetAllActiveCustomStatesForDepartment(departmentId.Value);

                    messageEvent.CustomerId = departmentId.Value.ToString();

                    if (authroized)
                    {
                        bool isDispatchSource = false;

                        if (!String.IsNullOrWhiteSpace(dispatchNumbers))
                        {
                            isDispatchSource = _numbersService.DoesNumberMatchAnyPattern(dispatchNumbers.Split(Char.Parse(",")).ToList(), textMessage.Msisdn);
                        }

                        // If we don't have dispatchNumbers and Text Command isn't enabled it's a dispatch text
                        if (!isDispatchSource && !textCommandEnabled)
                        {
                            isDispatchSource = true;
                        }

                        if (isDispatchSource && textToCallEnabled)
                        {
                            var c = new Call();
                            c.Notes            = textMessage.Text;
                            c.NatureOfCall     = textMessage.Text;
                            c.LoggedOn         = DateTime.UtcNow;
                            c.Name             = string.Format("TTC {0}", c.LoggedOn.TimeConverter(department).ToString("g"));
                            c.Priority         = (int)CallPriority.High;
                            c.ReportingUserId  = department.ManagingUserId;
                            c.Dispatches       = new Collection <CallDispatch>();
                            c.CallSource       = (int)CallSources.EmailImport;
                            c.SourceIdentifier = textMessage.MessageId;
                            c.DepartmentId     = departmentId.Value;

                            var users = _departmentsService.GetAllUsersForDepartment(departmentId.Value, true);
                            foreach (var u in users)
                            {
                                var cd = new CallDispatch();
                                cd.UserId = u.UserId;

                                c.Dispatches.Add(cd);
                            }

                            var savedCall = _callsService.SaveCall(c);

                            var cqi = new CallQueueItem();
                            cqi.Call                 = savedCall;
                            cqi.Profiles             = _userProfileService.GetSelectedUserProfiles(users.Select(x => x.UserId).ToList());
                            cqi.DepartmentTextNumber = _departmentSettingsService.GetTextToCallNumberForDepartment(cqi.Call.DepartmentId);

                            _queueService.EnqueueCallBroadcast(cqi);

                            messageEvent.Processed = true;
                        }

                        if (!isDispatchSource && textCommandEnabled)
                        {
                            var profile = _userProfileService.FindProfileByMobileNumber(textMessage.Msisdn);

                            if (profile != null)
                            {
                                var payload        = _textCommandService.DetermineType(textMessage.Text);
                                var customActions  = customStates.FirstOrDefault(x => x.Type == (int)CustomStateTypes.Personnel);
                                var customStaffing = customStates.FirstOrDefault(x => x.Type == (int)CustomStateTypes.Staffing);

                                switch (payload.Type)
                                {
                                case TextCommandTypes.None:
                                    response.Message("Resgrid (https://resgrid.com) Automated Text System. Unknown command, text help for supported commands.");
                                    break;

                                case TextCommandTypes.Help:
                                    messageEvent.Processed = true;

                                    var help = new StringBuilder();
                                    help.Append("Resgrid Text Commands" + Environment.NewLine);
                                    help.Append("---------------------" + Environment.NewLine);
                                    help.Append("These are the commands you can text to alter your status and staffing. Text help for help." + Environment.NewLine);
                                    help.Append("---------------------" + Environment.NewLine);
                                    help.Append("Core Commands" + Environment.NewLine);
                                    help.Append("---------------------" + Environment.NewLine);
                                    help.Append("STOP: To turn off all text messages" + Environment.NewLine);
                                    help.Append("HELP: This help text" + Environment.NewLine);
                                    help.Append("CALLS: List active calls" + Environment.NewLine);
                                    help.Append("C[CallId]: Get Call Detail i.e. C1445" + Environment.NewLine);
                                    help.Append("UNITS: List unit statuses" + Environment.NewLine);
                                    help.Append("---------------------" + Environment.NewLine);
                                    help.Append("Status or Action Commands" + Environment.NewLine);
                                    help.Append("---------------------" + Environment.NewLine);

                                    if (customActions != null && customActions.IsDeleted == false && customActions.GetActiveDetails() != null && customActions.GetActiveDetails().Any())
                                    {
                                        var activeDetails = customActions.GetActiveDetails();
                                        for (int i = 0; i < activeDetails.Count; i++)
                                        {
                                            help.Append($"{activeDetails[i].ButtonText.Trim().Replace(" ", "").Replace("-", "").Replace(":", "")} or {i + 1}: {activeDetails[i].ButtonText}" + Environment.NewLine);
                                        }
                                    }
                                    else
                                    {
                                        help.Append("responding or 1: Responding" + Environment.NewLine);
                                        help.Append("notresponding or 2: Not Responding" + Environment.NewLine);
                                        help.Append("onscene or 3: On Scene" + Environment.NewLine);
                                        help.Append("available or 4: Available" + Environment.NewLine);
                                    }
                                    help.Append("---------------------" + Environment.NewLine);
                                    help.Append("Staffing Commands" + Environment.NewLine);
                                    help.Append("---------------------" + Environment.NewLine);

                                    if (customStaffing != null && customStaffing.IsDeleted == false && customStaffing.GetActiveDetails() != null && customStaffing.GetActiveDetails().Any())
                                    {
                                        var activeDetails = customStaffing.GetActiveDetails();
                                        for (int i = 0; i < activeDetails.Count; i++)
                                        {
                                            help.Append($"{activeDetails[i].ButtonText.Trim().Replace(" ", "").Replace("-", "").Replace(":", "")} or S{i + 1}: {activeDetails[i].ButtonText}" + Environment.NewLine);
                                        }
                                    }
                                    else
                                    {
                                        help.Append("available or s1: Available Staffing" + Environment.NewLine);
                                        help.Append("delayed or s2: Delayed Staffing" + Environment.NewLine);
                                        help.Append("unavailable or s3: Unavailable Staffing" + Environment.NewLine);
                                        help.Append("committed or s4: Committed Staffing" + Environment.NewLine);
                                        help.Append("onshift or s4: On Shift Staffing" + Environment.NewLine);
                                    }

                                    response.Message(help.ToString());

                                    //_communicationService.SendTextMessage(profile.UserId, "Resgrid TCI Help", help.ToString(), department.DepartmentId, textMessage.To, profile);
                                    break;

                                case TextCommandTypes.Action:
                                    messageEvent.Processed = true;
                                    _actionLogsService.SetUserAction(profile.UserId, department.DepartmentId, (int)payload.GetActionType());
                                    response.Message(string.Format("Resgrid recieved your text command. Status changed to: {0}", payload.GetActionType()));
                                    //_communicationService.SendTextMessage(profile.UserId, "Resgrid TCI Status", string.Format("Resgrid recieved your text command. Status changed to: {0}", payload.GetActionType()), department.DepartmentId, textMessage.To, profile);
                                    break;

                                case TextCommandTypes.Staffing:
                                    messageEvent.Processed = true;
                                    _userStateService.CreateUserState(profile.UserId, department.DepartmentId, (int)payload.GetStaffingType());
                                    response.Message(string.Format("Resgrid recieved your text command. Staffing level changed to: {0}", payload.GetStaffingType()));
                                    //_communicationService.SendTextMessage(profile.UserId, "Resgrid TCI Staffing", string.Format("Resgrid recieved your text command. Staffing level changed to: {0}", payload.GetStaffingType()), department.DepartmentId, textMessage.To, profile);
                                    break;

                                case TextCommandTypes.Stop:
                                    messageEvent.Processed = true;
                                    _userProfileService.DisableTextMessagesForUser(profile.UserId);
                                    response.Message("Text messages are now turned off for this user, to enable again log in to Resgrid and update your profile.");
                                    break;

                                case TextCommandTypes.CustomAction:
                                    messageEvent.Processed = true;
                                    _actionLogsService.SetUserAction(profile.UserId, department.DepartmentId, payload.GetCustomActionType());

                                    if (customActions != null && customActions.IsDeleted == false && customActions.GetActiveDetails() != null && customActions.GetActiveDetails().Any() && customActions.GetActiveDetails().FirstOrDefault(x => x.CustomStateDetailId == payload.GetCustomActionType()) != null)
                                    {
                                        var detail = customActions.GetActiveDetails().FirstOrDefault(x => x.CustomStateDetailId == payload.GetCustomActionType());
                                        response.Message(string.Format("Resgrid recieved your text command. Status changed to: {0}", detail.ButtonText));
                                    }
                                    else
                                    {
                                        response.Message("Resgrid recieved your text command and updated your status");
                                    }
                                    break;

                                case TextCommandTypes.CustomStaffing:
                                    messageEvent.Processed = true;
                                    _userStateService.CreateUserState(profile.UserId, department.DepartmentId, payload.GetCustomStaffingType());

                                    if (customStaffing != null && customStaffing.IsDeleted == false && customStaffing.GetActiveDetails() != null && customStaffing.GetActiveDetails().Any() && customStaffing.GetActiveDetails().FirstOrDefault(x => x.CustomStateDetailId == payload.GetCustomStaffingType()) != null)
                                    {
                                        var detail = customStaffing.GetActiveDetails().FirstOrDefault(x => x.CustomStateDetailId == payload.GetCustomStaffingType());
                                        response.Message(string.Format("Resgrid recieved your text command. Staffing changed to: {0}", detail.ButtonText));
                                    }
                                    else
                                    {
                                        response.Message("Resgrid recieved your text command and updated your staffing");
                                    }
                                    break;

                                case TextCommandTypes.MyStatus:
                                    messageEvent.Processed = true;


                                    var userStatus   = _actionLogsService.GetLastActionLogForUser(profile.UserId);
                                    var userStaffing = _userStateService.GetLastUserStateByUserId(profile.UserId);

                                    var customStatusLevel   = _customStateService.GetCustomPersonnelStatus(department.DepartmentId, userStatus);
                                    var customStaffingLevel = _customStateService.GetCustomPersonnelStaffing(department.DepartmentId, userStaffing);

                                    response.Message($"Hello {profile.FullName.AsFirstNameLastName} at {DateTime.UtcNow.TimeConverterToString(department)} your current status is {customStatusLevel.ButtonText} and your current staffing is {customStaffingLevel.ButtonText}.");
                                    break;

                                case TextCommandTypes.Calls:
                                    messageEvent.Processed = true;

                                    var activeCalls = _callsService.GetActiveCallsByDepartment(department.DepartmentId);

                                    var activeCallText = new StringBuilder();
                                    activeCallText.Append($"Active Calls for {department.Name}" + Environment.NewLine);
                                    activeCallText.Append("---------------------" + Environment.NewLine);

                                    foreach (var activeCall in activeCalls)
                                    {
                                        activeCallText.Append($"CallId: {activeCall.CallId} Name: {activeCall.Name} Nature:{activeCall.NatureOfCall}" + Environment.NewLine);
                                    }


                                    response.Message(activeCallText.ToString());
                                    break;

                                case TextCommandTypes.Units:
                                    messageEvent.Processed = true;

                                    var unitStatus = _unitsService.GetAllLatestStatusForUnitsByDepartmentId(department.DepartmentId);

                                    var unitStatusesText = new StringBuilder();
                                    unitStatusesText.Append($"Unit Statuses for {department.Name}" + Environment.NewLine);
                                    unitStatusesText.Append("---------------------" + Environment.NewLine);

                                    foreach (var unit in unitStatus)
                                    {
                                        var unitState = _customStateService.GetCustomUnitState(unit);
                                        unitStatusesText.Append($"{unit.Unit.Name} is {unitState.ButtonText}" + Environment.NewLine);
                                    }

                                    response.Message(unitStatusesText.ToString());
                                    break;

                                case TextCommandTypes.CallDetail:
                                    messageEvent.Processed = true;

                                    var call = _callsService.GetCallById(int.Parse(payload.Data));

                                    var callText = new StringBuilder();
                                    callText.Append($"Call Information for {call.Name}" + Environment.NewLine);
                                    callText.Append("---------------------" + Environment.NewLine);
                                    callText.Append($"Id: {call.CallId}" + Environment.NewLine);
                                    callText.Append($"Number: {call.Number}" + Environment.NewLine);
                                    callText.Append($"Logged: {call.LoggedOn.TimeConverterToString(department)}" + Environment.NewLine);
                                    callText.Append("-----Nature-----" + Environment.NewLine);
                                    callText.Append(call.NatureOfCall + Environment.NewLine);
                                    callText.Append("-----Address-----" + Environment.NewLine);

                                    if (!String.IsNullOrWhiteSpace(call.Address))
                                    {
                                        callText.Append(call.Address + Environment.NewLine);
                                    }
                                    else if (!string.IsNullOrEmpty(call.GeoLocationData))
                                    {
                                        try
                                        {
                                            string[] points = call.GeoLocationData.Split(char.Parse(","));

                                            if (points != null && points.Length == 2)
                                            {
                                                callText.Append(_geoLocationProvider.GetAproxAddressFromLatLong(double.Parse(points[0]), double.Parse(points[1])) + Environment.NewLine);
                                            }
                                        }
                                        catch
                                        {
                                        }
                                    }

                                    response.Message(callText.ToString());
                                    break;
                                }
                            }
                        }
                    }
                }
                else if (textMessage.To == "17753765253")                 // Resgrid master text number
                {
                    var profile = _userProfileService.FindProfileByMobileNumber(textMessage.Msisdn);
                    var payload = _textCommandService.DetermineType(textMessage.Text);

                    switch (payload.Type)
                    {
                    case TextCommandTypes.None:
                        response.Message("Resgrid (https://resgrid.com) Automated Text System. Unknown command, text help for supported commands.");
                        break;

                    case TextCommandTypes.Help:
                        messageEvent.Processed = true;

                        var help = new StringBuilder();
                        help.Append("Resgrid Text Commands" + Environment.NewLine);
                        help.Append("---------------------" + Environment.NewLine);
                        help.Append("This is the Resgrid system for first responders (https://resgrid.com) automated text system. Your department isn't signed up for inbound text messages, but you can send the following commands." + Environment.NewLine);
                        help.Append("---------------------" + Environment.NewLine);
                        help.Append("STOP: To turn off all text messages" + Environment.NewLine);
                        help.Append("HELP: This help text" + Environment.NewLine);

                        response.Message(help.ToString());

                        break;

                    case TextCommandTypes.Stop:
                        messageEvent.Processed = true;
                        _userProfileService.DisableTextMessagesForUser(profile.UserId);
                        response.Message("Text messages are now turned off for this user, to enable again log in to Resgrid and update your profile.");
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Framework.Logging.LogException(ex);
            }
            finally
            {
                _numbersService.SaveInboundMessageEvent(messageEvent);
            }

            //return Request.CreateResponse(HttpStatusCode.OK);

            //var response = new TwilioResponse();

            return(Request.CreateResponse(HttpStatusCode.OK, response.Element, new XmlMediaTypeFormatter()));
        }
Exemplo n.º 7
0
        public IActionResult GetUnitOptionsDropdown(int unitId)
        {
            string buttonHtml = string.Empty;


            var unit = _unitsService.GetUnitById(unitId);
            var type = _unitsService.GetUnitTypeByName(DepartmentId, unit.Type);

            if (type != null && type.CustomStatesId.HasValue)
            {
                var customStates = _customStateService.GetCustomSateById(type.CustomStatesId.Value);
                var activeCalls  = _callsService.GetActiveCallsByDepartment(DepartmentId);
                var stations     = _departmentGroupsService.GetAllStationGroupsForDepartment(DepartmentId);

                StringBuilder sb = new StringBuilder();
                sb.Append($"<ul class='dropdown-menu multi-level unitStateList_{unitId}'>");

                foreach (var state in customStates.GetActiveDetails().OrderBy(x => x.Order))
                {
                    if (state.DetailType == (int)CustomStateDetailTypes.None)
                    {
                        sb.Append("<li><a style='color:" + state.ButtonColor + ";' href='/User/Units/SetUnitState?unitId=" + unitId + "&stateType=" + state.CustomStateDetailId + "'>" + state.ButtonText + "</a></li>");
                    }
                    else if (state.DetailType == (int)CustomStateDetailTypes.Calls)
                    {
                        sb.Append($"<li class='dropdown-submenu'><a style='color:{state.ButtonColor};' tabindex='-1' href='#'>{state.ButtonText}</a>");
                        sb.Append($"<ul class='dropdown-menu unitStateList_{unitId}'>");
                        sb.Append($"<li><a href='/User/Units/SetUnitState?unitId={unitId}&stateType={state.CustomStateDetailId}'>{state.ButtonText}</a></li>");
                        sb.Append("<li class='divider'></li>");
                        sb.Append("<li class='dropdown-header'>Calls</li>");

                        foreach (var call in activeCalls)
                        {
                            sb.Append($"<li><a href='/User/Units/SetUnitStateWithDest?unitId={unitId}&stateType={state.CustomStateDetailId}&type=2&destination={call.CallId}'>{call.GetIdentifier()}:{call.Name}</a></li>");
                        }

                        sb.Append("</ul>");
                    }
                    else if (state.DetailType == (int)CustomStateDetailTypes.Stations)
                    {
                        sb.Append($"<li class='dropdown-submenu'><a style='color:{state.ButtonColor};' tabindex='-1' href='#'>{state.ButtonText}</a>");
                        sb.Append($"<ul class='dropdown-menu unitStateList_{unitId}'>");
                        sb.Append($"<li><a href='/User/Units/SetUnitState?unitId={unitId}&stateType={state.CustomStateDetailId}'>{state.ButtonText}</a></li>");
                        sb.Append("<li class='divider'></li>");
                        sb.Append("<li class='dropdown-header'>Stations</li>");

                        foreach (var station in stations)
                        {
                            sb.Append("<li><a href='/User/Units/SetUnitStateWithDest?unitId=" + unitId + "&stateType=" + state.CustomStateDetailId + "&type=2&destination=" + station.DepartmentGroupId + "'>" + station.Name + "</a></li>");
                        }

                        sb.Append("</ul>");
                    }
                    else if (state.DetailType == (int)CustomStateDetailTypes.CallsAndStations)
                    {
                        sb.Append($"<li class='dropdown-submenu'><a style='color:{state.ButtonColor};' tabindex='-1' href='#'>{state.ButtonText}</a>");
                        sb.Append($"<ul class='dropdown-menu unitStateList_{unitId}'>");
                        sb.Append($"<li><a href='/User/Units/SetUnitState?unitId={unitId}&stateType={state.CustomStateDetailId}'>{state.ButtonText}</a></li>");
                        sb.Append("<li class='divider'></li>");
                        sb.Append("<li class='dropdown-header'>Calls</li>");

                        foreach (var call in activeCalls)
                        {
                            sb.Append($"<li><a href='/User/Units/SetUnitStateWithDest?unitId={unitId}&stateType={state.CustomStateDetailId}&type=2&destination={call.CallId}'>{call.GetIdentifier()}:{call.Name}</a></li>");
                        }

                        sb.Append("<li class='dropdown-header'>Stations</li>");

                        foreach (var station in stations)
                        {
                            sb.Append($"<li><a href='/User/Units/SetUnitStateWithDest?unitId={unitId}&stateType={state.CustomStateDetailId}&type=2&destination={station.DepartmentGroupId}'>{station.Name}</a></li>");
                        }

                        sb.Append("</ul>");
                    }
                }
                sb.Append("</ul>");

                buttonHtml = sb.ToString();
            }

            if (String.IsNullOrWhiteSpace(buttonHtml))
            {
                StringBuilder sb = new StringBuilder();
                sb.Append($"<ul class='dropdown-menu unitStateList_{unitId}'>");
                sb.Append($"<li><a href='/User/Units/SetUnitState?unitId={unitId}&stateType=0'>Available</a></li>");
                sb.Append($"<li><a href='/User/Units/SetUnitState?unitId={unitId}&stateType=3'>Committed</a></li>");
                sb.Append($"<li><a href='/User/Units/SetUnitState?unitId={unitId}&stateType=1'>Delayed</a></li>");
                sb.Append($"<li><a href='/User/Units/SetUnitState?unitId={unitId}&stateType=4'>Out Of Service</a></li>");
                sb.Append($"<li><a href='/User/Units/SetUnitState?unitId={unitId}&stateType=2'>Unavailable</a></li>");
                sb.Append("</ul>");

                buttonHtml = sb.ToString();
            }

            return(Content(buttonHtml));
        }
Exemplo n.º 8
0
        public HttpResponseMessage Receive(PostmarkInboundMessage message)
        {
            if (message != null)
            {
                try
                {
                    var mailMessage = new MimeMessage();

                    if (message.FromFull != null && !String.IsNullOrWhiteSpace(message.FromFull.Email) && message.FromFull.Email.Trim() == "*****@*****.**")
                    {
                        return(new HttpResponseMessage(HttpStatusCode.Created));
                    }

                    if (message.FromFull != null && !String.IsNullOrWhiteSpace(message.FromFull.Email) && !String.IsNullOrWhiteSpace(message.FromFull.Name))
                    {
                        mailMessage.From.Add(new MailboxAddress(message.FromFull.Name.Trim(), message.FromFull.Email.Trim()));
                    }
                    else
                    {
                        mailMessage.From.Add(new MailboxAddress("Inbound Email Dispatch", "*****@*****.**"));
                    }

                    if (!String.IsNullOrWhiteSpace(message.Subject))
                    {
                        mailMessage.Subject = message.Subject;
                    }
                    else
                    {
                        mailMessage.Subject = "Dispatch Email";
                    }

                    var builder = new BodyBuilder();

                    if (!String.IsNullOrWhiteSpace(message.HtmlBody))
                    {
                        builder.HtmlBody = HttpUtility.HtmlDecode(message.HtmlBody);
                    }

                    if (!String.IsNullOrWhiteSpace(message.TextBody))
                    {
                        builder.TextBody = message.TextBody;
                    }

                    int    type         = 0;          // 1 = dispatch // 2 = email list // 3 = group dispatch // 4 = group message
                    string emailAddress = String.Empty;
                    string bounceEmail  = String.Empty;
                    string name         = String.Empty;

                    #region Trying to Find What type of email this is
                    foreach (var email in message.ToFull)
                    {
                        if (StringHelpers.ValidateEmail(email.Email))
                        {
                            if (email.Email.Contains($"@{Config.InboundEmailConfig.DispatchDomain}") || email.Email.Contains($"@{Config.InboundEmailConfig.DispatchTestDomain}"))
                            {
                                type = 1;

                                if (email.Email.Contains($"@{Config.InboundEmailConfig.DispatchDomain}"))
                                {
                                    emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.DispatchDomain}", "");
                                }
                                else
                                {
                                    emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.DispatchTestDomain}", "");
                                }

                                name = email.Name;
                                mailMessage.To.Clear();
                                mailMessage.To.Add(new MailboxAddress(email.Name, email.Email));

                                break;
                            }
                            else if (email.Email.Contains($"@{Config.InboundEmailConfig.ListsDomain}") || email.Email.Contains($"@{Config.InboundEmailConfig.ListsTestDomain}"))
                            {
                                type = 2;

                                if (email.Email.Contains($"@{Config.InboundEmailConfig.ListsDomain}"))
                                {
                                    emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.ListsDomain}", "");
                                }
                                else
                                {
                                    emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.ListsTestDomain}", "");
                                }

                                if (emailAddress.Contains("+") && emailAddress.Contains("="))
                                {
                                    var tempBounceEmail = emailAddress.Substring(emailAddress.IndexOf("+") + 1);
                                    bounceEmail = tempBounceEmail.Replace("=", "@");

                                    emailAddress = emailAddress.Replace(tempBounceEmail, "");
                                    emailAddress = emailAddress.Replace("+", "");
                                }

                                name = email.Name;
                                mailMessage.To.Clear();
                                mailMessage.To.Add(new MailboxAddress(email.Name, email.Email));

                                break;
                            }
                            else if (email.Email.Contains($"@{Config.InboundEmailConfig.GroupsDomain}") || email.Email.Contains($"@{Config.InboundEmailConfig.GroupsTestDomain}"))
                            {
                                type = 3;

                                if (email.Email.Contains($"@{Config.InboundEmailConfig.GroupsDomain}"))
                                {
                                    emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.GroupsDomain}", "");
                                }
                                else
                                {
                                    emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.GroupsTestDomain}", "");
                                }

                                name = email.Name;
                                mailMessage.To.Clear();
                                mailMessage.To.Add(new MailboxAddress(email.Name, email.Email));

                                break;
                            }
                            else if (email.Email.Contains($"@{Config.InboundEmailConfig.GroupMessageDomain}") || email.Email.Contains($"@{Config.InboundEmailConfig.GroupTestMessageDomain}"))
                            {
                                type = 4;

                                if (email.Email.Contains($"@{Config.InboundEmailConfig.GroupMessageDomain}"))
                                {
                                    emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.GroupMessageDomain}", "");
                                }
                                else
                                {
                                    emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.GroupTestMessageDomain}", "");
                                }

                                name = email.Name;
                                mailMessage.To.Clear();
                                mailMessage.To.Add(new MailboxAddress(email.Name, email.Email));

                                break;
                            }
                        }
                    }

                    // Some providers aren't putting email address in the To line, process the CC line
                    if (type == 0)
                    {
                        foreach (var email in message.CcFull)
                        {
                            if (StringHelpers.ValidateEmail(email.Email))
                            {
                                var proccedEmailInfo = ProcessEmailAddress(email.Email);

                                if (proccedEmailInfo.Item1 > 0)
                                {
                                    type         = proccedEmailInfo.Item1;
                                    emailAddress = proccedEmailInfo.Item2;

                                    mailMessage.To.Clear();
                                    mailMessage.To.Add(new MailboxAddress(email.Name, email.Email));
                                }
                            }
                        }
                    }

                    // If To and CC didn't work, try the header.
                    if (type == 0)
                    {
                        try
                        {
                            if (message.Headers != null && message.Headers.Count > 0)
                            {
                                var header = message.Headers.FirstOrDefault(x => x.Name == "Received-SPF");

                                if (header != null)
                                {
                                    var lastValue = header.Value.LastIndexOf(char.Parse("="));
                                    var newEmail  = header.Value.Substring(lastValue + 1, (header.Value.Length - (lastValue + 1)));

                                    newEmail = newEmail.Trim();

                                    if (StringHelpers.ValidateEmail(newEmail))
                                    {
                                        emailAddress = newEmail;
                                        var proccedEmailInfo = ProcessEmailAddress(newEmail);

                                        type         = proccedEmailInfo.Item1;
                                        emailAddress = proccedEmailInfo.Item2;

                                        mailMessage.To.Clear();
                                        mailMessage.To.Add(new MailboxAddress("Email Importer", newEmail));
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                        }
                    }
                    #endregion Trying to Find What type of email this is

                    if (type == 1)                      // Dispatch
                    {
                        #region Dispatch Email
                        var departmentId = _departmentSettingsService.GetDepartmentIdForDispatchEmail(emailAddress);

                        if (departmentId.HasValue)
                        {
                            try
                            {
                                var emailSettings = _departmentsService.GetDepartmentEmailSettings(departmentId.Value);
                                List <IdentityUser> departmentUsers = _departmentsService.GetAllUsersForDepartment(departmentId.Value, true);

                                var callEmail = new CallEmail();

                                if (!String.IsNullOrWhiteSpace(message.Subject))
                                {
                                    callEmail.Subject = message.Subject;
                                }

                                else
                                {
                                    callEmail.Subject = "Dispatch Email";
                                }

                                if (!String.IsNullOrWhiteSpace(message.HtmlBody))
                                {
                                    callEmail.Body = HttpUtility.HtmlDecode(message.HtmlBody);
                                }
                                else
                                {
                                    callEmail.Body = message.TextBody;
                                }

                                callEmail.TextBody = message.TextBody;

                                foreach (var attachment in message.Attachments)
                                {
                                    try
                                    {
                                        if (Convert.ToInt32(attachment.ContentLength) > 0)
                                        {
                                            if (attachment.Name.Contains(".mp3") || attachment.Name.Contains(".amr"))
                                            {
                                                byte[] filebytes = Convert.FromBase64String(attachment.Content);

                                                callEmail.DispatchAudioFileName = attachment.Name;
                                                callEmail.DispatchAudio         = filebytes;
                                            }
                                        }
                                    }
                                    catch { }
                                }

                                if (emailSettings == null)
                                {
                                    emailSettings              = new DepartmentCallEmail();
                                    emailSettings.FormatType   = (int)CallEmailTypes.Generic;
                                    emailSettings.DepartmentId = departmentId.Value;
                                    emailSettings.Department   = _departmentsService.GetDepartmentById(departmentId.Value, false);
                                }
                                else if (emailSettings.Department == null)
                                {
                                    emailSettings.Department = _departmentsService.GetDepartmentById(departmentId.Value);
                                }

                                var activeCalls     = _callsService.GetLatest10ActiveCallsByDepartment(emailSettings.Department.DepartmentId);
                                var units           = _unitsService.GetUnitsForDepartment(emailSettings.Department.DepartmentId);
                                var priorities      = _callsService.GetActiveCallPrioritesForDepartment(emailSettings.Department.DepartmentId);
                                int defaultPriority = (int)CallPriority.High;

                                if (priorities != null && priorities.Any())
                                {
                                    var defaultPrio = priorities.FirstOrDefault(x => x.IsDefault && x.IsDeleted == false);

                                    if (defaultPrio != null)
                                    {
                                        defaultPriority = defaultPrio.DepartmentCallPriorityId;
                                    }
                                }

                                var call = _callsService.GenerateCallFromEmail(emailSettings.FormatType, callEmail,
                                                                               emailSettings.Department.ManagingUserId,
                                                                               departmentUsers, emailSettings.Department, activeCalls, units, defaultPriority);

                                if (call != null)
                                {
                                    call.DepartmentId = departmentId.Value;

                                    var savedCall = _callsService.SaveCall(call);

                                    var cqi = new CallQueueItem();
                                    cqi.Call                 = savedCall;
                                    cqi.Profiles             = _userProfileService.GetAllProfilesForDepartment(call.DepartmentId).Select(x => x.Value).ToList();
                                    cqi.DepartmentTextNumber = _departmentSettingsService.GetTextToCallNumberForDepartment(cqi.Call.DepartmentId);

                                    _queueService.EnqueueCallBroadcast(cqi);

                                    return(new HttpResponseMessage(HttpStatusCode.Created));
                                }
                            }
                            catch (Exception ex)
                            {
                                Logging.LogException(ex);
                                return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
                            }
                        }
                        #endregion Dispatch
                    }
                    else if (type == 2)                     // Email List
                    {
                        #region Distribution Email
                        var list = _distributionListsService.GetDistributionListByAddress(emailAddress);

                        if (list != null)
                        {
                            if (String.IsNullOrWhiteSpace(bounceEmail))
                            {
                                try
                                {
                                    List <Model.File> files = new List <Model.File>();

                                    try
                                    {
                                        if (message.Attachments != null && message.Attachments.Any())
                                        {
                                            foreach (var attachment in message.Attachments)
                                            {
                                                if (Convert.ToInt32(attachment.ContentLength) > 0)
                                                {
                                                    Model.File file = new Model.File();

                                                    byte[] filebytes = Convert.FromBase64String(attachment.Content);

                                                    file.Data         = filebytes;
                                                    file.FileName     = attachment.Name;
                                                    file.DepartmentId = list.DepartmentId;
                                                    file.ContentId    = attachment.ContentID;
                                                    file.FileType     = attachment.ContentType;
                                                    file.Timestamp    = DateTime.UtcNow;

                                                    files.Add(_fileService.SaveFile(file));
                                                }
                                            }
                                        }
                                    }
                                    catch { }

                                    var dlqi = new DistributionListQueueItem();
                                    dlqi.List  = list;
                                    dlqi.Users = _departmentsService.GetAllUsersForDepartment(list.DepartmentId);

                                    if (files != null && files.Any())
                                    {
                                        dlqi.FileIds = new List <int>();
                                        dlqi.FileIds.AddRange(files.Select(x => x.FileId).ToList());
                                    }

                                    dlqi.Message             = new InboundMessage();
                                    dlqi.Message.Attachments = new List <InboundMessageAttachment>();

                                    if (message.FromFull != null && !String.IsNullOrWhiteSpace(message.FromFull.Email) && !String.IsNullOrWhiteSpace(message.FromFull.Name))
                                    {
                                        dlqi.Message.FromEmail = message.FromFull.Email.Trim();
                                        dlqi.Message.FromName  = message.FromFull.Name.Trim();
                                    }

                                    dlqi.Message.Subject   = message.Subject;
                                    dlqi.Message.HtmlBody  = message.HtmlBody;
                                    dlqi.Message.TextBody  = message.TextBody;
                                    dlqi.Message.MessageID = message.MessageID;

                                    _queueService.EnqueueDistributionListBroadcast(dlqi);
                                }
                                catch (Exception ex)
                                {
                                    Logging.LogException(ex);
                                    return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
                                }
                            }
                            else
                            {
                                return(new HttpResponseMessage(HttpStatusCode.Created));
                            }
                        }

                        return(new HttpResponseMessage(HttpStatusCode.Created));

                        #endregion Distribution Email
                    }
                    if (type == 3)                      // Group Dispatch
                    {
                        #region Group Dispatch Email
                        var departmentGroup = _departmentGroupsService.GetGroupByDispatchEmailCode(emailAddress);

                        if (departmentGroup != null)
                        {
                            try
                            {
                                var emailSettings = _departmentsService.GetDepartmentEmailSettings(departmentGroup.DepartmentId);
                                //var departmentGroupUsers = _departmentGroupsService.GetAllMembersForGroup(departmentGroup.DepartmentGroupId);
                                var departmentGroupUsers = _departmentGroupsService.GetAllMembersForGroupAndChildGroups(departmentGroup);

                                var callEmail = new CallEmail();
                                callEmail.Subject = message.Subject;

                                if (!String.IsNullOrWhiteSpace(message.HtmlBody))
                                {
                                    callEmail.Body = HttpUtility.HtmlDecode(message.HtmlBody);
                                }
                                else
                                {
                                    callEmail.Body = message.TextBody;
                                }

                                foreach (var attachment in message.Attachments)
                                {
                                    try
                                    {
                                        if (Convert.ToInt32(attachment.ContentLength) > 0)
                                        {
                                            if (attachment.Name.Contains(".mp3") || attachment.Name.Contains(".amr"))
                                            {
                                                byte[] filebytes = Convert.FromBase64String(attachment.Content);

                                                callEmail.DispatchAudioFileName = attachment.Name;
                                                callEmail.DispatchAudio         = filebytes;
                                            }
                                        }
                                    }
                                    catch { }
                                }

                                if (emailSettings == null)
                                {
                                    emailSettings              = new DepartmentCallEmail();
                                    emailSettings.FormatType   = (int)CallEmailTypes.Generic;
                                    emailSettings.DepartmentId = departmentGroup.DepartmentId;

                                    if (departmentGroup.Department != null)
                                    {
                                        emailSettings.Department = departmentGroup.Department;
                                    }
                                    else
                                    {
                                        emailSettings.Department = _departmentsService.GetDepartmentById(departmentGroup.DepartmentId);
                                    }
                                }

                                var activeCalls = _callsService.GetActiveCallsByDepartment(emailSettings.Department.DepartmentId);
                                var units       = _unitsService.GetAllUnitsForGroup(departmentGroup.DepartmentGroupId);

                                var priorities      = _callsService.GetActiveCallPrioritesForDepartment(emailSettings.Department.DepartmentId);
                                int defaultPriority = (int)CallPriority.High;

                                if (priorities != null && priorities.Any())
                                {
                                    var defaultPrio = priorities.FirstOrDefault(x => x.IsDefault && x.IsDeleted == false);

                                    if (defaultPrio != null)
                                    {
                                        defaultPriority = defaultPrio.DepartmentCallPriorityId;
                                    }
                                }

                                var call = _callsService.GenerateCallFromEmail(emailSettings.FormatType, callEmail,
                                                                               emailSettings.Department.ManagingUserId,
                                                                               departmentGroupUsers.Select(x => x.User).ToList(), emailSettings.Department, activeCalls, units, defaultPriority);

                                if (call != null)
                                {
                                    call.DepartmentId = departmentGroup.DepartmentId;

                                    var savedCall = _callsService.SaveCall(call);

                                    var cqi = new CallQueueItem();
                                    cqi.Call                 = savedCall;
                                    cqi.Profiles             = _userProfileService.GetSelectedUserProfiles(departmentGroupUsers.Select(x => x.UserId).ToList());
                                    cqi.DepartmentTextNumber = _departmentSettingsService.GetTextToCallNumberForDepartment(cqi.Call.DepartmentId);

                                    _queueService.EnqueueCallBroadcast(cqi);

                                    return(new HttpResponseMessage(HttpStatusCode.Created));
                                }
                            }
                            catch (Exception ex)
                            {
                                Logging.LogException(ex);
                                return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
                            }
                        }
                        #endregion Group Dispatch Email
                    }
                    if (type == 4)                      // Group Message
                    {
                        #region Group Message
                        var departmentGroup = _departmentGroupsService.GetGroupByMessageEmailCode(emailAddress);

                        if (departmentGroup != null)
                        {
                            try
                            {
                                //var departmentGroupUsers = _departmentGroupsService.GetAllMembersForGroup(departmentGroup.DepartmentGroupId);
                                var departmentGroupUsers = _departmentGroupsService.GetAllMembersForGroupAndChildGroups(departmentGroup);

                                var newMessage = new Message();
                                newMessage.SentOn          = DateTime.UtcNow;
                                newMessage.SendingUserId   = departmentGroup.Department.ManagingUserId;
                                newMessage.IsBroadcast     = true;
                                newMessage.Subject         = message.Subject;
                                newMessage.SystemGenerated = true;

                                if (!String.IsNullOrWhiteSpace(message.HtmlBody))
                                {
                                    newMessage.Body = HttpUtility.HtmlDecode(message.HtmlBody);
                                }
                                else
                                {
                                    newMessage.Body = message.TextBody;
                                }

                                foreach (var member in departmentGroupUsers)
                                {
                                    if (newMessage.GetRecipients().All(x => x != member.UserId))
                                    {
                                        newMessage.AddRecipient(member.UserId);
                                    }
                                }

                                var savedMessage = _messageService.SaveMessage(newMessage);
                                _messageService.SendMessage(savedMessage, "", departmentGroup.DepartmentId, false);

                                return(new HttpResponseMessage(HttpStatusCode.Created));
                            }
                            catch (Exception ex)
                            {
                                Logging.LogException(ex);
                                return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
                            }
                        }

                        #endregion Group Message
                    }

                    return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
                }
                catch (Exception ex)
                {
                    Framework.Logging.LogException(ex);
                    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                    {
                        Content = new StringContent(ex.ToString())
                    });
                }
            }
            else
            {
                // If our message was null, we throw an exception
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent("Error parsing Inbound Message, message is null.")
                });
            }
        }
Exemplo n.º 9
0
        public IActionResult GetMapData(MapSettingsInput input)
        {
            MapDataJson dataJson = new MapDataJson();

            var calls              = _callsService.GetActiveCallsByDepartment(DepartmentId);
            var department         = _departmentsService.GetDepartmentById(DepartmentId, false);
            var stations           = _departmentGroupsService.GetAllStationGroupsForDepartment(DepartmentId);
            var lastUserActionlogs = _actionLogsService.GetActionLogsForDepartment(DepartmentId);
            var personnelNames     = _departmentsService.GetAllPersonnelNamesForDepartment(DepartmentId);
            var unitStates         = _unitsService.GetAllLatestStatusForUnitsByDepartmentId(DepartmentId);

            var userLocationPermission = _permissionsService.GetPermisionByDepartmentType(DepartmentId, PermissionTypes.CanSeePersonnelLocations);

            if (userLocationPermission != null)
            {
                var userGroup = _departmentGroupsService.GetGroupForUser(UserId, DepartmentId);
                int?groupId   = null;

                if (userGroup != null)
                {
                    groupId = userGroup.DepartmentGroupId;
                }

                var roles        = _personnelRolesService.GetRolesForUser(UserId, DepartmentId);
                var allowedUsers = _permissionsService.GetAllowedUsers(userLocationPermission, DepartmentId, groupId, ClaimsAuthorizationHelper.IsUserDepartmentAdmin(), ClaimsAuthorizationHelper.IsUserDepartmentAdmin(), roles);

                lastUserActionlogs.RemoveAll(x => !allowedUsers.Contains(x.UserId));
            }

            if (input.ShowDistricts)
            {
                foreach (var station in stations)
                {
                    if (!String.IsNullOrWhiteSpace(station.Geofence))
                    {
                        GeofenceJson geofence = new GeofenceJson();
                        geofence.Name  = station.Name;
                        geofence.Color = station.GeofenceColor;
                        geofence.Fence = station.Geofence;

                        dataJson.Geofences.Add(geofence);
                    }
                }
            }

            if (input.ShowStations)
            {
                foreach (var station in stations)
                {
                    MapMakerInfo info = new MapMakerInfo();
                    info.ImagePath         = "Station";
                    info.Title             = station.Name;
                    info.InfoWindowContent = station.Name;

                    if (station.Address != null)
                    {
                        string coordinates =
                            _geoLocationProvider.GetLatLonFromAddress(string.Format("{0} {1} {2} {3}", station.Address.Address1,
                                                                                    station.Address.City,
                                                                                    station.Address.State,
                                                                                    station.Address.PostalCode));

                        if (!String.IsNullOrEmpty(coordinates))
                        {
                            info.Latitude  = double.Parse(coordinates.Split(char.Parse(","))[0]);
                            info.Longitude = double.Parse(coordinates.Split(char.Parse(","))[1]);

                            dataJson.Markers.Add(info);
                        }
                    }
                    else if (!String.IsNullOrWhiteSpace(station.Latitude) && !String.IsNullOrWhiteSpace(station.Longitude))
                    {
                        info.Latitude  = double.Parse(station.Latitude);
                        info.Longitude = double.Parse(station.Longitude);

                        dataJson.Markers.Add(info);
                    }
                }
            }

            if (input.ShowCalls)
            {
                foreach (var call in calls)
                {
                    MapMakerInfo info = new MapMakerInfo();
                    info.ImagePath         = "Call";
                    info.Title             = call.Name;
                    info.InfoWindowContent = call.NatureOfCall;

                    if (!String.IsNullOrEmpty(call.GeoLocationData))
                    {
                        try
                        {
                            info.Latitude  = double.Parse(call.GeoLocationData.Split(char.Parse(","))[0]);
                            info.Longitude = double.Parse(call.GeoLocationData.Split(char.Parse(","))[1]);

                            dataJson.Markers.Add(info);
                        }
                        catch
                        {
                        }
                    }
                    else if (!String.IsNullOrEmpty(call.Address))
                    {
                        string coordinates = _geoLocationProvider.GetLatLonFromAddress(call.Address);
                        if (!String.IsNullOrEmpty(coordinates))
                        {
                            info.Latitude  = double.Parse(coordinates.Split(char.Parse(","))[0]);
                            info.Longitude = double.Parse(coordinates.Split(char.Parse(","))[1]);
                        }

                        dataJson.Markers.Add(info);
                    }
                }
            }

            if (input.ShowUnits)
            {
                foreach (var unit in unitStates)
                {
                    if (unit.Latitude.HasValue && unit.Latitude.Value != 0 && unit.Longitude.HasValue &&
                        unit.Longitude.Value != 0)
                    {
                        MapMakerInfo info = new MapMakerInfo();
                        info.ImagePath         = "Engine_Responding";
                        info.Title             = unit.Unit.Name;
                        info.InfoWindowContent = "";
                        info.Latitude          = double.Parse(unit.Latitude.Value.ToString());
                        info.Longitude         = double.Parse(unit.Longitude.Value.ToString());

                        dataJson.Markers.Add(info);
                    }
                }
            }

            if (input.ShowPersonnel)
            {
                foreach (var person in lastUserActionlogs)
                {
                    if (!String.IsNullOrWhiteSpace(person.GeoLocationData))
                    {
                        MapMakerInfo info = new MapMakerInfo();
                        info.ImagePath = "Person";

                        var name = personnelNames.FirstOrDefault(x => x.UserId == person.UserId);
                        if (name != null)
                        {
                            info.Title             = name.Name;
                            info.InfoWindowContent = "";
                        }
                        else
                        {
                            info.Title             = "";
                            info.InfoWindowContent = "";
                        }

                        var infos = person.GeoLocationData.Split(char.Parse(","));
                        if (infos != null && infos.Length == 2)
                        {
                            info.Latitude  = double.Parse(infos[0]);
                            info.Longitude = double.Parse(infos[1]);

                            dataJson.Markers.Add(info);
                        }
                    }
                }
            }

            if (input.ShowPOIs)
            {
                var poiTypes = _mappingService.GetPOITypesForDepartment(DepartmentId);

                foreach (var poiType in poiTypes)
                {
                    foreach (var poi in poiType.Pois)
                    {
                        MapMakerInfo info = new MapMakerInfo();
                        info.ImagePath         = poiType.Image;
                        info.Marker            = poiType.Marker;
                        info.Title             = poiType.Name;
                        info.InfoWindowContent = "";
                        info.Latitude          = poi.Latitude;
                        info.Longitude         = poi.Longitude;
                        info.Color             = poiType.Color;

                        dataJson.Pois.Add(info);
                    }
                }
            }

            return(Json(dataJson));
        }
Exemplo n.º 10
0
        public List <PersonnelViewModel> GetPersonnelStatuses()
        {
            var department         = _departmentsService.GetDepartmentById(DepartmentId, false);
            var stations           = _departmentGroupsService.GetAllStationGroupsForDepartment(DepartmentId);
            var calls              = _callsService.GetActiveCallsByDepartment(DepartmentId);
            var allUsers           = _departmentsService.GetAllUsersForDepartment(DepartmentId);
            var hideUnavailable    = _departmentSettingsService.GetBigBoardHideUnavailableDepartment(DepartmentId);
            var lastUserActionlogs = _actionLogsService.GetActionLogsForDepartment(DepartmentId);
            //var departmentGroups = _departmentGroupsService.GetAllGroupsForDepartment(DepartmentId);

            var lastUserStates = _userStateService.GetLatestStatesForDepartment(DepartmentId);
            var personnelNames = _departmentsService.GetAllPersonnelNamesForDepartment(DepartmentId);

            var names = new Dictionary <string, string>();

            var userStates = new List <UserState>();

            foreach (var u in allUsers)
            {
                var state = lastUserStates.FirstOrDefault(x => x.UserId == u.UserId);

                if (state != null)
                {
                    userStates.Add(state);
                }
                else
                {
                    userStates.Add(_userStateService.GetLastUserStateByUserId(u.UserId));
                }

                var name = personnelNames.FirstOrDefault(x => x.UserId == u.UserId);
                if (name != null)
                {
                    names.Add(u.UserId, name.Name);
                }
            }

            var personnelViewModels = new List <PersonnelViewModel>();

            var sortedUngroupedUsers = from u in allUsers
                                       // let mu = Membership.GetUser(u.UserId)
                                       let userGroup = _departmentGroupsService.GetGroupForUser(u.UserId, DepartmentId)
                                                       let groupName                         = userGroup == null ? "" : userGroup.Name
                                                                                   let roles = _personnelRolesService.GetRolesForUser(u.UserId, DepartmentId)
                                                                                               //let name = (ProfileBase.Create(mu.UserName, true)).GetPropertyValue("Name").ToString()
                                                                                               let name = names[u.UserId]
                                                                                                          let weight = lastUserActionlogs.Where(x => x.UserId == u.UserId).FirstOrDefault().GetWeightForAction()
                                                                                                                       orderby groupName, weight, name ascending
                select new
            {
                Name  = name,
                User  = u,
                Group = userGroup,
                Roles = roles
            };

            foreach (var u in sortedUngroupedUsers)
            {
                //var mu = Membership.GetUser(u.User.UserId);
                var al = lastUserActionlogs.Where(x => x.UserId == u.User.UserId).FirstOrDefault();
                var us = userStates.Where(x => x.UserId == u.User.UserId).FirstOrDefault();

                // if setting is such, ignore unavailable users.
                if (hideUnavailable.HasValue && hideUnavailable.Value && us.State != (int)UserStateTypes.Unavailable)
                {
                    continue;
                }

                string callNumber = "";
                if (al != null && al.ActionTypeId == (int)ActionTypes.RespondingToScene ||
                    (al != null && al.DestinationType.HasValue && al.DestinationType.Value == 2))
                {
                    if (al.DestinationId.HasValue)
                    {
                        var call = calls.FirstOrDefault(x => x.CallId == al.DestinationId.Value);

                        if (call != null)
                        {
                            callNumber = call.Number;
                        }
                    }
                }
                var respondingToDepartment =
                    stations.Where(s => al != null && s.DepartmentGroupId == al.DestinationId).FirstOrDefault();
                var personnelViewModel = PersonnelViewModel.Create(u.Name, al, us, department, respondingToDepartment, u.Group,
                                                                   u.Roles, callNumber);

                personnelViewModels.Add(personnelViewModel);
            }

            return(personnelViewModels);
        }
Exemplo n.º 11
0
        public Tuple <bool, string> Process(CallEmailQueueItem item)
        {
            bool   success = true;
            string result  = "";

            _callEmailProvider = Bootstrapper.GetKernel().Resolve <ICallEmailProvider>();

            if (!String.IsNullOrWhiteSpace(item?.EmailSettings?.Hostname))
            {
                CallEmailsResult emailResult = _callEmailProvider.GetAllCallEmailsFromServer(item.EmailSettings);

                if (emailResult?.Emails != null && emailResult.Emails.Count > 0)
                {
                    var calls = new List <Call>();

                    _callsService              = Bootstrapper.GetKernel().Resolve <ICallsService>();
                    _queueService              = Bootstrapper.GetKernel().Resolve <IQueueService>();
                    _departmentsService        = Bootstrapper.GetKernel().Resolve <IDepartmentsService>();
                    _userProfileService        = Bootstrapper.GetKernel().Resolve <IUserProfileService>();
                    _departmentSettingsService = Bootstrapper.GetKernel().Resolve <IDepartmentSettingsService>();
                    _unitsService              = Bootstrapper.GetKernel().Resolve <IUnitsService>();

                    // Ran into an issue where the department users didn't come back. We can't put the email back in the POP
                    // email box so just added some simple retry logic here.
                    List <IdentityUser> departmentUsers = _departmentsService.GetAllUsersForDepartment(item.EmailSettings.DepartmentId, true);
                    var profiles = _userProfileService.GetAllProfilesForDepartment(item.EmailSettings.DepartmentId);

                    int retry = 0;
                    while (retry < 3 && departmentUsers == null)
                    {
                        Thread.Sleep(150);
                        departmentUsers = _departmentsService.GetAllUsersForDepartment(item.EmailSettings.DepartmentId, true);
                        retry++;
                    }

                    foreach (var email in emailResult.Emails)
                    {
                        var activeCalls = _callsService.GetActiveCallsByDepartment(item.EmailSettings.Department.DepartmentId);
                        var units       = _unitsService.GetUnitsForDepartment(item.EmailSettings.Department.DepartmentId);

                        var priorities      = _callsService.GetActiveCallPrioritesForDepartment(item.EmailSettings.Department.DepartmentId);
                        int defaultPriority = (int)CallPriority.High;

                        if (priorities != null && priorities.Any())
                        {
                            var defaultPrio = priorities.FirstOrDefault(x => x.IsDefault && x.IsDeleted == false);

                            if (defaultPrio != null)
                            {
                                defaultPriority = defaultPrio.DepartmentCallPriorityId;
                            }
                        }

                        var call = _callsService.GenerateCallFromEmail(item.EmailSettings.FormatType, email,
                                                                       item.EmailSettings.Department.ManagingUserId, departmentUsers, item.EmailSettings.Department, activeCalls, units, defaultPriority);

                        if (call != null)
                        {
                            call.DepartmentId = item.EmailSettings.DepartmentId;

                            if (!calls.Any(x => x.Name == call.Name && x.NatureOfCall == call.NatureOfCall))
                            {
                                calls.Add(call);
                            }
                        }
                    }

                    if (calls.Any())
                    {
                        var departmentTextNumber = _departmentSettingsService.GetTextToCallNumberForDepartment(item.EmailSettings.DepartmentId);
                        foreach (var call in calls)
                        {
                            try
                            {
                                // Adding this in here to try and fix the error below with ObjectContext issues.
                                var newCall = CreateNewCallFromCall(call);

                                if (newCall.Dispatches != null && newCall.Dispatches.Any())
                                {
                                    // We've been having this error here:
                                    //      The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.
                                    // So I'm wrapping this in a try catch to prevent all calls form being dropped.
                                    var savedCall = _callsService.SaveCall(newCall);
                                    var cqi       = new CallQueueItem();
                                    cqi.Call = savedCall;

                                    cqi.Profiles             = profiles.Values.ToList();
                                    cqi.DepartmentTextNumber = departmentTextNumber;

                                    _queueService.EnqueueCallBroadcast(cqi);
                                }
                            }
                            catch (Exception ex)
                            {
                                result = ex.ToString();
                                Logging.LogException(ex);
                            }
                        }
                    }

                    _departmentsService.SaveDepartmentEmailSettings(emailResult.EmailSettings);

                    _callsService              = null;
                    _queueService              = null;
                    _departmentsService        = null;
                    _callEmailProvider         = null;
                    _userProfileService        = null;
                    _departmentSettingsService = null;
                }
            }

            return(new Tuple <bool, string>(success, result));
        }