< Summary

Class:SVETA.Api.Services.Implements.FeedGenerateJob
Assembly:SVETA.Api
File(s):/opt/dev/sveta_api_build/SVETA.Api/Services/Implements/FeedGenerateJob.cs
Covered lines:0
Uncovered lines:60
Coverable lines:60
Total lines:109
Line coverage:0% (0 of 60)
Covered branches:0
Total branches:14
Branch coverage:0% (0 of 14)

Metrics

MethodLine coverage Branch coverage
.ctor(...)0%100%
DoWork()0%0%
ExecuteAsync()0%0%
StopAsync()0%100%

File(s)

/opt/dev/sveta_api_build/SVETA.Api/Services/Implements/FeedGenerateJob.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Threading;
 5using System.Threading.Tasks;
 6using Microsoft.EntityFrameworkCore.Internal;
 7using Microsoft.Extensions.DependencyInjection;
 8using Microsoft.Extensions.Hosting;
 9using Microsoft.Extensions.Logging;
 10using SVETA.Api.Helpers;
 11using SVETA.Api.Data.Domain;
 12using SVETA.Api.Services.Interfaces;
 13using WinSolutions.Sveta.Common;
 14using WinSolutions.Sveta.Server.Data.DataModel.Entities;
 15using WinSolutions.Sveta.Server.Data.DataModel.Kinds;
 16using WinSolutions.Sveta.Server.Services.Interfaces;
 17using Microsoft.Extensions.Configuration;
 18using WinSolutions.Sveta.Server.Services.Implements;
 19using Microsoft.Extensions.Options;
 20
 21
 22namespace SVETA.Api.Services.Implements
 23{
 24    public class FeedGenerateJob : BackgroundService
 25    {
 26        private readonly IServiceProvider _service;
 27        private readonly ILogger<FeedGenerateJob> _logger;
 28        private readonly UploadDownloadSettings _upSettings;
 29        private readonly ConfigurationsSettings _confsSettings;
 30
 031        public FeedGenerateJob(IServiceProvider service, ILogger<FeedGenerateJob> logger, IConfiguration configuration, 
 032        {
 033            _service = service;
 034            _logger = logger;
 035            _upSettings = upSettings.Value;
 036            _confsSettings = confsSettings.Value;
 037        }
 38
 39        /// <summary>
 40        /// Джоб для автоматической генерации фидов
 41        /// </summary>
 42        /// <returns></returns>
 43        private async Task DoWork()
 044        {
 045            using (var scope = _service.CreateScope())
 046            {
 047                var authUserService = scope.ServiceProvider.GetRequiredService<IAuthenticationService>();
 048                authUserService.SwitchToServiceUser();
 049                var feedWorker = scope.ServiceProvider.GetRequiredService<IFeedsWorker>();
 050                var jobLogger = scope.ServiceProvider.GetRequiredService<IJobService>();
 51
 52                try
 053                {
 054                    await jobLogger.Create(new JobLogger
 055                    {
 056                        JobName = nameof(FeedGenerateJob),
 057                        LogLevel = JobLogLevel.info,
 058                        Log = $"Старт работы джоба"
 059                    });
 60                    DateTime dt;
 061                    if (!DateTime.TryParse(_confsSettings.GetConfValue("FeedsSettings", "GoogleTimestamp"), out dt))
 062                    {
 063                        _logger.LogError($"Не удалось разобрать значение ключа GoogleTimestamp в секции FeedsSettings");
 064                        await jobLogger.Create(new JobLogger
 065                        {
 066                            JobName = nameof(FeedGenerateJob),
 067                            LogLevel = JobLogLevel.error,
 068                            Log = $"Не удалось разобрать значение ключа GoogleTimestamp в секции FeedsSettings"
 069                        });
 070                        return;
 71                    }
 72
 073                    if (dt.Date != DateTime.UtcNow.Date)
 074                    {
 075                        string filename = "GoogleFeed_auto.txt";
 076                        await feedWorker.CreateFeedForGoogle(filename);
 077                        _confsSettings.SetConfValue("FeedsSettings", "GoogleTimestamp", DateTime.UtcNow.Date.ToString())
 078                    }
 079                }
 080                catch (Exception ex)
 081                {
 082                    _logger.LogError($"Ошибка выполнения джоба {nameof(FeedGenerateJob)}. {ex.Message}");
 083                    return;
 84                }
 085            }
 086        }
 87
 88        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
 089        {
 090            _logger.LogDebug($"FeedGenerateJob is starting.");
 91
 092            stoppingToken.Register(() =>
 093                _logger.LogDebug($"FeedGenerateJob background task is stopping."));
 94
 095            while (!stoppingToken.IsCancellationRequested)
 096            {
 097                _logger.LogDebug($"FeedGenerateJob task doing background work.");
 098                await DoWork();
 099                await Task.Delay(TimeSpan.FromHours(1), stoppingToken);
 0100            }
 0101        }
 102        public override async Task StopAsync(CancellationToken stoppingToken)
 0103        {
 0104            _logger.LogInformation(
 0105                "FeedGenerateJob service is stopping.");
 0106            await Task.CompletedTask;
 0107        }
 108    }
 109}