public async Task <IActionResult> Create(BookViewModel viewModel, int[] categories, int[] authors)
        {
            if (!ModelState.IsValid)
            {
                viewModel.Categories   = _db.Categories;
                viewModel.Authors      = _db.Authors;
                viewModel.CategoriesId = categories;
                viewModel.AuthorsId    = authors;
                return(View(viewModel));
            }

            if (categories.Length == 0 || authors.Length == 0)
            {
                ModelState.AddModelError("", "Minimum one category and author are required.");
                viewModel.Categories   = _db.Categories;
                viewModel.Authors      = _db.Authors;
                viewModel.CategoriesId = categories;
                viewModel.AuthorsId    = authors;
                return(View(viewModel));
            }

            if (viewModel.Book.Photos.Count > 5)
            {
                ModelState.AddModelError("", "Maximum 5 images can be added.");
                viewModel.Categories   = _db.Categories;
                viewModel.Authors      = _db.Authors;
                viewModel.CategoriesId = categories;
                viewModel.AuthorsId    = authors;
                return(View(viewModel));
            }

            foreach (var file in viewModel.Book.Photos)
            {
                if (!file.IsPhoto())
                {
                    ModelState.AddModelError("", "Files must be images.");
                    viewModel.Categories   = _db.Categories;
                    viewModel.Authors      = _db.Authors;
                    viewModel.CategoriesId = categories;
                    viewModel.AuthorsId    = authors;
                    return(View(viewModel));
                }
            }

            viewModel.Book.CreatedAt  = DateTime.Now;
            viewModel.Book.ModifiedAt = DateTime.Now;

            await _db.Books.AddAsync(viewModel.Book);

            await _db.SaveChangesAsync();

            foreach (var img in viewModel.Book.Photos)
            {
                var image = new Image
                {
                    BookId   = viewModel.Book.Id,
                    ImageUrl = await img.SavePhotoAsync(_env.WebRootPath, "books")
                };

                await _db.Images.AddAsync(image);

                await _db.SaveChangesAsync();
            }

            foreach (var catId in categories)
            {
                var bookCategory = new BookCategoryPivot
                {
                    CategoryId = catId,
                    BookId     = viewModel.Book.Id
                };
                await _db.BookCategories.AddAsync(bookCategory);

                await _db.SaveChangesAsync();
            }

            foreach (var authorId in authors)
            {
                var bookAuhtor = new BookAuthorPivot
                {
                    AuthorId = authorId,
                    BookId   = viewModel.Book.Id
                };
                await _db.BookAuthors.AddAsync(bookAuhtor);

                await _db.SaveChangesAsync();
            }

            return(RedirectToAction(nameof(Index)));
        }
        public async Task <IActionResult> Books()
        {
            var service = new BooksService(new BaseClientService.Initializer
            {
                ApiKey = _config["Data:APIKeys:GoogleBookAPI"]
            });

            for (int i = 0; i < 100; i++)
            {
                var volumes = await service.Volumes.List(i.ToString()).ExecuteAsync();

                var items = volumes?.Items;

                if (items != null)
                {
                    foreach (var item in items)
                    {
                        var categories = item?.VolumeInfo?.Categories;
                        var authors    = item?.VolumeInfo?.Authors;
                        var volume     = item?.VolumeInfo;

                        if (categories != null && authors != null && volume != null)
                        {
                            foreach (var author1 in volume.Authors)
                            {
                                if (!_db.Authors.Any(c => c.Fullname == author1))
                                {
                                    await _db.Authors.AddAsync(new Author
                                    {
                                        Fullname   = author1,
                                        CreatedAt  = DateTime.Now,
                                        ModifiedAt = DateTime.Now
                                    });

                                    await _db.SaveChangesAsync();
                                }
                            }

                            foreach (var category1 in volume.Categories)
                            {
                                if (!_db.Categories.Any(c => c.Name == category1))
                                {
                                    await _db.Categories.AddAsync(new Category
                                    {
                                        Name       = category1,
                                        CreatedAt  = DateTime.Now,
                                        ModifiedAt = DateTime.Now
                                    });

                                    await _db.SaveChangesAsync();
                                }
                            }

                            var publishdate = DateTime.Now;

                            try
                            {
                                publishdate = Convert.ToDateTime(volume.PublishedDate);
                            }
                            catch (Exception ex)
                            {
                                publishdate = DateTime.Now;
                            }

                            //var images = new Image
                            //{
                            //    ExtraLarge = volume.ImageLinks.ExtraLarge,
                            //    Large = volume.ImageLinks.Large,
                            //    Meddium = volume.ImageLinks.Medium,
                            //    SmallThumbnail = volume.ImageLinks.SmallThumbnail,
                            //    Thumbnail = volume.ImageLinks.Thumbnail
                            //};

                            var book = new Book
                            {
                                Title         = volume.Title,
                                Subtitle      = volume.Subtitle,
                                CreatedAt     = DateTime.Now,
                                ModifiedAt    = DateTime.Now,
                                Description   = volume.Description,
                                GID           = item.Id,
                                Language      = volume.Language,
                                PageCount     = volume.PageCount ?? 100,
                                PublishedDate = publishdate,
                                Publisher     = volume.Publisher,
                                //Images = images
                            };
                            await _db.Books.AddAsync(book);

                            await _db.SaveChangesAsync();

                            foreach (var category2 in volume.Categories)
                            {
                                var pivot = new BookCategoryPivot
                                {
                                    BookId     = book.Id,
                                    CategoryId = _db.Categories.FirstOrDefault(c => c.Name == category2).Id
                                };
                                await _db.BookCategories.AddAsync(pivot);

                                await _db.SaveChangesAsync();
                            }

                            foreach (var author2 in volume.Authors)
                            {
                                var pivot = new BookAuthorPivot
                                {
                                    BookId   = book.Id,
                                    AuthorId = _db.Authors.FirstOrDefault(a => a.Fullname == author2).Id
                                };
                                await _db.BookAuthors.AddAsync(pivot);

                                await _db.SaveChangesAsync();
                            }
                        }
                    }
                }
            }

            return(Content("ok"));
        }
        public async Task <IActionResult> Edit(BookViewModel viewModel, int[] categories, int[] authors)
        {
            if (!ModelState.IsValid)
            {
                viewModel.Categories   = _db.Categories;
                viewModel.Authors      = _db.Authors;
                viewModel.CategoriesId = categories;
                viewModel.AuthorsId    = authors;
                return(View(viewModel));
            }

            if (categories.Length == 0 || authors.Length == 0)
            {
                ModelState.AddModelError("", "Minimum one category and author are required.");
                viewModel.Categories   = _db.Categories;
                viewModel.Authors      = _db.Authors;
                viewModel.CategoriesId = categories;
                viewModel.AuthorsId    = authors;
                return(View(viewModel));
            }

            var bookFromDb = await _db.Books.FindAsync(viewModel.Book.Id);

            if (viewModel.Book.Photos != null)
            {
                if (viewModel.Book.Photos.Count + bookFromDb.Images.Count > 5)
                {
                    ModelState.AddModelError("", "Maximum 5 images can be in one book.");
                    viewModel.Categories   = _db.Categories;
                    viewModel.Authors      = _db.Authors;
                    viewModel.CategoriesId = categories;
                    viewModel.AuthorsId    = authors;
                    viewModel.Book.Images  = bookFromDb.Images;
                    return(View(viewModel));
                }

                foreach (var file in viewModel.Book.Photos)
                {
                    if (!file.IsPhoto())
                    {
                        ModelState.AddModelError("", "Files must be images.");
                        viewModel.Categories   = _db.Categories;
                        viewModel.Authors      = _db.Authors;
                        viewModel.CategoriesId = categories;
                        viewModel.AuthorsId    = authors;
                        return(View(viewModel));
                    }
                }

                foreach (var img in viewModel.Book.Photos)
                {
                    var image = new Image
                    {
                        BookId   = viewModel.Book.Id,
                        ImageUrl = await img.SavePhotoAsync(_env.WebRootPath, "books")
                    };

                    await _db.Images.AddAsync(image);

                    await _db.SaveChangesAsync();
                }
            }


            foreach (var cat in bookFromDb.Categories.ToList().Where(c => !categories.Any(ct => ct == c.CategoryId)))
            {
                var pivot = await _db.BookCategories.FindAsync(cat.Id);

                _db.Entry(pivot).State = EntityState.Deleted;
                await _db.SaveChangesAsync();
            }

            foreach (var author in bookFromDb.Authors.ToList().Where(a => !authors.Any(au => au == a.AuthorId)))
            {
                var pivot = await _db.BookAuthors.FindAsync(author.Id);

                _db.Entry(pivot).State = EntityState.Deleted;
                await _db.SaveChangesAsync();
            }

            foreach (var catId in categories.Where(c => !bookFromDb.Categories.Any(bc => bc.CategoryId == c)))
            {
                var bookCategory = new BookCategoryPivot
                {
                    CategoryId = catId,
                    BookId     = viewModel.Book.Id
                };
                await _db.BookCategories.AddAsync(bookCategory);

                await _db.SaveChangesAsync();
            }

            foreach (var authorId in authors.Where(a => !bookFromDb.Authors.Any(ab => ab.AuthorId == a)))
            {
                var bookAuhtor = new BookAuthorPivot
                {
                    AuthorId = authorId,
                    BookId   = viewModel.Book.Id
                };
                await _db.BookAuthors.AddAsync(bookAuhtor);

                await _db.SaveChangesAsync();
            }

            viewModel.Book.CreatedAt        = bookFromDb.CreatedAt;
            viewModel.Book.ModifiedAt       = DateTime.Now;
            _db.Entry(bookFromDb).State     = EntityState.Detached;
            _db.Entry(viewModel.Book).State = EntityState.Modified;
            await _db.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
Exemple #4
0
        public async Task CheckDbBook(string q)
        {
            var service = new BooksService(new BaseClientService.Initializer
            {
                ApiKey = _config["Data:APIKeys:GoogleBookAPI"]
            });

            var volumes = await service.Volumes.List(q).ExecuteAsync();

            var items = volumes?.Items;

            if (items != null)
            {
                foreach (var item in items)
                {
                    if (_db.Books.Any(b => b.GID == item.Id))
                    {
                        return;
                    }

                    var categories = item?.VolumeInfo?.Categories;
                    var authors    = item?.VolumeInfo?.Authors;
                    var volume     = item?.VolumeInfo;

                    if (categories != null && authors != null && volume != null)
                    {
                        foreach (var author1 in volume.Authors)
                        {
                            if (!_db.Authors.Any(c => c.Fullname == author1))
                            {
                                await _db.Authors.AddAsync(new Author
                                {
                                    Fullname   = author1,
                                    CreatedAt  = DateTime.Now,
                                    ModifiedAt = DateTime.Now
                                });

                                await _db.SaveChangesAsync();
                            }
                        }

                        foreach (var category1 in volume.Categories)
                        {
                            if (!_db.Categories.Any(c => c.Name == category1))
                            {
                                await _db.Categories.AddAsync(new Category
                                {
                                    Name       = category1,
                                    CreatedAt  = DateTime.Now,
                                    ModifiedAt = DateTime.Now
                                });

                                await _db.SaveChangesAsync();
                            }
                        }

                        var publishdate = DateTime.Now;

                        try
                        {
                            publishdate = Convert.ToDateTime(volume.PublishedDate);
                        }
                        catch (Exception)
                        {
                            publishdate = DateTime.Now;
                        }

                        var book = new Book
                        {
                            Title         = volume.Title,
                            Subtitle      = volume.Subtitle,
                            CreatedAt     = DateTime.Now,
                            ModifiedAt    = DateTime.Now,
                            Description   = volume.Description,
                            GID           = item.Id,
                            Language      = volume.Language,
                            PageCount     = volume.PageCount ?? 100,
                            PublishedDate = publishdate,
                            Publisher     = volume.Publisher,
                        };
                        await _db.Books.AddAsync(book);

                        await _db.SaveChangesAsync();

                        #region Images

                        var image = new Image
                        {
                            ImageUrl = volume.ImageLinks.ExtraLarge,
                            BookId   = book.Id
                        };
                        if (!string.IsNullOrEmpty(image.ImageUrl))
                        {
                            await _db.Images.AddAsync(image);

                            await _db.SaveChangesAsync();
                        }

                        var image1 = new Image
                        {
                            ImageUrl = volume.ImageLinks.Large,
                            BookId   = book.Id
                        };
                        if (!string.IsNullOrEmpty(image1.ImageUrl))
                        {
                            await _db.Images.AddAsync(image1);

                            await _db.SaveChangesAsync();
                        }

                        var image2 = new Image
                        {
                            ImageUrl = volume.ImageLinks.Medium,
                            BookId   = book.Id
                        };
                        if (!string.IsNullOrEmpty(image2.ImageUrl))
                        {
                            await _db.Images.AddAsync(image2);

                            await _db.SaveChangesAsync();
                        }

                        var image3 = new Image
                        {
                            ImageUrl = volume.ImageLinks.Thumbnail,
                            BookId   = book.Id
                        };
                        if (!string.IsNullOrEmpty(image3.ImageUrl))
                        {
                            await _db.Images.AddAsync(image3);

                            await _db.SaveChangesAsync();
                        }

                        var image4 = new Image
                        {
                            ImageUrl = volume.ImageLinks.SmallThumbnail,
                            BookId   = book.Id
                        };
                        if (!string.IsNullOrEmpty(image4.ImageUrl))
                        {
                            await _db.Images.AddAsync(image4);

                            await _db.SaveChangesAsync();
                        }

                        #endregion

                        foreach (var category2 in volume.Categories)
                        {
                            var pivot = new BookCategoryPivot
                            {
                                BookId     = book.Id,
                                CategoryId = _db.Categories.FirstOrDefault(c => c.Name == category2).Id
                            };
                            await _db.BookCategories.AddAsync(pivot);

                            await _db.SaveChangesAsync();
                        }

                        foreach (var author2 in volume.Authors)
                        {
                            var pivot = new BookAuthorPivot
                            {
                                BookId   = book.Id,
                                AuthorId = _db.Authors.FirstOrDefault(a => a.Fullname == author2).Id
                            };
                            await _db.BookAuthors.AddAsync(pivot);

                            await _db.SaveChangesAsync();
                        }
                    }
                }
            }
        }