Skip to content

armgit / Filee

Public Imported from GitHub
0

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.

JSON, YAML, TOML, XML and CSV convert into each other, vCard contacts to and from CSV, and Outlook MSG mails to EML, HTML, text and a ZIP of the attachments

KnifeLemon2c9b87cd16f6
diff --git a/Directory.Packages.props b/Directory.Packages.props
index e08ef703..b9e69b7b 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -47,6 +47,11 @@
<PackageVersion Include="MimeKitLite" Version="4.18.1" />
<PackageVersion Include="ACadSharp" Version="3.8.0" />
<PackageVersion Include="AngleSharp" Version="1.8.2" />
+ <PackageVersion Include="YamlDotNet" Version="18.1.0" />
+ <PackageVersion Include="Tomlyn" Version="2.10.1" />
+ <!-- 6.2 no longer reads files an attachment only links to (ATTACH_BY_REFERENCE) and caps nested messages and
+ stream sizes of untrusted .msg files; brings OpenMcdf (MPL-2.0), RtfPipe and UTF.Unknown (MPL-1.1). -->
+ <PackageVersion Include="MsgReader" Version="6.2.0" />
</ItemGroup>
<ItemGroup Label="Tests">
diff --git a/README.ko.md b/README.ko.md
index f6e5d109..ea37b5ba 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -84,8 +84,8 @@
| **이미지**: JPG, PNG, WEBP, AVIF, TIFF, BMP, GIF, ICO, ICNS, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, HEIC; GIMP XCF, 카메라 RAW(CR2, CR3, NEF, ARW, DNG 등)는 읽기 | 위 형식끼리(HEIC⁵), PDF, 크기 조정, 흑백 |
| **벡터**: SVG, SVGZ, EMF, WMF, AI · EPS, PS¹ · CDR, VSD, CGM, ODG² | PDF(벡터), PNG 등 이미지, SVG ↔ SVGZ, PDF → EPS/PS¹ |
| **PDF** | DOCX, HWPX, TXT, PNG, JPG, TIFF, CBZ; 합치기, 나누기, 페이지 범위 |
-| **문서**: DOCX, DOCM, DOTX, EML · DOC, ODT, RTF, WPS, WPD, Pages 등² | PDF, DOCX, HWPX, EPUB, TXT, HTML |
-| **스프레드시트**: XLSX, XLSM, XLS, ODS, CSV, TSV · Numbers, ET² | PDF, XLSX, ODS, CSV, TSV, HWPX, HTML |
+| **문서**: DOCX, DOCM, DOTX, EML, Outlook MSG · DOC, ODT, RTF, WPS, WPD, Pages 등² | PDF, DOCX, HWPX, EPUB, TXT, HTML; MSG → EML |
+| **스프레드시트**: XLSX, XLSM, XLS, ODS, CSV, TSV · Numbers, ET² | PDF, XLSX, ODS, CSV, TSV, JSON, HWPX, HTML |
| **프레젠테이션**: PPTX, PPTM, POTX, PPSX · PPT, ODP, Keynote² | PDF, PNG, JPG, DOCX, HWPX |
| **한글**: HWP, HWPX | PDF, PNG, DOCX, HWPX ↔ HWP, TXT, 마크다운, HTML |
| **텍스트**: TXT, 마크다운, HTML · reStructuredText, LaTeX³ | PDF, DOCX, HWPX, EPUB |
@@ -95,6 +95,7 @@
| **압축 파일**: ZIP, 7Z, RAR, TAR, TAR.GZ, TAR.BZ2, TAR.XZ, GZ, ISO, CAB, DMG, ALZ, EGG 등 | 압축 풀기, ZIP, 7Z, TAR, TAR.GZ; 여러 파일 → ZIP 하나 |
| **CAD**: DWG, DXF | PDF, SVG, PNG, DWG ↔ DXF |
| **글꼴**: TTF, OTF, WOFF, WOFF2, EOT | 서로 변환 |
+| **데이터**: JSON, JSON Lines, YAML, TOML, XML · vCard | 서로 변환, CSV·XLSX(표 모양 데이터); vCard ↔ CSV |
표시가 없는 형식은 오피스·한컴오피스·LibreOffice 없이 바로 변환돼요.
표시가 있는 형식은 추가 엔진이 필요하고, 필요할 때만 내려받아요: ¹ Ghostscript, ² LibreOffice, ³ Pandoc,
diff --git a/README.md b/README.md
index c2f73df1..868e336c 100644
--- a/README.md
+++ b/README.md
@@ -84,8 +84,8 @@ Filee shows new releases in its menu and updates itself, keeping your settings a
| **Images**: JPG, PNG, WEBP, AVIF, TIFF, BMP, GIF, ICO, ICNS, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, HEIC; GIMP XCF, camera RAW (CR2, CR3, NEF, ARW, DNG, …) read | any of these (HEIC⁵), PDF, resized, grayscale |
| **Vector**: SVG, SVGZ, EMF, WMF, AI · EPS, PS¹ · CDR, VSD, CGM, ODG² | PDF (vector), PNG and other images, SVG ↔ SVGZ, PDF → EPS/PS¹ |
| **PDF** | DOCX, HWPX, TXT, PNG, JPG, TIFF, CBZ; merge, split, page ranges |
-| **Documents**: DOCX, DOCM, DOTX, EML · DOC, ODT, RTF, WPS, WPD, Pages, …² | PDF, DOCX, HWPX, EPUB, TXT, HTML |
-| **Spreadsheets**: XLSX, XLSM, XLS, ODS, CSV, TSV · Numbers, ET² | PDF, XLSX, ODS, CSV, TSV, HWPX, HTML |
+| **Documents**: DOCX, DOCM, DOTX, EML, Outlook MSG · DOC, ODT, RTF, WPS, WPD, Pages, …² | PDF, DOCX, HWPX, EPUB, TXT, HTML; MSG → EML |
+| **Spreadsheets**: XLSX, XLSM, XLS, ODS, CSV, TSV · Numbers, ET² | PDF, XLSX, ODS, CSV, TSV, JSON, HWPX, HTML |
| **Presentations**: PPTX, PPTM, POTX, PPSX · PPT, ODP, Keynote² | PDF, PNG, JPG, DOCX, HWPX |
| **HWP**: HWP, HWPX | PDF, PNG, DOCX, HWPX ↔ HWP, TXT, Markdown, HTML |
| **Text**: TXT, Markdown, HTML · reStructuredText, LaTeX³ | PDF, DOCX, HWPX, EPUB |
@@ -95,6 +95,7 @@ Filee shows new releases in its menu and updates itself, keeping your settings a
| **Archives**: ZIP, 7Z, RAR, TAR, TAR.GZ, TAR.BZ2, TAR.XZ, GZ, ISO, CAB, DMG, ALZ, EGG, … | extract, ZIP, 7Z, TAR, TAR.GZ; any files → one ZIP |
| **CAD**: DWG, DXF | PDF, SVG, PNG, DWG ↔ DXF |
| **Fonts**: TTF, OTF, WOFF, WOFF2, EOT | each other |
+| **Data**: JSON, JSON Lines, YAML, TOML, XML · vCard | each other, CSV and XLSX (tables); vCard ↔ CSV |
Unmarked formats work out of the box, without Office, Hancom Office or LibreOffice.
Marked ones need an optional engine, downloaded only when needed: ¹ Ghostscript, ² LibreOffice, ³ Pandoc, ⁴ calibre,
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 9ca8989c..07e3327e 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -83,8 +83,8 @@
| **图片**:JPG、PNG、WEBP、AVIF、TIFF、BMP、GIF、ICO、ICNS、JPEG XL、JPEG 2000、PSD/PSB、TGA、PPM、HEIC;GIMP XCF、相机 RAW(CR2、CR3、NEF、ARW、DNG 等)仅读取 | 上述格式互转(HEIC⁵)、PDF、缩放、灰度 |
| **矢量图**:SVG、SVGZ、EMF、WMF、AI · EPS、PS¹ · CDR、VSD、CGM、ODG² | PDF(矢量)、PNG 等图片、SVG ↔ SVGZ、PDF → EPS/PS¹ |
| **PDF** | DOCX、HWPX、TXT、PNG、JPG、TIFF、CBZ;合并、拆分、页码范围 |
-| **文档**:DOCX、DOCM、DOTX、EML · DOC、ODT、RTF、WPS、WPD、Pages 等² | PDF、DOCX、HWPX、EPUB、TXT、HTML |
-| **表格**:XLSX、XLSM、XLS、ODS、CSV、TSV · Numbers、ET² | PDF、XLSX、ODS、CSV、TSV、HWPX、HTML |
+| **文档**:DOCX、DOCM、DOTX、EML、Outlook MSG · DOC、ODT、RTF、WPS、WPD、Pages 等² | PDF、DOCX、HWPX、EPUB、TXT、HTML、MSG → EML |
+| **表格**:XLSX、XLSM、XLS、ODS、CSV、TSV · Numbers、ET² | PDF、XLSX、ODS、CSV、TSV、JSON、HWPX、HTML |
| **演示文稿**:PPTX、PPTM、POTX、PPSX · PPT、ODP、Keynote² | PDF、PNG、JPG、DOCX、HWPX |
| **HWP**:HWP、HWPX | PDF、PNG、DOCX、HWPX ↔ HWP、TXT、Markdown、HTML |
| **文本**:TXT、Markdown、HTML · reStructuredText、LaTeX³ | PDF、DOCX、HWPX、EPUB |
@@ -94,6 +94,7 @@
| **压缩包**:ZIP、7Z、RAR、TAR、TAR.GZ、TAR.BZ2、TAR.XZ、GZ、ISO、CAB、DMG、ALZ、EGG 等 | 解压、ZIP、7Z、TAR、TAR.GZ;多个文件 → 一个 ZIP |
| **CAD**:DWG、DXF | PDF、SVG、PNG、DWG ↔ DXF |
| **字体**:TTF、OTF、WOFF、WOFF2、EOT | 互相转换 |
+| **数据**:JSON、JSON Lines、YAML、TOML、XML · vCard | 互相转换、CSV 和 XLSX(表格数据)、vCard ↔ CSV |
未标注的格式装好即用,无需 Office、韩文办公软件或 LibreOffice。
标注的格式需要可选引擎,只在需要时下载,分别是 ¹ Ghostscript、² LibreOffice、³ Pandoc、⁴ calibre、⁵ FFmpeg
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
index a8ca94ba..74ae2144 100644
--- a/THIRD-PARTY-NOTICES.md
+++ b/THIRD-PARTY-NOTICES.md
@@ -25,6 +25,13 @@ Each component remains under its own license.
| ExcelDataReader | MIT | https://github.com/ExcelDataReader/ExcelDataReader |
| PdfPig (PDF text, layout and pictures) | Apache-2.0 | https://github.com/UglyToad/PdfPig |
| MimeKitLite (e-mail / MIME parsing) | MIT | https://github.com/jstedfast/MimeKit |
+| MsgReader (Outlook .msg reading) | MIT, Copyright (c) Kees van Spelde | https://github.com/Sicos1977/MSGReader |
+| OpenMcdf (OLE compound files, used by MsgReader) | MPL-2.0 (source: the project page) | https://github.com/openmcdf/openmcdf |
+| RtfPipe (RTF → HTML, used by MsgReader) | MIT, Copyright (c) 2018 Eric Domke | https://github.com/erdomke/RtfPipe |
+| UTF.Unknown (charset detection, used by MsgReader) | MPL-1.1 (source: the project page) | https://github.com/CharsetDetector/UTF-unknown |
+| Microsoft.Maui.Graphics, Microsoft.IO.RecyclableMemoryStream (used by MsgReader) | MIT | https://github.com/dotnet/maui, https://github.com/microsoft/Microsoft.IO.RecyclableMemoryStream |
+| YamlDotNet (YAML reading and writing) | MIT, Copyright (c) Antoine Aubry and contributors | https://github.com/aaubry/YamlDotNet |
+| Tomlyn (TOML reading) | BSD-2-Clause, Copyright (c) Alexandre Mutel | https://github.com/xoofx/Tomlyn |
| ACadSharp (DWG/DXF reading and writing; includes CSMath and CSUtilities) | MIT, Copyright (c) Albert Domenech | https://github.com/DomCR/ACadSharp |
| AngleSharp | MIT | https://github.com/AngleSharp/AngleSharp |
| pypandoc-hwpx (Pandoc AST mapping and package layout in `Filee.Engines/Hwp/Hwpx`, incl. the `blank.hwpx` reference document) | MIT, Copyright (c) 2024 pypandoc-hwpx Contributors | https://github.com/msjang/pypandoc-hwpx |
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index e1434f2f..2ea40406 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -22,7 +22,7 @@
│ Built in: Magick (images, RAW) · PdfSharp · Pdfium · PdfPig · Svg.Skia · ICNS │
│ HwpxWriter + DocxWriter over DocumentReaders (DOCX, XLSX, XLS, ODS, PPTX, │
│ PDF, HTML, EPUB, MOBI, FB2, HWPX, Markdown) · Spreadsheets · OOXML variants │
- │ · E-mail · E-books · CAD · Fonts │
+ │ · E-mail · Data · E-books · CAD · Fonts │
│ Bundled: rhwp (HWP→PDF, HWP↔HWPX) · 7-Zip (archives) · Unhwp · Markdig │
│ Optional: FFmpeg · LibreOffice + H2Orestart · calibre · Ghostscript · Pandoc │
└────────────────────────────────────────────────────────────────────────────────────┘
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index da0fca5f..d345e2cf 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -18,7 +18,8 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| **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** |
| PDF text | built in (PdfPig) | **PDF → TXT** (reading order, also two columns; no OCR) |
-| E-mail | built in (MimeKit) | **EML → HTML** (headers + body, inline pictures), **TXT**, **ZIP** (the attachments) |
+| E-mail | built in (MimeKit, MsgReader) | **EML, Outlook MSG → HTML** (headers + body, inline pictures), **TXT**, **ZIP** (the attachments); **MSG → EML** |
+| 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 |
| CAD (ACadSharp + built-in renderer) | built in (library) | **DWG ↔ DXF**; DWG/DXF → **PDF** (vector), **SVG**, PNG, JPG, WEBP, TIFF, BMP, GIF, ICO, AVIF |
| rhwp | bundled with the installer (`engines/rhwp`) | HWP/HWPX → PDF, **HWP → HWPX, HWPX → HWP** |
@@ -287,11 +288,52 @@ XLSM → CSV, PPSX → DOCX ...).
headers (RFC 2047 / 2231) and charsets including EUC-KR / CP949 and ISO-2022-KR; raw 8-bit header text that is not
UTF-8 is read as CP949, as older Korean mail programs wrote it.
+Outlook .msg files are read with MsgReader (MIT, `Email/OutlookMessage.cs`) and rebuilt as a MIME message with
+MimeKit: sender, To / Cc / Bcc, subject, sent date, Message-ID, the text and HTML bodies (MsgReader takes the HTML out
+of RTF-only messages), attachments, pictures the HTML shows (`cid:`, kept with the body) and attached Outlook items
+(as attached .eml messages). That message then goes the EML way below, so MSG → HTML / TXT / ZIP are direct edges
+(cost 10; through EML would be 20 and parse twice) and **MSG → EML** writes the rebuilt message. Attachments that only
+link to a file elsewhere (`ATTACH_BY_REFERENCE`) are not followed. MsgReader brings OpenMcdf (MPL-2.0, the compound
+file reader), RtfPipe (MIT) and UTF.Unknown (MPL-1.1, charset detection for old ANSI messages).
+
- **EML → HTML**: a standalone page with From / To / Cc / Date / Subject / Attachments and the HTML body (its style
sheets kept, scripts removed) or the text body; pictures sent inline (`cid:`) become data URIs.
- **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.
+## Data (JSON, YAML, TOML, XML, CSV, vCard)
+
+`Data/DataConverter.cs` (engine id `data`) reads every format into one tree (`Data/DataTree.cs`: objects with their
+keys in file order, arrays, text, true / false, integers of any size, floats, TOML dates and null) and writes it
+again, so structure and types carry over as far as the target can hold them. Output is UTF-8 without BOM with LF
+line ends, indented by two spaces (CSV: like the spreadsheet engine, UTF-8 with BOM and CRLF for Excel). There are no
+options: the output is always pretty-printed.
+
+| Format | Library | Read | Written / lost |
+|---|---|---|---|
+| JSON (`.json`) | System.Text.Json | comments and trailing commas allowed (JSONC) | non-ASCII text as it is; NaN / infinities as text ("NaN") |
+| JSON Lines (`.jsonl`, `.ndjson`) | System.Text.Json | one value per line, blank lines skipped, read as an array | one compact line per record (the array, or the array inside wrappers, see CSV) |
+| YAML (`.yaml`, `.yml`) | YamlDotNet (MIT) | YAML 1.2 core schema: unquoted `true`, `null` / `~`, numbers (`0x`, `0o`, `.inf`, `.nan`) are typed, the rest and anything quoted is text (`yes` / `no` stay text); explicit `!!str` / `!!int` … tags; anchors and aliases resolved (copied), merge keys (`<<`) applied; several documents (`---`) become an array; comments dropped; alias "bombs" (more than 5 million values) and nesting deeper than 256 refused | block style; text that would read back as another type (`"true"`, `"007"`, `""`, YAML 1.1's `yes` / `on`, dates) is quoted; multi-line text as a literal block (`\|`) |
+| TOML (`.toml`) | Tomlyn (BSD-2-Clause, TOML 1.1) | dates and times keep their TOML spelling (text in JSON / YAML) | written by Filee: plain keys, then `[tables]` and `[[arrays of tables]]`; **null values are left out** (TOML has none); a root that is not an object goes under `items` (`[[items]]`); integers beyond 64 bits as text |
+| XML (`.xml`) | System.Xml | root element = an object with one key; attributes as `@name`, text next to attributes or children as `#text`, repeated elements as an array (**one child is no array**), `<a/>` → null, `<a></a>` → empty text, CDATA as text; all values are text (XML has no types); comments, processing instructions and the DTD dropped, external entities never loaded; the encoding from the declaration (EUC-KR …) | a root that is not one object with one key goes into `<root>`, items of nested arrays into `<item>`; names that are not XML names are escaped (`first name` → `first_x0020_name`, unescaped when read back); `x:name` keeps its namespace when `@xmlns:x` declares it; control characters XML 1.0 can't hold are removed |
+| CSV (`.csv`) | Filee (`Office/Sheets/CsvFormat.cs`) | first row = keys, one object per row; plain numbers (not `007`) and `true` / `false` typed, the rest text; delimiter and encoding detected as for spreadsheets | only tables: an array of objects (columns = every key, first seen first; an object inside a row becomes `parent.child` columns, one level only), an object of arrays (columns), an array of arrays (rows) or one flat object (one row); objects that only wrap the array (`{"users": […]}`, `<rows><row/>…</rows>`) are looked through. Anything else stops with a message saying what is not a table |
+
+**`.csv` and `.xml` ownership.** CSV stays a spreadsheet format: the spreadsheets donut, XLSX / ODS routes and
+"Merge into PDF" are unchanged, and the data engine only adds edges `csv ↔ json / jsonl / yaml / toml / xml`. Routes
+combine: XLSX → CSV → JSON, YAML → CSV → XLSX, vCard → CSV → JSON. The spreadsheets donut gets "JSON". `.xml` had no
+owner before; XML-based formats Filee converts have their own extensions (`.svg`, `.fb2`, `.dbk`, `.opml` …), so a
+plain `.xml` file is treated as data and opens the data donut.
+
+**vCard** (`Data/VCard.cs`, own parser): vCard 2.1, 3.0 and 4.0 → CSV with the columns Full name, Given name, Family
+name, Organization, Title, Email, Phone, Address, Birthday, Note (one row per contact; several values joined with
+`; `, each with its kind in brackets: `010-1234-5678 (mobile); 02-123-4567 (work)`). Folded lines, quoted-printable
+with soft line breaks, `CHARSET` parameters, escapes, groups (`item1.EMAIL`), 2.1's bare types (`TEL;CELL`) and 4.0's
+quoted type lists and `tel:` URIs are read; a value without `CHARSET` is UTF-8 when valid, else CP949 (address books
+of older Korean phones); UTF-16 files with a BOM are read too. Pictures and nested cards (2.1 `AGENT`) are skipped,
+a missing full name is made from the name parts (홍길동, "Ada Lovelace"). CSV → vCard reads those columns (also
+`Name`, `Company`, `Mobile`, `E-mail` … and Korean / Chinese headers such as 이름, 전화번호, 이메일, 姓名, 电话) and writes
+vCard 3.0 in UTF-8, lines folded at 75 bytes; an address goes into the street field.
+
## CAD drawings (DWG, DXF)
Built in, no AutoCAD or ODA software (`Filee.Engines/Cad`). [ACadSharp](https://github.com/DomCR/ACadSharp) reads
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 2828fbba..e0af6097 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -71,7 +71,8 @@
"engine.hwpx-writer.description": "Writes HWPX from Word, Excel, PowerPoint, PDF, HTML, e-books and Markdown.\nThe first step of turning documents into PDF without Office.",
"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.email.description": "E-mails (EML) to HTML and text with sender, recipients and date, pictures included; attachments into a ZIP.",
+ "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.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 and to images; Illustrator files saved with PDF content.",
"engine.icns.description": "macOS app icons (ICNS) from and to images.",
"engine.font.description": "Fonts: TTF, OTF, WOFF, WOFF2 and EOT into each other.",
@@ -98,6 +99,7 @@
"profile.archives": "Archives",
"profile.cad": "CAD drawings",
"profile.fonts": "Fonts",
+ "profile.data": "Data",
"profile.mixed": "Mixed files",
"preset.half_size": "Half size",
@@ -124,6 +126,7 @@
"format.category.Vector": "Vector",
"format.category.Cad": "CAD",
"format.category.Font": "Font",
+ "format.category.Data": "Data",
"general.title": "General",
"general.language": "Language",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index c0074be4..bb4ea560 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -71,7 +71,8 @@
"engine.hwpx-writer.description": "워드, 엑셀, 파워포인트, PDF, HTML, 전자책, 마크다운을 HWPX로 써요.\n오피스 없이 문서를 PDF로 바꾸는 첫 단계예요.",
"engine.docx-writer.description": "PDF, HWP/HWPX, 마크다운, HTML, 스프레드시트, 슬라이드, 전자책으로 워드 문서(DOCX)를 만들어요.",
"engine.pdf-text.description": "PDF의 글자를 읽는 순서대로 뽑아내요.\n2단 편집도 순서대로 읽어요(스캔 이미지 글자 인식은 안 해요).",
- "engine.email.description": "이메일(EML)을 보낸 사람·받는 사람·날짜와 본문 그림까지 담아 HTML·텍스트로 바꾸고, 첨부 파일은 ZIP으로 모아요.",
+ "engine.email.description": "이메일(EML, Outlook MSG)을 보낸 사람·받는 사람·날짜와 본문 그림까지 담아 HTML·텍스트로 바꾸고, 첨부 파일은 ZIP으로 모아요.\nMSG는 EML로도 바꿔요.",
+ "engine.data.description": "JSON, JSON Lines, YAML, TOML, XML, CSV를 서로 바꿔요.\nvCard 연락처를 CSV로, CSV를 vCard로 바꿔요.\n주석은 빠져요. CSV는 표 모양 데이터만 담아요.",
"engine.vector.description": "SVG·SVGZ를 벡터 PDF와 이미지로, PDF 내용이 들어 있는 일러스트레이터 파일도 변환해요.",
"engine.icns.description": "macOS 앱 아이콘(ICNS)을 이미지로, 이미지를 ICNS로.",
"engine.font.description": "글꼴: TTF, OTF, WOFF, WOFF2, EOT를 서로 변환해요.",
@@ -98,6 +99,7 @@
"profile.archives": "압축 파일",
"profile.cad": "CAD 도면",
"profile.fonts": "글꼴",
+ "profile.data": "데이터",
"profile.mixed": "혼합 파일",
"preset.half_size": "50% 축소",
@@ -124,6 +126,7 @@
"format.category.Vector": "벡터",
"format.category.Cad": "CAD",
"format.category.Font": "글꼴",
+ "format.category.Data": "데이터",
"general.title": "일반",
"general.language": "언어",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index 8ec41bb7..10960f6d 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -71,7 +71,8 @@
"engine.hwpx-writer.description": "把 Word、Excel、PowerPoint、PDF、HTML、电子书和 Markdown 写成 HWPX。\n这是不用 Office 把文档转为 PDF 的第一步。",
"engine.docx-writer.description": "用 PDF、HWP/HWPX、Markdown、HTML、表格、幻灯片和电子书生成 Word 文档(DOCX)。",
"engine.pdf-text.description": "按阅读顺序提取 PDF 中的文字,双栏页面也能正确排序(不对扫描件做文字识别)。",
- "engine.email.description": "将电子邮件(EML)连同发件人、收件人、日期和图片转为 HTML 和文本,附件打包为 ZIP。",
+ "engine.email.description": "将电子邮件(EML、Outlook MSG)连同发件人、收件人、日期和图片转为 HTML 和文本,附件打包为 ZIP。\nMSG 也可转为 EML。",
+ "engine.data.description": "JSON、JSON Lines、YAML、TOML、XML、CSV 互相转换。\nvCard 联系人与 CSV 互转。\n注释不保留。CSV 仅支持表格数据。",
"engine.vector.description": "将 SVG、SVGZ 转为矢量 PDF 和图片;也支持包含 PDF 内容的 Illustrator 文件。",
"engine.icns.description": "macOS 应用图标(ICNS)与图片互转。",
"engine.font.description": "字体:TTF、OTF、WOFF、WOFF2 和 EOT 互相转换。",
@@ -98,6 +99,7 @@
"profile.archives": "压缩文件",
"profile.cad": "CAD 图纸",
"profile.fonts": "字体",
+ "profile.data": "数据",
"profile.mixed": "混合文件",
"preset.half_size": "缩小 50%",
@@ -124,6 +126,7 @@
"format.category.Vector": "矢量图",
"format.category.Cad": "CAD",
"format.category.Font": "字体",
+ "format.category.Data": "数据",
"general.title": "常规",
"general.language": "语言",
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index b608376d..04f998d1 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -232,8 +232,9 @@ public sealed partial class PresetEditorViewModel : ObservableObject
public bool ShowWebp => TargetId is "webp" or BuiltInData.SameAsSource;
public bool ShowMultiPageTiff => TargetId is "tiff";
public bool ShowIco => TargetId == "ico";
- /// <summary>PDF options (also used when a PDF source becomes images) mean nothing for media, archive and font targets.</summary>
- public bool ShowPdf => TargetCategory is not (FormatCategory.Video or FormatCategory.Audio or FormatCategory.Archive or FormatCategory.Font);
+ /// <summary>PDF options (also used when a PDF source becomes images) mean nothing for media, archive, font and data targets.</summary>
+ public bool ShowPdf => TargetCategory is not (FormatCategory.Video or FormatCategory.Audio or FormatCategory.Archive or FormatCategory.Font or FormatCategory.Data)
+ && TargetId != "eml";
public bool ShowPdfBuild => TargetId == "pdf";
public bool ShowPdfSplit => TargetId == "pdf";
diff --git a/src/Filee.Core/Formats/FileFormat.cs b/src/Filee.Core/Formats/FileFormat.cs
index c8049d3d..34a9f0a3 100644
--- a/src/Filee.Core/Formats/FileFormat.cs
+++ b/src/Filee.Core/Formats/FileFormat.cs
@@ -19,6 +19,7 @@ public enum FormatCategory
Vector,
Cad,
Font,
+ Data,
}
/// <summary>
diff --git a/src/Filee.Core/Formats/FormatRegistry.cs b/src/Filee.Core/Formats/FormatRegistry.cs
index 46c2be56..9072ef07 100644
--- a/src/Filee.Core/Formats/FormatRegistry.cs
+++ b/src/Filee.Core/Formats/FormatRegistry.cs
@@ -66,7 +66,8 @@ public static class FormatRegistry
new("pages", "Pages", FormatCategory.Document, ["pages"], Writable: false),
new("sdw", "SDW", FormatCategory.Document, ["sdw"], Writable: false),
new("pub", "PUB", FormatCategory.Document, ["pub"], Writable: false),
- new("eml", "EML", FormatCategory.Document, ["eml"], Writable: false),
+ new("eml", "EML", FormatCategory.Document, ["eml"]),
+ new("msg", "MSG", FormatCategory.Document, ["msg"], Writable: false),
// Korean word processor (Hancom)
new("hwpx", "HWPX", FormatCategory.Hwp, ["hwpx"]),
@@ -102,6 +103,16 @@ public static class FormatRegistry
new("rst", "reStructuredText", FormatCategory.Text, ["rst"]),
new("tex", "LaTeX", FormatCategory.Text, ["tex", "latex"]),
+ // Structured data. CSV stays a spreadsheet (its donut and routes); the data engine adds CSV ↔ JSON / YAML /
+ // TOML / XML edges. ".xml" means a data document here: XML-based formats Filee converts have their own
+ // extensions (.svg, .fb2, .dbk, ...).
+ new("json", "JSON", FormatCategory.Data, ["json"]),
+ new("jsonl", "JSON Lines", FormatCategory.Data, ["jsonl", "ndjson"]),
+ new("yaml", "YAML", FormatCategory.Data, ["yaml", "yml"]),
+ new("toml", "TOML", FormatCategory.Data, ["toml"]),
+ new("xml", "XML", FormatCategory.Data, ["xml"]),
+ new("vcf", "vCard", FormatCategory.Data, ["vcf", "vcard"]),
+
// E-books
new("epub", "EPUB", FormatCategory.Ebook, ["epub"]),
new("mobi", "MOBI", FormatCategory.Ebook, ["mobi"]),
diff --git a/src/Filee.Core/Presets/BuiltInData.cs b/src/Filee.Core/Presets/BuiltInData.cs
index 65fab5c3..59a16e28 100644
--- a/src/Filee.Core/Presets/BuiltInData.cs
+++ b/src/Filee.Core/Presets/BuiltInData.cs
@@ -74,6 +74,7 @@ public static class BuiltInData
new() { Id = "to-html", Name = "HTML", TargetFormat = "html" },
.. SpreadsheetPresets(),
.. CatalogPresets(),
+ .. DataPresets(),
];
/// <summary>HWP as a target, through HWPX (added in settings schema 7, see SettingsMigrations).</summary>
@@ -165,6 +166,20 @@ public static class BuiltInData
new() { Id = "to-eot", Name = "EOT", TargetFormat = "eot" },
];
+ /// <summary>
+ /// Structured data and contacts targets (added in settings schema 11, see SettingsMigrations). EML is for Outlook
+ /// MSG files, vCard for contact lists in CSV; neither is on a donut.
+ /// </summary>
+ public static List<Preset> DataPresets() =>
+ [
+ new() { Id = "to-json", Name = "JSON", TargetFormat = "json" },
+ new() { Id = "to-yaml", Name = "YAML", TargetFormat = "yaml" },
+ new() { Id = "to-toml", Name = "TOML", TargetFormat = "toml" },
+ new() { Id = "to-xml", Name = "XML", TargetFormat = "xml" },
+ new() { Id = "to-eml", Name = "EML", TargetFormat = "eml" },
+ new() { Id = "to-vcf", Name = "vCard", TargetFormat = "vcf" },
+ ];
+
/// <summary>Creates the default toolbar profiles.</summary>
public static List<ToolbarProfile> CreateProfiles() =>
[
@@ -196,6 +211,7 @@ public static class BuiltInData
},
TextProfile(),
.. CatalogProfiles(),
+ DataProfile(),
new()
{
Id = "mixed", NameKey = "profile.mixed", IsFallback = true,
@@ -209,7 +225,7 @@ public static class BuiltInData
Id = "spreadsheets",
NameKey = "profile.spreadsheets",
Extensions = ExtensionsOf(FormatCategory.Spreadsheet),
- PresetIds = ["to-pdf", "to-xlsx", "to-csv", "to-ods", "to-hwpx", "to-hwp", "to-html", "merge-pdf"],
+ PresetIds = ["to-pdf", "to-xlsx", "to-csv", "to-json", "to-ods", "to-hwpx", "to-hwp", "to-html", "merge-pdf"],
};
/// <summary>PowerPoint and OpenDocument slides (split from "office" in settings schema 5).</summary>
@@ -277,6 +293,15 @@ public static class BuiltInData
},
];
+ /// <summary>JSON, YAML, TOML, XML and vCard files (added in settings schema 11, after "fonts").</summary>
+ public static ToolbarProfile DataProfile() => new()
+ {
+ Id = "data",
+ NameKey = "profile.data",
+ Extensions = ExtensionsOf(FormatCategory.Data),
+ PresetIds = ["to-json", "to-yaml", "to-toml", "to-xml", "to-csv", "to-xlsx"],
+ };
+
/// <summary>Every file extension of the formats in <paramref name="category"/>.</summary>
public static List<string> ExtensionsOf(FormatCategory category) =>
FormatRegistry.Known.Where(f => f.Category == category)
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
index 7e4f98ea..bb6d8b4e 100644
--- a/src/Filee.Core/Settings/AppSettings.cs
+++ b/src/Filee.Core/Settings/AppSettings.cs
@@ -50,7 +50,7 @@ public sealed class DonutSettings
public sealed class AppSettings
{
/// <summary>Current schema version. Increase when the format changes and add a migration.</summary>
- public const int CurrentSchemaVersion = 10;
+ public const int CurrentSchemaVersion = 11;
public int SchemaVersion { get; set; } = CurrentSchemaVersion;
@@ -89,7 +89,7 @@ public sealed class AppSettings
public List<string> EnginePriority { get; set; } =
[
"magick", "pdfium", "pdfsharp", "rhwp", "unhwp", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer",
- "pdf-text", "email", "vector", "icns", "font", "cad", "archive", "ebook", "ffmpeg", "pandoc", "ghostscript", "calibre",
+ "pdf-text", "email", "data", "vector", "icns", "font", "cad", "archive", "ebook", "ffmpeg", "pandoc", "ghostscript", "calibre",
"libreoffice",
];
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
index ae92ef14..1d12a825 100644
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -252,6 +252,16 @@ internal static class SettingsMigrations
InsertBefore(settings.EnginePriority, id, "libreoffice");
}
+ // v11: built-in "data" engine (JSON, YAML, TOML, XML, CSV, vCard), next to the e-mail engine.
+ if (settings.SchemaVersion < 11 && !settings.EnginePriority.Contains("data"))
+ {
+ var email = settings.EnginePriority.IndexOf("email");
+ if (email >= 0)
+ settings.EnginePriority.Insert(email + 1, "data");
+ else
+ InsertBefore(settings.EnginePriority, "data", "pandoc");
+ }
+
if (settings.Triggers.Count == 0)
settings.Triggers = TriggerGesture.Defaults();
@@ -360,21 +370,53 @@ internal static class SettingsMigrations
presets.Add(BuiltInData.CreatePresets().Single(p => p.Id == "remove-background"));
changed = true;
}
+
+ // v11: structured data (JSON, YAML, TOML, XML, vCard) gets its own donut after "fonts", Outlook MSG joins
+ // the documents donut next to EML, and the spreadsheets donut gets JSON after CSV.
+ if (from < 11)
+ changed |= AddData(presets, profiles);
return changed;
}
- private static bool AddCatalog(List<Preset> presets, List<ToolbarProfile> profiles)
+ private static bool AddData(List<Preset> presets, List<ToolbarProfile> profiles)
{
var changed = false;
- foreach (var preset in BuiltInData.CatalogPresets().Where(p => presets.All(existing => existing.Id != p.Id)))
+ foreach (var preset in BuiltInData.DataPresets().Where(p => presets.All(existing => existing.Id != p.Id)))
{
presets.Add(preset);
changed = true;
}
- var presetIds = presets.Select(p => p.Id).ToHashSet();
+ changed |= LearnExtensions(profiles, out var claimed);
+
+ if (profiles.All(p => p.Id != "data"))
+ {
+ var data = BuiltInData.DataProfile();
+ // Only the extensions no donut of the user takes yet.
+ data.Extensions = data.Extensions.Where(claimed.Add).ToList();
+ if (data.Extensions.Count > 0)
+ {
+ var presetIds = presets.Select(p => p.Id).ToHashSet();
+ data.PresetIds = data.PresetIds.Where(presetIds.Contains).ToList();
+ var fonts = profiles.FindIndex(p => p.Id == "fonts");
+ var insertAt = fonts >= 0 ? fonts + 1 : profiles.FindIndex(p => p.IsFallback);
+ profiles.Insert(insertAt < 0 ? profiles.Count : insertAt, data);
+ changed = true;
+ }
+ }
+
+ changed |= Offer(presets, profiles, "spreadsheets", "to-json", "to-csv");
+ return changed;
+ }
+ /// <summary>
+ /// Adds the default extensions of the built-in donuts that no donut of the user takes yet.
+ /// </summary>
+ /// <param name="claimed">Every extension a donut takes afterwards.</param>
+ private static bool LearnExtensions(List<ToolbarProfile> profiles, out HashSet<string> claimed)
+ {
+ var changed = false;
// Extensions checked on a mixed-selection profile only limit that profile; they don't claim files.
- var claimed = profiles.Where(p => !p.IsFallback).SelectMany(p => p.Extensions).ToHashSet(StringComparer.OrdinalIgnoreCase);
+ claimed = profiles.Where(p => !p.IsFallback).SelectMany(p => p.Extensions).ToHashSet(StringComparer.OrdinalIgnoreCase);
var defaults = BuiltInData.CreateProfiles().ToDictionary(p => p.Id);
foreach (var profile in profiles.Where(p => !p.IsFallback && defaults.ContainsKey(p.Id)))
{
@@ -384,6 +426,19 @@ internal static class SettingsMigrations
changed = true;
}
}
+ return changed;
+ }
+
+ private static bool AddCatalog(List<Preset> presets, List<ToolbarProfile> profiles)
+ {
+ var changed = false;
+ foreach (var preset in BuiltInData.CatalogPresets().Where(p => presets.All(existing => existing.Id != p.Id)))
+ {
+ presets.Add(preset);
+ changed = true;
+ }
+ var presetIds = presets.Select(p => p.Id).ToHashSet();
+ changed |= LearnExtensions(profiles, out var claimed);
var text = profiles.FindIndex(p => p.Id == "text");
var insertAt = text >= 0 ? text + 1 : profiles.FindIndex(p => p.IsFallback);
diff --git a/src/Filee.Engines/Data/CsvData.cs b/src/Filee.Engines/Data/CsvData.cs
new file mode 100644
index 00000000..3ffe3c2c
--- /dev/null
+++ b/src/Filee.Engines/Data/CsvData.cs
@@ -0,0 +1,159 @@
+// CSV ↔ the data tree. CSV is read like the spreadsheet engine reads it (delimiter and encoding detected, see
+// CsvFormat): the first row names the columns and every other row becomes an object. Cells that are plain numbers
+// (not "007") or true / false get that type; everything else, empty cells included, stays text.
+// Only tables become CSV: an array of objects (columns = every key, in the order first seen), an object of arrays
+// (one column per key), an array of arrays (rows as they are) or a single flat object (one row). Objects inside a row
+// one level deep become "parent.child" columns; deeper nesting, or a list inside a row, is an error. Wrappers around
+// the array (an object with only that key, XML's <rows><row/>…</rows>) are looked through. Written as the spreadsheet
+// engine writes CSV: UTF-8 with BOM, CRLF, so Excel opens Korean text correctly.
+
+using System.Text.RegularExpressions;
+using Filee.Engines.Hwp.Hwpx;
+using Filee.Engines.Office.Sheets;
+
+namespace Filee.Engines.Data;
+
+internal static partial class CsvData
+{
+ /// <summary>The rows of a CSV file as text, delimiter (comma, semicolon or tab) and encoding detected.</summary>
+ public static List<List<string>> ReadRows(string path)
+ {
+ var text = HwpxConverter.DecodeText(File.ReadAllBytes(path));
+ var rows = CsvFormat.Parse(text, CsvFormat.DetectDelimiter(text));
+ rows.RemoveAll(row => row.All(cell => cell.Length == 0));
+ return rows;
+ }
+
+ /// <summary>A CSV file as an array of objects keyed by the header row.</summary>
+ public static List<object?> Read(string path)
+ {
+ var rows = ReadRows(path);
+ if (rows.Count == 0)
+ return [];
+ var headers = UniqueHeaders(rows[0]);
+ var records = new List<object?>();
+ foreach (var row in rows.Skip(1))
+ {
+ while (headers.Count < row.Count)
+ headers.Add($"column{headers.Count + 1}");
+ var record = new DataMap();
+ for (var c = 0; c < headers.Count; c++)
+ record[headers[c]] = Typed(c < row.Count ? row[c] : "");
+ records.Add(record);
+ }
+ return records;
+ }
+
+ /// <summary>Header names: blank ones become "columnN", repeated ones get "_2", "_3".</summary>
+ private static List<string> UniqueHeaders(List<string> row)
+ {
+ var used = new HashSet<string>(StringComparer.Ordinal);
+ var headers = new List<string>();
+ for (var c = 0; c < row.Count; c++)
+ {
+ var name = row[c].Trim();
+ if (name.Length == 0)
+ name = $"column{c + 1}";
+ var unique = name;
+ for (var i = 2; !used.Add(unique); i++)
+ unique = $"{name}_{i}";
+ headers.Add(unique);
+ }
+ return headers;
+ }
+
+ private static object? Typed(string cell)
+ {
+ if (cell.Length is > 0 and < 20 && JsonNumber().IsMatch(cell))
+ return DataTree.Number(cell);
+ if (cell.Equals("true", StringComparison.OrdinalIgnoreCase))
+ return true;
+ if (cell.Equals("false", StringComparison.OrdinalIgnoreCase))
+ return false;
+ return cell;
+ }
+
+ /// <summary>Writes a table-like tree as CSV, or explains why it is not a table.</summary>
+ public static void Write(object? root, string path) => CsvFormat.WriteRows(Table(root), path);
+
+ /// <summary>The header row and the rows of a table-like tree.</summary>
+ internal static List<List<string>> Table(object? root)
+ {
+ var node = DataTree.UnwrapRecords(root);
+ switch (node)
+ {
+ case List<object?> list when list.Count == 0:
+ return [];
+ case List<object?> list when list.All(item => item is DataMap or null):
+ return Records(list.Select(item => item as DataMap ?? new DataMap()).ToList());
+ case List<object?> list when list.All(item => item is List<object?> row && row.All(DataTree.IsScalar)):
+ return list.Select(item => ((List<object?>)item!).Select(DataTree.Text).ToList()).ToList();
+ case List<object?> list when list.All(DataTree.IsScalar):
+ return [["value"], .. list.Select(item => new List<string> { DataTree.Text(item) })];
+ case DataMap map when map.Count > 0 && map.Values.All(v => v is List<object?> column && column.All(DataTree.IsScalar)):
+ return Columns(map);
+ case DataMap map:
+ return Records([map]);
+ case List<object?>:
+ throw NotATable("The array mixes objects, lists and single values");
+ default:
+ throw NotATable("The data is a single value");
+ }
+ }
+
+ private static List<List<string>> Records(List<DataMap> records)
+ {
+ var columns = new List<string>();
+ var known = new HashSet<string>(StringComparer.Ordinal);
+ var flat = new List<Dictionary<string, string>>();
+ for (var r = 0; r < records.Count; r++)
+ {
+ var cells = new Dictionary<string, string>(StringComparer.Ordinal);
+ foreach (var (key, value) in records[r])
+ {
+ if (value is DataMap nested)
+ {
+ foreach (var (childKey, child) in nested)
+ {
+ if (!DataTree.IsScalar(child))
+ throw NotATable($"Row {r + 1}, “{key}.{childKey}” is nested more than one level");
+ Add($"{key}.{childKey}", child);
+ }
+ }
+ else if (value is List<object?>)
+ {
+ throw NotATable($"Row {r + 1}, “{key}” holds a list");
+ }
+ else
+ {
+ Add(key, value);
+ }
+ }
+ flat.Add(cells);
+
+ void Add(string column, object? value)
+ {
+ if (known.Add(column))
+ columns.Add(column);
+ cells[column] = DataTree.Text(value);
+ }
+ }
+ return [columns, .. flat.Select(cells => columns.Select(c => cells.GetValueOrDefault(c, "")).ToList())];
+ }
+
+ private static List<List<string>> Columns(DataMap map)
+ {
+ var columns = map.Values.Cast<List<object?>>().ToList();
+ var height = columns.Max(c => c.Count);
+ var rows = new List<List<string>> { map.Keys.ToList() };
+ for (var r = 0; r < height; r++)
+ rows.Add(columns.Select(c => r < c.Count ? DataTree.Text(c[r]) : "").ToList());
+ return rows;
+ }
+
+ private static InvalidDataException NotATable(string what) =>
+ new($"{what}: CSV holds a table. Convert an array of objects (one level of nesting at most), an object of arrays or an array of arrays.");
+
+ [GeneratedRegex(@"^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?$")]
+ private static partial Regex JsonNumber();
+}
diff --git a/src/Filee.Engines/Data/DataConverter.cs b/src/Filee.Engines/Data/DataConverter.cs
new file mode 100644
index 00000000..258b2f31
--- /dev/null
+++ b/src/Filee.Engines/Data/DataConverter.cs
@@ -0,0 +1,108 @@
+// Structured data between JSON, JSON Lines, YAML, TOML and XML (and CSV for tables), plus vCard contacts ↔ CSV,
+// in-process. Every format is read into one tree (DataTree) and written from it, so structure and types carry over as
+// far as the target can hold them; see the format files for what each one loses (TOML has no null, XML no types,
+// CSV only tables). Output is UTF-8 without BOM (CSV: with BOM, like the spreadsheet engine), indented by two spaces.
+// Spreadsheets reach JSON and the others through CSV (XLSX → CSV → JSON), contacts through CSV as well.
+
+using System.Text;
+using Filee.Core.Conversion;
+using Filee.Engines.Hwp.Hwpx;
+using Filee.Engines.Infrastructure;
+using Filee.Engines.Office.Sheets;
+
+namespace Filee.Engines.Data;
+
+/// <summary>JSON, JSON Lines, YAML, TOML, XML and CSV into each other; vCard ↔ CSV.</summary>
+public sealed class DataConverter : IConverter
+{
+ private static readonly string[] Trees = ["json", "jsonl", "yaml", "toml", "xml"];
+
+ public string Id => "data";
+ public string DisplayName => "Data (built-in)";
+ public int MaxParallelism => 0;
+
+ public IReadOnlyList<ConversionEdge> Edges { get; } =
+ [
+ .. Trees.SelectMany(from => Trees.Where(to => to != from).Select(to => new ConversionEdge(from, to))),
+ .. Trees.Select(from => new ConversionEdge(from, "csv")),
+ .. Trees.Select(to => new ConversionEdge("csv", to)),
+ new("vcf", "csv"),
+ new("csv", "vcf"),
+ ];
+
+ public EngineStatus GetStatus() =>
+ EngineStatus.Available("JSON, JSON Lines, YAML, TOML, XML, CSV ↔ each other; vCard ↔ CSV",
+ $"{EngineVersions.BuiltIn} · {EngineVersions.Library("YamlDotNet", typeof(YamlDotNet.RepresentationModel.YamlStream))}"
+ + $" · {EngineVersions.Library("Tomlyn", typeof(Tomlyn.TomlSerializer))}");
+
+ private static readonly UTF8Encoding Utf8 = new(encoderShouldEmitUTF8Identifier: false);
+
+ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
+ Task.Run<IReadOnlyList<string>>(() =>
+ {
+ progress?.Report(0.1);
+ if (step.From == "vcf")
+ {
+ var contacts = VCard.Read(File.ReadAllBytes(step.InputPath));
+ if (contacts.Count == 0)
+ throw new InvalidDataException("The file has no vCard contacts.");
+ cancellationToken.ThrowIfCancellationRequested();
+ if (step.Output.Allocate("csv") is not { } csv)
+ return [];
+ CsvFormat.WriteRows(VCard.ToRows(contacts), csv);
+ progress?.Report(1);
+ return [csv];
+ }
+ if (step.To == "vcf")
+ {
+ var contacts = VCard.FromRows(CsvData.ReadRows(step.InputPath));
+ cancellationToken.ThrowIfCancellationRequested();
+ if (step.Output.Allocate("vcf") is not { } vcf)
+ return [];
+ File.WriteAllText(vcf, VCard.Write(contacts), Utf8);
+ progress?.Report(1);
+ return [vcf];
+ }
+
+ var tree = Read(step.InputPath, step.From);
+ cancellationToken.ThrowIfCancellationRequested();
+ progress?.Report(0.6);
+ // Built before a path is taken, so a tree the target can't hold leaves no empty file behind.
+ var text = step.To switch
+ {
+ "csv" => null,
+ "json" => JsonData.Write(tree),
+ "jsonl" => JsonData.WriteLines(tree),
+ "yaml" => YamlData.Write(tree),
+ "toml" => TomlData.Write(tree),
+ "xml" => XmlData.Write(tree),
+ _ => throw new NotSupportedException($"Data → {step.To} is not supported."),
+ };
+ var rows = step.To == "csv" ? CsvData.Table(tree) : null;
+ if (step.Output.Allocate(step.To) is not { } output)
+ return [];
+ if (rows is not null)
+ CsvFormat.WriteRows(rows, output);
+ else
+ File.WriteAllText(output, text, Utf8);
+ progress?.Report(1);
+ return [output];
+ }, cancellationToken);
+
+ /// <summary>Reads a data file of a format id this engine accepts into the common tree.</summary>
+ internal static object? Read(string path, string format) => format switch
+ {
+ "xml" => XmlData.Read(path),
+ "csv" => CsvData.Read(path),
+ _ => ReadText(HwpxConverter.DecodeText(File.ReadAllBytes(path)), format),
+ };
+
+ private static object? ReadText(string text, string format) => format switch
+ {
+ "json" => JsonData.Read(text),
+ "jsonl" => JsonData.ReadLines(text),
+ "yaml" => YamlData.Read(text),
+ "toml" => TomlData.Read(text),
+ _ => throw new NotSupportedException($"{format} → data is not supported."),
+ };
+}
diff --git a/src/Filee.Engines/Data/DataTree.cs b/src/Filee.Engines/Data/DataTree.cs
new file mode 100644
index 00000000..ba912d96
--- /dev/null
+++ b/src/Filee.Engines/Data/DataTree.cs
@@ -0,0 +1,78 @@
+// The in-memory tree every data format is read into and written from, the common ground of JSON, YAML, TOML, XML and
+// CSV: objects (DataMap, keys in file order), arrays (List<object?>) and scalars: string, bool, long, BigInteger,
+// double, DataDate (a TOML date / time, kept as written) and null.
+
+using System.Globalization;
+using System.Numerics;
+
+namespace Filee.Engines.Data;
+
+/// <summary>An object: keys in the order the file has them; a repeated key keeps its first place and the last value.</summary>
+internal sealed class DataMap() : OrderedDictionary<string, object?>(StringComparer.Ordinal);
+
+/// <summary>A TOML date, time or date-time as written in the file (RFC 3339), e.g. <c>1979-05-27T07:32:00Z</c>.</summary>
+internal sealed record DataDate(string Text)
+{
+ public override string ToString() => Text;
+}
+
+internal static class DataTree
+{
+ /// <summary>Deepest nesting read or written; deeper input is rejected instead of overflowing the stack.</summary>
+ public const int MaxDepth = 256;
+
+ /// <summary>A number in JSON syntax ("12", "-3.5", "1e3") as long, BigInteger or double.</summary>
+ public static object Number(string text)
+ {
+ if (long.TryParse(text, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var integer))
+ return integer;
+ if (text.IndexOfAny(['.', 'e', 'E']) < 0 && BigInteger.TryParse(text, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var big))
+ return big;
+ return double.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture);
+ }
+
+ /// <summary>
+ /// A float as the shortest text that reads back the same, always with a fraction or exponent so it stays a float
+ /// in YAML and TOML ("3.0", not "3"). Not for NaN or infinities, which every format spells differently.
+ /// </summary>
+ public static string FormatDouble(double value)
+ {
+ var text = value.ToString("R", CultureInfo.InvariantCulture);
+ return text.IndexOfAny(['.', 'E', 'e']) < 0 ? text + ".0" : text;
+ }
+
+ /// <summary>Text of a scalar for formats without types (XML, CSV): "true", "12", "3.5", "" for null.</summary>
+ public static string Text(object? value) => value switch
+ {
+ null => "",
+ string s => s,
+ bool b => b ? "true" : "false",
+ double d when double.IsNaN(d) => "NaN",
+ double d when double.IsPositiveInfinity(d) => "Infinity",
+ double d when double.IsNegativeInfinity(d) => "-Infinity",
+ double d => FormatDouble(d),
+ IFormattable f => f.ToString(null, CultureInfo.InvariantCulture),
+ _ => value.ToString() ?? "",
+ };
+
+ public static bool IsScalar(object? value) => value is not (DataMap or List<object?>);
+
+ /// <summary>
+ /// The list of records a table-like target (CSV, JSON Lines) is made of: the root array, or the array inside
+ /// objects that hold nothing else (<c>{"users": [...]}</c>, XML's <c>&lt;rows&gt;&lt;row/&gt;…&lt;/rows&gt;</c>).
+ /// </summary>
+ public static object? UnwrapRecords(object? root)
+ {
+ var node = root;
+ for (var i = 0; i < MaxDepth && node is DataMap { Count: 1 } map; i++)
+ {
+ var only = map.GetAt(0).Value;
+ // {"name": ["a", "b"]} is one column, not a wrapper around a list of values.
+ if (only is DataMap || (only is List<object?> list && list.Any(item => item is DataMap)))
+ node = only;
+ else
+ break;
+ }
+ return node;
+ }
+}
diff --git a/src/Filee.Engines/Data/JsonData.cs b/src/Filee.Engines/Data/JsonData.cs
new file mode 100644
index 00000000..f20ea0e8
--- /dev/null
+++ b/src/Filee.Engines/Data/JsonData.cs
@@ -0,0 +1,173 @@
+// JSON and JSON Lines with System.Text.Json. Reading allows comments and trailing commas (JSONC, as in settings files);
+// writing is indented by two spaces, keeps non-ASCII text as it is (Korean, Chinese) and ends with a line break.
+
+using System.Globalization;
+using System.Numerics;
+using System.Text;
+using System.Text.Encodings.Web;
+using System.Text.Json;
+
+namespace Filee.Engines.Data;
+
+internal static class JsonData
+{
+ private static readonly JsonDocumentOptions ReadOptions = new()
+ {
+ AllowTrailingCommas = true,
+ CommentHandling = JsonCommentHandling.Skip,
+ MaxDepth = DataTree.MaxDepth,
+ };
+
+ public static object? Read(string text)
+ {
+ try
+ {
+ using var document = JsonDocument.Parse(text, ReadOptions);
+ return FromElement(document.RootElement);
+ }
+ catch (JsonException ex)
+ {
+ throw new InvalidDataException($"Not valid JSON: {ex.Message}", ex);
+ }
+ }
+
+ /// <summary>JSON Lines: one value per line (blank lines skipped), read as an array.</summary>
+ public static List<object?> ReadLines(string text)
+ {
+ var values = new List<object?>();
+ var lines = text.Split('\n');
+ for (var i = 0; i < lines.Length; i++)
+ {
+ var line = lines[i].Trim();
+ if (line.Length == 0)
+ continue;
+ try
+ {
+ using var document = JsonDocument.Parse(line, ReadOptions);
+ values.Add(FromElement(document.RootElement));
+ }
+ catch (JsonException ex)
+ {
+ throw new InvalidDataException($"Line {i + 1} is not valid JSON: {ex.Message}", ex);
+ }
+ }
+ return values;
+ }
+
+ private static object? FromElement(JsonElement element)
+ {
+ switch (element.ValueKind)
+ {
+ case JsonValueKind.Object:
+ var map = new DataMap();
+ foreach (var property in element.EnumerateObject())
+ map[property.Name] = FromElement(property.Value);
+ return map;
+ case JsonValueKind.Array:
+ return element.EnumerateArray().Select(FromElement).ToList();
+ case JsonValueKind.String:
+ return element.GetString();
+ case JsonValueKind.Number:
+ return DataTree.Number(element.GetRawText());
+ case JsonValueKind.True:
+ return true;
+ case JsonValueKind.False:
+ return false;
+ default:
+ return null;
+ }
+ }
+
+ /// <summary>Indented JSON (two spaces, "\n").</summary>
+ public static string Write(object? root)
+ {
+ using var buffer = new MemoryStream();
+ using (var writer = new Utf8JsonWriter(buffer, Options(indented: true)))
+ WriteValue(writer, root, 0);
+ return Encoding.UTF8.GetString(buffer.ToArray()) + "\n";
+ }
+
+ /// <summary>
+ /// JSON Lines: one compact line per record (see <see cref="DataTree.UnwrapRecords"/>); anything else becomes one
+ /// line.
+ /// </summary>
+ public static string WriteLines(object? root)
+ {
+ var records = DataTree.UnwrapRecords(root) is List<object?> list ? list : [root];
+ var sb = new StringBuilder();
+ foreach (var record in records)
+ {
+ using var buffer = new MemoryStream();
+ using (var writer = new Utf8JsonWriter(buffer, Options(indented: false)))
+ WriteValue(writer, record, 0);
+ sb.Append(Encoding.UTF8.GetString(buffer.ToArray())).Append('\n');
+ }
+ return sb.ToString();
+ }
+
+ private static JsonWriterOptions Options(bool indented) => new()
+ {
+ Indented = indented,
+ IndentSize = 2,
+ NewLine = "\n",
+ // Readable text: only what JSON requires is escaped (quotes, backslashes, control characters).
+ Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
+ MaxDepth = DataTree.MaxDepth + 1,
+ };
+
+ /// <summary>
+ /// A big integer or a float ("3.0" stays a float). A decimal keeps its digits and scale and is indented like any
+ /// value; raw values are not, so they are only the fallback for numbers beyond decimal's range (1e300).
+ /// </summary>
+ private static void WriteNumber(Utf8JsonWriter writer, string text, bool isFloat)
+ {
+ if (decimal.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var number)
+ && (number != 0 || !text.Contains('e', StringComparison.OrdinalIgnoreCase)))
+ writer.WriteNumberValue(isFloat && number.Scale == 0 ? number * 1.0m : number);
+ else
+ writer.WriteRawValue(text);
+ }
+
+ private static void WriteValue(Utf8JsonWriter writer, object? value, int depth)
+ {
+ if (depth > DataTree.MaxDepth)
+ throw new InvalidDataException("The data is nested too deeply.");
+ switch (value)
+ {
+ case DataMap map:
+ writer.WriteStartObject();
+ foreach (var (key, item) in map)
+ {
+ writer.WritePropertyName(key);
+ WriteValue(writer, item, depth + 1);
+ }
+ writer.WriteEndObject();
+ break;
+ case List<object?> list:
+ writer.WriteStartArray();
+ foreach (var item in list)
+ WriteValue(writer, item, depth + 1);
+ writer.WriteEndArray();
+ break;
+ case null:
+ writer.WriteNullValue();
+ break;
+ case bool b:
+ writer.WriteBooleanValue(b);
+ break;
+ case long l:
+ writer.WriteNumberValue(l);
+ break;
+ case BigInteger big:
+ WriteNumber(writer, big.ToString(CultureInfo.InvariantCulture), isFloat: false);
+ break;
+ case double d when double.IsFinite(d):
+ WriteNumber(writer, DataTree.FormatDouble(d), isFloat: true);
+ break;
+ default:
+ // Strings, TOML dates, and NaN / infinities, which JSON has no number for.
+ writer.WriteStringValue(DataTree.Text(value));
+ break;
+ }
+ }
+}
diff --git a/src/Filee.Engines/Data/TomlData.cs b/src/Filee.Engines/Data/TomlData.cs
new file mode 100644
index 00000000..bae8a098
--- /dev/null
+++ b/src/Filee.Engines/Data/TomlData.cs
@@ -0,0 +1,206 @@
+// TOML: read with Tomlyn (BSD-2-Clause, TOML 1.1), written here so the layout is predictable: plain keys first, then
+// [tables] and [[arrays of tables]] in document order, a blank line before each header. Dates and times keep their
+// TOML spelling (JSON and YAML get them as text). TOML has no null and needs a table at the root: null values are left
+// out, and anything that is not an object (an array of CSV rows, a single value) is written under the key "items".
+
+using System.Globalization;
+using System.Numerics;
+using System.Text;
+using System.Text.RegularExpressions;
+using Tomlyn;
+using Tomlyn.Model;
+
+namespace Filee.Engines.Data;
+
+internal static partial class TomlData
+{
+ /// <summary>Key of the root table that holds a value that is not an object.</summary>
+ public const string RootKey = "items";
+
+ public static object? Read(string text)
+ {
+ TomlTable table;
+ try
+ {
+ table = TomlSerializer.Deserialize<TomlTable>(text) ?? new TomlTable();
+ }
+ catch (TomlException ex)
+ {
+ throw new InvalidDataException($"Not valid TOML: {ex.Message}", ex);
+ }
+ return FromModel(table);
+ }
+
+ private static object? FromModel(object? value) => value switch
+ {
+ TomlTable table => Map(table),
+ TomlTableArray tables => tables.Select(t => (object?)Map(t)).ToList(),
+ TomlArray array => array.Select(FromModel).ToList(),
+ TomlDateTime date => new DataDate(date.ToString()),
+ int i => (long)i,
+ float f => (double)f,
+ _ => value,
+ };
+
+ private static DataMap Map(TomlTable table)
+ {
+ var map = new DataMap();
+ foreach (var (key, value) in table)
+ map[key] = FromModel(value);
+ return map;
+ }
+
+ // ───────────────────────── Writing ─────────────────────────
+
+ public static string Write(object? root)
+ {
+ var table = root as DataMap ?? new DataMap { [RootKey] = root };
+ var sb = new StringBuilder();
+ WriteTable(sb, [], table, 0);
+ var text = sb.ToString().TrimStart('\n');
+ return text.Length == 0 || text.EndsWith('\n') ? text : text + "\n";
+ }
+
+ private static void WriteTable(StringBuilder sb, List<string> path, DataMap table, int depth)
+ {
+ if (depth > DataTree.MaxDepth)
+ throw new InvalidDataException("The data is nested too deeply.");
+
+ // Keys with plain values first: after a [header] every key belongs to that table.
+ var nested = new List<(string Key, object Value)>();
+ foreach (var (key, value) in table)
+ {
+ switch (value)
+ {
+ case null:
+ break; // TOML has no null.
+ case DataMap:
+ nested.Add((key, value));
+ break;
+ case List<object?> list when list.Count > 0 && list.All(item => item is DataMap):
+ nested.Add((key, value));
+ break;
+ default:
+ sb.Append(Key(key)).Append(" = ");
+ Inline(sb, value, depth + 1);
+ sb.Append('\n');
+ break;
+ }
+ }
+
+ foreach (var (key, value) in nested)
+ {
+ List<string> child = [.. path, key];
+ var header = string.Join('.', child.Select(Key));
+ if (value is DataMap map)
+ {
+ sb.Append('\n').Append('[').Append(header).Append("]\n");
+ WriteTable(sb, child, map, depth + 1);
+ }
+ else
+ {
+ foreach (var item in (List<object?>)value)
+ {
+ sb.Append('\n').Append("[[").Append(header).Append("]]\n");
+ WriteTable(sb, child, (DataMap)item!, depth + 1);
+ }
+ }
+ }
+ }
+
+ /// <summary>A value on one line: arrays as [a, b], objects as inline tables { a = 1 }.</summary>
+ private static void Inline(StringBuilder sb, object? value, int depth)
+ {
+ if (depth > DataTree.MaxDepth)
+ throw new InvalidDataException("The data is nested too deeply.");
+ switch (value)
+ {
+ case DataMap map:
+ var entries = map.Where(kv => kv.Value is not null).ToList();
+ if (entries.Count == 0)
+ {
+ sb.Append("{}");
+ break;
+ }
+ sb.Append("{ ");
+ for (var i = 0; i < entries.Count; i++)
+ {
+ if (i > 0)
+ sb.Append(", ");
+ sb.Append(Key(entries[i].Key)).Append(" = ");
+ Inline(sb, entries[i].Value, depth + 1);
+ }
+ sb.Append(" }");
+ break;
+ case List<object?> list:
+ sb.Append('[');
+ var first = true;
+ foreach (var item in list.Where(item => item is not null))
+ {
+ if (!first)
+ sb.Append(", ");
+ first = false;
+ Inline(sb, item, depth + 1);
+ }
+ sb.Append(']');
+ break;
+ case bool b:
+ sb.Append(b ? "true" : "false");
+ break;
+ case long l:
+ sb.Append(l.ToString(CultureInfo.InvariantCulture));
+ break;
+ case double d:
+ sb.Append(double.IsNaN(d) ? "nan" : double.IsPositiveInfinity(d) ? "inf" : double.IsNegativeInfinity(d) ? "-inf" : DataTree.FormatDouble(d));
+ break;
+ case DataDate date:
+ sb.Append(date.Text);
+ break;
+ case BigInteger big:
+ // TOML integers are 64-bit: a larger one is kept as text rather than rounded.
+ Quote(sb, big.ToString(CultureInfo.InvariantCulture));
+ break;
+ default:
+ Quote(sb, DataTree.Text(value));
+ break;
+ }
+ }
+
+ private static string Key(string key)
+ {
+ if (BareKey().IsMatch(key))
+ return key;
+ var sb = new StringBuilder();
+ Quote(sb, key);
+ return sb.ToString();
+ }
+
+ /// <summary>A basic string: quotes, backslashes and control characters escaped.</summary>
+ private static void Quote(StringBuilder sb, string text)
+ {
+ sb.Append('"');
+ foreach (var ch in text)
+ {
+ switch (ch)
+ {
+ case '"': sb.Append("\\\""); break;
+ case '\\': sb.Append("\\\\"); break;
+ case '\b': sb.Append("\\b"); break;
+ case '\t': sb.Append("\\t"); break;
+ case '\n': sb.Append("\\n"); break;
+ case '\f': sb.Append("\\f"); break;
+ case '\r': sb.Append("\\r"); break;
+ default:
+ if (char.IsControl(ch))
+ sb.Append("\\u").Append(((int)ch).ToString("X4", CultureInfo.InvariantCulture));
+ else
+ sb.Append(ch);
+ break;
+ }
+ }
+ sb.Append('"');
+ }
+
+ [GeneratedRegex("^[A-Za-z0-9_-]+$")]
+ private static partial Regex BareKey();
+}
diff --git a/src/Filee.Engines/Data/VCard.cs b/src/Filee.Engines/Data/VCard.cs
new file mode 100644
index 00000000..35aa60d0
--- /dev/null
+++ b/src/Filee.Engines/Data/VCard.cs
@@ -0,0 +1,586 @@
+// vCard (.vcf) contacts ↔ CSV, one row per contact. Reads vCard 2.1, 3.0 and 4.0: folded lines, quoted-printable
+// (with its "=" soft line breaks), CHARSET parameters, escaped characters (\n \, \; \\), grouped names (item1.EMAIL),
+// and 2.1's bare TYPE parameters (TEL;CELL;PREF). A value without a CHARSET is UTF-8 when it is valid UTF-8 and CP949
+// otherwise, as Korean phones (Anycall, Cyon, SKY) exported their address books; UTF-16 files with a BOM are read too.
+// Pictures (PHOTO, LOGO) and other binary values are skipped.
+// Columns: Full name, Given name, Family name, Organization, Title, Email, Phone, Address, Birthday, Note. Several
+// values in one cell are joined with "; ", each with its kind in brackets: "010-1234-5678 (mobile); 02-123-4567 (work)".
+// CSV → vCard reads those columns (and common other names for them, also in Korean and Chinese) and writes vCard 3.0
+// in UTF-8, which phones and mail programs import.
+
+using System.Globalization;
+using System.Text;
+using System.Text.RegularExpressions;
+
+namespace Filee.Engines.Data;
+
+internal sealed class Contact
+{
+ public string FullName { get; set; } = "";
+ public string GivenName { get; set; } = "";
+ public string FamilyName { get; set; } = "";
+ public string Organization { get; set; } = "";
+ public string Title { get; set; } = "";
+ public List<(string Value, string? Kind)> Emails { get; } = [];
+ public List<(string Value, string? Kind)> Phones { get; } = [];
+ public List<(string Value, string? Kind)> Addresses { get; } = [];
+ public string Birthday { get; set; } = "";
+ public List<string> Notes { get; } = [];
+
+ public bool IsEmpty =>
+ FullName.Length == 0 && GivenName.Length == 0 && FamilyName.Length == 0 && Organization.Length == 0
+ && Emails.Count == 0 && Phones.Count == 0;
+}
+
+internal static partial class VCard
+{
+ public static readonly string[] Columns =
+ ["Full name", "Given name", "Family name", "Organization", "Title", "Email", "Phone", "Address", "Birthday", "Note"];
+
+ private const string Separator = "; ";
+
+ // ───────────────────────── Reading ─────────────────────────
+
+ public static List<Contact> Read(byte[] bytes)
+ {
+ Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+ if (bytes is [0xFF, 0xFE, ..] or [0xFE, 0xFF, ..])
+ bytes = Encoding.UTF8.GetBytes(new StreamReader(new MemoryStream(bytes), detectEncodingFromByteOrderMarks: true).ReadToEnd());
+ else if (bytes is [0xEF, 0xBB, 0xBF, ..])
+ bytes = bytes[3..];
+
+ // Latin-1 keeps every byte as one char: the structure is ASCII, values are decoded per property.
+ var lines = Encoding.Latin1.GetString(bytes).Split(["\r\n", "\n", "\r"], StringSplitOptions.None);
+ var contacts = new List<Contact>();
+ Contact? contact = null;
+ var depth = 0;
+ foreach (var line in Unfold(lines))
+ {
+ if (Property.Parse(line) is not { } property)
+ continue;
+ switch (property.Name)
+ {
+ case "BEGIN" when property.Raw.Trim().Equals("VCARD", StringComparison.OrdinalIgnoreCase):
+ if (depth++ == 0)
+ contact = new Contact();
+ continue;
+ case "END" when property.Raw.Trim().Equals("VCARD", StringComparison.OrdinalIgnoreCase):
+ if (depth > 0 && --depth == 0 && contact is not null)
+ {
+ Finish(contact);
+ contacts.Add(contact);
+ contact = null;
+ }
+ continue;
+ }
+ // Properties of a nested card (2.1 AGENT) are not this contact's.
+ if (contact is not null && depth == 1)
+ Apply(contact, property);
+ }
+ return contacts;
+ }
+
+ /// <summary>
+ /// Joins folded lines (a line starting with a space or tab continues the previous one) and quoted-printable soft
+ /// line breaks (a quoted-printable value ending in "=" continues on the next line, indented or not).
+ /// </summary>
+ private static IEnumerable<string> Unfold(string[] lines)
+ {
+ var current = new StringBuilder();
+ var started = false;
+ foreach (var line in lines)
+ {
+ // A soft line break first: the next line's leading space is part of the value then.
+ if (started && current.Length > 0 && current[^1] == '=' && IsQuotedPrintable(current))
+ {
+ current.Length--;
+ current.Append(line);
+ continue;
+ }
+ if (started && line.Length > 0 && line[0] is ' ' or '\t')
+ {
+ current.Append(line, 1, line.Length - 1);
+ continue;
+ }
+ if (started)
+ yield return current.ToString();
+ current.Clear().Append(line);
+ started = true;
+ }
+ if (started)
+ yield return current.ToString();
+ }
+
+ private static bool IsQuotedPrintable(StringBuilder line)
+ {
+ var text = line.ToString();
+ var colon = text.IndexOf(':');
+ return colon > 0 && text[..colon].Contains("QUOTED-PRINTABLE", StringComparison.OrdinalIgnoreCase);
+ }
+
+ private static void Apply(Contact contact, Property property)
+ {
+ if (property.IsBinary)
+ return;
+ switch (property.Name)
+ {
+ case "FN":
+ contact.FullName = Unescape(property.Value).Trim();
+ break;
+ case "N":
+ var name = Components(property.Value);
+ contact.FamilyName = name.ElementAtOrDefault(0)?.Trim() ?? "";
+ contact.GivenName = string.Join(" ", name.Skip(1).Take(2).Select(n => n.Trim()).Where(n => n.Length > 0));
+ break;
+ case "ORG":
+ contact.Organization = string.Join(", ", Components(property.Value).Select(o => o.Trim()).Where(o => o.Length > 0));
+ break;
+ case "TITLE":
+ contact.Title = Unescape(property.Value).Trim();
+ break;
+ case "EMAIL":
+ AddValue(contact.Emails, StripScheme(Unescape(property.Value), "mailto:"), property.Kind);
+ break;
+ case "TEL":
+ AddValue(contact.Phones, StripScheme(Unescape(property.Value), "tel:"), property.Kind);
+ break;
+ case "ADR":
+ var parts = Components(property.Value).Select(p => OneLine(p.Trim())).Where(p => p.Length > 0);
+ AddValue(contact.Addresses, string.Join(", ", parts), property.Kind);
+ break;
+ case "BDAY":
+ contact.Birthday = Birthday(Unescape(property.Value).Trim());
+ break;
+ case "NOTE":
+ var note = Unescape(property.Value).Trim();
+ if (note.Length > 0)
+ contact.Notes.Add(note);
+ break;
+ }
+ }
+
+ private static void AddValue(List<(string, string?)> list, string value, string? kind)
+ {
+ value = value.Trim();
+ if (value.Length > 0)
+ list.Add((value, kind));
+ }
+
+ private static string StripScheme(string value, string scheme) =>
+ value.StartsWith(scheme, StringComparison.OrdinalIgnoreCase) ? value[scheme.Length..] : value;
+
+ private static string OneLine(string text) => NewLines().Replace(text, ", ");
+
+ /// <summary>"19900131" → "1990-01-31"; other forms ("1990-01-31", 4.0's "--0131") as written.</summary>
+ private static string Birthday(string value) =>
+ value.Length == 8 && value.All(char.IsAsciiDigit) ? $"{value[..4]}-{value[4..6]}-{value[6..]}" : value;
+
+ /// <summary>A missing full name (common in 2.1 files) is made from the name parts: 홍길동, or "John Smith".</summary>
+ private static void Finish(Contact contact)
+ {
+ if (contact.FullName.Length > 0)
+ return;
+ var family = contact.FamilyName;
+ var given = contact.GivenName;
+ contact.FullName = family.Length == 0 || given.Length == 0 ? family + given
+ : IsCjk(family) && IsCjk(given) ? family + given
+ : $"{given} {family}";
+ }
+
+ private static bool IsCjk(string text) =>
+ text.All(ch => ch is >= '가' and <= '힣' or >= 'ᄀ' and <= 'ᇿ' or >= '㄰' and <= '㆏' or >= '一' and <= '鿿' or >= '぀' and <= 'ヿ');
+
+ /// <summary>A structured value (N, ADR, ORG) split at unescaped ";", each part unescaped.</summary>
+ private static List<string> Components(string value)
+ {
+ var parts = new List<string>();
+ var current = new StringBuilder();
+ for (var i = 0; i < value.Length; i++)
+ {
+ if (value[i] == '\\' && i + 1 < value.Length)
+ {
+ current.Append(value, i, 2);
+ i++;
+ }
+ else if (value[i] == ';')
+ {
+ parts.Add(Unescape(current.ToString()));
+ current.Clear();
+ }
+ else
+ {
+ current.Append(value[i]);
+ }
+ }
+ parts.Add(Unescape(current.ToString()));
+ return parts;
+ }
+
+ private static string Unescape(string value)
+ {
+ if (!value.Contains('\\'))
+ return value;
+ var sb = new StringBuilder(value.Length);
+ for (var i = 0; i < value.Length; i++)
+ {
+ if (value[i] != '\\' || i + 1 >= value.Length)
+ {
+ sb.Append(value[i]);
+ continue;
+ }
+ var next = value[++i];
+ sb.Append(next is 'n' or 'N' ? '\n' : next);
+ }
+ return sb.ToString();
+ }
+
+ /// <summary>One content line: name (group removed), parameters and the value decoded to text.</summary>
+ private sealed class Property
+ {
+ public string Name { get; private init; } = "";
+
+ /// <summary>The value as written (Latin-1: one char per byte), for BEGIN / END.</summary>
+ public string Raw { get; private init; } = "";
+
+ public string Value { get; private set; } = "";
+ public bool IsBinary { get; private set; }
+ public string? Kind { get; private set; }
+
+ public static Property? Parse(string line)
+ {
+ var colon = -1;
+ var quoted = false;
+ for (var i = 0; i < line.Length; i++)
+ {
+ if (line[i] == '"')
+ quoted = !quoted;
+ else if (line[i] == ':' && !quoted)
+ {
+ colon = i;
+ break;
+ }
+ }
+ if (colon <= 0)
+ return null;
+
+ var head = SplitParameters(line[..colon]);
+ var name = head[0];
+ var dot = name.LastIndexOf('.');
+ var property = new Property
+ {
+ Name = (dot >= 0 ? name[(dot + 1)..] : name).Trim().ToUpperInvariant(),
+ Raw = line[(colon + 1)..],
+ };
+
+ string? encoding = null, charset = null;
+ var types = new List<string>();
+ foreach (var parameter in head.Skip(1))
+ {
+ var equals = parameter.IndexOf('=');
+ var key = (equals < 0 ? "TYPE" : parameter[..equals]).Trim().ToUpperInvariant();
+ var value = (equals < 0 ? parameter : parameter[(equals + 1)..]).Trim().Trim('"');
+ switch (key)
+ {
+ case "ENCODING":
+ encoding = value.ToUpperInvariant();
+ break;
+ case "CHARSET":
+ charset = value;
+ break;
+ case "TYPE":
+ types.AddRange(value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries));
+ break;
+ case "VALUE" when value.Equals("binary", StringComparison.OrdinalIgnoreCase):
+ property.IsBinary = true;
+ break;
+ }
+ // 2.1 also writes the encoding bare: TEL;QUOTED-PRINTABLE:…
+ if (equals < 0 && value.ToUpperInvariant() is "QUOTED-PRINTABLE" or "BASE64" or "B")
+ encoding = value.ToUpperInvariant();
+ }
+
+ if (encoding is "BASE64" or "B")
+ {
+ property.IsBinary = true;
+ return property;
+ }
+ var bytes = Encoding.Latin1.GetBytes(property.Raw);
+ if (encoding == "QUOTED-PRINTABLE")
+ bytes = DecodeQuotedPrintable(bytes);
+ property.Value = Decode(bytes, charset);
+ property.Kind = KindOf(types, property.Name);
+ return property;
+ }
+
+ /// <summary>"N;CHARSET=UTF-8;TYPE=\"a;b\"" → name and parameters, ";" inside quotes kept.</summary>
+ private static List<string> SplitParameters(string head)
+ {
+ var parts = new List<string>();
+ var current = new StringBuilder();
+ var quoted = false;
+ foreach (var ch in head)
+ {
+ if (ch == '"')
+ quoted = !quoted;
+ if (ch == ';' && !quoted)
+ {
+ parts.Add(current.ToString());
+ current.Clear();
+ }
+ else
+ {
+ current.Append(ch);
+ }
+ }
+ parts.Add(current.ToString());
+ return parts;
+ }
+
+ private static byte[] DecodeQuotedPrintable(byte[] bytes)
+ {
+ var output = new List<byte>(bytes.Length);
+ for (var i = 0; i < bytes.Length; i++)
+ {
+ if (bytes[i] == '=' && i + 2 < bytes.Length && IsHex(bytes[i + 1]) && IsHex(bytes[i + 2]))
+ {
+ output.Add(Convert.ToByte(Encoding.ASCII.GetString(bytes, i + 1, 2), 16));
+ i += 2;
+ }
+ else if (bytes[i] == '=' && i == bytes.Length - 1)
+ {
+ // A soft line break left at the very end.
+ }
+ else
+ {
+ output.Add(bytes[i]);
+ }
+ }
+ return [.. output];
+ }
+
+ private static bool IsHex(byte b) => b is >= (byte)'0' and <= (byte)'9' or >= (byte)'A' and <= (byte)'F' or >= (byte)'a' and <= (byte)'f';
+
+ /// <summary>The declared charset, else UTF-8 when the bytes are valid UTF-8, else CP949.</summary>
+ private static string Decode(byte[] bytes, string? charset)
+ {
+ if (charset is { Length: > 0 })
+ {
+ try
+ {
+ return Encoding.GetEncoding(charset).GetString(bytes);
+ }
+ catch (ArgumentException)
+ {
+ // Unknown charset name: guess as below.
+ }
+ }
+ try
+ {
+ return new UTF8Encoding(false, throwOnInvalidBytes: true).GetString(bytes);
+ }
+ catch (DecoderFallbackException)
+ {
+ return Encoding.GetEncoding(949).GetString(bytes);
+ }
+ }
+
+ /// <summary>The kind shown in brackets: mobile, home, work, fax, pager or main; null for none of these.</summary>
+ private static string? KindOf(List<string> types, string property)
+ {
+ var kinds = new List<string>();
+ foreach (var type in types.Select(t => t.ToUpperInvariant()))
+ {
+ var kind = type switch
+ {
+ "CELL" when property == "TEL" => "mobile",
+ "HOME" => "home",
+ "WORK" => "work",
+ "FAX" when property == "TEL" => "fax",
+ "PAGER" when property == "TEL" => "pager",
+ "MAIN" when property == "TEL" => "main",
+ _ => null,
+ };
+ if (kind is not null && !kinds.Contains(kind))
+ kinds.Add(kind);
+ }
+ return kinds.Count == 0 ? null : string.Join(", ", kinds);
+ }
+ }
+
+ // ───────────────────────── CSV ─────────────────────────
+
+ /// <summary>The header row and one row per contact.</summary>
+ public static List<List<string>> ToRows(List<Contact> contacts)
+ {
+ var rows = new List<List<string>> { Columns.ToList() };
+ foreach (var c in contacts)
+ {
+ rows.Add(
+ [
+ c.FullName, c.GivenName, c.FamilyName, c.Organization, c.Title,
+ Join(c.Emails), Join(c.Phones), Join(c.Addresses), c.Birthday, string.Join("\n", c.Notes),
+ ]);
+ }
+ return rows;
+ }
+
+ private static string Join(List<(string Value, string? Kind)> values) =>
+ string.Join(Separator, values.Select(v => v.Kind is null ? v.Value : $"{v.Value} ({v.Kind})"));
+
+ /// <summary>Contacts from CSV rows (the first row names the columns).</summary>
+ public static List<Contact> FromRows(List<List<string>> rows)
+ {
+ if (rows.Count == 0)
+ throw new InvalidDataException("The CSV file is empty.");
+ var fields = rows[0].Select(h => Field(h)).ToList();
+ if (fields.All(f => f is null))
+ throw new InvalidDataException("No contact columns found. Name the columns Full name, Email, Phone, Address and so on.");
+
+ var contacts = new List<Contact>();
+ foreach (var row in rows.Skip(1))
+ {
+ var contact = new Contact();
+ for (var c = 0; c < row.Count && c < fields.Count; c++)
+ {
+ var value = row[c].Trim();
+ if (value.Length == 0)
+ continue;
+ switch (fields[c])
+ {
+ case "FN": contact.FullName = value; break;
+ case "GIVEN": contact.GivenName = value; break;
+ case "FAMILY": contact.FamilyName = value; break;
+ case "ORG": contact.Organization = value; break;
+ case "TITLE": contact.Title = value; break;
+ case "EMAIL": contact.Emails.AddRange(Split(value)); break;
+ case "TEL": contact.Phones.AddRange(Split(value)); break;
+ case "ADR": contact.Addresses.AddRange(Split(value)); break;
+ case "BDAY": contact.Birthday = value; break;
+ case "NOTE": contact.Notes.Add(value); break;
+ }
+ }
+ if (contact.IsEmpty)
+ continue;
+ Finish(contact);
+ if (contact.FullName.Length == 0)
+ contact.FullName = contact.Organization.Length > 0 ? contact.Organization
+ : contact.Emails.Count > 0 ? contact.Emails[0].Value : contact.Phones[0].Value;
+ contacts.Add(contact);
+ }
+ if (contacts.Count == 0)
+ throw new InvalidDataException("The CSV file has no contacts.");
+ return contacts;
+ }
+
+ /// <summary>"[email protected] (work); [email protected]" → values with their kind.</summary>
+ private static IEnumerable<(string, string?)> Split(string cell) =>
+ cell.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(part =>
+ {
+ var match = KindSuffix().Match(part);
+ return match.Success ? (match.Groups[1].Value.Trim(), match.Groups[2].Value.Trim()) : (part, (string?)null);
+ });
+
+ /// <summary>The vCard field a CSV column holds, by its header (English, Korean or Chinese), or null.</summary>
+ private static string? Field(string header)
+ {
+ var key = new string([.. header.Where(char.IsLetterOrDigit)]).ToLowerInvariant();
+ return key switch
+ {
+ "fullname" or "name" or "displayname" or "이름" or "성명" or "姓名" or "名称" => "FN",
+ "givenname" or "firstname" or "given" or "first" or "名" => "GIVEN",
+ "familyname" or "lastname" or "surname" or "family" or "last" or "성" or "姓" => "FAMILY",
+ "organization" or "organisation" or "company" or "org" or "회사" or "소속" or "公司" or "单位" => "ORG",
+ "title" or "jobtitle" or "직함" or "직책" or "직위" or "职位" or "职务" => "TITLE",
+ "email" or "emails" or "emailaddress" or "mail" or "이메일" or "전자메일" or "메일" or "邮箱" or "电子邮件" => "EMAIL",
+ "phone" or "phones" or "telephone" or "tel" or "mobile" or "phonenumber" or "cell" or "전화" or "전화번호" or "휴대폰" or "휴대전화" or "연락처" or "电话" or "手机" => "TEL",
+ "address" or "addresses" or "주소" or "地址" => "ADR",
+ "birthday" or "bday" or "birthdate" or "dateofbirth" or "생일" or "생년월일" or "生日" => "BDAY",
+ "note" or "notes" or "memo" or "메모" or "비고" or "备注" => "NOTE",
+ _ => null,
+ };
+ }
+
+ // ───────────────────────── Writing ─────────────────────────
+
+ /// <summary>vCard 3.0, UTF-8, CRLF, lines folded at 75 bytes.</summary>
+ public static string Write(List<Contact> contacts)
+ {
+ var sb = new StringBuilder();
+ foreach (var c in contacts)
+ {
+ Line(sb, "BEGIN:VCARD");
+ Line(sb, "VERSION:3.0");
+ Line(sb, "FN:" + Escape(c.FullName));
+ Line(sb, $"N:{Escape(c.FamilyName)};{Escape(c.GivenName)};;;");
+ if (c.Organization.Length > 0)
+ Line(sb, "ORG:" + Escape(c.Organization));
+ if (c.Title.Length > 0)
+ Line(sb, "TITLE:" + Escape(c.Title));
+ foreach (var (value, kind) in c.Emails)
+ Line(sb, $"EMAIL;TYPE={string.Join(',', ["INTERNET", .. Types(kind, "EMAIL")])}:{Escape(value)}");
+ foreach (var (value, kind) in c.Phones)
+ Line(sb, Types(kind, "TEL") is { Count: > 0 } types ? $"TEL;TYPE={string.Join(',', types)}:{Escape(value)}" : "TEL:" + Escape(value));
+ // The address as one street line: the parts can't be told apart reliably from a single cell.
+ foreach (var (value, kind) in c.Addresses)
+ Line(sb, (Types(kind, "ADR") is { Count: > 0 } types ? $"ADR;TYPE={string.Join(',', types)}" : "ADR") + $":;;{Escape(value)};;;;");
+ if (c.Birthday.Length > 0)
+ Line(sb, "BDAY:" + Escape(c.Birthday));
+ if (c.Notes.Count > 0)
+ Line(sb, "NOTE:" + Escape(string.Join("\n", c.Notes)));
+ Line(sb, "END:VCARD");
+ }
+ return sb.ToString();
+ }
+
+ private static List<string> Types(string? kind, string property)
+ {
+ var types = new List<string>();
+ foreach (var word in (kind ?? "").Split([',', ' '], StringSplitOptions.RemoveEmptyEntries))
+ {
+ var type = word.ToLowerInvariant() switch
+ {
+ "mobile" or "cell" or "휴대폰" or "手机" when property == "TEL" => "CELL",
+ "home" or "집" or "家" => "HOME",
+ "work" or "office" or "직장" or "회사" or "工作" => "WORK",
+ "fax" or "팩스" or "传真" when property == "TEL" => "FAX",
+ "pager" when property == "TEL" => "PAGER",
+ "main" when property == "TEL" => "MAIN",
+ _ => null,
+ };
+ if (type is not null && !types.Contains(type))
+ types.Add(type);
+ }
+ return types;
+ }
+
+ private static string Escape(string value) =>
+ value.Replace("\\", "\\\\").Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\\n").Replace(",", "\\,").Replace(";", "\\;");
+
+ /// <summary>Appends a content line folded at 75 bytes (RFC 6350), never inside a character.</summary>
+ private static void Line(StringBuilder sb, string line)
+ {
+ var bytes = 0;
+ var limit = 75;
+ var e = StringInfo.GetTextElementEnumerator(line);
+ while (e.MoveNext())
+ {
+ var element = e.GetTextElement();
+ var size = Encoding.UTF8.GetByteCount(element);
+ if (bytes + size > limit)
+ {
+ sb.Append("\r\n ");
+ bytes = 1;
+ limit = 75;
+ }
+ sb.Append(element);
+ bytes += size;
+ }
+ sb.Append("\r\n");
+ }
+
+ [GeneratedRegex(@"^(.*?)\s*\(([^()]*)\)$")]
+ private static partial Regex KindSuffix();
+
+ [GeneratedRegex(@"\r\n|\n|\r")]
+ private static partial Regex NewLines();
+}
diff --git a/src/Filee.Engines/Data/XmlData.cs b/src/Filee.Engines/Data/XmlData.cs
new file mode 100644
index 00000000..cf273816
--- /dev/null
+++ b/src/Filee.Engines/Data/XmlData.cs
@@ -0,0 +1,264 @@
+// XML ↔ the data tree with System.Xml, in the widespread "@attribute / #text" convention (as xmltodict and Json.NET):
+// - the root element becomes an object with one key, its name;
+// - an element with only text becomes that text; an empty element (<a/>) becomes null, <a></a> empty text;
+// - attributes become "@name" keys, text next to attributes or child elements becomes "#text" (mixed content is
+// joined into one text); child elements become keys, and repeated ones an array (a single child is no array, so
+// the shape of one row can differ from several);
+// - XML has no types: values read are text. Comments, processing instructions and the DTD are dropped; external
+// entities are never loaded.
+// Writing does the reverse. A root that is not one object with one key goes into <root>, array items without a name
+// into <item>; names that are not valid XML names are escaped as XmlConvert does ("first name" → first_x0020_name)
+// and unescaped when read back. Prefixed names ("x:a") keep their namespace when an "@xmlns:x" key declares it.
+
+using System.Text;
+using System.Xml;
+using System.Xml.Linq;
+
+namespace Filee.Engines.Data;
+
+internal static class XmlData
+{
+ public const string RootName = "root";
+ public const string ItemName = "item";
+ public const string TextKey = "#text";
+
+ private const string XmlnsNamespace = "http://www.w3.org/2000/xmlns/";
+ private const string XmlNamespace = "http://www.w3.org/XML/1998/namespace";
+
+ public static object? Read(string path)
+ {
+ Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+ var settings = new XmlReaderSettings
+ {
+ DtdProcessing = DtdProcessing.Ignore,
+ XmlResolver = null,
+ IgnoreComments = true,
+ IgnoreProcessingInstructions = true,
+ MaxCharactersInDocument = 0,
+ };
+ XDocument document;
+ try
+ {
+ // The reader picks the encoding from the BOM or the declaration (<?xml encoding="EUC-KR"?>).
+ using var reader = XmlReader.Create(path, settings);
+ document = XDocument.Load(reader);
+ }
+ catch (XmlException ex)
+ {
+ throw new InvalidDataException($"Not valid XML: {ex.Message}", ex);
+ }
+ var root = document.Root ?? throw new InvalidDataException("The XML file has no root element.");
+ return new DataMap { [Name(root)] = Element(root, 0) };
+ }
+
+ private static object? Element(XElement element, int depth)
+ {
+ if (depth > DataTree.MaxDepth)
+ throw new InvalidDataException("The XML is nested too deeply.");
+ var attributes = element.Attributes().ToList();
+ var children = element.Elements().ToList();
+ if (attributes.Count == 0 && children.Count == 0)
+ return element.IsEmpty ? null : element.Value;
+
+ var map = new DataMap();
+ foreach (var attribute in attributes)
+ map["@" + Name(attribute)] = attribute.Value;
+
+ if (children.Count == 0)
+ {
+ if (!element.IsEmpty)
+ map[TextKey] = element.Value;
+ return map;
+ }
+
+ var text = string.Join(" ", element.Nodes().OfType<XText>().Select(t => t.Value.Trim()).Where(t => t.Length > 0));
+ if (text.Length > 0)
+ map[TextKey] = text;
+ foreach (var child in children)
+ {
+ var name = Name(child);
+ var value = Element(child, depth + 1);
+ // Element values are never arrays themselves, so an array under a name means "repeated element".
+ if (!map.TryGetValue(name, out var existing))
+ map[name] = value;
+ else if (existing is List<object?> repeated)
+ repeated.Add(value);
+ else
+ map[name] = new List<object?> { existing, value };
+ }
+ return map;
+ }
+
+ private static string Name(XElement element) => Qualified(element.Name, element.GetPrefixOfNamespace(element.Name.Namespace));
+
+ private static string Name(XAttribute attribute)
+ {
+ if (attribute.IsNamespaceDeclaration)
+ return attribute.Name.Namespace == XNamespace.None ? "xmlns" : "xmlns:" + attribute.Name.LocalName;
+ var prefix = attribute.Name.Namespace == XNamespace.Xml ? "xml"
+ : attribute.Parent?.GetPrefixOfNamespace(attribute.Name.Namespace);
+ return Qualified(attribute.Name, prefix);
+ }
+
+ private static string Qualified(XName name, string? prefix)
+ {
+ var local = XmlConvert.DecodeName(name.LocalName);
+ return string.IsNullOrEmpty(prefix) ? local : prefix + ":" + local;
+ }
+
+ // ───────────────────────── Writing ─────────────────────────
+
+ public static string Write(object? root)
+ {
+ var settings = new XmlWriterSettings
+ {
+ Indent = true,
+ IndentChars = " ",
+ NewLineChars = "\n",
+ Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false),
+ };
+ using var buffer = new MemoryStream();
+ using (var writer = XmlWriter.Create(buffer, settings))
+ {
+ writer.WriteStartDocument();
+ var scope = new Scope(null);
+ if (root is DataMap { Count: 1 } map && map.GetAt(0) is var (name, value)
+ && name.Length > 0 && name[0] is not ('@' or '#') && value is not List<object?>)
+ WriteElement(writer, name, value, scope, 0);
+ else
+ WriteElement(writer, RootName, root, scope, 0);
+ writer.WriteEndDocument();
+ }
+ return Encoding.UTF8.GetString(buffer.ToArray()) + "\n";
+ }
+
+ private static void WriteElement(XmlWriter writer, string name, object? value, Scope parent, int depth)
+ {
+ if (depth > DataTree.MaxDepth)
+ throw new InvalidDataException("The data is nested too deeply.");
+
+ // Namespace declarations of this element ("@xmlns", "@xmlns:x") apply to its own name too.
+ var scope = new Scope(parent);
+ if (value is DataMap declarations)
+ {
+ foreach (var (key, declared) in declarations)
+ {
+ if (key == "@xmlns")
+ scope.Namespaces[""] = DataTree.Text(declared);
+ else if (key.StartsWith("@xmlns:", StringComparison.Ordinal))
+ scope.Namespaces[key[7..]] = DataTree.Text(declared);
+ }
+ }
+
+ var (prefix, local, ns) = scope.Resolve(name, element: true);
+ writer.WriteStartElement(prefix, local, ns);
+ switch (value)
+ {
+ case DataMap map:
+ foreach (var (key, item) in map.Where(kv => kv.Key.StartsWith('@')))
+ {
+ var attribute = key[1..];
+ var text = Clean(DataTree.IsScalar(item) ? DataTree.Text(item) : JsonData.Write(item).Trim());
+ if (attribute == "xmlns")
+ writer.WriteAttributeString("xmlns", text);
+ else if (attribute.StartsWith("xmlns:", StringComparison.Ordinal))
+ writer.WriteAttributeString("xmlns", attribute[6..], XmlnsNamespace, text);
+ else
+ {
+ var (attributePrefix, attributeLocal, attributeNs) = scope.Resolve(attribute, element: false);
+ writer.WriteAttributeString(attributePrefix, attributeLocal, attributeNs, text);
+ }
+ }
+ if (map.TryGetValue(TextKey, out var content) && content is not null)
+ writer.WriteString(Clean(DataTree.Text(content)));
+ foreach (var (key, item) in map.Where(kv => !kv.Key.StartsWith('@') && kv.Key != TextKey))
+ {
+ if (item is List<object?> repeated)
+ {
+ foreach (var each in repeated)
+ WriteElement(writer, key, each, scope, depth + 1);
+ }
+ else
+ {
+ WriteElement(writer, key, item, scope, depth + 1);
+ }
+ }
+ writer.WriteEndElement();
+ break;
+ case List<object?> list:
+ // An array inside an array (or at the root): its items have no name of their own.
+ foreach (var item in list)
+ WriteElement(writer, ItemName, item, scope, depth + 1);
+ writer.WriteEndElement();
+ break;
+ case null:
+ writer.WriteEndElement(); // <a />
+ break;
+ default:
+ writer.WriteString(Clean(DataTree.Text(value)));
+ writer.WriteFullEndElement(); // "" stays <a></a>
+ break;
+ }
+ }
+
+ /// <summary>Removes characters XML 1.0 cannot hold (most control characters).</summary>
+ private static string Clean(string text)
+ {
+ if (XmlConvert.VerifyXmlChars(text) is null)
+ return text;
+ var sb = new StringBuilder(text.Length);
+ for (var i = 0; i < text.Length; i++)
+ {
+ if (char.IsHighSurrogate(text[i]) && i + 1 < text.Length && char.IsLowSurrogate(text[i + 1]))
+ {
+ sb.Append(text[i]).Append(text[++i]);
+ }
+ else if (XmlConvert.IsXmlChar(text[i]))
+ {
+ sb.Append(text[i]);
+ }
+ }
+ return sb.ToString();
+ }
+
+ /// <summary>Namespace prefixes declared on an element and its ancestors.</summary>
+ private sealed class Scope(Scope? parent)
+ {
+ public Dictionary<string, string> Namespaces { get; } = [];
+
+ private string? Lookup(string prefix) =>
+ Namespaces.TryGetValue(prefix, out var ns) ? ns : parent?.Lookup(prefix);
+
+ /// <summary>
+ /// Prefix, local name and namespace for a key. Elements without a prefix take the default namespace;
+ /// attributes don't. A prefix nobody declared becomes part of the escaped local name.
+ /// </summary>
+ public (string? Prefix, string Local, string? Namespace) Resolve(string name, bool element)
+ {
+ var colon = name.IndexOf(':');
+ if (colon > 0 && colon < name.Length - 1)
+ {
+ var prefix = name[..colon];
+ var ns = prefix == "xml" ? XmlNamespace : Lookup(prefix);
+ if (ns is { Length: > 0 } && IsNcName(prefix))
+ return (prefix, Encode(name[(colon + 1)..]), ns);
+ }
+ return (null, Encode(name), element ? Lookup("") ?? "" : null);
+ }
+
+ private static bool IsNcName(string name)
+ {
+ try
+ {
+ XmlConvert.VerifyNCName(name);
+ return true;
+ }
+ catch (XmlException)
+ {
+ return false;
+ }
+ }
+
+ private static string Encode(string name) => name.Length == 0 ? "_" : XmlConvert.EncodeLocalName(name)!;
+ }
+}
diff --git a/src/Filee.Engines/Data/YamlData.cs b/src/Filee.Engines/Data/YamlData.cs
new file mode 100644
index 00000000..9cc2fca9
--- /dev/null
+++ b/src/Filee.Engines/Data/YamlData.cs
@@ -0,0 +1,233 @@
+// YAML with YamlDotNet (MIT). Reading follows the YAML 1.2 core schema: unquoted true / false, null / ~, numbers
+// (also 0x / 0o, .inf, .nan) get their type, everything else (and anything quoted) is text; "yes" / "no" stay text as
+// in YAML 1.2. Anchors and aliases are resolved (the value is copied wherever it is referenced), merge keys ("<<")
+// are applied, comments are dropped, and a file of several documents ("---") becomes an array of them.
+// Writing uses block style indented by two spaces; text that would read back as another type ("true", "12", "") is
+// quoted, multi-line text becomes a literal block ("|").
+
+using System.Globalization;
+using System.Numerics;
+using System.Text.RegularExpressions;
+using YamlDotNet.Core;
+using YamlDotNet.Core.Events;
+using YamlDotNet.RepresentationModel;
+
+namespace Filee.Engines.Data;
+
+internal static partial class YamlData
+{
+ /// <summary>Most values an alias may expand to ("billion laughs" files), far above any real document.</summary>
+ private const int MaxValues = 5_000_000;
+
+ public static object? Read(string text)
+ {
+ var stream = new YamlStream();
+ try
+ {
+ stream.Load(new StringReader(text));
+ }
+ catch (YamlException ex)
+ {
+ throw new InvalidDataException($"Not valid YAML: {ex.Message}", ex);
+ }
+ var reader = new Reader();
+ return stream.Documents.Count switch
+ {
+ 0 => null,
+ 1 => reader.Value(stream.Documents[0].RootNode, 0),
+ _ => stream.Documents.Select(d => reader.Value(d.RootNode, 0)).ToList(),
+ };
+ }
+
+ private sealed class Reader
+ {
+ private int _values;
+
+ public object? Value(YamlNode node, int depth)
+ {
+ if (depth > DataTree.MaxDepth)
+ throw new InvalidDataException("The YAML is nested too deeply (or an alias refers to itself).");
+ if (++_values > MaxValues)
+ throw new InvalidDataException("The YAML expands to too many values (aliases repeated too often).");
+ return node switch
+ {
+ YamlMappingNode mapping => Mapping(mapping, depth),
+ YamlSequenceNode sequence => sequence.Children.Select(child => Value(child, depth + 1)).ToList(),
+ YamlScalarNode scalar => Scalar(scalar),
+ _ => null,
+ };
+ }
+
+ private DataMap Mapping(YamlMappingNode mapping, int depth)
+ {
+ var map = new DataMap();
+ foreach (var (keyNode, valueNode) in mapping.Children)
+ {
+ if (keyNode is YamlScalarNode { Value: "<<", Style: ScalarStyle.Plain or ScalarStyle.Any })
+ {
+ // Merge key: the merged mappings' entries, unless this mapping sets them itself (earlier or later).
+ var sources = valueNode is YamlSequenceNode many ? many.Children.ToList() : [valueNode];
+ foreach (var source in sources)
+ {
+ if (Value(source, depth + 1) is not DataMap merged)
+ throw new InvalidDataException("A YAML merge key (<<) must refer to a mapping.");
+ foreach (var (key, value) in merged)
+ {
+ if (!map.ContainsKey(key) && !HasKey(mapping, key))
+ map[key] = value;
+ }
+ }
+ continue;
+ }
+ map[Key(keyNode, depth)] = Value(valueNode, depth + 1);
+ }
+ return map;
+ }
+
+ private static bool HasKey(YamlMappingNode mapping, string key) =>
+ mapping.Children.Keys.Any(k => k is YamlScalarNode { Value: var v } && v == key && v != "<<");
+
+ /// <summary>Keys are text as written ("1", "null"); a complex key (a list or mapping, rare) is written as JSON.</summary>
+ private string Key(YamlNode node, int depth) =>
+ node is YamlScalarNode scalar ? scalar.Value ?? "" : JsonData.Write(Value(node, depth + 1)).Trim();
+ }
+
+ private static object? Scalar(YamlScalarNode node)
+ {
+ var text = node.Value ?? "";
+ var tag = node.Tag.IsEmpty ? "" : node.Tag.Value;
+ switch (tag)
+ {
+ case "tag:yaml.org,2002:str":
+ return text;
+ case "tag:yaml.org,2002:null":
+ return null;
+ case "tag:yaml.org,2002:bool":
+ return Resolve(text) is bool b ? b : throw new InvalidDataException($"“{text}” is not a YAML boolean.");
+ case "tag:yaml.org,2002:int" or "tag:yaml.org,2002:float":
+ return Resolve(text) is { } number and not (string or bool) ? number
+ : throw new InvalidDataException($"“{text}” is not a YAML number.");
+ }
+ // Quoted and block text is always text; only plain scalars are typed.
+ return node.Style is ScalarStyle.Plain or ScalarStyle.Any && tag is "" or "?" ? Resolve(text) : text;
+ }
+
+ /// <summary>The YAML 1.2 core schema type of a plain scalar.</summary>
+ private static object? Resolve(string text)
+ {
+ switch (text)
+ {
+ case "" or "~" or "null" or "Null" or "NULL":
+ return null;
+ case "true" or "True" or "TRUE":
+ return true;
+ case "false" or "False" or "FALSE":
+ return false;
+ case ".inf" or ".Inf" or ".INF" or "+.inf" or "+.Inf" or "+.INF":
+ return double.PositiveInfinity;
+ case "-.inf" or "-.Inf" or "-.INF":
+ return double.NegativeInfinity;
+ case ".nan" or ".NaN" or ".NAN":
+ return double.NaN;
+ }
+ if (DecimalInteger().IsMatch(text))
+ return DataTree.Number(text.TrimStart('+'));
+ if (text.StartsWith("0x", StringComparison.Ordinal) && HexInteger().IsMatch(text))
+ return Small(BigInteger.Parse("0" + text[2..], NumberStyles.HexNumber, CultureInfo.InvariantCulture));
+ if (text.StartsWith("0o", StringComparison.Ordinal) && OctalInteger().IsMatch(text))
+ return Small(text[2..].Aggregate(BigInteger.Zero, (n, digit) => n * 8 + (digit - '0')));
+ if (Float().IsMatch(text))
+ return double.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture);
+ return text;
+ }
+
+ private static object Small(BigInteger value) => value >= long.MinValue && value <= long.MaxValue ? (object)(long)value : value;
+
+ /// <summary>True when a plain scalar with this text would read back as something other than the same text.</summary>
+ private static bool NeedsQuotes(string text) =>
+ Resolve(text) is not string
+ // YAML 1.1 readers (PyYAML, older tools) take these as booleans, numbers with "_" or dates.
+ || YamlOneOne().IsMatch(text)
+ || text.Trim() != text;
+
+ // ───────────────────────── Writing ─────────────────────────
+
+ public static string Write(object? root)
+ {
+ var output = new StringWriter { NewLine = "\n" };
+ var settings = new EmitterSettings()
+ .WithBestIndent(2)
+ .WithIndentedSequences()
+ .WithBestWidth(int.MaxValue)
+ .WithNewLine("\n");
+ var emitter = new Emitter(output, settings);
+ emitter.Emit(new StreamStart());
+ emitter.Emit(new DocumentStart());
+ Emit(emitter, root, 0);
+ emitter.Emit(new DocumentEnd(isImplicit: true));
+ emitter.Emit(new StreamEnd());
+ return output.ToString();
+ }
+
+ private static void Emit(IEmitter emitter, object? value, int depth)
+ {
+ if (depth > DataTree.MaxDepth)
+ throw new InvalidDataException("The data is nested too deeply.");
+ switch (value)
+ {
+ case DataMap map:
+ emitter.Emit(new MappingStart(AnchorName.Empty, TagName.Empty, true, map.Count == 0 ? MappingStyle.Flow : MappingStyle.Block));
+ foreach (var (key, item) in map)
+ {
+ emitter.Emit(Text(key, multiLine: false));
+ Emit(emitter, item, depth + 1);
+ }
+ emitter.Emit(new MappingEnd());
+ break;
+ case List<object?> list:
+ emitter.Emit(new SequenceStart(AnchorName.Empty, TagName.Empty, true, list.Count == 0 ? SequenceStyle.Flow : SequenceStyle.Block));
+ foreach (var item in list)
+ Emit(emitter, item, depth + 1);
+ emitter.Emit(new SequenceEnd());
+ break;
+ case string text:
+ emitter.Emit(Text(text, multiLine: true));
+ break;
+ default:
+ emitter.Emit(Plain(value switch
+ {
+ null => "null",
+ double d when double.IsNaN(d) => ".nan",
+ double d when double.IsPositiveInfinity(d) => ".inf",
+ double d when double.IsNegativeInfinity(d) => "-.inf",
+ _ => DataTree.Text(value),
+ }));
+ break;
+ }
+ }
+
+ private static Scalar Plain(string text) => new(AnchorName.Empty, TagName.Empty, text, ScalarStyle.Plain, true, false);
+
+ private static Scalar Text(string text, bool multiLine)
+ {
+ var style = multiLine && text.Contains('\n') ? ScalarStyle.Literal
+ : NeedsQuotes(text) ? ScalarStyle.DoubleQuoted
+ : ScalarStyle.Any;
+ return new Scalar(AnchorName.Empty, TagName.Empty, text, style, style == ScalarStyle.Any, true);
+ }
+
+ [GeneratedRegex("^[-+]?[0-9]+$")]
+ private static partial Regex DecimalInteger();
+
+ [GeneratedRegex("^0x[0-9a-fA-F]+$")]
+ private static partial Regex HexInteger();
+
+ [GeneratedRegex("^0o[0-7]+$")]
+ private static partial Regex OctalInteger();
+
+ [GeneratedRegex(@"^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$")]
+ private static partial Regex Float();
+
+ [GeneratedRegex(@"^(y|Y|yes|Yes|YES|n|N|no|No|NO|on|On|ON|off|Off|OFF|[-+]?[0-9][0-9_]*(\.[0-9_]*)?|[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}([Tt ].*)?|[0-9]+(:[0-5]?[0-9])+(\.[0-9_]*)?)$")]
+ private static partial Regex YamlOneOne();
+}
diff --git a/src/Filee.Engines/Email/EmlConverter.cs b/src/Filee.Engines/Email/EmlConverter.cs
index c33f4cf8..d05d320d 100644
--- a/src/Filee.Engines/Email/EmlConverter.cs
+++ b/src/Filee.Engines/Email/EmlConverter.cs
@@ -2,7 +2,8 @@
// body, or the plain text; pictures sent inline with "cid:" links become data URIs), as plain text, or its attachments
// 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.
+// 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.
using System.Globalization;
using System.IO.Compression;
@@ -15,23 +16,38 @@ using MimeKit;
namespace Filee.Engines.Email;
-/// <summary>EML → HTML, TXT and ZIP (attachments).</summary>
+/// <summary>EML and MSG → HTML, TXT and ZIP (attachments); MSG → EML.</summary>
public sealed partial class EmlConverter : IConverter
{
public string Id => "email";
public string DisplayName => "E-mail (built-in)";
public int MaxParallelism => 0;
- public IReadOnlyList<ConversionEdge> Edges { get; } = [new("eml", "html"), new("eml", "txt"), new("eml", "zip")];
+ // MSG has direct edges too: through EML (cost 20) would rebuild and parse the message twice.
+ public IReadOnlyList<ConversionEdge> Edges { get; } =
+ [
+ new("eml", "html"), new("eml", "txt"), new("eml", "zip"),
+ new("msg", "eml"), new("msg", "html"), new("msg", "txt"), new("msg", "zip"),
+ ];
- public EngineStatus GetStatus() => EngineStatus.Available("EML → HTML, TXT, ZIP (attachments)", $"{EngineVersions.BuiltIn} · {EngineVersions.Library("MimeKitLite", typeof(MimeKit.MimeMessage))}");
+ public EngineStatus GetStatus() => EngineStatus.Available("EML, MSG → HTML, TXT, ZIP (attachments); MSG → EML",
+ $"{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);
- var message = Load(step.InputPath, cancellationToken);
+ var message = step.From == "msg" ? OutlookMessage.Load(step.InputPath) : Load(step.InputPath, cancellationToken);
progress?.Report(0.5);
+ if (step.To == "eml")
+ {
+ if (step.Output.Allocate("eml") is not { } eml)
+ return [];
+ using (var file = File.Create(eml))
+ message.WriteTo(FormatOptions.Default, file, cancellationToken);
+ progress?.Report(1);
+ return [eml];
+ }
if (step.To == "zip")
{
var attachments = Attachments(message);
diff --git a/src/Filee.Engines/Email/OutlookMessage.cs b/src/Filee.Engines/Email/OutlookMessage.cs
new file mode 100644
index 00000000..9d405b96
--- /dev/null
+++ b/src/Filee.Engines/Email/OutlookMessage.cs
@@ -0,0 +1,102 @@
+// Outlook .msg (an OLE compound file of MAPI properties) read with MsgReader (MIT) and rebuilt as a MIME message with
+// MimeKit, so MSG → HTML, TXT and ZIP take the same path as EML and MSG → EML is the rebuilt message itself.
+// Carried over: sender, To / Cc / Bcc, subject, sent date, Message-ID, the text and HTML bodies (MsgReader takes the
+// HTML out of RTF-only messages), attachments, pictures shown in the body (Content-ID) and attached Outlook items,
+// which become attached .eml messages. Attachments that only link to a file elsewhere are not followed.
+
+using MimeKit;
+using MsgReader.Outlook;
+
+namespace Filee.Engines.Email;
+
+internal static class OutlookMessage
+{
+ public static MimeMessage Load(string path)
+ {
+ Storage.Message message;
+ try
+ {
+ message = new Storage.Message(path, FileAccess.Read);
+ }
+ catch (Exception ex) when (ex is not (OperationCanceledException or OutOfMemoryException))
+ {
+ throw new InvalidDataException($"Not an Outlook message: {ex.Message}", ex);
+ }
+ using (message)
+ return ToMime(message);
+ }
+
+ internal static MimeMessage ToMime(Storage.Message message)
+ {
+ var mime = new MimeMessage();
+ if (Mailbox(message.Sender?.DisplayName, message.Sender?.Email) is { } from)
+ mime.From.Add(from);
+ foreach (var recipient in message.Recipients)
+ {
+ if (Mailbox(recipient.DisplayName, recipient.Email) is not { } mailbox)
+ continue;
+ var list = recipient.Type switch
+ {
+ RecipientType.Cc => mime.Cc,
+ RecipientType.Bcc => mime.Bcc,
+ _ => mime.To,
+ };
+ list.Add(mailbox);
+ }
+ mime.Subject = message.Subject ?? "";
+ if (message.SentOn is { } sent)
+ mime.Date = sent;
+ if (message.Headers?.MessageId is { Length: > 0 } id)
+ mime.MessageId = id.Trim('<', '>');
+
+ var body = new BodyBuilder
+ {
+ TextBody = string.IsNullOrEmpty(message.BodyText) ? null : message.BodyText,
+ HtmlBody = string.IsNullOrEmpty(message.BodyHtml) ? null : message.BodyHtml,
+ };
+ foreach (var item in message.Attachments)
+ {
+ switch (item)
+ {
+ case Storage.Attachment { IsExternalReference: false, Data: { Length: >= 0 } data } attachment:
+ var name = string.IsNullOrWhiteSpace(attachment.FileName) ? "attachment" : attachment.FileName;
+ var type = ContentType.TryParse(attachment.MimeType ?? "", out var parsed) ? parsed : ContentType.Parse(MimeTypes.GetMimeType(name));
+ // A picture the HTML body shows ("cid:") goes with the body, not into the attachments.
+ if (attachment.ContentId is { Length: > 0 } contentId
+ && body.HtmlBody?.Contains("cid:" + contentId.Trim('<', '>'), StringComparison.OrdinalIgnoreCase) == true)
+ {
+ var resource = body.LinkedResources.Add(name, data, type);
+ resource.ContentId = contentId.Trim('<', '>');
+ }
+ else
+ {
+ body.Attachments.Add(name, data, type);
+ }
+ break;
+ case Storage.Message attached:
+ var inner = ToMime(attached);
+ var fileName = string.IsNullOrWhiteSpace(inner.Subject) ? "message" : inner.Subject;
+ body.Attachments.Add(new MessagePart
+ {
+ Message = inner,
+ ContentDisposition = new ContentDisposition(ContentDisposition.Attachment) { FileName = fileName },
+ });
+ break;
+ }
+ }
+ mime.Body = body.ToMessageBody();
+ return mime;
+ }
+
+ /// <summary>A sender or recipient; Exchange-only addresses (no "@") keep the name.</summary>
+ private static MailboxAddress? Mailbox(string? name, string? address)
+ {
+ name = name?.Trim();
+ address = address?.Trim();
+ if (string.IsNullOrEmpty(name) && string.IsNullOrEmpty(address))
+ return null;
+ if (string.Equals(name, address, StringComparison.OrdinalIgnoreCase))
+ name = null;
+ return new MailboxAddress(name ?? "", address ?? "");
+ }
+}
diff --git a/src/Filee.Engines/EngineRegistry.cs b/src/Filee.Engines/EngineRegistry.cs
index 731e3bf3..c67c299c 100644
--- a/src/Filee.Engines/EngineRegistry.cs
+++ b/src/Filee.Engines/EngineRegistry.cs
@@ -3,6 +3,7 @@
using Filee.Core.Conversion;
using Filee.Engines.Archives;
using Filee.Engines.Cad;
+using Filee.Engines.Data;
using Filee.Engines.Ebooks;
using Filee.Engines.Email;
using Filee.Engines.Fonts;
@@ -45,6 +46,7 @@ public static class EngineRegistry
new DocxWriterConverter(),
new PdfTextConverter(),
new EmlConverter(),
+ new DataConverter(),
new FfmpegConverter(),
new CadConverter(),
new EbookConverter(),
diff --git a/src/Filee.Engines/Filee.Engines.csproj b/src/Filee.Engines/Filee.Engines.csproj
index 923aab6e..871484e8 100644
--- a/src/Filee.Engines/Filee.Engines.csproj
+++ b/src/Filee.Engines/Filee.Engines.csproj
@@ -28,6 +28,9 @@
<PackageReference Include="MimeKitLite" />
<PackageReference Include="ACadSharp" />
<PackageReference Include="AngleSharp" />
+ <PackageReference Include="YamlDotNet" />
+ <PackageReference Include="Tomlyn" />
+ <PackageReference Include="MsgReader" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
</ItemGroup>
diff --git a/src/Filee.Engines/Office/Sheets/CsvFormat.cs b/src/Filee.Engines/Office/Sheets/CsvFormat.cs
index 7d873a40..4b4fc700 100644
--- a/src/Filee.Engines/Office/Sheets/CsvFormat.cs
+++ b/src/Filee.Engines/Office/Sheets/CsvFormat.cs
@@ -70,6 +70,15 @@ internal static class CsvFormat
File.WriteAllText(path, sb.ToString(), new UTF8Encoding(encoderShouldEmitUTF8Identifier: true));
}
+ /// <summary>Writes rows of text as CSV the same way as <see cref="Write"/> (UTF-8 with BOM, CRLF).</summary>
+ public static void WriteRows(IEnumerable<IEnumerable<string>> rows, string path, char delimiter = ',')
+ {
+ var sb = new StringBuilder();
+ foreach (var row in rows)
+ sb.Append(string.Join(delimiter, row.Select(value => Quote(value, delimiter)))).Append("\r\n");
+ File.WriteAllText(path, sb.ToString(), new UTF8Encoding(encoderShouldEmitUTF8Identifier: true));
+ }
+
internal static List<List<string>> Parse(string text, char delimiter)
{
var rows = new List<List<string>>();
diff --git a/tests/Filee.Cli.Tests/CliTests.cs b/tests/Filee.Cli.Tests/CliTests.cs
index fdf3af16..f4cb72da 100644
--- a/tests/Filee.Cli.Tests/CliTests.cs
+++ b/tests/Filee.Cli.Tests/CliTests.cs
@@ -168,6 +168,23 @@ public sealed class CliTests : IDisposable
Assert.Contains("to-png", output);
}
+ [Fact]
+ public async Task Data_files_convert_to_each_other()
+ {
+ var json = Path.Combine(_folder, "config.json");
+ await File.WriteAllTextAsync(json, """{"name": "Filee", "ports": [80, 443]}""", TestContext.Current.CancellationToken);
+
+ var (code, output, errors) = await Run("convert", json, "--to", "yaml");
+
+ Assert.Equal(Cli.Success, code);
+ Assert.Equal("", errors);
+ Assert.Equal("name: Filee\nports:\n - 80\n - 443\n", await File.ReadAllTextAsync(Path.Combine(_folder, "config.yaml"), TestContext.Current.CancellationToken));
+
+ (code, output, _) = await Run("formats", "json");
+ Assert.Equal(Cli.Success, code);
+ Assert.Contains("yaml, toml, xml", output);
+ }
+
[Fact]
public async Task Help_and_version_need_no_engines()
{
diff --git a/tests/Filee.Core.Tests/ProfileSelectorTests.cs b/tests/Filee.Core.Tests/ProfileSelectorTests.cs
index 2c852bad..b7391236 100644
--- a/tests/Filee.Core.Tests/ProfileSelectorTests.cs
+++ b/tests/Filee.Core.Tests/ProfileSelectorTests.cs
@@ -26,6 +26,10 @@ public class ProfileSelectorTests
[InlineData("archives", "a.tar.gz", "b.zip")]
[InlineData("video", @"C:\clips\a.MP4", @"C:\clips\b.mkv")]
[InlineData("text", "notes.md", "readme.txt")]
+ [InlineData("data", "a.json", "b.YML", "c.toml", "d.xml")]
+ [InlineData("data", "contacts.vcf")]
+ [InlineData("spreadsheets", "table.csv")]
+ [InlineData("office", "mail.msg", "mail.eml")]
public void Built_in_profiles_take_their_files(string expected, params string[] files) =>
Assert.Equal(expected, Pick(_builtIn, files));
diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.cs
index cf18bdab..e3c1f436 100644
--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs
+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs
@@ -60,7 +60,7 @@ public class UserDataStoreTests
var store = new UserDataStore(dir.Path);
store.Load();
- Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "email", "vector", "icns", "font", "cad", "archive", "ebook", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);
+ Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "email", "data", "vector", "icns", "font", "cad", "archive", "ebook", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);
Assert.Equal(AppSettings.CurrentSchemaVersion, store.Settings.SchemaVersion);
}
@@ -112,7 +112,7 @@ public class UserDataStoreTests
var store = new UserDataStore(dir.Path);
store.Load();
- Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "email", "vector", "icns", "font", "cad", "archive", "ebook", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);
+ Assert.Equal(["magick", "markdown", "spreadsheet", "ooxml", "hwpx-writer", "docx-writer", "pdf-text", "email", "data", "vector", "icns", "font", "cad", "archive", "ebook", "ffmpeg", "pandoc", "ghostscript", "calibre", "libreoffice"], store.Settings.EnginePriority);
var ids = store.Profiles.Select(p => p.Id).ToList();
Assert.Equal(ids.IndexOf("office") + 1, ids.IndexOf("spreadsheets"));
Assert.Equal(ids.IndexOf("office") + 2, ids.IndexOf("presentations"));
@@ -139,7 +139,7 @@ public class UserDataStoreTests
var ids = profiles.Select(p => p.Id).ToList();
Assert.Equal(ids.IndexOf("text") + 1, ids.IndexOf("ebooks"));
- Assert.Equal(ids.IndexOf("mixed") - 1, ids.IndexOf("fonts"));
+ Assert.Equal(ids.IndexOf("mixed") - 2, ids.IndexOf("fonts")); // then "data" (schema 11)
Assert.Contains("cr2", profiles.Single(p => p.Id == "images").Extensions);
Assert.DoesNotContain("mp3", profiles.Single(p => p.Id == "audio").Extensions);
Assert.Contains("flac", profiles.Single(p => p.Id == "audio").Extensions);
@@ -210,6 +210,52 @@ public class UserDataStoreTests
Assert.False(SettingsMigrations.ApplyToLibrary(9, presets, profiles)); // once only
}
+ [Fact]
+ public void Version_10_libraries_get_the_data_donut_msg_files_and_json_for_spreadsheets()
+ {
+ // As written by 1.10.x: no data presets or donut, no MSG on the documents donut, no JSON on the spreadsheets
+ // donut; and a donut of the user that already takes YAML.
+ var presets = BuiltInData.CreatePresets();
+ presets.RemoveAll(p => BuiltInData.DataPresets().Any(d => d.Id == p.Id));
+ var profiles = BuiltInData.CreateProfiles();
+ profiles.RemoveAll(p => p.Id == "data");
+ profiles.Single(p => p.Id == "office").Extensions.Remove("msg");
+ profiles.Single(p => p.Id == "spreadsheets").PresetIds.Remove("to-json");
+ profiles.Insert(0, new ToolbarProfile { Id = "mine", Name = "Mine", Extensions = ["yml"] });
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(10, presets, profiles));
+
+ Assert.All(BuiltInData.DataPresets(), d => Assert.Contains(presets, p => p.Id == d.Id));
+ var ids = profiles.Select(p => p.Id).ToList();
+ Assert.Equal(ids.IndexOf("fonts") + 1, ids.IndexOf("data"));
+ var data = profiles.Single(p => p.Id == "data");
+ Assert.Contains("json", data.Extensions);
+ Assert.Contains("yaml", data.Extensions);
+ Assert.DoesNotContain("yml", data.Extensions); // the user's donut keeps it
+ Assert.Equal(["to-json", "to-yaml", "to-toml", "to-xml", "to-csv", "to-xlsx"], data.PresetIds);
+ Assert.Contains("msg", profiles.Single(p => p.Id == "office").Extensions);
+ var sheets = profiles.Single(p => p.Id == "spreadsheets").PresetIds;
+ Assert.Equal(sheets.IndexOf("to-csv") + 1, sheets.IndexOf("to-json"));
+ Assert.DoesNotContain(profiles, p => p.PresetIds.Contains("to-eml") || p.PresetIds.Contains("to-vcf"));
+ Assert.False(SettingsMigrations.ApplyToLibrary(10, presets, profiles)); // once only
+
+ var all = profiles.SelectMany(p => p.Extensions).ToList();
+ Assert.Equal(all.Count, all.Distinct(StringComparer.OrdinalIgnoreCase).Count());
+ }
+
+ [Fact]
+ public void Version_10_settings_get_the_data_engine_after_email()
+ {
+ using var dir = new TempDir();
+ File.WriteAllText(Path.Combine(dir.Path, "settings.json"),
+ """{ "schemaVersion": 10, "enginePriority": ["magick", "email", "vector", "pandoc", "libreoffice"] }""");
+
+ var store = new UserDataStore(dir.Path);
+ store.Load();
+
+ Assert.Equal(["magick", "email", "data", "vector", "pandoc", "libreoffice"], store.Settings.EnginePriority);
+ }
+
[Fact]
public void Catalog_migration_ignores_extensions_checked_on_mixed_profiles()
{
diff --git a/tests/Filee.Engines.Tests/DataTests.cs b/tests/Filee.Engines.Tests/DataTests.cs
new file mode 100644
index 00000000..d968a6c4
--- /dev/null
+++ b/tests/Filee.Engines.Tests/DataTests.cs
@@ -0,0 +1,398 @@
+// JSON, JSON Lines, YAML, TOML, XML and CSV through the built-in data engine: types and structure carried over, the
+// documented lossy cases (TOML root, XML attributes and repeats, YAML anchors, CSV tables only) and the routes through
+// CSV to spreadsheets. Inputs are written in the test.
+
+using System.Text;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Tomlyn;
+using Tomlyn.Model;
+
+namespace Filee.Engines.Tests;
+
+public class DataTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ static DataTests() => Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+
+ private string Write(string name, string text, Encoding? encoding = null)
+ {
+ var path = Path.Combine(fx.NewFolder(), name);
+ File.WriteAllText(path, text, encoding ?? new UTF8Encoding(false));
+ return path;
+ }
+
+ 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 async Task<string> ConvertTextAsync(string name, string text, string target)
+ {
+ var output = await ConvertAsync(Write(name, text), target);
+ var bytes = await File.ReadAllBytesAsync(output, TestContext.Current.CancellationToken);
+ if (target != "csv")
+ Assert.False(bytes is [0xEF, 0xBB, 0xBF, ..], "UTF-8 without BOM");
+ return Encoding.UTF8.GetString(bytes).TrimStart('');
+ }
+
+ private async Task<string> FailAsync(string name, string text, string target)
+ {
+ var job = await fx.ConvertAsync([Write(name, text)], new Preset { TargetFormat = target });
+ Assert.Equal(JobState.Failed, job.State);
+ return job.Files.Single().ErrorDetail ?? "";
+ }
+
+ private const string Sample = """
+ {
+ "name": "Filee 변환기",
+ "version": 3,
+ "ratio": 3.0,
+ "big": 12345678901234567890,
+ "enabled": true,
+ "missing": null,
+ "notes": "first line\nsecond line",
+ "looksLikeABoolean": "true",
+ "looksLikeANumber": "007",
+ "empty": "",
+ "tags": ["a", "b"],
+ "nothing": [],
+ "owner": { "id": 1, "email": "[email protected]" },
+ "rows": [ { "x": 1 }, { "x": 2 } ]
+ }
+ """;
+
+ [Fact]
+ public async Task Json_to_yaml_keeps_types_quotes_ambiguous_text_and_indents_by_two()
+ {
+ var yaml = await ConvertTextAsync("sample.json", Sample, "yaml");
+
+ Assert.Equal("""
+ name: Filee 변환기
+ version: 3
+ ratio: 3.0
+ big: 12345678901234567890
+ enabled: true
+ missing: null
+ notes: |-
+ first line
+ second line
+ looksLikeABoolean: "true"
+ looksLikeANumber: "007"
+ empty: ""
+ tags:
+ - a
+ - b
+ nothing: []
+ owner:
+ id: 1
+ rows:
+ - x: 1
+ - x: 2
+
+ """.ReplaceLineEndings("\n"), yaml);
+ }
+
+ [Fact]
+ public async Task Json_round_trips_through_yaml_toml_and_xml_where_the_format_allows()
+ {
+ var yaml = await ConvertAsync(Write("sample.json", Sample), "yaml");
+ var back = await File.ReadAllTextAsync(await ConvertAsync(yaml, "json"), TestContext.Current.CancellationToken);
+ Assert.Contains("\"name\": \"Filee 변환기\"", back);
+ Assert.Contains("\"ratio\": 3.0,", back);
+ Assert.Contains("\"big\": 12345678901234567890,", back);
+ Assert.Contains("\"missing\": null,", back);
+ Assert.Contains("\"looksLikeABoolean\": \"true\",", back);
+ Assert.Contains("\"notes\": \"first line\\nsecond line\",", back);
+ Assert.Contains(" \"tags\": [\n \"a\",", back); // two-space indentation
+
+ var toml = await ConvertTextAsync("sample.json", Sample, "toml");
+ Assert.DoesNotContain("missing", toml); // TOML has no null
+ Assert.Contains("big = \"12345678901234567890\"\n", toml); // beyond 64-bit: kept as text
+ Assert.Contains("ratio = 3.0\n", toml);
+ Assert.Contains("\n[owner]\nid = 1\n", toml);
+ Assert.Contains("\n[[rows]]\nx = 1\n\n[[rows]]\nx = 2\n", toml);
+ var table = TomlSerializer.Deserialize<TomlTable>(toml)!; // valid TOML
+ Assert.Equal("Filee 변환기", table["name"]);
+ Assert.Equal(3L, table["version"]);
+
+ var xml = await ConvertTextAsync("sample.json", Sample, "xml");
+ Assert.StartsWith("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n <name>Filee 변환기</name>\n", xml);
+ Assert.Contains(" <missing />\n", xml);
+ Assert.Contains(" <empty></empty>\n", xml);
+ Assert.Contains(" <tags>a</tags>\n <tags>b</tags>\n", xml);
+ }
+
+ [Fact]
+ public async Task Yaml_anchors_merge_keys_and_core_schema_types_become_json()
+ {
+ const string Yaml = """
+ # comments are dropped
+ defaults: &defaults
+ adapter: postgres
+ port: 5432
+ development:
+ <<: *defaults
+ port: 5433
+ database: dev
+ flags: [yes, no, on, ~, 0x1F, 0o17, .inf, -1.5e3, '42']
+ when: 2026-10-16
+ text: |
+ line one
+ line two
+ """;
+
+ var json = await ConvertTextAsync("config.yml", Yaml, "json");
+
+ Assert.Contains("""
+ "development": {
+ "adapter": "postgres",
+ "port": 5433,
+ "database": "dev"
+ },
+ """.ReplaceLineEndings("\n"), json);
+ Assert.Contains("""
+ "flags": [
+ "yes",
+ "no",
+ "on",
+ null,
+ 31,
+ 15,
+ "Infinity",
+ -1500.0,
+ "42"
+ ],
+ """.ReplaceLineEndings("\n"), json);
+ Assert.Contains("\"when\": \"2026-10-16\"", json);
+ Assert.Contains("\"text\": \"line one\\nline two\"", json); // the file ends without a line break
+ Assert.DoesNotContain("comments", json);
+ }
+
+ [Fact]
+ public async Task Several_yaml_documents_become_an_array_and_alias_bombs_are_refused()
+ {
+ var json = await ConvertTextAsync("docs.yaml", "a: 1\n---\nb: 2\n", "json");
+ Assert.Equal("[\n {\n \"a\": 1\n },\n {\n \"b\": 2\n }\n]\n", json);
+
+ var error = await FailAsync("bad.yaml", "key: [unclosed\n", "json");
+ Assert.Contains("Not valid YAML", error);
+
+ // "Billion laughs": each level repeats the one before ten times (10^8 values).
+ var bomb = new StringBuilder("l0: &l0 [x, x, x, x, x, x, x, x, x, x]\n");
+ for (var i = 1; i <= 8; i++)
+ bomb.Append($"l{i}: &l{i} [{string.Join(", ", Enumerable.Repeat($"*l{i - 1}", 10))}]\n");
+ error = await FailAsync("bomb.yaml", bomb.ToString(), "json");
+ Assert.Contains("too many values", error);
+ }
+
+ [Fact]
+ public async Task Toml_dates_tables_and_arrays_of_tables_become_json_and_yaml()
+ {
+ const string Toml = """
+ title = "TOML 예제"
+ released = 1979-05-27T07:32:00-08:00
+ day = 2026-10-16
+
+ [server]
+ ports = [8000, 8001]
+ limits = { cpu = 2.5, memory = "1G" }
+
+ [[products]]
+ name = "Hammer"
+ sku = 738594937
+
+ [[products]]
+ name = "Nail"
+ """;
+
+ var json = await ConvertTextAsync("config.toml", Toml, "json");
+ Assert.Contains("\"title\": \"TOML 예제\"", json);
+ Assert.Contains("\"released\": \"1979-05-27T07:32:00-08:00\"", json);
+ Assert.Contains("\"day\": \"2026-10-16\"", json);
+ Assert.Contains("\"limits\": {\n \"cpu\": 2.5,\n \"memory\": \"1G\"\n }", json);
+ Assert.Contains("\"products\": [\n {\n \"name\": \"Hammer\",\n \"sku\": 738594937\n },", json);
+
+ var yaml = await ConvertTextAsync("config.toml", Toml, "yaml");
+ Assert.Contains("released: 1979-05-27T07:32:00-08:00\n", yaml);
+ Assert.Contains("products:\n - name: Hammer\n sku: 738594937\n - name: Nail\n", yaml);
+ }
+
+ [Fact]
+ public async Task A_root_that_is_not_a_table_goes_under_items_in_toml()
+ {
+ var toml = await ConvertTextAsync("list.json", """[{"a": 1, "b": null}, {"a": 2}]""", "toml");
+ Assert.Equal("[[items]]\na = 1\n\n[[items]]\na = 2\n", toml);
+
+ toml = await ConvertTextAsync("value.json", "\"just text\"", "toml");
+ Assert.Equal("items = \"just text\"\n", toml);
+ }
+
+ [Fact]
+ public async Task Xml_attributes_repeats_text_and_namespaces_become_json()
+ {
+ const string Xml = """
+ <?xml version="1.0" encoding="utf-8"?>
+ <!-- dropped -->
+ <catalog xmlns:dc="http://purl.org/dc/elements/1.1/" version="2">
+ <book id="b1" lang="ko">
+ <dc:title>한국어 책</dc:title>
+ <price currency="KRW">15000</price>
+ <note/>
+ <summary></summary>
+ <body><![CDATA[a < b]]></body>
+ </book>
+ <book id="b2">
+ <dc:title>Second</dc:title>
+ </book>
+ </catalog>
+ """;
+
+ var json = await ConvertTextAsync("catalog.xml", Xml, "json");
+
+ Assert.Equal("""
+ {
+ "catalog": {
+ "@xmlns:dc": "http://purl.org/dc/elements/1.1/",
+ "@version": "2",
+ "book": [
+ {
+ "@id": "b1",
+ "@lang": "ko",
+ "dc:title": "한국어 책",
+ "price": {
+ "@currency": "KRW",
+ "#text": "15000"
+ },
+ "note": null,
+ "summary": "",
+ "body": "a < b"
+ },
+ {
+ "@id": "b2",
+ "dc:title": "Second"
+ }
+ ]
+ }
+ }
+
+ """.ReplaceLineEndings("\n"), json);
+
+ // And back: the same elements, attributes and namespace.
+ var xml = await File.ReadAllTextAsync(await ConvertAsync(Write("catalog.json", json), "xml"), TestContext.Current.CancellationToken);
+ Assert.Contains("<catalog xmlns:dc=\"http://purl.org/dc/elements/1.1/\" version=\"2\">", xml);
+ Assert.Contains(" <dc:title>한국어 책</dc:title>\n <price currency=\"KRW\">15000</price>\n <note />\n <summary></summary>\n <body>a &lt; b</body>\n", xml);
+ Assert.Equal(2, xml.Split("<book ").Length - 1);
+ }
+
+ [Fact]
+ public async Task A_default_namespace_survives_xml_to_yaml_and_back()
+ {
+ const string Xml = "<feed xmlns=\"http://www.w3.org/2005/Atom\" xml:lang=\"ko\"><title>소식</title><entry><id>1</id></entry></feed>";
+
+ var yaml = await ConvertTextAsync("feed.xml", Xml, "yaml");
+ Assert.Equal("feed:\n '@xmlns': http://www.w3.org/2005/Atom\n '@xml:lang': ko\n title: 소식\n entry:\n id: \"1\"\n", yaml);
+
+ var xml = await ConvertTextAsync("feed.yaml", yaml, "xml");
+ Assert.Equal("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<feed xmlns=\"http://www.w3.org/2005/Atom\" xml:lang=\"ko\">\n <title>소식</title>\n <entry>\n <id>1</id>\n </entry>\n</feed>\n", xml);
+ }
+
+ [Fact]
+ public async Task Xml_in_euc_kr_and_names_that_are_not_xml_names()
+ {
+ var path = Write("old.xml", "<?xml version=\"1.0\" encoding=\"EUC-KR\"?><memo><to>홍길동</to></memo>", Encoding.GetEncoding("EUC-KR"));
+ var json = await File.ReadAllTextAsync(await ConvertAsync(path, "json"), TestContext.Current.CancellationToken);
+ Assert.Contains("\"to\": \"홍길동\"", json);
+
+ var xml = await ConvertTextAsync("names.json", """{"first name": "Ada", "1st": 1, "list": [[1, 2]]}""", "xml");
+ Assert.Contains("<first_x0020_name>Ada</first_x0020_name>", xml);
+ Assert.Contains("<_x0031_st>1</_x0031_st>", xml);
+ Assert.Contains("<list>\n <item>1</item>\n <item>2</item>\n </list>", xml);
+ var back = await File.ReadAllTextAsync(await ConvertAsync(Write("names.xml", xml), "json"), TestContext.Current.CancellationToken);
+ Assert.Contains("\"first name\": \"Ada\"", back); // names unescaped again
+ }
+
+ [Fact]
+ public async Task Csv_becomes_typed_records_and_back()
+ {
+ const string Csv = "name,zip,age,member,score\r\n홍길동,01234,42,TRUE,3.5\r\n\"Kim, Ada\",,7,false,\r\n";
+
+ var json = await ConvertTextAsync("people.csv", Csv, "json");
+ Assert.Equal("""
+ [
+ {
+ "name": "홍길동",
+ "zip": "01234",
+ "age": 42,
+ "member": true,
+ "score": 3.5
+ },
+ {
+ "name": "Kim, Ada",
+ "zip": "",
+ "age": 7,
+ "member": false,
+ "score": ""
+ }
+ ]
+
+ """.ReplaceLineEndings("\n"), json);
+
+ var csv = await ConvertTextAsync("people.json", json, "csv");
+ Assert.Equal("name,zip,age,member,score\r\n홍길동,01234,42,true,3.5\r\n\"Kim, Ada\",,7,false,\r\n", csv);
+ }
+
+ [Fact]
+ public async Task Tables_become_csv_in_every_shape_and_anything_else_is_refused()
+ {
+ // Wrapped array of objects, with one level of nesting and keys that only some rows have.
+ var csv = await ConvertTextAsync("users.json",
+ """{"users": [{"id": 1, "address": {"city": "Seoul"}}, {"id": 2, "vip": true}]}""", "csv");
+ Assert.Equal("id,address.city,vip\r\n1,Seoul,\r\n2,,true\r\n", csv);
+
+ // Object of arrays (columns).
+ csv = await ConvertTextAsync("columns.yaml", "name: [a, b]\nage: [1]\n", "csv");
+ Assert.Equal("name,age\r\na,1\r\nb,\r\n", csv);
+
+ // XML rows.
+ csv = await ConvertTextAsync("rows.xml", "<rows><row><a>1</a><b>x</b></row><row><a>2</a><b>y</b></row></rows>", "csv");
+ Assert.Equal("a,b\r\n1,x\r\n2,y\r\n", csv);
+
+ var error = await FailAsync("nested.json", """[{"id": 1, "tags": ["a", "b"]}]""", "csv");
+ Assert.Contains("“tags” holds a list", error);
+ Assert.Contains("CSV holds a table", error);
+ error = await FailAsync("deep.json", """[{"a": {"b": {"c": 1}}}]""", "csv");
+ Assert.Contains("“a.b” is nested more than one level", error);
+ error = await FailAsync("value.json", "42", "csv");
+ Assert.Contains("single value", error);
+ }
+
+ [Fact]
+ public async Task Json_lines_both_ways()
+ {
+ var json = await ConvertTextAsync("events.jsonl", "{\"a\":1}\n\n{\"a\":2,\"b\":\"한\"}\n", "json");
+ Assert.Equal("[\n {\n \"a\": 1\n },\n {\n \"a\": 2,\n \"b\": \"한\"\n }\n]\n", json);
+
+ var lines = await ConvertTextAsync("events.json", json, "jsonl");
+ Assert.Equal("{\"a\":1}\n{\"a\":2,\"b\":\"한\"}\n", lines);
+
+ var error = await FailAsync("broken.jsonl", "{\"a\":1}\n{oops}\n", "json");
+ Assert.Contains("Line 2", error);
+ }
+
+ [Fact]
+ public async Task Spreadsheets_and_contacts_reach_json_through_csv()
+ {
+ var planner = fx.Catalog.CreatePlanner();
+ Assert.Equal(["spreadsheet", "data"], planner.Plan("xlsx", "json")!.Steps.Select(s => s.Converter.Id));
+ Assert.Equal(["data", "spreadsheet"], planner.Plan("yaml", "xlsx")!.Steps.Select(s => s.Converter.Id));
+ Assert.Equal(["data", "data"], planner.Plan("vcf", "json")!.Steps.Select(s => s.Converter.Id));
+ Assert.Single(planner.Plan("csv", "json")!.Steps);
+
+ var xlsx = await ConvertAsync(Write("sheet.csv", "item,qty\r\n사과,3\r\n"), "xlsx");
+ var json = await File.ReadAllTextAsync(await ConvertAsync(xlsx, "json"), TestContext.Current.CancellationToken);
+ Assert.Contains("\"item\": \"사과\",\n \"qty\": 3", json);
+ }
+}
diff --git a/tests/Filee.Engines.Tests/MsgBuilder.cs b/tests/Filee.Engines.Tests/MsgBuilder.cs
new file mode 100644
index 00000000..7e4fb6ac
--- /dev/null
+++ b/tests/Filee.Engines.Tests/MsgBuilder.cs
@@ -0,0 +1,161 @@
+// Writes small Outlook .msg files (MS-OXMSG: MAPI properties in an OLE compound file) for the e-mail tests, with
+// OpenMcdf, which MsgReader brings along. Only what Outlook needs to show a message is written: the property streams,
+// strings and binaries in "__substg1.0_" streams, one storage per recipient and attachment, and an empty named
+// property map.
+
+using System.Text;
+using OpenMcdf;
+
+namespace Filee.Engines.Tests;
+
+internal sealed class MsgBuilder
+{
+ private const ushort Long = 0x0003, Boolean = 0x000B, Time = 0x0040, Unicode = 0x001F, Binary = 0x0102, Object = 0x000D;
+
+ public string Subject { get; init; } = "";
+ public string SenderName { get; init; } = "";
+ public string SenderEmail { get; init; } = "";
+ public DateTime SentUtc { get; init; } = new(2026, 10, 1, 0, 30, 0, DateTimeKind.Utc);
+ public string? Body { get; init; }
+ public string? Html { get; init; }
+ public string? MessageId { get; init; }
+ public List<(string Name, string Email, int Type)> Recipients { get; } = [];
+ public List<(string FileName, byte[] Data, string MimeType, string? ContentId)> Attachments { get; } = [];
+ public List<MsgBuilder> AttachedMessages { get; } = [];
+
+ public void Save(string path)
+ {
+ using var root = RootStorage.Create(path, OpenMcdf.Version.V3, StorageModeFlags.None);
+ WriteMessage(root, topLevel: true);
+ var names = root.CreateStorage("__nameid_version1.0");
+ foreach (var stream in new[] { "__substg1.0_00020102", "__substg1.0_00030102", "__substg1.0_00040102" })
+ names.CreateStream(stream).Dispose();
+ }
+
+ private void WriteMessage(Storage storage, bool topLevel)
+ {
+ var properties = new Properties(storage);
+ properties.String(0x001A, "IPM.Note");
+ properties.String(0x0037, Subject);
+ properties.String(0x0C1A, SenderName);
+ properties.String(0x0C1F, SenderEmail);
+ properties.String(0x0C1E, "SMTP");
+ properties.String(0x5D01, SenderEmail);
+ properties.String(0x0042, SenderName);
+ properties.String(0x0065, SenderEmail);
+ properties.String(0x0064, "SMTP");
+ properties.Fixed(0x0039, Time, BitConverter.GetBytes(SentUtc.ToFileTimeUtc()));
+ properties.Fixed(0x3FDE, Long, BitConverter.GetBytes(65001)); // PR_INTERNET_CPID: UTF-8
+ properties.Fixed(0x0E07, Long, BitConverter.GetBytes(1)); // PR_MESSAGE_FLAGS: read
+ if (Body is not null)
+ properties.String(0x1000, Body);
+ if (Html is not null)
+ properties.Bytes(0x1013, Encoding.UTF8.GetBytes(Html));
+ if (MessageId is not null)
+ {
+ properties.String(0x1035, MessageId);
+ properties.String(0x007D, $"Message-ID: {MessageId}\r\nSubject: {Subject}\r\n");
+ }
+
+ for (var i = 0; i < Recipients.Count; i++)
+ {
+ var (name, email, type) = Recipients[i];
+ var recipient = new Properties(storage.CreateStorage($"__recip_version1.0_#{i:X8}"));
+ recipient.Fixed(0x0C15, Long, BitConverter.GetBytes(type)); // 1 To, 2 Cc, 3 Bcc
+ recipient.Fixed(0x3000, Long, BitConverter.GetBytes(i)); // PR_ROWID
+ recipient.String(0x3001, name);
+ recipient.String(0x3002, "SMTP");
+ recipient.String(0x3003, email);
+ recipient.String(0x39FE, email);
+ recipient.Save(8);
+ }
+
+ var count = 0;
+ foreach (var (fileName, data, mimeType, contentId) in Attachments)
+ {
+ var attachment = new Properties(storage.CreateStorage($"__attach_version1.0_#{count:X8}"));
+ attachment.Fixed(0x3705, Long, BitConverter.GetBytes(1)); // ATTACH_BY_VALUE
+ attachment.Fixed(0x0E21, Long, BitConverter.GetBytes(count)); // PR_ATTACH_NUM
+ attachment.Bytes(0x3701, data);
+ attachment.String(0x3707, fileName);
+ attachment.String(0x3704, fileName);
+ attachment.String(0x370E, mimeType);
+ if (contentId is not null)
+ {
+ attachment.String(0x3712, contentId);
+ attachment.Fixed(0x3714, Long, BitConverter.GetBytes(4)); // ATT_MHTML_REF
+ attachment.Fixed(0x7FFE, Boolean, BitConverter.GetBytes(1)); // hidden: shown in the body
+ }
+ attachment.Fixed(0x370B, Long, BitConverter.GetBytes(-1)); // PR_RENDERING_POSITION
+ attachment.Save(8);
+ count++;
+ }
+ foreach (var message in AttachedMessages)
+ {
+ var storageOfAttachment = storage.CreateStorage($"__attach_version1.0_#{count:X8}");
+ var attachment = new Properties(storageOfAttachment);
+ attachment.Fixed(0x3705, Long, BitConverter.GetBytes(5)); // ATTACH_EMBEDDED_MSG
+ attachment.Fixed(0x0E21, Long, BitConverter.GetBytes(count));
+ attachment.String(0x3001, message.Subject);
+ attachment.Fixed(0x3701, Object, new byte[8]);
+ attachment.Save(8);
+ var embedded = storageOfAttachment.CreateStorage("__substg1.0_3701000D");
+ message.WriteMessage(embedded, topLevel: false);
+ count++;
+ }
+
+ // Header: reserved, next recipient id, next attachment id, recipient count, attachment count (+ reserved at
+ // the top level).
+ var header = new List<byte>(new byte[8]);
+ header.AddRange(BitConverter.GetBytes(Recipients.Count));
+ header.AddRange(BitConverter.GetBytes(count));
+ header.AddRange(BitConverter.GetBytes(Recipients.Count));
+ header.AddRange(BitConverter.GetBytes(count));
+ if (topLevel)
+ header.AddRange(new byte[8]);
+ properties.Save([.. header]);
+ }
+
+ /// <summary>The property stream of one storage plus the streams of its variable-size values.</summary>
+ private sealed class Properties(Storage storage)
+ {
+ private readonly MemoryStream _entries = new();
+
+ public void String(ushort id, string value)
+ {
+ var bytes = Encoding.Unicode.GetBytes(value);
+ Stream(id, Unicode, bytes);
+ Entry(id, Unicode, [.. BitConverter.GetBytes(bytes.Length + 2), 0, 0, 0, 0]);
+ }
+
+ public void Bytes(ushort id, byte[] value)
+ {
+ Stream(id, Binary, value);
+ Entry(id, Binary, [.. BitConverter.GetBytes(value.Length), 0, 0, 0, 0]);
+ }
+
+ public void Fixed(ushort id, ushort type, byte[] value) => Entry(id, type, [.. value, .. new byte[8 - value.Length]]);
+
+ private void Stream(ushort id, ushort type, byte[] data)
+ {
+ using var stream = storage.CreateStream($"__substg1.0_{id:X4}{type:X4}");
+ stream.Write(data);
+ }
+
+ private void Entry(ushort id, ushort type, byte[] value)
+ {
+ _entries.Write(BitConverter.GetBytes((uint)(id << 16 | type)));
+ _entries.Write(BitConverter.GetBytes(6)); // readable, writable
+ _entries.Write(value);
+ }
+
+ public void Save(int headerSize) => Save(new byte[headerSize]);
+
+ public void Save(byte[] header)
+ {
+ using var stream = storage.CreateStream("__properties_version1.0");
+ stream.Write(header);
+ stream.Write(_entries.ToArray());
+ }
+ }
+}
diff --git a/tests/Filee.Engines.Tests/MsgTests.cs b/tests/Filee.Engines.Tests/MsgTests.cs
new file mode 100644
index 00000000..8dd63697
--- /dev/null
+++ b/tests/Filee.Engines.Tests/MsgTests.cs
@@ -0,0 +1,111 @@
+// Outlook .msg → EML / HTML / TXT / ZIP: MsgReader reads the message, which is rebuilt as MIME and goes the EML way.
+// Messages are written in the test (MsgBuilder).
+
+using System.IO.Compression;
+using System.Text;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using ImageMagick;
+using MimeKit;
+
+namespace Filee.Engines.Tests;
+
+public class MsgTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private static readonly byte[] Report = Encoding.ASCII.GetBytes("%PDF-1.4 fake report");
+
+ private string Message()
+ {
+ using var logo = new MagickImage(MagickColors.Teal, 16, 16);
+ var builder = new MsgBuilder
+ {
+ Subject = "회의 자료",
+ SenderName = "보낸이",
+ SenderEmail = "[email protected]",
+ Body = "안녕하세요. 자료를 보냅니다.\r\n둘째 줄",
+ Html = "<html><head><style>p { color: #C00000; }</style></head><body><p>안녕하세요. 자료를 보냅니다.</p>" +
+ "<img src=\"cid:logo@filee\"></body></html>",
+ MessageId = "<[email protected]>",
+ Recipients = { ("Receiver", "[email protected]", 1), ("Copy", "[email protected]", 2) },
+ Attachments =
+ {
+ ("보고서.pdf", Report, "application/pdf", null),
+ ("logo.png", logo.ToByteArray(MagickFormat.Png), "image/png", "logo@filee"),
+ },
+ AttachedMessages = { new MsgBuilder { Subject = "Earlier mail", SenderName = "Old", SenderEmail = "[email protected]", Body = "older text" } },
+ };
+ var path = Path.Combine(fx.NewFolder(), "회의.msg");
+ builder.Save(path);
+ return path;
+ }
+
+ 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();
+ }
+
+ [Fact]
+ public async Task Msg_to_eml_rebuilds_the_mime_message()
+ {
+ var eml = await ConvertAsync(Message(), "eml");
+ var mime = await MimeMessage.LoadAsync(eml, TestContext.Current.CancellationToken);
+
+ Assert.Equal("회의 자료", mime.Subject);
+ var from = mime.From.Mailboxes.Single();
+ Assert.Equal(("보낸이", "[email protected]"), (from.Name, from.Address));
+ Assert.Equal("[email protected]", mime.To.Mailboxes.Single().Address);
+ Assert.Equal("[email protected]", mime.Cc.Mailboxes.Single().Address);
+ Assert.Equal(new DateTimeOffset(2026, 10, 1, 0, 30, 0, TimeSpan.Zero), mime.Date.ToUniversalTime());
+ Assert.Equal("[email protected]", mime.MessageId);
+ Assert.Equal("안녕하세요. 자료를 보냅니다.\r\n둘째 줄", mime.TextBody.TrimEnd());
+ Assert.Contains("<img src=\"cid:logo@filee\">", mime.HtmlBody);
+
+ var attachments = mime.Attachments.ToList();
+ Assert.Equal(2, attachments.Count); // the PDF and the attached message; the logo is part of the body
+ var pdf = Assert.IsType<MimePart>(attachments[0]);
+ Assert.Equal("보고서.pdf", pdf.FileName);
+ using var data = new MemoryStream();
+ await pdf.Content.DecodeToAsync(data, TestContext.Current.CancellationToken);
+ Assert.Equal(Report, data.ToArray());
+ var attached = Assert.IsType<MessagePart>(attachments[1]);
+ Assert.Equal("Earlier mail", attached.Message.Subject);
+ Assert.Equal("older text", attached.Message.TextBody.TrimEnd());
+ Assert.Contains(mime.BodyParts.OfType<MimePart>(), p => p.ContentId == "logo@filee");
+ }
+
+ [Fact]
+ public async Task Msg_to_html_text_and_zip_directly()
+ {
+ var msg = Message();
+ var route = fx.Catalog.CreatePlanner().Plan("msg", "html")!;
+ Assert.Equal("email", Assert.Single(route.Steps).Converter.Id); // not through EML
+
+ var html = await File.ReadAllTextAsync(await ConvertAsync(msg, "html"), TestContext.Current.CancellationToken);
+ Assert.Contains("<title>회의 자료</title>", html);
+ Assert.Contains("<th>From</th><td>보낸이 &lt;[email protected]&gt;</td>", html);
+ Assert.Contains("<th>Cc</th><td>Copy &lt;[email protected]&gt;</td>", html);
+ Assert.Contains("<th>Attachments</th><td>보고서.pdf, Earlier mail.eml</td>", html);
+ Assert.Contains("src=\"data:image/png;base64,", html);
+ Assert.DoesNotContain("cid:", html);
+
+ var text = await File.ReadAllTextAsync(await ConvertAsync(msg, "txt"), TestContext.Current.CancellationToken);
+ Assert.Contains("Subject: 회의 자료\r\n", text);
+ Assert.EndsWith("\r\n\r\n안녕하세요. 자료를 보냅니다.\r\n둘째 줄\r\n", text);
+
+ using var zip = ZipFile.OpenRead(await ConvertAsync(msg, "zip"));
+ Assert.Equal(["보고서.pdf", "Earlier mail.eml"], zip.Entries.Select(e => e.FullName));
+ }
+
+ [Fact]
+ public async Task A_file_that_is_no_outlook_message_fails_clearly()
+ {
+ var path = Path.Combine(fx.NewFolder(), "broken.msg");
+ await File.WriteAllTextAsync(path, "not a compound file", TestContext.Current.CancellationToken);
+
+ var job = await fx.ConvertAsync([path], new Preset { TargetFormat = "html" });
+ Assert.Equal(JobState.Failed, job.State);
+ Assert.Contains("Not an Outlook message", job.Files.Single().ErrorDetail);
+ }
+}
diff --git a/tests/Filee.Engines.Tests/VCardTests.cs b/tests/Filee.Engines.Tests/VCardTests.cs
new file mode 100644
index 00000000..ff343b84
--- /dev/null
+++ b/tests/Filee.Engines.Tests/VCardTests.cs
@@ -0,0 +1,139 @@
+// vCard → CSV and CSV → vCard with the built-in data engine: 2.1 from old Korean phones (CP949 bytes, quoted-printable
+// with soft line breaks, bare TYPE parameters, no FN, a photo), 3.0 (folding, escapes, groups) and 4.0 (quoted TYPE
+// lists, tel: URIs). Cards are written in the test.
+
+using System.Text;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+
+namespace Filee.Engines.Tests;
+
+public class VCardTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ static VCardTests() => Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+
+ private static Encoding Cp949 => Encoding.GetEncoding(949);
+
+ /// <summary>Quoted-printable of text in a charset, every byte outside printable ASCII as =XX, soft breaks at 60.</summary>
+ private static string QuotedPrintable(string text, Encoding encoding)
+ {
+ var sb = new StringBuilder();
+ var column = 0;
+ foreach (var b in encoding.GetBytes(text))
+ {
+ var piece = b is >= 33 and <= 126 and not (byte)'=' ? ((char)b).ToString() : $"={b:X2}";
+ if (column + piece.Length > 60)
+ {
+ sb.Append("=\r\n");
+ column = 0;
+ }
+ sb.Append(piece);
+ column += piece.Length;
+ }
+ return sb.ToString();
+ }
+
+ 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 static List<string[]> Rows(string csv) =>
+ csv.TrimStart('').Split("\r\n", StringSplitOptions.RemoveEmptyEntries).Select(line => line.Split(',')).ToList();
+
+ [Fact]
+ public async Task Cards_of_every_version_become_one_csv_row_each()
+ {
+ var file = new MemoryStream();
+ void Ascii(string text) => file.Write(Encoding.ASCII.GetBytes(text));
+
+ // vCard 2.1 as Korean feature phones wrote it: CP949, partly quoted-printable, no FN.
+ Ascii("BEGIN:VCARD\r\nVERSION:2.1\r\n");
+ Ascii($"N;CHARSET=KS_C_5601-1987;ENCODING=QUOTED-PRINTABLE:{QuotedPrintable("홍", Cp949)};{QuotedPrintable("길동", Cp949)};;;\r\n");
+ Ascii("TEL;CELL:010-1234-5678\r\nTEL;WORK;VOICE:02-123-4567\r\nEMAIL;PREF;INTERNET:[email protected]\r\n");
+ Ascii($"ADR;HOME;ENCODING=QUOTED-PRINTABLE:;;{QuotedPrintable("서울특별시 종로구 세종대로 209 정부서울청사 별관 3층", Cp949)};;;03171;\r\n");
+ Ascii("NOTE:");
+ file.Write(Cp949.GetBytes("전화 주세요"));
+ Ascii("\r\nPHOTO;ENCODING=BASE64;TYPE=JPEG:\r\n /9j/4AAQSkZJRgABAQAAAQABAAD\r\n 2wBDAAgGBgcGBQgHBwcJ\r\n\r\n");
+ Ascii("AGENT:\r\nBEGIN:VCARD\r\nVERSION:2.1\r\nFN:Assistant\r\nTEL:000\r\nEND:VCARD\r\n");
+ Ascii("BDAY:19800102\r\nEND:VCARD\r\n");
+
+ // vCard 3.0 in UTF-8: folded lines, escapes, a group, structured ORG.
+ file.Write(Encoding.UTF8.GetBytes(string.Join("\r\n",
+ "BEGIN:VCARD", "VERSION:3.0", "FN:Ada Lovelace", "N:Lovelace;Ada;;;",
+ "ORG:Analytical Engines\\, Ltd.;Research", "TITLE:Engineer",
+ "item1.EMAIL;TYPE=INTERNET,WORK:[email protected]", "EMAIL;TYPE=HOME:[email protected]",
+ "TEL;TYPE=CELL,VOICE:+44 20 7946 0000",
+ "NOTE:First line\\nSecond line\\; folded over two li", " nes here",
+ "END:VCARD", "")));
+
+ // vCard 4.0: quoted TYPE list, tel: URI, birthday without a year.
+ file.Write(Encoding.UTF8.GetBytes(string.Join("\r\n",
+ "BEGIN:VCARD", "VERSION:4.0", "FN:王小明", "N:王;小明;;;",
+ "TEL;VALUE=uri;TYPE=\"cell,voice\":tel:+86-10-1234-5678", "BDAY:--0412", "END:VCARD", "")));
+
+ var path = Path.Combine(fx.NewFolder(), "contacts.vcf");
+ await File.WriteAllBytesAsync(path, file.ToArray(), TestContext.Current.CancellationToken);
+
+ var bytes = await File.ReadAllBytesAsync(await ConvertAsync(path, "csv"), TestContext.Current.CancellationToken);
+ Assert.True(bytes is [0xEF, 0xBB, 0xBF, ..], "CSV with BOM for Excel");
+ var csv = Encoding.UTF8.GetString(bytes).TrimStart('');
+
+ Assert.Equal(string.Join("\r\n",
+ "Full name,Given name,Family name,Organization,Title,Email,Phone,Address,Birthday,Note",
+ "홍길동,길동,홍,,,[email protected],010-1234-5678 (mobile); 02-123-4567 (work),\"서울특별시 종로구 세종대로 209 정부서울청사 별관 3층, 03171 (home)\",1980-01-02,전화 주세요",
+ "Ada Lovelace,Ada,Lovelace,\"Analytical Engines, Ltd., Research\",Engineer,[email protected] (work); [email protected] (home),+44 20 7946 0000 (mobile),,,\"First line\nSecond line; folded over two lines here\"",
+ "王小明,小明,王,,,,+86-10-1234-5678 (mobile),,--0412,",
+ ""), csv);
+ }
+
+ [Fact]
+ public async Task Utf16_cards_are_read()
+ {
+ var path = Path.Combine(fx.NewFolder(), "phone.vcf");
+ await File.WriteAllTextAsync(path, "BEGIN:VCARD\r\nVERSION:3.0\r\nFN:김철수\r\nTEL:010-0000-0000\r\nEND:VCARD\r\n",
+ Encoding.Unicode, TestContext.Current.CancellationToken);
+
+ var csv = await File.ReadAllTextAsync(await ConvertAsync(path, "csv"), TestContext.Current.CancellationToken);
+ Assert.Equal("김철수", Rows(csv)[1][0]);
+ }
+
+ [Fact]
+ public async Task Csv_with_korean_headers_becomes_vcard_3_and_reads_back()
+ {
+ var folder = fx.NewFolder();
+ var path = Path.Combine(folder, "주소록.csv");
+ await File.WriteAllTextAsync(path,
+ "이름,전화번호,이메일,회사,메모,관계\r\n" +
+ "홍길동,010-1111-2222 (mobile); 02-333-4444 (work),[email protected],\"필이, 주식회사\",아주 긴 메모입니다. 한 줄이 75바이트를 넘으면 vCard는 줄을 접어요. 접힌 줄은 공백으로 시작해요.,친구\r\n" +
+ ",,,,,\r\n",
+ new UTF8Encoding(true), TestContext.Current.CancellationToken);
+
+ var vcf = await ConvertAsync(path, "vcf");
+ var text = await File.ReadAllTextAsync(vcf, TestContext.Current.CancellationToken);
+ Assert.StartsWith("BEGIN:VCARD\r\nVERSION:3.0\r\nFN:홍길동\r\nN:;;;;\r\nORG:필이\\, 주식회사\r\n", text);
+ Assert.Contains("\r\nEMAIL;TYPE=INTERNET:[email protected]\r\nTEL;TYPE=CELL:010-1111-2222\r\nTEL;TYPE=WORK:02-333-4444\r\n", text);
+ Assert.Single(text.Split("BEGIN:VCARD")[1..]); // the empty row is no contact
+ foreach (var line in text.Split("\r\n"))
+ Assert.True(Encoding.UTF8.GetByteCount(line) <= 75, $"not folded: {line}");
+
+ // And back to CSV: the same values.
+ var csv = Rows(await File.ReadAllTextAsync(await ConvertAsync(vcf, "csv"), TestContext.Current.CancellationToken));
+ Assert.Equal("홍길동", csv[1][0]);
+ Assert.Contains("아주 긴 메모입니다. 한 줄이 75바이트를 넘으면 vCard는 줄을 접어요. 접힌 줄은 공백으로 시작해요.", string.Join(",", csv[1]));
+ Assert.Contains("010-1111-2222 (mobile); 02-333-4444 (work)", string.Join(",", csv[1]));
+ }
+
+ [Fact]
+ public async Task Csv_without_contact_columns_is_refused()
+ {
+ var path = Path.Combine(fx.NewFolder(), "numbers.csv");
+ await File.WriteAllTextAsync(path, "x,y\r\n1,2\r\n", TestContext.Current.CancellationToken);
+
+ var job = await fx.ConvertAsync([path], new Preset { TargetFormat = "vcf" });
+ Assert.Equal(JobState.Failed, job.State);
+ Assert.Contains("No contact columns", job.Files.Single().ErrorDetail);
+ }
+}