alps/plugins/viewhtml/viewer.go

66 lines
1.6 KiB
Go
Raw Normal View History

2020-05-13 12:07:44 +00:00
package alpsviewhtml
2020-02-12 13:42:51 +00:00
import (
"bytes"
"fmt"
"html/template"
"io/ioutil"
"strings"
2020-05-13 12:07:44 +00:00
"git.sr.ht/~emersion/alps"
alpsbase "git.sr.ht/~emersion/alps/plugins/base"
2020-02-12 13:42:51 +00:00
"github.com/emersion/go-message"
)
2020-02-25 08:51:57 +00:00
const tplSrc = `
2020-02-12 13:42:51 +00:00
<!-- allow-same-origin is required to resize the frame with its content -->
<!-- allow-popups is required for target="_blank" links -->
<iframe id="email-frame" srcdoc="{{.}}" sandbox="allow-same-origin allow-popups"></iframe>
<script src="/plugins/viewhtml/assets/script.js"></script>
<link rel="stylesheet" href="/plugins/viewhtml/assets/style.css">
`
2020-02-25 08:51:57 +00:00
var tpl = template.Must(template.New("view-html.html").Parse(tplSrc))
2020-02-12 13:42:51 +00:00
type viewer struct{}
2020-05-13 12:07:44 +00:00
func (viewer) ViewMessagePart(ctx *alps.Context, msg *alpsbase.IMAPMessage, part *message.Entity) (interface{}, error) {
allowRemoteResources := ctx.QueryParam("allow-remote-resources") == "1"
2020-02-12 13:42:51 +00:00
mimeType, _, err := part.Header.ContentType()
if err != nil {
return nil, err
}
if !strings.EqualFold(mimeType, "text/html") {
2020-05-13 12:07:44 +00:00
return nil, alpsbase.ErrViewUnsupported
2020-02-12 13:42:51 +00:00
}
body, err := ioutil.ReadAll(part.Body)
if err != nil {
return nil, fmt.Errorf("failed to read part body: %v", err)
}
san := sanitizer{
msg: msg,
allowRemoteResources: allowRemoteResources,
}
2020-02-25 08:51:57 +00:00
body, err = san.sanitizeHTML(body)
2020-02-12 13:42:51 +00:00
if err != nil {
return nil, fmt.Errorf("failed to sanitize HTML part: %v", err)
}
ctx.Set("viewhtml.hasRemoteResources", san.hasRemoteResources)
2020-02-12 13:42:51 +00:00
var buf bytes.Buffer
2020-02-25 08:51:57 +00:00
err = tpl.Execute(&buf, string(body))
2020-02-12 13:42:51 +00:00
if err != nil {
return nil, err
}
return template.HTML(buf.String()), nil
}
func init() {
2020-05-13 12:07:44 +00:00
alpsbase.RegisterViewer(viewer{})
2020-02-12 13:42:51 +00:00
}