forked from kotarf/Smart-Bookmark-Sorter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbookmarksorter.js
1469 lines (1277 loc) · 43.7 KB
/
bookmarksorter.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
// Copyright (c) 2013 ICRL
// See the file license.txt for copying permission.
/******* BOOKMARK SORTER *******/
(function(global) {
global.SmartBookmarkSorter = {
/** SmartBookmarkSorter configuration properties. These are all constants. */
config : {
requestCategoryURL : "http://access.alchemyapi.com/calls/url/URLGetCategory",
requestTitleURL : "http://access.alchemyapi.com/calls/url/URLGetTitle",
requestTopicURL : "http://access.alchemyapi.com/calls/url/URLGetRankedConcepts",
apiStorageKey : "bookmarksort_apikey",
oldBookmarkDaysKey : "bookmarksort_oldarchive",
autoSortActiveKey : "bookmarksort_auto_on",
autoSortCreateKey : "bookmarkauto_oncreate",
autoSortTimedKey : "bookmarkauto_timed",
autoSortPriorityKey : "bookmarkauto_priority",
outputMode : "json",
autoSortMinutes : 5,
indexCounter : "bookmarkIndexCounter",
oldBookmarkDaysDefault : 7,
bookmarkAlarm : "bookmarkAlarm",
rootBookmarksId : "1",
rootBookmarksIndex : 0,
otherBookmarksIndex : 1,
sampleNumber : 5,
categoryErrorScore : .5,
unsortedFolderName : "unsorted",
redoCode : "_REDO",
okStatus : "OK",
dailyLimitError : "daily-transaction-limit-exceeded",
sortBeginMsg : "sortBegin",
sortSuccessfulMsg : "sortSuccessful",
sortCompleteMsg : "sortComplete",
isSortingKey : "isSorting",
isOnCreateSortingKey : "isSortingOnCreate",
isOnIntervalSortingKey : "isSortingInterval",
isOnManualSortingKey : "isSortingManual"
},
/**
* Enable the automatic create sort.
* Sorts bookmarks as they are created
*/
attachCreateSort : function () {
/* When a bookmark is created, it will be moved to an appropriate Title folder." */
this.chromeBookmarkOnCreated(this.onCreatedListener);
},
/**
* Enable the automatic timed sort.
* Sorts older bookmarks on a timed interval.
*/
attachIntervalSort : function () {
/* On a timed interval, older bookmarks will be archived to a Category folder and loose bookmarks will be sorted. */
this.chromeDeployAlarm(this.config.bookmarkAlarm, this.intervalAlarm, this.config.autoSortMinutes);
},
/**
* Enable the automatic visit sort.
* Will send bookmarks to the top as they are accessed.
*/
attachVisitSort : function () {
/*When visiting a URL, a matching bookmark will be moved up. <TODO?> If it's in an archive, it will be taken out. */
this.chromeHistoryOnVisited(this.onVisitedListener);
},
/**
* Detaches the automatic create sort
*/
detachCreateSort : function () {
this.chromeBookmarksDetachCreated(this.onCreatedListener);
},
/**
* Detaches the automatic interval sort
*/
detachIntervalSort : function () {
// TODO clear alarm by name
this.chromeClearAlarms();
},
/**
* Detaches the automatic visit sort
*/
detachVisitSort : function () {
this.chromeHistoryDetachVisited(this.onVisitedListener);
},
/**
* Enables automatic sort
* Checks local storage configuration values to determine which sorts to enable
*/
enableAutomaticSort : function () {
var me = this,
isOnCreate = me.getAutoOnCreate(),
isOnInterval = me.getAutoInterval(),
isPrioritize = me.getAutoPrioritize(),
isSorting = me.getIsSorting();
if(isOnCreate && !isSorting)
me.attachCreateSort();
if(isOnInterval)
me.attachIntervalSort();
if(isPrioritize)
me.attachVisitSort();
},
/**
* Disables automatic sort
* Drops all of the attached sorts
*/
disableAutomaticSort : function () {
var me = this;
me.detachCreateSort();
me.detachVisitSort();
me.detachIntervalSort();
},
/**
* Listener for the onCreated automatic sort
* @param {id} id The id of the bookmark that was just created.
* @param {bookmark} bookmark The bookmark that was just created.
*/
onCreatedListener : function (id, bookmark)
{
console.log("****************ON CREATE LISTENER KICKED OFF****************", id, bookmark);
// Sort the bookmark by title
var me = this,
SBS = me.SmartBookmarkSorter,
deferred = $.Deferred();
// Always re-attach create sort if it should be enabled, but only after a bookmark is sorted
deferred.always(function() {
SBS.setIsOnCreateSorting(false);
// If auto create should be on, re-attach it
if (SBS.getAutoOnCreate() && SBS.getAutoOn() && !SBS.getIsSorting()) {
SBS.attachCreateSort();
}
});
// Set is sorting
SBS.setIsOnCreateSorting(true);
// Disable the bookmark onCreate listener, because programmatic creation of bookmarks/folders will kick off the event
SBS.detachCreateSort();
SBS.sortBookmark(bookmark, function(){
deferred.resolve();
}, deferred);
},
/**
* Listener for the onVisited automatic sort
* Searches through bookmarks for a URL match
* @param {HistoryItem} result The HistoryItem of the URL that was visited.
*/
onVisitedListener : function (result)
{
var url = result.url,
me = this,
SBS = me.SmartBookmarkSorter,
isSorting = SBS.getIsSorting();
// Check if any sorting is in progress, if so do not move anything
if (!isSorting) {
// Check if a matching bookmark exists
SBS.searchBookmarks(url, function(results) {
var result = results[0];
// Matching bookmark to url exists
if(result !== undefined)
{
var id = result.id;
var parentId = result.parentId;
if ( parentId !== SBS.config.rootBookmarksId ) {
// Move it to the top of other bookmarks if it's not in root bookmarks
SBS.getOtherBookmarks(function(result) {
var otherBookmarksId = result.id;
var destination = {
parentId : otherBookmarksId,
index : 0
};
SBS.moveBookmark(id, destination, function() {});
});
}
}
// Otherwise, do nothing.
});
}
},
/**
* Listener for the onInterval automatic sort
* Iterates through bookmarks on a timed interval, sorting older ones
* @param {Alarm} alarm The alarm to attach.
* @config {int} [oldBookmarkDays] Sort bookmarks that are older than this in days
* @config {int} [rootBookmarksIndex] Index of root bookmarks
* @config {int} [otherBookmarksIndex] Index of other bookmarks
*/
intervalAlarm : function (alarm)
{
// Get the local counter or start it at 0
var me = this.SmartBookmarkSorter,
counterKey = me.config.indexCounter,
counterValue = me.jQueryStorageGetValue(counterKey) || 0;
console.log("Interval alarm - ", counterValue);
// Get the ID of other bookmarks folder
me.getBookmarkChildren(me.config.rootBookmarksIndex.toString(), function(results) {
var otherBookmarksId = results[me.config.otherBookmarksIndex].id;
// Get the children of other Bookmarks
me.getBookmarkChildren(otherBookmarksId, function(results) {
// Get the bookmark at the current index
var bookmark = results[counterValue];
if(bookmark !== undefined) {
// Check if the URL hasn't been visited in a while
var title = bookmark.title,
url = bookmark.url,
myId = bookmark.id,
baseUrl = me.getBaseUrl(url),
deferred = $.Deferred();
// Could be a folder
if(url !== undefined)
{
// Always re-attach create sort if it should be enabled, but only after a bookmark is sorted
deferred.always(function() {
me.setIsOnAlarmSorting(false);
if (me.getAutoOnCreate() && me.getAutoOn() && !me.getIsSorting()) {
me.attachCreateSort();
}
});
// Set is sorting
me.setIsOnAlarmSorting(true);
// Disable the bookmark onCreate listener, because programmatic creation of bookmarks/folders will kick off the event
me.detachCreateSort();
// Sort the bookmark if it's older than the configured amount
me.sortIfOld(bookmark, me, function(result, deferred){
deferred.resolve();
}, deferred);
}
}
// Otherwise, do nothing.
// Set the counter to the next index, or 0 if it is the tail
var incCounter = counterValue < results.length ? counterValue + 1 : 0;
me.jQueryStorageSetValue(counterKey, incCounter);
});
});
},
/**
* Attach import listeners
*/
attachImportListeners : function() {
this.chromeOnImportBegan(this.onImportBeganListener);
this.chromeOnImportEnd(this.onImportEndListener);
},
/**
* When an import starts, disable automatic sort
*/
onImportBeganListener : function () {
// When an import starts, disable automatic sort
var me = this.SmartBookmarkSorter;
me.disableAutomaticSort();
},
/**
* When an import ends, enable automatic sort if it is configured to be enabled
*/
onImportEndListener : function() {
// When an import ends, enable automatic sort
var me = this.SmartBookmarkSorter,
isAutoSort = me.getAutoOn();
if (isAutoSort) {
me.enableAutomaticSort();
}
},
/**
* Sorts a single bookmark
* Makes two folders and puts the bookmark in the 2nd folder
* @param {BookmarkTreeNode} bookmark The bookmark to sort.
* @param {function} callback The bookmark to sort.
* @param {object} deferred The deferred object to resolve [JQuery whenSync].
*/
sortBookmark : function (bookmark, callback, deferred) {
var me = this;
me.createFolderByCategory(bookmark.url, undefined, function(result) {
me.createFolderByTitle(bookmark.url, result.id, function(result) {
var destination = {
index : 0,
parentId : result.id
};
// Move the bookmark to that folder only if there is a successful result
if (result !== undefined && result !== null) {
me.moveBookmark(bookmark.id, destination, function(result){
callback.call(me, result, deferred);
});
} else {
callback.call(me, result, deferred);
}
});
});
},
/**
* Sorts a bookmark if it is older than the configured age
* @param {BookmarkTreeNode} bookmark The bookmark to sort.
* @param {object} scope The scope to run the function in.
* @param {function} callback The bookmark to sort.
* @param {object} deferred The deferred object to resolve [JQuery whenSync].
*/
sortIfOld : function(bookmark, scope, callback, deferred) {
var me = scope;
if (bookmark !== undefined) {
var myId = bookmark.id;
var url = bookmark.url;
// It may be a folder
if (url !== undefined) {
var oldBookmarkDays = me.getOldBookmarkDays();
// Get visits for the url
me.chromeGetVisits(url, function(results){
if(results !== undefined) {
var visit = results[0];
if (visit !== undefined)
{
var visitTime = visit.visitTime;
var currentTime = new Date();
var daysBetween = me.daysBetween(visitTime, currentTime.getTime());
if (oldBookmarkDays === 0 || ( daysBetween > oldBookmarkDays) ) {
// Sort the bookmark
me.sortBookmark(bookmark, callback, deferred);
} else {
// Move the bookmark to the top of other bookmarks
me.getOtherBookmarks(function(result) {
var otherBookmarksId = result.id;
var destination = {
parentId : otherBookmarksId,
index : 0
};
me.moveBookmark(myId, destination, function() {
callback.call(me, undefined, deferred);
});
});
}
} else {
// No history on this item... sort it anyways.
me.sortBookmark(bookmark, callback, deferred);
}
}
});
}
}
},
/**
* Creates a folder by the category of the given URL
* Makes an Alchemy API request to check the category if it is not already cached
* @param {string} url The url to lookup.
* @param {string} parentId The parentId to create the folder in.
* @param {function} callback The callback to run after creating the folder.
*/
createFolderByCategory : function (url, parentId, callback)
{
var me = this;
me.alchemyCategoryLookup(url, function(category) {
me.createFolder(category, parentId, callback);
});
},
/**
* Creates a folder by the title of the given URL
* Makes an Alchemy API request to check the title if it is not already cached
* @param {string} url The url to lookup.
* @param {string} parentId The parentId to create the folder in.
* @param {function} callback The callback to run after creating the folder.
*/
createFolderByTitle : function (url, parentId, callback) {
var me = this;
me.alchemyTitleLookup(url, function(title) {
me.createFolder(title, parentId, callback);
});
},
/**
* Makes an Alchemy API request to check the category if it is not already cached
* TODO merge category and title functions together
* @param {string} url The url to lookup.
* @param {function} callback The callback to run after the REST request completes.
*/
alchemyCategoryLookup : function (url, callback)
{
var me = this,
cachedData = me.jQueryStorageGetValue(url);
baseUrl = me.getBaseUrl(url);
// Check if there is cached data
if(cachedData === null || cachedData.category === undefined) {
console.log("Making a CATEGORY request for - ", url);
// If not, make an API request.
me.alchemyCategory(url, function(data, textStatus, jqXHR) {
var category = data.category,
title = undefined,
status = data.status,
statusInfo = data.statusInfo,
score = data.score;
// Check the status first
if (status === me.config.okStatus && score && category) {
// If the score of the result is horrible, redo the whole thing using the baseUrl (if not already using it)
var score = data.score;
if (score < me.config.categoryErrorScore && baseUrl !== url ) {
// Redo the categorization with the base URL because the result was not good enough
console.log("*** REDOING CAT ON SCORE *** with baseUrl = ", baseUrl, " and category ", category);
// Cache it as a redo
me.cacheCategory(cachedData, url, me.config.redoCode);
me.alchemyCategoryLookup(baseUrl, callback);
} else {
// Cache the category
me.cacheCategory(cachedData, url, category);
// Invoke the callback
callback.call(me, category);
}
} else {
// Error handling
console.log("*****ERROR CAT********= ", data, " for url = " , url);
if(statusInfo == me.config.dailyLimitError) {
// Daily limit reached must stop the chain
me.chromeSendMessage(me.config.dailyLimitError);
} else if (baseUrl !== url) {
// Otherwise the page isn't HTML- fall back on the base URL.
console.log("*** REDOING CAT ON ERROR *** with baseUrl = ", baseUrl);
// Cache the redo
me.cacheCategory(cachedData, url, me.config.redoCode);
// Redo
me.alchemyCategoryLookup(baseUrl, callback);
} else {
// Cannot read this page- resolve with Unsorted after caching as unsorted
category = me.config.unsortedFolderName;
// Cache the category
me.cacheCategory(cachedData, url, category);
// Invoke the callback
callback.call(me, category);
}
}
});
} else {
// Cached category
var category = cachedData.category;
// If a Redo is cached, call it with the baseUrl
if (category === me.config.redoCode) {
me.alchemyCategoryLookup(baseUrl, callback);
} else {
// Invoke the callback
callback.call(me, category);
}
}
},
/**
* Makes an Alchemy API request to check the title if it is not already cached
* @param {string} url The url to lookup.
* @param {function} callback The callback to run after the REST request completes.
*/
alchemyTitleLookup : function (url, callback) {
// Check local cache to see if the base URL has associated data.
var me = this,
baseUrl = me.getBaseUrl(url),
cachedData = me.jQueryStorageGetValue(baseUrl);
// If not, make an API request.
if(cachedData === null || cachedData.title === undefined)
{
console.log("Making a TITLE request for - ", url);
me.alchemyTitle(baseUrl, function(data, textStatus, jqXHR) {
var title = data.title,
category = undefined,
status = data.status,
statusInfo = data.statusInfo;
// Check the status first
if (status === me.config.okStatus && title) {
// Cache the title
me.cacheTitle(cachedData, baseUrl, title);
// Invoke the callback
callback.call(me, title);
} else {
// Error handling
console.log("*****ERROR TITLE********= ", data, " for url = " , url);
if(statusInfo == me.config.dailyLimitError) {
// Daily limit reached must stop the chain
me.chromeSendMessage(me.config.dailyLimitError);
} else {
// Cannot read this page- resolve with Unsorted after caching as unsorted
title = me.config.unsortedFolderName;
// Cache the title
me.cacheTitle(cachedData, baseUrl, title);
// Invoke the callback
callback.call(me, title);
}
}
});
}
else
{
// Cached title
var title = cachedData.title;
// Invoke the callback
callback.call(me, title);
}
},
/**
* Store the title (value) by the url (key)
* This could be refactored along with with half of my code
* @param {object} cachedData The cachedData object that was retrieved
* @param {string} url The url to store by
* @param {string} title The title to store
*/
cacheTitle : function(cachedData, url, title) {
// Category data may already exist
var category = undefined,
me = this;
if(cachedData !== null) {
category = cachedData.category;
}
// Cache the title in local storage
me.jQueryStorageSetValue(url, {title: title, category: category});
},
/**
* Store the category (value) by the url (key)
* @param {object} cachedData The cachedData object that was retrieved
* @param {string} url The url to store by
* @param {string} category The category to store
*/
cacheCategory : function(cachedData, url, category) {
// Title data may already exist
var title = undefined,
me = this;
if(cachedData !== null) {
title = cachedData.title;
}
// Cache the category in local storage
me.jQueryStorageSetValue(url, {title: title, category: category});
},
/**
* Create folder (if it does not exist) with specified parentID with name, callback
* @param {string} title The title of the folder.
* @param {string} parentId The parentId to create the folder in.
* @param {function} callback The callback to run after the folder is created.
*/
createFolder : function (title, parentId, callback) {
var me = this;
me.searchFolders(parentId, function(bookmark) {return bookmark !== undefined && bookmark.title === title && bookmark.url === undefined},
function(ret) {
if(ret.length > 0){
// Folder already exists - invoke the callback with the first result
callback.call(me, ret[0]);
}
else {
// Create the folder and move to it
var folder = {
title : title,
parentId : parentId
};
// Create the folder
me.createBookmark(folder, function(result) {
// Invoke the callback
callback.call(me, result);
});
}
});
},
/**
* Sort a sample of bookmarks in Other Bookmarks
* @config {int} [sampleNumber] The number of bookmarks to sort in this sample
*/
sortSample : function ()
{
this.sortToplevelBookmarks(this.config.sampleNumber);
},
/**
* Sort all bookmarks in Other Bookmarks
*/
sortAllBookmarks : function()
{
this.sortSubBookmarks(undefined);
},
/**
* Manually sort only top-level bookmarks in the Other Bookmarks folder
* @param {int} num The number of bookmarks to sort. If left undefined, sorts all bookmarks.
*/
sortToplevelBookmarks : function (num)
{
var me = this;
// Get the other bookmarks children
me.getOtherBookmarks(function(result) {
me.getBookmarkChildren(result.id, function(results) {
var bookmarks = me.filterBookmarks(results);
// Sort the bookmarks tree
me.sortBookmarks(bookmarks, num, function(){});
});
});
},
/**
* Sorts all Other Bookmarks, including ones nested in folders.
* @param {number} num Number of bookmarks to sort. If left undefined, sort all bookmarks.
*/
sortSubBookmarks : function (num)
{
var me = this;
// Get the ID of other bookmarks folder
me.getOtherBookmarks(function(result) {
// Get the flattened subtree of bookmark nodes
me.getFlatSubTree(result.id, function(results) {
// Filter out folders
var bookmarks = me.filterBookmarks(results);
// Sort the bookmarks tree
me.sortBookmarks(bookmarks, num, function() {
me.removeEmptyFolders();
});
});
});
},
/**
* Filters out folders from an array of bookmarks and folders.
* @param {array} bookmarksAndFolders An array of bookmarks and folders to filter
*/
filterBookmarks : function (bookmarksAndFolders) {
var bookmarks = [],
i;
for(i = 0; i < bookmarksAndFolders.length; i++) {
if (bookmarksAndFolders[i].url !== undefined) {
bookmarks.push(bookmarksAndFolders[i]);
}
}
return bookmarks;
},
/**
* Manually sorts the given BookmarkTreeNodes. If left undefined, sorts all bookmarks
* This code makes use of JQuery whenSync to chain an arbitrary number of asynchronous callbacks in sequence
* Performance is a concern, because whenSync gives all previous results to each callback in the chain- we don't need that.
* @param {string} rootId The rootId of the folder to sort.
* @param {int} num The number of bookmarks to sort. If left undefined, sorts all bookmarks.
* @config {string} sortBeginMsg Successful message code sent to UI
* @config {string} sortSuccessfulMsg Successful message code sent to UI
* @config {string} sortCompleteMsg Successful message code sent to UI
* @config {boolean} isSorting Successful Local storage variable for in progress sorting
*/
sortBookmarks : function (result, num, callback)
{
var me = this;
// Make an array of sort functors
var sortFuncts = [],
length = (num !== undefined && num < result.length) ? num : result.length;
// Send a message saying the sorting has begun
me.chromeSendMessage(me.config.sortBeginMsg + "," + length);
// Set a local storage variable to sorting in progress
me.setIsOnManualSorting(true);
// Detach create sort
me.detachCreateSort();
// Generate the asynchronous calls in the chain
for(i = 0; i < length; i++) {
// Closure
(function(bookmark, index) {
// Push a function to sort a bookmark at the chained index
sortFuncts.push(
function () {
var deferred = arguments[0];
me.sortIfOld(bookmark, me, function(result, deferred) {
// Send a message to the UI saying there was a successful conversion at the specified index
var msgSort = index;
// Send a message to the UI with the bookmark that was just sorted
me.chromeSendMessage(me.config.sortSuccessfulMsg + "," + msgSort);
// Resolve the deferred object, allowing the chain to continue
deferred.resolve(index);
}, deferred);
}
);
})(result[i], i);
}
// Chained asynchronous callbacks
var asyncChain = me.jQueryWhenSync(me, sortFuncts);
// Bind the done callback to the asynchronous chain.
asyncChain.done(
function(){
// Execute the completion callback
callback.call(me);
}
);
// Bind the always callback to the asynchronous chain
asyncChain.always(
function() {
// Set that we are no longer sorting
me.setIsOnManualSorting(false);
// Send a message to the UI saying we're done
me.chromeSendMessage(SmartBookmarkSorter.config.sortCompleteMsg);
// Reattach the create sort listener if it is enabled
if (me.getAutoOnCreate() && me.getAutoOn() && !me.getIsSorting()) {
me.attachCreateSort();
}
}
);
},
/**
* Gets an array of all bookmarks (children of folders included) with a given parentId
* @param {string} id The parentId to get the full subtree of
* @param {number} num The number of children to grab. If left undefined, grabs everything.
* @param {function} callback The callback to run with the results
*/
getFlatSubTree : function(id, callback) {
var me = this;
me.chromeGetSubTree(id, function(results) {
var result = [];
var enqueue = [];
enqueue.push(results[0]);
while (enqueue.length > 0) {
var element = enqueue.pop();
var elementChildren = element.children;
if (element.children === undefined) {
result.push(element);
} else {
for (var i = 0; i < elementChildren.length; i++) {
enqueue.push(elementChildren[i]);
}
}
}
callback.call(me, result);
});
},
/**
* Removes all empty folders in Other Bookmarks
*/
removeEmptyFolders : function()
{
var me = this;
me.getOtherBookmarks(function(result) {
me.searchFolders(result.id, function(bookmark){return bookmark.url === undefined;}, function(ret) {
// Loop through
me.forEach(ret, function(bookmark) {
// If I'm empty, remove me
me.getBookmarkChildren(bookmark.id, function(results) {
if (results.length == 0) {
me.removeBookmark(bookmark.id, function(){});
}
});
});
});
});
},
/**
* Sets the api key in local storage
* @param {string} apikey The apikey to set
* @config {string} [apiStorageKey] Local storage key for api key
*/
setApiKey : function (apikey)
{
this.jQueryStorageSetValue(this.config.apiStorageKey, apikey);
},
/**
* Gets the api key in local storage
* @config {string} [apiStorageKey] Local storage key for api key
* @returns {string}
*/
getApiKey : function ()
{
return this.jQueryStorageGetValue(this.config.apiStorageKey);
},
/**
* Sets auto create on
* @param {bool} value The boolean to set
* @config {string} [autoSortCreateKey] Local storage key auto create on
*/
setAutoOnCreate : function (value)
{
this.jQueryStorageSetValue(this.config.autoSortCreateKey, value);
},
/**
* Gets the api key in local storage
* @config {string} [autoSortCreateKey] Local storage key for api key
* @returns {bool}
*/
getAutoOnCreate : function ()
{
return this.jQueryStorageGetValue(this.config.autoSortCreateKey);
},
/**
* Sets the auto interval in local storage
* @config {string} [autoSortTimedKey] Local storage key for timed sort
* @param {bool} value The boolean to set
*/
setAutoInterval : function (value)
{
this.jQueryStorageSetValue(this.config.autoSortTimedKey, value);
},
/**
* Get the auto interval in local storage
* @config {string} [autoSortTimedKey] Local storage key for timed sort
* @returns {bool}
*/
getAutoInterval : function ()
{
return this.jQueryStorageGetValue(this.config.autoSortTimedKey);
},
/**
* Sets the auto prioritize in local storage
* @config {string} [autoSortPriorityKey] Local storage key for priority sort
* @param {bool} value The boolean to set
*/
setAutoPrioritize : function (value)
{
this.jQueryStorageSetValue(this.config.autoSortPriorityKey, value);
},
/**
* Get the auto interval in local storage
* @config {string} [autoSortPriorityKey] Local storage key for priority sort
* @returns {bool}
*/
getAutoPrioritize : function ()
{
return this.jQueryStorageGetValue(this.config.autoSortPriorityKey);
},
/**
* Sets the auto sort in local storage
* @config {string} [autoSortActiveKey] Local storage key for auto sort on
* @param {bool} value The boolean to set
*/
setAutoOn : function (value)
{
this.jQueryStorageSetValue(this.config.autoSortActiveKey, value);
},
/**
* Gets the auto sort in local storage
* @config {string} [autoSortActiveKey] Local storage key for auto sort on
* @returns {bool}
*/
getAutoOn : function ()
{
return this.jQueryStorageGetValue(this.config.autoSortActiveKey);
},
/**
* Set the old bookmark days in local storage
* @config {string} [oldBookmarkDaysKey] Local storage key for old bookmark days
* @param {int} value The int to set
*/
setOldBookmarkDays : function (value)
{
this.jQueryStorageSetValue(this.config.oldBookmarkDaysKey, value);
},
/**
* Get the old bookmark days in local storage
* @config {string} [autoSortPriorityKey] Local storage key for old bookmark days
* @config {string} [oldBookmarkDaysDefault] Default old bookmark days
* @returns {int}
*/
getOldBookmarkDays : function ()
{
var oldBookmarkDays = this.jQueryStorageGetValue(this.config.oldBookmarkDaysKey);
return oldBookmarkDays === null ? this.config.oldBookmarkDaysDefault : oldBookmarkDays;
},
/**
* Set the sorting in progress in local storage
* @config {string} [isSortingKey] Sorting in progress key
* @param {int} value The int to set
*/
setIsSorting : function (value)
{
this.jQueryStorageSetValue(this.config.isSortingKey, value);
},
/**
* Get the sorting in progress from storage
* @config {string} [isSortingKey] Sorting in progress key
* @returns {boolean}
*/
getIsSorting : function()
{
var me = this,
manualSorting = me.getIsOnManualSorting(),
createSorting = me.getIsOnCreateSorting(),
alarmSorting = me.getIsOnAlarmSorting(),
isSorting = manualSorting || createSorting || alarmSorting;
return isSorting;
},
/**
* Set the sorting in progress for the manual sorting in local storage
* @config {string} [isOnManualSortingKey] Sorting in progress key
* @param {int} value The int to set
*/
setIsOnManualSorting : function (value)
{
this.jQueryStorageSetValue(this.config.isOnManualSortingKey, value);
},
/**
* Get the sorting in progress from storage
* @config {string} [isOnManualSortingKey] Sorting in progress key
* @returns {boolean}
*/
getIsOnManualSorting : function()