Skip to content

Commit fd4efdf

Browse files
fix: incorrectly detecting epub as html (#234)
1 parent 51b0310 commit fd4efdf

1 file changed

Lines changed: 28 additions & 4 deletions

File tree

internal/webhook/handler.go

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"fmt"
99
"io"
1010
"net/http"
11+
"net/url"
1112
"os"
1213
"path/filepath"
1314
"regexp"
@@ -388,17 +389,18 @@ func processPDFForUser(jobID string, form map[string]string, userID uuid.UUID) (
388389
return "backend.status.no_url", nil, fmt.Errorf("no URL")
389390
}
390391

391-
// Check if this is a direct PDF/EPUB URL or a web article
392-
lowerURL := strings.ToLower(match)
393-
if strings.HasSuffix(lowerURL, ".pdf") || strings.HasSuffix(lowerURL, ".epub") {
392+
// Detect content type from URL path extension or HTTP sniffing
393+
contentType := detectURLContentType(match)
394+
395+
if contentType == "application/pdf" || contentType == "application/epub+zip" {
394396
// Direct download of PDF/EPUB
395397
manager.Logf("DownloadPDF: tmp=true, prefix=%q", prefix)
396398
jobStore.UpdateWithOperation(jobID, "Running", "backend.status.downloading", nil, "downloading")
397399
localPath, err = downloader.DownloadPDFForUser(match, true, prefix, userID, nil)
398400
if err != nil {
399401
return "backend.status.download_error", nil, err
400402
}
401-
} else if strings.HasSuffix(lowerURL, ".md") || strings.HasSuffix(lowerURL, ".markdown") {
403+
} else if contentType == "text/markdown" || contentType == "text/plain" {
402404
// Markdown URL - fetch raw content and convert
403405
manager.Logf("Fetching markdown from URL: %s", match)
404406
jobStore.UpdateWithOperation(jobID, "Running", "backend.status.fetching_url", nil, "fetching")
@@ -1127,6 +1129,28 @@ func isURL(s string) bool {
11271129
return strings.HasPrefix(s, "http://") || strings.HasPrefix(s, "https://")
11281130
}
11291131

1132+
// detectURLContentType determines content type for a URL.
1133+
// First checks URL path extension (fast), then falls back to HTTP sniffing.
1134+
func detectURLContentType(urlStr string) string {
1135+
if parsedURL, err := url.Parse(urlStr); err == nil {
1136+
ext := strings.ToLower(filepath.Ext(parsedURL.Path))
1137+
switch ext {
1138+
case ".pdf":
1139+
return "application/pdf"
1140+
case ".epub":
1141+
return "application/epub+zip"
1142+
case ".md", ".markdown":
1143+
return "text/markdown"
1144+
}
1145+
}
1146+
1147+
if mime, err := downloader.SniffMime(urlStr); err == nil {
1148+
return mime
1149+
}
1150+
1151+
return "text/html"
1152+
}
1153+
11301154
// trackDocumentUpload records a document upload in the database
11311155
func trackDocumentUpload(userID uuid.UUID, localPath, remoteName, rmDir string) error {
11321156
if database.DB == nil {

0 commit comments

Comments
 (0)