Пример #1
0
        public BookViewModel(Book book, EbooksContext db)
        {
            BookId = book.BookId;
            Title = book.Title;
            Author = book.Author?.AuthorId;
            Authors = new SelectList(new Author[] { new Author() }.Concat(db.Authors.Where(a => a.Books.Any(b => b.UserId == book.UserId))).ToArray(), "AuthorId", "Name", Author);
            Publisher = book.Publisher?.PublisherId;
            Publishers = new SelectList(new Publisher[] { new Publisher() }.Concat(db.Publishers.Where(p => p.Books.Any(b => b.UserId == book.UserId))).ToArray(), "PublisherId", "Name", Publisher);
            Description = book.Description;
            SelectedTags = book.Tags.Select(t => t.Item).ToArray();

            // Because of the bug in ListBoxFor both the tag objects and a tag list are required to
            // populate the tagger control.
            Tags = book.Tags.ToList();
            TagList = new MultiSelectList(db.Tags.Where(t => t.Books.Any(b => b.UserId == book.UserId)).ToArray(), "Item", "Item", SelectedTags);

            // The JSON data required by the tagger control.
            var tagsInfo = new JObject();
            foreach (var tag in db.Tags) {
                var item = new JObject();
                item["id"] = tag.Item;
                item["selected"] = book.Tags.Contains(tag);
                item["suggestable"] = true;
                item["suggestion"] = tag.Item;
                item["key"] = tag.Item;
                tagsInfo.Add(tag.Item, item);
            }
            TagsInfo = tagsInfo.ToString();

            Idents = db.Idents.Where(i => i.BookIdents.Any(bi => bi.Book.UserId == book.UserId)).Select(i => i.Name).ToArray();
            BookIdents = book.BookIdents.ToDictionary(bi => bi.Ident.Name, bi => bi.Identifier);
        }
 public void Run() {
     var docs = getRdfFiles()
         .Where(f => f.Id.NotIn(0, 999999) && f.Title != null)
         // Don't include any that have no epubs (eg sound files)
         .Where(f => f.EpubUrlImages != null || f.EpubUrlNoImages != null);
     using (var db = new EbooksContext()) {
         int count = 0;
         var newBooks = new List<GutBook>();
         var newAuthors = new List<GutAuthor>();
         var newLangNames = new List<LanguageName>();
         var newLangCodes = new List<LanguageCode>();
         foreach (var doc in docs) {
             loadBookData(db, doc, newBooks, newAuthors, newLangNames, newLangCodes);
             if (++count >= 1000) {
                 db.LanguageNames.AddRange(newLangNames);
                 newLangNames.Clear();
                 db.LanguageCodes.AddRange(newLangCodes);
                 newLangCodes.Clear();
                 db.GutAuthors.AddRange(newAuthors);
                 newAuthors.Clear();
                 db.GutBooks.AddRange(newBooks);
                 newBooks.Clear();
                 db.SaveChanges();
                 count = 0;
             }
         }
         db.LanguageNames.AddRange(newLangNames);
         db.LanguageCodes.AddRange(newLangCodes);
         db.GutAuthors.AddRange(newAuthors);
         db.GutBooks.AddRange(newBooks);
         db.SaveChanges();
     }
 }
Пример #3
0
 // GET: Admin
 public ActionResult Index()
 {
     using (var db = new EbooksContext()) {
         if (!db.GetEbooksUser(User).IsAdmin) return RedirectToAction("Index", "Ebooks");
     }
     return View(new AdminViewModel());
 }
Пример #4
0
 // GET: Image
 public ActionResult ShowThumbnail(int bookId)
 {
     using (var db = new EbooksContext()) {
         var thumbnail = db.Books.Single(b => b.BookId == bookId).Cover?.Thumbnail ?? Cover.EmptyThumbnail;
         return new FileStreamResult(new MemoryStream(thumbnail), "image/jpeg");
     }
 }
Пример #5
0
 public ActionResult ShowGutCover(int bookId)
 {
     using (var db = new EbooksContext()) {
         var cover = db.GutBooks.Single(b => b.GutBookId == bookId).GetCoverData() ?? Cover.EmptyCover;
         return new FileStreamResult(new MemoryStream(cover), "image/jpeg");
     }
 }
Пример #6
0
 public ActionResult Download(int gutBookId, bool images)
 {
     using (var db = new EbooksContext()) {
         var gutBook = db.GutBooks.Single(b => b.GutBookId == gutBookId);
         // Check whether the book has already been downloaded
         var ef = db.EpubFiles.SingleOrDefault(e => e.GutBookId == gutBook.GutBookId && e.GutBookWithImages == images);
         Epub ep;
         if (ef != null) {
             ep = new Epub(ef.Contents);
         } else {
             ep = new Epub(images ? gutBook.GetEpubImages() : gutBook.GetEpubNoImages());
         }
         try {
             var user = db.GetEbooksUser(User);
             var book = Book.Load(db, ep, user.UserId);
             if (book.Publisher == null) book.Publisher = Publisher.Get(db, "Project Gutenberg");
             if (ef == null) {
                 book.EpubFile.GutBookId = gutBook.GutBookId;
                 book.EpubFile.GutBookWithImages = images;
             }
             db.SaveChanges();
         } finally {
             ep.Dispose();
         }
     }
     return RedirectToAction("Index", "Ebooks");
 }
Пример #7
0
 public ActionResult Cover(int bookId)
 {
     using (var db = new EbooksContext()) {
         var book = db.GutBooks.Single(b => b.GutBookId == bookId);
         return View(new CoverViewModel { BookId = bookId, Title = book.Title });
     }
 }
Пример #8
0
 public ActionResult ShowGutThumbnail(int bookId)
 {
     using (var db = new EbooksContext()) {
         var thumbnail = db.GutBooks.Single(b => b.GutBookId == bookId).GetThumbnailData() ?? Cover.EmptyThumbnail;
         db.SaveChanges();   // May have read and cached the thumbnail data
         return new FileStreamResult(new MemoryStream(thumbnail), "image/jpeg");
     }
 }
Пример #9
0
 public static Author Get(EbooksContext db, string name)
 {
     if (string.IsNullOrWhiteSpace(name)) return null;
     var author = db.Authors.SingleOrDefault(a => a.Name == name);
     if (author == null) {
         db.Authors.Add(author = new Author { Name = name });
     }
     return author;
 }
Пример #10
0
 public ActionResult DisplayDetails(int gutBookId)
 {
     using (var db = new EbooksContext()) {
         var book = db.GutBooks.Single(b => b.GutBookId == gutBookId);
         var lang = book.Language != null && book.Language.Length == 2 ? book.Language : null;
         var gbooks = GoogleBook.GetBooks(title: $"\"{book.Title}\"", author: book.GutAuthor.Name, language: lang);
         return View("Details", new GutGoogleViewModel(book, gbooks));
     }
 }
Пример #11
0
 public static Publisher Get(EbooksContext db, string name)
 {
     if (string.IsNullOrWhiteSpace(name)) return null;
     var pub = db.Publishers.SingleOrDefault(p => p.Name == name);
     if (pub == null) {
         db.Publishers.Add(pub = new Publisher { Name = name });
     }
     return pub;
 }
Пример #12
0
 public ActionResult ShowCover(int bookId)
 {
     using (var db = new EbooksContext()) {
         var cover = db.Books.Single(b => b.BookId == bookId).Cover;
         var pic = cover?.Picture ?? Cover.EmptyCover;
         var type = cover?.ContentType ?? "image/jpeg";
         return new FileStreamResult(new MemoryStream(pic), type);
     }
 }
Пример #13
0
 public ActionResult Download(int bookId)
 {
     using (var db = new EbooksContext()) {
         var user = db.GetEbooksUser(User);
         var book = db.Books.SingleOrDefault(b => b.BookId == bookId && b.UserId == user.UserId);
         if (book == null) return RedirectToAction("Index");
         return File(book.EpubFile.Contents, System.Net.Mime.MediaTypeNames.Application.Octet, book.Title + ".epub");
     }
 }
Пример #14
0
 public static Series Get(EbooksContext db, Epub ep)
 {
     if (string.IsNullOrWhiteSpace(ep.Series)) return null;
     var series = db.Series.SingleOrDefault(s => s.Name == ep.Series);
     if (series == null) {
         db.Series.Add(series = new Series { Name = ep.Series });
     }
     return series;
 }
Пример #15
0
 public ActionResult Cover(int bookId)
 {
     using (var db = new EbooksContext()) {
         var user = db.GetEbooksUser(User);
         var book = db.Books.SingleOrDefault(b => b.BookId == bookId && b.UserId == user.UserId);
         if (book == null) return RedirectToAction("Index");
         var model = new CoverViewModel { BookId = book.BookId, Title = book.Title };
         return View(model);
     }
 }
Пример #16
0
        public ActionResult ImportGutCatalogue()
        {
            using (var db = new EbooksContext()) {
                if (!db.GetEbooksUser(User).IsAdmin) return RedirectToAction("Index", "Ebooks");
            }

            TaskManager.AddTask<GutenbergLoadTask>(schedule => schedule.ToRunNow());
            // Wait a second for it to start
            Thread.Sleep(1000);
            return RedirectToAction("Index");
        }
Пример #17
0
 public ActionResult Delete(int bookId)
 {
     using (var db = new EbooksContext()) {
         var user = db.GetEbooksUser(User);
         var book = db.Books.SingleOrDefault(b => b.BookId == bookId && b.UserId == user.UserId);
         if (book != null) {
             db.Books.Remove(book);
             db.SaveChanges();
         }
     }
     return RedirectToAction("Index");
 }
Пример #18
0
 public ActionResult ReadContent()
 {
     int bookId = Convert.ToInt32(Request.Url.Segments[3].TrimEnd('/'));
     string file = HttpUtility.UrlDecode(string.Join("", Request.Url.Segments.Skip(4)));
     using (var db = new EbooksContext()) {
         var userId = db.GetEbooksUser(User).UserId;
         var book = db.Books.Single(b => b.BookId == bookId && b.UserId == userId);
         if (book == null) return null;
         using (var ep = new Epub(book)) {
             return new FileStreamResult(ep.GetContentFile(file), "text/html");
         }
     }
 }
Пример #19
0
 public ActionResult Edit(int? bookId)
 {
     if (bookId == null) return RedirectToAction("Index");
     using (var db = new EbooksContext()) {
         var user = db.GetEbooksUser(User);
         var book = db.Books.SingleOrDefault(b => b.BookId == bookId && b.UserId == user.UserId);
         if (book == null) return Redirect(Request.UrlReferrer.ToString());
         var model = new BookViewModel(book, db);
         // ListBoxFor is broken, see https://social.msdn.microsoft.com/Forums/vstudio/en-US/05ee3b35-f3d3-48b4-83f5-ca3d9073624e/mvc-htmlhelper-listboxfor-and-listbox-multiselectlist-bug?forum=netfxbcl
         ViewBag.Tags = model.TagList;
         return View(model);
     }
 }
Пример #20
0
        /// <summary>
        /// Sets the identifiers on the book to match the list passed in
        /// </summary>
        /// <param name="db"></param>
        /// <param name="newIds">Item1 = the ident name, Item2 = the value for this book</param>
        public void SetIdentifiers(EbooksContext db, IEnumerable<Tuple<string, string>> newIds)
        {
            // Clear the idents against the book and re-add them.
            BookIdents.Clear();

            if (newIds == null) return;
            foreach (var id in newIds) {
                var ident = db.Idents.SingleOrDefault(i => i.Name == id.Item1);
                if (ident == null) {
                    db.Idents.Add(ident = new Ident { Name = id.Item1 });
                }
                db.BookIdents.Add(new BookIdent { Book = this, Ident = ident, Identifier = id.Item2 });
            }
        }
Пример #21
0
 // GET: Gutenberg
 public ActionResult Index(string filter, int language = 0)
 {
     using (var db = new EbooksContext()) {
         if (string.IsNullOrWhiteSpace(filter) && language == 0) return View(new GutenbergViewModel(LanguageName.InUse(db)));
         string usefilter = filter.ToLower();
         var langCodes = db.LanguageNames.SingleOrDefault(l => l.LanguageNameId == language)?.LanguageCodes.Select(c => c.Code).ToArray();
         IQueryable<GutBook> books = db.GutBooks;
         if (langCodes != null && langCodes.Any()) {
             books = books.Where(b => langCodes.Contains(b.Language));
         }
         books = books.Where(b => b.Title.ToLower().Contains(usefilter) || (b.GutAuthor != null && b.GutAuthor.Name.Contains(usefilter)))
             .Take(200).OrderBy(b => b.Title).ThenBy(b => b.GutAuthor == null ? null : b.GutAuthor.Name);
         var vm = new GutenbergViewModel(books, filter, language, LanguageName.InUse(db));
         return View(vm);
     }
 }
Пример #22
0
        /// <summary>
        /// Reloads the database record with the book data, overwriting any changes made by the user.
        /// </summary>
        /// <param name="db"></param>
        /// <remarks>Does not save the changes.</remarks>
        public void Reload(EbooksContext db)
        {
            var ep = new Epub(this);

            Title = ep.Title;
            Author = Author.Get(db, ep);
            Publisher = string.IsNullOrWhiteSpace(ep.Publisher) && EpubFile.GutBook != null
                ? Publisher.Get(db, "Project Gutenberg")
                : Publisher = Publisher.Get(db, ep);
            Cover = Cover.Get(db, ep);
            EpubFile = EpubFile.Get(db, ep);
            Series = Series.Get(db, ep);
            SeriesNbr = ep.SeriesNbr;
            Description = ep.Description;
            SetTags(db, ep.Tags);
            SetIdentifiers(db, ep.Identifiers);
        }
Пример #23
0
        public static EpubFile Get(EbooksContext db, Epub ep)
        {
            using (var s = ep.GetDataStream()) {
                string checksum = s.GetChecksum();
                var epub = db.EpubFiles.SingleOrDefault(ef => ef.Checksum == checksum);
                if (epub == null) {
                    using (var m = new MemoryStream()) {
                        s.Seek(0, SeekOrigin.Begin);
                        s.CopyTo(m);

                        db.EpubFiles.Add(epub = new EpubFile {
                            Contents = m.ToArray(),
                            Checksum = checksum
                        });
                    }
                }
                return epub;
            }
        }
Пример #24
0
        /// <summary>
        /// Loads a new book into the database for the given user, reusing records wherever possible.
        /// </summary>
        /// <param name="db"></param>
        /// <param name="ep"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        /// <remarks>Does not save the changes.</remarks>
        public static Book Load(EbooksContext db, Epub ep, int userId)
        {
            var book = new Book {
                UserId = userId,
                Title = ep.Title,
                Author = Author.Get(db, ep),
                Publisher = Publisher.Get(db, ep),
                Cover = Cover.Get(db, ep),
                EpubFile = EpubFile.Get(db, ep),
                Series = Series.Get(db, ep),
                SeriesNbr = ep.SeriesNbr,
                Description = ep.Description
            };
            book.SetTags(db, ep.Tags);
            book.SetIdentifiers(db, ep.Identifiers);

            db.Books.Add(book);

            return book;
        }
Пример #25
0
        public static Cover Get(EbooksContext db, Epub ep)
        {
            var bcover = ep.GetCoverData();
            if (bcover == null) return null;
            string checksum = bcover.GetChecksum();
            var cover = db.Covers.SingleOrDefault(c => c.Checksum == checksum);
            if (cover == null) {
                using (var ts = new MemoryStream()) {
                    ImageCodecInfo encoder = ImageCodecInfo.GetImageEncoders().Single(e => e.FormatID == ImageFormat.Jpeg.Guid);
                    var encoderParams = new EncoderParameters(1);
                    encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 75L);

                    ep.CoverThumbnail.Save(ts, encoder, encoderParams);
                    db.Covers.Add(cover = new Cover {
                        Picture = bcover,
                        Thumbnail = ts.ToArray(),
                        Checksum = checksum
                    });
                }
            }
            return cover;
        }
Пример #26
0
        // GET: ReadBook
        public ActionResult Index(int bookId = 0, int spineIndex = 0)
        {
            using (var db = new EbooksContext()) {
                var user = db.GetEbooksUser(User);
                var book = db.Books.SingleOrDefault(b => b.BookId == bookId && b.UserId == user.UserId);
                if (book == null) return RedirectToAction("Index", "Ebooks");
                using (var ep = new Epub(book)) {
                    var spine = ep.SpineRefs.ToArray();
                    spineIndex = Math.Max(0, Math.Min(spineIndex, spine.Length - 1));
                    string url = Url.Action($"ReadContent/{bookId}/{spine[spineIndex]}");

                    var model = new ReadBookViewModel {
                        SpineRefs = ep.SpineRefs.ToArray(),
                        Title = book.Title,
                        Url = url,
                        BookId = bookId,
                        Toc = ep.Toc
                    };

                    return View(model);
                }
            }
        }
        private void loadBookData(EbooksContext db, GutCatDoc doc, IList<GutBook> newBooks, IList<GutAuthor> newAuthors, IList<LanguageName> newLangNames, IList<LanguageCode> newLangCodes) {
            var gutBook = db.GutBooks.SingleOrDefault(b => b.GutBookId == doc.Id);
            if (gutBook == null) {
                gutBook = new GutBook { GutBookId = doc.Id };
                newBooks.Add(gutBook);
            }
            gutBook.Title = doc.Title;
            var gutAuthor = newAuthors.SingleOrDefault(a => a.Name == doc.Author);
            if (gutAuthor == null) gutAuthor = db.GutAuthors.SingleOrDefault(a => a.Name == doc.Author);
            if (gutAuthor == null && doc.Author != null) {
                gutAuthor = new GutAuthor { Name = doc.Author };
                newAuthors.Add(gutAuthor);
            }
            gutBook.GutAuthor = gutAuthor;

            var langCode = newLangCodes.SingleOrDefault(c => c.Code == doc.Language);
            if (langCode == null) langCode = db.LanguageCodes.SingleOrDefault(c => c.Code == doc.Language);
            if (langCode == null) {
                var langName = newLangNames.SingleOrDefault(n => n.Name == doc.Language);
                if (langName == null) newLangNames.Add(langName = new LanguageName { Name = doc.Language });
                langCode = new LanguageCode { Code = doc.Language };
                langCode.LanguageNames = new Collection<LanguageName>();
                langCode.LanguageNames.Add(langName);
                newLangCodes.Add(langCode);
            }
            gutBook.Language = doc.Language;

            var getUrl = new Func<string, string, string>((url, standard) => url != null && url != standard ? url : null);
            gutBook.EpubUrlImages = getUrl(doc.EpubUrlImages, doc.StandardEpubUrlImages);
            gutBook.StandardEpubUrlImages = doc.EpubUrlImages == doc.StandardEpubUrlImages;
            gutBook.EpubUrlNoImages = getUrl(doc.EpubUrlNoImages, doc.StandardEpubUrlNoImages);
            gutBook.StandardEpubUrlNoImages = doc.EpubUrlNoImages == doc.StandardEpubUrlNoImages;
            gutBook.ThumbnailUrl = getUrl(doc.ThumbnailUrl, doc.StandardThumbnailUrl);
            gutBook.StandardThumbnailUrl = doc.ThumbnailUrl == doc.StandardThumbnailUrl;
            gutBook.CoverUrl = getUrl(doc.CoverUrl, doc.StandardCoverUrl);
            gutBook.StandardCoverUrl = doc.CoverUrl == doc.StandardCoverUrl;
        }
Пример #28
0
        public ActionResult Edit(BookEditedViewModel model)
        {
            using (var db = new EbooksContext()) {
                var book = db.Books.Single(b => b.BookId == model.BookId);
                book.Title = model.Title;
                if (model.Author.StartsWith("~")) {
                    book.Author = Author.Get(db, model.Author.Substring(1));
                } else {
                    book.AuthorId = model.AuthorId != 0 ? model.AuthorId : null;
                }
                if (model.Publisher.StartsWith("~")) {
                    book.Publisher = Publisher.Get(db, model.Publisher.Substring(1));
                } else {
                    book.PublisherId = model.PublisherId != 0 ? model.PublisherId : null;
                }
                book.SetTags(db, model.Tags);
                book.SetIdentifiers(db, model.BookIdents);

                book.Description = model.Description;
                db.SaveChanges();
            }

            return RedirectToAction("Index");
        }
Пример #29
0
 public static Publisher Get(EbooksContext db, Epub ep)
 {
     return Get(db, ep.Publisher);
 }
Пример #30
0
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                    // Create a User in the Ebooks database
                    using (var ebdb = new EbookObjects.Models.EbooksContext()) {
                        ebdb.Users.Add(new EbookObjects.Models.User { Identity = user.Id });
                        ebdb.SaveChanges();
                    }
                    
                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }