private static void SendEmail(MandrillApi api, SendInfo info, string subj, string content)
        {
            LogManager.GetLogger(typeof(EmailWorker)).Info("Sending email to:" + info.UserEmail);

            var _task = api.SendMessageTemplate(
                new SendMessageTemplateRequest(new EmailMessage
                {
                    To = new[] { new EmailAddress(info.UserEmail) },
                    FromEmail = "*****@*****.**",
                    Subject = subj,
                    TrackClicks = false,
                    TrackOpens = false
                },
                    MANDRILL_TEMPLATE,
                    new[]
                    {
                        new TemplateContent
                        {
                            Name = "main",
                            Content = content
                        }
                    }));
        }
        public SendInfo Update(SendInfo sendInfo)
        {
            SendInfo result = null;
            try
            {
                using (var dbCtx = new WeatherAppDbEntities())
                {
                    result = dbCtx.SendInfo.SingleOrDefault(info => info.UserName == sendInfo.UserName);

                    if (result != null)
                    {
                        result.Merge(sendInfo);
                        dbCtx.SaveChanges();

                        return result;
                    }
                    else
                        throw new DaoException("No user " + sendInfo.UserName + " found in database");
                }
            }
            catch (Exception e)
            {
                throw new DaoException("Error updating user " + sendInfo.UserName + " in database. " + e.Message, e);
            }
        }
        public ActionResult ChangeNotification(bool emailChk, bool smsChk, string email, string phone,
            string wakeupDay, string wakeupEnd, string timezoneSelect, string timezoneOffset,
            WeekEndMode weekendMode, TemperatureMode temperature, string countryCode)
        {
            SendInfo info = new SendInfo()
            {
                UserName = User.Identity.Name,
                SendEmail = emailChk,
                SendSms = smsChk,
                UserEmail = email,
                UserPhone = phone,
                TimeWeekDay = wakeupDay,
                TimeWeekEnd = wakeupEnd,
                TimeZoneValue = timezoneSelect,
                WeekendMode = weekendMode,
                Temperature = temperature,
                CountryCode = countryCode
            };

            if (!string.IsNullOrEmpty(timezoneOffset))
                info.TimeZoneOffset = settingService.ParseTimeZoneOffset(timezoneOffset);

            settingService.UpdateUserSettings(info);

            return RedirectToAction("GoToResults", "Default");
        }
        public JsonResult ChangeNotification(bool emailChk, bool smsChk, string email, string phone, string wakeupDay, string wakeupEnd,
            string timezoneSelect, string timezoneOffset, WeekEndMode weekendMode, TemperatureMode temperature, string token, string countryCode)
        {
            GenericResponse responseObj = null;
            int timeStart = DateTime.Now.TimeOfDay.Seconds;

            try
            {
                string name = oauthFactory.GetOAuthTokenDao().getUser(token).username;

                if (name != null)
                {
                    SendInfo info = new SendInfo()
                    {
                        UserName = name,
                        SendEmail = emailChk,
                        SendSms = smsChk,
                        UserEmail = email,
                        UserPhone = phone,
                        TimeWeekDay = wakeupDay,
                        TimeWeekEnd = wakeupEnd,
                        TimeZoneValue = timezoneSelect,
                        WeekendMode = weekendMode,
                        Temperature = temperature,
                        CountryCode = countryCode,
                    };

                    if (!string.IsNullOrEmpty(timezoneOffset))
                        info.TimeZoneOffset = settingsService.ParseTimeZoneOffset(timezoneOffset);

                    settingsService.UpdateUserSettings(info);
                }

                responseObj = new GenericResponse()
                {
                    Status = 0,
                    ResponseTime = DateTime.Now.TimeOfDay.Seconds - timeStart,
                    Message = "Settings successfully updated for user: "+ name,
                    Data = null,
                };

                return Json(responseObj, JsonRequestBehavior.AllowGet);
            }
            catch (Exception e)
            {
                responseObj = new GenericResponse()
                {
                    Status = 1,
                    ResponseTime = DateTime.Now.TimeOfDay.Milliseconds - timeStart,
                    Message = e.Message,
                    Data = null,
                };

                ResponseLogging(responseObj);
                return Json(responseObj, JsonRequestBehavior.AllowGet);
            }
        }
 public SendInfo Insert(SendInfo info)
 {
     try
     {
         using (var dbCtx = new WeatherAppDbEntities())
         {
             dbCtx.SendInfo.Add(info);
             dbCtx.SaveChanges();
         }
         return info;
     }
     catch (Exception e)
     {
         throw new DaoException("Error inserting user " + info.UserName + " in database", e);
     }
 }
        /// <summary>
        /// Subscribes push notifications
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="token"></param>
        /// <param name="deviceType"></param>
        public void SubscribePushNotification(string token, DeviceType deviceType, SendInfo info, ApplicationType? appType)
        {
            try
            {
                IPushNotificationService notificationService = new DefaultPushNotificationService();

                if (notificationService.IsTokenSubscribed(token) == false)
                {
                    notificationService.SubscribeDeviceToken(token, deviceType, info.Id, appType);
                    notificationService.Send(info.Id, deviceType, token, Options.NotificationMessage, appType);
                }
                else
                    throw new ApplicationException("Device already subscribed");
            }
            catch (Exception e)
            {
                throw new ApplicationException(e.Message);
            }
        }
Ejemplo n.º 7
0
        public void Merge(SendInfo from)
        {
            SendInfo to = this;

            if (from.City != null)
            {
                to.City = from.City;
            }

            if (from.DataFileId != null)
            {
                to.DataFileId = from.DataFileId;
            }

            if (from.DataFileName != null)
            {
                to.DataFileName = from.DataFileName;
            }

            if (from.LastSendDt != null)
            {
                to.LastSendDt = from.LastSendDt;
            }

            if (from.SendRoost != null)
            {
                to.SendRoost = from.SendRoost;
            }

            if (from.SendSms != null)
            {
                to.SendSms = from.SendSms;
            }

            if (from.SmsId != null)
            {
                to.SmsId = from.SmsId;
            }

            if (from.SendEmail != null)
            {
                to.SendEmail = from.SendEmail;
            }

            if (from.SmsUseFrom2 != null)
            {
                to.SmsUseFrom2 = from.SmsUseFrom2;
            }

            if (from.Temperature != null)
            {
                to.Temperature = from.Temperature;
            }

            if (from.TimeWeekDay != null)
            {
                to.TimeWeekDay = from.TimeWeekDay;
            }

            if (from.TimeWeekEnd != null)
            {
                to.TimeWeekEnd = from.TimeWeekEnd;
            }

            if (from.TimeZoneOffset != null)
            {
                to.TimeZoneOffset = from.TimeZoneOffset;
            }

            if (from.TimeZoneValue != null)
            {
                to.TimeZoneValue = from.TimeZoneValue;
            }

            if (from.UserEmail != null)
            {
                to.UserEmail = from.UserEmail;
            }

            if (from.UserPhone != null)
            {
                to.UserPhone = from.UserPhone;
            }

            if (from.WeatherUpdateDt != null)
            {
                to.WeatherUpdateDt = from.WeatherUpdateDt;
            }

            if (from.WeekendMode != null)
            {
                to.WeekendMode = from.WeekendMode;
            }

            if (from.LastWeatherUpdate != null)
            {
                to.LastWeatherUpdate = from.LastWeatherUpdate;
            }

            if (from.CountryCode != null)
            {
                to.CountryCode = from.CountryCode;
            }
        }
 /// <summary>
 /// Sends SMS notification after its enablement
 /// </summary>
 /// <param name="name"></param>
 public void SendSmsInvite(SendInfo info)
 {
     string message = "Genetically tailored SMS notifications successfully enabled for your Weather My Way + RTP app. Email [email protected] if you did not activate this notification.";
     SendSms(info, message);
 }
        /// <summary>
        /// Determines whether initial invitation email should be sent to a user
        /// </summary>
        /// <param name="info"></param>
        /// <param name="email"></param>
        /// <param name="emailChk"></param>
        /// <returns></returns>
        private bool ShouldSendInitialEmail(SendInfo info, string email, bool emailChk)
        {
            bool isAlreadySubscribed = (info.SendEmail ?? false);

            if (!emailChk)
                return false;

            if (!isAlreadySubscribed)
                return true;

            bool emailMatches = email.Equals(info.UserEmail);

            return !emailMatches;
        }
        private void SendSms(SendInfo info, string content)
        {
            var _from = Options.FromPhone;
            if (info.SmsUseFrom2 ?? false)
                _from = Options.FromPhone2;

            var _sid = SmsSendImpl(_from, info.UserPhone, content);
            if (string.IsNullOrEmpty(_sid) && !(info.SmsUseFrom2 ?? false))
            {
                _sid = SmsSendImpl(Options.FromPhone2, info.UserPhone, content);
                if (!string.IsNullOrEmpty(_sid))
                    info.SmsUseFrom2 = true;
            }
            info.SmsId = _sid;
            _logger.InfoFormat("SID: {0} ", _sid);
        }
 private void SendOnSiteNotification(SendInfo info, string msg1)
 {
     var _srv = new SqApiServiceFacade(Options.ApiUrl, info.UserName);
     _srv.SendUserNotification(msg1);
 }
 private void SendEmailNotification(SendInfo _info, string _city, string _todayForecast, string _currentObservation, string _riskDescription,
     Forecast10Root _forecastRoot, TemperatureMode _mode, MandrillApi _api, string _subj)
 {
     var _sb = new StringBuilder();
     _sb.Append("<p style='text-align:center'>")
         .AppendFormat(
             "Genetically tailored notification from your <a href='{0}' class='external'>Weather My Way +RTP</a> app",
             Options.BaseSiteUrl)
         .Append("</p>");
     _sb.Append("<p style='text-align:center'><strong>");
     _sb.AppendFormat("Current weather for {0}", _city).Append("</strong></p>");
     _sb.Append("<p style='text-align:center'>");
     _sb.Append(_currentObservation).Append("</p><br/>");
     _sb.Append("<p style='text-align:center'>");
     _sb.Append("<strong>Today's forecast</strong>").Append("</p>");
     _sb.Append("<p style='text-align:center'>");
     _sb.Append(_todayForecast).Append("</p><br/>");
     _sb.Append("<p style='text-align:center'>");
     _sb.Append("<strong>Your genetically tailored forecast</strong>").Append("</p>");
     _sb.Append("<p style='text-align:center'>");
     _sb.Append(_riskDescription).Append("</p><br/>");
     _sb.Append("<p style='text-align:center'><strong>Extended forecast</strong></p>");
     for (int _idx = 1; _idx <
         Math.Min(5, _forecastRoot.forecast.txt_forecast.forecastday.Count); _idx++)
     {
         _sb.Append("<p style='text-align:center'>");
         _sb.Append(_forecastRoot.forecast.txt_forecast.forecastday[_idx].title).Append(":");
         _sb.Append(_mode == TemperatureMode.F ?
             _forecastRoot.forecast.txt_forecast.forecastday[_idx].fcttext :
             _forecastRoot.forecast.txt_forecast.forecastday[_idx].fcttext_metric).Append("</p>");
     }
     SendEmail(_api, _info, _subj, _sb.ToString());
 }
 private bool IsRightTime(SendInfo info)
 {
     var _now = DateTime.Now;
     if (!info.LastSendDt.HasValue ||
         (info.LastSendDt.HasValue &&
          DateTime.Today.Subtract(info.LastSendDt.Value.Date).TotalDays >= 1))
     {
         var _weekend = _now.DayOfWeek == DayOfWeek.Saturday || _now.DayOfWeek == DayOfWeek.Sunday;
         if (info.TimeZoneOffset.HasValue)
         {
             var _finalOffset = -TimeZone.CurrentTimeZone.GetUtcOffset(_now).TotalHours + (double)info.TimeZoneOffset.Value;
             _now = _now.AddHours(_finalOffset);
         }
         if (!string.IsNullOrEmpty(info.TimeWeekEnd) && _weekend)
         {
             if (_now.Subtract(DateTime.Parse(info.TimeWeekEnd)).TotalMinutes > 0)
                 return true;
             return false;
         }
         if (!string.IsNullOrEmpty(info.TimeWeekDay))
         {
             if (_now.Subtract(DateTime.Parse(info.TimeWeekDay)).TotalMinutes > 0)
                 return true;
             return false;
         }
         return true;
     }
     return false;
 }
        private Tuple<long, long> GetJobId(SendInfo info)
        {
            var _srv = new SqApiServiceFacade(Options.ApiUrl, info.UserName);
            var _rs = _srv.StartAppChain(SqApiServiceFacade.MELANOMA_APP_CHAIN_ID, new Dictionary<string, string> { { "dataSourceId", info.DataFileId } });
            var _rs2 = _srv.StartAppChain(SqApiServiceFacade.VITD_APP_CHAIN_ID, new Dictionary<string, string> { { "dataSourceId", info.DataFileId } });

            while (true)
            {
                var _appStatus = _srv.CheckAppChainStatus(Convert.ToInt64(_rs.jobId));
                var _appStatus2 = _srv.CheckAppChainStatus(Convert.ToInt64(_rs2.jobId));
                if (_appStatus == "Completed" && _appStatus2 == "Completed")
                    break;
                Thread.Sleep(5000);
            }

            return Tuple.Create(_rs.jobId, _rs2.jobId);
        }
        public void UpdateUserSettings(SendInfo newInfo)
        {
            SendInfo existingInfo = factory.GetSendInfoDao().Find(newInfo.UserName);

            bool shouldSendEmail = ShouldSendInitialEmail(existingInfo, newInfo.UserEmail, newInfo.SendEmail.Value);
            bool shouldSendSms = ShouldSendInitialSms(existingInfo, newInfo.UserPhone, newInfo.SendSms.Value);

            existingInfo.Merge(newInfo);

            var _emailWorker = new EmailWorker();
            if (shouldSendEmail)
                _emailWorker.SendEmailInvite(existingInfo.UserName);

            if (shouldSendSms)
                _emailWorker.SendSmsInvite(existingInfo);

            UpdateUserSettingsImpl(existingInfo);
        }
        /// <summary>
        /// Updates user settings in the database
        /// </summary>
        /// <param name="newInfo"></param>
        protected SendInfo UpdateUserSettingsImpl(SendInfo newInfo)
        {
            if (newInfo == null)
            {
                factory.GetSendInfoDao().Insert(newInfo);
                return newInfo;
            }

            return factory.GetSendInfoDao().Update(newInfo);
        }
 private void SendSmsNotification(SendInfo _info, string _city, string _todayForecast, string _currentObservation, string _riskDescription)
 {
     string _msg1 = string.Format("Your genetically tailored forecast for {0}: {1} Right now it's {2}. {3}",
                        _city, _todayForecast, _currentObservation, _riskDescription);
     SendSms(_info, _msg1);
     SendOnSiteNotification(_info, _msg1);
 }
        /// <summary>
        /// Determines whether initial invitation SMS should be sent to a user
        /// </summary>
        /// <param name="info"></param>
        /// <param name="phone"></param>
        /// <param name="smsChk"></param>
        /// <returns></returns>
        private bool ShouldSendInitialSms(SendInfo info, string phone, bool smsChk)
        {
            bool isAlreadySubscribed = (info.SendSms ?? false);

            if (!smsChk)
                return false;

            if (!isAlreadySubscribed)
                return true;

            bool phoneMatches = phone.Equals(info.UserPhone);

            return !phoneMatches;
        }
        public void Merge(SendInfo from)
        {
            SendInfo to = this;

            if (from.City != null)
                to.City = from.City;

            if (from.DataFileId != null)
                to.DataFileId = from.DataFileId;

            if (from.DataFileName != null)
                to.DataFileName = from.DataFileName;

            if (from.LastSendDt != null)
                to.LastSendDt = from.LastSendDt;

            if (from.SendRoost != null)
                to.SendRoost = from.SendRoost;

            if (from.SendSms != null)
                to.SendSms = from.SendSms;

            if (from.SmsId != null)
                to.SmsId = from.SmsId;

            if (from.SendEmail != null)
                to.SendEmail = from.SendEmail;

            if (from.SmsUseFrom2 != null)
                to.SmsUseFrom2 = from.SmsUseFrom2;

            if (from.Temperature != null)
                to.Temperature = from.Temperature;

            if (from.TimeWeekDay != null)
                to.TimeWeekDay = from.TimeWeekDay;

            if (from.TimeWeekEnd != null)
                to.TimeWeekEnd = from.TimeWeekEnd;

            if (from.TimeZoneOffset != null)
                to.TimeZoneOffset = from.TimeZoneOffset;

            if (from.TimeZoneValue != null)
                to.TimeZoneValue = from.TimeZoneValue;

            if (from.UserEmail != null)
                to.UserEmail = from.UserEmail;

            if (from.UserPhone != null)
                to.UserPhone = from.UserPhone;

            if (from.WeatherUpdateDt != null)
                to.WeatherUpdateDt = from.WeatherUpdateDt;

            if (from.WeekendMode != null)
                to.WeekendMode = from.WeekendMode;

            if (from.LastWeatherUpdate != null)
                to.LastWeatherUpdate = from.LastWeatherUpdate;

            if (from.CountryCode != null)
                to.CountryCode = from.CountryCode;
        }
        public Forecast10Root GetForecast10(string city)
        {
            if (!string.IsNullOrEmpty(userName))
            {
                using (var _ctx = new WeatherAppDbEntities())
                {
                    var _si = _ctx.SendInfo.FirstOrDefault(info => info.UserName == userName);
                    if (_si == null)
                    {
                        _si = new SendInfo(userName);
                        _ctx.SendInfo.Add(_si);
                    }
                    if (_si.WeatherUpdateDt.HasValue &&
                        DateTime.Now.Subtract(_si.WeatherUpdateDt.Value).TotalSeconds < WEATHER_UPD_SECONDS
                        && _si.City == city && _si.LastWeatherUpdate != null)
                    {
                        var _deserializeObject = JsonConvert.DeserializeObject<Forecast10Root>(_si.LastWeatherUpdate);
                        if (_deserializeObject.forecast != null)
                            return _deserializeObject;
                    }

                    var _forecast10Impl = GetForecast10Impl(city);
                    if (_forecast10Impl == null)
                        return null;
                    _si.LastWeatherUpdate = JsonConvert.SerializeObject(_forecast10Impl);
                    _si.WeatherUpdateDt = DateTime.Now;
                    _si.City = city;
                    _ctx.SaveChanges();
                    return _forecast10Impl;
                }
            }
            return GetForecast10Impl(city);
        }
 public static ExternalSendInfo Create(SendInfo info)
 {
     return new ExternalSendInfo
     {
         City = info.City,
         DataFileId = info.DataFileId,
         DataFileName = info.DataFileName,
         SendEmail = info.SendEmail,
         SendSms = info.SendSms,
         Temperature = info.Temperature,
         TimeWeekDay = info.TimeWeekDay,
         TimeWeekEnd = info.TimeWeekEnd,
         TimeZoneOffset = info.TimeZoneOffset,
         UserEmail = info.UserEmail,
         UserPhone = info.UserPhone,
         WeekendMode = info.WeekendMode
     };
 }