aboutsummaryrefslogtreecommitdiff
path: root/src/background.ts
blob: 997dd68dea6c86aedfe69254ee4ce8af4e40fa4a (plain)
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
type Identity = {
  id?: string;
  email?: string;
  name?: string;
};

type ComposeContext = {
  account: Identity;
  compose: {
    subject?: string;
    to?: string[];
    cc?: string[];
    bcc?: string[];
    bodyPlain?: string;
    bodyHTML?: string;
    identityId?: string;
  };
};

async function getComposeContext(): Promise<ComposeContext> {
  const data: ComposeContext = { account: {}, compose: {} };

  try {
    const tabs = await browser.tabs.query({ active: true, currentWindow: true });
    const tabId = tabs[0]?.id;
    if (!tabId) return data;

    const details: any = await (browser as any).compose.getComposeDetails(tabId);

    data.compose.subject = details?.subject ?? "";
    data.compose.to = details?.to ?? [];
    data.compose.cc = details?.cc ?? [];
    data.compose.bcc = details?.bcc ?? [];
    data.compose.identityId = details?.identityId ?? undefined;
    data.compose.bodyPlain = details?.plainTextBody ?? "";
    data.compose.bodyHTML = details?.body ?? "";

    const accounts: any[] = (browser as any).accounts?.list
      ? await (browser as any).accounts.list()
      : [];

    if (data.compose.identityId) {
      for (const acc of accounts) {
        for (const ident of acc.identities) {
          if (ident.id === data.compose.identityId) {
            data.account = {
              id: ident.id,
              email: ident.email,
              name: ident.name,
            };
          }
        }
      }
    }
  } catch (err) {
    console.warn("getComposeContext failed:", err);
  }

  return data;
}

// Handle requests from popup/options
browser.runtime.onMessage.addListener(async (message: any) => {
  if (message?.type === "getComposeContext") {
    return await getComposeContext();
  }
  return { error: "unknown message" };
});