summaryrefslogtreecommitdiffstats
path: root/comm/mail/components/extensions/parent/ext-identities.js
blob: 1b9e719ebeacb0152487d46056cb68130cb9108e (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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/* 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"
);
ChromeUtils.defineESModuleGetters(this, {
  DeferredTask: "resource://gre/modules/DeferredTask.sys.mjs",
});

function findIdentityAndAccount(identityId) {
  for (let account of MailServices.accounts.accounts) {
    for (let identity of account.identities) {
      if (identity.key == identityId) {
        return { account, identity };
      }
    }
  }
  return null;
}

function checkForProtectedProperties(details) {
  const protectedProperties = ["id", "accountId"];
  for (let [key, value] of Object.entries(details)) {
    // Check only properties explicitly provided.
    if (value != null && protectedProperties.includes(key)) {
      throw new ExtensionError(
        `Setting the ${key} property of a MailIdentity is not supported.`
      );
    }
  }
}

function updateIdentity(identity, details) {
  for (let [key, value] of Object.entries(details)) {
    // Update only properties explicitly provided.
    if (value == null) {
      continue;
    }
    // Map from WebExtension property names to nsIMsgIdentity property names.
    switch (key) {
      case "signatureIsPlainText":
        identity.htmlSigFormat = !value;
        break;
      case "name":
        identity.fullName = value;
        break;
      case "signature":
        identity.htmlSigText = value;
        break;
      default:
        identity[key] = value;
    }
  }
}

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

    this.identities = new Map();
    this.deferredNotifications = new ExtensionUtils.DefaultMap(
      key =>
        new DeferredTask(
          () => this.emitPendingNotification(key),
          NOTIFICATION_COLLAPSE_TIME
        )
    );

    // Keep track of identities and their values, to suppress superfluous
    // update notifications. The deferredTask timer is used to collapse multiple
    // update notifications.
    for (let account of MailServices.accounts.accounts) {
      for (let identity of account.identities) {
        this.identities.set(
          identity.key,
          convertMailIdentity(account, identity)
        );
      }
    }
  }

  incrementListeners() {
    this.listenerCount++;
    if (this.listenerCount == 1) {
      for (let topic of this._notifications) {
        Services.obs.addObserver(this, topic);
      }
      Services.prefs.addObserver("mail.identity.", this);
    }
  }
  decrementListeners() {
    this.listenerCount--;
    if (this.listenerCount == 0) {
      for (let topic of this._notifications) {
        Services.obs.removeObserver(this, topic);
      }
      Services.prefs.removeObserver("mail.identity.", this);
    }
  }

  emitPendingNotification(key) {
    let ia = findIdentityAndAccount(key);
    if (!ia) {
      return;
    }

    let oldValues = this.identities.get(key);
    let newValues = convertMailIdentity(ia.account, ia.identity);
    let changedValues = {};
    for (let propertyName of Object.keys(newValues)) {
      if (
        !oldValues.hasOwnProperty(propertyName) ||
        oldValues[propertyName] != newValues[propertyName]
      ) {
        changedValues[propertyName] = newValues[propertyName];
      }
    }
    if (Object.keys(changedValues).length > 0) {
      changedValues.accountId = ia.account.key;
      changedValues.id = ia.identity.key;
      let notification =
        Object.keys(oldValues).length == 0
          ? "account-identity-added"
          : "account-identity-updated";
      this.identities.set(key, newValues);
      this.emit(notification, key, changedValues);
    }
  }

  // nsIObserver
  _notifications = ["account-identity-added", "account-identity-removed"];

  async observe(subject, topic, data) {
    switch (topic) {
      case "account-identity-added":
        {
          let key = data;
          this.identities.set(key, {});
          this.deferredNotifications.get(key).arm();
        }
        break;

      case "nsPref:changed":
        {
          let key = data.split(".").slice(2, 3).pop();

          // Ignore update notifications for created identities, before they are
          // added to an account (looks like they are cloned from a default
          // identity). Also ignore notifications for deleted identities.
          if (
            key &&
            this.identities.has(key) &&
            this.identities.get(key) != null
          ) {
            this.deferredNotifications.get(key).disarm();
            this.deferredNotifications.get(key).arm();
          }
        }
        break;

      case "account-identity-removed":
        {
          let key = data;
          if (
            key &&
            this.identities.has(key) &&
            this.identities.get(key) != null
          ) {
            // Mark identities as deleted instead of removing them.
            this.identities.set(key, null);
            // Force any pending notification to be emitted.
            await this.deferredNotifications.get(key).finalize();

            this.emit("account-identity-removed", key);
          }
        }
        break;
    }
  }
})();

this.identities = 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, identity) {
        if (fire.wakeup) {
          await fire.wakeup();
        }
        fire.sync(key, identity);
      }
      identitiesTracker.on("account-identity-added", listener);
      return {
        unregister: () => {
          identitiesTracker.off("account-identity-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);
      }
      identitiesTracker.on("account-identity-updated", listener);
      return {
        unregister: () => {
          identitiesTracker.off("account-identity-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);
      }
      identitiesTracker.on("account-identity-removed", listener);
      return {
        unregister: () => {
          identitiesTracker.off("account-identity-removed", listener);
        },
        convert(newFire, extContext) {
          fire = newFire;
          context = extContext;
        },
      };
    },
  };

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

  onShutdown() {
    identitiesTracker.decrementListeners();
  }

  getAPI(context) {
    return {
      identities: {
        async list(accountId) {
          let accounts = accountId
            ? [MailServices.accounts.getAccount(accountId)]
            : MailServices.accounts.accounts;

          let identities = [];
          for (let account of accounts) {
            for (let identity of account.identities) {
              identities.push(convertMailIdentity(account, identity));
            }
          }
          return identities;
        },
        async get(identityId) {
          let ia = findIdentityAndAccount(identityId);
          return ia ? convertMailIdentity(ia.account, ia.identity) : null;
        },
        async delete(identityId) {
          let ia = findIdentityAndAccount(identityId);
          if (!ia) {
            throw new ExtensionError(`Identity not found: ${identityId}`);
          }
          if (
            ia.account?.defaultIdentity &&
            ia.account.defaultIdentity.key == ia.identity.key
          ) {
            throw new ExtensionError(
              `Identity ${identityId} is the default identity of account ${ia.account.key} and cannot be deleted`
            );
          }
          ia.account.removeIdentity(ia.identity);
        },
        async create(accountId, details) {
          let account = MailServices.accounts.getAccount(accountId);
          if (!account) {
            throw new ExtensionError(`Account not found: ${accountId}`);
          }
          // Abort and throw, if details include protected properties.
          checkForProtectedProperties(details);

          let identity = MailServices.accounts.createIdentity();
          updateIdentity(identity, details);
          account.addIdentity(identity);
          return convertMailIdentity(account, identity);
        },
        async update(identityId, details) {
          let ia = findIdentityAndAccount(identityId);
          if (!ia) {
            throw new ExtensionError(`Identity not found: ${identityId}`);
          }
          // Abort and throw, if details include protected properties.
          checkForProtectedProperties(details);

          updateIdentity(ia.identity, details);
          return convertMailIdentity(ia.account, ia.identity);
        },
        async getDefault(accountId) {
          let account = MailServices.accounts.getAccount(accountId);
          return convertMailIdentity(account, account?.defaultIdentity);
        },
        async setDefault(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: "identities",
          event: "onCreated",
          extensionApi: this,
        }).api(),
        onUpdated: new EventManager({
          context,
          module: "identities",
          event: "onUpdated",
          extensionApi: this,
        }).api(),
        onDeleted: new EventManager({
          context,
          module: "identities",
          event: "onDeleted",
          extensionApi: this,
        }).api(),
      },
    };
  }
};