summaryrefslogtreecommitdiffstats
path: root/mobile/android/modules/Home.jsm
blob: e77d35dbdaa11f7585473ad4e2a362d136fdf43d (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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
// -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
/* 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 = ["Home"];

const { classes: Cc, interfaces: Ci, utils: Cu } = Components;

Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/SharedPreferences.jsm");
Cu.import("resource://gre/modules/Messaging.jsm");

// Keep this in sync with the constant defined in PanelAuthCache.java
const PREFS_PANEL_AUTH_PREFIX = "home_panels_auth_";

// Default weight for a banner message.
const DEFAULT_WEIGHT = 100;

// See bug 915424
function resolveGeckoURI(aURI) {
  if (!aURI)
    throw "Can't resolve an empty uri";

  if (aURI.startsWith("chrome://")) {
    let registry = Cc['@mozilla.org/chrome/chrome-registry;1'].getService(Ci["nsIChromeRegistry"]);
    return registry.convertChromeURL(Services.io.newURI(aURI, null, null)).spec;
  } else if (aURI.startsWith("resource://")) {
    let handler = Services.io.getProtocolHandler("resource").QueryInterface(Ci.nsIResProtocolHandler);
    return handler.resolveURI(Services.io.newURI(aURI, null, null));
  }
  return aURI;
}

function BannerMessage(options) {
  let uuidgen = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator);
  this.id = uuidgen.generateUUID().toString();

  if ("text" in options && options.text != null)
    this.text = options.text;

  if ("icon" in options && options.icon != null)
    this.iconURI = resolveGeckoURI(options.icon);

  if ("onshown" in options && typeof options.onshown === "function")
    this.onshown = options.onshown;

  if ("onclick" in options && typeof options.onclick === "function")
    this.onclick = options.onclick;

  if ("ondismiss" in options && typeof options.ondismiss === "function")
    this.ondismiss = options.ondismiss;

  let weight = parseInt(options.weight, 10);
  this.weight = weight > 0 ? weight : DEFAULT_WEIGHT;
}

// We need this object to have access to the HomeBanner
// private members without leaking it outside Home.jsm.
var HomeBannerMessageHandlers;

var HomeBanner = (function () {
  // Whether there is a "HomeBanner:Get" request we couldn't fulfill.
  let _pendingRequest = false;

  // Functions used to handle messages sent from Java.
  HomeBannerMessageHandlers = {
    "HomeBanner:Get": function handleBannerGet(data) {
      if (Object.keys(_messages).length > 0) {
        _sendBannerData();
      } else {
        _pendingRequest = true;
      }
    }
  };

  // Holds the messages that will rotate through the banner.
  let _messages = {};

  // Choose a random message from the set of messages, biasing towards those with higher weight.
  // Weight logic copied from desktop snippets:
  // https://github.com/mozilla/snippets-service/blob/7d80edb8b1cddaed075275c2fc7cdf69a10f4003/snippets/base/templates/base/includes/snippet_js.html#L119
  let _sendBannerData = function() {
    let totalWeight = 0;
    for (let key in _messages) {
      let message = _messages[key];
      totalWeight += message.weight;
      message.totalWeight = totalWeight;
    }

    let threshold = Math.random() * totalWeight;
    for (let key in _messages) {
      let message = _messages[key];
      if (threshold < message.totalWeight) {
        Messaging.sendRequest({
          type: "HomeBanner:Data",
          id: message.id,
          text: message.text,
          iconURI: message.iconURI
        });
        return;
      }
    }
  };

  let _handleShown = function(id) {
    let message = _messages[id];
    if (message.onshown)
      message.onshown();
  };

  let _handleClick = function(id) {
    let message = _messages[id];
    if (message.onclick)
      message.onclick();
  };

  let _handleDismiss = function(id) {
    let message = _messages[id];
    if (message.ondismiss)
      message.ondismiss();
  };

  return Object.freeze({
    observe: function(subject, topic, data) {
      switch(topic) {
        case "HomeBanner:Shown":
          _handleShown(data);
          break;

        case "HomeBanner:Click":
          _handleClick(data);
          break;

        case "HomeBanner:Dismiss":
          _handleDismiss(data);
          break;
      }
    },

    /**
     * Adds a new banner message to the rotation.
     *
     * @return id Unique identifer for the message.
     */
    add: function(options) {
      let message = new BannerMessage(options);
      _messages[message.id] = message;

      // If this is the first message we're adding, add
      // observers to listen for requests from the Java UI.
      if (Object.keys(_messages).length == 1) {
        Services.obs.addObserver(this, "HomeBanner:Shown", false);
        Services.obs.addObserver(this, "HomeBanner:Click", false);
        Services.obs.addObserver(this, "HomeBanner:Dismiss", false);

        // Send a message to Java if there's a pending "HomeBanner:Get" request.
        if (_pendingRequest) {
          _pendingRequest = false;
          _sendBannerData();
        }
      }

      return message.id;
    },

    /**
     * Removes a banner message from the rotation.
     *
     * @param id The id of the message to remove.
     */
    remove: function(id) {
      if (!(id in _messages)) {
        throw "Home.banner: Can't remove message that doesn't exist: id = " + id;
      }

      delete _messages[id];

      // If there are no more messages, remove the observers.
      if (Object.keys(_messages).length == 0) {
        Services.obs.removeObserver(this, "HomeBanner:Shown");
        Services.obs.removeObserver(this, "HomeBanner:Click");
        Services.obs.removeObserver(this, "HomeBanner:Dismiss");
      }
    }
  });
})();

// We need this object to have access to the HomePanels
// private members without leaking it outside Home.jsm.
var HomePanelsMessageHandlers;

var HomePanels = (function () {
  // Functions used to handle messages sent from Java.
  HomePanelsMessageHandlers = {

    "HomePanels:Get": function handlePanelsGet(data) {
      data = JSON.parse(data);

      let requestId = data.requestId;
      let ids = data.ids || null;

      let panels = [];
      for (let id in _registeredPanels) {
        // Null ids means we want to fetch all available panels
        if (ids == null || ids.indexOf(id) >= 0) {
          try {
            panels.push(_generatePanel(id));
          } catch(e) {
            Cu.reportError("Home.panels: Invalid options, panel.id = " + id + ": " + e);
          }
        }
      }

      Messaging.sendRequest({
        type: "HomePanels:Data",
        panels: panels,
        requestId: requestId
      });
    },

    "HomePanels:Authenticate": function handlePanelsAuthenticate(id) {
      // Generate panel options to get auth handler.
      let options = _registeredPanels[id]();
      if (!options.auth) {
        throw "Home.panels: Invalid auth for panel.id = " + id;
      }
      if (!options.auth.authenticate || typeof options.auth.authenticate !== "function") {
        throw "Home.panels: Invalid auth authenticate function: panel.id = " + this.id;
      }
      options.auth.authenticate();
    },

    "HomePanels:RefreshView": function handlePanelsRefreshView(data) {
      data = JSON.parse(data);

      let options = _registeredPanels[data.panelId]();
      let view = options.views[data.viewIndex];

      if (!view) {
        throw "Home.panels: Invalid view for panel.id = " + data.panelId
            + ", view.index = " + data.viewIndex;
      }

      if (!view.onrefresh || typeof view.onrefresh !== "function") {
        throw "Home.panels: Invalid onrefresh for panel.id = " + data.panelId
            + ", view.index = " + data.viewIndex;
      }

      view.onrefresh();
    },

    "HomePanels:Installed": function handlePanelsInstalled(id) {
      _assertPanelExists(id);

      let options = _registeredPanels[id]();
      if (!options.oninstall) {
        return;
      }
      if (typeof options.oninstall !== "function") {
        throw "Home.panels: Invalid oninstall function: panel.id = " + this.id;
      }
      options.oninstall();
    },

    "HomePanels:Uninstalled": function handlePanelsUninstalled(id) {
      _assertPanelExists(id);

      let options = _registeredPanels[id]();
      if (!options.onuninstall) {
        return;
      }
      if (typeof options.onuninstall !== "function") {
        throw "Home.panels: Invalid onuninstall function: panel.id = " + this.id;
      }
      options.onuninstall();
    }
  };

  // Holds the current set of registered panels that can be
  // installed, updated, uninstalled, or unregistered. It maps
  // panel ids with the functions that dynamically generate
  // their respective panel options. This is used to retrieve
  // the current list of available panels in the system.
  // See HomePanels:Get handler.
  let _registeredPanels = {};

  // Valid layouts for a panel.
  let Layout = Object.freeze({
    FRAME: "frame"
  });

  // Valid types of views for a dataset.
  let View = Object.freeze({
    LIST: "list",
    GRID: "grid"
  });

  // Valid item types for a panel view.
  let Item = Object.freeze({
    ARTICLE: "article",
    IMAGE: "image",
    ICON: "icon"
  });

  // Valid item handlers for a panel view.
  let ItemHandler = Object.freeze({
    BROWSER: "browser",
    INTENT: "intent"
  });

  function Panel(id, options) {
    this.id = id;
    this.title = options.title;
    this.layout = options.layout;
    this.views = options.views;
    this.default = !!options.default;

    if (!this.id || !this.title) {
      throw "Home.panels: Can't create a home panel without an id and title!";
    }

    if (!this.layout) {
      // Use FRAME layout by default
      this.layout = Layout.FRAME;
    } else if (!_valueExists(Layout, this.layout)) {
      throw "Home.panels: Invalid layout for panel: panel.id = " + this.id + ", panel.layout =" + this.layout;
    }

    for (let view of this.views) {
      if (!_valueExists(View, view.type)) {
        throw "Home.panels: Invalid view type: panel.id = " + this.id + ", view.type = " + view.type;
      }

      if (!view.itemType) {
        if (view.type == View.LIST) {
          // Use ARTICLE item type by default in LIST views
          view.itemType = Item.ARTICLE;
        } else if (view.type == View.GRID) {
          // Use IMAGE item type by default in GRID views
          view.itemType = Item.IMAGE;
        }
      } else if (!_valueExists(Item, view.itemType)) {
        throw "Home.panels: Invalid item type: panel.id = " + this.id + ", view.itemType = " + view.itemType;
      }

      if (!view.itemHandler) {
        // Use BROWSER item handler by default
        view.itemHandler = ItemHandler.BROWSER;
      } else if (!_valueExists(ItemHandler, view.itemHandler)) {
        throw "Home.panels: Invalid item handler: panel.id = " + this.id + ", view.itemHandler = " + view.itemHandler;
      }

      if (!view.dataset) {
        throw "Home.panels: No dataset provided for view: panel.id = " + this.id + ", view.type = " + view.type;
      }

      if (view.onrefresh) {
        view.refreshEnabled = true;
      }
    }

    if (options.auth) {
      if (!options.auth.messageText) {
        throw "Home.panels: Invalid auth messageText: panel.id = " + this.id;
      }
      if (!options.auth.buttonText) {
        throw "Home.panels: Invalid auth buttonText: panel.id = " + this.id;
      }

      this.authConfig = {
        messageText: options.auth.messageText,
        buttonText: options.auth.buttonText
      };

      // Include optional image URL if it is specified.
      if (options.auth.imageUrl) {
        this.authConfig.imageUrl = options.auth.imageUrl;
      }
    }

    if (options.position >= 0) {
      this.position = options.position;
    }
  }

  let _generatePanel = function(id) {
    let options = _registeredPanels[id]();
    return new Panel(id, options);
  };

  // Helper function used to see if a value is in an object.
  let _valueExists = function(obj, value) {
    for (let key in obj) {
      if (obj[key] == value) {
        return true;
      }
    }
    return false;
  };

  let _assertPanelExists = function(id) {
    if (!(id in _registeredPanels)) {
      throw "Home.panels: Panel doesn't exist: id = " + id;
    }
  };

  return Object.freeze({
    Layout: Layout,
    View: View,
    Item: Item,
    ItemHandler: ItemHandler,

    register: function(id, optionsCallback) {
      // Bail if the panel already exists
      if (id in _registeredPanels) {
        throw "Home.panels: Panel already exists: id = " + id;
      }

      if (!optionsCallback || typeof optionsCallback !== "function") {
        throw "Home.panels: Panel callback must be a function: id = " + id;
      }

      _registeredPanels[id] = optionsCallback;
    },

    unregister: function(id) {
      _assertPanelExists(id);

      delete _registeredPanels[id];
    },

    install: function(id) {
      _assertPanelExists(id);

      Messaging.sendRequest({
        type: "HomePanels:Install",
        panel: _generatePanel(id)
      });
    },

    uninstall: function(id) {
      _assertPanelExists(id);

      Messaging.sendRequest({
        type: "HomePanels:Uninstall",
        id: id
      });
    },

    update: function(id) {
      _assertPanelExists(id);

      Messaging.sendRequest({
        type: "HomePanels:Update",
        panel: _generatePanel(id)
      });
    },

    setAuthenticated: function(id, isAuthenticated) {
      _assertPanelExists(id);

      let authKey = PREFS_PANEL_AUTH_PREFIX + id;
      let sharedPrefs = SharedPreferences.forProfile();
      sharedPrefs.setBoolPref(authKey, isAuthenticated);
    }
  });
})();

// Public API
this.Home = Object.freeze({
  banner: HomeBanner,
  panels: HomePanels,

  // Lazy notification observer registered in browser.js
  observe: function(subject, topic, data) {
    if (topic in HomeBannerMessageHandlers) {
      HomeBannerMessageHandlers[topic](data);
    } else if (topic in HomePanelsMessageHandlers) {
      HomePanelsMessageHandlers[topic](data);
    } else {
      Cu.reportError("Home.observe: message handler not found for topic: " + topic);
    }
  }
});