< Summary

Class:WinSolutions.Sveta.Server.Data.DataLoading.Loaders.ImagePackageLoader
Assembly:WinSolutions.Sveta.Server
File(s):/opt/dev/sveta_api_build/WinSolutions.Sveta.Server/Data/DataLoading/Loaders/ImagePackageLoader.cs
Covered lines:0
Uncovered lines:111
Coverable lines:111
Total lines:157
Line coverage:0% (0 of 111)
Covered branches:0
Total branches:18
Branch coverage:0% (0 of 18)

Metrics

MethodLine coverage Branch coverage
get_PhotoService()0%100%
get_BeforeAddRecordAction()0%100%
Commit(...)0%100%
GetTemplate(...)0%100%
Load(...)0%0%
Rollback(...)0%100%

File(s)

/opt/dev/sveta_api_build/WinSolutions.Sveta.Server/Data/DataLoading/Loaders/ImagePackageLoader.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.IO;
 4using System.IO.Compression;
 5using System.Linq;
 6using System.Text;
 7using WinSolutions.Sveta.Server.Data.DataModel.Contexts;
 8using WinSolutions.Sveta.Server.Data.DataModel.Entities;
 9using SkiaSharp;
 10using WinSolutions.Sveta.Server.Services.Interfaces;
 11
 12namespace WinSolutions.Sveta.Server.Data.DataLoading.Loaders
 13{
 14    public class ImagePackageLoader : IDataLoader
 15    {
 016        public IPhotoService PhotoService { get; set; }
 17
 018        public Action<BaseRecord> BeforeAddRecordAction {get;set;}
 19
 20        public void Commit(SvetaDbContext context, long uploadId)
 021        {
 022            throw new NotImplementedException();
 23        }
 24
 25        public void GetTemplate(SvetaDbContext context, Stream stream, bool csvFormat = true)
 026        {
 027            throw new NotImplementedException();
 28        }
 29
 30        public LoadingResult Load(SvetaDbContext context, Stream stream)
 031        {
 032            LoadingResult res = new LoadingResult
 033            {
 034                Errors = new List<ParsingError>()
 035            };
 36
 037            var photos = new List<Photo>();
 38
 039            int x = 0;
 040            Upload upload = new Upload();
 41            int newPrevWidth, newPrevHeight;
 042            using (var zip = new ZipArchive(stream))
 043            {
 044                foreach (var e in zip.Entries)
 045                {
 046                    if (string.IsNullOrEmpty(e.Name)) continue;
 47
 048                    x ++;
 049                    var photo = new Photo
 050                    {
 051                        FullSizeUrl = e.Name,
 052                        PreviewUrl = e.Name
 053                    };
 54
 55                    try
 056                    {
 057                        BeforeAddRecordAction?.Invoke(photo);
 58
 059                        e.ExtractToFile(photo.FullSizePath, true);
 60
 061                        using (var streamImg = File.OpenRead(photo.FullSizePath))
 062                        using (var inputStream = new SKManagedStream(streamImg))
 063                        using (var original = SKBitmap.Decode(inputStream))
 064                        {
 065                            if (original.Width > original.Height)  //сохраняем пропорции
 066                            {
 067                                newPrevWidth = photo.PreviewWidth;
 068                                newPrevHeight = original.Height * photo.PreviewWidth / original.Width;
 069                            }
 70                            else
 071                            {
 072                                newPrevWidth = original.Width * photo.PreviewHeight / original.Height;
 073                                newPrevHeight = photo.PreviewHeight;
 074                            }
 075                            using (var resized = original.Resize(new SKImageInfo(newPrevWidth, newPrevHeight), SKFilterQ
 076                            using (var image = SKImage.FromBitmap(resized))
 077                            using (var output = File.OpenWrite(photo.PreviewPath))
 078                                image.Encode(SKEncodedImageFormat.Jpeg, 75).SaveTo(output);
 79
 080                            photo.FullSizeHeight = original.Height;
 081                            photo.FullSizeWidth = original.Width;
 082                            photo.PreviewHeight = newPrevHeight;
 083                            photo.PreviewWidth = newPrevWidth;
 084                        }
 85
 086                        photos.Add(photo);
 087                        res.AffectedCount ++;
 088                    }
 089                    catch(Exception ex)
 090                    {
 091                        (res.Errors as  List<ParsingError>).Add(new ParsingError
 092                        {
 093                            LineNumber = x,
 094                            Line = new List<string> { e.Name },
 095                            Exception = new Exception($"'{e.Name}' -> '{photo.FullSizePath}' | {ex.Message}")
 096                        });
 097                    }
 098                }
 099            }
 100
 0101            var dbPhotos = PhotoService.FindPhotos(photos.Select(x => x.FullSizeUrl.TrimStart('/').ToLower()).ToList());
 0102            dbPhotos.AddRange(PhotoService.FindPhotos(photos.Select(x => x.FullSizeUrl.ToLower()).ToList()));
 0103            photos.ForEach(x =>
 0104            {
 0105                var dbPhts = dbPhotos.Where(p => p.FullSizeUrl.TrimStart('/').ToLower() == x.FullSizeUrl.TrimStart('/').
 0106                if (dbPhts.Any())
 0107                {
 0108                    dbPhts.ForEach(p =>
 0109                    {
 0110                        p.FullSizeHeight = x.FullSizeHeight;
 0111                        p.FullSizeWidth = x.FullSizeWidth;
 0112                        p.PreviewUrl = x.PreviewUrl;
 0113                        p.PreviewHeight = x.PreviewHeight;
 0114                        p.PreviewWidth = x.PreviewWidth;
 0115                    });
 0116                }
 0117                else
 0118                {
 0119                    (res.Errors as List<ParsingError>).Add(new ParsingError
 0120                    {
 0121                        LineNumber = -1,
 0122                        Line = new List<string> { x.FullSizeUrl.TrimStart('/') },
 0123                        Exception = new Exception($"Фотография не найдена в БД")
 0124                    });
 0125                }
 0126            });
 127
 0128            if(res.Errors.Any())
 0129            {
 0130                (res.Errors as List<ParsingError>).Insert(0, new ParsingError
 0131                {
 0132                    LineNumber = -1,
 0133                    Line = new List<string> { "Файл" },
 0134                    Exception = new Exception("Ошибка")
 0135                });
 0136                upload.Status = res.AffectedCount > 0 ? UploadStatus.PartlyLoaded : UploadStatus.Error;
 0137            }
 138            else
 0139            {
 0140                upload.Status = UploadStatus.FullLoaded;
 0141            }
 0142            upload.ResultFile = res.GetResultFile();
 143
 0144            context.Uploads.Add(upload);
 0145            context.SaveChanges();
 146
 0147            res.UploadId = upload.Id;
 148
 0149            return res;
 0150        }
 151
 152        public void Rollback(SvetaDbContext context, long uploadId)
 0153        {
 0154            throw new NotImplementedException();
 155        }
 156    }
 157}