Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
Read MHTML web archives: the saved page as one HTML file, and on to PDF, DOCX and HWPX
KnifeLemon48c60d60075b
diff --git a/README.ko.md b/README.ko.mdindex 1b188d0b..209495b6 100644--- a/README.ko.md+++ b/README.ko.md@@ -34,7 +34,7 @@<table><tr><td width="33%" valign="top"><b>커서 바로 옆에서</b><br>앱 창을 열 필요가 없어요. 끌고 있는 파일에 맞는 형식만 지금 있는 자리에 나타나요.</td>- <td width="33%" valign="top"><b>246가지 형식, 다른 프로그램 없이</b><br>이미지, PDF, 워드, 엑셀, 파워포인트, HWP, 전자책, 압축 파일, 글꼴, CAD, 3D 모델을 오피스·한컴오피스·LibreOffice 없이 변환해요.</td>+ <td width="33%" valign="top"><b>247가지 형식, 다른 프로그램 없이</b><br>이미지, PDF, 워드, 엑셀, 파워포인트, HWP, 전자책, 압축 파일, 글꼴, CAD, 3D 모델을 오피스·한컴오피스·LibreOffice 없이 변환해요.</td><td width="33%" valign="top"><b>내 컴퓨터 안에서만</b><br>아무것도 업로드하지 않아요. 오프라인으로 동작하고 결과는 원본 옆에 저장해요.</td></tr></table>@@ -93,7 +93,7 @@| **스프레드시트**: XLSX, XLSM, XLS, XLT, ODS, CSV, TSV · OTS, FODS, Numbers, ET² | PDF, XLSX, ODS, CSV, TSV, JSON, HWPX, HTML · XLT, OTS² || **프레젠테이션**: PPTX, PPTM, POTX, PPSX · PPT, ODP, OTP, FODP, Keynote² | PDF, PNG, JPG, DOCX, HWPX · OTP² || **한글**: HWP, HWPX | PDF, PNG, DOCX, HWPX ↔ HWP, TXT, 마크다운, HTML |-| **텍스트**: TXT, 마크다운, HTML · reStructuredText, LaTeX, Org, AsciiDoc, Typst, MediaWiki, DocBook, Jupyter, Textile, man, OPML³ | PDF, DOCX, HWPX, EPUB · 서로 변환, PPTX 슬라이드³ |+| **텍스트**: TXT, 마크다운, HTML; MHTML(저장한 웹 페이지)은 읽기 · reStructuredText, LaTeX, Org, AsciiDoc, Typst, MediaWiki, DocBook, Jupyter, Textile, man, OPML³ | PDF, DOCX, HWPX, EPUB · 서로 변환, PPTX 슬라이드³ || **전자책**: EPUB, KEPUB, MOBI, AZW3, AZW, AZW4, FB2, CBZ, CBR, CB7, HTMLZ, TXTZ · LIT, LRF, CHM, PDB 등⁴ | PDF, EPUB, KEPUB(코보), DOCX, TXT, HTML, HWPX · MOBI, AZW3⁴ || **동영상**⁵: MP4, MOV, MKV, WEBM, AVI, WMV, FLV, MPEG, TS, M2TS, 3GP, OGV, VOB 등 | MP4(H.264, HEVC, AV1), WEBM, MOV, MKV, AVI, GIF, APNG, MP3, M4A, 720p, 자막(SRT, ASS, WebVTT) || **오디오**⁵: MP3, M4A, AAC, WAV, FLAC, OGG, OPUS, WMA, AIFF, AMR, APE, WavPack, TTA, DSD(DSF, DFF), DTS, AC3, E-AC3 등 | MP3, M4A(AAC, ALAC), WAV, FLAC, OGG, OPUS, AAC, WavPack, TTA, W64, AC3, E-AC3 |diff --git a/README.md b/README.mdindex da6549e4..fd6b1ae9 100644--- a/README.md+++ b/README.md@@ -34,7 +34,7 @@<table><tr><td width="33%" valign="top"><b>Right at your cursor</b><br>No app window to open. The formats appear where you already are, only the ones that make sense for the files you drag.</td>- <td width="33%" valign="top"><b>246 formats, no other software</b><br>Images, PDF, Word, Excel, PowerPoint, HWP, e-books, archives, fonts, CAD and 3D models work without Office, Hancom Office or LibreOffice.</td>+ <td width="33%" valign="top"><b>247 formats, no other software</b><br>Images, PDF, Word, Excel, PowerPoint, HWP, e-books, archives, fonts, CAD and 3D models work without Office, Hancom Office or LibreOffice.</td><td width="33%" valign="top"><b>Stays on your computer</b><br>Nothing is uploaded. Filee works offline and saves the result next to the original.</td></tr></table>@@ -93,7 +93,7 @@ Filee shows new releases in its menu and updates itself, keeping your settings a| **Spreadsheets**: XLSX, XLSM, XLS, XLT, ODS, CSV, TSV · OTS, FODS, Numbers, ET² | PDF, XLSX, ODS, CSV, TSV, JSON, HWPX, HTML · XLT, OTS² || **Presentations**: PPTX, PPTM, POTX, PPSX · PPT, ODP, OTP, FODP, Keynote² | PDF, PNG, JPG, DOCX, HWPX · OTP² || **HWP**: HWP, HWPX | PDF, PNG, DOCX, HWPX ↔ HWP, TXT, Markdown, HTML |-| **Text**: TXT, Markdown, HTML · reStructuredText, LaTeX, Org, AsciiDoc, Typst, MediaWiki, DocBook, Jupyter, Textile, man, OPML³ | PDF, DOCX, HWPX, EPUB · each other, PPTX slides³ |+| **Text**: TXT, Markdown, HTML; MHTML (saved web pages) read · reStructuredText, LaTeX, Org, AsciiDoc, Typst, MediaWiki, DocBook, Jupyter, Textile, man, OPML³ | PDF, DOCX, HWPX, EPUB · each other, PPTX slides³ || **E-books**: EPUB, KEPUB, MOBI, AZW3, AZW, AZW4, FB2, CBZ, CBR, CB7, HTMLZ, TXTZ · LIT, LRF, CHM, PDB, …⁴ | PDF, EPUB, KEPUB (Kobo), DOCX, TXT, HTML, HWPX · MOBI, AZW3⁴ || **Video**⁵: MP4, MOV, MKV, WEBM, AVI, WMV, FLV, MPEG, TS, M2TS, 3GP, OGV, VOB, … | MP4 (H.264, HEVC, AV1), WEBM, MOV, MKV, AVI, GIF, APNG, MP3, M4A, 720p, subtitles (SRT, ASS, WebVTT) || **Audio**⁵: MP3, M4A, AAC, WAV, FLAC, OGG, OPUS, WMA, AIFF, AMR, APE, WavPack, TTA, DSD (DSF, DFF), DTS, AC3, E-AC3, … | MP3, M4A (AAC, ALAC), WAV, FLAC, OGG, OPUS, AAC, WavPack, TTA, W64, AC3, E-AC3 |diff --git a/README.zh-CN.md b/README.zh-CN.mdindex afff399d..ab428d2b 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -34,7 +34,7 @@<table><tr><td width="33%" valign="top"><b>就在光标旁</b><br>无需打开应用窗口。只显示适合当前拖动文件的格式,就在你所在的位置。</td>- <td width="33%" valign="top"><b>246 种格式,无需其他软件</b><br>图片、PDF、Word、Excel、PowerPoint、HWP、电子书、压缩包、字体、CAD 和 3D 模型,无需 Office、韩文办公软件或 LibreOffice。</td>+ <td width="33%" valign="top"><b>247 种格式,无需其他软件</b><br>图片、PDF、Word、Excel、PowerPoint、HWP、电子书、压缩包、字体、CAD 和 3D 模型,无需 Office、韩文办公软件或 LibreOffice。</td><td width="33%" valign="top"><b>只在你的电脑上</b><br>不上传任何文件。Filee 离线工作,结果保存在原文件旁边。</td></tr></table>@@ -92,7 +92,7 @@| **表格**:XLSX、XLSM、XLS、XLT、ODS、CSV、TSV · OTS、FODS、Numbers、ET² | PDF、XLSX、ODS、CSV、TSV、JSON、HWPX、HTML · XLT、OTS² || **演示文稿**:PPTX、PPTM、POTX、PPSX · PPT、ODP、OTP、FODP、Keynote² | PDF、PNG、JPG、DOCX、HWPX · OTP² || **HWP**:HWP、HWPX | PDF、PNG、DOCX、HWPX ↔ HWP、TXT、Markdown、HTML |-| **文本**:TXT、Markdown、HTML · reStructuredText、LaTeX、Org、AsciiDoc、Typst、MediaWiki、DocBook、Jupyter、Textile、man、OPML³ | PDF、DOCX、HWPX、EPUB · 互相转换、PPTX 幻灯片³ |+| **文本**:TXT、Markdown、HTML;MHTML(保存的网页)仅读取 · reStructuredText、LaTeX、Org、AsciiDoc、Typst、MediaWiki、DocBook、Jupyter、Textile、man、OPML³ | PDF、DOCX、HWPX、EPUB · 互相转换、PPTX 幻灯片³ || **电子书**:EPUB、KEPUB、MOBI、AZW3、AZW、AZW4、FB2、CBZ、CBR、CB7、HTMLZ、TXTZ · LIT、LRF、CHM、PDB 等⁴ | PDF、EPUB、KEPUB(Kobo)、DOCX、TXT、HTML、HWPX · MOBI、AZW3⁴ || **视频**⁵:MP4、MOV、MKV、WEBM、AVI、WMV、FLV、MPEG、TS、M2TS、3GP、OGV、VOB 等 | MP4(H.264、HEVC、AV1)、WEBM、MOV、MKV、AVI、GIF、APNG、MP3、M4A、720p、字幕(SRT、ASS、WebVTT) || **音频**⁵:MP3、M4A、AAC、WAV、FLAC、OGG、OPUS、WMA、AIFF、AMR、APE、WavPack、TTA、DSD(DSF、DFF)、DTS、AC3、E-AC3 等 | MP3、M4A(AAC、ALAC)、WAV、FLAC、OGG、OPUS、AAC、WavPack、TTA、W64、AC3、E-AC3 |diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 5ef91e29..d7cac7db 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -16,11 +16,11 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,| Spreadsheets (ExcelDataReader for XLS) | built in (library) | **XLSX, XLS, ODS, CSV, TSV → XLSX, ODS, CSV, TSV** (one CSV / TSV per sheet) || Office Open XML | built in | **DOCM / DOTX / DOTM ↔ DOCX, XLSM / XLTX ↔ XLSX, PPTM / POTX / PPSX ↔ PPTX** (macros removed for macro-free types) || Fonts | built in | **TTF, OTF, WOFF, WOFF2, EOT ↔ each other**; CFF (PostScript) outlines become TrueType for TTF and EOT |-| **HWPX writer** | built in | **DOCX (+ DOCM/DOTX/DOTM), XLSX (+ XLSM/XLTX), XLS, ODS, CSV, TSV, PPTX (+ PPTM/POTX/PPSX), PDF, HTML, EPUB, MOBI/AZW3, FB2, HWPX, TXT, Markdown → HWPX** (and with rhwp → PDF and images); ODT, RTF, reStructuredText, LaTeX → HWPX with Pandoc |-| **DOCX writer** | built in | **HWPX (and HWP through rhwp), PDF, HTML, EPUB, MOBI/AZW3, FB2, Markdown, TXT, XLSX, XLS, ODS, CSV, PPTX (+ variants) → DOCX** |+| **HWPX writer** | built in | **DOCX (+ DOCM/DOTX/DOTM), XLSX (+ XLSM/XLTX), XLS, ODS, CSV, TSV, PPTX (+ PPTM/POTX/PPSX), PDF, HTML, MHTML, EPUB, MOBI/AZW3, FB2, HWPX, TXT, Markdown → HWPX** (and with rhwp → PDF and images); ODT, RTF, reStructuredText, LaTeX → HWPX with Pandoc |+| **DOCX writer** | built in | **HWPX (and HWP through rhwp), PDF, HTML, MHTML, EPUB, MOBI/AZW3, FB2, Markdown, TXT, XLSX, XLS, ODS, CSV, PPTX (+ variants) → DOCX** || PDF text | built in (PdfPig) | **PDF → TXT, Markdown** (reading order, also two columns; Markdown keeps headings, emphasis, links and the pictures; no OCR) || PDF slides | built in (PDFium, PdfPig) | **PDF → PPTX**: a picture of each page on its own slide (looks like the PDF, not editable), the page's text in the speaker notes |-| E-mail | built in (MimeKit, MsgReader) | **EML, Outlook MSG → HTML** (headers + body, inline pictures), **TXT**, **ZIP** (the attachments); **MSG → EML** |+| E-mail | built in (MimeKit, MsgReader) | **EML, Outlook MSG → HTML** (headers + body, inline pictures), **TXT**, **ZIP** (the attachments); **MSG → EML**; **MHTML → HTML** (the saved page in one file, pictures inlined; on to PDF, DOCX, HWPX, TXT, Markdown, EPUB from there) || Data | built in (System.Text.Json, YamlDotNet, Tomlyn, System.Xml) | **JSON, JSON Lines, YAML, TOML, XML, CSV ↔ each other** (CSV for tables); **vCard ↔ CSV**; spreadsheets and contacts reach JSON / YAML / TOML / XML through CSV || **E-books** | built in | **EPUB, MOBI/AZW/AZW3/PRC, FB2, HTMLZ, TXTZ → EPUB, HWPX (→ PDF), TXT, HTML, Markdown, FB2, HTMLZ, TXTZ**; HTML, Markdown, TXT, DOCX → EPUB/FB2/HTMLZ/TXTZ; HTML → TXT; comics CBZ/CBR/CB7/CBT/CBC → PDF, EPUB, CBZ; PDF → CBZ; AZW4 → PDF; **EPUB ↔ KEPUB** (Kobo) || CAD (ACadSharp + built-in renderer) | built in (library) | **DWG ↔ DXF**; DWG/DXF → **PDF** (vector), **SVG**, PNG, JPG, WEBP, TIFF, BMP, GIF, ICO, AVIF |@@ -290,6 +290,8 @@ Readers turn the source into a small document model (`Hwp/Hwpx/HwpxModel.cs`) anpictures are skipped), links and anchors, quotes, `pre`, `hr` and figures. Scripts, styles, forms and `nav` areskipped. The encoding comes from the BOM, the XML declaration or `<meta charset>`, else UTF-8 or the systemcode page. No Pandoc needed.+- **MHTML** (`.mhtml`, `.mht`) is turned into its standalone page first (see *E-mail* below) and that page read like+ HTML; it refers to nothing but data: URIs, so no file outside the job's scratch folder is looked at.- **ODT, RTF** are parsed by Pandoc into its JSON AST (`PandocAstReader.cs`, following[pypandoc-hwpx](https://github.com/msjang/pypandoc-hwpx)).- Markdown, HTML and Pandoc keep structure only, so page setup comes from the built-in template (A4).@@ -572,6 +574,41 @@ file reader), RtfPipe (MIT) and UTF.Unknown (MPL-1.1, charset detection for old- **EML → TXT**: the same headers and the text body (or the HTML body as text).- **EML → ZIP**: the attachments (attached messages as .eml) with safe, unique file names.+### MHTML web archives++A web page saved as "Webpage, Single File" (`.mhtml` from Chrome and Edge, `.mht` from Word and Internet Explorer)+is a MIME message like an e-mail: the page and its pictures, style sheets and frames as parts of a+multipart/related body (RFC 2557). `Email/MhtmlArchive.cs` reads it with the same MimeKit parser and writes the page+as **one HTML file** (`MHTML → HTML`, engine `email`); the HWPX and DOCX writers read archives directly through the+same code (`DocumentReaders`), so MHTML → DOCX / HWPX is one step and → PDF two (rhwp), and TXT, Markdown, EPUB and+the other HTML targets go on from the page.++- **The page** is the root of multipart/related (its `start` parameter, else the first part), else the first+ text/html part. Its charset parameter decodes it; without one (Chrome writes none) or with a wrong "us-ascii" over+ 8-bit text, the BOM, `<meta charset>` or UTF-8 decide, as for HTML files. Quoted-printable and base64 are undone+ by MimeKit.+- **References** are matched against the parts' Content-Location, as written or resolved against the page's own+ location or its `<base href>` (Chrome: `https://…`; Word: `file:///C:/…/page_files/image001.png` named relatively+ from the page), and `cid:` against Content-ID (Chrome names its style sheets `cid:css-…@mhtml.blink`). These are+ compared as text only: nothing is downloaded, and no Content-Location is ever opened or written as a file.+- **Pictures** of the archive (`img src`, `srcset`, `<picture>` sources, the `background` attribute and CSS `url()`)+ become data URIs; raster only (PNG, JPEG, GIF, WebP, BMP, AVIF, also when saved as application/octet-stream), not+ SVG. Linked style sheets the archive holds are inlined as `<style>` (with their `@import`s, four levels deep);+ `url()`s that point elsewhere (web fonts, remote backgrounds) become `none`, and `<` in CSS is escaped so a style+ sheet cannot end its element.+- **Safety**: the result goes through the e-mail sanitizer (`EmlConverter.SafeHtml`): scripts, frames, forms,+ `<link>`, `<base>`, `<meta>`, inline SVG / MathML, event handlers and `javascript:` links are removed, the+ `Content-Security-Policy` meta allows only inline styles and data: pictures. Links stay when they are http(s) or+ mailto (made absolute against the page), anchors into the page itself become `#id`.+- **Limits**: archives over 256 MB are refused; a picture over 32 MB (decoded) is left out, as is any picture once+ the page's data URIs reach 192 MB (a picture used many times counts each time); 8 MB of style sheet text per page.++Tests (`tests/Filee.Engines.Tests/MhtmlTests.cs`) write archives in code: a Chrome-style one (quoted-printable page+with the charset only in its meta tag, a `cid:` style sheet, pictures by absolute and relative URL and from CSS, one+saved as octet-stream, and scripts, frames, remote pictures, fonts and style sheets that must go), a Word `.mht`+(windows-1252, `file:///C:/` locations, VML fallbacks), a `cid:`-only page in EUC-KR, a picture on disk named by a+`file:` URI that must not be read, and the routes to HTML, TXT, DOCX, HWPX and PDF.+## Data (JSON, YAML, TOML, XML, CSV, vCard)`Data/DataConverter.cs` (engine id `data`) reads every format into one tree (`Data/DataTree.cs`: objects with theirdiff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex df3dd260..a1589a5d 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -98,7 +98,7 @@"engine.docx-writer.description": "Writes Word documents (DOCX) from PDF, HWP/HWPX, Markdown, HTML, spreadsheets, slides and e-books.","engine.pdf-text.description": "Extracts the text of PDFs in reading order, also from two-column pages (no OCR for scans).","engine.pdf-slides.description": "Turns PDFs into PowerPoint slides: each page becomes a picture on its own slide (looks like the PDF, not editable), with the page text in the speaker notes.",- "engine.email.description": "E-mails (EML, Outlook MSG) to HTML and text with sender, recipients and date, pictures included; attachments into a ZIP.\nMSG to EML.",+ "engine.email.description": "E-mails (EML, Outlook MSG) to HTML and text with sender, recipients and date, pictures included; attachments into a ZIP.\nMSG to EML. Saved web pages (MHTML) to one HTML file with their pictures.","engine.data.description": "JSON, JSON Lines, YAML, TOML, XML and CSV into each other.\nvCard contacts to CSV and back.\nComments are dropped. CSV holds tables only.","engine.vector.description": "SVG and SVGZ to vector PDF, images and DXF; pictures traced into SVG; Illustrator files saved with PDF content.","engine.icns.description": "macOS app icons (ICNS) from and to images.",diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.jsonindex a4a7658f..c8f3106a 100644--- a/src/Filee.App/Assets/i18n/es.json+++ b/src/Filee.App/Assets/i18n/es.json@@ -91,7 +91,7 @@"engine.docx-writer.description": "Escribe documentos de Word (DOCX) desde PDF, HWP/HWPX, Markdown, HTML, hojas de cálculo, diapositivas y libros electrónicos.","engine.pdf-text.description": "Extrae el texto de los PDF en orden de lectura, también de páginas en dos columnas (sin OCR para escaneos).","engine.pdf-slides.description": "Convierte PDF en diapositivas de PowerPoint: cada página pasa a ser una imagen en su propia diapositiva (con el aspecto del PDF, no editable), con el texto de la página en las notas del orador.",- "engine.email.description": "Correos electrónicos (EML, Outlook MSG) a HTML y texto con remitente, destinatarios y fecha, imágenes incluidas; los adjuntos van a un ZIP.\nMSG a EML.",+ "engine.email.description": "Correos electrónicos (EML, Outlook MSG) a HTML y texto con remitente, destinatarios y fecha, imágenes incluidas; los adjuntos van a un ZIP.\nMSG a EML. Páginas web guardadas (MHTML) a un solo archivo HTML con sus imágenes.","engine.data.description": "JSON, JSON Lines, YAML, TOML, XML y CSV entre sí.\nContactos vCard a CSV y viceversa.\nLos comentarios se descartan. CSV solo admite tablas.","engine.vector.description": "SVG y SVGZ a PDF vectorial, imágenes y DXF; imágenes trazadas a SVG; archivos de Illustrator guardados con contenido PDF.","engine.icns.description": "Iconos de apps de macOS (ICNS) desde y hacia imágenes.",diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.jsonindex cdef7ca9..1ce6c8ca 100644--- a/src/Filee.App/Assets/i18n/hi.json+++ b/src/Filee.App/Assets/i18n/hi.json@@ -91,7 +91,7 @@"engine.docx-writer.description": "PDF, HWP/HWPX, Markdown, HTML, स्प्रेडशीट, स्लाइड और ई-बुक से Word दस्तावेज़ (DOCX) लिखता है।","engine.pdf-text.description": "PDF का टेक्स्ट पढ़ने के क्रम में निकालता है, दो-कॉलम वाले पेजों से भी (स्कैन के लिए OCR नहीं)।","engine.pdf-slides.description": "PDF को PowerPoint स्लाइड में बदलता है: हर पेज अपनी स्लाइड पर एक तस्वीर बन जाता है (PDF जैसा दिखता है, संपादन योग्य नहीं), और पेज का टेक्स्ट स्पीकर नोट्स में रहता है।",- "engine.email.description": "ई-मेल (EML, Outlook MSG) को भेजने वाले, प्राप्तकर्ताओं और तारीख के साथ HTML और टेक्स्ट में बदलता है, तस्वीरों सहित; अटैचमेंट ZIP में।\nMSG से EML।",+ "engine.email.description": "ई-मेल (EML, Outlook MSG) को भेजने वाले, प्राप्तकर्ताओं और तारीख के साथ HTML और टेक्स्ट में बदलता है, तस्वीरों सहित; अटैचमेंट ZIP में।\nMSG से EML। सहेजे गए वेब पेज (MHTML) उनकी तस्वीरों सहित एक HTML फ़ाइल में।","engine.data.description": "JSON, JSON Lines, YAML, TOML, XML और CSV एक-दूसरे में।\nvCard संपर्क CSV में और वापस।\nकमेंट हटा दिए जाते हैं। CSV में केवल टेबल रहती हैं।","engine.vector.description": "SVG और SVGZ से वेक्टर PDF, इमेज और DXF; तस्वीरों को SVG में ट्रेस करना; Illustrator फ़ाइलें PDF सामग्री के साथ सहेजना।","engine.icns.description": "इमेज से और इमेज में macOS ऐप आइकन (ICNS)।",diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.jsonindex e70dfab9..adfc01b8 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -98,7 +98,7 @@"engine.docx-writer.description": "PDF, HWP/HWPX, 마크다운, HTML, 스프레드시트, 슬라이드, 전자책으로 워드 문서(DOCX)를 만들어요.","engine.pdf-text.description": "PDF의 글자를 읽는 순서대로 뽑아내요.\n2단 편집도 순서대로 읽어요(스캔 이미지 글자 인식은 안 해요).","engine.pdf-slides.description": "PDF를 파워포인트 슬라이드로 바꿔요. 페이지마다 그림 한 장으로 슬라이드에 넣어서 PDF와 똑같이 보여요(편집은 안 돼요).\n페이지 글자는 슬라이드 노트에 넣어요.",- "engine.email.description": "이메일(EML, Outlook MSG)을 보낸 사람·받는 사람·날짜와 본문 그림까지 담아 HTML·텍스트로 바꾸고, 첨부 파일은 ZIP으로 모아요.\nMSG는 EML로도 바꿔요.",+ "engine.email.description": "이메일(EML, Outlook MSG)을 보낸 사람·받는 사람·날짜와 본문 그림까지 담아 HTML·텍스트로 바꾸고, 첨부 파일은 ZIP으로 모아요.\nMSG는 EML로도 바꾸고, 저장한 웹 페이지(MHTML)는 그림까지 담긴 HTML 파일 하나로 바꿔요.","engine.data.description": "JSON, JSON Lines, YAML, TOML, XML, CSV를 서로 바꿔요.\nvCard 연락처를 CSV로, CSV를 vCard로 바꿔요.\n주석은 빠져요. CSV는 표 모양 데이터만 담아요.","engine.vector.description": "SVG·SVGZ를 벡터 PDF, 이미지, DXF로 바꾸고 그림을 SVG로 벡터화해요. PDF 내용이 들어 있는 일러스트레이터 파일도 변환해요.","engine.icns.description": "macOS 앱 아이콘(ICNS)을 이미지로, 이미지를 ICNS로.",diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.jsonindex 969fc55b..81d4b95f 100644--- a/src/Filee.App/Assets/i18n/pl.json+++ b/src/Filee.App/Assets/i18n/pl.json@@ -98,7 +98,7 @@"engine.docx-writer.description": "Zapisuje dokumenty Word (DOCX) z PDF, HWP/HWPX, Markdown, HTML, arkuszy, slajdów i e-booków.","engine.pdf-text.description": "Wyodrębnia tekst z PDF w kolejności czytania, także ze stron dwukolumnowych (bez OCR skanów).","engine.pdf-slides.description": "Zamienia PDF na slajdy PowerPoint: każda strona staje się obrazem na osobnym slajdzie (wygląda jak PDF, bez edycji), a tekst strony trafia do notatek prelegenta.",- "engine.email.description": "E-maile (EML, Outlook MSG) do HTML i tekstu z nadawcą, odbiorcami i datą, razem z obrazami; załączniki do ZIP.\nMSG do EML.",+ "engine.email.description": "E-maile (EML, Outlook MSG) do HTML i tekstu z nadawcą, odbiorcami i datą, razem z obrazami; załączniki do ZIP.\nMSG do EML. Zapisane strony internetowe (MHTML) do jednego pliku HTML razem z obrazami.","engine.data.description": "JSON, JSON Lines, YAML, TOML, XML i CSV między sobą.\nKontakty vCard do CSV i z powrotem.\nKomentarze są pomijane. CSV przechowuje tylko tabele.","engine.vector.description": "SVG i SVGZ do wektorowego PDF, obrazów i DXF; obrazy wektoryzowane do SVG; pliki Illustratora zapisane z zawartością PDF.","engine.icns.description": "Ikony aplikacji macOS (ICNS) z obrazów i do obrazów.",diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.jsonindex 19c10eb3..810a1683 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -98,7 +98,7 @@"engine.docx-writer.description": "用 PDF、HWP/HWPX、Markdown、HTML、表格、幻灯片和电子书生成 Word 文档(DOCX)。","engine.pdf-text.description": "按阅读顺序提取 PDF 中的文字,双栏页面也能正确排序(不对扫描件做文字识别)。","engine.pdf-slides.description": "将 PDF 转换为 PowerPoint 幻灯片。每页作为一张图片放在单独的幻灯片上,外观与 PDF 相同(不可编辑),页面文字放入演讲者备注。",- "engine.email.description": "将电子邮件(EML、Outlook MSG)连同发件人、收件人、日期和图片转为 HTML 和文本,附件打包为 ZIP。\nMSG 也可转为 EML。",+ "engine.email.description": "将电子邮件(EML、Outlook MSG)连同发件人、收件人、日期和图片转为 HTML 和文本,附件打包为 ZIP。\nMSG 也可转为 EML。保存的网页(MHTML)可连同图片转为单个 HTML 文件。","engine.data.description": "JSON、JSON Lines、YAML、TOML、XML、CSV 互相转换。\nvCard 联系人与 CSV 互转。\n注释不保留。CSV 仅支持表格数据。","engine.vector.description": "将 SVG、SVGZ 转为矢量 PDF、图片和 DXF,并可将图片描摹为 SVG。也支持包含 PDF 内容的 Illustrator 文件。","engine.icns.description": "macOS 应用图标(ICNS)与图片互转。",diff --git a/src/Filee.Core/Formats/FormatRegistry.cs b/src/Filee.Core/Formats/FormatRegistry.csindex c4793b42..c8105b60 100644--- a/src/Filee.Core/Formats/FormatRegistry.cs+++ b/src/Filee.Core/Formats/FormatRegistry.cs@@ -132,6 +132,8 @@ public static class FormatRegistrynew("txt", "TXT", FormatCategory.Text, ["txt"]),new("md", "Markdown", FormatCategory.Text, ["md", "markdown"]),new("html", "HTML", FormatCategory.Text, ["html", "htm", "xhtml"]),+ // A web page saved with its pictures in one MIME file (Chrome, Edge, Word); read as the page it holds.+ new("mhtml", "MHTML", FormatCategory.Text, ["mhtml", "mht"], Writable: false),new("rst", "reStructuredText", FormatCategory.Text, ["rst"]),new("tex", "LaTeX", FormatCategory.Text, ["tex", "latex"]),// Read and written by Pandoc. Man pages claim only ".man": the section numbers (.1 … .9) are also thediff --git a/src/Filee.Core/Presets/BuiltInData.cs b/src/Filee.Core/Presets/BuiltInData.csindex 1ad105a2..e5738307 100644--- a/src/Filee.Core/Presets/BuiltInData.cs+++ b/src/Filee.Core/Presets/BuiltInData.cs@@ -380,7 +380,7 @@ public static class BuiltInDataPresetIds = ["to-pdf", "to-png", "to-jpg", "to-pptx", "to-hwpx", "to-hwp", "merge-pdf"],};- /// <summary>Markdown, plain text and HTML (added in settings schema 4, see SettingsMigrations).</summary>+ /// <summary>Markdown, plain text and HTML (added in settings schema 4, see SettingsMigrations); MHTML (schema 23).</summary>public static ToolbarProfile TextProfile() => new(){Id = "text",diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.csindex f1d77877..7ec34b1d 100644--- a/src/Filee.Core/Settings/AppSettings.cs+++ b/src/Filee.Core/Settings/AppSettings.cs@@ -64,7 +64,7 @@ public sealed class DonutSettingspublic sealed class AppSettings{/// <summary>Current schema version. Increase when the format changes and add a migration.</summary>- public const int CurrentSchemaVersion = 22;+ public const int CurrentSchemaVersion = 23;public int SchemaVersion { get; set; } = CurrentSchemaVersion;diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.csindex 72d44f90..b534dee8 100644--- a/src/Filee.Core/Settings/UserDataStore.cs+++ b/src/Filee.Core/Settings/UserDataStore.cs@@ -563,6 +563,10 @@ internal static class SettingsMigrations// takes it. Other extensions the user removed from a built-in donut stay removed.if (from < 22)changed |= LearnExtensions(profiles, out _, ["fbx"]);+ // v23: MHTML web archives (.mhtml, .mht; read only) open from the text donut next to HTML, unless a donut of+ // the user already takes them.+ if (from < 23)+ changed |= LearnExtensions(profiles, out _, ["mhtml", "mht"]);return changed;}diff --git a/src/Filee.Engines/Email/EmlConverter.cs b/src/Filee.Engines/Email/EmlConverter.csindex f309816f..ee304c72 100644--- a/src/Filee.Engines/Email/EmlConverter.cs+++ b/src/Filee.Engines/Email/EmlConverter.cs@@ -3,7 +3,8 @@// as a ZIP. MimeKit decodes the transfer encodings (quoted-printable, base64), encoded headers (RFC 2047 / 2231) and// charsets, including the Korean ones (EUC-KR / CP949, ISO-2022-KR); header text in raw 8-bit that is not UTF-8 is read// as CP949, as older Korean mail programs wrote it. Outlook .msg files are rebuilt as MIME messages first (see-// OutlookMessage) and take the same path; MSG → EML writes that message.+// OutlookMessage) and take the same path; MSG → EML writes that message. MHTML web archives are MIME messages too:+// MhtmlArchive turns the saved page into one HTML file with the same sanitizer.using System.Globalization;using System.IO.Compression;@@ -18,7 +19,7 @@ using MimeKit;namespace Filee.Engines.Email;-/// <summary>EML and MSG → HTML, TXT and ZIP (attachments); MSG → EML.</summary>+/// <summary>EML and MSG → HTML, TXT and ZIP (attachments); MSG → EML; MHTML → HTML.</summary>public sealed partial class EmlConverter : IConverter{public string Id => "email";@@ -35,15 +36,28 @@ public sealed partial class EmlConverter : IConverter[new("eml", "html"), new("eml", "txt"), new("eml", "zip"),new("msg", "eml"), new("msg", "html"), new("msg", "txt"), new("msg", "zip"),+ // A web archive becomes its page; every HTML target follows from there. The HWPX and DOCX writers read it+ // directly (DocumentReaders), one step shorter.+ new("mhtml", "html"),];- public EngineStatus GetStatus() => EngineStatus.Available("EML, MSG → HTML, TXT, ZIP (attachments); MSG → EML",+ public EngineStatus GetStatus() => EngineStatus.Available("EML, MSG → HTML, TXT, ZIP (attachments); MSG → EML; MHTML → HTML",$"{EngineVersions.BuiltIn} · {EngineVersions.Library("MimeKitLite", typeof(MimeKit.MimeMessage))} · {EngineVersions.Library("MsgReader", typeof(MsgReader.Outlook.Storage))}");public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>Task.Run<IReadOnlyList<string>>(() =>{progress?.Report(0.1);+ if (step.From == "mhtml")+ {+ var page = MhtmlArchive.Html(MhtmlArchive.Load(step.InputPath, cancellationToken));+ progress?.Report(0.8);+ if (step.Output.Allocate("html") is not { } html)+ return [];+ File.WriteAllText(html, page, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));+ progress?.Report(1);+ return [html];+ }var message = step.From == "msg" ? OutlookMessage.Load(step.InputPath) : Load(step.InputPath, cancellationToken);progress?.Report(0.5);if (step.To == "eml")@@ -132,7 +146,7 @@ public sealed partial class EmlConverter : IConvertervar sb = new StringBuilder();sb.Append("<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n");- sb.Append("<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; img-src data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'\">\n");+ sb.Append(ContentSecurityPolicy).Append('\n');sb.Append($"<title>{WebUtility.HtmlEncode(message.Subject ?? "")}</title>\n");sb.Append("<style>\n.filee-mail-headers { border-collapse: collapse; margin: 0 0 12px 0; font-family: sans-serif; font-size: 14px; }\n").Append(".filee-mail-headers th { text-align: left; vertical-align: top; padding: 2px 16px 2px 0; color: #555; font-weight: 600; }\n")@@ -148,6 +162,10 @@ public sealed partial class EmlConverter : IConverterreturn sb.ToString();}+ /// <summary>Only inline styles and data: pictures, should a browser meet anything the sanitizer let through.</summary>+ internal const string ContentSecurityPolicy =+ "<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; img-src data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'\">";+/// <summary>"cid:" references → data URIs of the parts with that Content-ID, so the page needs no other files.</summary>private static string InlinePictures(string html, MimeMessage message){@@ -171,7 +189,7 @@ public sealed partial class EmlConverter : IConverter}/// <summary>Keep readable mail markup while dropping browser-active elements, attributes and remote images.</summary>- private static (string Body, string Styles) SafeHtml(string html)+ internal static (string Body, string Styles) SafeHtml(string html){var document = new HtmlParser().ParseDocument(html);// Raw-text elements (noembed, xmp…) and comments go too: browsers read them as text, other HTML readers may not.@@ -207,7 +225,7 @@ public sealed partial class EmlConverter : IConverterreturn (document.Body?.InnerHtml ?? "", styles);}- private static readonly HashSet<string> SafeHtmlAttributes = new(StringComparer.OrdinalIgnoreCase)+ internal static readonly HashSet<string> SafeHtmlAttributes = new(StringComparer.OrdinalIgnoreCase){"class", "id", "title", "lang", "dir", "style", "align", "valign", "width", "height", "colspan", "rowspan","cellpadding", "cellspacing", "border", "bgcolor", "color", "face", "size", "nowrap", "start", "type",@@ -218,7 +236,7 @@ public sealed partial class EmlConverter : IConverter|| Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Scheme is "http" or "https" or "mailto";/// <summary>Any raster data: image (old Outlook writes image/x-png, image/pjpeg…), never SVG, which can carry script.</summary>- private static bool SafeInlineImage(string value) => RasterDataImage().IsMatch(value);+ internal static bool SafeInlineImage(string value) => RasterDataImage().IsMatch(value);// ───────────────────────── Text ─────────────────────────diff --git a/src/Filee.Engines/Email/MhtmlArchive.cs b/src/Filee.Engines/Email/MhtmlArchive.csnew file mode 100644index 00000000..62145268--- /dev/null+++ b/src/Filee.Engines/Email/MhtmlArchive.cs@@ -0,0 +1,360 @@+// MHTML web archives (.mhtml / .mht, RFC 2557): a web page saved with its pictures and style sheets in one MIME+// message, the structure of an e-mail, so MimeKit reads it. Chrome and Edge write multipart/related with the page+// first, pictures named by Content-Location (the URL they came from) and style sheets as "cid:…@mhtml.blink" parts;+// Word and Internet Explorer write .mht files whose parts sit at file:///C:/… locations next to the page, referred to+// relatively ("page_files/image001.png"). The page becomes one standalone HTML file: linked style sheets are inlined,+// pictures of the archive become data: URIs, and the e-mail sanitizer (EmlConverter.SafeHtml) drops scripts, frames,+// forms and anything that would load from elsewhere. Nothing is fetched: a reference the archive does not hold is+// removed, and Content-Location values are only compared as text, never opened or written as files.++using System.Globalization;+using System.Net;+using System.Text;+using System.Text.RegularExpressions;+using AngleSharp.Dom;+using AngleSharp.Html.Parser;+using Filee.Engines.Hwp.Hwpx;+using MimeKit;++namespace Filee.Engines.Email;++/// <summary>MHTML → a standalone, sanitized HTML page (and the document model, for the HWPX and DOCX writers).</summary>+internal static partial class MhtmlArchive+{+ /// <summary>Larger archives are refused: MimeKit keeps every part in memory.</summary>+ internal const long MaxFileBytes = 256L * 1024 * 1024;++ /// <summary>A picture larger than this (decoded) is left out.</summary>+ internal const int MaxPictureBytes = 32 * 1024 * 1024;++ /// <summary>The data URIs of one page together; a picture shown many times counts every time.</summary>+ internal const long MaxEmbeddedChars = 192L * 1024 * 1024;++ /// <summary>Style sheet text inlined into one page; @import is followed this deep.</summary>+ private const int MaxStyleChars = 8 * 1024 * 1024;+ private const int MaxImportDepth = 4;++ /// <summary>Parses an archive, refusing files over <see cref="MaxFileBytes"/>.</summary>+ public static MimeMessage Load(string path, CancellationToken cancellationToken = default)+ {+ if (new FileInfo(path).Length > MaxFileBytes)+ throw new InvalidDataException($"The web archive is larger than {MaxFileBytes / (1024 * 1024)} MB.");+ return EmlConverter.Load(path, cancellationToken);+ }++ /// <summary>Reads an archive into the document model (MHTML → HWPX, DOCX and on to PDF).</summary>+ public static HDocument ReadDocument(string path, string mediaFolder)+ {+ var html = Html(Load(path));+ // The page refers to nothing but data: URIs; no local file is looked up outside the job's media folder.+ var content = HtmlReader.Parse(html, new HtmlReadOptions { BaseFolder = mediaFolder, MediaFolder = mediaFolder, ResourceRoot = mediaFolder });+ return HtmlReader.ToDocument(content);+ }++ /// <summary>The saved page as one HTML file: style sheets inline, pictures as data URIs, nothing active or remote.</summary>+ public static string Html(MimeMessage message)+ {+ var page = Page(message) ?? throw new InvalidDataException("The web archive holds no HTML page.");+ var archive = new Archive(message, page);+ var document = new HtmlParser().ParseDocument(Text(page, HtmlReader.Decode));+ var baseUri = document.QuerySelector("base[href]")?.GetAttribute("href") is { } baseHref+ && Absolute(baseHref, archive.PageLocation) is { } declared+ ? declared+ : archive.PageLocation;++ foreach (var style in document.QuerySelectorAll("style").ToArray())+ style.TextContent = archive.Css(style.TextContent, baseUri, 0);+ foreach (var link in document.QuerySelectorAll("link[href]").ToArray())+ {+ if (!(link.GetAttribute("rel") ?? "").Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries).Contains("stylesheet", StringComparer.OrdinalIgnoreCase)+ || archive.StyleSheet(link.GetAttribute("href"), baseUri, 0) is not { } css)+ continue;+ var media = link.GetAttribute("media")?.Trim();+ var inline = document.CreateElement("style");+ inline.TextContent = string.IsNullOrEmpty(media) || media.Equals("all", StringComparison.OrdinalIgnoreCase)+ ? css+ : $"@media {media.Replace("<", "\\3c ", StringComparison.Ordinal)} {{\n{css}\n}}";+ link.Parent?.ReplaceChild(inline, link);+ }+ foreach (var element in document.QuerySelectorAll("[style]").ToArray())+ element.SetAttribute("style", archive.Css(element.GetAttribute("style") ?? "", baseUri, 0));+ foreach (var element in document.QuerySelectorAll("[background]").ToArray())+ {+ // Old pages and Word put the background picture in an attribute the sanitizer drops: move it into CSS.+ if (archive.Picture(element.GetAttribute("background"), baseUri) is { } picture)+ element.SetAttribute("style", $"background-image: url(\"{picture}\"); {element.GetAttribute("style")}");+ }+ foreach (var image in document.QuerySelectorAll("img").ToArray())+ {+ var candidates = new[] { image.GetAttribute("src") }+ .Concat(SourceSet(image.GetAttribute("srcset")))+ .Concat(image.ParentElement is { LocalName: "picture" } picture+ ? picture.Children.Where(c => c.LocalName == "source").SelectMany(c => SourceSet(c.GetAttribute("srcset")))+ : []);+ if (candidates.Select(c => archive.Picture(c, baseUri)).FirstOrDefault(p => p is not null) is { } data)+ image.SetAttribute("src", data);+ else+ image.RemoveAttribute("src");+ }+ foreach (var anchor in document.QuerySelectorAll("a[href]").ToArray())+ {+ var href = anchor.GetAttribute("href")!.Trim();+ if (href.StartsWith('#') || Absolute(href, baseUri) is not { } target)+ continue;+ if (archive.PageLocation is { } location && Key(target) == Key(location))+ anchor.SetAttribute("href", target.Fragment.Length > 1 ? target.Fragment : "#");+ else if (target.Scheme is "http" or "https" or "mailto")+ anchor.SetAttribute("href", target.AbsoluteUri);+ }++ var title = document.Title?.Trim() is { Length: > 0 } documentTitle ? documentTitle : message.Subject?.Trim() ?? "";+ var language = document.DocumentElement?.GetAttribute("lang") is { } lang && LanguageTag().IsMatch(lang) ? lang : null;+ var bodyAttributes = new StringBuilder();+ foreach (var attribute in document.Body?.Attributes.ToArray() ?? [])+ {+ if (EmlConverter.SafeHtmlAttributes.Contains(attribute.Name))+ bodyAttributes.Append($" {attribute.Name}=\"{WebUtility.HtmlEncode(attribute.Value)}\"");+ }+ var safe = EmlConverter.SafeHtml(document.DocumentElement!.OuterHtml);++ var sb = new StringBuilder();+ sb.Append("<!DOCTYPE html>\n<html").Append(language is null ? "" : $" lang=\"{language}\"").Append(">\n<head>\n<meta charset=\"utf-8\">\n");+ sb.Append(EmlConverter.ContentSecurityPolicy).Append('\n');+ sb.Append($"<title>{WebUtility.HtmlEncode(title)}</title>\n");+ sb.Append(safe.Styles);+ sb.Append("\n</head>\n<body").Append(bodyAttributes).Append(">\n");+ sb.Append(safe.Body);+ sb.Append("\n</body>\n</html>\n");+ return sb.ToString();+ }++ /// <summary>The page: the root of multipart/related ("start" parameter or the first part), else the first HTML part.</summary>+ private static MimePart? Page(MimeMessage message) =>+ message.Body is MultipartRelated { Root: MimePart root } && IsHtml(root)+ ? root+ : message.BodyParts.OfType<MimePart>().FirstOrDefault(IsHtml);++ private static bool IsHtml(MimePart part) =>+ part.ContentType.IsMimeType("text", "html") || part.ContentType.IsMimeType("application", "xhtml+xml");++ /// <summary>+ /// A text part decoded with its charset parameter; without one (or a wrong "us-ascii" over 8-bit text) the+ /// <paramref name="fallback"/> looks at the BOM, the page's own declaration and UTF-8.+ /// </summary>+ private static string Text(MimePart part, Func<byte[], string> fallback)+ {+ using var data = new MemoryStream();+ part.Content?.DecodeTo(data);+ var bytes = data.ToArray();+ var charset = part.ContentType.Charset?.Trim();+ var bom = bytes is [0xEF, 0xBB, 0xBF, ..] or [0xFF, 0xFE, ..] or [0xFE, 0xFF, ..];+ var ascii = charset is not null && (charset.Equals("us-ascii", StringComparison.OrdinalIgnoreCase) || charset.Equals("ascii", StringComparison.OrdinalIgnoreCase));+ if (!string.IsNullOrEmpty(charset) && !bom && !(ascii && bytes.Any(b => b >= 0x80)))+ {+ try+ {+ return Encoding.GetEncoding(charset).GetString(bytes).TrimStart('\uFEFF');+ }+ catch (ArgumentException)+ {+ // Unknown charset name: detect below.+ }+ }+ return fallback(bytes);+ }++ /// <summary>The URLs of a srcset ("a.png 1x, b.png 2x"), largest first as the last is usually the sharpest.</summary>+ private static IEnumerable<string> SourceSet(string? srcset) =>+ string.IsNullOrWhiteSpace(srcset)+ ? []+ : srcset.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)+ .Select(candidate => candidate.Split((char[]?)null, 2, StringSplitOptions.RemoveEmptyEntries)[0])+ .Reverse();++ /// <summary>+ /// <paramref name="reference"/> as an absolute URI: as written when it has a scheme, else against+ /// <paramref name="baseUri"/>. Only ever compared with Content-Location values, never opened.+ /// </summary>+ private static Uri? Absolute(string? reference, Uri? baseUri)+ {+ if (string.IsNullOrWhiteSpace(reference))+ return null;+ reference = reference.Trim();+ try+ {+ // "/images/a.png" is an absolute file path to Uri on Linux and macOS; on a web page it is relative.+ if (UriScheme().IsMatch(reference))+ return Uri.TryCreate(reference, UriKind.Absolute, out var absolute) ? absolute : null;+ return baseUri is not null && Uri.TryCreate(baseUri, reference, out var combined) ? combined : null;+ }+ catch (Exception ex) when (ex is UriFormatException or ArgumentException or InvalidOperationException)+ {+ return null;+ }+ }++ /// <summary>The URI without its fragment, for lookups.</summary>+ private static string Key(Uri uri)+ {+ var text = uri.IsAbsoluteUri ? uri.AbsoluteUri : uri.OriginalString;+ var hash = text.IndexOf('#');+ return hash < 0 ? text : text[..hash];+ }++ /// <summary>The parts of one archive by Content-Location and Content-ID, and what was inlined from them so far.</summary>+ private sealed class Archive+ {+ private readonly Dictionary<string, MimePart> _byLocation = new(StringComparer.OrdinalIgnoreCase);+ private readonly Dictionary<string, MimePart> _byId = new(StringComparer.OrdinalIgnoreCase);+ private readonly Dictionary<MimePart, string?> _pictures = [];+ private long _embedded;+ private long _styles;++ public Archive(MimeMessage message, MimePart page)+ {+ PageLocation = Absolute(Location(page), null);+ foreach (var part in message.BodyParts.OfType<MimePart>())+ {+ if (part.ContentId is { Length: > 0 } id)+ _byId.TryAdd(id.Trim().Trim('<', '>'), part);+ if (Location(part) is not { } location)+ continue;+ _byLocation.TryAdd(location, part);+ if (Absolute(location, PageLocation) is { } absolute)+ _byLocation.TryAdd(Key(absolute), part);+ }+ }++ /// <summary>Where the page was saved from (its Content-Location), the base of its relative references.</summary>+ public Uri? PageLocation { get; }++ /// <summary>The Content-Location header as written, unfolded (URLs hold no white space).</summary>+ private static string? Location(MimePart part) =>+ part.Headers[HeaderId.ContentLocation] is { } value && Whitespace().Replace(value, "") is { Length: > 0 } location+ ? location+ : null;++ /// <summary>The part a reference names: its Content-Location as written or resolved, or "cid:" its Content-ID.</summary>+ private MimePart? Find(string? reference, Uri? baseUri)+ {+ if (string.IsNullOrWhiteSpace(reference))+ return null;+ reference = reference.Trim();+ if (_byLocation.TryGetValue(reference, out var part))+ return part;+ if (reference.StartsWith("cid:", StringComparison.OrdinalIgnoreCase))+ return _byId.GetValueOrDefault(Uri.UnescapeDataString(reference[4..]).Trim('<', '>'));+ return Absolute(reference, baseUri) is { } absolute ? _byLocation.GetValueOrDefault(Key(absolute)) : null;+ }++ /// <summary>+ /// A data URI of the raster picture a reference names, or null when the archive does not hold one (remote,+ /// SVG, too large, or the page's picture budget is spent). Data URIs already in the page are kept when raster.+ /// </summary>+ public string? Picture(string? reference, Uri? baseUri)+ {+ if (string.IsNullOrWhiteSpace(reference))+ return null;+ reference = reference.Trim();+ if (reference.StartsWith("data:", StringComparison.OrdinalIgnoreCase))+ return EmlConverter.SafeInlineImage(reference) ? Spend(reference) : null;+ if (Find(reference, baseUri) is not { } part)+ return null;+ if (!_pictures.TryGetValue(part, out var uri))+ _pictures[part] = uri = DataUri(part);+ return Spend(uri);+ }++ private string? Spend(string? uri)+ {+ if (uri is null || _embedded + uri.Length > MaxEmbeddedChars)+ return null;+ _embedded += uri.Length;+ return uri;+ }++ private static string? DataUri(MimePart part)+ {+ if (part.Content is null)+ return null;+ var declared = part.ContentType.MimeType.ToLowerInvariant();+ var maybeImage = declared.StartsWith("image/", StringComparison.Ordinal) || declared is "application/octet-stream";+ // Base64 and quoted-printable only grow data, so the encoded size bounds the decoded one.+ if (!maybeImage || part.Content.Stream is { CanSeek: true } encoded && encoded.Length > MaxPictureBytes * 2L)+ return null;+ using var data = new MemoryStream();+ part.Content.DecodeTo(data);+ if (data.Length is 0 or > MaxPictureBytes)+ return null;+ var bytes = data.ToArray();+ var type = SniffPicture(bytes) ?? (declared.StartsWith("image/", StringComparison.Ordinal) && !declared.Contains("svg", StringComparison.Ordinal) ? declared : null);+ return type is null ? null : $"data:{type};base64,{Convert.ToBase64String(bytes)}";+ }++ /// <summary>The style sheet a reference names, its url()s rewritten (see <see cref="Css"/>), or null.</summary>+ public string? StyleSheet(string? reference, Uri? baseUri, int depth)+ {+ if (depth > MaxImportDepth || Find(reference, baseUri) is not { } part || !part.ContentType.IsMimeType("text", "css"))+ return null;+ // Chrome names style sheets "cid:…", which is no base: their url()s are absolute, else read like the page's.+ var location = Absolute(Location(part), PageLocation);+ var sheetBase = location?.Scheme is "http" or "https" or "file" or "ftp" ? location : baseUri;+ return Css(Text(part, HtmlReader.Decode), sheetBase, depth);+ }++ /// <summary>+ /// CSS with @import replaced by the imported sheet when the archive holds it, url() of archived raster pictures+ /// as data URIs and every other url() as "none", so a browser loads nothing. "<" is escaped so the text+ /// cannot close its <style> element.+ /// </summary>+ public string Css(string css, Uri? baseUri, int depth)+ {+ if (css.Length == 0)+ return css;+ _styles += css.Length;+ if (_styles > MaxStyleChars)+ return "";+ // Imported sheets are rewritten on their own (against their own location) and put in after this sheet's+ // url()s are, so their data URIs aren't scanned and counted twice. NUL marks the spots; CSS has none.+ var imported = new List<string>();+ css = CssImport().Replace(css.Replace('\0', '�'), match =>+ {+ imported.Add(StyleSheet(match.Groups["url"].Value, baseUri, depth + 1) ?? "");+ return $"\0{imported.Count - 1}\0";+ });+ css = CssUrl().Replace(css, match => Picture(match.Groups["url"].Value, baseUri) is { } data ? $"url(\"{data}\")" : "none");+ css = css.Replace("<", "\\3c ", StringComparison.Ordinal);+ return imported.Count == 0 ? css : ImportMark().Replace(css, match => imported[int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture)]);+ }+ }++ /// <summary>The picture type from the first bytes, for parts saved as application/octet-stream or mislabelled.</summary>+ private static string? SniffPicture(byte[] bytes) => bytes switch+ {+ [0x89, 0x50, 0x4E, 0x47, ..] => "image/png",+ [0xFF, 0xD8, 0xFF, ..] => "image/jpeg",+ [0x47, 0x49, 0x46, 0x38, ..] => "image/gif",+ [0x52, 0x49, 0x46, 0x46, _, _, _, _, 0x57, 0x45, 0x42, 0x50, ..] => "image/webp",+ [0x42, 0x4D, ..] => "image/bmp",+ [_, _, _, _, 0x66, 0x74, 0x79, 0x70, 0x61, 0x76, 0x69, 0x66, ..] => "image/avif",+ _ => null,+ };++ [GeneratedRegex(@"@import\s+(?:url\(\s*)?(?<q>[""']?)(?<url>[^""')\s;]+)\k<q>\s*\)?[^;{}]*;?", RegexOptions.IgnoreCase)]+ private static partial Regex CssImport();++ [GeneratedRegex(@"url\(\s*(?:""(?<url>[^""]*)""|'(?<url>[^']*)'|(?<url>[^)\s""']*))\s*\)", RegexOptions.IgnoreCase)]+ private static partial Regex CssUrl();++ [GeneratedRegex("\0([0-9]+)\0")]+ private static partial Regex ImportMark();++ [GeneratedRegex("^[A-Za-z][A-Za-z0-9+.-]*:")]+ private static partial Regex UriScheme();++ [GeneratedRegex("^[A-Za-z]{1,8}(-[A-Za-z0-9]{1,8})*$")]+ private static partial Regex LanguageTag();++ [GeneratedRegex(@"\s+")]+ private static partial Regex Whitespace();+}diff --git a/src/Filee.Engines/Hwp/Hwpx/DocumentReaders.cs b/src/Filee.Engines/Hwp/Hwpx/DocumentReaders.csindex e816bf57..2affa40b 100644--- a/src/Filee.Engines/Hwp/Hwpx/DocumentReaders.cs+++ b/src/Filee.Engines/Hwp/Hwpx/DocumentReaders.cs@@ -5,6 +5,7 @@using System.Text;using System.Text.Json.Nodes;using Filee.Engines.Ebooks;+using Filee.Engines.Email;using Filee.Engines.Hwp.Hwpx.Docx;using Filee.Engines.Hwp.Hwpx.Pptx;using Filee.Engines.Infrastructure;@@ -47,6 +48,7 @@ internal static class DocumentReaders// HWP comes here as HWPX, converted by rhwp first (the route planner adds that step).["hwpx"] = HwpxReader.Read,["html"] = HtmlReader.Read,+ ["mhtml"] = MhtmlArchive.ReadDocument, // the saved page with its pictures, sanitized like an e-mail["epub"] = EpubReader.Read,["kepub"] = EpubReader.Read, // a Kobo EPUB: its koboSpan markup is plain spans to the HTML reader["mobi"] = MobiReader.Read,diff --git a/src/Filee.Engines/Hwp/Hwpx/HtmlReader.cs b/src/Filee.Engines/Hwp/Hwpx/HtmlReader.csindex 4453142f..76940c9e 100644--- a/src/Filee.Engines/Hwp/Hwpx/HtmlReader.cs+++ b/src/Filee.Engines/Hwp/Hwpx/HtmlReader.cs@@ -93,6 +93,12 @@ internal sealed partial class HtmlReaderBaseFolder = Path.GetDirectoryName(Path.GetFullPath(path))!,MediaFolder = mediaFolder,});+ return ToDocument(content);+ }++ /// <summary>One section with what was read, titled like the page.</summary>+ public static HDocument ToDocument(HtmlContent content)+ {var section = new HSection();section.Blocks.AddRange(content.Blocks);var document = new HDocument { Title = content.Title };diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.csindex 42c55c56..09a31904 100644--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs@@ -577,6 +577,30 @@ public class UserDataStoreTestsAssert.DoesNotContain("fbx", profiles.Single(p => p.Id == "models").Extensions);}+ [Fact]+ public void Version_22_libraries_learn_mhtml_on_the_text_donut_and_nothing_else()+ {+ // As written with schema 22: no MHTML, and the user took Markdown off the text donut.+ var presets = BuiltInData.CreatePresets();+ var profiles = BuiltInData.CreateProfiles();+ var text = profiles.Single(p => p.Id == "text");+ text.Extensions.RemoveAll(e => e is "mhtml" or "mht" or "md" or "markdown");++ Assert.True(SettingsMigrations.ApplyToLibrary(22, presets, profiles));++ Assert.Contains("mhtml", text.Extensions);+ Assert.Contains("mht", text.Extensions);+ Assert.DoesNotContain("md", text.Extensions);+ Assert.False(SettingsMigrations.ApplyToLibrary(22, presets, profiles)); // once only++ // A donut of the user that already opens .mht files keeps them; .mhtml still goes to the text donut.+ profiles = BuiltInData.CreateProfiles();+ profiles.Single(p => p.Id == "text").Extensions.RemoveAll(e => e is "mhtml" or "mht");+ profiles.Insert(0, new ToolbarProfile { Id = "web", Name = "Web", Extensions = ["mht"] });+ Assert.True(SettingsMigrations.ApplyToLibrary(22, presets, profiles));+ Assert.Equal(["mhtml"], profiles.Single(p => p.Id == "text").Extensions.Where(e => e.StartsWith("mht", StringComparison.Ordinal)));+ }+[Fact]public void Version_15_libraries_get_the_tracing_presets_on_the_images_donut_after_pdf(){diff --git a/tests/Filee.Engines.Tests/MhtmlTests.cs b/tests/Filee.Engines.Tests/MhtmlTests.csnew file mode 100644index 00000000..d548e64b--- /dev/null+++ b/tests/Filee.Engines.Tests/MhtmlTests.cs@@ -0,0 +1,364 @@+// MHTML web archives (.mhtml / .mht) → HTML (one file, pictures as data URIs), DOCX, HWPX, PDF and text. The archives+// are written in the test the way Chrome / Edge (multipart/related, Content-Location URLs, "cid:" style sheets,+// quoted-printable page without a charset parameter) and Word (file:///C:/… locations, windows-1252, VML fallbacks)+// save them, plus a cid:-only archive in EUC-KR.++using System.IO.Compression;+using System.Text;+using Filee.Core.Conversion;+using Filee.Core.Formats;+using Filee.Core.Presets;+using Filee.Engines.Email;+using ImageMagick;++namespace Filee.Engines.Tests;++public class MhtmlTests(EngineFixture fx) : IClassFixture<EngineFixture>+{+ static MhtmlTests() => Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);++ private static readonly string[] OptionalEngines = ["pandoc", "libreoffice", "calibre"];++ private static readonly byte[] Photo = EbookBuilders.Png(40, 30, MagickColors.Teal);+ private static readonly byte[] Banner = EbookBuilders.Png(50, 10, MagickColors.Orange);+ private static readonly byte[] Secret = EbookBuilders.Png(12, 12, MagickColors.Red);++ private static string Base64Lines(byte[] bytes) =>+ string.Join("\r\n", Convert.ToBase64String(bytes).Chunk(76).Select(c => new string(c)));++ /// <summary>Quoted-printable of <paramref name="text"/> in <paramref name="charset"/>, lines kept under 76.</summary>+ private static string QuotedPrintable(string text, string charset)+ {+ var sb = new StringBuilder();+ var column = 0;+ foreach (var b in Encoding.GetEncoding(charset).GetBytes(text))+ {+ if (b == '\n')+ {+ sb.Append("\r\n");+ column = 0;+ continue;+ }+ var piece = b is >= 33 and <= 126 and not (byte)'=' || b == ' ' ? ((char)b).ToString() : $"={b:X2}";+ if (column + piece.Length > 72)+ {+ sb.Append("=\r\n");+ column = 0;+ }+ sb.Append(piece);+ column += piece.Length;+ }+ return sb.ToString();+ }++ private async Task<string> WriteAsync(string name, string content)+ {+ var path = Path.Combine(fx.NewFolder(), name);+ await File.WriteAllTextAsync(path, content, Encoding.ASCII, TestContext.Current.CancellationToken);+ return path;+ }++ /// <summary>+ /// As Chrome saves "Webpage, Single File": the page (quoted-printable, charset only in its meta tag) refers to a+ /// style sheet by "cid:", to pictures by absolute and relative URL, and to things the archive does not hold.+ /// </summary>+ private Task<string> ChromeArchiveAsync(string? secretFile = null)+ {+ var html = $$"""+ <!DOCTYPE html><html lang="ko"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">+ <base href="https://example.com/news/">+ <link rel="stylesheet" type="text/css" href="cid:[email protected]" />+ <link rel="stylesheet" href="https://cdn.example.net/remote.css">+ <title>오늘의 기사</title><script src="https://example.com/app.js"></script></head>+ <body class="article" onload="alert(1)">+ <h1>큰 제목</h1>+ <p class="hero">본문 첫 문단입니다. 카페 메뉴 – “라떼”.</p>+ <p><img src="https://example.com/img/photo.png" alt="사진"></p>+ <p><img src="../img/banner.png" alt="배너"></p>+ <p><img src="https://tracker.example/pixel.gif" alt="추적"></p>+ <p><img src="{{secretFile ?? "secret.png"}}" alt="비밀"></p>+ <iframe src="https://ads.example/frame"></iframe>+ <script>document.write('injected')</script>+ <p><a href="https://example.com/news/other.html">다른 기사</a> · <a href="article.html#comments">댓글</a>+ · <a href="javascript:alert(1)">나쁜 링크</a></p>+ <p id="comments">댓글 영역</p>+ </body></html>+ """;+ const string Css = """+ @charset "utf-8";+ h1 { color: rgb(200, 0, 0); }+ .hero { background-image: url("https://example.com/img/banner.png"); }+ .remote { background: url(https://tracker.example/bg.png) no-repeat; }+ @font-face { font-family: Remote; src: url(https://fonts.example/x.woff2) format("woff2"); }+ .escape { content: "</style><script>alert(1)</script>"; }+ """;+ return WriteAsync("기사.mhtml", string.Join("\r\n",+ "From: <Saved by Blink>",+ "Snapshot-Content-Location: https://example.com/news/article.html",+ "Subject: =?utf-8?Q?=EC=98=A4=EB=8A=98=EC=9D=98_=EA=B8=B0=EC=82=AC?=",+ "Date: Tue, 20 Oct 2026 10:00:00 +0900",+ "MIME-Version: 1.0",+ "Content-Type: multipart/related;",+ "\ttype=\"text/html\";",+ "\tboundary=\"----MultipartBoundary--abc----\"",+ "",+ "",+ "------MultipartBoundary--abc----",+ "Content-Type: text/html",+ "Content-ID: <[email protected]>",+ "Content-Transfer-Encoding: quoted-printable",+ "Content-Location: https://example.com/news/article.html",+ "",+ QuotedPrintable(html.ReplaceLineEndings("\n"), "utf-8"),+ "------MultipartBoundary--abc----",+ "Content-Type: text/css",+ "Content-Transfer-Encoding: quoted-printable",+ "Content-Location: cid:[email protected]",+ "",+ QuotedPrintable(Css.ReplaceLineEndings("\n"), "utf-8"),+ "------MultipartBoundary--abc----",+ "Content-Type: image/png",+ "Content-Transfer-Encoding: base64",+ "Content-Location: https://example.com/img/photo.png",+ "",+ Base64Lines(Photo),+ "------MultipartBoundary--abc----",+ "Content-Type: application/octet-stream",+ "Content-Transfer-Encoding: base64",+ "Content-Location: https://example.com/img/banner.png",+ "",+ Base64Lines(Banner),+ "------MultipartBoundary--abc------",+ ""));+ }++ private async Task<string> ConvertAsync(string input, string target)+ {+ var job = await fx.ConvertAsync([input], new Preset { TargetFormat = target });+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));+ return job.Outputs.Single();+ }++ private RoutePlanner BuiltInPlanner(params string[] assumeInstalled) =>+ new ConverterCatalog(fx.Converters.Where(c => !OptionalEngines.Contains(c.Id))) { Priority = fx.Catalog.Priority }.CreatePlanner(assumeInstalled);++ [Fact]+ public void Mhtml_is_a_read_only_text_format_with_both_extensions()+ {+ Assert.Equal("mhtml", FormatRegistry.FindByExtension("mht")!.Id);+ Assert.Equal("mhtml", FormatRegistry.Detect("page.MHTML")!.Id);+ Assert.False(FormatRegistry.Get("mhtml").Writable);+ Assert.Equal(FormatCategory.Text, FormatRegistry.Get("mhtml").Category);+ var text = BuiltInData.CreateProfiles().Single(p => p.Id == "text");+ Assert.Contains("mhtml", text.Extensions);+ Assert.Contains("mht", text.Extensions);+ }++ [Fact]+ public void Every_html_target_is_reachable_without_optional_engines()+ {+ var planner = BuiltInPlanner("rhwp");++ Assert.Equal("email", Assert.Single(planner.Plan("mhtml", "html")!.Steps).Converter.Id);+ Assert.Equal("docx-writer", Assert.Single(planner.Plan("mhtml", "docx")!.Steps).Converter.Id);+ Assert.Equal("hwpx-writer", Assert.Single(planner.Plan("mhtml", "hwpx")!.Steps).Converter.Id);+ Assert.Equal(["hwpx-writer", "rhwp"], planner.Plan("mhtml", "pdf")!.Steps.Select(s => s.Converter.Id));+ foreach (var target in new[] { "txt", "md", "epub", "hwp" })+ Assert.NotNull(planner.Plan("mhtml", target));+ }++ [Fact]+ public async Task Chrome_archive_becomes_one_safe_html_file_with_its_pictures()+ {+ var html = await File.ReadAllTextAsync(await ConvertAsync(await ChromeArchiveAsync(), "html"), TestContext.Current.CancellationToken);++ Assert.StartsWith("<!DOCTYPE html>\n<html lang=\"ko\">", html);+ Assert.Contains("<meta charset=\"utf-8\">", html);+ Assert.Contains("Content-Security-Policy", html);+ Assert.Contains("<title>오늘의 기사</title>", html);+ Assert.Contains("<body class=\"article\">", html);+ Assert.Contains("<h1>큰 제목</h1>", html);+ Assert.Contains("카페 메뉴 – “라떼”.", html); // quoted-printable UTF-8, the charset only in the page's meta tag++ // Pictures of the archive: by absolute URL, by URL relative to <base>, from CSS, saved as octet-stream.+ Assert.Contains($"src=\"data:image/png;base64,{Convert.ToBase64String(Photo)}\"", html);+ Assert.Contains($"src=\"data:image/png;base64,{Convert.ToBase64String(Banner)}\"", html);+ Assert.Contains($".hero {{ background-image: url(\"data:image/png;base64,{Convert.ToBase64String(Banner)}\"); }}", html);+ Assert.Contains("h1 { color: rgb(200, 0, 0); }", html); // the "cid:" style sheet, inlined++ // Nothing loads from elsewhere, nothing runs.+ Assert.DoesNotContain("tracker.example", html);+ Assert.DoesNotContain("fonts.example", html);+ Assert.DoesNotContain("cdn.example.net", html);+ Assert.DoesNotContain("ads.example", html);+ Assert.DoesNotContain("app.js", html);+ Assert.DoesNotContain("<script", html);+ Assert.DoesNotContain("<iframe", html);+ Assert.DoesNotContain("<link", html);+ Assert.DoesNotContain("<base", html);+ Assert.DoesNotContain("onload", html);+ Assert.DoesNotContain("javascript:", html);+ Assert.DoesNotContain("cid:", html);+ Assert.DoesNotContain("injected", html);+ Assert.DoesNotContain("</style><script>", html); // a style sheet cannot close its <style> element+ Assert.Contains("src: none format(\"woff2\")", html);+ Assert.DoesNotContain("src=\"secret.png\"", html);++ // Links: absolute, and the page's own anchors stay in the page.+ Assert.Contains("href=\"https://example.com/news/other.html\"", html);+ Assert.Contains("href=\"#comments\"", html);+ }++ [Fact]+ public async Task Content_location_never_opens_a_local_file()+ {+ // A real picture on disk, named by a file: URI and by a path, that the archive does not hold.+ var folder = fx.NewFolder();+ var secret = Path.Combine(folder, "secret.png");+ await File.WriteAllBytesAsync(secret, Secret, TestContext.Current.CancellationToken);+ var archive = await ChromeArchiveAsync(new Uri(secret).AbsoluteUri);+ File.Copy(secret, Path.Combine(Path.GetDirectoryName(archive)!, "secret.png"));++ var html = await File.ReadAllTextAsync(await ConvertAsync(archive, "html"), TestContext.Current.CancellationToken);+ Assert.DoesNotContain(Convert.ToBase64String(Secret), html);+ Assert.DoesNotContain("secret.png", html);++ // The document writers see only the archived pictures too.+ var docx = await ConvertAsync(archive, "docx");+ DocxAssert.ValidPackage(docx);+ using var zip = ZipFile.OpenRead(docx);+ var media = zip.Entries.Where(e => e.FullName.StartsWith("word/media/", StringComparison.Ordinal)).ToList();+ Assert.Equal(2, media.Count);+ foreach (var entry in media)+ {+ using var stream = entry.Open();+ using var image = new MagickImage(stream);+ Assert.NotEqual(12u, image.Width);+ }+ }++ [Fact]+ public async Task Word_mht_with_file_locations_and_windows_1252()+ {+ const string Html = """+ <html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">+ <head><meta http-equiv=Content-Type content="text/html; charset=windows-1252">+ <link rel=File-List href="report_files/filelist.xml">+ <style><!-- p.MsoNormal { margin: 0in; font-family: "Calibri"; } --></style></head>+ <body lang=EN-US style='tab-interval:.5in'>+ <p class=MsoNormal>Café crème – naïve</p>+ <p class=MsoNormal><!--[if gte vml 1]><v:shape><v:imagedata src="report_files/image001.png" o:title=""/></v:shape><![endif]--><![if !vml]><img width=40 height=30 src="report_files/image002.png" v:shapes="Picture_x0020_1"><![endif]></p>+ </body></html>+ """;+ var path = await WriteAsync("report.mht", string.Join("\r\n",+ "MIME-Version: 1.0",+ "Content-Type: multipart/related; boundary=\"----=_NextPart_01DB0000.12345678\"",+ "",+ "This document is a Single File Web Page, also known as a Web Archive file.",+ "",+ "------=_NextPart_01DB0000.12345678",+ "Content-Location: file:///C:/D0C1A2B3/report.htm",+ "Content-Transfer-Encoding: quoted-printable",+ "Content-Type: text/html; charset=\"windows-1252\"",+ "",+ QuotedPrintable(Html.ReplaceLineEndings("\n"), "windows-1252"),+ "",+ "------=_NextPart_01DB0000.12345678",+ "Content-Location: file:///C:/D0C1A2B3/report_files/image002.png",+ "Content-Transfer-Encoding: base64",+ "Content-Type: image/png",+ "",+ Base64Lines(Photo),+ "",+ "------=_NextPart_01DB0000.12345678",+ "Content-Location: file:///C:/D0C1A2B3/report_files/filelist.xml",+ "Content-Transfer-Encoding: quoted-printable",+ "Content-Type: text/xml; charset=\"utf-8\"",+ "",+ "<xml></xml>",+ "------=_NextPart_01DB0000.12345678--",+ ""));++ var html = await File.ReadAllTextAsync(await ConvertAsync(path, "html"), TestContext.Current.CancellationToken);+ Assert.Contains("Café crème – naïve", html);+ Assert.Contains($"src=\"data:image/png;base64,{Convert.ToBase64String(Photo)}\"", html);+ Assert.Contains("<body lang=\"EN-US\" style=\"tab-interval:.5in\">", html);+ Assert.DoesNotContain("file:", html);+ Assert.DoesNotContain("<v:", html);++ var text = await File.ReadAllTextAsync(await ConvertAsync(path, "txt"), TestContext.Current.CancellationToken);+ Assert.Contains("Café crème – naïve", text);+ }++ [Fact]+ public async Task Cid_references_in_euc_kr_base64_page_and_docx()+ {+ const string Html = "<html><head><title>사진 보고서</title></head><body><h1>보고서</h1><p>첫 문단에 한글이 있습니다.</p>" ++ "<p><img src=\"cid:photo@archive\" alt=\"사진\"></p><p><img src=\"cid:missing@archive\"></p>" ++ "<p><img src=\"data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=\"></p></body></html>";+ var path = await WriteAsync("보고서.mht", string.Join("\r\n",+ "MIME-Version: 1.0",+ "Content-Type: multipart/related; type=\"text/html\"; start=\"<page@archive>\"; boundary=\"b1\"",+ "",+ "--b1",+ "Content-Type: image/png",+ "Content-ID: <photo@archive>",+ "Content-Transfer-Encoding: base64",+ "",+ Base64Lines(Photo),+ "--b1",+ "Content-Type: text/html; charset=euc-kr",+ "Content-ID: <page@archive>",+ "Content-Transfer-Encoding: base64",+ "",+ Base64Lines(Encoding.GetEncoding("euc-kr").GetBytes(Html)),+ "--b1--",+ ""));++ var html = await File.ReadAllTextAsync(await ConvertAsync(path, "html"), TestContext.Current.CancellationToken);+ Assert.Contains("<title>사진 보고서</title>", html);+ Assert.Contains("<p>첫 문단에 한글이 있습니다.</p>", html);+ Assert.Contains($"src=\"data:image/png;base64,{Convert.ToBase64String(Photo)}\"", html);+ Assert.DoesNotContain("cid:", html);+ Assert.DoesNotContain("svg", html);++ var docx = await ConvertAsync(path, "docx");+ DocxAssert.ValidPackage(docx);+ var document = DocxAssert.ReadBack(docx);+ var paragraphs = DocxAssert.Paragraphs(document.Sections.SelectMany(s => s.Blocks)).Select(DocxAssert.TextOf).ToList();+ Assert.Contains("보고서", paragraphs);+ Assert.Contains("첫 문단에 한글이 있습니다.", paragraphs);+ using var zip = ZipFile.OpenRead(docx);+ Assert.Single(zip.Entries, e => e.FullName.StartsWith("word/media/", StringComparison.Ordinal));+ }++ [Fact]+ public async Task Archive_without_a_page_and_oversized_archives_fail_clearly()+ {+ var empty = await WriteAsync("empty.mhtml", "MIME-Version: 1.0\r\nContent-Type: image/png\r\nContent-Transfer-Encoding: base64\r\n\r\n" + Base64Lines(Photo) + "\r\n");+ var job = await fx.ConvertAsync([empty], new Preset { TargetFormat = "html" });+ Assert.Equal(JobState.Failed, job.State);+ Assert.Contains("no HTML page", job.Files.Single().ErrorDetail, StringComparison.OrdinalIgnoreCase);++ var huge = Path.Combine(fx.NewFolder(), "huge.mhtml");+ using (var file = File.Create(huge))+ file.SetLength(MhtmlArchive.MaxFileBytes + 1);+ var error = Assert.Throws<InvalidDataException>(() => MhtmlArchive.Load(huge, TestContext.Current.CancellationToken));+ Assert.Contains("larger than", error.Message);+ }++ [Fact]+ public async Task Mhtml_to_hwpx_and_pdf()+ {+ var archive = await ChromeArchiveAsync();+ var hwpx = await ConvertAsync(archive, "hwpx");+ var xml = HwpxAssert.Xml(hwpx).ToString();+ Assert.Contains("큰 제목", xml);+ Assert.DoesNotContain("injected", xml);++ var rhwp = fx.Converters.Single(c => c.Id == "rhwp");+ Assert.SkipUnless(fx.Catalog.StatusOf(rhwp).IsAvailable, "rhwp not found (pwsh build/fetch-engines.ps1 -Only rhwp)");+ var pdf = await ConvertAsync(archive, "pdf");+ Assert.Equal("%PDF", Encoding.ASCII.GetString((await File.ReadAllBytesAsync(pdf, TestContext.Current.CancellationToken))[..4]));+ }+}