summaryrefslogtreecommitdiffstats
path: root/services/cloudsync/CloudSyncAdapters.jsm
blob: 16264a4f7601f83d79f3428a66cdd601809cafc7 (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
/* 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/. */

"use strict";

this.EXPORTED_SYMBOLS = ["Adapters"];

Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/CloudSyncEventSource.jsm");

this.Adapters = function () {
  let eventTypes = [
    "sync",
  ];

  let suspended = true;

  let suspend = function () {
    if (!suspended) {
      Services.obs.removeObserver(observer, "cloudsync:user-sync", false);
      suspended = true;
    }
  }.bind(this);

  let resume = function () {
    if (suspended) {
      Services.obs.addObserver(observer, "cloudsync:user-sync", false);
      suspended = false;
    }
  }.bind(this);

  let eventSource = new EventSource(eventTypes, suspend, resume);
  let registeredAdapters = new Map();

  function register (name, opts) {
    opts = opts || {};
    registeredAdapters.set(name, opts);
  }

  function unregister (name) {
    if (!registeredAdapters.has(name)) {
      throw new Error("adapter is not registered: " + name)
    }
    registeredAdapters.delete(name);
  }

  function getAdapterNames () {
    let result = [];
    for (let name of registeredAdapters.keys()) {
      result.push(name);
    }
    return result;
  }

  function getAdapter (name) {
    if (!registeredAdapters.has(name)) {
      throw new Error("adapter is not registered: " + name)
    }
    return registeredAdapters.get(name);
  }

  function countAdapters () {
    return registeredAdapters.size;
  }

  let observer = {
    observe: function (subject, topic, data) {
      switch (topic) {
        case "cloudsync:user-sync":
          eventSource.emit("sync");
          break;
      }
    }
  };

  this.addEventListener = eventSource.addEventListener;
  this.removeEventListener = eventSource.removeEventListener;
  this.register = register.bind(this);
  this.get = getAdapter.bind(this);
  this.unregister = unregister.bind(this);
  this.__defineGetter__("names", getAdapterNames);
  this.__defineGetter__("count", countAdapters);
};

Adapters.prototype = {

};