Ejemplo n.º 1
0
        public ActionResult Create(CreateOtherView model, List <HttpPostedFileBase> images)
        {
            if (String.IsNullOrEmpty(model.Phone) && String.IsNullOrEmpty(model.VkId) && String.IsNullOrEmpty(model.OkId))
            {
                ModelState.AddModelError("Phone", "Как с вами связаться? Укажите хотя бы один способ связи:\r\nлибо телефон");
                ModelState.AddModelError("VkId", "либо ВК");
                ModelState.AddModelError("OkId", "либо Одноклассники");
            }

            if (!String.IsNullOrEmpty(model.Phone) && model.Phone.Last() == '_')
            {
                ModelState.AddModelError("Phone", "Кажется, Вы неверно ввели телефон :(");
            }

            if (ModelState.IsValid)
            {
                //mapping
                var config = new MapperConfiguration(cfg =>
                {
                    cfg.CreateMap <CreateOtherView, Advertisement>()
                    .ForMember(dest => dest.Id, opt => opt.UseValue(Guid.NewGuid()))
                    .ForMember(dest => dest.Category, opt => opt.UseValue(Category.Other))
                    .ForMember(dest => dest.Created, opt => opt.UseValue(DateTime.Now))
                    .ForMember(dest => dest.Premoderated, opt => opt.UseValue(false))
                    .BeforeMap((s, d) =>
                    {
                        s.VkId = String.IsNullOrWhiteSpace(s.VkId) ? null : "https://vk.com/" + s.VkId;
                        d.OkId = String.IsNullOrWhiteSpace(s.OkId) ? null : "https://ok.ru/profile/" + s.OkId;
                    });
                });
                IMapper       mapper        = config.CreateMapper();
                Advertisement advertisement = mapper.Map <Advertisement>(model);

                if (images != null && images.Count > 0 && images.First() != null)
                {
                    advertisement.Images     = new List <Image>(images.Count);
                    advertisement.Thumbnails = new List <Thumbnail>(images.Count);

                    foreach (var image in images)
                    {
                        if (image == null)
                        {
                            continue;
                        }

                        MemoryStream stream = new MemoryStream();
                        image.InputStream.CopyTo(stream);
                        stream.Seek(0, SeekOrigin.Begin);

                        //create path to save images
                        var guid     = Guid.NewGuid().ToString();
                        var folder1  = guid.Substring(0, 2);
                        var folder2  = guid.Substring(2, 2);
                        var fileName = guid.Substring(4, 4) + ".jpg";

                        //create directory if not exists
                        var absolutePathImage = Server.MapPath($"{Constants.ImagesFolder + folder1}/{folder2}/");
                        if (!Directory.Exists(absolutePathImage))
                        {
                            Directory.CreateDirectory(absolutePathImage);
                        }
                        absolutePathImage = absolutePathImage + fileName;
                        var virtualPathImage = $"{folder1}/{folder2}/{fileName}";

                        var absolutePathThumbnail = Server.MapPath($"{Constants.ThumbnailsFolder + folder1}/{folder2}/");
                        if (!Directory.Exists(absolutePathThumbnail))
                        {
                            Directory.CreateDirectory(absolutePathThumbnail);
                        }
                        absolutePathThumbnail = absolutePathThumbnail + fileName;
                        var virtualPathThumbnail = $"{folder1}/{folder2}/{fileName}";

                        //convert and save image
                        ImageJob job = new ImageJob(stream, absolutePathImage, new Instructions("width=800;height=500;mode=pad;format=jpg;scale=both"));
                        job.Build();
                        Image newImage = new Image()
                        {
                            Path            = virtualPathImage,
                            AdvertisementId = advertisement.Id
                        };
                        advertisement.Images.Add(newImage);

                        //ImageJob close stream when read, so create new
                        stream = new MemoryStream();
                        image.InputStream.Seek(0, SeekOrigin.Begin);
                        image.InputStream.CopyTo(stream);
                        stream.Seek(0, SeekOrigin.Begin);

                        //convert and save thumbnail
                        job = new ImageJob(stream, absolutePathThumbnail, new Instructions("width=135;height=100;mode=crop;format=jpg;scale=both"));
                        job.Build();
                        Thumbnail newThumbnail = new Thumbnail()
                        {
                            Path            = virtualPathImage,
                            AdvertisementId = advertisement.Id
                        };
                        advertisement.Thumbnails.Add(newThumbnail);
                    }
                }

                manager.AddAdvertisement(advertisement);

                //send notification to telegram
                var         urlToCheck = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port) + Url.Action("Advertisements", "Check");
                TelegramApi api        = new TelegramApi();
                api.SendNotification("*Новое объявление*\r\n[Перейти](" + urlToCheck + ")");

                return(RedirectToAction("Success", "Home"));
            }
            else
            {
                return(View(model));
            }
        }