BookmarksPolicies.jsm 9.6 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
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
 *
 * The schema for this object is defined in policies-schema.json.
 */

ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
ChromeUtils.import("resource://gre/modules/Services.jsm");

ChromeUtils.defineModuleGetter(this, "PlacesUtils",
  "resource://gre/modules/PlacesUtils.jsm");

const PREF_LOGLEVEL = "browser.policies.loglevel";

XPCOMUtils.defineLazyGetter(this, "log", () => {
  let { ConsoleAPI } = ChromeUtils.import("resource://gre/modules/Console.jsm", {});
  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,
  });
});

this.EXPORTED_SYMBOLS = [ "BookmarksPolicies" ];

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());
    });
90
  },
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
};

/*
 * 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) {
112
    specifiedBookmarksMap.set(bookmark.URL.href, bookmark);
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
  }

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

  // --------- 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 },
      (folder) => {
        if (!foldersSeen.has(folder.title)) {
          log.debug(`Folder to remove: ${folder.title}`);
          foldersToRemove.add(folder);
        }
      }
    );
  }

  return {
    add: specifiedBookmarksMap,
    remove: existingBookmarksMap,
187
    emptyFolders: foldersToRemove,
188
189
190
191
192
193
194
195
  };
}

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

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

  if (bookmark.Favicon) {
    await setFaviconForBookmark(bookmark).catch(
      () => log.error(`Error setting favicon for ${bookmark.Title}`));
  }
}

async function setFaviconForBookmark(bookmark) {
  let faviconURI;
  let nullPrincipal = Services.scriptSecurityManager.createNullPrincipal({});

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

      PlacesUtils.favicons.replaceFaviconDataFromDataURL(
        faviconURI,
221
        bookmark.Favicon.href,
222
223
224
225
226
        0, /* max expiration length */
        nullPrincipal
      );
      break;

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

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

  return new Promise(resolve => {
    PlacesUtils.favicons.setAndFetchFaviconForPage(
239
      Services.io.newURI(bookmark.URL.href),
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
      faviconURI,
      false, /* forceReload */
      PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
      resolve,
      nullPrincipal
    );
  });
}

function generateGuidWithPrefix(prefix) {
  // Generates a random GUID and replace its beginning with the given
  // prefix. We do this instead of just prepending the prefix to keep
  // the correct character length.
  return prefix + PlacesUtils.history.makeGuid().substring(prefix.length);
}

// 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();
    return PlacesUtils.bookmarks.fetch(
      {
265
        guidPrefix: BookmarksPolicies.FOLDER_GUID_PREFIX,
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
      },
      (result) => {
        foldersMap.set(`${result.parentGuid}|${result.title}`, result.guid);
      }
    ).then(() => resolve(foldersMap));
  });
});

async function getParentGuid(placement, folderTitle) {
  // Defaults to toolbar if no placement was given.
  let parentGuid = (placement == "menu") ?
                   PlacesUtils.bookmarks.menuGuid :
                   PlacesUtils.bookmarks.toolbarGuid;

  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);
  }

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

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