summaryrefslogtreecommitdiffstats
path: root/browser/extensions/pocket/bootstrap.js
blob: c470eb8d32862265483f121a917851004de1634f (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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
/* -*- 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/. */

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

Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://services-common/utils.js");
Cu.import("resource://gre/modules/Preferences.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Services",
                                  "resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "RecentWindow",
                                  "resource:///modules/RecentWindow.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "CustomizableUI",
                                  "resource:///modules/CustomizableUI.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "AddonManager",
                                  "resource://gre/modules/AddonManager.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "ReaderMode",
                                  "resource://gre/modules/ReaderMode.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Pocket",
                                  "chrome://pocket/content/Pocket.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "AboutPocket",
                                  "chrome://pocket/content/AboutPocket.jsm");
XPCOMUtils.defineLazyGetter(this, "gPocketBundle", function() {
  return Services.strings.createBundle("chrome://pocket/locale/pocket.properties");
});
XPCOMUtils.defineLazyGetter(this, "gPocketStyleURI", function() {
  return Services.io.newURI("chrome://pocket/skin/pocket.css", null, null);
});

// Due to bug 1051238 frame scripts are cached forever, so we can't update them
// as a restartless add-on. The Math.random() is the work around for this.
const PROCESS_SCRIPT = "chrome://pocket/content/pocket-content-process.js?" + Math.random();

const PREF_BRANCH = "extensions.pocket.";
const PREFS = {
  enabled: true, // bug 1229937, figure out ui tour support
  api: "api.getpocket.com",
  site: "getpocket.com",
  oAuthConsumerKey: "40249-e88c401e1b1f2242d9e441c4"
};

function setDefaultPrefs() {
  let branch = Services.prefs.getDefaultBranch(PREF_BRANCH);
  for (let [key, val] of Object.entries(PREFS)) {
    // If someone beat us to setting a default, don't overwrite it.  This can
    // happen if distribution.ini sets the default first.
    if (branch.getPrefType(key) != branch.PREF_INVALID)
      continue;
    switch (typeof val) {
      case "boolean":
        branch.setBoolPref(key, val);
        break;
      case "number":
        branch.setIntPref(key, val);
        break;
      case "string":
        branch.setCharPref(key, val);
        break;
    }
  }
}

function createElementWithAttrs(document, type, attrs) {
  let element = document.createElement(type);
  Object.keys(attrs).forEach(function (attr) {
    element.setAttribute(attr, attrs[attr]);
  })
  return element;
}

function CreatePocketWidget(reason) {
  let id = "pocket-button"
  let widget = CustomizableUI.getWidget(id);
  // The widget is only null if we've created then destroyed the widget.
  // Once we've actually called createWidget the provider will be set to
  // PROVIDER_API.
  if (widget && widget.provider == CustomizableUI.PROVIDER_API)
    return;
  // if upgrading from builtin version and the button was placed in ui,
  // seenWidget will not be null
  let seenWidget = CustomizableUI.getPlacementOfWidget("pocket-button", false, true);
  let pocketButton = {
    id: "pocket-button",
    defaultArea: CustomizableUI.AREA_NAVBAR,
    introducedInVersion: "pref",
    type: "view",
    tabSpecific: true,
    viewId: "PanelUI-pocketView",
    label: gPocketBundle.GetStringFromName("pocket-button.label"),
    tooltiptext: gPocketBundle.GetStringFromName("pocket-button.tooltiptext"),
    // Use forwarding functions here to avoid loading Pocket.jsm on startup:
    onViewShowing: function() {
      return Pocket.onPanelViewShowing.apply(this, arguments);
    },
    onViewHiding: function() {
      return Pocket.onPanelViewHiding.apply(this, arguments);
    },
    onBeforeCreated: function(doc) {
      // Bug 1223127,CUI should make this easier to do.
      if (doc.getElementById("PanelUI-pocketView"))
        return;
      let view = doc.createElement("panelview");
      view.id = "PanelUI-pocketView";
      let panel = doc.createElement("vbox");
      panel.setAttribute("class", "panel-subview-body");
      view.appendChild(panel);
      doc.getElementById("PanelUI-multiView").appendChild(view);
    }
  };

  CustomizableUI.createWidget(pocketButton);
  CustomizableUI.addListener(pocketButton);
  // placed is null if location is palette
  let placed = CustomizableUI.getPlacementOfWidget("pocket-button");

  // a first time install will always have placed the button somewhere, and will
  // not have a placement prior to creating the widget. Thus, !seenWidget &&
  // placed.
  if (reason == ADDON_ENABLE && !seenWidget && placed) {
    // initially place the button after the bookmarks button if it is in the UI
    let widgets = CustomizableUI.getWidgetIdsInArea(CustomizableUI.AREA_NAVBAR);
    let bmbtn = widgets.indexOf("bookmarks-menu-button");
    if (bmbtn > -1) {
      CustomizableUI.moveWidgetWithinArea("pocket-button", bmbtn + 1);
    }
  }

  // Uninstall the Pocket social provider if it exists, but only if we haven't
  // already uninstalled it in this manner.  That way the user can reinstall
  // it if they prefer it without its being uninstalled every time they start
  // the browser.
  let SocialService;
  try {
    // For Firefox 51+
    SocialService = Cu.import("resource:///modules/SocialService.jsm", {}).SocialService;
  } catch (e) {
    SocialService = Cu.import("resource://gre/modules/SocialService.jsm", {}).SocialService;
  }

  let origin = "https://getpocket.com";
  SocialService.getProvider(origin, provider => {
    if (provider) {
      let pref = "social.backup.getpocket-com";
      if (!Services.prefs.prefHasUserValue(pref)) {
        let str = Cc["@mozilla.org/supports-string;1"].
                  createInstance(Ci.nsISupportsString);
        str.data = JSON.stringify(provider.manifest);
        Services.prefs.setComplexValue(pref, Ci.nsISupportsString, str);
        SocialService.uninstallProvider(origin, () => {});
      }
    }
  });

}

// PocketContextMenu
// When the context menu is opened check if we need to build and enable pocket UI.
var PocketContextMenu = {
  init: function() {
    Services.obs.addObserver(this, "on-build-contextmenu", false);
  },
  shutdown: function() {
    Services.obs.removeObserver(this, "on-build-contextmenu");
    // loop through windows and remove context menus
    // iterate through all windows and add pocket to them
    for (let win of CustomizableUI.windows) {
      let document = win.document;
      for (let id of ["context-pocket", "context-savelinktopocket"]) {
        let element = document.getElementById(id);
        if (element)
          element.remove();
      }
    }
  },
  observe: function(aSubject, aTopic, aData) {
    let subject = aSubject.wrappedJSObject;
    let document = subject.menu.ownerDocument;
    let pocketEnabled = CustomizableUI.getPlacementOfWidget("pocket-button");

    let showSaveCurrentPageToPocket = !(subject.onTextInput || subject.onLink ||
                                        subject.isContentSelected || subject.onImage ||
                                        subject.onCanvas || subject.onVideo || subject.onAudio);
    let targetUrl = subject.onLink ? subject.linkUrl : subject.pageUrl;
    let targetURI = Services.io.newURI(targetUrl, null, null);
    let canPocket = pocketEnabled && (targetURI.schemeIs("http") || targetURI.schemeIs("https") ||
                    (targetURI.schemeIs("about") && ReaderMode.getOriginalUrl(targetUrl)));

    let showSaveLinkToPocket = canPocket && !showSaveCurrentPageToPocket && subject.onLink;

    // create menu entries if necessary
    let menu = document.getElementById("context-pocket");
    if (!menu) {
      menu = createElementWithAttrs(document, "menuitem", {
        "id": "context-pocket",
        "label": gPocketBundle.GetStringFromName("saveToPocketCmd.label"),
        "accesskey": gPocketBundle.GetStringFromName("saveToPocketCmd.accesskey"),
        "oncommand": "Pocket.savePage(gContextMenu.browser, gContextMenu.browser.currentURI.spec, gContextMenu.browser.contentTitle);"
      });
      let sibling = document.getElementById("context-savepage");
      if (sibling.nextSibling) {
        sibling.parentNode.insertBefore(menu, sibling.nextSibling);
      } else {
        sibling.parentNode.appendChild(menu);
      }
    }
    menu.hidden = !(canPocket && showSaveCurrentPageToPocket);

    menu = document.getElementById("context-savelinktopocket");
    if (!menu) {
      menu = createElementWithAttrs(document, "menuitem", {
        "id": "context-savelinktopocket",
        "label": gPocketBundle.GetStringFromName("saveLinkToPocketCmd.label"),
        "accesskey": gPocketBundle.GetStringFromName("saveLinkToPocketCmd.accesskey"),
        "oncommand": "Pocket.savePage(gContextMenu.browser, gContextMenu.linkURL);"
      });
      let sibling = document.getElementById("context-savelink");
      if (sibling.nextSibling) {
        sibling.parentNode.insertBefore(menu, sibling.nextSibling);
      } else {
        sibling.parentNode.appendChild(menu);
      }
    }
    menu.hidden = !showSaveLinkToPocket;
  }
}

// PocketReader
// Listen for reader mode setup and add our button to the reader toolbar
var PocketReader = {
  _hidden: true,
  get hidden() {
    return this._hidden;
  },
  set hidden(hide) {
    hide = !!hide;
    if (hide === this._hidden)
      return;
    this._hidden = hide;
    this.update();
  },
  startup: function() {
    // Setup the listeners, update will be called when the widget is added,
    // no need to do that now.
    let mm = Services.mm;
    mm.addMessageListener("Reader:OnSetup", this);
    mm.addMessageListener("Reader:Clicked-pocket-button", this);
  },
  shutdown: function() {
    let mm = Services.mm;
    mm.removeMessageListener("Reader:OnSetup", this);
    mm.removeMessageListener("Reader:Clicked-pocket-button", this);
    this.hidden = true;
  },
  update: function() {
    if (this.hidden) {
      Services.mm.broadcastAsyncMessage("Reader:RemoveButton", { id: "pocket-button" });
    } else {
      Services.mm.broadcastAsyncMessage("Reader:AddButton",
                               { id: "pocket-button",
                                 title: gPocketBundle.GetStringFromName("pocket-button.tooltiptext"),
                                 image: "chrome://pocket/content/panels/img/pocket.svg#pocket-mark" });
    }
  },
  receiveMessage: function(message) {
    switch (message.name) {
      case "Reader:OnSetup": {
        // Tell the reader about our button.
        if (this.hidden)
          break;
        message.target.messageManager.
          sendAsyncMessage("Reader:AddButton", { id: "pocket-button",
                                                 title: gPocketBundle.GetStringFromName("pocket-button.tooltiptext"),
                                                 image: "chrome://pocket/content/panels/img/pocket.svg#pocket-mark"});
        break;
      }
      case "Reader:Clicked-pocket-button": {
        let doc = message.target.ownerDocument;
        let pocketWidget = doc.getElementById("pocket-button");
        let placement = CustomizableUI.getPlacementOfWidget("pocket-button");
        if (placement) {
          if (placement.area == CustomizableUI.AREA_PANEL) {
            doc.defaultView.PanelUI.show().then(function() {
              // The DOM node might not exist yet if the panel wasn't opened before.
              pocketWidget = doc.getElementById("pocket-button");
              pocketWidget.doCommand();
            });
          } else {
            pocketWidget.doCommand();
          }
        }
        break;
      }
    }
  }
}


function pktUIGetter(prop, window) {
  return {
    get: function() {
      // delete any getters for properties loaded from main.js so we only load main.js once
      delete window.pktUI;
      delete window.pktApi;
      delete window.pktUIMessaging;
      Services.scriptloader.loadSubScript("chrome://pocket/content/main.js", window);
      return window[prop];
    },
    configurable: true,
    enumerable: true
  };
}

var PocketOverlay = {
  startup: function(reason) {
    let styleSheetService = Cc["@mozilla.org/content/style-sheet-service;1"]
                              .getService(Ci.nsIStyleSheetService);
    this._sheetType = styleSheetService.AUTHOR_SHEET;
    this._cachedSheet = styleSheetService.preloadSheet(gPocketStyleURI,
                                                       this._sheetType);
    Services.ppmm.loadProcessScript(PROCESS_SCRIPT, true);
    PocketReader.startup();
    CustomizableUI.addListener(this);
    CreatePocketWidget(reason);
    PocketContextMenu.init();

    for (let win of CustomizableUI.windows) {
      this.onWindowOpened(win);
    }
  },
  shutdown: function(reason) {
    let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"]
                 .getService(Ci.nsIMessageBroadcaster);
    ppmm.broadcastAsyncMessage("PocketShuttingDown");
    // Although the ppmm loads the scripts into the chrome process as well,
    // we need to manually unregister here anyway to ensure these aren't part
    // of the chrome process and avoid errors.
    AboutPocket.aboutSaved.unregister();
    AboutPocket.aboutSignup.unregister();

    CustomizableUI.removeListener(this);
    for (let window of CustomizableUI.windows) {
      for (let id of ["panelMenu_pocket", "menu_pocket", "BMB_pocket",
                      "panelMenu_pocketSeparator", "menu_pocketSeparator",
                      "BMB_pocketSeparator"]) {
        let element = window.document.getElementById(id);
        if (element)
          element.remove();
      }
      this.removeStyles(window);
      // remove script getters/objects
      delete window.Pocket;
      delete window.pktApi;
      delete window.pktUI;
      delete window.pktUIMessaging;
    }
    CustomizableUI.destroyWidget("pocket-button");
    PocketContextMenu.shutdown();
    PocketReader.shutdown();
  },
  onWindowOpened: function(window) {
    if (window.hasOwnProperty("pktUI"))
      return;
    this.setWindowScripts(window);
    this.addStyles(window);
    this.updateWindow(window);
  },
  setWindowScripts: function(window) {
    XPCOMUtils.defineLazyModuleGetter(window, "Pocket",
                                      "chrome://pocket/content/Pocket.jsm");
    // Can't use XPCOMUtils for these because the scripts try to define the variables
    // on window, and so the defineProperty inside defineLazyGetter fails.
    Object.defineProperty(window, "pktApi", pktUIGetter("pktApi", window));
    Object.defineProperty(window, "pktUI", pktUIGetter("pktUI", window));
    Object.defineProperty(window, "pktUIMessaging", pktUIGetter("pktUIMessaging", window));
  },
  // called for each window as it is opened
  updateWindow: function(window) {
    // insert our three menu items
    let document = window.document;
    let hidden = !CustomizableUI.getPlacementOfWidget("pocket-button");

    // add to bookmarksMenu
    let sib = document.getElementById("menu_bookmarkThisPage");
    if (sib && !document.getElementById("menu_pocket")) {
      let menu = createElementWithAttrs(document, "menuitem", {
        "id": "menu_pocket",
        "label": gPocketBundle.GetStringFromName("pocketMenuitem.label"),
        "class": "menuitem-iconic", // OSX only
        "oncommand": "openUILink(Pocket.listURL, event);",
        "hidden": hidden
      });
      let sep = createElementWithAttrs(document, "menuseparator", {
        "id": "menu_pocketSeparator",
        "hidden": hidden
      });
      sib.parentNode.insertBefore(menu, sib);
      sib.parentNode.insertBefore(sep, sib);
    }

    // add to bookmarks-menu-button
    sib = document.getElementById("BMB_bookmarksToolbar");
    if (sib && !document.getElementById("BMB_pocket")) {
      let menu = createElementWithAttrs(document, "menuitem", {
        "id": "BMB_pocket",
        "label": gPocketBundle.GetStringFromName("pocketMenuitem.label"),
        "class": "menuitem-iconic bookmark-item subviewbutton",
        "oncommand": "openUILink(Pocket.listURL, event);",
        "hidden": hidden
      });
      let sep = createElementWithAttrs(document, "menuseparator", {
        "id": "BMB_pocketSeparator",
        "hidden": hidden
      });
      sib.parentNode.insertBefore(menu, sib);
      sib.parentNode.insertBefore(sep, sib);
    }

    // add to PanelUI-bookmarks
    sib = document.getElementById("panelMenuBookmarkThisPage");
    if (sib && !document.getElementById("panelMenu_pocket")) {
      let menu = createElementWithAttrs(document, "toolbarbutton", {
        "id": "panelMenu_pocket",
        "label": gPocketBundle.GetStringFromName("pocketMenuitem.label"),
        "class": "subviewbutton cui-withicon",
        "oncommand": "openUILink(Pocket.listURL, event);",
        "hidden": hidden
      });
      let sep = createElementWithAttrs(document, "toolbarseparator", {
        "id": "panelMenu_pocketSeparator",
        "hidden": hidden
      });
      // nextSibling is no-id toolbarseparator
      // insert separator first then button
      sib = sib.nextSibling;
      sib.parentNode.insertBefore(sep, sib);
      sib.parentNode.insertBefore(menu, sib);
    }
  },
  onWidgetAfterDOMChange: function(aWidgetNode) {
    if (aWidgetNode.id != "pocket-button") {
      return;
    }
    let doc = aWidgetNode.ownerDocument;
    let hidden = !CustomizableUI.getPlacementOfWidget("pocket-button");
    for (let prefix of ["panelMenu_", "menu_", "BMB_"]) {
      let element = doc.getElementById(prefix + "pocket");
      if (element) {
        element.hidden = hidden;
        doc.getElementById(prefix + "pocketSeparator").hidden = hidden;
      }
    }
    // enable or disable reader button
    PocketReader.hidden = hidden;
  },

  addStyles: function(win) {
    let utils = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils);
    utils.addSheet(this._cachedSheet, this._sheetType);
  },

  removeStyles: function(win) {
    let utils = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils);
    utils.removeSheet(gPocketStyleURI, this._sheetType);
  }

}

// use enabled pref as a way for tests (e.g. test_contextmenu.html) to disable
// the addon when running.
function prefObserver(aSubject, aTopic, aData) {
  let enabled = Services.prefs.getBoolPref("extensions.pocket.enabled");
  if (enabled)
    PocketOverlay.startup(ADDON_ENABLE);
  else
    PocketOverlay.shutdown(ADDON_DISABLE);
}

function startup(data, reason) {
  AddonManager.getAddonByID("isreaditlater@ideashower.com", addon => {
    if (addon && addon.isActive)
      return;
    setDefaultPrefs();
    // migrate enabled pref
    if (Services.prefs.prefHasUserValue("browser.pocket.enabled")) {
      Services.prefs.setBoolPref("extensions.pocket.enabled", Services.prefs.getBoolPref("browser.pocket.enabled"));
      Services.prefs.clearUserPref("browser.pocket.enabled");
    }
    // watch pref change and enable/disable if necessary
    Services.prefs.addObserver("extensions.pocket.enabled", prefObserver, false);
    if (!Services.prefs.getBoolPref("extensions.pocket.enabled"))
      return;
    PocketOverlay.startup(reason);
  });
}

function shutdown(data, reason) {
  // For speed sake, we should only do a shutdown if we're being disabled.
  // On an app shutdown, just let it fade away...
  if (reason != APP_SHUTDOWN) {
    Services.prefs.removeObserver("extensions.pocket.enabled", prefObserver);
    PocketOverlay.shutdown(reason);
  }
}

function install() {
}

function uninstall() {
}