Esempio n. 1
0
        /// <summary>
        /// Twilio Posts SMS messages here
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public virtual HttpResponseMessage Post([FromBody] TwilioRequest request)
        {
            try
            {
                Dandabu.AttendanceTracker.Models.Message newMessage = new Dandabu.AttendanceTracker.Models.Message();
                newMessage.AccountSid      = request.AccountSid;
                newMessage.MessageSid      = request.MessageSid;
                newMessage.From            = request.From;
                newMessage.To              = request.To;
                newMessage.Body            = request.Body;
                newMessage.CreatedOn       = DateTime.Now;
                newMessage.IsAttendaceData = ParseAttendanceData(newMessage);

                db.Messages.Add(newMessage);

                db.SaveChanges();


                if (newMessage.IsAttendaceData == true)
                {
                    _client.SendMessage("763-316-3318", "952-484-9131", "Accepted attendance data has been sent from " + request.From);
                }
                else
                {
                    _client.SendMessage("763-316-3318", "952-484-9131", "An unknown message has been received from " + request.From);
                }


                return(Request.CreateResponse(HttpStatusCode.OK, "Message Received Successfully"));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, "Error adding message"));
            }
        }
Esempio n. 2
0
        public KUser CreateUser(TwilioRequest trequest)
        {
            var u = new KUser
            {
                Mobile = trequest.From,
                Email = _bodyParser.GetSwitchValue("#EMAIL",trequest.Body)
            };

            //var uid = (long)_session.Save(u);

            u = _session.Get<KUser>((long)_session.Save(u));

            var l = new Ledger
            {
                KUserId = u.KUserId,
                MessageSid = trequest.MessageSid,
                Money = 10,
                Description = "Opening bonus",
                TransactionType = "CR"

            };

            _session.Save(l);

            return u;
        }
        public async Task <TwilioResponse> StopRecording(TwilioRequest request)
        {
            TwilioResponse response = new TwilioResponse();

            using (var db = dbFactory())
            {
                var call = db.Calls.Single(f => f.CallId == request.CallSid);
                //if (!string.IsNullOrWhiteSpace(call.RecordingUrl))
                //{
                //  // Delete previous recording
                //}
                call.RecordingDuration = request.RecordingDuration;
                call.RecordingUrl      = request.RecordingUrl;
                await db.SaveChangesAsync();

                this.session.HasRecording = true;

                this.config.GetPushHub <CallsHub>().updatedCall(CallsController.GetCallEntry(call));

                BeginMenu(response);
                response.SayVoice(Speeches.CallerRecordingSaved);
                await EndMenu(response, true);
            }
            return(LogResponse(response));
        }
        public async Task <TwilioResponse> ConfirmClose(TwilioRequest request)
        {
            var response = new TwilioResponse();
            int targetId;

            BeginMenu(response);
            if (int.TryParse(GetQueryParameter("targetId") ?? string.Empty, out targetId))
            {
                if (request.Digits != "9")
                {
                    response.SayVoice("{0} was not closed.", GetEventName());
                }
                else
                {
                    var target = await eventService.QuickClose(targetId);

                    this.session.EventId = null;
                    LoadActiveEvents();
                    response.SayVoice("{0} was closed.", target.Name);
                }
            }
            await EndMenu(response);

            return(response);
        }
        public async Task <TwilioResponse> Answer(TwilioRequest request)
        {
            await SetMemberInfoFromPhone(request.From);
            await UpdateSigninStatus();

            using (var db = dbFactory())
            {
                var call = new VoiceCall
                {
                    CallId   = request.CallSid,
                    Number   = request.From,
                    CallTime = TimeUtils.GetLocalDateTime(this.config),
                    Name     = this.session.MemberName
                };

                db.Calls.Add(call);
                await db.SaveChangesAsync();

                this.config.GetPushHub <CallsHub>().updatedCall(CallsController.GetCallEntry(call));
            }

            var response = new TwilioResponse();

            BeginMenu(response);
            if (this.session.MemberId == null)
            {
                response.SayVoice(Speeches.WelcomeUnknownCaller);
            }

            await EndMenu(response);

            return(LogResponse(response));
        }
        public async Task <TwilioResponse> SetMiles(TwilioRequest request)
        {
            var response = new TwilioResponse();

            BeginMenu(response);

            int miles;

            if (int.TryParse(request.Digits, out miles))
            {
                using (var db = dbFactory())
                {
                    var signin = db.SignIns.OrderByDescending(f => f.TimeIn).FirstOrDefault(f => f.MemberId == this.session.MemberId);
                    signin.Miles = miles;
                    await db.SaveChangesAsync();

                    this.config.GetPushHub <CallsHub>().updatedRoster(RosterController.GetRosterEntry(signin.Id, db), true);
                }
                response.SayVoice(Speeches.MilesUpdated);
            }

            await EndMenu(response, true);

            return(LogResponse(response));
        }
        public async Task <TwilioResponse> SetTimeOut(TwilioRequest request)
        {
            int minutes;
            var response = new TwilioResponse();

            // add prompt for miles
            response.BeginGather(new { timeout = 10, action = GetAction("SetMiles") });
            if (int.TryParse(request.Digits, out minutes))
            {
                using (var db = dbFactory())
                {
                    var signin = await GetMembersLatestSignin(db, this.session.MemberId);

                    signin.TimeOut = signin.TimeOut.Value.AddMinutes(minutes);
                    await db.SaveChangesAsync();

                    this.config.GetPushHub <CallsHub>().updatedRoster(RosterController.GetRosterEntry(signin.Id, db), true);
                    var sayDate = TimeUtils.GetMiltaryTimeVoiceText(signin.TimeOut.Value);
                    response.SayVoice(Speeches.SignedOutTemplate, this.session.MemberName, sayDate);
                }
            }
            response.SayVoice(Speeches.MilesPrompt);
            response.EndGather();

            return(LogResponse(response));
        }
Esempio n. 8
0
        public decimal GetBalance(TwilioRequest trequest)
        {
            var us = _session.QueryOver<KUser>().Where(u => u.Mobile == trequest.From).List().FirstOrDefault();
            List<decimal> userLedgers = _session.QueryOver<Ledger>().Where(u => u.KUserId == us.KUserId).List().Select(GetTransactionNumbers).ToList();

            return userLedgers.Sum();
        }
 public async Task <TwilioResponse> Login(TwilioRequest request)
 {
     if (request.Digits == (this.config.GetConfig("AdminPassword") ?? "1954"))
     {
         this.session.IsAdmin = true;
     }
     return(await Menu());
 }
Esempio n. 10
0
        public async Task <TwilioResponse> Menu(TwilioRequest request)
        {
            var response = new TwilioResponse();

            BeginMenu(response);
            await EndMenu(response);

            return(LogResponse(response));
        }
        public async Task <TwilioResponse> DoMenu(TwilioRequest request)
        {
            var response = new TwilioResponse();

            if (request.Digits == "1")
            {
                var now      = TimeUtils.GetLocalDateTime(this.config);
                var newEvent = new SarEvent {
                    Name = "New Event at " + TimeUtils.GetMiltaryTimeVoiceText(now), Opened = now
                };
                await this.eventService.Create(newEvent);

                LoadActiveEvents();
                this.session.EventId = newEvent.Id;

                BeginMenu(response);
                response.SayVoice("Created " + newEvent.Name);

                await EndMenu(response);
            }
            else if (request.Digits == "2")
            {
                using (var db = dbFactory())
                {
                    BuildSetEventMenu(response, string.Empty, Url.Content("~/api/VoiceAdmin/Menu"));
                }
            }
            else if (request.Digits == "3")
            {
                response.SayVoice("Record a short description of this event at the tone");
                response.Record(new { maxLength = 120, action = GetAction("SetDescription", controller: "VoiceAdmin") });
                BeginMenu(response);
                await EndMenu(response);
            }
            else if (request.Digits == "9")
            {
                Dictionary <string, string> args = new Dictionary <string, string>();
                args.Add("targetId", this.session.EventId.ToString());
                response.BeginGather(new { numDigits = 1, action = GetAction("ConfirmClose", args, controller: "VoiceAdmin"), timeout = 10 });
                response.SayVoice("Press 9 to confirm close of {0}. Press any other key to return to menu.", GetEventName());
                response.EndGather();
            }
            else if (request.Digits == "0")
            {
                response.Redirect(GetAction("Menu"));
            }
            else
            {
                response.SayVoice("I didn't understand.");
                BeginMenu(response);
                await EndMenu(response);
            }
            return(response);
        }
Esempio n. 12
0
        public Response ProcessCommands(TwilioRequest trequest)
        {
            if (_bodyParser.CommandExists("BAL", trequest.Body)) return SendBalance(trequest);

            if (_bodyParser.CommandExists("PAY", trequest.Body)) return PayUser(trequest);

            if (_bodyParser.CommandExists("MORE", trequest.Body)) return _responseManager.GetResponse("MORE", null);

            if (_bodyParser.CommandExists("GAME", trequest.Body)) return _responseManager.GetResponse("GAME", null);

            return new Response {Message = string.Format("Send MORE for more menu options")};
        }
        public async Task <TwilioResponse> SetDescription(TwilioRequest request)
        {
            await this.eventService.SetRecordedDescription(this.session.EventId.Value, request.RecordingUrl);

            TwilioResponse response = new TwilioResponse();

            BeginMenu(response);
            response.SayVoice("New greeting saved.");
            await EndMenu(response);

            return(response);
        }
Esempio n. 14
0
 public Response ProcessCommand(string command, TwilioRequest trequest)
 {
     switch (command.ToUpper())
     {
         case "REGISTER":
             var u = _createKUser.CreateUser(trequest);
             return _responseManager.GetResponse("REGISTER", null);
         case "NEWACCOUNT":
             return _responseManager.GetResponse("NEWACCOUNT", null);
         case "HELP":
             return _responseManager.GetResponse("HELP", null);
         default:
             return _responseManager.GetResponse("DEFAULT", null);
     }
 }
Esempio n. 15
0
        public async Task <TwilioResponse> SetSigninEvent(TwilioRequest request)
        {
            var response = new TwilioResponse();

            using (var db = dbFactory())
            {
                var signin = await GetMembersLatestSignin(db, session.MemberId);

                await RosterController.AssignInternal(signin, session.EventId, db, this.config);

                var name = CurrentEvents.Where(f => f.Id == session.EventId).Select(f => f.Name).SingleOrDefault();
                response.SayVoice(Speeches.ChangeEventTemplate, name);
            }

            response.Redirect(Url.Content("~/api/Voice/Menu") + session.ToQueryString());

            return(LogResponse(response));
        }
Esempio n. 16
0
        public async Task <TwilioResponse> Complete(TwilioRequest request)
        {
            using (var db = dbFactory())
            {
                var call = db.Calls.Where(f => f.CallId == request.CallSid).SingleOrDefault();
                if (call != null)
                {
                    call.Duration = request.CallDuration;
                    await db.SaveChangesAsync();

                    this.config.GetPushHub <CallsHub>().updatedCall(CallsController.GetCallEntry(call));
                }
            };

            var response = new TwilioResponse();

            response.Hangup();
            return(LogResponse(response));
        }
Esempio n. 17
0
        public async Task <TwilioResponse> DoMenu(TwilioRequest request)
        {
            var response = new TwilioResponse();

            if (request.Digits == "1")
            {
                if (this.session.MemberId == null)
                {
                    await AddLoginPrompt(response, Url.Content("~/api/Voice/DoSignInOut"));
                }
                else
                {
                    response = await DoSignInOut(request);
                }
            }
            else if (request.Digits == "2")
            {
                BuildSetEventMenu(response, string.Empty, Url.Content("~/api/voice/Menu"));
            }
            else if (request.Digits == "3")
            {
                response.SayVoice(Speeches.StartRecording);
                response.Record(new { maxLength = 120, action = GetAction("StopRecording") });
                BeginMenu(response);
                await EndMenu(response);
            }
            else if (request.Digits == "8")
            {
                await AddLoginPrompt(response, Url.Content("~/api/voice/Menu"));
            }
            else if (request.Digits == "9")
            {
                response.Redirect(GetAction("Menu", controller: "VoiceAdmin"));
            }
            else
            {
                response.SayVoice(Speeches.InvalidSelection);
                BeginMenu(response);
                await EndMenu(response);
            }

            return(LogResponse(response));
        }
Esempio n. 18
0
        public ActionResult Sms(TwilioRequest request)
        {
            var vote = new Vote {
                Choice = request.Body
            };

            vote.Save();

            var context = GlobalHost.ConnectionManager.GetHubContext <VoteHub>();

            context.Clients.updateVotes(
                string.Format("Vote Choice: {0}", vote.Choice));

            var response = new TwilioResponse();

            response.Sms("Thanks for voting!");

            return(new TwiMLResult(response));
        }
Esempio n. 19
0
        public async Task <TwilioResponse> DoLogin(TwilioRequest request)
        {
            var response = new TwilioResponse();
            var next     = this.GetQueryParameter(NextKey);

            var lookup = await members.LookupMemberDEM(request.Digits);

            if (lookup != null)
            {
                this.session.MemberId   = lookup.Id;
                this.session.MemberName = lookup.Name;
                await UpdateSigninStatus();

                response.Redirect((next ?? Url.Content("~/api/Voice/Menu")) + this.session.ToQueryString());
            }
            else
            {
                await AddLoginPrompt(response, next);
            }

            return(LogResponse(response));
        }
Esempio n. 20
0
        public async Task <TwilioResponse> DoSignInOut(TwilioRequest request)
        {
            var response = new TwilioResponse();

            using (var db = dbFactory())
            {
                var signin = await db.SignIns.Where(f => f.MemberId == this.session.MemberId).OrderByDescending(f => f.TimeIn).FirstOrDefaultAsync();

                var call = await db.Calls.SingleAsync(f => f.CallId == request.CallSid);

                DateTimeOffset time    = TimeUtils.GetLocalDateTime(this.config);
                var            sayDate = TimeUtils.GetMiltaryTimeVoiceText(time);

                if (signin == null || signin.TimeOut.HasValue)
                {
                    if (this.session.IsSignedIn)
                    {
                        throw new InvalidOperationException("Tried to sign out when not signed in");
                    }

                    signin = new MemberSignIn
                    {
                        MemberId = this.session.MemberId,
                        isMember = true,
                        Name     = this.session.MemberName,
                        TimeIn   = time,
                        EventId  = (this.CurrentEvents.Count == 1) ? this.CurrentEvents[0].Id : this.session.EventId,
                    };

                    db.SignIns.Add(signin);
                    call.Actions.Add(new CallAction {
                        Call = call, CallId = call.Id, Time = signin.TimeIn, Action = "Signed in " + signin.Name
                    });
                    await db.SaveChangesAsync();

                    this.session.IsSignedIn = true;

                    if (this.CurrentEvents.Count == 0)
                    {
                        await RosterController.AssignInternal(signin, null, db, this.config);

                        BeginMenu(response);
                        response.SayVoice(Speeches.SignedInUnassignedTemplate, this.session.MemberName, sayDate);
                        await EndMenu(response);
                    }
                    else if (this.CurrentEvents.Count == 1)
                    {
                        await RosterController.AssignInternal(signin, this.CurrentEvents[0].Id, db, this.config);

                        BeginMenu(response);
                        response.SayVoice(Speeches.SignedInTemplate, this.CurrentEvents[0].Name, this.session.MemberName, sayDate);
                        await EndMenu(response);
                    }
                    else
                    {
                        await RosterController.AssignInternal(signin, null, db, this.config);

                        BuildSetEventMenu(response, string.Format(Speeches.SignedInUnassignedTemplate, this.session.MemberName, sayDate), Url.Content("~/api/voice/SetSigninEvent"));
                    }
                }
                else
                {
                    signin.TimeOut = time;
                    call.Actions.Add(new CallAction {
                        Call = call, CallId = call.Id, Time = time, Action = "Signed out " + this.session.MemberName
                    });
                    this.session.IsSignedIn = false;
                    await db.SaveChangesAsync();

                    this.config.GetPushHub <CallsHub>().updatedRoster(RosterController.GetRosterEntry(signin.Id, db), true);

                    // add prompt for timeout beyond right now
                    response.BeginGather(new { timeout = 10, action = GetAction("SetTimeOut") });
                    response.SayVoice(Speeches.SignedOutTemplate, this.session.MemberName, sayDate);
                    response.SayVoice(Speeches.TimeoutPrompt);
                    response.EndGather();
                }
            }

            return(LogResponse(response));
        }
Esempio n. 21
0
        public async Task <TwilioResponse> DoApiCall(string url, TwilioRequest request, bool redirects = true)
        {
            HttpRequestMessage    requestMessage;
            HttpControllerContext ctrlContext;
            MethodInfo            method;

            GetActionMethod(url, out requestMessage, out ctrlContext, out method);

            var controller = new VoiceController(() => this.DBMock.Object, this.EventsServiceMock.Object, this.ConfigMock.Object, this.MembersMock.Object, new ConsoleLogger());

            controller.ControllerContext  = ctrlContext;
            controller.RequestContext.Url = new System.Web.Http.Routing.UrlHelper(requestMessage);

            var queryArgs = ctrlContext.Request.GetQueryNameValuePairs().ToDictionary(f => f.Key, f => f.Value);

            controller.InitBody(queryArgs);

            var           parameters = method.GetParameters();
            List <object> arguments  = new List <object>();

            foreach (var parameter in parameters)
            {
                if (parameter.ParameterType == typeof(TwilioRequest))
                {
                    arguments.Add(request);
                }
                else if (parameter.ParameterType == typeof(string))
                {
                    arguments.Add(queryArgs[parameter.Name]);
                }

                else
                {
                    throw new NotImplementedException("Don't know how to bind parameter " + parameter.Name + " with type " + parameter.ParameterType.Name);
                }
            }

            TwilioResponse result;

            if (method.ReturnType == typeof(TwilioResponse))
            {
                result = (TwilioResponse)method.Invoke(controller, arguments.ToArray());
            }
            else if (method.ReturnType == typeof(Task <TwilioResponse>))
            {
                result = await(Task <TwilioResponse>) method.Invoke(controller, arguments.ToArray());
            }
            else
            {
                throw new NotImplementedException("API controller returns type " + method.ReturnType.Name);
            }

            var first = result.ToXDocument().Root.FirstNode as XElement;

            if (redirects && first != null && first.Name == "Redirect")
            {
                result = await DoApiCall(first.Value, CreateRequest(null), true);
            }

            return(result);
        }
Esempio n. 22
0
        private Response SendBalance(TwilioRequest trequest)
        {
            var us = _session.QueryOver<KUser>().Where(u => u.Mobile == trequest.From).List().FirstOrDefault();
            List<decimal> userLedgers = _session.QueryOver<Ledger>().Where(u => u.KUserId == us.KUserId).List().Select(GetTransactionNumbers).ToList();

            var totalAmount = userLedgers.Sum();

            return new Response { Message = string.Format("Your balance is {0:C}", totalAmount) };
        }
Esempio n. 23
0
        private Response PayUser(TwilioRequest trequest)
        {
            decimal amount;
            var allstrings = trequest.Body.Split(Convert.ToChar(" "));
            if ((allstrings.Count() != 3) || (allstrings[1].Length != 10) || (!decimal.TryParse(allstrings[2], out amount)))
                return _responseManager.GetResponse("INCORRECTPAY", null);
            if (amount > GetBalance(trequest)) return _responseManager.GetResponse("INSUFFICIENTBALANCE", new Dictionary<string, string> { { "amount", Convert.ToString(amount) } });
            var payeeMobile = allstrings[1];
            var payee = _kUserFetcher.GetKUser(payeeMobile) ?? _createKUser.CreateUser(payeeMobile);

            var payerDr = new Ledger
            {
                KUserId = _kUserFetcher.GetKUser(trequest.From).KUserId,
                RelatedKUserId = _kUserFetcher.GetKUser(payee.Mobile).KUserId,
                TransactionType = "DR",
                Money = amount,
                MessageSid = trequest.MessageSid,
                Description = string.Format("Sending money to {0:C}", payeeMobile)
            };

            var payeeCr = new Ledger
            {
                KUserId = _kUserFetcher.GetKUser(payee.Mobile).KUserId,
                RelatedKUserId = _kUserFetcher.GetKUser(trequest.From).KUserId,
                TransactionType = "CR",
                Money = amount,
                MessageSid = trequest.MessageSid,
                Description = string.Format("Receiving money from {0:C}", trequest.To)
            };

            //_session.Save(payee);
            _session.Save(payerDr);
            _session.Save(payeeCr);

            _commClient.SendMessage(payee.Mobile, string.Format("You have received {0:C} from {1}",amount, trequest.From));

            var dict = new Dictionary<string, string>
            {
                {"amount", Convert.ToString(amount)},
                {"bal", Convert.ToString(GetBalance(trequest))}
            };
            return _responseManager.GetResponse("PAYMENTSENT", dict);
        }
Esempio n. 24
0
        public TwilioResponse SetEvent([FromUri] string evtIds, [FromUri] string next, TwilioRequest request)
        {
            var response = new TwilioResponse();

            if (!Regex.IsMatch(evtIds, "^[\\.0-9]+$"))
            {
                log.ErrorFormat("Offered events in bad format: {0}", evtIds);
                BuildSetEventMenu(response, Speeches.InvalidSelection, next);
                return(response);
            }

            var offeredEvents = evtIds.Split('.').Select(f => int.Parse(f)).ToArray();
            int selected;

            if (!int.TryParse(request.Digits, out selected))
            {
                log.ErrorFormat("Digits {0} are not an integer", request.Digits);
                BuildSetEventMenu(response, Speeches.InvalidSelection, next);
                return(response);
            }
            if (selected < 1 || selected > offeredEvents.Length)
            {
                BuildSetEventMenu(response, Speeches.InvalidSelection, next);
                return(response);
            }

            session.EventId = offeredEvents[selected - 1];
            response.Redirect((next ?? Url.Content("~/api/Voice/Menu")) + session.ToQueryString());

            return(LogResponse(response));
        }