refactor: drop skill file, rework client #3

Merged
albnnc merged 8 commits from able-swan into main 2026-07-11 08:52:56 +00:00
15 changed files with 382 additions and 315 deletions
Showing only changes of commit 07db914ca0 - Show all commits
+38 -262
View File
@@ -1,36 +1,19 @@
import { XMLParser } from "fast-xml-parser"; import { XMLParser } from "fast-xml-parser";
import fs from "node:fs";
import https from "node:https"; import https from "node:https";
import { createRequire } from "node:module"; import { createRequire } from "node:module";
import path from "node:path";
import { promisify } from "node:util"; import { promisify } from "node:util";
import type { Email } from "./types/email.ts"; import { extractEmail, type Email } from "../utils/extract_email.ts";
import type { Folder } from "./types/folder.ts"; import { extractFolders, type Folder } from "../utils/extract_folder.ts";
import type { LoginConfig } from "./types/login_config.ts"; import {
loadConfig,
let inMemoryPassword: string | null = null; saveConfig,
let dataDir: string = "./data"; clearConfig,
setPassword,
export function initDataDir(dir: string): void { getPassword,
dataDir = path.resolve(dir); hasPassword,
fs.mkdirSync(dataDir, { recursive: true }); initDataDir,
} type LoginConfig,
} from "../utils/config.ts";
export function setPassword(password: string): void {
inMemoryPassword = password;
}
export function getPassword(): string | null {
return inMemoryPassword;
}
export function hasPassword(): boolean {
return inMemoryPassword !== null;
}
export function clearPassword(): void {
inMemoryPassword = null;
}
const ntlm: any = createRequire(import.meta.url)("httpntlm"); const ntlm: any = createRequire(import.meta.url)("httpntlm");
const postAsync = promisify(ntlm.post.bind(ntlm)); const postAsync = promisify(ntlm.post.bind(ntlm));
@@ -43,13 +26,6 @@ const AGENT = new https.Agent({
secureOptions: SSL_OP_LEGACY_SERVER_CONNECT, secureOptions: SSL_OP_LEGACY_SERVER_CONNECT,
}); });
const PARSER = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: "@_",
removeNSPrefix: true,
textNodeName: "#text",
});
const DISTINGUISHED_FOLDERS: Record<string, string> = { const DISTINGUISHED_FOLDERS: Record<string, string> = {
inbox: "inbox", inbox: "inbox",
"входящие": "inbox", "входящие": "inbox",
@@ -78,30 +54,12 @@ ${body}
</s:Envelope>`; </s:Envelope>`;
} }
function configFilePath(): string { const PARSER = new XMLParser({
return path.join(dataDir, "config.json"); ignoreAttributes: false,
} attributeNamePrefix: "@_",
removeNSPrefix: true,
export function loadConfig(): LoginConfig { textNodeName: "#text",
const filePath = configFilePath(); });
if (!fs.existsSync(filePath)) {
throw new Error("Not logged in. Use the login tool first.");
}
return JSON.parse(fs.readFileSync(filePath, "utf-8")) as LoginConfig;
}
export function saveConfig(config: LoginConfig): void {
const filePath = configFilePath();
fs.writeFileSync(filePath, JSON.stringify(config, null, 2), "utf-8");
}
export function clearConfig(): void {
const filePath = configFilePath();
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
}
clearPassword();
}
export class EwsClient { export class EwsClient {
private config: LoginConfig; private config: LoginConfig;
@@ -110,10 +68,7 @@ export class EwsClient {
constructor(config: LoginConfig, password?: string) { constructor(config: LoginConfig, password?: string) {
this.config = config; this.config = config;
this.ewsUrl = `${config.serverUrl.replace(/\/+$/, "")}/EWS/Exchange.asmx`; this.ewsUrl = `${config.serverUrl.replace(/\/+$/, "")}/EWS/Exchange.asmx`;
if (password) setPassword(password);
if (password) {
setPassword(password);
}
} }
private get domain(): string { private get domain(): string {
@@ -144,8 +99,7 @@ export class EwsClient {
throw new Error(`NTLM request failed, status=${res.statusCode}`); throw new Error(`NTLM request failed, status=${res.statusCode}`);
} }
const parsed = PARSER.parse(res.body); return PARSER.parse(res.body);
return parsed;
} }
private extractResponseMessages(data: any): any[] { private extractResponseMessages(data: any): any[] {
@@ -176,7 +130,7 @@ export class EwsClient {
async getFolderId(folderName: string): Promise<string> { async getFolderId(folderName: string): Promise<string> {
const lower = folderName.toLowerCase(); const lower = folderName.toLowerCase();
const distinguished = DISTINGUISHED_FOLDERS[lower]; const distinguished = (DISTINGUISHED_FOLDERS as Record<string, string>)[lower];
if (distinguished) { if (distinguished) {
const soap = buildSoapEnvelope(`\ const soap = buildSoapEnvelope(`\
@@ -251,7 +205,7 @@ export class EwsClient {
} = options; } = options;
const isDistinguished = const isDistinguished =
DISTINGUISHED_FOLDERS[folderId.toLowerCase()] !== undefined; (DISTINGUISHED_FOLDERS as Record<string, string>)[folderId.toLowerCase()] !== undefined;
const folderIdXml = isDistinguished const folderIdXml = isDistinguished
? `<t:DistinguishedFolderId Id="${folderId}"/>` ? `<t:DistinguishedFolderId Id="${folderId}"/>`
@@ -331,197 +285,16 @@ ${restriction}
parentFolderId: string, parentFolderId: string,
recursive: boolean = false, recursive: boolean = false,
): Promise<Folder[]> { ): Promise<Folder[]> {
const traversal = recursive ? "Deep" : "Shallow"; return extractFolders(
const isDistinguished = (body, soapAction) => this.soapRequest(body, soapAction),
DISTINGUISHED_FOLDERS[parentFolderId.toLowerCase()] !== undefined parentFolderId,
|| ["msgfolderroot"].includes(parentFolderId.toLowerCase()); recursive,
const folderIdXml = isDistinguished
? `<t:DistinguishedFolderId Id="${parentFolderId}"/>`
: `<t:FolderId Id="${parentFolderId}"/>`;
const soap = buildSoapEnvelope(`\
<m:FindFolder Traversal="${traversal}">
<m:FolderShape>
<t:BaseShape>Default</t:BaseShape>
</m:FolderShape>
<m:ParentFolderIds>
${folderIdXml}
</m:ParentFolderIds>
<m:IndexedPageFolderView MaxEntriesReturned="200" Offset="0" BasePoint="Beginning"/>
</m:FindFolder>`);
const data = await this.soapRequest(
soap,
"http://schemas.microsoft.com/exchange/services/2006/messages/FindFolder",
); );
const folders: Folder[] = [];
for (const msg of this.extractResponseMessages(data)) {
const folderList = msg?.RootFolder?.Folders?.Folder;
if (!folderList) continue;
const list = Array.isArray(folderList) ? folderList : [folderList];
for (const f of list) {
folders.push({
name: f.DisplayName ?? "Unknown",
id: f.FolderId?.["@_Id"] ?? "",
totalCount: f.TotalCount ?? 0,
unreadCount: f.UnreadCount ?? 0,
childFolderCount: f.ChildFolderCount ?? 0,
});
}
}
return folders;
} }
extractEmail(item: any): Email { extractEmail(item: any): Email {
const itemType = item["@_xsi_type"] ?? item.__type ?? ""; return extractEmail(item);
const isMeeting =
/MeetingRequest|MeetingResponse|MeetingCancellation|CalendarItem/i.test(
itemType,
);
const fromMailbox = item.From?.Mailbox
?? item.Organizer?.Mailbox
?? item.Sender?.Mailbox
?? {};
const email: Email = {
subject: item.Subject ?? "(No subject)",
from: fromMailbox.EmailAddress ?? "",
fromName: fromMailbox.Name ?? "",
date: item.DateTimeSent ?? item.DateTimeReceived ?? item.DateTimeCreated
?? "",
isRead: item.IsRead === "true" || item.IsRead === true,
hasAttachments: item.HasAttachments === "true"
|| item.HasAttachments === true,
hasLinks: false,
itemId: item.ItemId?.["@_Id"] ?? "",
size: item.Size ? Number(item.Size) : 0,
isMeeting,
itemType: itemType || "Message",
to: [],
cc: [],
body: "",
bodyType: "Text",
attachments: [],
preview: item.Preview ?? "",
};
if (item.DisplayTo) {
email.to = item.DisplayTo.split(";").map((t: string) => t.trim()).filter(
Boolean,
);
} }
if (item.DisplayCc) {
email.cc = item.DisplayCc.split(";").map((c: string) => c.trim()).filter(
Boolean,
);
}
if (isMeeting) {
email.location = item.Location ?? "";
email.start = item.Start ?? item.StartWallClock ?? item.ReminderDueBy
?? "";
email.end = item.End ?? item.EndWallClock ?? "";
}
const bodyVal = item.Body?.Value ?? item.Body?.["#text"] ?? "";
const bodyType = item.Body?.["@_BodyType"] ?? item.Body?.BodyType ?? "Text";
if (bodyType === "HTML") {
email.hasLinks = /<a\s/i.test(bodyVal);
email.body = this.htmlToText(bodyVal);
} else {
email.body = bodyVal;
}
email.bodyType = bodyType;
const toRecipients = item.ToRecipients?.Mailbox ?? [];
email.to = (Array.isArray(toRecipients) ? toRecipients : [toRecipients])
.map((r: any) => {
const name = r.Name ?? "";
const addr = r.EmailAddress ?? "";
return name && addr ? `${name} <${addr}>` : addr;
})
.filter(Boolean);
const ccRecipients = item.CcRecipients?.Mailbox ?? [];
email.cc = (Array.isArray(ccRecipients) ? ccRecipients : [ccRecipients])
.map((r: any) => {
const name = r.Name ?? "";
const addr = r.EmailAddress ?? "";
return name && addr ? `${name} <${addr}>` : addr;
})
.filter(Boolean);
const attachments = item.Attachments?.FileAttachment ?? [];
const attList = Array.isArray(attachments) ? attachments : [attachments];
email.attachments = attList
.filter((a: any) => a)
.map((a: any) => ({
name: a.Name ?? "",
size: a.Size ? Number(a.Size) : 0,
contentType: a.ContentType ?? "",
attachmentId: a.AttachmentId?.["@_Id"] ?? "",
isInline: a.IsInline === "true" || a.IsInline === true,
}));
if (isMeeting) {
email.location = item.Location ?? item.EnhancedLocation?.DisplayName
?? "";
email.start = item.Start ?? "";
email.end = item.End ?? "";
const reqAtt = item.RequiredAttendees?.Attendee ?? [];
email.requiredAttendees = (Array.isArray(reqAtt) ? reqAtt : [reqAtt])
.map((a: any) => {
const mb = a.Mailbox ?? {};
const name = mb.Name ?? "";
const addr = mb.EmailAddress ?? "";
return name && addr ? `${name} <${addr}>` : addr;
})
.filter(Boolean);
const optAtt = item.OptionalAttendees?.Attendee ?? [];
email.optionalAttendees = (Array.isArray(optAtt) ? optAtt : [optAtt])
.map((a: any) => {
const mb = a.Mailbox ?? {};
const name = mb.Name ?? "";
const addr = mb.EmailAddress ?? "";
return name && addr ? `${name} <${addr}>` : addr;
})
.filter(Boolean);
}
return email;
}
private htmlToText(html: string): string {
if (!html) return "";
let text = html.replace(/<script[^>]*>.*?<\/script>/gis, "");
text = text.replace(/<style[^>]*>.*?<\/style>/gis, "");
text = text.replace(/<br\s*\/?>/gi, "\n");
text = text.replace(/<p[^>]*>/gi, "\n");
text = text.replace(/<\/p>/gi, "");
text = text.replace(/<div[^>]*>/gi, "\n");
text = text.replace(/<\/div>/gi, "");
text = text.replace(/<[^>]+>/g, "");
text = text.replace(/&nbsp;/g, " ");
text = text.replace(/&amp;/g, "&");
text = text.replace(/&lt;/g, "<");
text = text.replace(/&gt;/g, ">");
text = text.replace(/&quot;/g, "\"");
text = text.replace(/&#39;/g, "'");
text = text.replace(/\n\s*\n/g, "\n\n");
text = text.replace(/[ \t]+/g, " ");
return text.trim();
}
// ── UpdateItem (for marking read/unread, etc.) ──────────────────────────
async updateItems( async updateItems(
itemIds: string[], itemIds: string[],
@@ -572,8 +345,6 @@ ${changesXml}
return this.extractResponseMessages(data); return this.extractResponseMessages(data);
} }
// ── GetAttachment ───────────────────────────────────────────────────────
async getAttachment( async getAttachment(
attachmentId: string, attachmentId: string,
): Promise<{ content: Buffer; name: string; contentType: string }> { ): Promise<{ content: Buffer; name: string; contentType: string }> {
@@ -607,8 +378,6 @@ ${changesXml}
throw new Error(`Attachment '${attachmentId}' not found`); throw new Error(`Attachment '${attachmentId}' not found`);
} }
// ── FindItem with CalendarView ──────────────────────────────────────────
async findCalendarItems( async findCalendarItems(
folderId: string, folderId: string,
startDate: string, startDate: string,
@@ -640,8 +409,6 @@ ${changesXml}
return []; return [];
} }
// ── GetUserAvailability ─────────────────────────────────────────────────
async getUserAvailability( async getUserAvailability(
emails: string[], emails: string[],
startDate: string, startDate: string,
@@ -689,8 +456,6 @@ ${mailboxDataXml}
return data; return data;
} }
// ── ResolveNames (directory search) ─────────────────────────────────────
async resolveNames( async resolveNames(
query: string, query: string,
fullContact: boolean = true, fullContact: boolean = true,
@@ -717,3 +482,14 @@ ${mailboxDataXml}
return []; return [];
} }
} }
// Re-export for backward compatibility
export {
initDataDir,
loadConfig,
saveConfig,
clearConfig,
setPassword,
getPassword,
hasPassword,
} from "../utils/config.ts";
+1 -1
View File
@@ -4,7 +4,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
import { Command } from "commander"; import { Command } from "commander";
import crypto from "node:crypto"; import crypto from "node:crypto";
import http from "node:http"; import http from "node:http";
import { initDataDir } from "./ews_client.ts"; import { initDataDir } from "./client/ews_client.ts";
import { registerAuthTools } from "./tools/auth.ts"; import { registerAuthTools } from "./tools/auth.ts";
import { registerAvailabilityTools } from "./tools/availability.ts"; import { registerAvailabilityTools } from "./tools/availability.ts";
import { registerCalendarTools } from "./tools/calendar.ts"; import { registerCalendarTools } from "./tools/calendar.ts";
+2 -2
View File
@@ -7,8 +7,8 @@ import {
loadConfig, loadConfig,
saveConfig, saveConfig,
setPassword, setPassword,
} from "../ews_client.ts"; } from "../client/ews_client.ts";
import type { LoginConfig } from "../types/login_config.ts"; import { type LoginConfig } from "../utils/config.ts";
export function registerAuthTools(server: McpServer): void { export function registerAuthTools(server: McpServer): void {
server.registerTool( server.registerTool(
+1 -1
View File
@@ -1,6 +1,6 @@
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod/v4"; import { z } from "zod/v4";
import { EwsClient, loadConfig } from "../ews_client.ts"; import { EwsClient, loadConfig } from "../client/ews_client.ts";
export function registerAvailabilityTools(server: McpServer): void { export function registerAvailabilityTools(server: McpServer): void {
server.registerTool( server.registerTool(
+1 -1
View File
@@ -2,7 +2,7 @@ import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import fs from "node:fs"; import fs from "node:fs";
import path from "node:path"; import path from "node:path";
import { z } from "zod/v4"; import { z } from "zod/v4";
import { EwsClient, loadConfig } from "../ews_client.ts"; import { EwsClient, loadConfig } from "../client/ews_client.ts";
export function registerCalendarTools(server: McpServer): void { export function registerCalendarTools(server: McpServer): void {
server.registerTool( server.registerTool(
+1 -1
View File
@@ -2,7 +2,7 @@ import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import fs from "node:fs"; import fs from "node:fs";
import path from "node:path"; import path from "node:path";
import { z } from "zod/v4"; import { z } from "zod/v4";
import { EwsClient, loadConfig } from "../ews_client.ts"; import { EwsClient, loadConfig } from "../client/ews_client.ts";
function getClient(): EwsClient { function getClient(): EwsClient {
return new EwsClient(loadConfig()); return new EwsClient(loadConfig());
+1 -1
View File
@@ -1,6 +1,6 @@
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod/v4"; import { z } from "zod/v4";
import { EwsClient, loadConfig } from "../ews_client.ts"; import { EwsClient, loadConfig } from "../client/ews_client.ts";
export function registerFolderTools(server: McpServer): void { export function registerFolderTools(server: McpServer): void {
server.registerTool( server.registerTool(
+1 -1
View File
@@ -1,6 +1,6 @@
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod/v4"; import { z } from "zod/v4";
import { EwsClient, loadConfig } from "../ews_client.ts"; import { EwsClient, loadConfig } from "../client/ews_client.ts";
export function registerPeopleTools(server: McpServer): void { export function registerPeopleTools(server: McpServer): void {
server.registerTool( server.registerTool(
-32
View File
@@ -1,32 +0,0 @@
export interface Email {
subject: string;
from: string;
fromName: string;
date: string;
isRead: boolean;
hasAttachments: boolean;
hasLinks: boolean;
itemId: string;
size: number;
isMeeting: boolean;
itemType: string;
to: string[];
cc: string[];
body: string;
bodyType: string;
attachments: Attachment[];
preview: string;
location?: string;
start?: string;
end?: string;
requiredAttendees?: string[];
optionalAttendees?: string[];
}
export interface Attachment {
name: string;
size: number;
contentType: string;
attachmentId: string;
isInline: boolean;
}
-7
View File
@@ -1,7 +0,0 @@
export interface Folder {
name: string;
id: string;
totalCount: number;
unreadCount: number;
childFolderCount: number;
}
-6
View File
@@ -1,6 +0,0 @@
export interface LoginConfig {
serverUrl: string;
email: string;
username: string;
domain?: string;
}
+59
View File
@@ -0,0 +1,59 @@
export interface LoginConfig {
serverUrl: string;
email: string;
username: string;
domain?: string;
}
import fs from "node:fs";
import path from "node:path";
let dataDir: string = "./data";
export function initDataDir(dir: string): void {
dataDir = path.resolve(dir);
fs.mkdirSync(dataDir, { recursive: true });
}
let inMemoryPassword: string | null = null;
export function setPassword(password: string): void {
inMemoryPassword = password;
}
export function getPassword(): string | null {
return inMemoryPassword;
}
export function hasPassword(): boolean {
return inMemoryPassword !== null;
}
export function clearPassword(): void {
inMemoryPassword = null;
}
function configFilePath(): string {
return path.join(dataDir, "config.json");
}
export function loadConfig(): LoginConfig {
const filePath = configFilePath();
if (!fs.existsSync(filePath)) {
throw new Error("Not logged in. Use the login tool first.");
}
return JSON.parse(fs.readFileSync(filePath, "utf-8")) as LoginConfig;
}
export function saveConfig(config: LoginConfig): void {
const filePath = configFilePath();
fs.writeFileSync(filePath, JSON.stringify(config, null, 2), "utf-8");
}
export function clearConfig(): void {
const filePath = configFilePath();
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
}
clearPassword();
}
+156
View File
@@ -0,0 +1,156 @@
import { htmlToText } from "./html_to_text.ts";
export interface Attachment {
name: string;
size: number;
contentType: string;
attachmentId: string;
isInline: boolean;
}
export interface Email {
subject: string;
from: string;
fromName: string;
date: string;
isRead: boolean;
hasAttachments: boolean;
hasLinks: boolean;
itemId: string;
size: number;
isMeeting: boolean;
itemType: string;
to: string[];
cc: string[];
body: string;
bodyType: string;
attachments: Attachment[];
preview: string;
location?: string;
start?: string;
end?: string;
requiredAttendees?: string[];
optionalAttendees?: string[];
}
export function extractEmail(item: any): Email {
const itemType = item["@_xsi_type"] ?? item.__type ?? "";
const isMeeting =
/MeetingRequest|MeetingResponse|MeetingCancellation|CalendarItem/i.test(
itemType,
);
const fromMailbox = item.From?.Mailbox
?? item.Organizer?.Mailbox
?? item.Sender?.Mailbox
?? {};
const email: Email = {
subject: item.Subject ?? "(No subject)",
from: fromMailbox.EmailAddress ?? "",
fromName: fromMailbox.Name ?? "",
date: item.DateTimeSent ?? item.DateTimeReceived ?? item.DateTimeCreated
?? "",
isRead: item.IsRead === "true" || item.IsRead === true,
hasAttachments: item.HasAttachments === "true"
|| item.HasAttachments === true,
hasLinks: false,
itemId: item.ItemId?.["@_Id"] ?? "",
size: item.Size ? Number(item.Size) : 0,
isMeeting,
itemType: itemType || "Message",
to: [],
cc: [],
body: "",
bodyType: "Text",
attachments: [],
preview: item.Preview ?? "",
};
if (item.DisplayTo) {
email.to = item.DisplayTo.split(";").map((t: string) => t.trim()).filter(
Boolean,
);
}
if (item.DisplayCc) {
email.cc = item.DisplayCc.split(";").map((c: string) => c.trim()).filter(
Boolean,
);
}
if (isMeeting) {
email.location = item.Location ?? "";
email.start = item.Start ?? item.StartWallClock ?? item.ReminderDueBy
?? "";
email.end = item.End ?? item.EndWallClock ?? "";
}
const bodyVal = item.Body?.Value ?? item.Body?.["#text"] ?? "";
const bodyType = item.Body?.["@_BodyType"] ?? item.Body?.BodyType ?? "Text";
if (bodyType === "HTML") {
email.hasLinks = /<a\s/i.test(bodyVal);
email.body = htmlToText(bodyVal);
} else {
email.body = bodyVal;
}
email.bodyType = bodyType;
const toRecipients = item.ToRecipients?.Mailbox ?? [];
email.to = (Array.isArray(toRecipients) ? toRecipients : [toRecipients])
.map((r: any) => {
const name = r.Name ?? "";
const addr = r.EmailAddress ?? "";
return name && addr ? `${name} <${addr}>` : addr;
})
.filter(Boolean);
const ccRecipients = item.CcRecipients?.Mailbox ?? [];
email.cc = (Array.isArray(ccRecipients) ? ccRecipients : [ccRecipients])
.map((r: any) => {
const name = r.Name ?? "";
const addr = r.EmailAddress ?? "";
return name && addr ? `${name} <${addr}>` : addr;
})
.filter(Boolean);
const attachments = item.Attachments?.FileAttachment ?? [];
const attList = Array.isArray(attachments) ? attachments : [attachments];
email.attachments = attList
.filter((a: any) => a)
.map((a: any) => ({
name: a.Name ?? "",
size: a.Size ? Number(a.Size) : 0,
contentType: a.ContentType ?? "",
attachmentId: a.AttachmentId?.["@_Id"] ?? "",
isInline: a.IsInline === "true" || a.IsInline === true,
}));
if (isMeeting) {
email.location = item.Location ?? item.EnhancedLocation?.DisplayName ?? "";
email.start = item.Start ?? "";
email.end = item.End ?? "";
const reqAtt = item.RequiredAttendees?.Attendee ?? [];
email.requiredAttendees = (Array.isArray(reqAtt) ? reqAtt : [reqAtt])
.map((a: any) => {
const mb = a.Mailbox ?? {};
const name = mb.Name ?? "";
const addr = mb.EmailAddress ?? "";
return name && addr ? `${name} <${addr}>` : addr;
})
.filter(Boolean);
const optAtt = item.OptionalAttendees?.Attendee ?? [];
email.optionalAttendees = (Array.isArray(optAtt) ? optAtt : [optAtt])
.map((a: any) => {
const mb = a.Mailbox ?? {};
const name = mb.Name ?? "";
const addr = mb.EmailAddress ?? "";
return name && addr ? `${name} <${addr}>` : addr;
})
.filter(Boolean);
}
return email;
}
+101
View File
@@ -0,0 +1,101 @@
export interface Folder {
name: string;
id: string;
totalCount: number;
unreadCount: number;
childFolderCount: number;
}
type SoapRequest = (body: string, soapAction: string) => Promise<any>;
export async function extractFolders(
soapRequest: SoapRequest,
parentFolderId: string,
recursive: boolean = false,
): Promise<Folder[]> {
const DISTINGUISHED_FOLDERS: Record<string, string> = {
inbox: "inbox",
"входящие": "inbox",
sent: "sentitems",
"отправленные": "sentitems",
drafts: "drafts",
"черновики": "drafts",
deleted: "deleteditems",
"удаленные": "deleteditems",
junk: "junkemail",
"нежелательная почта": "junkemail",
outbox: "outbox",
"исходящие": "outbox",
calendar: "calendar",
"календарь": "calendar",
};
function buildSoapEnvelope(body: string): string {
return `<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
<s:Body>
${body}
</s:Body>
</s:Envelope>`;
}
function extractResponseMessages(data: any): any[] {
const body = data?.Envelope?.Body;
if (!body) return [];
const firstKey = Object.keys(body).find((k) => k.endsWith("Response"));
if (!firstKey) return [];
const rm = body[firstKey]?.ResponseMessages;
if (!rm) return [];
const msgKey = Object.keys(rm).find((k) => k.endsWith("ResponseMessage"));
if (!msgKey) return [];
const msgs = rm[msgKey];
return Array.isArray(msgs) ? msgs : [msgs];
}
const traversal = recursive ? "Deep" : "Shallow";
const isDistinguished =
DISTINGUISHED_FOLDERS[parentFolderId.toLowerCase()] !== undefined
|| ["msgfolderroot"].includes(parentFolderId.toLowerCase());
const folderIdXml = isDistinguished
? `<t:DistinguishedFolderId Id="${parentFolderId}"/>`
: `<t:FolderId Id="${parentFolderId}"/>`;
const soap = buildSoapEnvelope(`\
<m:FindFolder Traversal="${traversal}">
<m:FolderShape>
<t:BaseShape>Default</t:BaseShape>
</m:FolderShape>
<m:ParentFolderIds>
${folderIdXml}
</m:ParentFolderIds>
<m:IndexedPageFolderView MaxEntriesReturned="200" Offset="0" BasePoint="Beginning"/>
</m:FindFolder>`);
const data = await soapRequest(
soap,
"http://schemas.microsoft.com/exchange/services/2006/messages/FindFolder",
);
const folders: Folder[] = [];
for (const msg of extractResponseMessages(data)) {
const folderList = msg?.RootFolder?.Folders?.Folder;
if (!folderList) continue;
const list = Array.isArray(folderList) ? folderList : [folderList];
for (const f of list) {
folders.push({
name: f.DisplayName ?? "Unknown",
id: f.FolderId?.["@_Id"] ?? "",
totalCount: f.TotalCount ?? 0,
unreadCount: f.UnreadCount ?? 0,
childFolderCount: f.ChildFolderCount ?? 0,
});
}
}
return folders;
}
+20
View File
@@ -0,0 +1,20 @@
export function htmlToText(html: string): string {
if (!html) return "";
let text = html.replace(/<script[^>]*>.*?<\/script>/gis, "");
text = text.replace(/<style[^>]*>.*?<\/style>/gis, "");
text = text.replace(/<br\s*\/?>/gi, "\n");
text = text.replace(/<p[^>]*>/gi, "\n");
text = text.replace(/<\/p>/gi, "");
text = text.replace(/<div[^>]*>/gi, "\n");
text = text.replace(/<\/div>/gi, "");
text = text.replace(/<[^>]+>/g, "");
text = text.replace(/&nbsp;/g, " ");
text = text.replace(/&amp;/g, "&");
text = text.replace(/&lt;/g, "<");
text = text.replace(/&gt;/g, ">");
text = text.replace(/&quot;/g, "\"");
text = text.replace(/&#39;/g, "'");
text = text.replace(/\n\s*\n/g, "\n\n");
text = text.replace(/[ \t]+/g, " ");
return text.trim();
}