public void Remove(Book book) { using (var ctx = new Context()) { if (book.Cover != null) { ctx.Covers.Attach(book.Cover); ctx.Entry(book.Cover).State = EntityState.Deleted; ctx.SaveChanges(); } if (book.BookMarks != null && book.BookMarks.Count > 0) { foreach (var bookmark in book.BookMarks) { ctx.Bookmarks.Attach(bookmark); ctx.Entry(bookmark).State = EntityState.Deleted; ctx.SaveChanges(); } } ctx.Books.Attach(book); ctx.Entry(book).State = EntityState.Deleted; ctx.SaveChanges(); } }
public bool Exists(Book book) { using (var ctx = new Context()) { return ctx.Books.Any(x => x.FullPathAndFileName == book.FullPathAndFileName); } }
public async Task<Book> AddAsync(Book book) { using (var ctx = new Context()) { var added = ctx.Books.Add(book); await ctx.SaveChangesAsync(); return added.Entity; } }
public async void Update(Book book) { using (var ctx = new Context()) { ctx.Books.Attach(book); ctx.Entry(book).State = EntityState.Modified; await ctx.SaveChangesAsync(); } }
public async Task<string> GenerateCoverImage(Book book, uint pageIndex, ISourceRepository sourceRepository, StorageFolder storageFolder, StorageFile pdfFile) { try { // var pdfFile = await storageFolder.GetFileAsync(book.FileName); try { _pdfDocument = await PdfDocument.LoadFromFileAsync(pdfFile); } catch (Exception) { return null; } if (_pdfDocument == null || _pdfDocument.PageCount <= 0) return null; //Get Pdf page using (var pdfPage = _pdfDocument.GetPage(pageIndex)) { if (pdfPage == null) return null; // next, generate a bitmap of the page var thumbfolder = await Globals.GetCoversFolder(); var pngFile = await thumbfolder.CreateFileAsync(Utils.GenerateRandomString() + ".png", CreationCollisionOption.ReplaceExisting); if (pngFile == null) return null; using (var randomStream = await pngFile.OpenAsync(FileAccessMode.ReadWrite)) { await pdfPage.RenderToStreamAsync(randomStream, new PdfPageRenderOptions() { DestinationHeight = 340, DestinationWidth = 240 }); await randomStream.FlushAsync(); } return pngFile.Path; } } catch (Exception) { //rootPage.NotifyUser("Error: " + err.Message, NotifyType.ErrorMessage); return null; } }
public static async Task<ImageSource> GetImage(Book book) { var storageFolder = await Globals.GetCoversFolder(); var storageFile = await storageFolder.GetFileAsync(book.Cover.FileName); BitmapImage bitmapImage = null; if (storageFile != null) { bitmapImage = new BitmapImage(); using (var stream = await storageFile.OpenReadAsync()) { await bitmapImage.SetSourceAsync(stream); } } return bitmapImage; }
public List<BookMark> GetAllForBook(Book book) { return _repository.Find(x => x.Book.Id == book.Id).ToList(); }
public async Task<ObservableCollection<SearchResult>> SearchBooks(object searchQuery) { var searchResults = new ObservableCollection<SearchResult>(); SearchQuery = searchQuery; if (searchQuery == null) { throw new ArgumentNullException("searchQuery"); } if (DateTime.Now.Subtract(lastTimeIWasCalled).Seconds < 1) { await Task.Delay(TimeSpan.FromSeconds(1)); } lastTimeIWasCalled = DateTime.Now; var foundBook = new Book(); var result = await GetXml(GetUrlForSearch()); var titleRegex = new Regex("<dc:title>(.*)</dc:title>"); var titleMatch = titleRegex.Match(result); if (titleMatch.Success) { foundBook.Title = titleMatch.Groups[1].ToString(); } var abstractRegex = new Regex("<dc:description>(.*)</dc:description>"); var abstractMatch = abstractRegex.Match(result); if (abstractMatch.Success) { foundBook.Abstract = abstractMatch.Groups[1].ToString(); } DateTime publishedDate; var dateRegex = new Regex("<dc:date>(.*)</dc:date>"); var dateMatch = dateRegex.Match(result); if (dateMatch.Success) { DateTime.TryParse(dateMatch.Groups[1].ToString(), out publishedDate); if (publishedDate != null || publishedDate != DateTime.MinValue) { foundBook.DatePublished = publishedDate; } } var authorRegex = new Regex("<dc:creator>(.*)</dc:creator>"); var authorMatch = authorRegex.Match(result); if (authorMatch.Success) { foundBook.Author = authorMatch.Groups[1].ToString(); } var publisherRegex = new Regex("<dc:publisher>(.*)</dc:publisher>"); var publisherMatch = publisherRegex.Match(result); if (publisherMatch.Success) { foundBook.Publisher = publisherMatch.Groups[1].ToString(); } //Regex pagesRegex = new Regex("<dc:format>(.*)</dc:format>"); //var pagesMatch = pagesRegex.Match(result); //if (pagesMatch.Success) //{ // var p = pagesMatch.Groups[1].ToString(); // Regex re = new Regex(@"\d+"); // Match m = re.Match(p); // if (m.Success) // { // foundBook.Pages = Convert.ToInt32(m.Groups[1].ToString()); // } //} var sresult = new SearchResult(); if (string.IsNullOrEmpty(foundBook.Title)) { sresult.Book = null; } else { sresult.Book = foundBook; } searchResults.Add(sresult); //try //{ // xdcDocument = XDocument.Parse(result); // XNamespace ns = "http://www.w3.org/2005/Atom"; // var nodes = xdcDocument.Descendants(ns + "entry"); // if (nodes != null) // found a result // { // var t = nodes.Descendants(); // var title = t.Nodes(); // } //} //catch (Exception ex) //{ //} // var ns = new XmlNamespaceManager(xdcDocument.NameTable); //ns.AddNamespace("openSearch", "http://a9.com/-/spec/opensearchrss/1.0/"); //ns.AddNamespace("atom", "http://www.w3.org/2005/Atom"); //ns.AddNamespace("dc", "http://purl.org/dc/terms"); //var xelRoot = xdcDocument.DocumentElement; //var xnlNodes = xelRoot.SelectNodes("//atom:entry", ns); // var xnlNodes = xdcDocument.Element("//atom:entry"); //foreach (XmlNode xndNode in xnlNodes) //{ // var searchResult = new SearchResult(); // var book = new Book(); // var xmlTitle = xndNode["title"]; // if (xmlTitle != null) // { // book.Title = xmlTitle.InnerText; // } // var xmlDatePublished = xndNode["dc:date"]; // if (xmlDatePublished != null) // { // var dp = xmlDatePublished.InnerText; // if (dp.Length == 4) // { // var dt = Convert.ToDateTime(string.Format("01/01/,{0}", dp)); // book.DatePublished = dt; // } // else // { // DateTime dt; // if (DateTime.TryParse(dp, out dt)) // { // book.DatePublished = dt; // } // } // } // var xmlDescription = xndNode["dc:description"]; // if (xmlDescription != null) // { // // Remove ASCII Control Characters // book.Abstract = xmlDescription.InnerText.Replace("'", "'"); // book.Abstract = xmlDescription.InnerText.Replace(""", string.Empty); // } // var formatNodes = xndNode.SelectNodes("dc:format", ns); // if (formatNodes != null) // { // foreach (XmlNode node in formatNodes) // { // if (node.InnerText.Contains("pages")) // { // var resultString = Regex.Match(node.InnerText, @"\d+").Value; // book.Pages = Convert.ToInt32(resultString); // } // } // } // var identifierNodes = xndNode.SelectNodes("dc:identifier", ns); // if (identifierNodes != null) // { // foreach (XmlNode node in identifierNodes) // { // if (node.InnerText.Length == 18) // 13 digit ISBN Node // { // book.Isbn = Regex.Match(node.InnerText, @"\d+").Value; // } // } // } // var xmlPublisher = xndNode["dc:publisher"]; // if (xmlPublisher != null) // { // // searchResult.Publishers.Add(new Publisher { Name = xmlPublisher.InnerText }); // } // var xmlAuthor = xndNode["dc:creator"]; // if (xmlAuthor != null) // { // var words = xmlAuthor.InnerText.Split(' '); // if (words.Length == 1) // { // // searchResult.Authors.Add(new Author { LastName = words[0] }); // } // else // { // //searchResult.Authors.Add(new Author // //{ // // FirstName = words[0], // // LastName = words[1] // //}); // } // } // // book.Scraped = true; // searchResult.Book = book; // // searchResult.Percentage = MatchStrings.Compute(searchQuery.ToString(), book.Title)*100; // searchResults.Add(searchResult); //} // var s = searchResults.OrderByDescending(x => x.Percentage); // return new ObservableCollection<SearchResult>(s); return searchResults; }
public bool Exists(Book book) { return _repository.Exists(book); }
public void Remove(Book book) { _repository.Remove(book); }
public void Update(Book book) { _repository.Update(book); }
public Book Add(Book book) { return _repository.AddAsync(book).Result; }
public void OnBookChanged(Book book, BookEventArgs.BookState bookState, int? progress) { BookChanged?.Invoke(this, new BookEventArgs { Book = book, State = bookState, Progress = progress }); }
private Book XmlToBook(StorageFile xml, Book book) { Stopwatch stop = new Stopwatch(); stop.Start(); var file = xml; var stream = file.OpenStreamForReadAsync().GetAwaiter().GetResult(); var outBook = new Book(); using (var reader = XmlReader.Create(stream)) { while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "Title": outBook.Title = reader.ReadElementContentAsString(); break; case "Description": outBook.Abstract = reader.ReadElementContentAsString(); break; case "Year": DateTime datePublished; var successDate = DateTime.TryParseExact(reader.ReadElementContentAsString(), "yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out datePublished); if (successDate) { outBook.DatePublished = datePublished; } break; case "Pages": int pages; var successPages = int.TryParse(reader.ReadElementContentAsString(), out pages); if (successPages) { outBook.Pages = pages; } break; case "Isbn": outBook.Isbn = reader.ReadElementContentAsString(); break; case "Publisher": var publisherReader = reader.ReadSubtree(); publisherReader.Read(); while (publisherReader.Read()) { if (reader.Name == "Name") { outBook.Publisher += reader.ReadElementContentAsString(); } } break; case "Author": var authorReader = reader.ReadSubtree(); authorReader.Read(); while (authorReader.Read()) { if (reader.Name == "Name") { outBook.Author += reader.ReadElementContentAsString() + ","; } } break; } } } } outBook.Source = book.Source; outBook.FileName = book.FileName; outBook.FullPathAndFileName = book.FullPathAndFileName; outBook.Scraped = true; stream.Dispose(); stop.Stop(); var t = stop.ElapsedMilliseconds; return outBook; }
private Book UseIsbn(StorageFile storageFile, Book book) { var outBook = new Book { Title = Path.GetFileNameWithoutExtension(storageFile.Name), Source = book.Source, FileName = book.FileName, FullPathAndFileName = book.FullPathAndFileName }; var parser = new PdfParser(); var s = parser.Extract(storageFile, 1, 10).Result; var isbn = PdfIsbnParser.FindIsbn(s); if (IsNullOrEmpty(isbn)) return outBook; outBook.Isbn = isbn; var scraper = new Scraper.Scraper(); var results = scraper.Scrape(outBook.Isbn).Result; if (results.items == null || results.items.Count <= 0) return outBook; outBook.Title = results.items[0].volumeInfo.title; outBook.Abstract = results.items[0].volumeInfo.description; outBook.Pages = results.items[0].volumeInfo.pageCount; outBook.Scraped = true; if (results.items[0].volumeInfo.authors != null) { outBook.Author = Join(",", results.items[0].volumeInfo.authors.ToArray()); } outBook.Publisher = results.items[0].volumeInfo.publisher; return outBook; }
private void Worker_DoWork(object sender, DoWorkEventArgs e) { var filter = new List<string> { ".pdf" }; var storageFolders = _sourceService.GetAllAsStorageFoldersAsync().Result; foreach (var storageFolder in storageFolders) { var source = _sourceService.GetByUrl(storageFolder.Path); var options = new QueryOptions(CommonFileQuery.OrderByName, filter); var ss = storageFolder.CreateItemQueryWithOptions(options); //Get all PDF files for storagefolder var pdfFiles = ss.GetItemsAsync().GetAwaiter().GetResult(); for (var i = 0; i < pdfFiles.Count; i++) { var progress = Utils.CalculatePercentage(i, 0, pdfFiles.Count); if (Worker.CancellationPending) { e.Cancel = true; return; } var book = new Book { Title = Path.GetFileNameWithoutExtension(pdfFiles[i].Name), Source = source, FileName = Path.GetFileName(pdfFiles[i].Path), FullPathAndFileName = pdfFiles[i].Path, Rating = 0 }; var book1 = book; var existingBook = _bookService.Exists(book1); if (existingBook == false) // Add Book { var xml = storageFolder.TryGetItemAsync(book.Title + ".xml").GetAwaiter().GetResult(); if (xml != null) { book = XmlToBook(xml as StorageFile, book); } else { book = UseIsbn(pdfFiles[i] as StorageFile, book); } var cover = new Cover(); var coverPath = _pdfCover.GenerateCoverImage(book, 0, _sourcerepo, storageFolder, pdfFiles[i] as StorageFile).Result; cover.FileName = Path.GetFileName(coverPath); book.Cover = cover; book = _bookService.Add(book); Worker.ReportProgress(progress, book); } else { Tuple<Book, string> exists = new Tuple<Book, string>(book, "Exists"); Worker.ReportProgress(progress, exists); } } } }