forked from orbitbot/chrome-extensions-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
365 lines (333 loc) · 11.2 KB
/
background.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
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
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* Maps policy names to the root node that they affect.
*/
var policyToNodeId = {
'Bookmarks Bar': '1',
'Other Bookmarks': '2'
};
/**
* A function that fixes a URL. Turns e.g. "google.com" into
* "http://google.com/". This is used to correctly match against the
* canonicalized URLs stored in bookmarks created with the bookmarks API.
*/
var fixURL = (function() {
// An "a" element is used to parse the given URL and build the fixed version.
var a = document.createElement('a');
return function(url) {
// Preserve null, undefined, etc.
if (!url)
return url;
a.href = url;
// Handle cases like "google.com", which will be relative to the extension.
if (a.protocol === 'chrome-extension:' &&
url.substr(0, 17) !== 'chrome-extension:') {
a.href = 'http://' + url;
}
return a.href;
}
})();
/**
* A CallbackChain can be used to wrap other callbacks and perform a list of
* actions at the end, once all the wrapped callbacks have been invoked.
*/
var CallbackChain = function() {
this._count = 0;
this._callbacks = [];
}
CallbackChain.prototype.push = function(callback) {
this._callbacks.push(callback);
}
CallbackChain.prototype.wrap = function(callback) {
var self = this;
self._count++;
return function() {
if (callback)
callback.apply(null, arguments);
self._count--;
if (self._count == 0) {
for (var i = 0; i < self._callbacks.length; ++i)
self._callbacks[i]();
}
}
}
/**
* Represents a managed bookmark.
*/
var Node = function(nodesMap, id, title, url) {
this._nodesMap = nodesMap;
this._id = id;
this._title = title;
if (url !== undefined)
this._url = url;
else
this._children = [];
if (id)
this._nodesMap[id] = this;
}
Node.prototype.isRoot = function() {
return this._id in [ '0', '1', '2' ];
}
Node.prototype.getIndex = function() {
return this._nodesMap[this._parentId]._children.indexOf(this);
}
Node.prototype.appendChild = function(node) {
node._parentId = this._id;
this._children.push(node);
}
Node.prototype.droppedFromParent = function() {
// Remove |this| and its children from the |nodesMap|.
var nodesMap = this._nodesMap;
var removeFromNodesMap = function(node) {
delete nodesMap[node._id];
(node._children || []).forEach(removeFromNodesMap);
}
removeFromNodesMap(this);
if (this._children)
chrome.bookmarks.removeTree(this._id);
else
chrome.bookmarks.remove(this._id);
}
Node.prototype.matches = function(bookmark) {
return this._title === bookmark.title &&
this._url === bookmark.url &&
typeof this._children === typeof bookmark.children;
}
/**
* Makes this node's children match |wantedChildren|.
*/
Node.prototype.updateChildren = function(wantedChildren, callbackChain) {
// Rebuild the list of children to match |wantedChildren|.
var currentChildren = this._children;
this._children = [];
for (var i = 0; i < wantedChildren.length; ++i) {
var currentChild = currentChildren[i];
var wantedChild = wantedChildren[i];
wantedChild.url = fixURL(wantedChild.url);
if (currentChild && currentChild.matches(wantedChild)) {
this.appendChild(currentChild);
if (wantedChild.children)
currentChild.updateChildren(wantedChild.children, callbackChain);
} else {
// This child is either missing, invalid or misplaced; drop it and
// generate it again. Note that the actual dropping is delayed so that
// bookmarks.onRemoved is triggered after the changes have been persisted.
if (currentChild)
callbackChain.push(currentChild.droppedFromParent.bind(currentChild));
// The "id" comes with the callback from bookmarks.create() but the Node
// is created now so that the child is placed at the right position.
var newChild = new Node(
this._nodesMap, undefined, wantedChild.title, wantedChild.url);
this.appendChild(newChild);
chrome.bookmarks.create({
'parentId': this._id,
'title': newChild._title,
'url': newChild._url,
'index': i
}, callbackChain.wrap((function(wantedChild, newChild, createdNode) {
newChild._id = createdNode.id;
newChild._nodesMap[newChild._id] = newChild;
if (wantedChild.children)
newChild.updateChildren(wantedChild.children, callbackChain);
}).bind(null, wantedChild, newChild)));
}
}
// Drop all additional bookmarks past the end that are not wanted anymore.
if (currentChildren.length > wantedChildren.length) {
var chainCounter = callbackChain.wrap();
currentChildren.slice(wantedChildren.length).forEach(function(child) {
callbackChain.push(child.droppedFromParent.bind(child));
});
// This wrapped nop makes sure that the callbacks appended to the chain
// execute if nothing else was wrapped.
chainCounter();
}
}
/**
* Creates new nodes in the bookmark model to represent this Node and its
* children.
*/
Node.prototype.regenerate = function(parentId, index, callbackChain) {
var self = this;
chrome.bookmarks.create({
'parentId': parentId,
'title': self._title,
'url': self._url,
'index': index
}, callbackChain.wrap(function(newNode) {
delete self._nodesMap[self._id];
self._id = newNode.id;
self._parentId = newNode.parentId;
self._nodesMap[self._id] = self;
(self._children || []).forEach(function(child, i) {
child.regenerate(self._id, i, callbackChain);
});
}));
}
/**
* Moves this node to the correct position in the model.
* |currentParentId| and |currentIndex| indicate the current position in
* the model, which may not match the expected position.
*/
Node.prototype.moveInModel = function(currentParentId, currentIndex, callback) {
var index = this.getIndex();
if (currentParentId == this._parentId) {
if (index == currentIndex) {
// Nothing to do.
callback();
return;
} else if (index > currentIndex) {
// A bookmark moved is inserted at the new position before it is removed
// from the previous position. So when moving forward in the same parent,
// the index must be adjusted by one from the desired index.
++index;
}
}
chrome.bookmarks.move(this._id, {
'parentId': this._parentId,
'index': index
}, callback);
}
/**
* Moves any misplaced child nodes into their expected positions.
*/
Node.prototype.reorderChildren = function() {
var self = this;
chrome.bookmarks.getChildren(self._id, function(currentOrder) {
for (var i = 0; i < currentOrder.length; ++i) {
var node = currentOrder[i];
var child = self._nodesMap[node.id];
if (child && child.getIndex() != i) {
// Check again after moving this child.
child.moveInModel(
node.parentId, node.index, self.reorderChildren.bind(self));
return;
}
}
});
}
var serializeNode = function(node) {
var result = {
'id': node._id,
'title': node._title
}
if (node._url)
result['url'] = node._url;
else
result['children'] = node._children.map(serializeNode);
return result;
}
var unserializeNode = function(nodesMap, node) {
var result = new Node(nodesMap, node['id'], node['title'], node['url']);
if (node.children) {
node.children.forEach(function(child) {
result.appendChild(unserializeNode(nodesMap, child));
});
}
return result;
}
/**
* Tracks all the managed bookmarks, and persists the known state so that
* managed bookmarks can be updated after restarts.
*/
var ManagedBookmarkTree = function() {
// Maps a string id to its Node. Used to lookup an entry by ID.
this._nodesMap = {};
this._root = new Node(this._nodesMap, '0', '');
this._root.appendChild(new Node(this._nodesMap, '1', 'Bookmarks Bar'));
this._root.appendChild(new Node(this._nodesMap, '2', 'Other Bookmarks'));
}
ManagedBookmarkTree.prototype.store = function() {
chrome.storage.local.set({
'ManagedBookmarkTree': serializeNode(this._root)
});
}
ManagedBookmarkTree.prototype.load = function(callback) {
var self = this;
chrome.storage.local.get('ManagedBookmarkTree', function(result) {
if (result.hasOwnProperty('ManagedBookmarkTree')) {
self._nodesMap = {};
self._root = unserializeNode(self._nodesMap,
result['ManagedBookmarkTree']);
}
callback();
});
}
ManagedBookmarkTree.prototype.getById = function(id) {
return this._nodesMap[id];
}
ManagedBookmarkTree.prototype.update = function(rootNodeId, currentPolicy) {
// Note that the |callbackChain| is only invoked if a callback is wrapped,
// otherwise its callbacks are never invoked. So store() is called only if
// bookmarks.create() is actually used.
var callbackChain = new CallbackChain();
callbackChain.push(this.store.bind(this));
this._nodesMap[rootNodeId].updateChildren(currentPolicy || [], callbackChain);
}
var tree = new ManagedBookmarkTree();
chrome.runtime.onInstalled.addListener(function() {
// Enforce the initial policy.
// This load() should be empty on the first install, but is useful during
// development to handle reloads.
tree.load(function() {
chrome.storage.managed.get(function(policy) {
Object.keys(policyToNodeId).forEach(function(policyName) {
tree.update(policyToNodeId[policyName], policy[policyName]);
});
});
});
});
// Start observing policy changes. The tree is reloaded since this may be
// called back while the page was inactive.
chrome.storage.onChanged.addListener(function(changes, namespace) {
if (namespace !== 'managed')
return;
tree.load(function() {
Object.keys(changes).forEach(function(policyName) {
tree.update(policyToNodeId[policyName], changes[policyName].newValue);
});
});
});
// Observe bookmark modifications and revert any modifications made to managed
// bookmarks. The tree is always reloaded in case the events happened while the
// page was inactive.
chrome.bookmarks.onMoved.addListener(function(id, info) {
tree.load(function() {
var managedNode = tree.getById(id);
if (managedNode && !managedNode.isRoot()) {
managedNode.moveInModel(info.parentId, info.index, function(){});
} else {
// Check if the parent node has managed children that need to move.
// Example: moving a non-managed bookmark in front of the managed
// bookmarks.
var parentNode = tree.getById(info.parentId);
if (parentNode)
parentNode.reorderChildren();
}
});
});
chrome.bookmarks.onChanged.addListener(function(id, info) {
tree.load(function() {
var managedNode = tree.getById(id);
if (!managedNode || managedNode.isRoot())
return;
chrome.bookmarks.update(id, {
'title': managedNode._title,
'url': managedNode._url
});
});
});
chrome.bookmarks.onRemoved.addListener(function(id, info) {
tree.load(function() {
var managedNode = tree.getById(id);
if (!managedNode || managedNode.isRoot())
return;
// A new tree.store() is needed at the end because the regenerated nodes
// will have new IDs.
var callbackChain = new CallbackChain();
callbackChain.push(tree.store.bind(tree));
managedNode.regenerate(info.parentId, info.index, callbackChain);
});
});