429 lines
13 KiB
Go
429 lines
13 KiB
Go
package backend
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"html"
|
|
"io"
|
|
"net/http"
|
|
"net/mail"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
// Der Viewer betrachtet die LOKALEN mbox-Dateien im Browser (Outlook-2013-
|
|
// Dreispalter): links Konto/Ordner-Baum, Mitte Nachrichtenliste, rechts
|
|
// Lesebereich. Optional Weiterleiten einzelner Mails per SMTP (09-smtp.go).
|
|
|
|
func viewerHandler(w http.ResponseWriter, r *http.Request) {
|
|
account := r.URL.Query().Get("account")
|
|
folder := r.URL.Query().Get("folder")
|
|
q := strings.TrimSpace(r.URL.Query().Get("q"))
|
|
if account != "" && folder != "" {
|
|
renderMessageList(w, account, folder, q)
|
|
return
|
|
}
|
|
if r.Header.Get("HX-Request") == "true" {
|
|
renderViewerTree(w)
|
|
return
|
|
}
|
|
renderShell(w, "", `<div class="ef-empty">Backup-Postfach links waehlen.</div>`)
|
|
}
|
|
|
|
func messageHandler(w http.ResponseWriter, r *http.Request) {
|
|
account := r.URL.Query().Get("account")
|
|
folder := r.URL.Query().Get("folder")
|
|
targetAccount := r.URL.Query().Get("target_account")
|
|
index, err := strconv.Atoi(r.URL.Query().Get("index"))
|
|
if err != nil {
|
|
http.Error(w, "bad index", http.StatusBadRequest)
|
|
return
|
|
}
|
|
path, err := mboxPath(account, folder)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
raw, err := ReadMboxMessage(path, index)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusNotFound)
|
|
return
|
|
}
|
|
msg, err := mail.ReadMessage(bytes.NewReader(raw))
|
|
if err != nil {
|
|
renderReadPanePair(w, account, folder, targetAccount, index, raw, "(unlesbar)", "", "", string(raw))
|
|
return
|
|
}
|
|
renderReadPanePair(w, account, folder, targetAccount, index, raw,
|
|
decodeHeader(msg.Header.Get("Subject")),
|
|
decodeHeader(msg.Header.Get("From")),
|
|
decodeHeader(msg.Header.Get("Date")),
|
|
messageBody(raw),
|
|
)
|
|
}
|
|
|
|
func targetMessageHandler(w http.ResponseWriter, r *http.Request) {
|
|
account := r.URL.Query().Get("account")
|
|
folder := r.URL.Query().Get("folder")
|
|
targetAccount := r.URL.Query().Get("target_account")
|
|
index, err := strconv.Atoi(r.URL.Query().Get("index"))
|
|
if err != nil {
|
|
http.Error(w, "bad index", http.StatusBadRequest)
|
|
return
|
|
}
|
|
path, err := mboxPath(account, folder)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
raw, err := ReadMboxMessage(path, index)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusNotFound)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
fmt.Fprint(w, renderTargetPane(account, folder, targetAccount, index, raw))
|
|
}
|
|
|
|
func forwardHandler(w http.ResponseWriter, r *http.Request) {
|
|
// TODO Codex: GET = Weiterleiten-Formular (An/Betreff/Text), POST =
|
|
// ForwardMessage() aufrufen. NUR hier kommt SMTP zum Einsatz -- der Umzug
|
|
// selbst nutzt IMAP APPEND.
|
|
}
|
|
|
|
func renderViewerTree(w http.ResponseWriter) {
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
fmt.Fprint(w, `<div class="pane-head">Originale</div>`)
|
|
entries, err := os.ReadDir(Cfg.MboxRoot)
|
|
if err != nil {
|
|
fmt.Fprintf(w, `<div class="ef-empty">%s</div>`, html.EscapeString(err.Error()))
|
|
return
|
|
}
|
|
found := false
|
|
for _, entry := range entries {
|
|
if !entry.IsDir() {
|
|
continue
|
|
}
|
|
account := entry.Name()
|
|
mboxes, _ := filepath.Glob(filepath.Join(Cfg.MboxRoot, account, "*.mbox"))
|
|
if len(mboxes) == 0 {
|
|
continue
|
|
}
|
|
found = true
|
|
fmt.Fprintf(w, `<div class="tree-node account">%s</div>`, html.EscapeString(sourceAccountLabel(account)))
|
|
for _, path := range mboxes {
|
|
folder := strings.TrimSuffix(filepath.Base(path), ".mbox")
|
|
fmt.Fprintf(w, `<a class="tree-node" href="/view?account=%s&folder=%s" hx-get="/view?account=%s&folder=%s" hx-target="#list" hx-swap="innerHTML">%s</a>`,
|
|
urlEsc(account), urlEsc(folder), urlEsc(account), urlEsc(folder), html.EscapeString(folder))
|
|
}
|
|
}
|
|
if !found {
|
|
fmt.Fprint(w, `<div class="ef-empty">Noch keine mbox-Backups.</div>`)
|
|
}
|
|
}
|
|
|
|
func renderMessageList(w http.ResponseWriter, account, folder, q string) {
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
path, err := mboxPath(account, folder)
|
|
if err != nil {
|
|
fmt.Fprintf(w, `<div class="pane-head">Nachrichten</div><div class="ef-empty">%s</div>`, html.EscapeString(err.Error()))
|
|
return
|
|
}
|
|
entries, err := ReadMboxList(path)
|
|
if err != nil {
|
|
fmt.Fprintf(w, `<div class="pane-head">Nachrichten</div><div class="ef-empty">%s</div>`, html.EscapeString(err.Error()))
|
|
return
|
|
}
|
|
filtered := entries
|
|
if q != "" {
|
|
filtered = filterEntries(path, entries, q)
|
|
}
|
|
fmt.Fprintf(w, `<div class="pane-head">%s / %s (%d)</div>`, html.EscapeString(account), html.EscapeString(folder), len(filtered))
|
|
fmt.Fprintf(w, `<form class="searchbar" hx-get="/view" hx-target="#list" hx-swap="innerHTML">
|
|
<input type="hidden" name="account" value="%s">
|
|
<input type="hidden" name="folder" value="%s">
|
|
<input class="input search-input" type="search" name="q" value="%s" placeholder="Suchen">
|
|
<button class="btn secondary search-btn" type="submit">Suchen</button>
|
|
</form>`, html.EscapeString(account), html.EscapeString(folder), html.EscapeString(q))
|
|
for _, entry := range filtered {
|
|
subject := entry.Subject
|
|
if subject == "" {
|
|
subject = "(ohne Betreff)"
|
|
}
|
|
from := entry.From
|
|
if from == "" {
|
|
from = "(ohne Absender)"
|
|
}
|
|
fmt.Fprintf(w, `<a class="msg-row" href="/view/message?account=%s&folder=%s&index=%d" hx-get="/view/message?account=%s&folder=%s&index=%d" hx-include="#target-account-select" hx-target="#read" hx-swap="innerHTML"><span class="msg-from">%s</span><span class="msg-subject">%s</span><span class="msg-date">%s</span></a>`,
|
|
urlEsc(account), urlEsc(folder), entry.Index, urlEsc(account), urlEsc(folder), entry.Index,
|
|
html.EscapeString(from), html.EscapeString(subject), html.EscapeString(entry.Date))
|
|
}
|
|
if len(entries) == 0 {
|
|
fmt.Fprint(w, `<div class="ef-empty">Keine Nachrichten in dieser mbox.</div>`)
|
|
} else if len(filtered) == 0 {
|
|
fmt.Fprint(w, `<div class="ef-empty">Keine Treffer.</div>`)
|
|
}
|
|
}
|
|
|
|
func renderReadPanePair(w http.ResponseWriter, account, folder, targetAccount string, index int, raw []byte, subject, from, date, body string) {
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
renderReadPane(w, "Original", subject, from, date, body)
|
|
targetHTML := renderTargetPane(account, folder, targetAccount, index, raw)
|
|
fmt.Fprintf(w, `<div id="read-target" hx-swap-oob="innerHTML">%s</div>`, targetHTML)
|
|
}
|
|
|
|
func renderReadPane(w io.Writer, title, subject, from, date, body string) {
|
|
if subject == "" {
|
|
subject = "(ohne Betreff)"
|
|
}
|
|
fmt.Fprintf(w, `<div class="pane-head">%s</div><div class="read-body"><div class="read-head"><h1 class="read-subject">%s</h1><div class="read-meta">Von: %s<br>Datum: %s</div></div><pre class="read-pre">%s</pre></div>`,
|
|
html.EscapeString(title), html.EscapeString(subject), html.EscapeString(from), html.EscapeString(date), html.EscapeString(body))
|
|
}
|
|
|
|
func renderTargetPane(account, folder, targetAccount string, index int, raw []byte) string {
|
|
var b strings.Builder
|
|
b.WriteString(renderTargetAccountSelect(account, folder, targetAccount, index))
|
|
match, ok := findForwardedCopy(account, targetAccount, raw)
|
|
if !ok {
|
|
id := messageIDHeader(raw)
|
|
if id == "" {
|
|
id = "(ohne Message-ID)"
|
|
}
|
|
fmt.Fprintf(&b, `<div class="ef-empty">Keine lokale Zielkopie gefunden.<br><br>Message-ID: %s</div>`, html.EscapeString(id))
|
|
return b.String()
|
|
}
|
|
msg, err := mail.ReadMessage(bytes.NewReader(match.Raw))
|
|
if err != nil {
|
|
renderReadContent(&b, "(unlesbar)", match.Location(), "", string(match.Raw))
|
|
return b.String()
|
|
}
|
|
renderReadContent(&b,
|
|
decodeHeader(msg.Header.Get("Subject")),
|
|
decodeHeader(msg.Header.Get("From")),
|
|
decodeHeader(msg.Header.Get("Date"))+" | "+match.Location(),
|
|
messageBody(match.Raw),
|
|
)
|
|
return b.String()
|
|
}
|
|
|
|
func renderInitialTargetPane() string {
|
|
var b strings.Builder
|
|
b.WriteString(renderTargetAccountSelect("", "", "", -1))
|
|
b.WriteString(`<div class="read-body"><div class="ef-empty">Nachricht waehlen.</div></div>`)
|
|
return b.String()
|
|
}
|
|
|
|
func renderReadContent(w io.Writer, subject, from, date, body string) {
|
|
if subject == "" {
|
|
subject = "(ohne Betreff)"
|
|
}
|
|
fmt.Fprintf(w, `<div class="read-body"><div class="read-head"><h1 class="read-subject">%s</h1><div class="read-meta">Von: %s<br>Datum: %s</div></div><pre class="read-pre">%s</pre></div>`,
|
|
html.EscapeString(subject), html.EscapeString(from), html.EscapeString(date), html.EscapeString(body))
|
|
}
|
|
|
|
func mboxPath(account, folder string) (string, error) {
|
|
if account == "" || folder == "" || strings.Contains(account, "..") || strings.Contains(folder, "..") {
|
|
return "", fmt.Errorf("ungueltiges Postfach")
|
|
}
|
|
root, err := filepath.Abs(Cfg.MboxRoot)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
path, err := filepath.Abs(filepath.Join(root, account, safeMboxName(folder)+".mbox"))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
rel, err := filepath.Rel(root, path)
|
|
if err != nil || strings.HasPrefix(rel, "..") {
|
|
return "", fmt.Errorf("ungueltiger mbox-Pfad")
|
|
}
|
|
return path, nil
|
|
}
|
|
|
|
func urlEsc(s string) string {
|
|
r := strings.NewReplacer("%", "%25", " ", "%20", "&", "%26", "?", "%3F", "#", "%23", "+", "%2B", "/", "%2F")
|
|
return r.Replace(s)
|
|
}
|
|
|
|
func filterEntries(path string, entries []MboxEntry, q string) []MboxEntry {
|
|
needle := strings.ToLower(strings.TrimSpace(q))
|
|
if needle == "" {
|
|
return entries
|
|
}
|
|
var out []MboxEntry
|
|
for _, entry := range entries {
|
|
hay := strings.ToLower(entry.From + " " + entry.Subject + " " + entry.Date)
|
|
if strings.Contains(hay, needle) {
|
|
out = append(out, entry)
|
|
continue
|
|
}
|
|
raw, err := ReadMboxMessage(path, entry.Index)
|
|
if err == nil && strings.Contains(strings.ToLower(messageBody(raw)), needle) {
|
|
out = append(out, entry)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
type forwardedMatch struct {
|
|
Account string
|
|
Folder string
|
|
Index int
|
|
Raw []byte
|
|
}
|
|
|
|
func (m forwardedMatch) Location() string {
|
|
return fmt.Sprintf("%s / %s #%d", m.Account, m.Folder, m.Index)
|
|
}
|
|
|
|
func findForwardedCopy(account, targetAccount string, raw []byte) (forwardedMatch, bool) {
|
|
id := messageIDHeader(raw)
|
|
if id == "" {
|
|
return forwardedMatch{}, false
|
|
}
|
|
entries, err := os.ReadDir(Cfg.MboxRoot)
|
|
if err != nil {
|
|
return forwardedMatch{}, false
|
|
}
|
|
for _, entry := range entries {
|
|
if !entry.IsDir() || entry.Name() == account {
|
|
continue
|
|
}
|
|
if targetAccount != "" && entry.Name() != targetAccount {
|
|
continue
|
|
}
|
|
mboxes, _ := filepath.Glob(filepath.Join(Cfg.MboxRoot, entry.Name(), "*.mbox"))
|
|
for _, path := range mboxes {
|
|
msgs, err := ReadMboxList(path)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
for _, msg := range msgs {
|
|
candidate, err := ReadMboxMessage(path, msg.Index)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
if messageIDHeader(candidate) == id {
|
|
return forwardedMatch{
|
|
Account: entry.Name(),
|
|
Folder: strings.TrimSuffix(filepath.Base(path), ".mbox"),
|
|
Index: msg.Index,
|
|
Raw: candidate,
|
|
}, true
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return forwardedMatch{}, false
|
|
}
|
|
|
|
func messageIDHeader(raw []byte) string {
|
|
msg, err := mail.ReadMessage(bytes.NewReader(raw))
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
return strings.TrimSpace(msg.Header.Get("Message-ID"))
|
|
}
|
|
|
|
func renderTargetAccountSelect(account, folder, selected string, index int) string {
|
|
accounts := viewerAccounts()
|
|
if selected == account {
|
|
selected = ""
|
|
}
|
|
var b strings.Builder
|
|
fmt.Fprintf(&b, `<div class="pane-head target-head"><span>Zielkopie</span><form class="target-select-form"`)
|
|
if account != "" && folder != "" && index >= 0 {
|
|
fmt.Fprintf(&b, ` hx-get="/view/target" hx-target="#read-target" hx-swap="innerHTML" hx-trigger="change from:#target-account-select"`)
|
|
}
|
|
fmt.Fprintf(&b, `>
|
|
<input type="hidden" name="account" value="%s">
|
|
<input type="hidden" name="folder" value="%s">
|
|
<input type="hidden" name="index" value="%d">
|
|
<select id="target-account-select" name="target_account" class="target-select">
|
|
<option value="">Automatisch</option>`, html.EscapeString(account), html.EscapeString(folder), index)
|
|
for _, a := range accounts {
|
|
if a.Name == account {
|
|
continue
|
|
}
|
|
attr := ""
|
|
if a.Name == selected {
|
|
attr = ` selected`
|
|
}
|
|
fmt.Fprintf(&b, `<option value="%s"%s>%s</option>`, html.EscapeString(a.Name), attr, html.EscapeString(a.TargetLabel))
|
|
}
|
|
b.WriteString(`</select></form></div>`)
|
|
return b.String()
|
|
}
|
|
|
|
type viewerAccount struct {
|
|
Name string
|
|
SourceLabel string
|
|
TargetLabel string
|
|
}
|
|
|
|
func viewerAccounts() []viewerAccount {
|
|
labels := accountLabels()
|
|
entries, err := os.ReadDir(Cfg.MboxRoot)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
var out []viewerAccount
|
|
for _, entry := range entries {
|
|
if !entry.IsDir() {
|
|
continue
|
|
}
|
|
mboxes, _ := filepath.Glob(filepath.Join(Cfg.MboxRoot, entry.Name(), "*.mbox"))
|
|
if len(mboxes) == 0 {
|
|
continue
|
|
}
|
|
a := labels[entry.Name()]
|
|
if a.Name == "" {
|
|
a = viewerAccount{Name: entry.Name(), SourceLabel: entry.Name(), TargetLabel: entry.Name()}
|
|
}
|
|
out = append(out, a)
|
|
}
|
|
return out
|
|
}
|
|
|
|
func sourceAccountLabel(mboxDir string) string {
|
|
if a := accountLabels()[mboxDir]; a.SourceLabel != "" {
|
|
return a.SourceLabel
|
|
}
|
|
return mboxDir
|
|
}
|
|
|
|
func accountLabels() map[string]viewerAccount {
|
|
out := map[string]viewerAccount{}
|
|
if DB == nil {
|
|
return out
|
|
}
|
|
accounts, err := ListAccounts()
|
|
if err != nil {
|
|
return out
|
|
}
|
|
for _, a := range accounts {
|
|
dir := accountMboxDir(a)
|
|
source := a.SrcUser
|
|
if source == "" {
|
|
source = a.Name
|
|
}
|
|
target := a.DstUser
|
|
if target == "" {
|
|
target = a.Name
|
|
}
|
|
if a.Name != "" {
|
|
target = target + " (" + a.Name + ")"
|
|
}
|
|
out[dir] = viewerAccount{Name: dir, SourceLabel: source, TargetLabel: target}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func accountMboxDir(a Account) string {
|
|
if strings.TrimSpace(a.MboxDir) != "" {
|
|
return a.MboxDir
|
|
}
|
|
return a.Name
|
|
}
|