File size: 6,544 Bytes
9646e24 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 | import { AppConfig, EmailMessage, EmailAttachment } from "@/types";
interface GraphTokenResponse {
access_token: string;
token_type: string;
expires_in: number;
}
let cachedToken: { token: string; expiresAt: number } | null = null;
export async function getAccessToken(config: AppConfig, userToken?: string): Promise<string> {
if (userToken) {
return userToken;
}
if (cachedToken && Date.now() < cachedToken.expiresAt) {
return cachedToken.token;
}
const url = `https://login.microsoftonline.com/${config.graph.tenantId}/oauth2/v2.0/token`;
const params = new URLSearchParams({
client_id: config.graph.clientId,
client_secret: config.graph.clientSecret,
scope: "https://graph.microsoft.com/.default",
grant_type: "client_credentials",
});
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 15000);
let response: Response;
try {
response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: params.toString(),
signal: controller.signal,
});
} finally {
clearTimeout(timeout);
}
if (!response.ok) {
const error = await response.text();
throw new Error(`Failed to get access token: ${error}`);
}
const data: GraphTokenResponse = await response.json().catch(() => ({}));
cachedToken = {
token: data.access_token,
expiresAt: Date.now() + (data.expires_in - 300) * 1000,
};
return data.access_token;
}
async function graphRequest(
token: string,
endpoint: string,
method: string = "GET",
body?: unknown
): Promise<any> {
const url = endpoint.startsWith("http")
? endpoint
: `https://graph.microsoft.com/v1.0${endpoint}`;
const options: RequestInit = {
method,
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
};
if (body) {
options.body = JSON.stringify(body);
}
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 30000);
let response: Response;
try {
response = await fetch(url, { ...options, signal: controller.signal });
} finally {
clearTimeout(timeout);
}
if (!response.ok) {
const error = await response.text();
throw new Error(`Graph API error (${response.status}): ${error}`);
}
if (response.status === 204) {
return null;
}
const text = await response.text();
return text ? JSON.parse(text) : null;
}
export async function fetchEmails(
config: AppConfig,
maxEmails: number = 50,
folderId: string = "inbox",
userToken?: string
): Promise<EmailMessage[]> {
const token = await getAccessToken(config, userToken);
const mailbox = config.graph.mailbox;
const endpoint = `/users/${mailbox}/mailFolders/${folderId}/messages?$top=${maxEmails}&$select=id,subject,from,receivedDateTime,bodyPreview,hasAttachments,isRead,importance,categories,body&$orderby=receivedDateTime desc`;
const data = await graphRequest(token, endpoint);
if (!data.value || data.value.length === 0) {
return [];
}
return data.value.map((msg: any): EmailMessage => ({
id: msg.id,
subject: msg.subject || "(No Subject)",
sender: msg.from?.emailAddress?.name || "Unknown",
senderEmail: msg.from?.emailAddress?.address || "unknown@example.com",
receivedDate: msg.receivedDateTime,
bodyPreview: msg.bodyPreview || "",
body: msg.body?.content || "",
hasAttachments: msg.hasAttachments || false,
attachments: [],
isRead: msg.isRead || false,
importance: msg.importance || "normal",
categories: msg.categories || [],
processed: false,
}));
}
export async function fetchAttachments(
config: AppConfig,
emailId: string,
userToken?: string
): Promise<EmailAttachment[]> {
const token = await getAccessToken(config, userToken);
const mailbox = config.graph.mailbox;
const endpoint = `/users/${mailbox}/messages/${emailId}/attachments`;
const data = await graphRequest(token, endpoint);
if (!data.value || data.value.length === 0) {
return [];
}
return data.value.map((att: any): EmailAttachment => ({
id: att.id,
name: att.name || "unknown",
contentType: att.contentType || "application/octet-stream",
size: att.size || 0,
content: att.contentBytes
? new Uint8Array(
atob(att.contentBytes)
.split("")
.map((c) => c.charCodeAt(0))
)
: undefined,
}));
}
export async function markEmailAsRead(
config: AppConfig,
emailId: string,
userToken?: string
): Promise<void> {
const token = await getAccessToken(config, userToken);
const mailbox = config.graph.mailbox;
await graphRequest(token, `/users/${mailbox}/messages/${emailId}`, "PATCH", {
isRead: true,
});
}
export async function getEmail(
config: AppConfig,
emailId: string,
userToken?: string
): Promise<EmailMessage> {
const token = await getAccessToken(config, userToken);
const mailbox = config.graph.mailbox;
const endpoint = `/users/${mailbox}/messages/${emailId}?$select=id,subject,from,receivedDateTime,bodyPreview,hasAttachments,isRead,importance,categories,body`;
const msg = await graphRequest(token, endpoint);
return {
id: msg.id,
subject: msg.subject || "(No Subject)",
sender: msg.from?.emailAddress?.name || "Unknown",
senderEmail: msg.from?.emailAddress?.address || "unknown@example.com",
receivedDate: msg.receivedDateTime,
bodyPreview: msg.bodyPreview || "",
body: msg.body?.content || "",
hasAttachments: msg.hasAttachments || false,
attachments: [],
isRead: msg.isRead || false,
importance: msg.importance || "normal",
categories: msg.categories || [],
processed: false,
};
}
export async function listFolders(
config: AppConfig,
userToken?: string
): Promise<{ id: string; name: string }[]> {
const token = await getAccessToken(config, userToken);
const mailbox = config.graph.mailbox;
const data = await graphRequest(
token,
`/users/${mailbox}/mailFolders?$select=id,displayName`
);
return (data.value || []).map((f: any) => ({
id: f.id,
name: f.displayName,
}));
}
export function validateConfig(config: AppConfig): string[] {
const errors: string[] = [];
if (!config.graph.clientId) errors.push("Graph client ID is required");
if (!config.graph.tenantId) errors.push("Graph tenant ID is required");
if (!config.llm.apiKey) errors.push("LLM API key is required");
return errors;
}
|