-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlegacyHelper.js
270 lines (224 loc) · 11.4 KB
/
legacyHelper.js
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
"use strict";
const { utils: Cu , classes: Cc, interfaces: Ci} = Components;
const globalMessageManager = Cc["@mozilla.org/globalmessagemanager;1"].getService();
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
//ChromeUtils.import("resource://gre/modules/Timer.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
ConsoleAPI: "resource://gre/modules/Console.jsm",
FileUtils: "resource://gre/modules/FileUtils.jsm",
ZipUtils: "resource://gre/modules/ZipUtils.jsm",
SessionStore: "resource:///modules/sessionstore/SessionStore.jsm"
});
XPCOMUtils.defineLazyServiceGetter(this, "styleSheetService",
"@mozilla.org/content/style-sheet-service;1",
"nsIStyleSheetService");
function remove(array, value) {
const index = array.indexOf(value);
if (index !== -1) {
array.splice(index, 1);
}
}
function ArrayEnumerator(aItems) {
this._index = 0;
this._contents = aItems;
}
ArrayEnumerator.prototype = {
_index: 0,
hasMoreElements() {
return this._index < this._contents.length;
},
getNext() {
return this._contents[this._index++];
}
};
this.legacy = class extends ExtensionAPI {
getAPI(context) {
const loadedDelayedFrameScripts = [];
const unloadMessages = [];
const loadedBootstrapSandboxes = {};
const loadedStyleSheets = [];
const chromeOverrideRelativePaths = [];
const temporaryFolders = [];
let chromeOverrideProvider;
const messageSender = {
_listeners: [],
sendMessage: function (message) {
const responses = [];
for (const listener of this._listeners) {
responses.push(listener.async(message));
}
// Only the first responder is used, other responses are ignored
return Promise.race(responses);
},
addListener(fire) {
this._listeners.push(fire);
},
removeListener(fire) {
remove(this._listeners, fire);
}
}
const api = {
legacy: {
async loadFrameScript(uri, allowDelayedLoad, runInGlobalScope) {
globalMessageManager.loadFrameScript(uri, allowDelayedLoad, runInGlobalScope);
if (allowDelayedLoad) {
loadedDelayedFrameScripts.push(uri);
}
},
async removeDelayedFrameScript(uri) {
globalMessageManager.removeDelayedFrameScript(uri);
// Remove from the list of loaded scripts to unload at extension disable
remove(loadedDelayedFrameScripts, uri);
},
async addUnloadMessage(messageName, data) {
unloadMessages.push({ name: messageName, data: data });
},
async broadcastAsyncMessage(messageName, data) {
globalMessageManager.broadcastAsyncMessage(messageName, data);
},
async loadBootstrapScript(uri) {
const runStartup = function (sandbox, reason) {
try {
const startupFunction = sandbox["startup"];
if (!startupFunction) {
console.log("error: startup() function not present");
}
startupFunction.call(sandbox, context.extension.addonData, reason, messageSender);
} catch (e) {
console.log("error calling startup() function: ", e);
return;
}
}
const existingScriptSandbox = loadedBootstrapSandboxes[uri];
if (existingScriptSandbox) {
runStartup(existingScriptSandbox, null);
}
const aId = context.extension.id;
const principal = Cc["@mozilla.org/systemprincipal;1"].createInstance(Ci.nsIPrincipal);
const sandbox = new Cu.Sandbox(principal, {
sandboxName: uri,
addonId: aId,
wantGlobalProperties: ["ChromeUtils"],
metadata: { addonID: aId, URI: uri }
});
// Define a console
XPCOMUtils.defineLazyGetter(
sandbox, "console",
() => new ConsoleAPI({ consoleID: "addon/" + aId }));
sandbox.__SCRIPT_URI_SPEC__ = uri;
Services.scriptloader.loadSubScript(uri, sandbox);
runStartup(sandbox, context.extension.startupReason);
let test = sandbox["shutdown"];
if (test) {
loadedBootstrapSandboxes[uri] = sandbox;
} else {
console.log("warning: shutdown() function not present");
}
},
async callFunctionInBootstrapScript(uri, functionName, data) {
const existingScriptSandbox = loadedBootstrapSandboxes[uri];
if (existingScriptSandbox) {
try {
const fun = existingScriptSandbox[functionName];
if (!fun) {
return Promise.reject(new Error("error: " + functionName + " function not present"));
}
const clonedDetails = Cu.cloneInto(data, existingScriptSandbox);
return Promise.resolve(fun.call(existingScriptSandbox, clonedDetails));
} catch (e) {
return Promise.reject(new Error("error calling: " + functionName, e));
}
} else {
return Promise.reject(new Error("bootstrap script not found: " + uri));
}
},
onBootstrapScriptMessage: new ExtensionCommon.EventManager(context, "legacy.onBootstrapScriptMessage", fire => {
messageSender.addListener(fire);
return () => {
messageSender.removeListener(fire);
};
}).api(),
async loadStyleSheet(uri, type) {
const styleSheetUri = Services.io.newURI(uri, null, null);
styleSheetService.loadAndRegisterSheet(styleSheetUri, type);
loadedStyleSheets.push({ uri: styleSheetUri, type: type });
},
async isStyleSheetLoaded(uri, type) {
return styleSheetService.sheetRegistered(Services.io.newURI(uri, null, null), type);
},
async unloadStyleSheet(uri, type) {
styleSheetService.unregisterSheet(Services.io.newURI(uri, null, null), type);
},
async registerChromeOverride(path, reloadSession) {
chromeOverrideRelativePaths.push(path);
if (!chromeOverrideProvider) {
let rootPath;
if (context.extension.rootURI instanceof Ci.nsIFileURL) {
rootPath = context.extension.rootURI.file;
} else {
// This is a packaged extension, and needs to be unpacked before chrome files can be read
const tempFolder = FileUtils.getFile("TmpD", [context.extension.id]);
tempFolder.createUnique(Components.interfaces.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
ZipUtils.extractFiles(context.extension.addonData.installPath, tempFolder);
temporaryFolders.push(tempFolder); // Store the temp folder for cleanup on shutdown
// Use the extracted location as the root path instead
rootPath = tempFolder;
}
chromeOverrideProvider = {
getFiles: function (prop) {
if (prop === "AChromDL") {
return new ArrayEnumerator(chromeOverrideRelativePaths.map(relativePath => {
const path = rootPath.clone();
path.appendRelativePath(relativePath);
return path;
}));
}
},
QueryInterface: XPCOMUtils.generateQI([Ci.nsIDirectoryServiceProvider2])
};
Services.dirsvc.registerProvider(chromeOverrideProvider);
if (reloadSession) {
const state = SessionStore.getBrowserState();
Services.wm.getMostRecentWindow("navigator:browser").open("about:blank");
SessionStore.setBrowserState(state);
}
}
},
// Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=1460555
async workaround1406055() {
if (context.extension.startupReason === "APP_STARTUP") {
const {AddonManager} = ChromeUtils.import("resource://gre/modules/AddonManager.jsm");
AddonManager.getAddonsByTypes(["extension"]).then(addons => {
for (const addon of addons) {
if (addon.dependencies.includes("[email protected]")) {
if (addon.isActive || addon.isActive === undefined) {
console.log("Legacy Helper reloading addon: " + addon.name, addon);
addon.reload();
} else {
console.log("Skipping addon: " + addon.name, addon.isActive, addon);
}
} else {
console.log("Skipping non-legacy addon: " + addon.name);
}
}
});
}
},
close: function () {
loadedDelayedFrameScripts.forEach(uri => globalMessageManager.removeDelayedFrameScript(uri));
unloadMessages.forEach(unloadMessage => globalMessageManager.broadcastAsyncMessage(unloadMessage.name, unloadMessage.data));
Object.values(loadedBootstrapSandboxes).forEach(sandbox => sandbox["shutdown"].call(sandbox, context.extension.addonData, context.extension.shutdownReason));
loadedStyleSheets.forEach(styleSheet => styleSheetService.unregisterSheet(styleSheet.uri, styleSheet.type));
temporaryFolders.forEach(tempFolder => tempFolder.remove(true));
if (chromeOverrideProvider) {
Services.dirsvc.unregisterProvider(chromeOverrideProvider);
chromeOverrideProvider = null;
}
}
}
};
context.extension.callOnClose(api.legacy);
return api;
}
}