BookmarksPolicies.jsm 9.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
/* 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";

/*
 * A Bookmark object received through the policy engine will be an
 * object with the following properties:
 *
11
 * - URL (URL)
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 *   (required) The URL for this bookmark
 *
 * - Title (string)
 *   (required) The title for this bookmark
 *
 * - Placement (string)
 *   (optional) Either "toolbar" or "menu". If missing or invalid,
 *   "toolbar" will be used
 *
 * - Folder (string)
 *   (optional) The name of the folder to put this bookmark into.
 *   If present, a folder with this name will be created in the
 *   chosen placement above, and the bookmark will be created there.
 *   If missing, the bookmark will be created directly into the
 *   chosen placement.
 *
28
 * - Favicon (URL)
29
30
31
32
33
34
35
36
 *   (optional) An http:, https: or data: URL with the favicon.
 *   If possible, we recommend against using this property, in order
 *   to keep the json file small.
 *   If a favicon is not provided through the policy, it will be loaded
 *   naturally after the user first visits the bookmark.
 *
 *
 * Note: The Policy Engine automatically converts the strings given to
37
 * the URL and favicon properties into a URL object.
38
39
40
41
 *
 * The schema for this object is defined in policies-schema.json.
 */

42
43
44
45
const { XPCOMUtils } = ChromeUtils.import(
  "resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
46

47
48
49
50
51
ChromeUtils.defineModuleGetter(
  this,
  "PlacesUtils",
  "resource://gre/modules/PlacesUtils.jsm"
);
52
53
54
55

const PREF_LOGLEVEL = "browser.policies.loglevel";

XPCOMUtils.defineLazyGetter(this, "log", () => {
56
  let { ConsoleAPI } = ChromeUtils.import("resource://gre/modules/Console.jsm");
57
58
59
60
61
62
63
64
65
  return new ConsoleAPI({
    prefix: "BookmarksPolicies.jsm",
    // tip: set maxLogLevel to "debug" and use log.debug() to create detailed
    // messages during development. See LOG_LEVELS in Console.jsm for details.
    maxLogLevel: "error",
    maxLogLevelPref: PREF_LOGLEVEL,
  });
});

66
this.EXPORTED_SYMBOLS = ["BookmarksPolicies"];
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

this.BookmarksPolicies = {
  // These prefixes must only contain characters
  // allowed by PlacesUtils.isValidGuid
  BOOKMARK_GUID_PREFIX: "PolB-",
  FOLDER_GUID_PREFIX: "PolF-",

  /*
   * Process the bookmarks specified by the policy engine.
   *
   * @param param
   *        This will be an array of bookmarks objects, as
   *        described on the top of this file.
   */
  processBookmarks(param) {
    calculateLists(param).then(async function addRemoveBookmarks(results) {
      for (let bookmark of results.add.values()) {
        await insertBookmark(bookmark).catch(log.error);
      }
      for (let bookmark of results.remove.values()) {
        await PlacesUtils.bookmarks.remove(bookmark).catch(log.error);
      }
      for (let bookmark of results.emptyFolders.values()) {
        await PlacesUtils.bookmarks.remove(bookmark).catch(log.error);
      }

      gFoldersMapPromise.then(map => map.clear());
    });
95
  },
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
};

/*
 * This function calculates the differences between the existing bookmarks
 * that are managed by the policy engine (which are known through a guid
 * prefix) and the specified bookmarks in the policy file.
 * They can differ if the policy file has changed.
 *
 * @param specifiedBookmarks
 *        This will be an array of bookmarks objects, as
 *        described on the top of this file.
 */
async function calculateLists(specifiedBookmarks) {
  // --------- STEP 1 ---------
  // Build two Maps (one with the existing bookmarks, another with
  // the specified bookmarks), to make iteration quicker.

  // LIST A
  // MAP of url (string) -> bookmarks objects from the Policy Engine
  let specifiedBookmarksMap = new Map();
  for (let bookmark of specifiedBookmarks) {
117
    specifiedBookmarksMap.set(bookmark.URL.href, bookmark);
118
119
120
121
122
123
124
  }

  // LIST B
  // MAP of url (string) -> bookmarks objects from Places
  let existingBookmarksMap = new Map();
  await PlacesUtils.bookmarks.fetch(
    { guidPrefix: BookmarksPolicies.BOOKMARK_GUID_PREFIX },
125
    bookmark => existingBookmarksMap.set(bookmark.url.href, bookmark)
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
  );

  // --------- STEP 2 ---------
  //
  //     /=====/====\=====\
  //    /     /      \     \
  //    |     |      |     |
  //    |  A  |  {}  |  B  |
  //    |     |      |     |
  //    \     \      /     /
  //     \=====\====/=====/
  //
  // Find the intersection of the two lists. Items in the intersection
  // are removed from the original lists.
  //
  // The items remaining in list A are new bookmarks to be added.
  // The items remaining in list B are old bookmarks to be removed.
  //
  // There's nothing to do with items in the intersection, so there's no
  // need to keep track of them.
  //
  // BONUS: It's necessary to keep track of the folder names that were
  // seen, to make sure we remove the ones that were left empty.

  let foldersSeen = new Set();

  for (let [url, item] of specifiedBookmarksMap) {
    foldersSeen.add(item.Folder);

    if (existingBookmarksMap.has(url)) {
      log.debug(`Bookmark intersection: ${url}`);
      // If this specified bookmark exists in the existing bookmarks list,
      // we can remove it from both lists as it's in the intersection.
      specifiedBookmarksMap.delete(url);
      existingBookmarksMap.delete(url);
    }
  }

  for (let url of specifiedBookmarksMap.keys()) {
    log.debug(`Bookmark to add: ${url}`);
  }

  for (let url of existingBookmarksMap.keys()) {
    log.debug(`Bookmark to remove: ${url}`);
  }

  // SET of folders to be deleted (bookmarks object from Places)
  let foldersToRemove = new Set();

  // If no bookmarks will be deleted, then no folder will
  // need to be deleted either, so this next section can be skipped.
  if (existingBookmarksMap.size > 0) {
    await PlacesUtils.bookmarks.fetch(
      { guidPrefix: BookmarksPolicies.FOLDER_GUID_PREFIX },
180
      folder => {
181
182
183
184
185
186
187
188
189
190
191
        if (!foldersSeen.has(folder.title)) {
          log.debug(`Folder to remove: ${folder.title}`);
          foldersToRemove.add(folder);
        }
      }
    );
  }

  return {
    add: specifiedBookmarksMap,
    remove: existingBookmarksMap,
192
    emptyFolders: foldersToRemove,
193
194
195
196
  };
}

async function insertBookmark(bookmark) {
197
  let parentGuid = await getParentGuid(bookmark.Placement, bookmark.Folder);
198
199

  await PlacesUtils.bookmarks.insert({
200
    url: Services.io.newURI(bookmark.URL.href),
201
    title: bookmark.Title,
202
203
204
    guid: PlacesUtils.generateGuidWithPrefix(
      BookmarksPolicies.BOOKMARK_GUID_PREFIX
    ),
205
206
207
208
    parentGuid,
  });

  if (bookmark.Favicon) {
209
    setFaviconForBookmark(bookmark);
210
211
212
  }
}

213
function setFaviconForBookmark(bookmark) {
214
215
216
  let faviconURI;
  let nullPrincipal = Services.scriptSecurityManager.createNullPrincipal({});

217
218
  switch (bookmark.Favicon.protocol) {
    case "data:":
219
220
221
      // data urls must first call replaceFaviconDataFromDataURL, using a
      // fake URL. Later, it's needed to call setAndFetchFaviconForPage
      // with the same URL.
222
      faviconURI = Services.io.newURI("fake-favicon-uri:" + bookmark.URL.href);
223
224
225

      PlacesUtils.favicons.replaceFaviconDataFromDataURL(
        faviconURI,
226
        bookmark.Favicon.href,
227
        0 /* max expiration length */,
228
229
230
231
        nullPrincipal
      );
      break;

232
233
234
    case "http:":
    case "https:":
      faviconURI = Services.io.newURI(bookmark.Favicon.href);
235
236
237
238
      break;

    default:
      log.error(`Bad URL given for favicon on bookmark "${bookmark.Title}"`);
239
      return;
240
241
  }

242
243
244
245
246
247
248
249
  PlacesUtils.favicons.setAndFetchFaviconForPage(
    Services.io.newURI(bookmark.URL.href),
    faviconURI,
    false /* forceReload */,
    PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
    null,
    nullPrincipal
  );
250
251
252
253
254
255
256
257
258
}

// Cache of folder names to guids to be used by the getParentGuid
// function. The name consists in the parentGuid (which should always
// be the menuGuid or the toolbarGuid) + the folder title. This is to
// support having the same folder name in both the toolbar and menu.
XPCOMUtils.defineLazyGetter(this, "gFoldersMapPromise", () => {
  return new Promise(resolve => {
    let foldersMap = new Map();
259
260
261
262
263
264
265
266
267
268
    return PlacesUtils.bookmarks
      .fetch(
        {
          guidPrefix: BookmarksPolicies.FOLDER_GUID_PREFIX,
        },
        result => {
          foldersMap.set(`${result.parentGuid}|${result.title}`, result.guid);
        }
      )
      .then(() => resolve(foldersMap));
269
270
271
272
273
  });
});

async function getParentGuid(placement, folderTitle) {
  // Defaults to toolbar if no placement was given.
274
275
276
277
  let parentGuid =
    placement == "menu"
      ? PlacesUtils.bookmarks.menuGuid
      : PlacesUtils.bookmarks.toolbarGuid;
278
279
280
281
282
283
284
285
286
287
288
289
290
291

  if (!folderTitle) {
    // If no folderTitle is given, this bookmark is to be placed directly
    // into the toolbar or menu.
    return parentGuid;
  }

  let foldersMap = await gFoldersMapPromise;
  let folderName = `${parentGuid}|${folderTitle}`;

  if (foldersMap.has(folderName)) {
    return foldersMap.get(folderName);
  }

292
293
294
  let guid = PlacesUtils.generateGuidWithPrefix(
    BookmarksPolicies.FOLDER_GUID_PREFIX
  );
295
296
297
298
  await PlacesUtils.bookmarks.insert({
    type: PlacesUtils.bookmarks.TYPE_FOLDER,
    title: folderTitle,
    guid,
299
    parentGuid,
300
301
302
303
304
  });

  foldersMap.set(folderName, guid);
  return guid;
}