Skip to content

Commit

Permalink
Support embedding PDF documents
Browse files Browse the repository at this point in the history
  • Loading branch information
csmith committed Dec 8, 2023
1 parent 9239219 commit 68231e7
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 10 deletions.
9 changes: 2 additions & 7 deletions handlers_file.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"fmt"
"github.com/mdbot/wiki/markdown"
"io"
"log"
"mime"
Expand Down Expand Up @@ -78,12 +79,6 @@ type FileProvider interface {
}

func FileHandler(provider FileProvider) http.HandlerFunc {
canEmbed := func(mimeType string) bool {
return strings.HasPrefix(mimeType, "image/") ||
strings.HasPrefix(mimeType, "video/") ||
strings.HasPrefix(mimeType, "audio/")
}

return func(writer http.ResponseWriter, request *http.Request) {
name := strings.TrimPrefix(request.URL.Path, "/files/view/")
reader, err := provider.GetFile(name)
Expand All @@ -100,7 +95,7 @@ func FileHandler(provider FileProvider) http.HandlerFunc {

writer.Header().Add("Content-Type", mimeType)
writer.Header().Add("X-Content-Type-Options", "nosniff")
if !canEmbed(mimeType) {
if !markdown.CanEmbed(mimeType) {
writer.Header().Add("Content-Disposition", "attachment")
}
_, _ = io.Copy(writer, reader)
Expand Down
19 changes: 16 additions & 3 deletions markdown/embeds.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,23 @@ const (
image mediaType = iota
video
audio
pdf
)

var mimePrefixes = map[string]mediaType{
"image/": image,
"video/": video,
"audio/": audio,
"image/": image,
"video/": video,
"audio/": audio,
"application/pdf": pdf,
}

func CanEmbed(mimeType string) bool {
for m, _ := range mimePrefixes {
if strings.HasPrefix(mimeType, m) {
return true
}
}
return false
}

type mediaEmbed struct {
Expand Down Expand Up @@ -117,6 +128,8 @@ func (m mediaRenderer) render(w util.BufWriter, source []byte, n ast.Node, enter
_, _ = w.WriteString(fmt.Sprintf(`<audio controls src="%s" class="embed">`, embed.file))
case video:
_, _ = w.WriteString(fmt.Sprintf(`<video controls src="%s" class="embed">`, embed.file))
case pdf:
_, _ = w.WriteString(fmt.Sprintf(`<iframe src="%s" class="embed"></iframe>`, embed.file))
}

return ast.WalkContinue, nil
Expand Down
5 changes: 5 additions & 0 deletions resources/static/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -282,3 +282,8 @@ blockquote > p:last-child {
max-width: 200px;
max-height: 200px;
}

iframe.embed {
width: 100%;
height: 100vh;
}

0 comments on commit 68231e7

Please sign in to comment.