< Summary

Class:SVETA.Api.Services.Implements.UpdatingLinkImagesJob
Assembly:SVETA.Api
File(s):/opt/dev/sveta_api_build/SVETA.Api/Services/Implements/UpdatingLinkImagesJob.cs
Covered lines:0
Uncovered lines:101
Coverable lines:101
Total lines:145
Line coverage:0% (0 of 101)
Covered branches:0
Total branches:47
Branch coverage:0% (0 of 47)

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/UpdatingLinkImagesJob.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;
 20using System.IO;
 21
 22namespace SVETA.Api.Services.Implements
 23{
 24    public class UpdatingLinkImagesJob : BackgroundService
 25    {
 26        private readonly IServiceProvider _service;
 27        private readonly ILogger<UpdatingLinkImagesJob> _logger;
 28        private readonly ConfigurationsSettings _confsSettings;
 029        private bool needRun = true;
 30
 031        public UpdatingLinkImagesJob(IServiceProvider service, ILogger<UpdatingLinkImagesJob> logger, IOptions<Configura
 032        {
 033            _service = service;
 034            _logger = logger;
 035            _confsSettings = confsSettings.Value;
 036        }
 37
 38        private async Task DoWork()
 039        {
 040            if (DateTime.UtcNow.Hour < 3 && !needRun) //делаем так, чтобы джоб запускался 1 раз с 0 до 3
 041                return;
 042            if (DateTime.UtcNow.Hour > 3) // если время больше 3, то меняем флаг, чтобы ночью запуститься
 043            {
 044                needRun = true;
 045                return;
 46            }
 047            using (var scope = _service.CreateScope())
 048            {
 049                var authUserService = scope.ServiceProvider.GetRequiredService<IAuthenticationService>();
 050                authUserService.SwitchToServiceUser();
 051                var goodsService = scope.ServiceProvider.GetRequiredService<IGoodService>();
 052                var storageService = scope.ServiceProvider.GetRequiredService<IDiskStorageService>();
 053                var jobLogger = scope.ServiceProvider.GetRequiredService<IJobService>();
 54                try
 055                {
 056                    string fullPH = _confsSettings.GetConfValue("ImageSettings", "FullSizeUrlPlaceholder");
 057                    string prevPH = _confsSettings.GetConfValue("ImageSettings", "PreviewUrlPlaceholder");
 058                    var goods = await goodsService.GetGoods(0, int.MaxValue, null, null, (long?)null, true);
 059                    await jobLogger.Create(new JobLogger
 060                    {
 061                        JobName = nameof(UpdatingLinkImagesJob),
 062                        LogLevel = JobLogLevel.info,
 063                        Log = $"Старт работы джоба. Кол-во товаров для обработки - {goods?.Count}."
 064                    });
 65
 066                    if (!File.Exists(storageService.GetFullPictureFileName(fullPH)))
 067                    {
 068                        _logger.LogError($"Не найден плейсхолдер с названием {fullPH}");
 069                        return;
 70                    }
 071                    if (!File.Exists(storageService.GetFullPictureFileName(prevPH)))
 072                    {
 073                        _logger.LogError($"Не найден плейсхолдер с названием {prevPH}");
 074                        return;
 75                    }
 76
 077                    if (goods?.Count == 0)
 078                        return;
 079                    var needUpdate = false;
 080                    foreach (var good in goods)
 081                    {
 082                        needUpdate = false;
 083                        foreach (var photo in good.Photos)
 084                        {
 085                            string fullsize = storageService.GetFullPictureFileName(photo.FullSizeUrl);
 086                            string prevsize = storageService.GetFullPictureFileName(photo.PreviewUrl);
 087                            if (string.IsNullOrWhiteSpace(photo.FullSizeUrl) || !File.Exists(fullsize))
 088                            {
 089                                photo.FullSizeUrl = fullPH;
 090                                _logger.LogInformation($"Установлен плейсхолдер (fullsize) для товара с id={good.Id}");
 091                                needUpdate = true;
 092                            }
 093                            if (string.IsNullOrWhiteSpace(photo.PreviewUrl) || !File.Exists(prevsize))
 094                            {
 095                                photo.PreviewUrl = prevPH;
 096                                _logger.LogInformation($"Установлен плейсхолдер (preview) для товара с id={good.Id}");
 097                                needUpdate = true;
 098                            }
 099                        }
 0100                        if (needUpdate)
 0101                            await goodsService.UpdateGood(good);
 0102                    }
 0103                    await jobLogger.Create(new JobLogger
 0104                    {
 0105                        JobName = nameof(UpdatingLinkImagesJob),
 0106                        LogLevel = JobLogLevel.info,
 0107                        Log = $"Окончание работы джоба."
 0108                    });
 0109                    needRun = false;
 0110                }
 0111                catch (Exception ex)
 0112                {
 0113                    _logger.LogError($"Ошибка работы джоба {nameof(UpdatingLinkImagesJob)}. {ex.Message}");
 0114                    await jobLogger.Create(new JobLogger
 0115                    {
 0116                        JobName = nameof(UpdatingLinkImagesJob),
 0117                        LogLevel = JobLogLevel.error,
 0118                        Log = $"Ошибка работы джоба. {ex.Message}"
 0119                    });
 0120                }
 0121            }
 0122        }
 123
 124        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
 0125        {
 0126            _logger.LogDebug($"UpdatingLinkImagesJob is starting.");
 127
 0128            stoppingToken.Register(() =>
 0129                _logger.LogDebug($"UpdatingLinkImagesJob  background task is stopping."));
 130
 0131            while (!stoppingToken.IsCancellationRequested)
 0132            {
 0133                _logger.LogDebug($"UpdatingLinkImagesJob task doing background work.");
 0134                await DoWork();
 0135                await Task.Delay(TimeSpan.FromMinutes(30), stoppingToken);
 0136            }
 0137        }
 138        public override async Task StopAsync(CancellationToken stoppingToken)
 0139        {
 0140            _logger.LogInformation(
 0141                "UpdatingLinkImagesJob service is stopping.");
 0142            await Task.CompletedTask;
 0143        }
 144    }
 145}