File size: 6,014 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
import { google } from "googleapis";
import { GmailConfig, EmailMessage, EmailAttachment } from "@/types";

export function createGmailClient(config: GmailConfig) {
  try {
    const oauth2Client = new google.auth.OAuth2(
      config.clientId,
      config.clientSecret,
      config.redirectUri
    );

    if (config.refreshToken) {
      oauth2Client.setCredentials({
        refresh_token: config.refreshToken,
      });
    }

    const gmail = google.gmail({ version: "v1", auth: oauth2Client });

    return { gmail, oauth2Client };
  } catch (e) {
    console.error("[gmail/client] createGmailClient:", e);
    throw new Error(`Failed to create Gmail client: ${e instanceof Error ? e.message : String(e)}`);
  }
}

export function getAuthUrl(config: GmailConfig): string {
  try {
    const oauth2Client = new google.auth.OAuth2(
      config.clientId,
      config.clientSecret,
      config.redirectUri
    );

    return oauth2Client.generateAuthUrl({
      access_type: "offline",
      scope: [
        "https://www.googleapis.com/auth/gmail.readonly",
        "https://www.googleapis.com/auth/gmail.modify",
      ],
      prompt: "consent",
    });
  } catch (e) {
    console.error("[gmail/client] getAuthUrl:", e);
    throw new Error(`Failed to generate auth URL: ${e instanceof Error ? e.message : String(e)}`);
  }
}

export async function exchangeCodeForTokens(
  config: GmailConfig,
  code: string
): Promise<{ refreshToken: string; accessToken: string }> {
  try {
    const oauth2Client = new google.auth.OAuth2(
      config.clientId,
      config.clientSecret,
      config.redirectUri
    );

    const { tokens } = await oauth2Client.getToken(code);
    return {
      refreshToken: tokens.refresh_token || "",
      accessToken: tokens.access_token || "",
    };
  } catch (e) {
    console.error("[gmail/client] exchangeCodeForTokens:", e);
    throw new Error(`Failed to exchange code for tokens: ${e instanceof Error ? e.message : String(e)}`);
  }
}

export async function fetchEmails(
  config: GmailConfig,
  maxResults: number = 100
): Promise<EmailMessage[]> {
  try {
    const { gmail } = createGmailClient(config);

    const listRes = await gmail.users.messages.list({
      userId: "me",
      maxResults,
      q: "has:attachment",
    });

    const messageIds = listRes.data.messages || [];
    const emails: EmailMessage[] = [];

    for (const msg of messageIds) {
      if (!msg.id) continue;
      const email = await fetchEmail(config, msg.id);
      if (email) emails.push(email);
    }

    return emails;
  } catch (e) {
    console.error("[gmail/client] fetchEmails:", e);
    throw new Error(`Failed to fetch emails: ${e instanceof Error ? e.message : String(e)}`);
  }
}

export async function fetchEmail(
  config: GmailConfig,
  messageId: string
): Promise<EmailMessage | null> {
  try {
    const { gmail } = createGmailClient(config);

    const res = await gmail.users.messages.get({
      userId: "me",
      id: messageId,
    });

    const msg = res.data;
    if (!msg) return null;

    const headers = msg.payload?.headers || [];
    const subject = headers.find((h) => h.name === "Subject")?.value || "";
    const from = headers.find((h) => h.name === "From")?.value || "";
    const date = headers.find((h) => h.name === "Date")?.value || "";

    const senderMatch = from.match(/^(.*?)\s*<(.*)>$/);
    const sender = senderMatch ? senderMatch[1].trim().replace(/"/g, "") : from;
    const senderEmail = senderMatch ? senderMatch[2] : from;

    const body = extractBody(msg.payload);
    const attachments = extractAttachments(msg.payload);

    return {
      id: messageId,
      subject,
      sender,
      senderEmail,
      receivedDate: date,
      bodyPreview: body.substring(0, 200),
      body,
      hasAttachments: attachments.length > 0,
      attachments,
      isRead: !msg.labelIds?.includes("UNREAD"),
      importance: "normal",
      categories: msg.labelIds || [],
      processed: false,
    };
  } catch (e) {
    console.error("[gmail/client] fetchEmail:", e);
    throw new Error(`Failed to fetch email ${messageId}: ${e instanceof Error ? e.message : String(e)}`);
  }
}

function extractBody(payload: any): string {
  if (!payload) return "";

  if (payload.body?.data) {
    return Buffer.from(payload.body.data, "base64").toString("utf-8");
  }

  if (payload.parts) {
    for (const part of payload.parts) {
      if (part.mimeType === "text/plain" && part.body?.data) {
        return Buffer.from(part.body.data, "base64").toString("utf-8");
      }
    }
    for (const part of payload.parts) {
      if (part.mimeType === "text/html" && part.body?.data) {
        return Buffer.from(part.body.data, "base64").toString("utf-8");
      }
    }
  }

  return "";
}

function extractAttachments(payload: any): EmailAttachment[] {
  const attachments: EmailAttachment[] = [];

  function walk(parts: any[]) {
    for (const part of parts) {
      if (part.filename && part.body?.attachmentId) {
        attachments.push({
          id: part.body.attachmentId,
          name: part.filename,
          contentType: part.mimeType || "application/octet-stream",
          size: part.body.size || 0,
        });
      }
      if (part.parts) {
        walk(part.parts);
      }
    }
  }

  if (payload?.parts) {
    walk(payload.parts);
  }

  return attachments;
}

export async function fetchAttachmentContent(
  config: GmailConfig,
  messageId: string,
  attachmentId: string
): Promise<Uint8Array> {
  try {
    const { gmail } = createGmailClient(config);

    const res = await gmail.users.messages.attachments.get({
      userId: "me",
      messageId,
      id: attachmentId,
    });

    const data = res.data.data || "";
    const buffer = Buffer.from(data, "base64");
    return new Uint8Array(buffer);
  } catch (e) {
    console.error("[gmail/client] fetchAttachmentContent:", e);
    throw new Error(`Failed to fetch attachment ${attachmentId}: ${e instanceof Error ? e.message : String(e)}`);
  }
}