summaryrefslogtreecommitdiffstats
path: root/devtools/client/webide/modules/app-projects.js
blob: 691d09064286a5f754a72d90fa8905ad5a7bccfb (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
/* 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/. */

const {Cc, Ci, Cu, Cr} = require("chrome");
const promise = require("promise");

const EventEmitter = require("devtools/shared/event-emitter");
const {generateUUID} = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator);
const {FileUtils} = Cu.import("resource://gre/modules/FileUtils.jsm", {});

/**
 * IndexedDB wrapper that just save project objects
 *
 * The only constraint is that project objects have to have
 * a unique `location` object.
 */

const IDB = {
  _db: null,
  databaseName: "AppProjects",

  open: function () {
    let deferred = promise.defer();

    let request = indexedDB.open(IDB.databaseName, 5);
    request.onerror = function (event) {
      deferred.reject("Unable to open AppProjects indexedDB: " +
                      this.error.name + " - " + this.error.message);
    };
    request.onupgradeneeded = function (event) {
      let db = event.target.result;
      db.createObjectStore("projects", { keyPath: "location" });
    };

    request.onsuccess = function () {
      let db = IDB._db = request.result;
      let objectStore = db.transaction("projects").objectStore("projects");
      let projects = [];
      let toRemove = [];
      objectStore.openCursor().onsuccess = function (event) {
        let cursor = event.target.result;
        if (cursor) {
          if (cursor.value.location) {

            // We need to make sure this object has a `.location` property.
            // The UI depends on this property.
            // This should not be needed as we make sure to register valid
            // projects, but in the past (before bug 924568), we might have
            // registered invalid objects.


            // We also want to make sure the location is valid.
            // If the location doesn't exist, we remove the project.

            try {
              let file = FileUtils.File(cursor.value.location);
              if (file.exists()) {
                projects.push(cursor.value);
              } else {
                toRemove.push(cursor.value.location);
              }
            } catch (e) {
              if (e.result == Cr.NS_ERROR_FILE_UNRECOGNIZED_PATH) {
                // A URL
                projects.push(cursor.value);
              }
            }
          }
          cursor.continue();
        } else {
          let removePromises = [];
          for (let location of toRemove) {
            removePromises.push(IDB.remove(location));
          }
          promise.all(removePromises).then(() => {
            deferred.resolve(projects);
          });
        }
      };
    };

    return deferred.promise;
  },

  add: function (project) {
    let deferred = promise.defer();

    if (!project.location) {
      // We need to make sure this object has a `.location` property.
      deferred.reject("Missing location property on project object.");
    } else {
      let transaction = IDB._db.transaction(["projects"], "readwrite");
      let objectStore = transaction.objectStore("projects");
      let request = objectStore.add(project);
      request.onerror = function (event) {
        deferred.reject("Unable to add project to the AppProjects indexedDB: " +
                        this.error.name + " - " + this.error.message);
      };
      request.onsuccess = function () {
        deferred.resolve();
      };
    }

    return deferred.promise;
  },

  update: function (project) {
    let deferred = promise.defer();

    var transaction = IDB._db.transaction(["projects"], "readwrite");
    var objectStore = transaction.objectStore("projects");
    var request = objectStore.put(project);
    request.onerror = function (event) {
      deferred.reject("Unable to update project to the AppProjects indexedDB: " +
                      this.error.name + " - " + this.error.message);
    };
    request.onsuccess = function () {
      deferred.resolve();
    };

    return deferred.promise;
  },

  remove: function (location) {
    let deferred = promise.defer();

    let request = IDB._db.transaction(["projects"], "readwrite")
                    .objectStore("projects")
                    .delete(location);
    request.onsuccess = function (event) {
      deferred.resolve();
    };
    request.onerror = function () {
      deferred.reject("Unable to delete project to the AppProjects indexedDB: " +
                      this.error.name + " - " + this.error.message);
    };

    return deferred.promise;
  }
};

var loadDeferred = promise.defer();

loadDeferred.resolve(IDB.open().then(function (projects) {
  AppProjects.projects = projects;
  AppProjects.emit("ready", projects);
}));

const AppProjects = {
  load: function () {
    return loadDeferred.promise;
  },

  addPackaged: function (folder) {
    let file = FileUtils.File(folder.path);
    if (!file.exists()) {
      return promise.reject("path doesn't exist");
    }
    let existingProject = this.get(folder.path);
    if (existingProject) {
      return promise.reject("Already added");
    }
    let project = {
      type: "packaged",
      location: folder.path,
      // We need a unique id, that is the app origin,
      // in order to identify the app when being installed on the device.
      // The packaged app local path is a valid id, but only on the client.
      // This origin will be used to generate the true id of an app:
      // its manifest URL.
      // If the app ends up specifying an explicit origin in its manifest,
      // we will override this random UUID on app install.
      packagedAppOrigin: generateUUID().toString().slice(1, -1)
    };
    return IDB.add(project).then(() => {
      this.projects.push(project);
      return project;
    });
  },

  addHosted: function (manifestURL) {
    let existingProject = this.get(manifestURL);
    if (existingProject) {
      return promise.reject("Already added");
    }
    let project = {
      type: "hosted",
      location: manifestURL
    };
    return IDB.add(project).then(() => {
      this.projects.push(project);
      return project;
    });
  },

  update: function (project) {
    return IDB.update(project);
  },

  updateLocation: function (project, newLocation) {
    return IDB.remove(project.location)
              .then(() => {
                project.location = newLocation;
                return IDB.add(project);
              });
  },

  remove: function (location) {
    return IDB.remove(location).then(() => {
      for (let i = 0; i < this.projects.length; i++) {
        if (this.projects[i].location == location) {
          this.projects.splice(i, 1);
          return;
        }
      }
      throw new Error("Unable to find project in AppProjects store");
    });
  },

  get: function (location) {
    for (let i = 0; i < this.projects.length; i++) {
      if (this.projects[i].location == location) {
        return this.projects[i];
      }
    }
    return null;
  },

  projects: []
};

EventEmitter.decorate(AppProjects);

exports.AppProjects = AppProjects;