-
Notifications
You must be signed in to change notification settings - Fork 54
/
Bookmarks.jsm
3395 lines (3149 loc) · 114 KB
/
Bookmarks.jsm
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* 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";
/**
* This module provides an asynchronous API for managing bookmarks.
*
* Bookmarks are organized in a tree structure, and include URLs, folders and
* separators. Multiple bookmarks for the same URL are allowed.
*
* Note that if you are handling bookmarks operations in the UI, you should
* not use this API directly, but rather use PlacesTransactions.jsm, so that
* any operation is undo/redo-able.
*
* Each bookmark-item is represented by an object having the following
* properties:
*
* - guid (string)
* The globally unique identifier of the item.
* - parentGuid (string)
* The globally unique identifier of the folder containing the item.
* This will be an empty string for the Places root folder.
* - index (number)
* The 0-based position of the item in the parent folder.
* - dateAdded (Date)
* The time at which the item was added.
* - lastModified (Date)
* The time at which the item was last modified.
* - type (number)
* The item's type, either TYPE_BOOKMARK, TYPE_FOLDER or TYPE_SEPARATOR.
*
* The following properties are only valid for URLs or folders.
*
* - title (string)
* The item's title, if any. Empty titles and null titles are considered
* the same. Titles longer than DB_TITLE_LENGTH_MAX will be truncated.
*
* The following properties are only valid for URLs:
*
* - url (URL, href or nsIURI)
* The item's URL. Note that while input objects can contains either
* an URL object, an href string, or an nsIURI, output objects will always
* contain an URL object.
* An URL cannot be longer than DB_URL_LENGTH_MAX, methods will throw if a
* longer value is provided.
*
* Each successful operation notifies through the nsINavBookmarksObserver
* interface. To listen to such notifications you must register using
* nsINavBookmarksService addObserver and removeObserver methods.
* Note that bookmark addition or order changes won't notify onItemMoved for
* items that have their indexes changed.
* Similarly, lastModified changes not done explicitly (like changing another
* property) won't fire an onItemChanged notification for the lastModified
* property.
* @see nsINavBookmarkObserver
*/
var EXPORTED_SYMBOLS = ["Bookmarks"];
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyGlobalGetters(this, ["URL"]);
ChromeUtils.defineModuleGetter(
this,
"NetUtil",
"resource://gre/modules/NetUtil.jsm"
);
ChromeUtils.defineModuleGetter(
this,
"PlacesUtils",
"resource://gre/modules/PlacesUtils.jsm"
);
ChromeUtils.defineModuleGetter(
this,
"PlacesSyncUtils",
"resource://gre/modules/PlacesSyncUtils.jsm"
);
// This is an helper to temporarily cover the need to know the tags folder
// itemId until bug 424160 is fixed. This exists so that startup paths won't
// pay the price to initialize the bookmarks service just to fetch this value.
// If the method is already initing the bookmarks service for other reasons
// (most of the writing methods will invoke getObservers() already) it can
// directly use the PlacesUtils.tagsFolderId property.
var gTagsFolderId;
async function promiseTagsFolderId() {
if (gTagsFolderId) {
return gTagsFolderId;
}
let db = await PlacesUtils.promiseDBConnection();
let rows = await db.execute(
"SELECT id FROM moz_bookmarks WHERE guid = :guid",
{ guid: Bookmarks.tagsGuid }
);
return (gTagsFolderId = rows[0].getResultByName("id"));
}
const MATCH_ANYWHERE_UNMODIFIED =
Ci.mozIPlacesAutoComplete.MATCH_ANYWHERE_UNMODIFIED;
const BEHAVIOR_BOOKMARK = Ci.mozIPlacesAutoComplete.BEHAVIOR_BOOKMARK;
var Bookmarks = Object.freeze({
/**
* Item's type constants.
* These should stay consistent with nsINavBookmarksService.idl
*/
TYPE_BOOKMARK: 1,
TYPE_FOLDER: 2,
TYPE_SEPARATOR: 3,
/**
* Sync status constants, stored for each item.
*/
SYNC_STATUS: {
UNKNOWN: Ci.nsINavBookmarksService.SYNC_STATUS_UNKNOWN,
NEW: Ci.nsINavBookmarksService.SYNC_STATUS_NEW,
NORMAL: Ci.nsINavBookmarksService.SYNC_STATUS_NORMAL,
},
/**
* Default index used to append a bookmark-item at the end of a folder.
* This should stay consistent with nsINavBookmarksService.idl
*/
DEFAULT_INDEX: -1,
/**
* Maximum length of a tag.
* Any tag above this length is rejected.
*/
MAX_TAG_LENGTH: 100,
/**
* Bookmark change source constants, passed as optional properties and
* forwarded to observers. See nsINavBookmarksService.idl for an explanation.
*/
SOURCES: {
DEFAULT: Ci.nsINavBookmarksService.SOURCE_DEFAULT,
SYNC: Ci.nsINavBookmarksService.SOURCE_SYNC,
IMPORT: Ci.nsINavBookmarksService.SOURCE_IMPORT,
SYNC_REPARENT_REMOVED_FOLDER_CHILDREN:
Ci.nsINavBookmarksService.SOURCE_SYNC_REPARENT_REMOVED_FOLDER_CHILDREN,
RESTORE: Ci.nsINavBookmarksService.SOURCE_RESTORE,
RESTORE_ON_STARTUP: Ci.nsINavBookmarksService.SOURCE_RESTORE_ON_STARTUP,
},
/**
* Special GUIDs associated with bookmark roots.
* It's guaranteed that the roots will always have these guids.
*/
rootGuid: "root________",
menuGuid: "menu________",
toolbarGuid: "toolbar_____",
unfiledGuid: "unfiled_____",
mobileGuid: "mobile______",
// With bug 424160, tags will stop being bookmarks, thus this root will
// be removed. Do not rely on this, rather use the tagging service API.
tagsGuid: "tags________",
/**
* The GUIDs of the user content root folders that we support, for easy access
* as a set.
*/
userContentRoots: [
"toolbar_____",
"menu________",
"unfiled_____",
"mobile______",
],
/**
* GUIDs associated with virtual queries that are used for displaying bookmark
* folders in the left pane.
*/
virtualMenuGuid: "menu_______v",
virtualToolbarGuid: "toolbar____v",
virtualUnfiledGuid: "unfiled____v",
virtualMobileGuid: "mobile_____v",
/**
* Checks if a guid is a virtual root.
*
* @param {String} guid The guid of the item to look for.
* @returns {Boolean} true if guid is a virtual root, false otherwise.
*/
isVirtualRootItem(guid) {
return (
guid == PlacesUtils.bookmarks.virtualMenuGuid ||
guid == PlacesUtils.bookmarks.virtualToolbarGuid ||
guid == PlacesUtils.bookmarks.virtualUnfiledGuid ||
guid == PlacesUtils.bookmarks.virtualMobileGuid
);
},
/**
* Returns the title to use on the UI for a bookmark item. Root folders
* in the database don't store fully localised versions of the title. To
* get those this function should be called.
*
* Hence, this function should only be called if a root folder object is
* likely to be displayed to the user.
*
* @param {Object} info An object representing a bookmark-item.
* @returns {String} The correct string.
* @throws {Error} If the guid in PlacesUtils.bookmarks.userContentRoots is
* not supported.
*/
getLocalizedTitle(info) {
if (!PlacesUtils.bookmarks.userContentRoots.includes(info.guid)) {
return info.title;
}
switch (info.guid) {
case PlacesUtils.bookmarks.toolbarGuid:
return PlacesUtils.getString("BookmarksToolbarFolderTitle");
case PlacesUtils.bookmarks.menuGuid:
return PlacesUtils.getString("BookmarksMenuFolderTitle");
case PlacesUtils.bookmarks.unfiledGuid:
return PlacesUtils.getString("OtherBookmarksFolderTitle");
case PlacesUtils.bookmarks.mobileGuid:
return PlacesUtils.getString("MobileBookmarksFolderTitle");
default:
throw new Error(
`Unsupported guid ${info.guid} passed to getLocalizedTitle!`
);
}
},
/**
* Inserts a bookmark-item into the bookmarks tree.
*
* For creating a bookmark, the following set of properties is required:
* - type
* - parentGuid
* - url, only for bookmarked URLs
*
* If an index is not specified, it defaults to appending.
* It's also possible to pass a non-existent GUID to force creation of an
* item with the given GUID, but unless you have a very sound reason, such as
* an undo manager implementation or synchronization, don't do that.
*
* Note that any known properties that don't apply to the specific item type
* cause an exception.
*
* @param info
* object representing a bookmark-item.
*
* @return {Promise} resolved when the creation is complete.
* @resolves to an object representing the created bookmark.
* @rejects if it's not possible to create the requested bookmark.
* @throws if the arguments are invalid.
*/
insert(info) {
let now = new Date();
let addedTime = (info && info.dateAdded) || now;
let modTime = addedTime;
if (addedTime > now) {
modTime = now;
}
let insertInfo = validateBookmarkObject("Bookmarks.jsm: insert", info, {
type: { defaultValue: this.TYPE_BOOKMARK },
index: { defaultValue: this.DEFAULT_INDEX },
url: {
requiredIf: b => b.type == this.TYPE_BOOKMARK,
validIf: b => b.type == this.TYPE_BOOKMARK,
},
parentGuid: {
required: true,
// Inserting into the root folder is not allowed.
validIf: b => b.parentGuid != this.rootGuid,
},
title: {
defaultValue: "",
validIf: b =>
b.type == this.TYPE_BOOKMARK ||
b.type == this.TYPE_FOLDER ||
b.title === "",
},
dateAdded: { defaultValue: addedTime },
lastModified: {
defaultValue: modTime,
validIf: b =>
b.lastModified >= now ||
(b.dateAdded && b.lastModified >= b.dateAdded),
},
source: { defaultValue: this.SOURCES.DEFAULT },
});
return (async () => {
// Ensure the parent exists.
let parent = await fetchBookmark({ guid: insertInfo.parentGuid });
if (!parent) {
throw new Error("parentGuid must be valid");
}
// Set index in the appending case.
if (
insertInfo.index == this.DEFAULT_INDEX ||
insertInfo.index > parent._childCount
) {
insertInfo.index = parent._childCount;
}
let item = await insertBookmark(insertInfo, parent);
// We need the itemId to notify, though once the switch to guids is
// complete we may stop using it.
let itemId = await PlacesUtils.promiseItemId(item.guid);
// Pass tagging information for the observers to skip over these notifications when needed.
let isTagging = parent._parentId == PlacesUtils.tagsFolderId;
let isTagsFolder = parent._id == PlacesUtils.tagsFolderId;
let url = "";
if (item.type == Bookmarks.TYPE_BOOKMARK) {
url = item.url.href;
}
let notification = new PlacesBookmarkAddition({
id: itemId,
url,
itemType: item.type,
parentId: parent._id,
index: item.index,
title: item.title,
dateAdded: item.dateAdded,
guid: item.guid,
parentGuid: item.parentGuid,
source: item.source,
isTagging: isTagging || isTagsFolder,
});
PlacesObservers.notifyListeners([notification]);
// If it's a tag, notify OnItemChanged to all bookmarks for this URL.
if (isTagging) {
let observers = PlacesUtils.bookmarks.getObservers();
for (let entry of await fetchBookmarksByURL(item, {
concurrent: true,
})) {
notify(observers, "onItemChanged", [
entry._id,
"tags",
false,
"",
PlacesUtils.toPRTime(entry.lastModified),
entry.type,
entry._parentId,
entry.guid,
entry.parentGuid,
"",
item.source,
]);
}
}
// Remove non-enumerable properties.
delete item.source;
return Object.assign({}, item);
})();
},
/**
* Inserts a bookmark-tree into the existing bookmarks tree.
*
* All the specified folders and bookmarks will be inserted as new, even
* if duplicates. There's no merge support at this time.
*
* The input should be of the form:
* {
* guid: "<some-existing-guid-to-use-as-parent>",
* source: "<some valid source>", (optional)
* children: [
* ... valid bookmark objects.
* ]
* }
*
* Children will be appended to any existing children of the parent
* that is specified. The source specified on the root of the tree
* will be used for all the items inserted. Any indices or custom parentGuids
* set on children will be ignored and overwritten.
*
* @param {Object} tree
* object representing a tree of bookmark items to insert.
* @param {Object} options [optional]
* object with properties representing options. Current options are:
* - fixupOrSkipInvalidEntries: makes the insert more lenient to
* mistakes in the input tree. Properties of an entry that are
* fixable will be corrected, otherwise the entry will be skipped.
* This is particularly convenient for import/restore operations,
* but should not be abused for common inserts, since it may hide
* bugs in the calling code.
*
* @return {Promise} resolved when the creation is complete.
* @resolves to an array of objects representing the created bookmark(s).
* @rejects if it's not possible to create the requested bookmark.
* @throws if the arguments are invalid.
*/
insertTree(tree, options) {
if (!tree || typeof tree != "object") {
throw new Error("Should be provided a valid tree object.");
}
if (!Array.isArray(tree.children) || !tree.children.length) {
throw new Error("Should have a non-zero number of children to insert.");
}
if (!PlacesUtils.isValidGuid(tree.guid)) {
throw new Error(
`The parent guid is not valid (${tree.guid} ${tree.title}).`
);
}
if (tree.guid == this.rootGuid) {
throw new Error("Can't insert into the root.");
}
if (tree.guid == this.tagsGuid) {
throw new Error("Can't use insertTree to insert tags.");
}
if (
tree.hasOwnProperty("source") &&
!Object.values(this.SOURCES).includes(tree.source)
) {
throw new Error("Can't use source value " + tree.source);
}
if (options && typeof options != "object") {
throw new Error("Options should be a valid object");
}
let fixupOrSkipInvalidEntries =
options && !!options.fixupOrSkipInvalidEntries;
// Serialize the tree into an array of items to insert into the db.
let insertInfos = [];
let urlsThatMightNeedPlaces = [];
// We want to use the same 'last added' time for all the entries
// we import (so they won't differ by a few ms based on where
// they are in the tree, and so we don't needlessly construct
// multiple dates).
let fallbackLastAdded = new Date();
const { TYPE_BOOKMARK, TYPE_FOLDER, SOURCES } = this;
// Reuse the 'source' property for all the entries.
let source = tree.source || SOURCES.DEFAULT;
// This is recursive.
function appendInsertionInfoForInfoArray(infos, indexToUse, parentGuid) {
// We want to keep the index of items that will be inserted into the root
// NULL, and then use a subquery to select the right index, to avoid
// races where other consumers might add items between when we determine
// the index and when we insert. However, the validator does not allow
// NULL values in in the index, so we fake it while validating and then
// correct later. Keep track of whether we're doing this:
let shouldUseNullIndices = false;
if (indexToUse === null) {
shouldUseNullIndices = true;
indexToUse = 0;
}
// When a folder gets an item added, its last modified date is updated
// to be equal to the date we added the item (if that date is newer).
// Because we're inserting a tree, we keep track of this date for the
// loop, updating it for inserted items as well as from any subfolders
// we insert.
let lastAddedForParent = new Date(0);
for (let info of infos) {
// Ensure to use the same date for dateAdded and lastModified, even if
// dateAdded may be imposed by the caller.
let time = (info && info.dateAdded) || fallbackLastAdded;
let insertInfo = {
guid: { defaultValue: PlacesUtils.history.makeGuid() },
type: { defaultValue: TYPE_BOOKMARK },
url: {
requiredIf: b => b.type == TYPE_BOOKMARK,
validIf: b => b.type == TYPE_BOOKMARK,
},
parentGuid: { replaceWith: parentGuid }, // Set the correct parent guid.
title: {
defaultValue: "",
validIf: b =>
b.type == TYPE_BOOKMARK ||
b.type == TYPE_FOLDER ||
b.title === "",
},
dateAdded: {
defaultValue: time,
validIf: b => !b.lastModified || b.dateAdded <= b.lastModified,
},
lastModified: {
defaultValue: time,
validIf: b =>
(!b.dateAdded && b.lastModified >= time) ||
(b.dateAdded && b.lastModified >= b.dateAdded),
},
index: { replaceWith: indexToUse++ },
source: { replaceWith: source },
keyword: { validIf: b => b.type == TYPE_BOOKMARK },
charset: { validIf: b => b.type == TYPE_BOOKMARK },
postData: { validIf: b => b.type == TYPE_BOOKMARK },
tags: { validIf: b => b.type == TYPE_BOOKMARK },
children: {
validIf: b => b.type == TYPE_FOLDER && Array.isArray(b.children),
},
};
if (fixupOrSkipInvalidEntries) {
insertInfo.guid.fixup = b =>
(b.guid = PlacesUtils.history.makeGuid());
insertInfo.dateAdded.fixup = insertInfo.lastModified.fixup = b =>
(b.lastModified = b.dateAdded = fallbackLastAdded);
}
try {
insertInfo = validateBookmarkObject(
"Bookmarks.jsm: insertTree",
info,
insertInfo
);
} catch (ex) {
if (fixupOrSkipInvalidEntries) {
indexToUse--;
continue;
} else {
throw ex;
}
}
if (shouldUseNullIndices) {
insertInfo.index = null;
}
// Store the URL if this is a bookmark, so we can ensure we create an
// entry in moz_places for it.
if (insertInfo.type == Bookmarks.TYPE_BOOKMARK) {
urlsThatMightNeedPlaces.push(insertInfo.url);
}
insertInfos.push(insertInfo);
// Process any children. We have to use info.children here rather than
// insertInfo.children because validateBookmarkObject doesn't copy over
// the children ref, as the default bookmark validators object doesn't
// know about children.
if (info.children) {
// start children of this item off at index 0.
let childrenLastAdded = appendInsertionInfoForInfoArray(
info.children,
0,
insertInfo.guid
);
if (childrenLastAdded > insertInfo.lastModified) {
insertInfo.lastModified = childrenLastAdded;
}
if (childrenLastAdded > lastAddedForParent) {
lastAddedForParent = childrenLastAdded;
}
}
// Ensure we track what time to update the parent to.
if (insertInfo.dateAdded > lastAddedForParent) {
lastAddedForParent = insertInfo.dateAdded;
}
}
return lastAddedForParent;
}
// We want to validate synchronously, but we can't know the index at which
// we're inserting into the parent. We just use NULL instead,
// and the SQL query with which we insert will update it as necessary.
let lastAddedForParent = appendInsertionInfoForInfoArray(
tree.children,
null,
tree.guid
);
// appendInsertionInfoForInfoArray will remove invalid items and may leave
// us with nothing to insert, if so, just return early.
if (!insertInfos.length) {
return [];
}
return (async function() {
let treeParent = await fetchBookmark({ guid: tree.guid });
if (!treeParent) {
throw new Error("The parent you specified doesn't exist.");
}
if (treeParent._parentId == PlacesUtils.tagsFolderId) {
throw new Error("Can't use insertTree to insert tags.");
}
await insertBookmarkTree(
insertInfos,
source,
treeParent,
urlsThatMightNeedPlaces,
lastAddedForParent
);
// Now update the indices of root items in the objects we return.
// These may be wrong if someone else modified the table between
// when we fetched the parent and inserted our items, but the actual
// inserts will have been correct, and we don't want to query the DB
// again if we don't have to. bug 1347230 covers improving this.
let rootIndex = treeParent._childCount;
for (let insertInfo of insertInfos) {
if (insertInfo.parentGuid == tree.guid) {
insertInfo.index += rootIndex++;
}
}
// We need the itemIds to notify, though once the switch to guids is
// complete we may stop using them.
let itemIdMap = await PlacesUtils.promiseManyItemIds(
insertInfos.map(info => info.guid)
);
let notifications = [];
for (let i = 0; i < insertInfos.length; i++) {
let item = insertInfos[i];
let itemId = itemIdMap.get(item.guid);
// For sub-folders, we need to make sure their children have the correct parent ids.
let parentId;
if (item.parentGuid === treeParent.guid) {
// This is a direct child of the tree parent, so we can use the
// existing parent's id.
parentId = treeParent._id;
} else {
// This is a parent folder that's been updated, so we need to
// use the new item id.
parentId = itemIdMap.get(item.parentGuid);
}
let url = "";
if (item.type == Bookmarks.TYPE_BOOKMARK) {
url = item.url instanceof URL ? item.url.href : item.url;
}
notifications.push(
new PlacesBookmarkAddition({
id: itemId,
url,
itemType: item.type,
parentId,
index: item.index,
title: item.title,
dateAdded: item.dateAdded,
guid: item.guid,
parentGuid: item.parentGuid,
source: item.source,
isTagging: false,
})
);
try {
await handleBookmarkItemSpecialData(itemId, item);
} catch (ex) {
// This is not critical, regardless the bookmark has been created
// and we should continue notifying the next ones.
Cu.reportError(
`An error occured while handling special bookmark data: ${ex}`
);
}
// Remove non-enumerable properties.
delete item.source;
insertInfos[i] = Object.assign({}, item);
}
PlacesObservers.notifyListeners(notifications);
return insertInfos;
})();
},
/**
* Updates a bookmark-item.
*
* Only set the properties which should be changed (undefined properties
* won't be taken into account).
* Moreover, the item's type or dateAdded cannot be changed, since they are
* immutable after creation. Trying to change them will reject.
*
* Note that any known properties that don't apply to the specific item type
* cause an exception.
*
* @param info
* object representing a bookmark-item, as defined above.
*
* @return {Promise} resolved when the update is complete.
* @resolves to an object representing the updated bookmark.
* @rejects if it's not possible to update the given bookmark.
* @throws if the arguments are invalid.
*/
update(info) {
// The info object is first validated here to ensure it's consistent, then
// it's compared to the existing item to remove any properties that don't
// need to be updated.
let updateInfo = validateBookmarkObject("Bookmarks.jsm: update", info, {
guid: { required: true },
index: {
requiredIf: b => b.hasOwnProperty("parentGuid"),
validIf: b => b.index >= 0 || b.index == this.DEFAULT_INDEX,
},
parentGuid: { validIf: b => b.parentGuid != this.rootGuid },
source: { defaultValue: this.SOURCES.DEFAULT },
});
// There should be at last one more property in addition to guid and source.
if (Object.keys(updateInfo).length < 3) {
throw new Error("Not enough properties to update");
}
return (async () => {
// Ensure the item exists.
let item = await fetchBookmark(updateInfo);
if (!item) {
throw new Error("No bookmarks found for the provided GUID");
}
if (updateInfo.hasOwnProperty("type") && updateInfo.type != item.type) {
throw new Error("The bookmark type cannot be changed");
}
// Remove any property that will stay the same.
removeSameValueProperties(updateInfo, item);
// Check if anything should still be updated.
if (Object.keys(updateInfo).length < 3) {
// Remove non-enumerable properties.
return Object.assign({}, item);
}
const now = new Date();
let lastModifiedDefault = now;
// In the case where `dateAdded` is specified, but `lastModified` is not,
// we only update `lastModified` if it is older than the new `dateAdded`.
if (!("lastModified" in updateInfo) && "dateAdded" in updateInfo) {
lastModifiedDefault = new Date(
Math.max(item.lastModified, updateInfo.dateAdded)
);
}
updateInfo = validateBookmarkObject("Bookmarks.jsm: update", updateInfo, {
url: { validIf: () => item.type == this.TYPE_BOOKMARK },
title: {
validIf: () =>
[this.TYPE_BOOKMARK, this.TYPE_FOLDER].includes(item.type),
},
lastModified: {
defaultValue: lastModifiedDefault,
validIf: b =>
b.lastModified >= now ||
b.lastModified >= (b.dateAdded || item.dateAdded),
},
dateAdded: { defaultValue: item.dateAdded },
});
return PlacesUtils.withConnectionWrapper(
"Bookmarks.jsm: update",
async db => {
let parent;
if (updateInfo.hasOwnProperty("parentGuid")) {
if (PlacesUtils.isRootItem(item.guid)) {
throw new Error("It's not possible to move Places root folders.");
}
if (item.type == this.TYPE_FOLDER) {
// Make sure we are not moving a folder into itself or one of its
// descendants.
let rows = await db.executeCached(
`WITH RECURSIVE
descendants(did) AS (
VALUES(:id)
UNION ALL
SELECT id FROM moz_bookmarks
JOIN descendants ON parent = did
WHERE type = :type
)
SELECT guid FROM moz_bookmarks
WHERE id IN descendants
`,
{ id: item._id, type: this.TYPE_FOLDER }
);
if (
rows
.map(r => r.getResultByName("guid"))
.includes(updateInfo.parentGuid)
) {
throw new Error(
"Cannot insert a folder into itself or one of its descendants"
);
}
}
parent = await fetchBookmark({ guid: updateInfo.parentGuid });
if (!parent) {
throw new Error("No bookmarks found for the provided parentGuid");
}
}
if (updateInfo.hasOwnProperty("index")) {
if (PlacesUtils.isRootItem(item.guid)) {
throw new Error("It's not possible to move Places root folders.");
}
// If at this point we don't have a parent yet, we are moving into
// the same container. Thus we know it exists.
if (!parent) {
parent = await fetchBookmark({ guid: item.parentGuid });
}
if (
updateInfo.index >= parent._childCount ||
updateInfo.index == this.DEFAULT_INDEX
) {
updateInfo.index = parent._childCount;
// Fix the index when moving within the same container.
if (parent.guid == item.parentGuid) {
updateInfo.index--;
}
}
}
let syncChangeDelta = PlacesSyncUtils.bookmarks.determineSyncChangeDelta(
info.source
);
let updatedItem = await db.executeTransaction(async function() {
let updatedItem = await updateBookmark(
db,
updateInfo,
item,
item.index,
parent,
syncChangeDelta
);
if (parent) {
await setAncestorsLastModified(
db,
parent.guid,
updatedItem.lastModified,
syncChangeDelta
);
}
return updatedItem;
});
if (
item.type == this.TYPE_BOOKMARK &&
item.url.href != updatedItem.url.href
) {
// ...though we don't wait for the calculation.
updateFrecency(db, [item.url]).catch(Cu.reportError);
updateFrecency(db, [updatedItem.url]).catch(Cu.reportError);
}
// Notify onItemChanged to listeners.
let observers = PlacesUtils.bookmarks.getObservers();
// For lastModified, we only care about the original input, since we
// should not notify implciit lastModified changes.
if (
info.hasOwnProperty("lastModified") &&
updateInfo.hasOwnProperty("lastModified") &&
item.lastModified != updatedItem.lastModified
) {
notify(observers, "onItemChanged", [
updatedItem._id,
"lastModified",
false,
`${PlacesUtils.toPRTime(updatedItem.lastModified)}`,
PlacesUtils.toPRTime(updatedItem.lastModified),
updatedItem.type,
updatedItem._parentId,
updatedItem.guid,
updatedItem.parentGuid,
"",
updatedItem.source,
]);
}
if (
info.hasOwnProperty("dateAdded") &&
updateInfo.hasOwnProperty("dateAdded") &&
item.dateAdded != updatedItem.dateAdded
) {
notify(observers, "onItemChanged", [
updatedItem._id,
"dateAdded",
false,
`${PlacesUtils.toPRTime(updatedItem.dateAdded)}`,
PlacesUtils.toPRTime(updatedItem.lastModified),
updatedItem.type,
updatedItem._parentId,
updatedItem.guid,
updatedItem.parentGuid,
"",
updatedItem.source,
]);
}
if (updateInfo.hasOwnProperty("title")) {
let isTagging = updatedItem.parentGuid == Bookmarks.tagsGuid;
notify(
observers,
"onItemChanged",
[
updatedItem._id,
"title",
false,
updatedItem.title,
PlacesUtils.toPRTime(updatedItem.lastModified),
updatedItem.type,
updatedItem._parentId,
updatedItem.guid,
updatedItem.parentGuid,
"",
updatedItem.source,
],
{ isTagging }
);
// If we're updating a tag, we must notify all the tagged bookmarks
// about the change.
if (isTagging) {
for (let entry of await fetchBookmarksByTags(
{ tags: [updatedItem.title] },
{ concurrent: true }
)) {
notify(observers, "onItemChanged", [
entry._id,
"tags",
false,
"",
PlacesUtils.toPRTime(entry.lastModified),
entry.type,
entry._parentId,
entry.guid,
entry.parentGuid,
"",
updatedItem.source,
]);
}
}
}
if (updateInfo.hasOwnProperty("url")) {
await PlacesUtils.keywords.reassign(
item.url,
updatedItem.url,
updatedItem.source
);
notify(observers, "onItemChanged", [
updatedItem._id,
"uri",
false,
updatedItem.url.href,
PlacesUtils.toPRTime(updatedItem.lastModified),
updatedItem.type,
updatedItem._parentId,
updatedItem.guid,
updatedItem.parentGuid,
item.url.href,
updatedItem.source,
]);
}
// If the item was moved, notify onItemMoved.
if (
item.parentGuid != updatedItem.parentGuid ||
item.index != updatedItem.index
) {
notify(observers, "onItemMoved", [
updatedItem._id,
item._parentId,
item.index,
updatedItem._parentId,
updatedItem.index,
updatedItem.type,
updatedItem.guid,
item.parentGuid,
updatedItem.parentGuid,
updatedItem.source,
updatedItem.url && updatedItem.url.href,
]);
}
// Remove non-enumerable properties.
delete updatedItem.source;
return Object.assign({}, updatedItem);
}
);
})();
},
/**
* Moves multiple bookmark-items to a specific folder.
*
* If you are only updating/moving a single bookmark, use update() instead.
*
* @param {Array} guids
* An array of GUIDs representing the bookmarks to move.
* @param {String} parentGuid
* Optional, the parent GUID to move the bookmarks to.
* @param {Integer} index
* The index to move the bookmarks to. If this is -1, the bookmarks
* will be appended to the folder.
* @param {Integer} source
* One of the Bookmarks.SOURCES.* options, representing the source of
* this change.
*
* @return {Promise} resolved when the move is complete.
* @resolves to an array of objects representing the moved bookmarks.