Files
Docwell/Server/internal/convert/mht.go
T
tajniak81andClaude Opus 5.5 3d1cf362d7 Add calendars, a web clipper, more importers and workspace snapshots
Phase F of the AFFiNE plan (ADR-16):

- Calendars: people subscribe to iCal feeds (webcal, Google's secret
  address, Outlook) or CalDAV accounts in account settings; their
  events show at the top of journal pages in the reader's time zone.
  Repeats, moved and cancelled occurrences, IANA and Windows zones
  are handled. Events are read on demand and kept in memory for 15
  minutes; passwords are sealed with DOCWELL_SECRET_KEY; sources
  follow the webhook address rules. New calendar_accounts collection.
- Importers: zips of Markdown (Obsidian vaults, Bear TextBundles and
  .bear2bk, Readwise's Markdown, Docwell's own space export) keep
  folders as pages, resolve [[wikilinks]] and embeds by name, and turn
  front matter and #tags into properties and tags. OneNote .mht
  exports, Readwise CSV, and any other CSV as a database page.
- Exports: PNG of a page drawn in the browser, print styles that print
  only the page in the light theme, and workspace snapshots (records,
  Yjs states, JSON and files in one zip) that restore as a new
  workspace. Old ids are swapped byte for byte inside the Yjs updates,
  so links point at the restored pages and comments stay anchored.
- Web-Clipper/: a Manifest V3 extension for Chrome, Edge and Firefox
  that saves the article or the selection as Markdown through the
  import API with a personal API token.
- OpenAPI, generated clients, translations and user docs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 11:56:03 +01:00

277 lines
7.3 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package convert
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"io"
"mime"
"mime/multipart"
"mime/quotedprintable"
"net/mail"
"net/textproto"
"net/url"
"path"
"strings"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
"golang.org/x/net/html/charset"
)
// ---- MHTML: OneNote pages and sections, saved web pages --------------------
//
// OneNote exports a page or a section as a "Single File Web Page" (.mht): a
// MIME message whose parts are the page's HTML and its images. A section
// holds one HTML part per page next to a frameset that shows them; each
// becomes a page. Browsers save pages as .mhtml the same way.
// ErrNotMHT is returned for a file that is not an MHTML archive.
var ErrNotMHT = errors.New("not an MHTML (.mht) file")
const (
maxMHTParts = 5000
maxMHTPart = 50 << 20
)
type mhtPart struct {
mime string
location string // Content-Location, as written
id string // Content-ID without the angle brackets
data []byte
page int // index of the page an HTML part became, or -1
}
// ReadMHT reads an MHTML archive into pages (one per HTML part, frames
// left out) and the files they use. name is the file's name, used as the
// title of a page without one.
func ReadMHT(data []byte, name string) ([]NotionPage, []Asset, error) {
msg, err := mail.ReadMessage(bytes.NewReader(bytes.TrimLeft(data, "\r\n\t ")))
if err != nil {
return nil, nil, ErrNotMHT
}
parts, err := mhtParts(textproto.MIMEHeader(msg.Header), msg.Body)
if err != nil {
return nil, nil, err
}
var pages []NotionPage
var assets []Asset
assetOf := map[int]string{}
for i := range parts {
parts[i].page = -1
if parts[i].mime != "text/html" || isFrameset(parts[i].data) {
continue
}
parts[i].page = len(pages)
pages = append(pages, NotionPage{Parent: -1})
}
if len(pages) == 0 {
return nil, nil, ErrNotMHT
}
if len(pages) > maxNotionPages {
return nil, nil, fmt.Errorf("the file has more than %d pages", maxNotionPages)
}
find := func(base *url.URL, raw string) int {
raw = strings.TrimSpace(raw)
if id, ok := strings.CutPrefix(raw, "cid:"); ok {
for i, p := range parts {
if p.id != "" && p.id == id {
return i
}
}
return -1
}
u, err := url.Parse(raw)
if err != nil {
return -1
}
if base != nil {
u = base.ResolveReference(u)
}
for i, p := range parts {
if p.location != "" && (p.location == raw || p.location == u.String()) {
return i
}
}
// Last, by file name: exporters write the same file in several ways.
want := strings.ToLower(path.Base(u.Path))
for i, p := range parts {
if p.location == "" || want == "" || want == "/" {
continue
}
if l, err := url.Parse(p.location); err == nil && strings.ToLower(path.Base(l.Path)) == want {
return i
}
}
return -1
}
for _, p := range parts {
if p.page < 0 {
continue
}
base, _ := url.Parse(p.location)
if p.location == "" {
base = nil
}
opts := ImportOptions{Resolve: func(raw string) (string, bool) {
i := find(base, raw)
switch {
case i < 0:
if strings.HasPrefix(strings.ToLower(raw), "http") || strings.HasPrefix(raw, "mailto:") {
return "", false
}
return "", true // A file the archive does not hold (file:///C:/…).
case parts[i].page >= 0:
return PageRef(parts[i].page), true
}
if ref, ok := assetOf[i]; ok {
return ref, true
}
ref := AssetRef(len(assets))
assets = append(assets, Asset{Ref: ref, Name: partName(parts[i], len(assets)), Data: parts[i].data})
assetOf[i] = ref
return ref, true
}}
doc, err := FromHTMLWith(string(p.data), opts)
if err != nil {
return nil, nil, err
}
title := htmlTitle(p.data)
if h1, rest := Title(doc); h1 != "" && (title == "" || strings.EqualFold(strings.TrimSpace(h1), title)) {
title, doc = h1, rest
}
if strings.TrimSpace(title) == "" {
title = strings.TrimSuffix(path.Base(name), path.Ext(name))
}
if len(doc.Content) == 0 {
doc.Content = []Node{{Type: "paragraph"}}
}
pages[p.page] = NotionPage{Title: strings.TrimSpace(title), Parent: -1, Doc: doc}
}
return pages, assets, nil
}
// mhtParts reads every leaf part of the message (nested multiparts too).
func mhtParts(h textproto.MIMEHeader, body io.Reader) ([]mhtPart, error) {
var out []mhtPart
var walk func(h textproto.MIMEHeader, body io.Reader, depth int) error
walk = func(h textproto.MIMEHeader, body io.Reader, depth int) error {
mt, params, err := mime.ParseMediaType(h.Get("Content-Type"))
if err != nil {
mt = "text/html"
}
if strings.HasPrefix(mt, "multipart/") {
if depth > 3 || params["boundary"] == "" {
return ErrNotMHT
}
mr := multipart.NewReader(body, params["boundary"])
for {
p, err := mr.NextRawPart()
if err == io.EOF {
return nil
}
if err != nil {
return fmt.Errorf("the file is damaged: %w", err)
}
if err := walk(p.Header, p, depth+1); err != nil {
return err
}
}
}
if len(out) >= maxMHTParts {
return ErrTooLarge
}
data, err := decodePart(h, body)
if err != nil {
return err
}
if mt == "text/html" {
if cs := params["charset"]; cs != "" && !strings.EqualFold(cs, "utf-8") {
if r, err := charset.NewReaderLabel(cs, bytes.NewReader(data)); err == nil {
if conv, err := io.ReadAll(io.LimitReader(r, maxMHTPart)); err == nil {
data = conv
}
}
}
}
out = append(out, mhtPart{
mime: mt, location: strings.TrimSpace(h.Get("Content-Location")),
id: strings.Trim(strings.TrimSpace(h.Get("Content-ID")), "<>"), data: data,
})
return nil
}
if err := walk(h, body, 0); err != nil {
return nil, err
}
return out, nil
}
func decodePart(h textproto.MIMEHeader, body io.Reader) ([]byte, error) {
r := body
switch strings.ToLower(strings.TrimSpace(h.Get("Content-Transfer-Encoding"))) {
case "base64":
r = base64.NewDecoder(base64.StdEncoding, &skipSpace{r: body})
case "quoted-printable":
r = quotedprintable.NewReader(body)
}
data, err := io.ReadAll(io.LimitReader(r, maxMHTPart+1))
if err != nil {
return nil, fmt.Errorf("the file is damaged: %w", err)
}
if len(data) > maxMHTPart {
return nil, ErrTooLarge
}
return data, nil
}
// skipSpace drops the line breaks base64 bodies are wrapped with.
type skipSpace struct{ r io.Reader }
func (s *skipSpace) Read(p []byte) (int, error) {
for {
n, err := s.r.Read(p)
j := 0
for _, b := range p[:n] {
if b != '\r' && b != '\n' && b != ' ' && b != '\t' {
p[j] = b
j++
}
}
if j > 0 || err != nil {
return j, err
}
}
}
func isFrameset(data []byte) bool {
return bytes.Contains(bytes.ToLower(data[:min(len(data), 4096)]), []byte("<frameset"))
}
func htmlTitle(data []byte) string {
root, err := html.Parse(bytes.NewReader(data))
if err != nil {
return ""
}
if t := find(root, atom.Title); t != nil {
return strings.TrimSpace(whitespace.ReplaceAllString(textOf(t), " "))
}
return ""
}
// partName is a file name for a part, from its location or its type.
func partName(p mhtPart, n int) string {
if u, err := url.Parse(p.location); err == nil && p.location != "" {
if b := path.Base(strings.ReplaceAll(u.Path, "\\", "/")); b != "" && b != "." && b != "/" {
return b
}
}
ext := ".bin"
if exts, _ := mime.ExtensionsByType(p.mime); len(exts) > 0 {
ext = exts[0]
}
return fmt.Sprintf("file-%d%s", n+1, ext)
}