예제 #1
0
        public CommandHandlerService(IServiceProvider services, DiscordSocketClient client,
                                     ConfigService config, InteractionService commands)
        {
            _client   = client;
            _config   = config;
            _services = services;
            _commands = commands;

            _client.Ready += RegisterCommands;

            _client.InteractionCreated     += InteractionCreated;
            _commands.SlashCommandExecuted += SlashCommandExecutedAsync;
        }
예제 #2
0
        public void Use(GameContext gameContext)
        {
            Console.WriteLine("How much Energy would you like to use?");
            Console.WriteLine($"You have {gameContext.Player.EnergyCurrent}/{gameContext.Player.EnergyTotal} energy");

            var tempUserInput = Console.ReadLine();

            var playerSelection = new InteractionService().GetUserInputForNumberedOptionMenu(tempUserInput, (int)gameContext.Player.EnergyCurrent);

            gameContext.Player.EnergyTotal -= playerSelection;

            var damage = playerSelection;
        }
예제 #3
0
        public async Task <IActionResult> GetExternalProviders(string returnUrl)
        {
            if (returnUrl == null)
            {
                throw new ArgumentNullException(nameof(returnUrl));
            }

            var authorizationContext = await InteractionService.GetAuthorizationContextAsync(returnUrl);

            var providers = await GetProvidersAsync(authorizationContext);

            return(new JsonResult(providers.ToList()));
        }
예제 #4
0
 /// <summary>
 ///     Injected automatically from the service provider.
 /// </summary>
 /// <param name="client"></param>
 /// <param name="interactionService"></param>
 /// <param name="config"></param>
 /// <param name="logger"></param>
 /// <param name="provider"></param>
 public InteractionHandlerService(
     DiscordSocketClient client,
     InteractionService interactionService,
     IOptions <DiscordOptions> config,
     ILogger <InteractionHandlerService> logger,
     IServiceProvider provider)
 {
     _client             = client;
     _interactionService = interactionService;
     _config             = config;
     _logger             = logger;
     _provider           = provider;
 }
예제 #5
0
        internal ModuleBuilder(InteractionService interactionService, ModuleBuilder parent = null)
        {
            InteractionService = interactionService;
            Parent             = parent;

            _attributes           = new List <Attribute>();
            _subModules           = new List <ModuleBuilder>();
            _slashCommands        = new List <SlashCommandBuilder>();
            _contextCommands      = new List <ContextCommandBuilder>();
            _componentCommands    = new List <ComponentCommandBuilder>();
            _autocompleteCommands = new List <AutocompleteCommandBuilder>();
            _modalCommands        = new List <ModalCommandBuilder> ();
            _preconditions        = new List <PreconditionAttribute>();
        }
예제 #6
0
        private void Remove()
        {
            var index = this.Words.IndexOf(this.Word);

            var text = this.WordText;

            this.Context.Items.Remove(this.Word);

            this.Words.Remove(this.Word);

            this.SelectNextWord(index);

            InteractionService.Notify(new NotifyOptions(States.WordRemoved, text));
        }
        public ActionResult Create(InteractionCreate model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }


            var service = new InteractionService();

            service.CreateInteraction(model);

            return(RedirectToAction("Index"));
        }
예제 #8
0
 public InteractionHandler(
     ILoggerFactory loggerFactory,
     DiscordShardedClient client,
     InteractionService interactionService,
     InteractionServiceConfig interactionConfig,
     IServiceProvider serviceProvider
     )
 {
     _logger             = loggerFactory.CreateLogger("Interaction Command");
     _client             = client;
     _interactionService = interactionService;
     _interactionConfig  = interactionConfig;
     _serviceProvider    = serviceProvider;
 }
예제 #9
0
 public Dev(
     ILoggerFactory loggerFactory,
     Cache cache,
     IYuGiOhDbService yuGiOhDbService,
     IGuildConfigDbService guildConfigDbService,
     Web web,
     Random rand,
     InteractionService interactionService,
     IYuGiOhRepository yugiohRepo
     ) : base(loggerFactory, cache, yuGiOhDbService, guildConfigDbService, web, rand)
 {
     _interactionService = interactionService;
     _yugiohRepo         = yugiohRepo;
 }
        /// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="entityIdProperty">The entity identifier property.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override Expression GetExpression(RockContext context, MemberExpression entityIdProperty, string selection)
        {
            string[] selectionValues = selection.Split('|');
            if (selectionValues.Length >= 4)
            {
                var  interactionQry           = new InteractionService(context).Queryable();
                Guid interactionChannelGuid   = selectionValues[0].AsGuid();
                var  interactionComponentGuid = selectionValues[1].AsGuidOrNull();

                if (interactionComponentGuid.HasValue)
                {
                    interactionQry = interactionQry.Where(xx => xx.InteractionComponent.Guid == interactionComponentGuid.Value);
                }
                else
                {
                    interactionQry = interactionQry.Where(xx => xx.InteractionComponent.Channel.Guid == interactionChannelGuid);
                }

                string operation = string.Empty;
                operation = selectionValues[2];

                if (!string.IsNullOrEmpty(operation))
                {
                    interactionQry = interactionQry.Where(xx => xx.Operation == operation);
                }

                string slidingDelimitedValues = selectionValues[3].Replace(',', '|');
                var    dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(slidingDelimitedValues);

                if (dateRange.Start.HasValue)
                {
                    interactionQry = interactionQry.Where(i => i.InteractionDateTime >= dateRange.Start.Value);
                }

                if (dateRange.End.HasValue)
                {
                    interactionQry = interactionQry.Where(i => i.InteractionDateTime <= dateRange.End.Value);
                }

                var qry = new PersonService(context).Queryable()
                          .Select(p => interactionQry.Where(l => l.PersonAlias.PersonId == p.Id)
                                  .Count());

                Expression selectExpression = SelectExpressionExtractor.Extract(qry, entityIdProperty, "p");

                return(selectExpression);
            }

            return(null);
        }
예제 #11
0
        private async Task <ConsentViewModel> BuildConsentViewModel(string returnUrl)
        {
            var request = await InteractionService.GetAuthorizationContextAsync(returnUrl);

            if (request == null)
            {
                throw new InvalidOperationException($"InteractionService.GetAuthorizationContextAsync('{returnUrl}') returned null.");
            }

            var client = await ClientStore.FindEnabledClientByIdAsync(request.ClientId);

            if (client == null)
            {
                throw new InvalidOperationException($"ClientStore.FindEnabledClientByIdAsync(clientid) returned null.");
            }

            var resources = await ResourceStore.FindEnabledResourcesByScopeAsync(request.ScopesRequested);

            if (resources == null)
            {
                var scopes = string.Join(", ", request.ScopesRequested);
                throw new InvalidOperationException($"ResourceStore.FindEnabledResourcesByScopeAsync({scopes}) returned null.");
            }
            if (!resources.IdentityResources.Any() && !resources.ApiResources.Any())
            {
                var scopes = string.Join(", ", request.ScopesRequested);
                throw new InvalidOperationException($"No scopes matching: {scopes}");
            }

            var identityScopes = resources.IdentityResources.Select(ScopeModelForIdentityResource);

            var offlineScopes  = resources.OfflineAccess ? new[] { OfflineAccessScope() } : new ScopeModel[0];
            var resourceScopes = resources.ApiResources
                                 .SelectMany(r => r.Scopes)
                                 .Select(ScopeModelForScope)
                                 .Union(offlineScopes);

            return(new ConsentViewModel
            {
                RememberConsent = true,
                ScopesConsented = Enumerable.Empty <string>(),
                ReturnUrl = returnUrl,
                ClientName = client.ClientName,
                ClientUrl = client.ClientUri,
                ClientLogoUrl = client.LogoUri,
                IdentityScopes = identityScopes,
                ResourceScopes = resourceScopes
            });
        }
        public async Task <IActionResult> Delete(int id)
        {
            await _context.Connection.OpenAsync();

            var query  = new InteractionService(_context);
            var result = await query.GetSingleAsync(id);

            if (result is null)
            {
                return(new NotFoundResult());
            }
            await result.DeleteAsync();

            return(new OkResult());
        }
예제 #13
0
        public Events()
        {
            _services = new ServiceCollection().BuildServices();
            _logger   = _services.GetService <ILoggerFactory>() !.CreateLogger("YuGiOh Bot");

            _logger.Info("Welcome to {AssemblyName:l}", Assembly.GetExecutingAssembly().GetName());
            _logger.Info("Using Discord.NET v{Version:l}", DiscordConfig.Version);
            _logger.Info("Initializing events...");

            _client             = _services.GetService <DiscordShardedClient>();
            _commandService     = _services.GetService <CommandService>();
            _interactionService = _services.GetService <InteractionService>();

            _logger.Info("Finished initializing events.");
        }
예제 #14
0
        public void ChooseWeaponToAttackWith(Character attacker, GameContext gameContext)
        {
            gameContext.PlayerInventory.EunumerateWeapons(gameContext);
            Console.WriteLine("Choose which weapon to attack with (enter the number) ");
            int chosenWeaponToAttackWith;
            var tempUserInput = Console.ReadLine();

            chosenWeaponToAttackWith = new InteractionService().GetUserInputForNumberedOptionMenu(tempUserInput, gameContext.List.WeaponList.Count);

            gameContext.Player.WeaponDamageCurrent = gameContext.List.WeaponList[chosenWeaponToAttackWith].Attack;

            PlayerAttackCalculator.CalculatePlayerAttack(gameContext);

            gameContext.List.WeaponList[chosenWeaponToAttackWith].DurabilityCurrent -= 1;
        }
예제 #15
0
        public void InteractionImport(Rock.BulkImport.InteractionsImport interactionsImport)
        {
            if (interactionsImport == null)
            {
                var response = new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.BadRequest,
                    Content    = new StringContent("InteractionsImport data is required")
                };

                throw new HttpResponseException(response);
            }

            InteractionService.BulkInteractionImport(interactionsImport);
        }
예제 #16
0
        void OnLoaded(object sender, EventArgs e)
        {
            // Disabling maximize button
            var hwnd = new WindowInteropHelper(this).Handle;

            SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_MAXIMIZEBOX);

            var wapkg = InteractionService.Get();

            wapkg.Subscribe();
            wapkg.RequestUpdate();
            wapkg.RequestDistributions();
            wapkg.RequestWorkingDirectory();
            wapkg.RequestSources();
        }
 public DiscordSocketAdapter(DiscordSocketClient client, Settings settings, Logger logger, IServiceProvider provider, IMediator mediator)
 {
     _client             = client;
     _settings           = settings;
     _logger             = logger;
     _provider           = provider;
     _mediator           = mediator;
     _interactionService = new InteractionService(_client, new InteractionServiceConfig()
     {
         DefaultRunMode    = RunMode.Async,
         UseCompiledLambda = true
     });
     _client.Ready += OnDiscordReady;
     _client.Log   += ClientOnLog;
 }
예제 #18
0
        public void ChooseSpellOrWeapon(GameContext gameContext, Character attacker, Character defender)
        {
            Console.WriteLine("0) Use a Spell");
            Console.WriteLine("1) Attack with a Weapon");
            Console.WriteLine("2) Use a Consumable");
            Console.WriteLine();
            Console.WriteLine("Please select an action using its number");
            var tempUserInput = Console.ReadLine();

            var playerSelection = new InteractionService().GetUserInputForNumberedOptionMenu(tempUserInput, 3);

            switch (playerSelection)
            {
            case 0:
                // Use Spell
                gameContext.PlayerInventory.EnumerateSpells(gameContext);
                Console.WriteLine("Choose a spell to use (Enter the number)");
                tempUserInput = Console.ReadLine();
                var chosenSpellToAttackWith = new InteractionService().GetUserInputForNumberedOptionMenu(tempUserInput, gameContext.List.SpellList.Count);

                // THIS IS GOING TO NEED TO BE FLESHED OUT
                gameContext.VirtualGun.Use(gameContext);
                break;

            case 1:
                // Attack with Weapon
                gameContext.List.WeaponList[playerSelection].DurabilityCurrent -= 1;

                // Rolling
                attacker.Roll = gameContext.Roller.GetRandomNumber(1, 12);
                Console.WriteLine("attacker's roll " + attacker.Roll + "\n");

                // Calculate Damage
                var damage = (attacker.Roll / 10) * attacker.Attack;
                Console.WriteLine("Damage " + (damage) + "\n");

                // Apply damage to defender
                defender.HitPointsCurrent = defender.HitPointsCurrent - damage;
                Console.WriteLine("Defender's HP  " + defender.HitPointsCurrent + "\n");
                StandardMessages.ReturnToContinue();

                break;

            case 2:
                // Use a Consumable
                break;
            }
        }
예제 #19
0
        private async Task Patch(DirectoryInfo translationDir)
        {
            Position = 0;

            if (CancelEvent.IsSet())
                return;

            FFXIIIGamePart gamePart = FFXIIIGamePart.Part1; // TODO
            InteractionService.SetGamePart(gamePart);

            String configurationFilePath = Path.Combine(translationDir.FullName, PatcherService.ConfigurationFileName);
            XmlElement config = XmlHelper.LoadDocument(configurationFilePath);
            LocalizatorEnvironmentInfo info = LocalizatorEnvironmentInfo.FromXml(config["LocalizatorEnvironment"]);
            info.Validate();

            LocalizatorEnvironmentInfo currentInfo = InteractionService.LocalizatorEnvironment.Provide();
            currentInfo.UpdateUrls(info);

            InteractionService.LocalizatorEnvironment.SetValue(currentInfo);
            InteractionService.WorkingLocation.SetValue(new WorkingLocationInfo(translationDir.FullName));

            if (currentInfo.IsIncompatible(typeof(App).Assembly.GetName().Version))
            {
                if (MessageBox.Show(this.GetParentElement<Window>(), "Ваша версия программы установки несовместима с текущим перевод. Обновить?", "Ошибка!", MessageBoxButton.YesNo, MessageBoxImage.Error) != MessageBoxResult.Yes)
                    return;

                string path = await DownloadLatestPatcher();
                DirectoryInfo updatePath = ExtractZipToTempFolder(path);
                string destination = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\');

                string patcherPath = Path.Combine(updatePath.FullName, "Pulse.Patcher.exe");
                ProcessStartInfo procInfo = new ProcessStartInfo(patcherPath, $"/u \"{destination}\"")
                {
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    WorkingDirectory = updatePath.FullName
                };
                
                Process.Start(procInfo);
                Environment.Exit(0);
            }

            if (CancelEvent.IsSet())
                return;

            GameLocationInfo gameLocation = PatcherService.GetGameLocation(gamePart);
            await Task.Run(() => Patch(translationDir, gameLocation));
        }
예제 #20
0
        /// <summary>
        /// Logs the interactions.
        /// </summary>
        /// <param name="interactionTransactionInfos">The interaction transaction infos to process.</param>
        /// <param name="rockContext">The rock context.</param>
        private void LogInteractions(List <InteractionTransactionInfo> interactionTransactionInfos, RockContext rockContext)
        {
            List <Interaction> interactionsToInsert = new List <Interaction>();

            var interactionService = new InteractionService(rockContext);

            foreach (var info in interactionTransactionInfos.Where(a => a.InteractionComponentId.HasValue))
            {
                /*
                 * 2020-06-29 - JH
                 *
                 * The 'CreateInteraction(...)' method called below sets the following properties on the Interaction object:
                 *
                 * - InteractionComponentId
                 * - InteractionDateTime (but with the wrong value)
                 * - InteractionSessionId
                 * - Source
                 * - Medium
                 * - Campaign
                 * - Content
                 * - Term
                 */
                var interaction = interactionService.CreateInteraction(info.InteractionComponentId.Value, info.UserAgent, info.InteractionData, info.IPAddress, info.BrowserSessionId);

                // The rest of the properties need to be manually set.
                interaction.EntityId               = info.InteractionEntityId;
                interaction.Operation              = info.InteractionOperation.IsNotNullOrWhiteSpace() ? info.InteractionOperation.Trim() : "View";
                interaction.InteractionSummary     = info.InteractionSummary?.Trim();
                interaction.PersonAliasId          = info.PersonAliasId;
                interaction.InteractionDateTime    = info.InteractionDateTime;
                interaction.InteractionTimeToServe = info.InteractionTimeToServe;
                interaction.RelatedEntityTypeId    = info.InteractionRelatedEntityTypeId;
                interaction.RelatedEntityId        = info.InteractionRelatedEntityId;
                interaction.ChannelCustom1         = info.InteractionChannelCustom1?.Trim();
                interaction.ChannelCustom2         = info.InteractionChannelCustom2?.Trim();
                interaction.ChannelCustomIndexed1  = info.InteractionChannelCustomIndexed1?.Trim();

                interaction.SetInteractionData(info.InteractionData?.Trim());
                interactionsToInsert.Add(interaction);
            }

            rockContext.BulkInsert(interactionsToInsert);

            // This logic is normally handled in the Interaction.PostSave method, but since the BulkInsert bypasses those
            // model hooks, streaks need to be updated here. Also, it is not necessary for this logic to complete before this
            // transaction can continue processing and exit, so update the streak using a task.
            interactionsToInsert.ForEach(i => Task.Run(() => StreakTypeService.HandleInteractionRecord(i)));
        }
예제 #21
0
        public static void Crash(object exceptionObject)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                new ExceptionWindow(exceptionObject).ShowDialog();
            });

            var process = InteractionService.Get().ServiceProcess;

            if (process != null && !process.HasExited)
            {
                process.Kill();
            }

            Environment.Exit(1);
        }
        public ActionResult Edit(int id)

        {
            var service = new InteractionService();
            var detail  = service.GetInteractionById(id);
            var model   =
                new InteractionEdit
            {
                InteractionID = detail.InteractionID,
                TypeOfContact = detail.TypeOfContact,
                Description   = detail.Description,
                ModifiedUtc   = DateTimeOffset.Now
            };

            return(View(model));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AndroidDevice"/> class.
        /// </summary>
        /// <param name="configuration">Device Configuration</param>
        public AndroidDevice(DeviceConfiguration configuration)
        {
            Configuration = configuration;
            var server = new UiAutomatorServer(new Terminal(configuration), configuration.Port, configuration.DumpTimeout);

            Adb = new AdbService(new Terminal(configuration));
            Ui  = new UiService(
                new ScreenDumper(server, configuration.DumpTries),
                new NodeParser(),
                new NodeFinder());
            Settings    = new SettingsService();
            Activity    = new ActivityService();
            Interaction = new InteractionService(server);
            SetOwner();
            InstallHelperApks();
        }
예제 #24
0
        public async Task <IActionResult> Login(LoginViewModel model, string button)
        {
            var context = await InteractionService.GetAuthorizationContextAsync(model.ReturnUrl);

            if (button != "login")
            {
                return(await Cancel(context, model));
            }
            if (ModelState.IsValid == false)
            {
                var viewModel = await BuildLoginViewModelAsync(model);

                return(View(viewModel));
            }
            return(await Login(context, model));
        }
        /// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="entityIdProperty">The entity identifier property.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override Expression GetExpression(RockContext context, MemberExpression entityIdProperty, string selection)
        {
            string[] selectionValues = selection.Split('|');
            if (selectionValues.Length >= 4)
            {
                var  interactionQry           = new InteractionService(context).Queryable();
                Guid interactionChannelGuid   = selectionValues[0].AsGuid();
                var  interactionComponentGuid = selectionValues[1].AsGuidOrNull();

                if (interactionComponentGuid.HasValue)
                {
                    interactionQry = interactionQry.Where(xx => xx.InteractionComponent.Guid == interactionComponentGuid.Value);
                }
                else
                {
                    interactionQry = interactionQry.Where(xx => xx.InteractionComponent.Channel.Guid == interactionChannelGuid);
                }

                string operation = string.Empty;
                operation = selectionValues[2];

                if (!string.IsNullOrEmpty(operation))
                {
                    interactionQry = interactionQry.Where(xx => xx.Operation == operation);
                }

                var selectionMode = selectionValues[3].ConvertToEnum <FirstLastInteraction>();

                IQueryable <DateTime?> qry;
                if (selectionMode == FirstLastInteraction.First)
                {
                    qry = new PersonService(context).Queryable().Select(p => interactionQry.Where(l => l.PersonAlias.PersonId == p.Id)
                                                                        .Min(l => ( DateTime? )l.InteractionDateTime));
                }
                else
                {
                    qry = new PersonService(context).Queryable().Select(p => interactionQry.Where(l => l.PersonAlias.PersonId == p.Id)
                                                                        .Max(l => ( DateTime? )l.InteractionDateTime));
                }

                Expression selectExpression = SelectExpressionExtractor.Extract(qry, entityIdProperty, "p");

                return(selectExpression);
            }

            return(null);
        }
        /// <summary>
        /// Handles the Click event of the btnUpdate control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
        private void btnUpdate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                isEditDone = true;
                DGCaseDataInfo.CancelEdit();
                var    selectedCallData = DGCaseDataInfo.SelectedItem as EmailCaseData;
                string key   = selectedCallData.Key;
                string value = selectedCallData.Value;
                if (CurrentData.ContainsKey(key))
                {
                    string originalValue = CurrentData[key].ToString();
                    if (value != originalValue)
                    {
                        KeyValueCollection caseData = new KeyValueCollection();
                        caseData.Add(key, value);
                        InteractionService interactionService = new InteractionService();
                        Pointel.Interactions.Core.Common.OutputValues result = interactionService.UpdateCaseDataProperties(interactionId, EmailDataContext.GetInstance().ProxyClientID, caseData);
                        if (result.MessageCode == "200")
                        {
                            CurrentData[key] = value;
                        }
                        caseData.Clear();
                    }
                }
                else
                {
                    KeyValueCollection caseData = new KeyValueCollection();
                    caseData.Add(key, value);
                    InteractionService interactionService = new InteractionService();
                    Pointel.Interactions.Core.Common.OutputValues result = interactionService.AddCaseDataProperties(interactionId, EmailDataContext.GetInstance().ProxyClientID, caseData);
                    if (result.MessageCode == "200")
                    {
                        CurrentData.Add(key, value);
                    }
                    caseData.Clear();
                }
                editingValue = editingKey = null;

                //  BindGrid();
            }
            catch (Exception commonException)
            {
                logger.Error("Error ocurred as " + commonException.Message);
            }
        }
예제 #27
0
        private void ExecuteCopyToClipboardCommand(object arg)
        {
            if (!(arg is string s))
            {
                return;
            }

            try
            {
                Clipboard.SetText(s);
                InteractionService.ShowInformationMessageBox(Application.Current.TryFindResource("ClipboardSuccess").ToString());
            }
            catch (Exception ex)
            {
                LOG.Error(ex, "{0} caused a(n) {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, ex.GetType().Name);
            }
        }
예제 #28
0
        public async Task <IActionResult> Login(LoginInputModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            if (!InteractionService.IsValidReturnUrl(model.ReturnUrl))
            {
                throw new InvalidOperationException($"The url of '{model.ReturnUrl}' is not a valid return url.");
            }

            if (ModelState.IsValid)
            {
                if (TestUserStore.ValidateCredentials(model.Username, model.Password))
                {
                    var expiry = DateTimeOffset.UtcNow.Add(AuthorizationOptions.RefreshTokenLifetime);
                    var props  = model.RememberLogin ?
                                 new AuthenticationProperties {
                        ExpiresUtc = expiry, IsPersistent = true
                    } :
                    null;

                    var user = TestUserStore.FindByUsername(model.Username);
                    await HttpContext.Authentication.SignInAsync(user.SubjectId, user.Username, props);

                    return(Redirect(model.ReturnUrl));
                }

                ModelState.AddModelError(string.Empty, "Invalid username or password");
            }

            var authorizationContext = await InteractionService.GetAuthorizationContextAsync(model.ReturnUrl);

            var externalProviders = await GetProvidersAsync(authorizationContext);

            var viewModel = new LoginViewModel
            {
                Username          = model.Username,
                Password          = model.Password,
                RememberLogin     = model.RememberLogin,
                ReturnUrl         = model.ReturnUrl,
                ExternalProviders = externalProviders
            };

            return(View(nameof(Login), viewModel));
        }
예제 #29
0
        internal ModuleInfo Build(InteractionService interactionService, IServiceProvider services, ModuleInfo parent = null)
        {
            var moduleInfo = new ModuleInfo(this, interactionService, services, parent);

            IInteractionModuleBase instance = ReflectionUtils <IInteractionModuleBase> .CreateObject(TypeInfo, interactionService, services);

            try
            {
                instance.OnModuleBuilding(interactionService, moduleInfo);
            }
            finally
            {
                (instance as IDisposable)?.Dispose();
            }

            return(moduleInfo);
        }
예제 #30
0
        public async Task <IActionResult> Login(LoginInputModel model)
        {
            if (ModelState.IsValid)
            {
                // validate username/password against in-memory store
                if (await UsersStore.ValidateCredentials(model.Username, model.Password))
                {
                    AuthenticationProperties props = null;
                    // only set explicit expiration here if persistent.
                    // otherwise we reply upon expiration configured in cookie middleware.
                    if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                    {
                        props = new AuthenticationProperties
                        {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                        };
                    }

                    // issue authentication cookie with subject ID and username
                    var user = await UsersStore.FindByUsername(model.Username);

                    await EventsService.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username));

                    await HttpContext.Authentication.SignInAsync(user.SubjectId, user.Username, props);

                    // make sure the returnUrl is still valid, and if yes - redirect back to authorize endpoint or a local page
                    if (InteractionService.IsValidReturnUrl(model.ReturnUrl) || Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }

                    return(Redirect("~/"));
                }

                await EventsService.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));

                ModelState.AddModelError("", AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = await AccountService.BuildLoginViewModelAsync(model);

            return(View(vm));
        }
예제 #31
0
        /// <summary>
        /// Shows the active users.
        /// </summary>
        private void ShowActiveUsers()
        {
            int? siteId = GetAttributeValue( "Site" ).AsIntegerOrNull();
            if ( !siteId.HasValue || SiteCache.Read(siteId.Value) == null )
            {
                lMessages.Text = "<div class='alert alert-warning'>No site is currently configured.</div>";
                return;
            }
            else
            {
                int pageViewCount = GetAttributeValue( "PageViewCount" ).AsIntegerOrNull() ?? 0;

                StringBuilder sbUsers = new StringBuilder();

                var site = SiteCache.Read( siteId.Value );
                lSiteName.Text = "<h4>" + site.Name + "</h4>";
                lSiteName.Visible = GetAttributeValue( "ShowSiteNameAsTitle" ).AsBoolean();

                if ( !site.EnablePageViews )
                {
                    lMessages.Text = "<div class='alert alert-warning'>Active " + site.Name + " users not available because page views are not enabled for site.</div>";
                    return;
                }

                lMessages.Text = string.Empty;
                string guestVisitorsStr = string.Empty;

                using ( var rockContext = new RockContext() )
                {
                    //var qryPageViews = new PageViewService( rockContext ).Queryable();

                    var qryPageViews = new InteractionService( rockContext ).Queryable();

                    var qryPersonAlias = new PersonAliasService( rockContext ).Queryable();
                    var pageViewQry = qryPageViews.Join(
                        qryPersonAlias,
                        pv => pv.PersonAliasId,
                        pa => pa.Id,
                        ( pv, pa ) =>
                        new
                        {
                            PersonAliasPersonId = pa.PersonId,
                            pv.InteractionDateTime,
                            pv.InteractionComponent.Channel.ChannelEntityId,
                            pv.InteractionSessionId,
                            PagePageTitle = pv.InteractionComponent.Name
                        } );

                    var last24Hours = RockDateTime.Now.AddDays( -1 );

                    int pageViewTakeCount = pageViewCount;
                    if ( pageViewTakeCount == 0 )
                    {
                        pageViewTakeCount = 1;
                    }

                    // Query to get who is logged in and last visit was to selected site
                    var activeLogins = new UserLoginService( rockContext ).Queryable()
                        .Where( l =>
                            l.PersonId.HasValue &&
                            l.IsOnLine == true )
                        .OrderByDescending( l => l.LastActivityDateTime )
                        .Select( l => new
                        {
                            login = new
                            {
                                l.UserName,
                                l.LastActivityDateTime,
                                l.PersonId,
                                Person = new
                                {
                                    l.Person.NickName,
                                    l.Person.LastName,
                                    l.Person.SuffixValueId
                                }
                            },
                            pageViews = pageViewQry
                                .Where( v => v.PersonAliasPersonId == l.PersonId )
                                .Where( v => v.InteractionDateTime > last24Hours )
                                .OrderByDescending( v => v.InteractionDateTime )
                                .Take( pageViewTakeCount )
                        } )
                        .Select( a => new
                        {
                            a.login,
                            pageViews = a.pageViews.ToList()
                        } );

                    if ( CurrentUser != null )
                    {
                        activeLogins = activeLogins.Where( m => m.login.UserName != CurrentUser.UserName );
                    }

                    foreach ( var activeLogin in activeLogins )
                    {
                        var login = activeLogin.login;

                        if ( !activeLogin.pageViews.Any() || activeLogin.pageViews.FirstOrDefault().ChannelEntityId != site.Id )
                        {
                            // only show active logins with PageViews and the most recent pageview is for the specified site
                            continue;
                        }

                        var latestPageViewSessionId = activeLogin.pageViews.FirstOrDefault().InteractionSessionId;

                        TimeSpan tsLastActivity = login.LastActivityDateTime.HasValue ? RockDateTime.Now.Subtract( login.LastActivityDateTime.Value ) : TimeSpan.MaxValue;
                        string className = tsLastActivity.Minutes <= 5 ? "recent" : "not-recent";

                        // create link to the person
                        string personFullName = Person.FormatFullName( login.Person.NickName, login.Person.LastName, login.Person.SuffixValueId );
                        string personLink = personFullName;

                        if ( GetAttributeValue( "PersonProfilePage" ) != null )
                        {
                            string personProfilePage = GetAttributeValue( "PersonProfilePage" );
                            var pageParams = new Dictionary<string, string>();
                            pageParams.Add( "PersonId", login.PersonId.ToString() );
                            var pageReference = new Rock.Web.PageReference( personProfilePage, pageParams );
                            personLink = string.Format( @"<a href='{0}'>{1}</a>", pageReference.BuildUrl(), personFullName );
                        }

                        // determine whether to show last page views
                        if ( GetAttributeValue( "PageViewCount" ).AsInteger() > 0 )
                        {
                            string activeLoginFormat = @"
            <li class='active-user {0}' data-toggle='tooltip' data-placement='top' title='{2}'>
            <i class='fa-li fa fa-circle'></i> {1}
            </li>";
                            // define the formatting for each user entry
                            if ( activeLogin.pageViews != null )
                            {
                                string pageViewsHtml = activeLogin.pageViews
                                                    .Where( v => v.InteractionSessionId == latestPageViewSessionId )
                                                    .Select( v => HttpUtility.HtmlEncode( v.PagePageTitle ) ).ToList().AsDelimited( "<br> " );

                                sbUsers.Append( string.Format( activeLoginFormat, className, personLink, pageViewsHtml ) );
                            }
                        }
                        else
                        {
                            string inactiveLoginFormat = @"
            <li class='active-user {0}'>
            <i class='fa-li fa fa-circle'></i> {1}
            </li>";
                            sbUsers.Append( string.Format( inactiveLoginFormat, className, personLink ) );
                        }
                    }

                    // get the 'show guests' attribute and if it's true, determine how many guests there are.
                    bool showGuestVisitors = GetAttributeValue( "ShowGuestVisitors" ).AsBoolean();
                    if ( showGuestVisitors )
                    {
                        // build a list of unique sessions views in the past 15 minutes.
                        // We'll only take entries with a null personAliasID, which means they're not logged in,
                        // and thus ARE guests.
                        var last5Minutes = RockDateTime.Now.AddMinutes( -5 );
                        var last15Minutes = RockDateTime.Now.AddMinutes( -15 );

                        var qryGuests = new PageViewService( rockContext ).Queryable().AsNoTracking()
                                          .Where(
                                                p => p.SiteId == site.Id
                                                && p.DateTimeViewed > last15Minutes
                                                && p.PersonAliasId == null
                                                && p.PageViewSession.PageViewUserAgent.Browser != "Other"
                                                && p.PageViewSession.PageViewUserAgent.ClientType != "Crawler" )
                                          .GroupBy( p => p.PageViewSessionId )
                                          .Select( g => new
                                          {
                                              SessionId = g.Key,
                                              LastVisit = g.Max( p => p.DateTimeViewed )
                                          } )
                                          .ToList();

                        var numRecentGuests = qryGuests.Where( g => g.LastVisit >= last5Minutes ).Count();
                        var numInactiveGuests = qryGuests.Where( g => g.LastVisit < last5Minutes ).Count();

                        // now build the formatted entry, which is "Current Guests (0) (1)" where the first is a green badge, and the second yellow.
                        if ( numRecentGuests > 0 || numInactiveGuests > 0 )
                        {
                            guestVisitorsStr = "Current Guests:";
                            if ( numRecentGuests > 0 )
                            {
                                guestVisitorsStr += string.Format( " <span class=\"badge badge-success\">{0}</span>", numRecentGuests );
                            }

                            if ( numInactiveGuests > 0 )
                            {
                                guestVisitorsStr += string.Format( " <span class=\"badge badge-warning\">{0}</span>", numInactiveGuests );
                            }
                        }
                    }
                }

                if ( sbUsers.Length > 0 )
                {
                    lUsers.Text = string.Format( @"<ul class='activeusers fa-ul'>{0}</ul>", sbUsers.ToString() );
                    lUsers.Text += string.Format( @"<p class='margin-l-sm'>{0}</p>", guestVisitorsStr );
                }
                else
                {
                    lMessages.Text = string.Format( "There are no logged in users on the {0} site.", site.Name );
                    lMessages.Text += "<br /><br />" + guestVisitorsStr;
                }
            }
        }
예제 #32
0
        public int GetLastVisitOnSite( int personId, int siteId )
        {
            int channelMediumValueId = DefinedValueCache.Read( SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid() ).Id;

            InteractionChannelService interactionChannelService = new InteractionChannelService( ( Rock.Data.RockContext ) Service.Context );
            var interactionChannel = interactionChannelService.Queryable()
                                                .Where( a => a.ChannelTypeMediumValueId == channelMediumValueId && a.ChannelEntityId == siteId )
                                                .FirstOrDefault();

            if ( interactionChannel == null )
            {
                return -1;
            }
            Interaction mostRecentPageView = new InteractionService( ( Rock.Data.RockContext ) Service.Context ).Queryable()
                                                .Where( a => a.PersonAlias.PersonId == personId && a.InteractionComponent.ChannelId == interactionChannel.Id )
                                                .OrderByDescending( p => p.InteractionDateTime )
                                                .FirstOrDefault();

            if ( mostRecentPageView != null )
            {
                TimeSpan duration = RockDateTime.Now - mostRecentPageView.InteractionDateTime;
                return duration.Days;
            }

            return -1;
        }
예제 #33
0
        /// <summary>
        /// Shows the list.
        /// </summary>
        public void ShowList()
        {
            var rockContext = new RockContext();

            int sessionCount = GetAttributeValue( "SessionCount" ).AsInteger();

            int skipCount = pageNumber * sessionCount;

            var person = new PersonService( rockContext ).GetByUrlEncodedKey( PageParameter( "Person" ) );

            if ( person != null )
            {
                lPersonName.Text = person.FullName;

                InteractionService interactionService = new InteractionService( rockContext );

                var pageViews = interactionService.Queryable();

                var sessionInfo = interactionService.Queryable()
                    .Where( s => s.PersonAlias.PersonId == person.Id );

                if ( startDate != DateTime.MinValue )
                {
                    sessionInfo = sessionInfo.Where( s => s.InteractionDateTime > drpDateFilter.LowerValue );
                }

                if ( endDate != DateTime.MaxValue )
                {
                    sessionInfo = sessionInfo.Where( s => s.InteractionDateTime < drpDateFilter.UpperValue );
                }

                if ( siteId != -1 )
                {
                    var site = SiteCache.Read( siteId );

                    string siteName = string.Empty;
                    if (site != null )
                    {
                        siteName = site.Name;
                    }
                    // lookup the interactionDeviceType, and create it if it doesn't exist
                    int channelMediumValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid() ).Id;

                    var interactionChannelId = new InteractionChannelService( rockContext ).Queryable()
                                                        .Where( a => a.ChannelTypeMediumValueId == channelMediumValueId && a.ChannelEntityId == siteId )
                                                        .Select( a => a.Id)
                                                        .FirstOrDefault();

                    sessionInfo = sessionInfo.Where( p => p.InteractionComponent.ChannelId == interactionChannelId );
                }

                var pageviewInfo = sessionInfo.GroupBy( s => new
                                {
                                    s.InteractionSession,
                                    s.InteractionComponent.Channel,
                                } )
                                .Select( s => new WebSession
                                {
                                    PageViewSession = s.Key.InteractionSession,
                                    StartDateTime = s.Min( x => x.InteractionDateTime ),
                                    EndDateTime = s.Max( x => x.InteractionDateTime ),
                                    SiteId = siteId,
                                    Site = s.Key.Channel.Name,
                                    PageViews = pageViews.Where( p => p.InteractionSessionId == s.Key.InteractionSession.Id && p.InteractionComponent.ChannelId == s.Key.Channel.Id ).OrderBy(p => p.InteractionDateTime).ToList()
                                } );

                pageviewInfo = pageviewInfo.OrderByDescending( p => p.StartDateTime )
                                .Skip( skipCount )
                                .Take( sessionCount + 1 );

                rptSessions.DataSource = pageviewInfo.ToList().Take( sessionCount );
                rptSessions.DataBind();

                // set next button
                if ( pageviewInfo.Count() > sessionCount )
                {
                    hlNext.Visible = hlNext.Enabled = true;
                    Dictionary<string, string> queryStringNext = new Dictionary<string, string>();
                    queryStringNext.Add( "Page", ( pageNumber + 1 ).ToString() );
                    queryStringNext.Add( "Person", person.UrlEncodedKey );
                    if ( siteId != -1 )
                    {
                        queryStringNext.Add( "SiteId", siteId.ToString() );
                    }

                    if ( startDate != DateTime.MinValue )
                    {
                        queryStringNext.Add( "StartDate", startDate.ToShortDateString() );
                    }

                    if ( endDate != DateTime.MaxValue )
                    {
                        queryStringNext.Add( "EndDate", endDate.ToShortDateString() );
                    }

                    var pageReferenceNext = new Rock.Web.PageReference( CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringNext );
                    hlNext.NavigateUrl = pageReferenceNext.BuildUrl();
                }
                else
                {
                    hlNext.Visible = hlNext.Enabled = false;
                }

                // set prev button
                if ( pageNumber == 0 )
                {
                    hlPrev.Visible = hlPrev.Enabled = false;
                }
                else
                {
                    hlPrev.Visible = hlPrev.Enabled = true;
                    Dictionary<string, string> queryStringPrev = new Dictionary<string, string>();
                    queryStringPrev.Add( "Page", ( pageNumber - 1 ).ToString() );
                    queryStringPrev.Add( "Person", person.UrlEncodedKey );
                    if ( siteId != -1 )
                    {
                        queryStringPrev.Add( "SiteId", siteId.ToString() );
                    }

                    if ( startDate != DateTime.MinValue )
                    {
                        queryStringPrev.Add( "StartDate", startDate.ToShortDateString() );
                    }

                    if ( endDate != DateTime.MaxValue )
                    {
                        queryStringPrev.Add( "EndDate", endDate.ToShortDateString() );
                    }

                    var pageReferencePrev = new Rock.Web.PageReference( CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringPrev );
                    hlPrev.NavigateUrl = pageReferencePrev.BuildUrl();
                }
            }
            else
            {
                lMessages.Text = "<div class='alert alert-warning'>No person provided to show results for.</div>";
            }
        }
예제 #34
0
        /// <summary>
        /// Execute method to write transaction to the database.
        /// </summary>
        public void Execute()
        {
            using ( var rockContext = new RockContext() )
            {

                var userAgent = (this.UserAgent ?? string.Empty).Trim();
                if ( userAgent.Length > 450 )
                {
                    userAgent = userAgent.Substring( 0, 450 ); // trim super long useragents to fit in pageViewUserAgent.UserAgent
                }

                // get user agent info
                var clientType = PageViewUserAgent.GetClientType( userAgent );

                // don't log visits from crawlers
                if ( clientType != "Crawler" )
                {
                    InteractionChannelService interactionChannelService = new InteractionChannelService( rockContext );
                    InteractionComponentService interactionComponentService = new InteractionComponentService( rockContext );
                    InteractionDeviceTypeService interactionDeviceTypeService = new InteractionDeviceTypeService( rockContext );
                    InteractionSessionService interactionSessionService = new InteractionSessionService( rockContext );
                    InteractionService interactionService = new InteractionService( rockContext );

                    ClientInfo client = uaParser.Parse( userAgent );
                    var clientOs = client.OS.ToString();
                    var clientBrowser = client.UserAgent.ToString();

                    // lookup the interactionDeviceType, and create it if it doesn't exist
                    var interactionDeviceType = interactionDeviceTypeService.Queryable().Where( a => a.Application == clientBrowser
                                                && a.OperatingSystem == clientOs && a.ClientType == clientType ).FirstOrDefault();

                    if ( interactionDeviceType == null )
                    {
                        interactionDeviceType = new InteractionDeviceType();
                        interactionDeviceType.DeviceTypeData = userAgent;
                        interactionDeviceType.ClientType = clientType;
                        interactionDeviceType.OperatingSystem = clientOs;
                        interactionDeviceType.Application = clientBrowser;
                        interactionDeviceType.Name = string.Format( "{0} - {1}", clientOs, clientBrowser );
                        interactionDeviceTypeService.Add( interactionDeviceType );
                        rockContext.SaveChanges();
                    }

                    // lookup interactionSession, and create it if it doesn't exist
                    Guid sessionId = this.SessionId.AsGuid();
                    int? interactionSessionId = interactionSessionService.Queryable()
                                                    .Where(
                                                        a => a.DeviceTypeId == interactionDeviceType.Id
                                                        && a.Guid == sessionId )
                                                    .Select( a => (int?)a.Id )
                                                    .FirstOrDefault();

                    if ( !interactionSessionId.HasValue )
                    {
                        var interactionSession = new InteractionSession();
                        interactionSession.DeviceTypeId = interactionDeviceType.Id;
                        interactionSession.IpAddress = this.IPAddress;
                        interactionSession.Guid = sessionId;
                        interactionSessionService.Add( interactionSession );
                        rockContext.SaveChanges();
                        interactionSessionId = interactionSession.Id;
                    }

                    int componentEntityTypeId = EntityTypeCache.Read<Rock.Model.Page>().Id;
                    string siteName = SiteCache.Read( SiteId ?? 1 ).Name;

                    // lookup the interaction channel, and create it if it doesn't exist
                    int channelMediumTypeValueId = DefinedValueCache.Read( SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid() ).Id;

                    // check that the site exists as a channel
                    var interactionChannel = interactionChannelService.Queryable()
                                                        .Where( a =>
                                                            a.ChannelTypeMediumValueId == channelMediumTypeValueId
                                                            && a.ChannelEntityId == this.SiteId )
                                                        .FirstOrDefault();
                    if ( interactionChannel == null )
                    {
                        interactionChannel = new InteractionChannel();
                        interactionChannel.Name = siteName;
                        interactionChannel.ChannelTypeMediumValueId = channelMediumTypeValueId;
                        interactionChannel.ChannelEntityId = this.SiteId;
                        interactionChannel.ComponentEntityTypeId = componentEntityTypeId;
                        interactionChannelService.Add( interactionChannel );
                        rockContext.SaveChanges();
                    }

                    // check that the page exists as a component
                    var interactionComponent = interactionComponentService.Queryable()
                                                        .Where( a =>
                                                            a.EntityId == PageId
                                                            && a.ChannelId == interactionChannel.Id )
                                                        .FirstOrDefault();
                    if ( interactionComponent == null )
                    {
                        interactionComponent = new InteractionComponent();
                        interactionComponent.Name = PageTitle;
                        interactionComponent.EntityId = PageId;
                        interactionComponent.ChannelId = interactionChannel.Id;
                        interactionComponentService.Add( interactionComponent );
                        rockContext.SaveChanges();
                    }

                    // add the interaction
                    Interaction interaction = new Interaction();
                    interactionService.Add( interaction );

                    // obfuscate rock magic token
                    Regex rgx = new Regex( @"rckipid=([^&]*)" );
                    string cleanUrl = rgx.Replace( this.Url, "rckipid=XXXXXXXXXXXXXXXXXXXXXXXXXXXX" );

                    interaction.InteractionData = cleanUrl;
                    interaction.Operation = "View";
                    interaction.PersonAliasId = this.PersonAliasId;
                    interaction.InteractionDateTime = this.DateViewed;
                    interaction.InteractionSessionId = interactionSessionId;
                    interaction.InteractionComponentId = interactionComponent.Id;
                    rockContext.SaveChanges();
                }
            }
        }