-
Notifications
You must be signed in to change notification settings - Fork 8
/
places.js
2271 lines (2054 loc) · 77.6 KB
/
places.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
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
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et: */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Jetpack.
*
* The Initial Developer of the Original Code is the Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Marco Bonardo <mak77@bonardo.net> (Original Author)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
const {Cc, Ci, Cr, Cu} = require("chrome");
// PlacesQuery is currently included at the bottom of this file,
// to ease distribution by not tying Jetpack's usage of it to a
// particular Firefox version.
//Cu.import("resource://gre/modules/PlacesQuery.jsm", this);
Cu.import("resource://gre/modules/PlacesUtils.jsm", this);
const apiUtils = require("api-utils");
const collection = require("collection");
const errors = require("errors");
// Main search function.
exports.search = (new PlacesHandler()).search;
// Shortcut helper to search visited places.
exports.history = new PlacesHandler({ visited: {} });
// Shortcut helper to search bookmarked places.
exports.bookmarks = new PlacesHandler({ bookmarked: {} });
// Add bookmark root folder shortcuts.
exports.bookmarks.unfiled = PlacesUtils.unfiledBookmarksFolderId;
exports.bookmarks.toolbar = PlacesUtils.toolbarFolderId;
exports.bookmarks.menu = PlacesUtils.bookmarksMenuFolderId;
// Method for creating a bookmark. Can take an options object or an array of
// options objects to create bookmarks in batch.
exports.bookmarks.create = function PF_create(aOptions) {
let options = validateBookmarkInfo(aOptions, true);
let bs = PlacesUtils.bookmarks;
// Create the bookmark item.
try {
switch(options.type) {
case "bookmark":
options._itemId =
bs.insertBookmark(options.folder,
PlacesUtils._uri(options.location),
options.position,
options.title);
if (options.tags.length > 0) {
PlacesUtils.tagging.tagURI(PlacesUtils._uri(options.location),
options.tags);
}
break;
case "folder":
options._itemId =
PlacesUtils.bookmarks.createFolder(options.folder,
options.title,
options.position);
break;
case "separator":
options._itemId =
PlacesUtils.bookmarks.insertSeparator(options.folder,
options.position);
}
/*
if (options.annotations) {
PlacesUtils.setAnnotationsForItem(options._itemId,
options.annotations);
}
*/
}
catch (err) {
console.exception("Failed to create new bookmark. " + err);
}
if (options.onCreate) {
safeCallback(undefined, options.onCreate, options);
}
};
/**
* Wrapper for safely calling user-callback functions.
* TODO: file a bug for getting this into api-utils.
*/
function safeCallback(aArgument, aCallbackFunc, aCallbackScope) {
if (aCallbackFunc) {
require("timer").setTimeout(function() {
try {
if (aCallbackScope)
aCallbackFunc.call(aCallbackScope, aArgument);
else
aCallbackFunc.call(exports, aArgument); // safe "this".
}
catch (err) {
console.exception(err);
}
}, 0);
}
}
/**
* This is the basic exposed object for searching.
* The caller will get access to it via an alias such as "bookmarks"
* or "history" and call it's .search() method.
*/
function PlacesHandler(helperOptions) {
this.search = function PH_createNewFilter(userOptions) {
// Merge helper configuration to user configurations.
let options = validateAndMergeConfigs(userOptions, helperOptions);
// Create and return a PlacesSearch.
return new PlacesSearch(options);
}
}
PlacesHandler.prototype = {}
/**
* apiUtils method does not support "date" type.
*/
function checkType(entry, type) {
switch (type) {
case "undefined":
return entry === undefined;
case "null":
return entry === null;
case "date":
return Object.prototype.toString.call(entry) === "[object Date]";
case "array":
return Object.prototype.toString.call(entry) === "[object Array]";
default:
return typeof(entry) == type;
}
}
/**
* apiUtils method does not support things like "array of optional string" or
* "array of positive optional number".
*/
function checkArrayElementsType(array, type, allowOptionalElement) {
let arrayIsValid = true;
array.every(function(elm) {
if (allowOptionalElement && (elm === undefined || elm === null))
return true;
return arrayIsValid = checkType(elm, type);
});
return arrayIsValid;
}
/**
* Take caller-supplied options and merge them with a set of default
* options.
*/
function validateAndMergeConfigs(userOptions, additionalOptions) {
userOptions = apiUtils.validateOptions(userOptions, {
phrase: {
map: function(v) v.toString(),
is: ["undefined", "string"],
ok: function(v) !v || v.length > 0,
msg: "Provided phrase must be a non-empty string."
},
host: {
map: function(v) v.toString(),
is: ["undefined", "string"],
ok: function(v) !v || v.length > 0,
msg: "Provided host must be a non-empty string."
},
uri: {
map: function(v) v.toString(),
is: ["undefined", "string"],
ok: function(v) !v || v.length > 0,
msg: "Provided uri must be a non empty string."
},
annotated: {
is: ["undefined", "array"],
ok: function (v) !v || v.length > 0,
msg: "Required annotations must be a valid array of strings."
},
bookmarked: apiUtils.validateOptions(userOptions.bookmarked, {
is: ["undefined", "boolean"],
ok: function (v) !v || apiUtils.validateOptions(userOptions.bookmarked, {
tags: {
is: ["undefined", "array"],
ok: function(v) !v || (v.length > 0 && checkArrayElementsType(v, "string")),
msg: "Tags must be a valid array of strings."
},
folder: {
is: ["undefined", "number"],
ok: function(v) !v || v > 0,
msg: "Folder id must be a positive number."
},
position: {
is: ["undefined", "number"],
ok: function(v) !v || v > 0,
msg: "Position must be a positive number."
},
id: {
is: ["undefined", "number"],
ok: function(v) !v || v > 0,
msg: "Bookmark id must be a positive number."
},
created: {
is: ["undefined", "array"],
ok: function(v) !v || (v.length > 0 && checkArrayElementsType(v, "date", true)),
msg: "Bookmark creation times must be an array of two optional Date objects."
},
modified: {
is: ["undefined", "array"],
ok: function(v) !v || (v.length > 0 && checkArrayElementsType(v, "date", true)),
msg: "Bookmark modification times must be an array of two optional Date objects."
}
}),
msg: "Bookmarked configuration is incorrect."
}),
visited: apiUtils.validateOptions(userOptions.visited, {
is: ["undefined", "object", "boolean"],
ok: function (v) !v || apiUtils.validateOptions(userOptions.visited, {
count: {
is: ["undefined", "array"],
ok: function(v) !v || (v.length > 0 && checkArrayElementsType(v, "number", true)),
msg: "Visit count must be an array of two optional numbers."
},
transitions: {
is: ["undefined", "array"],
ok: function(v) !v || (v.length > 0 && checkArrayElementsType(v, "number", true)),
msg: "Transitions must be an array of valid transition values."
},
when: {
is: ["undefined", "array"],
ok: function(v) !v || (v.length > 0 && checkArrayElementsType(v, "date", true)),
msg: "Visit times must be an array of two optional Date objects."
},
includeAllVisits: {
is: ["undefined", "boolean"]
}
}),
msg: "Visited configuration is incorrect."
}),
sortBy: {
is: ["undefined", "string"],
ok: function(v) !v || ["none", "title", "time", "uri", "accessCount",
"lastModified", "frecency"].indexOf(v) != -1,
msg: "Sorting must define an acceptable string for by."
},
sortDir: {
is: ["undefined", "string"],
ok: function(v) !v || ["asc", "desc"].indexOf(v) != -1,
msg: "sorting must define an acceptable direction."
},
limit: {
is: ["undefined", "number"],
ok: function (v) !v || v > 0,
msg: "Can limit only on positive number of results."
},
onResult: {
is: ["undefined", "function"]
},
onComplete: {
is: ["undefined", "function"]
},
onChange: {
is: ["undefined", "function"]
},
onRemove: {
is: ["undefined", "function"]
}
});
// This will only contain visited or bookmarked properties.
additionalOptions = apiUtils.validateOptions(additionalOptions, {
visited: {
is: ["undefined", "object", "boolean"]
},
bookmarked: {
is: ["undefined", "object", "boolean"]
},
});
// Do the merge.
for (let prop in additionalOptions) {
if (!userOptions[prop])
userOptions[prop] = additionalOptions[prop];
}
return userOptions;
}
// Defaults for bookmark properties.
let bookmarkDefaults = {
title: null,
type: "bookmark",
folder: PlacesUtils.unfiledBookmarksFolderId,
position: PlacesUtils.bookmarks.DEFAULT_INDEX,
tags: []
};
function validateBookmarkInfo(aOptions, aProvideDefaults) {
aOptions = apiUtils.validateOptions(aOptions, {
location: {
map: function(v) v.toString(),
is: ["undefined", "string"],
ok: function(v) !v || v.length > 0,
msg: "Bookmark location must be a non empty string."
},
title: {
map: function(v) v.toString(),
is: ["undefined", "string"],
ok: function(v) !v || v.length > 0
},
folder: {
is: ["undefined", "number"],
ok: function(v) !v || v > 0,
msg: "Required containing folder id must be a positive number."
},
position: {
is: ["undefined", "number"],
ok: function(v) !v || v >= 0,
msg: "Bookmark position, if present, must be a non-negative number."
},
tags: {
is: ["undefined", "array"],
ok: function(v) !v || (v.length > 0 && checkArrayElementsType(v, "string")),
msg: "Tags must be a valid array of strings."
},
//annotations: validateAnnotations,
type: {
is: ["undefined", "string"],
ok: function(v) !v || ["bookmark", "separator", "folder"].indexOf(v) != -1,
msg: "Bookmark type must be one of: bookmark, separator or folder."
},
onCreate: {
is: ["undefined", "function"],
}
});
if (aProvideDefaults && !aOptions.type) {
function checkProps(aObject, aDefaultObject) {
for (let prop in aDefaultObject) {
if (!(prop in aObject))
aObject[prop] = aDefaultObject[prop];
else if (typeof(aObject[prop]) == "object")
checkProps(aObject[prop], aDefaultObject[prop])
}
}
checkProps(aOptions, bookmarkDefaults);
if (aOptions.type == "bookmark" &&
!("location" in aOptions) || aOptions.title.length == 0)
throw new Error("Must provide a valid location for the bookmark.");
}
return aOptions;
}
let validateAnnotations = {
is: ["undefined", "array"],
ok: function(v) {
return !v || (v.length > 0 &&
checkArrayElementsType(v, "object") &&
v.every(function(a) a.name && a.value))
},
msg: "Annotations must be a valid array of { name: '', value: '' } objects."
};
/**
* An object that is returned by .search() and can be used to act on
* entries.
*/
function PlacesSearch(aOptions) {
let query = new PlacesQuery(aOptions);
this.change = function PS_change(aChangeOptions) {
// Allow editing of bookmark properties if a bookmark query.
if ("bookmarked" in aOptions) {
validateBookmarkInfo(aChangeOptions);
}
else {
throw new Error("Editing of history is not supported at this time.");
}
/*
// Otherwise only validate annotation properties
else {
aChangeOptions = apiUtils.validateOptions(aChangeOptions, {
annotations: validateAnnotations
});
}
*/
// When the owning query has finished, pass results to the walker that
// will make the changes, re-query to update the results, and then call
// the user's callback.
function changeCallback() {
new QueryExecutor(query, null, aOptions.onChange, aOptions);
}
let walker = new Walker(changeCallback, {}, function(result) {
let txns = [];
if ("bookmarked" in aOptions) {
let bs = PlacesUtils.bookmarks;
// location
if (aChangeOptions.location)
txns.push(new PlacesEditBookmarkURITransaction(result._itemId,
PlacesUtils._uri(aChangeOptions.location)));
// title
if (aChangeOptions.title) {
txns.push(new PlacesEditItemTitleTransaction(result._itemId, aChangeOptions.title));
}
// folder & position
if (aChangeOptions.folder != undefined || aChangeOptions.position != undefined) {
let position = (aChangeOptions.position === undefined) ? -1 : aChangeOptions.position;
txns.push(new PlacesMoveItemTransaction(result._itemId,
aChangeOptions.folder || result.folder,
position));
}
// tags
if (aChangeOptions.tags) {
let uri = PlacesUtils._uri(aChangeOptions.location || result.location);
txns.push(new PlacesTagURITransaction(uri, aChangeOptions.tags));
}
/*
// annotations
if (aChangeOptions.annotations) {
aChangeOptions.annotations.forEach(function(anno) {
txns.push(new PlacesSetItemAnnotationTransaction(result._itemId, anno));
});
}
*/
}
else if (aChangeOptions.annotations) {
aChangeOptions.annotations.forEach(function(anno) {
txns.push(new PlacesSetPageAnnotationTransaction(result.location, anno));
});
}
(new PlacesAggregatedTransaction("Changing " + result.title, txns)).doTransaction();
});
new QueryExecutor(query, null, walker.run, walker);
};
this.remove = function PS_remove() {
if (!("bookmarked" in aOptions)) {
throw new Error("Removal of history is not supported at this time.");
}
// When the owning query has finished, pass results to the walker that
// will make the changes, re-query to update the results, and then call
// the user's callback.
function removeCallback() {
new QueryExecutor(query, null, aOptions.onRemove, aOptions);
}
// When the owning query has finished, pass results to the walker that
// will remove them from the database.
let walker = new Walker(removeCallback, aOptions, function(result) {
(new PlacesRemoveItemTransaction(result._itemId)).doTransaction();
});
new QueryExecutor(query, null, walker.run, walker);
};
if (aOptions.onResult || aOptions.onComplete)
new QueryExecutor(query, aOptions.onResult, aOptions.onComplete, aOptions);
}
PlacesSearch.prototype = {}
/**
* Executes a query and receives results from it.
*/
function QueryExecutor(aPlacesQuery, aOnResult, aOnComplete, aScope) {
this.onResult = aOnResult;
this.onComplete = aOnComplete;
this.scope = aScope;
this.results = [];
aPlacesQuery.execute(this.resultsCallback, this);
}
QueryExecutor.prototype = {
resultsCallback: function QX_resultsCallback(aResult) {
// Query has finished returning results and caller registered onComplete
// so pass results to it.
if (!aResult && this.onComplete) {
this.scope.results = this.results;
safeCallback(null, this.onComplete, this.scope);
}
// Caller registered an onComplete, so don't send results until then.
else if (this.onComplete)
this.results.push(new Place(aResult));
// Send individual result to the caller.
if (this.onResult)
safeCallback(new Place(aResult), this.onResult, this.scope);
}
}
/**
* Walks through all results from an owning query that are passed to run,
* then calls aUserCallback in the scope of aUserScope. It will also set
* the results of the owning query as aUserScope.results. This ensures that
* when query results have their change/remove methods called, the result set
* is updated to reflect those calls.
*/
function Walker(aUserCallback, aUserScope, aMapFunction) {
this.userCallback = aUserCallback;
this.userScope = aUserScope;
this.mapFunction = aMapFunction;
}
Walker.prototype = {
run: function WLKR_run() {
// Process results.
this.results.forEach(this.mapFunction);
if (this.userScope)
this.userScope.results = this.results;
if (this.userCallback)
safeCallback(null, this.userCallback, this.userScope || undefined);
}
}
/**
* Place object, representing a single result in a set of search results.
*/
function Place(aOptions) {
for (var i in aOptions) {
switch (i) {
// Omitted for now.
case "pageId": // id from moz_places table, used for sql queries
case "referringVisitId":
case "revHost":
case "sessionId":
case "transitionType":
case "type": // type const from nsINavBookmarksService
case "visitId":
continue;
break;
// Rename bookmarkIndex to position.
case "bookmarkIndex":
this.position = aOptions[i];
break;
// Id from moz_bookmarks table, used for the internal boomark apis.
// HACK: Expose as "private" because we need to access it for
// internal use such as deletion, and query folders.
case "itemId":
this._itemId = aOptions[i];
break;
// Rename parentId to folder.
case "parentId":
this.folder = aOptions[i];
// Rename readableType to bookmarkType.
case "readableType":
this.type = aOptions[i] == "container" ? "folder" : aOptions[i];
break;
// Rename referringUri to referrer.
case "referringUri":
this.referrer = aOptions[i];
break;
// Rename uri to location.
case "uri":
this.location = aOptions[i];
break;
// Name/value does not need to change.
case "accessCount":
case "dateAdded":
case "frecency":
case "host":
case "icon": // is a URL, should rename to iconURL?
case "isBookmarked":
case "lastModified":
case "tags":
case "title":
case "time":
this[i] = aOptions[i];
break;
}
}
}
/******************************************************************************
* THE CODE FROM HERE TO THE END OF THE FILE IS THE JETPACK-LESS PLACES QUERY
* MODULE. IT MUST REMAIN JETPACK-FREE. ANY MODIFICATIONS MUST BE FILED AS
* BUGS AND MARKED AS BLOCKING BUG 522572.
*****************************************************************************/
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: sw=2 ts=2 sts=2 expandtab
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Mozilla Corporation.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Marco Bonardo <mak77@bonardo.net> (original author)
* David Dahl <ddahl@mozilla.com>
* Dietrich Ayala <dietrich@mozilla.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
//const EXPORTED_SYMBOLS = ["PlacesQuery"];
/* This is a pure async querying API.
* It provides non-liveupdating query results passed to a callback function.
*
* NOTE: history results returned by this object may be up to two minutes behind
* since it does not handle TEMP tables. We plan to remove them, so this bad
* behavior will be rectified at that point.
*
* TODO:
* - Hierarchal queries.
* - Accept a place: uri as input.
* - Par querying capabilities with the old querying API.
* - Faster queries.
* - Create a PlacesLiveQuery wrapper that will query through an internal
* PlacesQuery object and then will maintain an updated copy of the results.
* - Use PlacesLiveQuery wrapper in our views.
* - Add further querying capabilities.
*
* EXAMPLE:
*
* let query = new PlacesQuery({_QueryConf_});
*
* query.execute(function(result) {
* if (result)
* dump("Got a result: " + [result.title, result.uri, result.readableType].join(", "));
* else
* dump("Finished executing query!\n");
* }, this);
*
*
* _QueryConf_ = {
* phrase: string.
* Containing this string in either title, uri or tags. Case
* insensitive. Can use ^ and $ to match at beginning or end.
* host: string.
* Containing this string in the host. Case insensitive.
* Can use ^ and $ to match at beginning or end.
* uri: string.
* Containing this string in the uri. Case insensitive.
* Can use ^ and $ to match beginning or end.
* annotated: array of strings.
* With these annotations (Either page or item).
* bookmarked: object
* {
* tags: array of strings.
* Tagged with these tags.
* folder: number.
* Inside this folder. (non-recursive)
* position: number.
* At this position. (relative to folder).
* If undefined or null matches all children.
* If no folder is defined, position is ignored.
* id: number.
* Bookmarked with this id.
* createdBegin: optional Date object
* Bookmarks created after this time (included).
* Defaults to epoch.
* createdEnd: optional Date object
* Bookmarks created before this time (included).
* Defaults to now.
* modifiedBegin: optional Date object
* Bookmarks modified after this time (included).
* Defaults to epoch.
* modifiedEnd: optional Date object
* Bookmarks modified before this time (included).
* Defaults to now.
* onlyContainers: boolean.
* Removes any non-container from results.
* Default is false.
* excludeReadOnlyContainers: boolean.
* Removes read only containers from results.
* Default is false.
* }
* visited: object
* {
* countMin: optional number.
* With more than this many visits.
* Defaults to 0.
* This is lazily based on visit_count, thus is not going to work
* for not counted transitions: embed, download, framed_link.
* countMax: optional number.
* With less than this many visits.
* Defaults to inf.
* This is lazily based on visit_count, thus is not going to work
* for not counted transitions: embed, download, framed_link.
* transitions: array of transition types.
* With at least one visit for each of these transitions.
* begin: optional Date object
* With visits after this time (included).
* Defaults to epoch.
* end: optional Date object
* With visits before this time (included).
* Defaults to now.
* excludeRedirectSources: boolean.
* Removes redirects sources from results.
* Default is false.
* excludeRedirectTargets: boolean.
* Removes redirects targets from results.
* Default is false.
* includeHidden: boolean.
* Includes also pages marked as hidden.
* Default is false.
* includeAllVisits: boolean.
* Returns all visits ungrouped.
* Default is false, that means visits are grouped by uri.
* }
* sortBy: string.
* Either "none", "title", "time", "uri", "accessCount", "lastModified",
* "frecency". Defaults to "none".
* sortDir: string.
* Either "asc" or "desc". Defaults to "asc".
* group: string.
* Either "tags", "containers", "days", "months", "years" or "domains".
* Defaults to "none".
* NOTE: Not yet implemented.
* limit: number.
* Maximum number of results to return. Defaults to all results.
* merge: string.
* How to merge this query's results with others in the same request.
* Valid values:
* - "union": merge results from the 2 queries.
* - "except": exclude current results from the previous ones.
* - "intersect": only current results that are also in previous ones.
* }
*
*/
////////////////////////////////////////////////////////////////////////////////
//// Constants and Getters
//const Cc = Components.classes;
//const Ci = Components.interfaces;
//const Cr = Components.results;
//const Cu = Components.utils;
const TAGS_SEPARATOR = ", ";
const TAGS_SQL_FRAGMENT =
"("
+ "SELECT GROUP_CONCAT(tag_title, ', ') "
+ "FROM ( "
+ "SELECT t_t.title AS tag_title "
+ "FROM moz_bookmarks b_t "
+ "JOIN moz_bookmarks t_t ON t_t.id = b_t.parent "
+ "WHERE b_t.fk = h.id "
+ "AND LENGTH(t_t.title) > 0 "
+ "AND t_t.parent = :tags_folder "
+ "ORDER BY t_t.title COLLATE NOCASE ASC "
+ ") WHERE b.id NOTNULL "
+ ")";
const REFERRING_URI_SQL_FRAGMENT =
"("
+ "SELECT refh.url FROM moz_places refh "
+ "JOIN moz_historyvisits refv ON refh.id = refv.place_id "
+ "WHERE refv.id = v.from_visit "
+ ")";
Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
Cu.import("resource://gre/modules/Services.jsm", this);
Cu.import("resource://gre/modules/PlacesUtils.jsm", this);
XPCOMUtils.defineLazyGetter(this, "DB", function() {
return PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase)
.DBConnection;
});
////////////////////////////////////////////////////////////////////////////////
//// Utils and Helpers
function checkType(entry, type) {
switch (type) {
case "undefined":
return entry === undefined;
case "null":
return entry === null;
case "date":
return Object.prototype.toString.call(entry) === "[object Date]";
case "array":
// TODO: Use ES5 isArray() once available.
// NOTE: current method fails if the array comes from JSON.parse.
return Object.prototype.toString.call(entry) === "[object Array]";
default:
if (entry === null) // typeof(null) == "object" but we have a "null" type.
return false;
return typeof(entry) == type;
}
}
function checkArrayElementsType(array, type, allowOptionalElement) {
let arrayIsValid = true;
array.every(function(elm) {
if (allowOptionalElement && (elm === undefined || elm === null))
return true;
return arrayIsValid = checkType(elm, type);
});
return arrayIsValid;
}
function isValidArray(aObj, aValidator)
{
let validArray = checkType(aObj, "array");
if (validArray && aValidator) {
if (!checkType(aValidator, "function"))
throw new Error("Array validator must be a function.");
return aValidator(aObj);
}
return validArray;
}
function getReadableItemType(aResultItem, aItemType)
{
if (aItemType) {
// it's a bookmark.
if (!aResultItem.uri || aResultItem.uri.substr(0, 6) == "place:") {
switch (aItemType) {
case Ci.nsINavBookmarksService.TYPE_SEPARATOR:
return "separator";
default:
return "container";
}
}
return "bookmark";
}
if (aResultItem.visitId)
return "visit";
return "page";
}
function getNodeType(aResultItem, aItemType) {
if (aResultItem.transitionType)
return Ci.nsINavHistoryResultNode.RESULT_TYPE_FULL_VISIT;
let isQuery = aResultItem.uri && aResultItem.uri.substr(0, 6) == "place:";
if (aResultItem.isBookmarked) {
if (aItemType == PlacesUtils.bookmarks.TYPE_FOLDER)
return Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER;
if (aItemType == PlacesUtils.bookmarks.TYPE_SEPARATOR)
return Ci.nsINavHistoryResultNode.RESULT_TYPE_SEPARATOR;
if (isQuery && /^place:folder=[^&]+$/i.test(aResultItem.uri))
return Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER_SHORTCUT;
}
return isQuery ? Ci.nsINavHistoryResultNode.RESULT_TYPE_QUERY
: Ci.nsINavHistoryResultNode.RESULT_TYPE_URI;
}
function TextMatch(aText)
{
if (aText.substr(0, 1) == "^")
this.matchBegin = true;
if (aText.substr(-1, 1) == "$")
this.matchEnd = true;
this.exactMatch = this.matchEnd && this.matchBegin;
let cutFrom = this.matchBegin ? 1 : 0;
let cutLen = aText.length - cutFrom - (this.matchEnd ? 1 : 0);
this.value = aText.substr(cutFrom, cutLen);
}
TextMatch.prototype = {
matchBegin: false,
matchEnd: false,
exactMatch: false,
value: "",
getStringForLike: function TM_getStringForLike(aStmt) {
let escValue = aStmt.escapeStringForLIKE(this.value, '/');
if (this.exactMatch)
return escValue;
if (this.matchBegin)
return escValue + "%";
if (this.matchEnd)
return "%" + escValue;
return "%" + escValue + "%";
},
getRegExp: function TM_getRegExp(aUseWordBoundaries) {
let beginMod = aUseWordBoundaries ? "\\b" : "^";
let endMod = aUseWordBoundaries ? "\\b" : "$";
if (this.exactMatch)
return new RegExp(beginMod + this.value + endMod, "i");
if (this.matchBegin)
return new RegExp(beginMod + this.value, "i");
if (this.matchEnd)
return new RegExp(this.value + endMod, "i");
return new RegExp(this.value, "i");
}
}
////////////////////////////////////////////////////////////////////////////////
//// (De)Serializers
const SPECIAL_FOLDERS = {
BOOKMARKS_MENU_FOLDER: PlacesUtils.bookmarksMenuFolderId
, TAGS_FOLDER: PlacesUtils.tagsFolderId
, UNFILED_BOOKMARKS_FOLDER: PlacesUtils.unfiledBookmarksFolderId
, TOOLBAR_FOLDER: PlacesUtils.toolbarFolderId
};
const TIME_REFERENCE = {
0: 0 // EPOCH
, 1: new Date().setHours(0,0,0,0) * 1000 // TODAY'S START
, 2: Date.now() * 1000 // NOW
};
function deserializeLegacyPlaceUrl(aUrl) {
let queryConfs = [];
// Strip "place:" scheme.
aUrl = aUrl.substr(7);
// Split multiple queries.
let queries = aQuery.split("OR");
// Put each param in an array of objects like { name:, value: }.
let re = new RegExp("([^?=&]+)(=([^&]*))?", "gi");
queries.forEach(function(aQuery) {
let params = {};
let match = null;
while ((match = re.exec(aQuery))) {
let name = match[1].toLowerCase();
let value = match[3];
// Same key can have multiple params, for simplicity make values arrays.
if (!(name in params))
params[name] = [];
params[name].push(value);
};