summaryrefslogtreecommitdiffstats
path: root/browser/extensions/screenshots/background/main.js
blob: 594ba798ee582beee8ef57edceb98d9c44120554 (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
/* 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/. */

/* globals browser, getStrings, selectorLoader, analytics, communication, catcher, log, senderror, startBackground, blobConverters, startSelectionWithOnboarding */

"use strict";

this.main = (function () {
  const exports = {};

  const { incrementCount } = analytics;

  const manifest = browser.runtime.getManifest();
  let backend;

  exports.setBackend = function (newBackend) {
    backend = newBackend;
    backend = backend.replace(/\/*$/, "");
  };

  exports.getBackend = function () {
    return backend;
  };

  communication.register("getBackend", () => {
    return backend;
  });

  for (const permission of manifest.permissions) {
    if (/^https?:\/\//.test(permission)) {
      exports.setBackend(permission);
      break;
    }
  }

  function toggleSelector(tab) {
    return analytics
      .refreshTelemetryPref()
      .then(() => selectorLoader.toggle(tab.id))
      .catch(error => {
        if (
          error.message &&
          /Missing host permission for the tab/.test(error.message)
        ) {
          error.noReport = true;
        }
        error.popupMessage = "UNSHOOTABLE_PAGE";
        throw error;
      });
  }

  // This is called by startBackground.js, where is registered as a click
  // handler for the webextension page action.
  exports.onClicked = catcher.watchFunction(tab => {
    _startShotFlow(tab, "toolbar-button");
  });

  exports.onClickedContextMenu = catcher.watchFunction(tab => {
    _startShotFlow(tab, "context-menu");
  });

  exports.onShortcut = catcher.watchFunction(tab => {
    _startShotFlow(tab, "keyboard-shortcut");
  });

  const _startShotFlow = (tab, inputType) => {
    if (!tab) {
      // Not in a page/tab context, ignore
      return;
    }
    if (!urlEnabled(tab.url)) {
      senderror.showError({
        popupMessage: "UNSHOOTABLE_PAGE",
      });
      return;
    }

    catcher.watchPromise(
      toggleSelector(tab).catch(error => {
        throw error;
      })
    );
  };

  function urlEnabled(url) {
    // Allow screenshots on urls related to web pages in reader mode.
    if (url && url.startsWith("about:reader?url=")) {
      return true;
    }
    if (
      isShotOrMyShotPage(url) ||
      /^(?:about|data|moz-extension):/i.test(url) ||
      isBlacklistedUrl(url)
    ) {
      return false;
    }
    return true;
  }

  function isShotOrMyShotPage(url) {
    // It's okay to take a shot of any pages except shot pages and My Shots
    if (!url.startsWith(backend)) {
      return false;
    }
    const path = url
      .substr(backend.length)
      .replace(/^\/*/, "")
      .replace(/[?#].*/, "");
    if (path === "shots") {
      return true;
    }
    if (/^[^/]{1,4000}\/[^/]{1,4000}$/.test(path)) {
      // Blocks {:id}/{:domain}, but not /, /privacy, etc
      return true;
    }
    return false;
  }

  function isBlacklistedUrl(url) {
    // These specific domains are not allowed for general WebExtension permission reasons
    // Discussion: https://bugzilla.mozilla.org/show_bug.cgi?id=1310082
    // List of domains copied from: https://searchfox.org/mozilla-central/source/browser/app/permissions#18-19
    // Note we disable it here to be informative, the security check is done in WebExtension code
    const badDomains = ["testpilot.firefox.com"];
    let domain = url.replace(/^https?:\/\//i, "");
    domain = domain.replace(/\/.*/, "").replace(/:.*/, "");
    domain = domain.toLowerCase();
    return badDomains.includes(domain);
  }

  communication.register("getStrings", (sender, ids) => {
    return getStrings(ids.map(id => ({ id })));
  });

  communication.register("captureTelemetry", (sender, ...args) => {
    catcher.watchPromise(incrementCount(...args));
  });

  communication.register("openShot", async (sender, { url, copied }) => {
    if (copied) {
      const id = crypto.randomUUID();
      const [title, message] = await getStrings([
        { id: "screenshots-notification-link-copied-title" },
        { id: "screenshots-notification-link-copied-details" },
      ]);
      return browser.notifications.create(id, {
        type: "basic",
        iconUrl: "chrome://browser/content/screenshots/copied-notification.svg",
        title,
        message,
      });
    }
    return null;
  });

  communication.register("copyShotToClipboard", async (sender, blob) => {
    let buffer = await blobConverters.blobToArray(blob);
    await browser.clipboard.setImageData(buffer, blob.type.split("/", 2)[1]);

    const [title, message] = await getStrings([
      { id: "screenshots-notification-image-copied-title" },
      { id: "screenshots-notification-image-copied-details" },
    ]);

    catcher.watchPromise(incrementCount("copy"));
    return browser.notifications.create({
      type: "basic",
      iconUrl: "chrome://browser/content/screenshots/copied-notification.svg",
      title,
      message,
    });
  });

  communication.register("downloadShot", (sender, info) => {
    // 'data:' urls don't work directly, let's use a Blob
    // see http://stackoverflow.com/questions/40269862/save-data-uri-as-file-using-downloads-download-api
    const blob = blobConverters.dataUrlToBlob(info.url);
    const url = URL.createObjectURL(blob);
    let downloadId;
    const onChangedCallback = catcher.watchFunction(function (change) {
      if (!downloadId || downloadId !== change.id) {
        return;
      }
      if (change.state && change.state.current !== "in_progress") {
        URL.revokeObjectURL(url);
        browser.downloads.onChanged.removeListener(onChangedCallback);
      }
    });
    browser.downloads.onChanged.addListener(onChangedCallback);
    catcher.watchPromise(incrementCount("download"));
    return browser.windows.getLastFocused().then(windowInfo => {
      return browser.downloads
        .download({
          url,
          incognito: windowInfo.incognito,
          filename: info.filename,
        })
        .catch(error => {
          // We are not logging error message when user cancels download
          if (error && error.message && !error.message.includes("canceled")) {
            log.error(error.message);
          }
        })
        .then(id => {
          downloadId = id;
        });
    });
  });

  communication.register("abortStartShot", () => {
    // Note, we only show the error but don't report it, as we know that we can't
    // take shots of these pages:
    senderror.showError({
      popupMessage: "UNSHOOTABLE_PAGE",
    });
  });

  // A Screenshots page wants us to start/force onboarding
  communication.register("requestOnboarding", sender => {
    return startSelectionWithOnboarding(sender.tab);
  });

  communication.register("getPlatformOs", () => {
    return catcher.watchPromise(
      browser.runtime.getPlatformInfo().then(platformInfo => {
        return platformInfo.os;
      })
    );
  });

  // This allows the web site show notifications through sitehelper.js
  communication.register("showNotification", (sender, notification) => {
    return browser.notifications.create(notification);
  });

  return exports;
})();