public void updateMetaUi() {
    Book book = mSpritzer.getBook();
    Metadata meta = book.getMetadata();
    Author author = meta.getAuthors().get(0);
    int curChapter = mSpritzer.getCurrentChapter();

    mAuthorView.setText(author.getFirstname() + " " + author.getLastname());
    mTitleView.setText(meta.getFirstTitle());
    String chapterText;
    if (book.getSpine().getResource(curChapter).getTitle() == null
        || book.getSpine().getResource(curChapter).getTitle().trim().compareTo("") == 0) {
      chapterText = String.format("Chapter %d", curChapter);
    } else {
      chapterText = book.getSpine().getResource(curChapter).getTitle();
    }

    int startSpan = chapterText.length();
    chapterText =
        String.format(
            "%s  %s m left",
            chapterText,
            (mSpritzer.getMinutesRemainingInQueue() == 0)
                ? "<1"
                : String.valueOf(mSpritzer.getMinutesRemainingInQueue()));
    int endSpan = chapterText.length();
    Spannable spanRange = new SpannableString(chapterText);
    TextAppearanceSpan tas = new TextAppearanceSpan(mChapterView.getContext(), R.style.MinutesToGo);
    spanRange.setSpan(tas, startSpan, endSpan, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    mChapterView.setText(spanRange);

    mProgress.setMax(mSpritzer.getMaxChapter());
    mProgress.setProgress(curChapter);
  }
 public static void processEpub(String bookPath, String dest)
     throws FileNotFoundException, IOException {
   EpubReader reader = new EpubReader();
   Book b = reader.readEpub(new FileInputStream(new File(bookPath)));
   String content = "";
   int pagecount = 1;
   int tempCounter;
   Count cnt = new Count(0, 0);
   for (Resource res : b.getContents()) {
     content = new String(res.getData());
     Document doc = Jsoup.parse(content, "UTF-8");
     // http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"");
     Element elem = new Element(Tag.valueOf("meta"), "");
     elem.attr("http-equiv", "content-type");
     elem.attr("content", "text/html; charset=utf-8");
     doc.head().after(elem);
     System.out.println(doc.head().data());
     Element ele = doc.body();
     alterElement(ele);
     Count cTemp = modify(ele, cnt);
     cnt.setCount(cTemp.getCount());
     cnt.setPgCount(cTemp.getPgCount());
     doc.body().html(ele.html());
     res.setData(doc.html().getBytes());
     if (res.getMediaType() == null) res.setMediaType(new MediaType("html", "html"));
   }
   EpubWriter wr = new EpubWriter();
   wr.write(b, new FileOutputStream(new File(dest)));
 }
 private static void writeGuide(XmlSerializer serializer, Book book) throws IOException {
   if (!book.getGuide().isEmpty()) {
     serializer.startTag(NAMESPACE_OPF, OPFElements.GUIDE);
     ensureCoverPageGuideReferenceWritten(book.getGuide(), serializer);
     for (GuideReference reference : book.getGuide().getReferences()) {
       writeGuideReference(reference, serializer);
     }
     serializer.endTag(NAMESPACE_OPF, OPFElements.GUIDE);
   }
 }
Example #4
0
 public Book readEpub(Resources resources, Book result) throws IOException {
   if (result == null) {
     result = new Book();
   }
   handleMimeType(result, resources);
   String packageResourceHref = getPackageResourceHref(resources);
   Resource packageResource = processPackageResource(packageResourceHref, result, resources);
   result.setOpfResource(packageResource);
   Resource ncxResource = processNcxResource(packageResource, result);
   result.setNcxResource(ncxResource);
   result = postProcessBook(result);
   result.setResources(resources);
   return result;
 }
  /**
   * Write an EPUB 3.0 OPF package document.
   *
   * @param book the book to write the package document for
   * @param serializer the XML serialiser to write the package document to
   * @throws IOException if an I/O error occurs
   */
  public static void write(final XmlSerializer serializer, final Book book) throws IOException {
    Identifier bookId = book.getMetadata().getBookIdIdentifier();

    serializer.startDocument(Constants.CHARACTER_ENCODING, false);

    serializer.setPrefix(PREFIX_OPF, NAMESPACE_OPF);
    serializer.setPrefix(PREFIX_DUBLIN_CORE, NAMESPACE_DUBLIN_CORE);

    serializer.startTag(NAMESPACE_OPF, OPFElements.PACKAGE);
    serializer.attribute(PREFIX_EMPTY, OPFAttributes.VERSION, VERSION);
    serializer.attribute(
        PREFIX_EMPTY, OPFAttributes.UNIQUE_IDENTIFIER, bookId != null ? bookId.getId() : BOOK_ID);

    PackageDocumentMetadataWriter.writeMetaData(book, serializer);

    writeManifest(serializer, book);
    writeSpine(serializer, book);
    writeGuide(serializer, book);

    serializer.endTag(NAMESPACE_OPF, OPFElements.PACKAGE);

    serializer.endDocument();

    serializer.flush();
  }
 /**
  * Check whether a resource is valid. A valid resource must have a non-blank ID, a non-blank link
  * and a media type.
  *
  * @param book the book the resource is for
  * @param resource the resource to check
  * @return whether the resource is valid
  */
 private static boolean isValidResource(final Book book, final Resource resource) {
   if (resource == null
       || (resource.getMediaType() == MediatypeService.NCX
           && book.getSpine().getTocResource() != null)) {
     return false;
   }
   if (StringUtil.isBlank(resource.getId())) {
     LOGGER.error(
         "resource id must not be blank (href: "
             + resource.getHref()
             + ", mediatype:"
             + resource.getMediaType()
             + ")");
     return false;
   }
   if (StringUtil.isBlank(resource.getHref())) {
     LOGGER.error(
         "resource href must not be blank (id: "
             + resource.getId()
             + ", mediatype:"
             + resource.getMediaType()
             + ")");
     return false;
   }
   if (resource.getMediaType() == null) {
     LOGGER.error(
         "resource media type must be specified (id: "
             + resource.getId()
             + ", href:"
             + resource.getHref()
             + ")");
     return false;
   }
   return true;
 }
 private static List<Resource> getResourcesSortedById(final Book book) {
   List<Resource> resources = new ArrayList<>(book.getResources().getAll());
   Collections.sort(
       resources,
       (Resource resource1, Resource resource2) ->
           resource1.getId().compareToIgnoreCase(resource2.getId()));
   return resources;
 }
  /**
   * Write a manifest.
   *
   * @param serializer the XML serialiser to write the manifest to
   * @param book the book to write the manifest for
   * @throws IOException if an I/O error occurs
   */
  private static void writeManifest(final XmlSerializer serializer, final Book book)
      throws IOException {
    serializer.startTag(NAMESPACE_OPF, OPFElements.MANIFEST);

    if (book.isNcx()) {
      serializer.startTag(NAMESPACE_OPF, OPFElements.ITEM);
      serializer.attribute(PREFIX_EMPTY, OPFAttributes.ID, book.getNcxId());
      serializer.attribute(PREFIX_EMPTY, OPFAttributes.HREF, book.getNcxHref());
      serializer.attribute(PREFIX_EMPTY, OPFAttributes.MEDIA_TYPE, book.getNcxMediaType());
      serializer.endTag(NAMESPACE_OPF, OPFElements.ITEM);
    }

    for (Resource resource : getResourcesSortedById(book)) {
      writeItem(serializer, book, resource);
    }

    serializer.endTag(NAMESPACE_OPF, OPFElements.MANIFEST);
  }
 private void saveState() {
   SharedPreferences.Editor editor =
       mTarget.getContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit();
   editor
       .putInt("Chapter", mChapter)
       .putInt("Word", mWordArray.length - mWordQueue.size())
       .putString("Title", mBook.getTitle())
       .putInt("Wpm", mWPM)
       .apply();
 }
 private String loadCleanStringFromChapter(int chapter) {
   try {
     String bookStr = new String(mBook.getSpine().getResource(chapter).getData(), "UTF-8");
     return Html.fromHtml(bookStr).toString().replace("\n", "").replaceAll("(?s)<!--.*?-->", "");
   } catch (IOException e) {
     e.printStackTrace();
     Log.e(TAG, "Parsing failed " + e.getMessage());
     return "";
   }
 }
Example #11
0
  public List<TocEntry> getTableOfContents() {
    if (this.book == null) {
      return null;
    }

    List<TocEntry> result = new ArrayList<BookView.TocEntry>();

    flatten(book.getTableOfContents().getTocReferences(), result, 0);

    return result;
  }
 private void restoreState() {
   SharedPreferences prefs =
       mTarget.getContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE);
   if (mBook.getTitle().compareTo(prefs.getString("Title", "<>?l")) == 0) {
     mChapter = prefs.getInt("Chapter", 0);
     setText(loadCleanStringFromChapter(mChapter));
     int oldSize = prefs.getInt("Word", 0);
     setWpm(prefs.getInt("Wpm", 500));
     while (mWordQueue.size() > oldSize) {
       mWordQueue.remove();
     }
   } else {
     mChapter = 0;
     setText(loadCleanStringFromChapter(mChapter));
   }
 }
 public void openEpub(Uri epubUri) {
   try {
     InputStream epubInputStream =
         mTarget.getContext().getContentResolver().openInputStream(epubUri);
     String epubPath = FileUtils.getPath(mTarget.getContext(), epubUri);
     if (epubPath == null || !epubPath.contains("epub")) {
       reportFileUnsupported();
       return;
     }
     mBook = (new EpubReader()).readEpub(epubInputStream);
     mMaxChapter = mBook.getSpine().getSpineReferences().size();
     restoreState();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  public Image get(Object key) {
    try {
      if (book == null) {
        return null;
      }

      String imageURL = key.toString();

      // see if the image is already in the cache
      Image result = cache.get(imageURL);
      if (result != null) {
        return result;
      }

      // get the image resource href
      String resourceHref = getResourceHref(imageURL);

      // find the image resource in the book resources
      Resource imageResource = book.getResources().getByHref(resourceHref);
      if (imageResource == null) {
        return result;
      }

      // create an image from the resource and add it to the cache
      result = createImage(imageResource);

      if (result != null) {
        cache.put(imageURL.toString(), result);
      }
      return result;
    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }
  /**
   * Write a spine.
   *
   * @param serializer the XML serialiser to write the spine to
   * @param book the book to write the spine for
   * @throws IOException if an I/O error occurs
   */
  private static void writeSpine(final XmlSerializer serializer, final Book book)
      throws IOException {
    serializer.startTag(NAMESPACE_OPF, OPFElements.SPINE);
    // REMOVED WRITING OF TABLE OF CONTENTS ATTRIBUTE
    serializer.attribute(PREFIX_EMPTY, OPFAttributes.TOC, book.getSpine().getTocResource().getId());

    // REMOVED WRITING OF COVER PAGE
    if (book.getCoverPage() != null // there is a cover page
        && book.getSpine().findFirstResourceById(book.getCoverPage().getId())
            < 0) { // cover page is not already in the spine
      // write the cover html file
      serializer.startTag(NAMESPACE_OPF, OPFElements.ITEMREF);
      serializer.attribute(PREFIX_EMPTY, OPFAttributes.IDREF, book.getCoverPage().getId());
      serializer.attribute(PREFIX_EMPTY, OPFAttributes.LINEAR, "no");
      serializer.endTag(NAMESPACE_OPF, OPFElements.ITEMREF);
    }
    writeSpineItems(serializer, book.getSpine());

    serializer.endTag(NAMESPACE_OPF, OPFElements.SPINE);
  }
Example #16
0
  /**
   * Generate an ebook from an RSS DOM Document.
   *
   * @param url The URL from where the Document was fetched (used only to set the author metadata)
   * @param doc The DOM Document of the feed.
   * @return An ebook.
   * @throws IllegalArgumentException
   * @throws FeedException
   * @throws IOException
   */
  private static Book createBookFromFeed(URL url, Document doc, List<Keyword> keywords)
      throws IllegalArgumentException, FeedException, IOException {
    Book book = new Book();
    // start parsing our feed and have the above onItem methods called
    SyndFeedInput input = new SyndFeedInput();
    SyndFeed feed = input.build(doc);

    System.out.println(feed);

    // Set the title
    book.getMetadata().addTitle(feed.getTitle());

    // Add an Author
    String author = feed.getAuthor();
    if (author == null || "".equals(author.trim())) {
      author = url.getHost();
    }
    book.getMetadata().addAuthor(new Author(author));

    if (feed.getPublishedDate() != null) {
      book.getMetadata().addDate(new nl.siegmann.epublib.domain.Date(feed.getPublishedDate()));
    }

    if (feed.getDescription() != null) {
      book.getMetadata().addDescription(feed.getDescription());
    }

    if (feed.getCopyright() != null) {
      book.getMetadata().getRights().add(feed.getCopyright());
    }

    // Set cover image - This has never worked.
    // if (feed.getImage() != null) {
    // System.out.println("There is an image for the feed");

    // Promise<HttpResponse> futureImgResponse =
    // WS.url(feed.getImage().getUrl()).getAsync();
    // HttpResponse imgResponse = await(futureImgResponse);
    // System.out.println("Content-type: " + imgResponse.getContentType());
    // if (imgResponse.getContentType().startsWith("image/")) {
    // String extension =
    // imgResponse.getContentType().substring("image/".length());
    // InputStream imageStream = imgResponse.getStream();
    // book.getMetadata().setCoverImage(new Resource(imageStream, "cover." +
    // extension));

    // System.out.println("Using default cover");
    // imageStream =
    // VirtualFile.fromRelativePath("assets/cover.png").inputstream();
    // if (imageStream != null) {
    // System.out.println("Using default cover");
    // book.getMetadata().setCoverImage(new Resource(imageStream,
    // "cover.png"));
    // } else {
    // System.out.println("Could not load default cover");
    // }

    // }
    // }

    int entryNumber = 0;
    List<SyndEntry> entries = feed.getEntries();

    for (SyndEntry entry : entries) {
      if (matchesKeyword(entry, keywords)) {

        StringBuilder title = new StringBuilder(100);
        if (entry.getTitle() != null) {
          title.append(entry.getTitle());
        }
        if (entry.getAuthor() != null) {
          title.append(" - ").append(entry.getAuthor());
        }
        StringBuilder content = new StringBuilder();

        // Add title inside text
        content.append("<h2>").append(title).append("</h2>");

        if (entry.getDescription() != null) {
          SyndContent syndContent = (SyndContent) entry.getDescription();
          if (!syndContent.getType().contains("html")) {
            content.append("<pre>\n");
          }
          content.append(syndContent.getValue());
          if (!syndContent.getType().contains("html")) {
            content.append("\n</pre>");
          }
          content.append("<hr/>");
        }

        if (entry.getContents().size() > 0) {
          SyndContent syndContent = (SyndContent) entry.getContents().get(0);
          if (!syndContent.getType().contains("html")) {
            content.append("<pre>\n");
          }
          content.append(syndContent.getValue());
          if (!syndContent.getType().contains("html")) {
            content.append("\n</pre>");
          }
        }
        String strContent = clean(content.toString());
        // Add Chapter
        try {
          entryNumber++;
          book.addSection(
              title.toString(),
              new Resource(new StringReader(strContent), "entry" + entryNumber + ".xhtml"));
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }

    return book;
  }
  @Override
  public void storeBook(String fileName, Book book, boolean updateLastRead, boolean copyFile)
      throws IOException {

    File bookFile = new File(fileName);

    boolean hasBook = hasBook(bookFile.getName());

    if (hasBook && !updateLastRead) {
      return;
    } else if (hasBook) {
      helper.updateLastRead(bookFile.getName(), -1);
      return;
    }

    Metadata metaData = book.getMetadata();

    String authorFirstName = "Unknown author";
    String authorLastName = "";

    if (metaData.getAuthors().size() > 0) {
      authorFirstName = metaData.getAuthors().get(0).getFirstname();
      authorLastName = metaData.getAuthors().get(0).getLastname();
    }

    byte[] thumbNail = null;

    try {
      if (book.getCoverImage() != null && book.getCoverImage().getSize() < MAX_COVER_SIZE) {
        thumbNail = resizeImage(book.getCoverImage().getData());
        book.getCoverImage().close();
      }
    } catch (IOException io) {

    } catch (OutOfMemoryError err) {
      // If the image resource is too big, just import without a cover.
    }

    String description = "";

    if (!metaData.getDescriptions().isEmpty()) {
      description = metaData.getDescriptions().get(0);
    }

    String title = book.getTitle();

    if (title.trim().length() == 0) {
      title = fileName.substring(fileName.lastIndexOf('/') + 1);
    }

    if (copyFile) {
      bookFile = copyToLibrary(fileName, authorLastName + ", " + authorFirstName, title);
    }

    this.helper.storeNewBook(
        bookFile.getAbsolutePath(),
        authorFirstName,
        authorLastName,
        title,
        description,
        thumbNail,
        updateLastRead);
  }