< Summary

Class:SVETA.Api.Services.Implements.DownloadGoodsImagesTaskProcessor
Assembly:SVETA.Api
File(s):/opt/dev/sveta_api_build/SVETA.Api/Services/Implements/DownloadGoodsImagesTaskProcessor.cs
Covered lines:0
Uncovered lines:112
Coverable lines:112
Total lines:157
Line coverage:0% (0 of 112)
Covered branches:0
Total branches:41
Branch coverage:0% (0 of 41)

Metrics

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

File(s)

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

#LineLine coverage
 1using Microsoft.Extensions.DependencyInjection;
 2using Microsoft.Extensions.Hosting;
 3using Microsoft.Extensions.Logging;
 4using SVETA.Api.Services.Interfaces;
 5using System;
 6using System.IO;
 7using System.IO.Compression;
 8using System.Collections.Generic;
 9using System.Linq;
 10using System.Threading;
 11using System.Threading.Tasks;
 12using WinSolutions.Sveta.Common;
 13using WinSolutions.Sveta.Server.Services.Interfaces;
 14using WinSolutions.Sveta.Server.Data.DataModel.Entities;
 15
 16namespace SVETA.Api.Services.Implements
 17{
 18    public class DownloadGoodsImagesTaskProcessor : BackgroundService
 19    {
 20        private readonly IServiceProvider _service;
 21        private readonly ILogger<DownloadGoodsImagesTaskProcessor> _logger;
 22
 023        public DownloadGoodsImagesTaskProcessor(IServiceProvider service, ILogger<DownloadGoodsImagesTaskProcessor> logg
 024        {
 025            _service = service;
 026            _logger = logger;
 027        }
 28
 29        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
 030        {
 31            try
 032            {
 033                _logger.LogError($"DownloadGoodsImagesTaskProcessor is starting.");
 34
 035                stoppingToken.Register(() =>
 036                    _logger.LogError($"DownloadGoodsImagesTaskProcessor background task is stopping."));
 37
 038                while (!stoppingToken.IsCancellationRequested)
 039                {
 040                    _logger.LogError($"DownloadGoodsImagesTaskProcessor task doing background work.");
 041                    await DoWork();
 42                    // Запускаем раз в минуту
 043                    await Task.Delay(60_000, stoppingToken);
 044                }
 45
 046                _logger.LogError($"DownloadGoodsImagesTaskProcessor background task is stopping.");
 047            }
 048            catch(Exception ex)
 049            {
 050                _logger.LogError(ex, "DownloadGoodsImagesTaskProcessor error");
 051            }
 052        }
 53
 54        public override async Task StopAsync(CancellationToken stoppingToken)
 055        {
 056            _logger.LogError("DownloadGoodsImagesTaskProcessor Service Hosted Service is stopping.");
 057            await Task.CompletedTask;
 058        }
 59
 60        private async Task DoWork()
 061        {
 062            using (var scope = _service.CreateScope())
 063            {
 064                var srv = scope.ServiceProvider.GetRequiredService<IDownloadGoodsImagesTaskService>();
 065                var _storage = scope.ServiceProvider.GetRequiredService<IDiskStorageService>();
 066                var _goods = scope.ServiceProvider.GetRequiredService<IGoodService>();
 67
 68
 069                var nextPending = await srv.FindNextPending();
 070                if(nextPending == null)
 071                {
 072                    return;
 73                }
 74
 075                nextPending.InProgress = true;
 076                await srv.Update(nextPending);
 77                try
 078                {
 079                    var files2zip = new List<string>();
 080                    string fileName = null;
 081                    var goods = await _goods.GetGoods(0, int.MaxValue, null, null, (long?)null, nextPending.ActiveGoodsO
 82
 083                    var rows = new List<string[]>();
 084                    rows.Add(new string[] { "Товар", /*"Артикул",*/ "Уникальный код", "Картинка" });
 085                    goods.ForEach(x =>
 086                    {
 087                        bool added = false;
 088
 089                        if(x.Photos != null && x.Photos.Any())
 090                        {
 091                            x.Photos.ForEach(p =>
 092                            {
 093                                if (!string.IsNullOrEmpty(p.FullSizeUrl))
 094                                {
 095                                    rows.Add(new string[] { x.Name, /*x.VendorCode,*/ x.UniqueCode, p.FullSizeUrl.Trim('
 096                                    added = true;
 097
 098                                    fileName = _storage.GetFullPictureFileName(p.FullSizeUrl);
 099                                    if (File.Exists(fileName))
 0100                                    {
 0101                                        files2zip.Add(fileName);
 0102                                    }
 0103                                }
 0104
 0105                                if (!string.IsNullOrEmpty(p.PreviewUrl) && p.PreviewUrl != p.FullSizeUrl)
 0106                                {
 0107                                    rows.Add(new string[] { x.Name, /*x.VendorCode,*/ x.UniqueCode, p.PreviewUrl.Trim('/
 0108                                    added = true;
 0109
 0110                                    fileName = _storage.GetFullPictureFileName(p.PreviewUrl);
 0111                                    if (File.Exists(fileName))
 0112                                    {
 0113                                        files2zip.Add(fileName);
 0114                                    }
 0115                                }
 0116                            });
 0117                        }
 0118
 0119                        if (!added)
 0120                        {
 0121                            rows.Add(new string[] { x.Name, /*x.VendorCode,*/ x.UniqueCode, "" });
 0122                        }
 0123                    });
 0124                    var result = CsvUtil.ToCsv(rows);
 0125                    _storage.SaveDownload("GoodsImages.csv", result, out fileName);
 0126                    files2zip.Add(fileName);
 127
 128                    // собственно упаковка
 0129                    var zipFileName = _storage.GenerateUniqueFileName("GoodsImages.zip");
 0130                    var zipFilePath = _storage.GetDownloadPath(zipFileName);
 0131                    using (ZipArchive archive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create))
 0132                    {
 0133                        files2zip.ForEach(x =>
 0134                        {
 0135                            archive.CreateEntryFromFile(x, Path.GetFileName(x));
 0136                        });
 0137                    }
 138
 0139                    nextPending.DownloadUrl = _storage.GetDownloadUrl(zipFileName);
 0140                }
 0141                catch(Exception ex)
 0142                {
 0143                    nextPending.Error = ex.Message;
 0144                    nextPending.StackTrace = ex.StackTrace;
 0145                    nextPending.InnerError = ex.InnerException?.Message;
 0146                    nextPending.InnerStackTrace = ex.InnerException?.StackTrace;
 0147                }
 148                finally
 0149                {
 0150                    nextPending.InProgress = false;
 0151                    nextPending.FinishedDate = DateTime.UtcNow;
 0152                    await srv.Update(nextPending);
 0153                }
 0154            }
 0155        }
 156    }
 157}