summaryrefslogtreecommitdiffstats
path: root/comm/mail/components/extensions/parent/ext-accounts.js
blob: 2388f896c7b04169a332fd6d809c4ddb628dc78e (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
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

ChromeUtils.defineModuleGetter(
  this,
  "MailServices",
  "resource:///modules/MailServices.jsm"
);

/**
 * @implements {nsIObserver}
 * @implements {nsIMsgFolderListener}
 */
var accountsTracker = new (class extends EventEmitter {
  constructor() {
    super();
    this.listenerCount = 0;
    this.monitoredAccounts = new Map();

    // Keep track of accounts data monitored for changes.
    for (let nativeAccount of MailServices.accounts.accounts) {
      this.monitoredAccounts.set(
        nativeAccount.key,
        this.getMonitoredProperties(nativeAccount)
      );
    }
  }

  getMonitoredProperties(nativeAccount) {
    return {
      name: nativeAccount.incomingServer.prettyName,
      defaultIdentityKey: nativeAccount.defaultIdentity?.key,
    };
  }

  getChangedMonitoredProperty(nativeAccount, propertyName) {
    if (!nativeAccount || !this.monitoredAccounts.has(nativeAccount.key)) {
      return false;
    }
    let values = this.monitoredAccounts.get(nativeAccount.key);
    let propertyValue =
      this.getMonitoredProperties(nativeAccount)[propertyName];
    if (propertyValue && values[propertyName] != propertyValue) {
      values[propertyName] = propertyValue;
      this.monitoredAccounts.set(nativeAccount.key, values);
      return propertyValue;
    }
    return false;
  }

  incrementListeners() {
    this.listenerCount++;
    if (this.listenerCount == 1) {
      // nsIMsgFolderListener
      MailServices.mfn.addListener(this, MailServices.mfn.folderAdded);
      Services.prefs.addObserver("mail.server.", this);
      Services.prefs.addObserver("mail.account.", this);
      for (let topic of this._notifications) {
        Services.obs.addObserver(this, topic);
      }
    }
  }
  decrementListeners() {
    this.listenerCount--;
    if (this.listenerCount == 0) {
      MailServices.mfn.removeListener(this);
      Services.prefs.removeObserver("mail.server.", this);
      Services.prefs.removeObserver("mail.account.", this);
      for (let topic of this._notifications) {
        Services.obs.removeObserver(this, topic);
      }
    }
  }

  // nsIMsgFolderListener
  folderAdded(folder) {
    // If the account of this folder is unknown, it is new and this is the
    // initial root folder after the account has been created.
    let server = folder.server;
    let nativeAccount = MailServices.accounts.FindAccountForServer(server);
    if (nativeAccount && !this.monitoredAccounts.has(nativeAccount.key)) {
      this.monitoredAccounts.set(
        nativeAccount.key,
        this.getMonitoredProperties(nativeAccount)
      );
      let account = convertAccount(nativeAccount, false);
      this.emit("account-added", nativeAccount.key, account);
    }
  }

  // nsIObserver
  _notifications = ["message-account-removed"];

  async observe(subject, topic, data) {
    switch (topic) {
      case "nsPref:changed":
        {
          let [, type, key, property] = data.split(".");

          if (type == "server" && property == "name") {
            let server;
            try {
              server = MailServices.accounts.getIncomingServer(key);
            } catch (ex) {
              // Fails for servers being removed.
              return;
            }
            let nativeAccount =
              MailServices.accounts.FindAccountForServer(server);

            let name = this.getChangedMonitoredProperty(nativeAccount, "name");
            if (name) {
              this.emit("account-updated", nativeAccount.key, {
                id: nativeAccount.key,
                name,
              });
            }
          }

          if (type == "account" && property == "identities") {
            let nativeAccount = MailServices.accounts.getAccount(key);

            let defaultIdentityKey = this.getChangedMonitoredProperty(
              nativeAccount,
              "defaultIdentityKey"
            );
            if (defaultIdentityKey) {
              this.emit("account-updated", nativeAccount.key, {
                id: nativeAccount.key,
                defaultIdentity: convertMailIdentity(
                  nativeAccount,
                  nativeAccount.defaultIdentity
                ),
              });
            }
          }
        }
        break;

      case "message-account-removed":
        if (this.monitoredAccounts.has(data)) {
          this.monitoredAccounts.delete(data);
          this.emit("account-removed", data);
        }
        break;
    }
  }
})();

this.accounts = class extends ExtensionAPIPersistent {
  PERSISTENT_EVENTS = {
    // For primed persistent events (deactivated background), the context is only
    // available after fire.wakeup() has fulfilled (ensuring the convert() function
    // has been called).

    onCreated({ context, fire }) {
      async function listener(_event, key, account) {
        if (fire.wakeup) {
          await fire.wakeup();
        }
        fire.sync(key, account);
      }
      accountsTracker.on("account-added", listener);
      return {
        unregister: () => {
          accountsTracker.off("account-added", listener);
        },
        convert(newFire, extContext) {
          fire = newFire;
          context = extContext;
        },
      };
    },
    onUpdated({ context, fire }) {
      async function listener(_event, key, changedValues) {
        if (fire.wakeup) {
          await fire.wakeup();
        }
        fire.sync(key, changedValues);
      }
      accountsTracker.on("account-updated", listener);
      return {
        unregister: () => {
          accountsTracker.off("account-updated", listener);
        },
        convert(newFire, extContext) {
          fire = newFire;
          context = extContext;
        },
      };
    },
    onDeleted({ context, fire }) {
      async function listener(_event, key) {
        if (fire.wakeup) {
          await fire.wakeup();
        }
        fire.sync(key);
      }
      accountsTracker.on("account-removed", listener);
      return {
        unregister: () => {
          accountsTracker.off("account-removed", listener);
        },
        convert(newFire, extContext) {
          fire = newFire;
          context = extContext;
        },
      };
    },
  };

  constructor(...args) {
    super(...args);
    accountsTracker.incrementListeners();
  }

  onShutdown() {
    accountsTracker.decrementListeners();
  }

  getAPI(context) {
    return {
      accounts: {
        async list(includeFolders) {
          let accounts = [];
          for (let account of MailServices.accounts.accounts) {
            account = convertAccount(account, includeFolders);
            if (account) {
              accounts.push(account);
            }
          }
          return accounts;
        },
        async get(accountId, includeFolders) {
          let account = MailServices.accounts.getAccount(accountId);
          return convertAccount(account, includeFolders);
        },
        async getDefault(includeFolders) {
          let account = MailServices.accounts.defaultAccount;
          return convertAccount(account, includeFolders);
        },
        async getDefaultIdentity(accountId) {
          let account = MailServices.accounts.getAccount(accountId);
          return convertMailIdentity(account, account?.defaultIdentity);
        },
        async setDefaultIdentity(accountId, identityId) {
          let account = MailServices.accounts.getAccount(accountId);
          if (!account) {
            throw new ExtensionError(`Account not found: ${accountId}`);
          }
          for (let identity of account.identities) {
            if (identity.key == identityId) {
              account.defaultIdentity = identity;
              return;
            }
          }
          throw new ExtensionError(
            `Identity ${identityId} not found for ${accountId}`
          );
        },
        onCreated: new EventManager({
          context,
          module: "accounts",
          event: "onCreated",
          extensionApi: this,
        }).api(),
        onUpdated: new EventManager({
          context,
          module: "accounts",
          event: "onUpdated",
          extensionApi: this,
        }).api(),
        onDeleted: new EventManager({
          context,
          module: "accounts",
          event: "onDeleted",
          extensionApi: this,
        }).api(),
      },
    };
  }
};