Esempio n. 1
0
        protected override async Task <EditDynamicServiceDataViewModel> BuildViewModel(ExternalServiceData data)
        {
            var client     = new DynamicServiceService(data, null, null, null);
            var clientData = client.GetData();

            var recipes = await _recipeManager.GetRecipes(new RecipesQuery()
            {
                UserId = _userManager.GetUserId(User)
            });

            var recipe = string.IsNullOrEmpty(clientData.RecipeId)
                ? null
                : recipes.SingleOrDefault(recipe1 =>
                                          recipe1.Id.Equals(clientData.RecipeId, StringComparison.InvariantCultureIgnoreCase));

            return(new EditDynamicServiceDataViewModel()
            {
                Value = clientData.Value,
                RecipeId = clientData.RecipeId,
                RecipeActionId = clientData.RecipeActionId,
                RecipeActionGroupId = clientData.RecipeActionGroupId,
                Recipes = new SelectList(recipes, nameof(Recipe.Id), nameof(Recipe.Name), clientData.RecipeId),
                RecipeActions = recipe == null? null :  new SelectList(recipe.RecipeActions, nameof(RecipeAction.Id), nameof(RecipeAction.ActionId), clientData.RecipeActionId),
                RecipeActionGroups = recipe == null? null :  new SelectList(recipe.RecipeActionGroups, nameof(RecipeActionGroup.Id), nameof(RecipeActionGroup.Id), clientData.RecipeActionGroupId),
            });
        }
Esempio n. 2
0
        public IActionResult RecipeIndex(int recipeID)
        {
            recipeViewModel = new RecipeViewModel();
            var recipeList = recipeManager.GetRecipes();

            foreach (var item in recipeList)
            {
                recipeViewModel.Recipes.Add(RecipeModel.DtoToModel(item));
            }

            return(View(recipeViewModel));
        }
 public override void Execute()
 {
     foreach (Recipe recipe in recipeManager.GetRecipes())
     {
         recipeDrawer.Draw(recipe);
     }
 }
Esempio n. 4
0
        public async Task DispatchTrigger(ITrigger trigger)
        {
            _ = Task.Run(async() =>
            {
                _logger.LogInformation($"Trigger being dispatched: {trigger.Id}");
                var recipes = await _recipeManager.GetRecipes(new RecipesQuery()
                {
                    Enabled   = true,
                    TriggerId = trigger.Id
                });

                _logger.LogInformation($"{recipes.Count()} possible recipes to be triggered by {trigger.Id}");

                var triggeredRecipes = new List <(Recipe Recipe, object TriggerData, ITriggerHandler triggerHandler)>();
                foreach (var recipe in recipes)
                {
                    foreach (var triggerHandler in _handlers)
                    {
                        try
                        {
                            if (await triggerHandler.IsTriggered(trigger, recipe.RecipeTrigger))
                            {
                                triggeredRecipes.Add((recipe, await triggerHandler.GetData(trigger), triggerHandler));
                            }
                        }
                        catch (Exception e)
                        {
                            _logger.LogError($"Trigger Handler {triggerHandler} errored out on {e.Message}");
                        }
                    }
                }

                _logger.LogInformation($"{trigger.Id} triggered {triggeredRecipes.Count()}/{recipes.Count()} recipes");

                var nonGroupedRecipeTasks = triggeredRecipes.SelectMany(recipe =>
                                                                        recipe.Recipe.RecipeActions
                                                                        .Where(recipeAction => string.IsNullOrEmpty(recipeAction.RecipeActionGroupId))
                                                                        .Select(action => (Task)_actionDispatcher.Dispatch(
                                                                                    new Dictionary <string, (object data, string json)>()
                {
                    { "TriggerData", (recipe.TriggerData, trigger.DataJson) }
                }, action)));

                var groupExecutionTasks = triggeredRecipes.SelectMany(recipe => recipe.Recipe.RecipeActionGroups.Select(
                                                                          actionGroup => _actionDispatcher.Dispatch(new Dictionary <string, (object data, string json)>()
                {
                    { "TriggerData", (recipe.TriggerData, trigger.DataJson) }
                }, actionGroup)));

                await Task.WhenAll(nonGroupedRecipeTasks.Concat(groupExecutionTasks));

                foreach (var keyValuePair in triggeredRecipes.GroupBy(tuple => tuple.triggerHandler)
                         .ToDictionary(tuples => tuples.Key, tuples => tuples.ToArray()))
                {
                    await keyValuePair.Key.AfterExecution(keyValuePair.Value.Select(tuple => tuple.Recipe));
                }
            });
        }
Esempio n. 5
0
 public MainWindowViewModel(IRecipeManager recipeManager)
 {
     this.recipeManager = recipeManager;
     recipes            = new ObservableCollection <RecipeModel>();
     foreach (var recipe in recipeManager.GetRecipes())
     {
         recipes.Add(new RecipeModel(recipe));
     }
 }
        public async Task <IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }

            RequirePassword = await _userManager.HasPasswordAsync(user);

            if (RequirePassword)
            {
                if (!await _userManager.CheckPasswordAsync(user, Input.Password))
                {
                    ModelState.AddModelError(string.Empty, "Password not correct.");
                    return(Page());
                }
            }

            var services = await _externalServiceManager.GetExternalServicesData(new ExternalServicesDataQuery()
            {
                UserId = user.Id
            });

            var recipes = await _recipeManager.GetRecipes(new RecipesQuery()
            {
                UserId = user.Id
            });

            foreach (var recipe in recipes)
            {
                await _recipeManager.RemoveRecipe(recipe.Id);
            }

            foreach (var externalServiceData in services)
            {
                await _externalServiceManager.RemoveExternalServiceData(externalServiceData.Id);
            }
            var result = await _userManager.DeleteAsync(user);

            var userId = await _userManager.GetUserIdAsync(user);

            if (!result.Succeeded)
            {
                throw new InvalidOperationException($"Unexpected error occurred deleteing user with ID '{userId}'.");
            }

            await _signInManager.SignOutAsync();

            _logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId);

            return(Redirect("~/"));
        }
Esempio n. 7
0
        public MyRecipeBook(IRecipeManager businessLayer)
        {
            BusinessLayer = businessLayer;
            Recipes       = BusinessLayer.GetRecipes();
            RecipeTypes   = BusinessLayer.GetRecipeTypes();
            RawMaterials  = BusinessLayer.GetRawMaterial();
            Units         = BusinessLayer.GetUnits();

            Soups       = new ObservableCollection <Recipe>(Recipes.Where(r => r.Type.Name == "Leves"));
            MainCourses = new ObservableCollection <Recipe>(Recipes.Where(r => r.Type.Name == "Főétel"));
            Desserts    = new ObservableCollection <Recipe>(Recipes.Where(r => r.Type.Name == "Desszert"));
        }
Esempio n. 8
0
        public async Task <IActionResult> GetRecipes([FromQuery] string statusMessage = null)
        {
            var recipes = await _recipeManager.GetRecipes(new RecipesQuery()
            {
                UserId = _userManager.GetUserId(User)
            });

            return(View(new GetRecipesViewModel()
            {
                StatusMessage = statusMessage,
                Recipes = recipes
            }));
        }
Esempio n. 9
0
        public virtual async Task <IActionResult> UserRecipes(string userId, [FromQuery] string statusMessage = null)
        {
            var recipes = await _recipeManager.GetRecipes(new RecipesQuery()
            {
                UserId = userId
            });

            return(View(new GetRecipesViewModel()
            {
                StatusMessage = statusMessage,
                Recipes = recipes
            }));
        }
Esempio n. 10
0
        public virtual async Task <IActionResult> GetRecipes([FromQuery] string statusMessage = null, GetRecipesViewModel.ListMode mode = GetRecipesViewModel.ListMode.Cards)
        {
            var recipes = await _recipeManager.GetRecipes(new RecipesQuery()
            {
                UserId = GetUserId()
            });

            return(View("GetRecipes", new GetRecipesViewModel()
            {
                StatusMessage = statusMessage,
                Recipes = recipes,
                ViewMode = mode
            }));
        }
Esempio n. 11
0
        public async Task DispatchTrigger(ITrigger trigger)
        {
            var recipes = await _recipeManager.GetRecipes(new RecipesQuery()
            {
                Enabled         = true,
                RecipeTriggerId = trigger.Id
            });


            var triggeredRecipes = new List <(Recipe Recipe, object TriggerData, ITriggerHandler triggerHandler)>();

            foreach (var recipe in recipes)
            {
                foreach (var triggerHandler in _handlers)
                {
                    try
                    {
                        if (await triggerHandler.IsTriggered(trigger, recipe.RecipeTrigger))
                        {
                            triggeredRecipes.Add((recipe, await triggerHandler.GetData(trigger), triggerHandler));
                        }
                    }
                    catch
                    {
                    }
                }
            }

            await Task.WhenAll(triggeredRecipes.SelectMany(recipe =>
                                                           recipe.Recipe.RecipeActions.Select(action => _actionDispatcher.Dispatch(recipe.TriggerData, action))));

            foreach (var keyValuePair in triggeredRecipes.GroupBy(tuple => tuple.triggerHandler)
                     .ToDictionary(tuples => tuples.Key, tuples => tuples.ToArray()))
            {
                await keyValuePair.Key.AfterExecution(keyValuePair.Value.Select(tuple => tuple.Recipe));
            }
        }
Esempio n. 12
0
        private async Task MonitorClientForTriggers(ExplorerClient explorerClient, CancellationToken cancellationToken)
        {
            await explorerClient.WaitServerStartedAsync(cancellationToken);

            WebsocketNotificationSession notificationSession = null;

            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    var summary = _nbXplorerSummaryProvider.GetSummary(explorerClient.CryptoCode);
                    if (summary?.State != NBXplorerState.Ready)
                    {
                        await Task.Delay(TimeSpan.FromSeconds(10), cancellationToken);

                        continue;
                    }

                    notificationSession =
                        await explorerClient.CreateWebsocketNotificationSessionAsync(cancellationToken);

                    await notificationSession.ListenNewBlockAsync(cancellationToken);

                    await notificationSession.ListenAllTrackedSourceAsync(false, cancellationToken);

                    while (!cancellationToken.IsCancellationRequested)
                    {
                        var evt = await notificationSession.NextEventAsync(cancellationToken);

                        var factory =
                            _derivationStrategyFactoryProvider.GetDerivationStrategyFactory(
                                evt.CryptoCode);

                        switch (evt)
                        {
                        case NewBlockEvent newBlockEvent:
                            await _triggerDispatcher.DispatchTrigger(new NBXplorerNewBlockTrigger()
                            {
                                Data = new NBXplorerNewBlockTriggerData()
                                {
                                    CryptoCode = evt.CryptoCode,
                                    Event      = newBlockEvent
                                }
                            });

                            //we need to trigger transaction events for previous unconfirmed txs  so that they are checked again and trigger respective actions
                            var recipes = await _recipeManager.GetRecipes(new RecipesQuery()
                            {
                                Enabled   = true,
                                TriggerId = NBXplorerNewTransactionTrigger.Id
                            });

                            foreach (var recipe in recipes)
                            {
                                var triggerParameters =
                                    recipe.RecipeTrigger.Get <NBXplorerNewTransactionTriggerParameters>();
                                if (triggerParameters.Transactions == null || !triggerParameters.Transactions.Any())
                                {
                                    continue;
                                }

                                var tasks = triggerParameters.Transactions.Select(result =>
                                                                                  (result,
                                                                                   explorerClient.GetTransactionAsync(result.TransactionHash,
                                                                                                                      cancellationToken)));
                                await Task.WhenAll(tasks.Select(tuple => tuple.Item2));


                                foreach (var tx in tasks)
                                {
                                    if (tx.Item1.Confirmations != tx.Item2.Result.Confirmations)
                                    {
                                        var walletService = new NBXplorerWalletService(
                                            recipe.RecipeTrigger.ExternalService, _nbXplorerPublicWalletProvider,
                                            _derivationSchemeParser, _derivationStrategyFactoryProvider,
                                            _nbXplorerClientProvider);



                                        await _triggerDispatcher.DispatchTrigger(
                                            new NBXplorerNewTransactionTrigger(explorerClient)
                                        {
                                            Data = new NBXplorerNewTransactionTriggerData()
                                            {
                                                CryptoCode = evt.CryptoCode,
                                                Event      = new NewTransactionEvent()
                                                {
                                                    CryptoCode      = evt.CryptoCode,
                                                    BlockId         = newBlockEvent.Hash,
                                                    TransactionData = tx.Item2.Result,
                                                    TrackedSource   = await walletService.ConstructTrackedSource()
                                                }
                                            }
                                        });
                                    }
                                }
                            }

                            break;

                        case NewTransactionEvent newTransactionEvent:
                        {
                            await _triggerDispatcher.DispatchTrigger(
                                new NBXplorerNewTransactionTrigger(explorerClient)
                                {
                                    Data = new NBXplorerNewTransactionTriggerData()
                                    {
                                        CryptoCode = evt.CryptoCode,
                                        Event      = newTransactionEvent
                                    }
                                });

                            break;
                        }

                        case UnknownEvent unknownEvent:
                            _logger.LogWarning(
                                $"Received unknown message from NBXplorer ({unknownEvent.CryptoCode}), ID: {unknownEvent.EventId}");
                            break;
                        }
                    }
                }
                catch when(cancellationToken.IsCancellationRequested)
                {
                }
Esempio n. 13
0
 public IActionResult GetRecipes()
 {
     return(Ok(_recipeManager.GetRecipes()));
 }