Skip to content

Commit

Permalink
fix: ensure automatically generated filename is a valid filename (#27)
Browse files Browse the repository at this point in the history
* if filename is not valid replace unvalid charachter with -

* fix typo

* better file name for EmbedImages code by @fmartingr

* update unittests

* be sure filename came from EmbedImages not be duplicated

* update unittest

* add failover for detect extention

* add test for file without extention and fix other test
  • Loading branch information
Monirzadeh committed Feb 11, 2024
1 parent 2f66845 commit dc6435e
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 3 deletions.
26 changes: 24 additions & 2 deletions epub.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ import (
"fmt"
"io/fs"
"log"
"mime"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
Expand Down Expand Up @@ -601,8 +603,28 @@ func (e *Epub) EmbedImages() {

firstSrcIndex := strings.Index(match[0], " src=")
match[0] = match[0][:firstSrcIndex+len(" src=")] + strings.ReplaceAll(match[0][firstSrcIndex+len(" src="):], " src=", " data-src=")

filePath, err := e.AddImage(string(imageURL), "")
parsedImageURL, err := url.Parse(imageURL)
if err != nil {
log.Printf("can't parse image URL: %s", err)
continue
}
extension := filepath.Ext(parsedImageURL.Path)
if extension == "" {
res, err := http.Head(imageURL)
if err != nil {
log.Printf("can't get image headers: %s", err)
} else {
// Get extension from the file content type
extensions, err := mime.ExtensionsByType(res.Header.Get("Content-Type"))
if err != nil {
log.Printf("can't get file type from content type: %s", err)
} else if len(extensions) > 0 {
extension = extensions[0]
}
}
}
filename := fmt.Sprintf("image%04d%s", len(e.images)+1, extension)
filePath, err := e.AddImage(string(imageURL), filename)
if err != nil {
log.Printf("can't add image to the epub: %s", err)
continue
Expand Down
54 changes: 53 additions & 1 deletion epub_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1015,9 +1015,21 @@ func TestEmbedImage(t *testing.T) {
testSectionBodyWithImage := ` <h1>Section 1</h1>
<p>This is a paragraph.</p>
<p><img src="` + server.URL + `/gophercolor16x16.png" loading="lazy"/></p>`
testSectionBodyWithImageUnvalidname := ` <h1>Section 1</h1>
<p>This is a paragraph.</p>
<p><img src="` + server.URL + `/gophercolor16x16.png?width=300" loading="lazy"/></p>`
testSectionBodyWithImageWithoutExtention := ` <h1>Section 1</h1>
<p>This is a paragraph.</p>
<p><img src="` + server.URL + `/gophercolor16x16withoutextention" loading="lazy"/></p>`
testSectionBodyWithImageExpect := ` <h1>Section 1</h1>
<p>This is a paragraph.</p>
<p><img src="../images/gophercolor16x16.png" loading="lazy"/></p>`
<p><img src="../images/image0001.png" loading="lazy"/></p>`
testSectionBodyWithImageUnvalidnameExpect := ` <h1>Section 1</h1>
<p>This is a paragraph.</p>
<p><img src="../images/image0003.png" loading="lazy"/></p>`
testSectionBodyWithImageWithoutExtentionExpected := ` <h1>Section 1</h1>
<p>This is a paragraph.</p>
<p><img src="../images/image0004.png" loading="lazy"/></p>`
e, err := NewEpub(testEpubTitle)
if err != nil {
t.Error(err)
Expand All @@ -1036,6 +1048,18 @@ func TestEmbedImage(t *testing.T) {
if err != nil {
t.Errorf("Error adding section: %s", err)
}
_, err = e.AddSection(testSectionBodyWithImage, testSectionTitle, "", "")
if err != nil {
t.Errorf("Error adding section: %s", err)
}
testSection4Path, err := e.AddSection(testSectionBodyWithImageUnvalidname, testSectionTitle, "", "")
if err != nil {
t.Errorf("Error adding section: %s", err)
}
testSection5Path, err := e.AddSection(testSectionBodyWithImageWithoutExtention, testSectionTitle, "", "")
if err != nil {
t.Errorf("Error adding section: %s", err)
}
e.EmbedImages()
tempDir := writeAndExtractEpub(t, e, testEpubFilename)

Expand Down Expand Up @@ -1083,6 +1107,34 @@ func TestEmbedImage(t *testing.T) {
contents,
testSection3Contents)
}
// test 4
contents, err = storage.ReadFile(filesystem, filepath.Join(tempDir, contentFolderName, xhtmlFolderName, testSection4Path))
if err != nil {
t.Errorf("Unexpected error reading section file: %s", err)
}
testSection4Contents := fmt.Sprintf(testSectionContentTemplate, testSectionTitle, testSectionBodyWithImageUnvalidnameExpect)
if trimAllSpace(string(contents)) != trimAllSpace(testSection4Contents) {
t.Errorf(
"Section file contents don't match\n"+
"Got: %s\n"+
"Expected: %s",
contents,
testSection4Contents)
}
// test 5
contents, err = storage.ReadFile(filesystem, filepath.Join(tempDir, contentFolderName, xhtmlFolderName, testSection5Path))
if err != nil {
t.Errorf("Unexpected error reading section file: %s", err)
}
testSection5Contents := fmt.Sprintf(testSectionContentTemplate, testSectionTitle, testSectionBodyWithImageWithoutExtentionExpected)
if trimAllSpace(string(contents)) != trimAllSpace(testSection5Contents) {
t.Errorf(
"Section file contents don't match\n"+
"Got: %s\n"+
"Expected: %s",
contents,
testSection5Contents)
}
cleanup(testEpubFilename, tempDir)
}

Expand Down
Binary file added testdata/gophercolor16x16withoutextention
Binary file not shown.

0 comments on commit dc6435e

Please sign in to comment.