-
Notifications
You must be signed in to change notification settings - Fork 221
/
PlacesConnection.kt
968 lines (871 loc) · 33.5 KB
/
PlacesConnection.kt
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
/* 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/. */
package mozilla.appservices.places
import com.sun.jna.Native
import com.sun.jna.Pointer
import com.sun.jna.StringArray
import mozilla.appservices.support.native.toNioDirectBuffer
import mozilla.appservices.sync15.SyncTelemetryPing
import org.json.JSONArray
import org.json.JSONObject
import org.json.JSONException
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.atomic.AtomicReference
import java.lang.ref.WeakReference
/**
* An implementation of a [PlacesManager] backed by a Rust Places library.
*
* This type, as well as all connection types, are thread safe (they perform locking internally
* where necessary).
*
* @param path an absolute path to a file that will be used for the internal database.
*/
class PlacesApi(path: String) : PlacesManager, AutoCloseable {
private var handle: AtomicLong = AtomicLong(0)
private var writeConn: PlacesWriterConnection
init {
handle.set(rustCall(this) { error ->
LibPlacesFFI.INSTANCE.places_api_new(path, error)
})
writeConn = PlacesWriterConnection(rustCall(this) { error ->
LibPlacesFFI.INSTANCE.places_connection_new(handle.get(), READ_WRITE, error)
}, this)
}
companion object {
// These numbers come from `places::db::ConnectionType`
private const val READ_ONLY: Int = 1
private const val READ_WRITE: Int = 2
}
override fun openReader(): PlacesReaderConnection {
val connHandle = rustCall(this) { error ->
LibPlacesFFI.INSTANCE.places_connection_new(handle.get(), READ_ONLY, error)
}
return PlacesReaderConnection(connHandle)
}
override fun getWriter(): PlacesWriterConnection {
return writeConn
}
@Synchronized
override fun close() {
// Take the write connection's handle and clear its reference to us.
val writeHandle = this.writeConn.takeHandle()
this.writeConn.apiRef.clear()
val handle = this.handle.getAndSet(0L)
if (handle != 0L) {
if (writeHandle != 0L) {
try {
rustCall(this) { err ->
LibPlacesFFI.INSTANCE.places_api_return_write_conn(handle, writeHandle, err)
}
} catch (e: PlacesException) {
// Ignore it.
}
}
rustCall(this) { error ->
LibPlacesFFI.INSTANCE.places_api_destroy(handle, error)
}
}
}
override fun syncHistory(syncInfo: SyncAuthInfo): SyncTelemetryPing {
val pingJSONString = rustCallForString(this) { error ->
LibPlacesFFI.INSTANCE.sync15_history_sync(
this.handle.get(),
syncInfo.kid,
syncInfo.fxaAccessToken,
syncInfo.syncKey,
syncInfo.tokenserverURL,
error
)
}
return SyncTelemetryPing.fromJSONString(pingJSONString)
}
override fun syncBookmarks(syncInfo: SyncAuthInfo): SyncTelemetryPing {
val pingJSONString = rustCallForString(this) { error ->
LibPlacesFFI.INSTANCE.sync15_bookmarks_sync(
this.handle.get(),
syncInfo.kid,
syncInfo.fxaAccessToken,
syncInfo.syncKey,
syncInfo.tokenserverURL,
error
)
}
return SyncTelemetryPing.fromJSONString(pingJSONString)
}
}
internal inline fun <U> rustCall(syncOn: Any, callback: (RustError.ByReference) -> U): U {
synchronized(syncOn) {
val e = RustError.ByReference()
val ret: U = callback(e)
if (e.isFailure()) {
throw e.intoException()
} else {
return ret
}
}
}
@Suppress("TooGenericExceptionThrown")
internal inline fun rustCallForString(syncOn: Any, callback: (RustError.ByReference) -> Pointer?): String {
val cstring = rustCall(syncOn, callback)
?: throw RuntimeException("Bug: Don't use this function when you can return" +
" null on success.")
try {
return cstring.getString(0, "utf8")
} finally {
LibPlacesFFI.INSTANCE.places_destroy_string(cstring)
}
}
internal inline fun rustCallForOptString(syncOn: Any, callback: (RustError.ByReference) -> Pointer?): String? {
val cstring = rustCall(syncOn, callback)
try {
return cstring?.getString(0, "utf8")
} finally {
cstring?.let { LibPlacesFFI.INSTANCE.places_destroy_string(it) }
}
}
@Suppress("TooGenericExceptionCaught")
open class PlacesConnection internal constructor(connHandle: Long) : InterruptibleConnection, AutoCloseable {
protected var handle: AtomicLong = AtomicLong(0)
protected var interruptHandle: InterruptHandle
init {
handle.set(connHandle)
try {
interruptHandle = InterruptHandle(rustCall { err ->
LibPlacesFFI.INSTANCE.places_new_interrupt_handle(connHandle, err)
}!!)
} catch (e: Throwable) {
rustCall { error ->
LibPlacesFFI.INSTANCE.places_connection_destroy(this.handle.getAndSet(0), error)
}
throw e
}
}
@Synchronized
protected fun destroy() {
val handle = this.handle.getAndSet(0L)
if (handle != 0L) {
rustCall { error ->
LibPlacesFFI.INSTANCE.places_connection_destroy(handle, error)
}
}
interruptHandle.close()
}
@Synchronized
override fun close() {
destroy()
}
override fun interrupt() {
this.interruptHandle.interrupt()
}
internal inline fun <U> rustCall(callback: (RustError.ByReference) -> U): U {
return rustCall(this, callback)
}
internal inline fun rustCallForString(callback: (RustError.ByReference) -> Pointer?): String {
return rustCallForString(this, callback)
}
internal inline fun rustCallForOptString(callback: (RustError.ByReference) -> Pointer?): String? {
return rustCallForOptString(this, callback)
}
}
/**
* An implementation of a [ReadableHistoryConnection], used for read-only
* access to places APIs.
*
* This class is thread safe.
*/
open class PlacesReaderConnection internal constructor(connHandle: Long) :
PlacesConnection(connHandle),
ReadableHistoryConnection,
ReadableBookmarksConnection {
override fun queryAutocomplete(query: String, limit: Int): List<SearchResult> {
val json = rustCallForString { error ->
LibPlacesFFI.INSTANCE.places_query_autocomplete(this.handle.get(), query, limit, error)
}
return SearchResult.fromJSONArray(json)
}
override fun matchUrl(query: String): String? {
return rustCallForOptString { error ->
LibPlacesFFI.INSTANCE.places_match_url(this.handle.get(), query, error)
}
}
override fun getVisited(urls: List<String>): List<Boolean> {
// Note urlStrings has a potential footgun in that StringArray has a `size()` method
// which returns the size *in bytes*. Hence us using urls.size (which is an element count)
// for the actual number of urls!
val urlStrings = StringArray(urls.toTypedArray(), "utf8")
val byteBuffer = ByteBuffer.allocateDirect(urls.size)
byteBuffer.order(ByteOrder.nativeOrder())
rustCall { error ->
val bufferPtr = Native.getDirectBufferPointer(byteBuffer)
LibPlacesFFI.INSTANCE.places_get_visited(
this.handle.get(),
urlStrings, urls.size,
bufferPtr, urls.size,
error
)
}
val result = ArrayList<Boolean>(urls.size)
for (index in 0 until urls.size) {
val wasVisited = byteBuffer.get(index)
if (wasVisited != 0.toByte() && wasVisited != 1.toByte()) {
throw java.lang.RuntimeException(
"Places bug! Memory corruption possible! Report me!")
}
result.add(wasVisited == 1.toByte())
}
return result
}
override fun getVisitedUrlsInRange(start: Long, end: Long, includeRemote: Boolean): List<String> {
val urlsJson = rustCallForString { error ->
val incRemoteArg: Byte = if (includeRemote) { 1 } else { 0 }
LibPlacesFFI.INSTANCE.places_get_visited_urls_in_range(
this.handle.get(), start, end, incRemoteArg, error)
}
val arr = JSONArray(urlsJson)
val result = mutableListOf<String>()
for (idx in 0 until arr.length()) {
result.add(arr.getString(idx))
}
return result
}
override fun getVisitInfos(start: Long, end: Long, excludeTypes: List<VisitType>): List<VisitInfo> {
val infoBuffer = rustCall { error ->
LibPlacesFFI.INSTANCE.places_get_visit_infos(
this.handle.get(), start, end, visitTransitionSet(excludeTypes), error)
}
try {
val infos = MsgTypes.HistoryVisitInfos.parseFrom(infoBuffer.asCodedInputStream()!!)
return VisitInfo.fromMessage(infos)
} finally {
LibPlacesFFI.INSTANCE.places_destroy_bytebuffer(infoBuffer)
}
}
override fun getVisitPage(offset: Long, count: Long, excludeTypes: List<VisitType>): List<VisitInfo> {
val infoBuffer = rustCall { error ->
LibPlacesFFI.INSTANCE.places_get_visit_page(
this.handle.get(), offset, count, visitTransitionSet(excludeTypes), error)
}
try {
val infos = MsgTypes.HistoryVisitInfos.parseFrom(infoBuffer.asCodedInputStream()!!)
return VisitInfo.fromMessage(infos)
} finally {
LibPlacesFFI.INSTANCE.places_destroy_bytebuffer(infoBuffer)
}
}
override fun getVisitCount(excludeTypes: List<VisitType>): Long {
return rustCall { error ->
LibPlacesFFI.INSTANCE.places_get_visit_count(
this.handle.get(), visitTransitionSet(excludeTypes), error)
}
}
override fun getBookmark(guid: String): BookmarkTreeNode? {
val rustBuf = rustCall { err ->
LibPlacesFFI.INSTANCE.bookmarks_get_by_guid(this.handle.get(), guid, 0.toByte(), err)
}
try {
return rustBuf.asCodedInputStream()?.let { stream ->
unpackProtobuf(MsgTypes.BookmarkNode.parseFrom(stream))
}
} finally {
LibPlacesFFI.INSTANCE.places_destroy_bytebuffer(rustBuf)
}
}
override fun getBookmarksTree(rootGUID: String, recursive: Boolean): BookmarkTreeNode? {
val rustBuf = rustCall { err ->
if (recursive) {
LibPlacesFFI.INSTANCE.bookmarks_get_tree(this.handle.get(), rootGUID, err)
} else {
LibPlacesFFI.INSTANCE.bookmarks_get_by_guid(this.handle.get(), rootGUID, 1.toByte(), err)
}
}
try {
return rustBuf.asCodedInputStream()?.let { stream ->
unpackProtobuf(MsgTypes.BookmarkNode.parseFrom(stream))
}
} finally {
LibPlacesFFI.INSTANCE.places_destroy_bytebuffer(rustBuf)
}
}
override fun getBookmarksWithURL(url: String): List<BookmarkItem> {
val rustBuf = rustCall { err ->
LibPlacesFFI.INSTANCE.bookmarks_get_all_with_url(this.handle.get(), url, err)
}
try {
val message = MsgTypes.BookmarkNodeList.parseFrom(rustBuf.asCodedInputStream()!!)
return unpackProtobufItemList(message)
} finally {
LibPlacesFFI.INSTANCE.places_destroy_bytebuffer(rustBuf)
}
}
override fun getBookmarkUrlForKeyword(keyword: String): String? {
return rustCallForOptString { error ->
LibPlacesFFI.INSTANCE.bookmarks_get_url_for_keyword(this.handle.get(), keyword, error)
}
}
override fun searchBookmarks(query: String, limit: Int): List<BookmarkItem> {
val rustBuf = rustCall { err ->
LibPlacesFFI.INSTANCE.bookmarks_search(this.handle.get(), query, limit, err)
}
try {
val message = MsgTypes.BookmarkNodeList.parseFrom(rustBuf.asCodedInputStream()!!)
return unpackProtobufItemList(message)
} finally {
LibPlacesFFI.INSTANCE.places_destroy_bytebuffer(rustBuf)
}
}
override fun getRecentBookmarks(limit: Int): List<BookmarkItem> {
val rustBuf = rustCall { err ->
LibPlacesFFI.INSTANCE.bookmarks_get_recent(this.handle.get(), limit, err)
}
try {
val message = MsgTypes.BookmarkNodeList.parseFrom(rustBuf.asCodedInputStream()!!)
return unpackProtobufItemList(message)
} finally {
LibPlacesFFI.INSTANCE.places_destroy_bytebuffer(rustBuf)
}
}
}
fun visitTransitionSet(l: List<VisitType>): Int {
var res = 0
for (ty in l) {
res = res or (1 shl ty.type)
}
return res
}
/**
* An implementation of a [WritableHistoryConnection], use for read or write
* access to the Places APIs.
*
* This class is thread safe.
*/
class PlacesWriterConnection internal constructor(connHandle: Long, api: PlacesApi) :
PlacesReaderConnection(connHandle),
WritableHistoryConnection,
WritableBookmarksConnection {
// The reference to our PlacesAPI. Mostly used to know how to handle getting closed.
val apiRef = WeakReference(api)
override fun noteObservation(data: VisitObservation) {
val json = data.toJSON().toString()
rustCall { error ->
LibPlacesFFI.INSTANCE.places_note_observation(this.handle.get(), json, error)
}
}
override fun deletePlace(url: String) {
rustCall { error ->
LibPlacesFFI.INSTANCE.places_delete_place(
this.handle.get(), url, error)
}
}
override fun deleteVisit(url: String, visitTimestamp: Long) {
rustCall { error ->
LibPlacesFFI.INSTANCE.places_delete_visit(
this.handle.get(), url, visitTimestamp, error)
}
}
override fun deleteVisitsSince(since: Long) {
deleteVisitsBetween(since, Long.MAX_VALUE)
}
override fun importBookmarksFromFennec(path: String) {
rustCall { error ->
LibPlacesFFI.INSTANCE.places_bookmarks_import_from_fennec(
this.handle.get(), path, error)
}
}
override fun importVisitsFromFennec(path: String) {
rustCall { error ->
LibPlacesFFI.INSTANCE.places_history_import_from_fennec(
this.handle.get(), path, error)
}
}
override fun deleteVisitsBetween(startTime: Long, endTime: Long) {
rustCall { error ->
LibPlacesFFI.INSTANCE.places_delete_visits_between(
this.handle.get(), startTime, endTime, error)
}
}
override fun wipeLocal() {
rustCall { error ->
LibPlacesFFI.INSTANCE.places_wipe_local(this.handle.get(), error)
}
}
override fun runMaintenance() {
rustCall { error ->
LibPlacesFFI.INSTANCE.places_run_maintenance(this.handle.get(), error)
}
}
override fun pruneDestructively() {
rustCall { error ->
LibPlacesFFI.INSTANCE.places_prune_destructively(this.handle.get(), error)
}
}
override fun deleteEverything() {
rustCall { error ->
LibPlacesFFI.INSTANCE.places_delete_everything(this.handle.get(), error)
}
}
override fun deleteBookmarkNode(guid: String): Boolean {
val existedByte = rustCall { error ->
LibPlacesFFI.INSTANCE.bookmarks_delete(this.handle.get(), guid, error)
}
return existedByte.toInt() != 0
}
// Does the shared insert work, takes the position just because
// its a little tedious to type out setting it
private fun doInsert(builder: MsgTypes.BookmarkNode.Builder, position: Int?): String {
position?.let { builder.setPosition(position) }
val buf = builder.build()
val (nioBuf, len) = buf.toNioDirectBuffer()
return rustCallForString { err ->
val ptr = Native.getDirectBufferPointer(nioBuf)
LibPlacesFFI.INSTANCE.bookmarks_insert(this.handle.get(), ptr, len, err)
}
}
override fun createFolder(parentGUID: String, title: String, position: Int?): String {
val builder = MsgTypes.BookmarkNode.newBuilder()
.setNodeType(BookmarkType.Folder.value)
.setParentGuid(parentGUID)
.setTitle(title)
return this.doInsert(builder, position)
}
override fun createSeparator(parentGUID: String, position: Int?): String {
val builder = MsgTypes.BookmarkNode.newBuilder()
.setNodeType(BookmarkType.Separator.value)
.setParentGuid(parentGUID)
return this.doInsert(builder, position)
}
override fun createBookmarkItem(parentGUID: String, url: String, title: String, position: Int?): String {
val builder = MsgTypes.BookmarkNode.newBuilder()
.setNodeType(BookmarkType.Bookmark.value)
.setParentGuid(parentGUID)
.setUrl(url)
.setTitle(title)
return this.doInsert(builder, position)
}
override fun updateBookmark(guid: String, info: BookmarkUpdateInfo) {
val buf = info.toProtobuf(guid)
val (nioBuf, len) = buf.toNioDirectBuffer()
rustCall { err ->
val ptr = Native.getDirectBufferPointer(nioBuf)
LibPlacesFFI.INSTANCE.bookmarks_update(this.handle.get(), ptr, len, err)
}
}
override fun acceptResult(searchString: String, url: String) {
rustCall { error ->
LibPlacesFFI.INSTANCE.places_accept_result(
this.handle.get(), searchString, url, error)
}
}
@Synchronized
override fun close() {
// If our API is still around, do nothing.
if (apiRef.get() == null) {
// Otherwise, it must have gotten GCed without calling close() :(
// So we go through the non-writer connection destructor.
destroy()
}
}
@Synchronized
internal fun takeHandle(): PlacesConnectionHandle {
val handle = this.handle.getAndSet(0L)
interruptHandle.close()
return handle
}
}
/**
* A class for providing the auth-related information needed to sync.
* Note that this has the same shape as `SyncUnlockInfo` from logins - we
* probably want a way of sharing these.
*/
class SyncAuthInfo(
val kid: String,
val fxaAccessToken: String,
val syncKey: String,
val tokenserverURL: String
)
/**
* An API for interacting with Places. This is the top-level entry-point, and
* exposes functions which return lower-level objects with the core
* functionality.
*/
interface PlacesManager {
/**
* Open a reader connection.
*/
fun openReader(): ReadableHistoryConnection
/**
* Get a reference to the writer connection.
*
* This should always return the same object.
*/
fun getWriter(): WritableHistoryConnection
/**
* Syncs the places history store, returning a telemetry ping.
*
* Note that this function blocks until the sync is complete, which may
* take some time due to the network etc. Because only 1 thread can be
* using a PlacesAPI at a time, it is recommended, but not enforced, that
* you have all connections you intend using open before calling this.
*/
fun syncHistory(syncInfo: SyncAuthInfo): SyncTelemetryPing
/**
* Syncs the places bookmarks store, returning a telemetry ping.
*
* Note that this function blocks until the sync is complete, which may
* take some time due to the network etc. Because only 1 thread can be
* using a PlacesAPI at a time, it is recommended, but not enforced, that
* you have all connections you intend using open before calling this.
*/
fun syncBookmarks(syncInfo: SyncAuthInfo): SyncTelemetryPing
}
interface InterruptibleConnection : AutoCloseable {
/**
* Interrupt ongoing operations running on a separate thread.
*/
fun interrupt()
}
interface ReadableHistoryConnection : InterruptibleConnection {
/**
* A way to search the internal database tailored for autocompletion purposes.
*
* @param query a string to match results against.
* @param limit a maximum number of results to retrieve.
* @return a list of [SearchResult] matching the [query], in arbitrary order.
*/
fun queryAutocomplete(query: String, limit: Int): List<SearchResult>
/**
* See if a url that's sufficiently close to `search` exists in
* the database.
*
* @param query the search string
* @return If no url exists, returns null. If one exists, it returns the next
* portion of it that definitely matches (where portion is defined
* something like 'complete origin or path segment')
*/
fun matchUrl(query: String): String?
/**
* Maps a list of page URLs to a list of booleans indicating if each URL was visited.
* @param urls a list of page URLs about which "visited" information is being requested.
* @return a list of booleans indicating visited status of each
* corresponding page URI from [urls].
*/
fun getVisited(urls: List<String>): List<Boolean>
/**
* Returns a list of visited URLs for a given time range.
*
* @param start beginning of the range, unix timestamp in milliseconds.
* @param end end of the range, unix timestamp in milliseconds.
* @param includeRemote boolean flag indicating whether or not to include remote visits. A visit
* is (roughly) considered remote if it didn't originate on the current device.
*/
fun getVisitedUrlsInRange(start: Long, end: Long = Long.MAX_VALUE, includeRemote: Boolean = true): List<String>
/**
* Get detailed information about all visits that occurred in the
* given time range.
*
* @param start The (inclusive) start time to bound the query.
* @param end The (inclusive) end time to bound the query.
*/
fun getVisitInfos(
start: Long,
end: Long = Long.MAX_VALUE,
excludeTypes: List<VisitType> = listOf()
): List<VisitInfo>
/**
* Return a "page" of history results. Each page will have visits in descending order
* with respect to their visit timestamps. In the case of ties, their row id will
* be used.
*
* Note that you may get surprising results if the items in the database change
* while you are paging through records.
*
* @param offset The offset where the page begins.
* @param count The number of items to return in the page.
* @param excludeTypes List of visit types to exclude.
*/
fun getVisitPage(offset: Long, count: Long, excludeTypes: List<VisitType> = listOf()): List<VisitInfo>
/**
* Get the number of history visits.
*
* It is intended that this be used with `getVisitPage` to allow pagination
* through records, however be aware that (unless you hold the only
* reference to the write connection, and know a sync may not occur at this
* time), the number of items in the database may change between when you
* call `getVisitCount` and `getVisitPage`.
*
*
* @param excludeTypes List of visit types to exclude.
*/
fun getVisitCount(excludeTypes: List<VisitType> = listOf()): Long
}
interface WritableHistoryConnection : ReadableHistoryConnection {
/**
* Record a visit to a URL, or update meta information about page URL. See [VisitObservation].
*/
fun noteObservation(data: VisitObservation)
/**
* Deletes all history visits, without recording tombstones.
*
* That is, these deletions will not be synced. Any changes which were
* pending upload on the next sync are discarded and will be lost.
*/
fun wipeLocal()
/**
* Run periodic database maintenance. This might include, but is not limited
* to:
*
* - `VACUUM`ing.
* - Requesting that the indices in our tables be optimized.
* - Expiring irrelevant history visits.
* - Periodic repair or deletion of corrupted records.
* - etc.
*
* It should be called at least once a day, but this is merely a
* recommendation and nothing too dire should happen if it is not
* called.
*/
fun runMaintenance()
/**
* Aggressively prune history visits. These deletions are not intended
* to be synced, however due to the way history sync works, this can
* still cause data loss.
*
* As a result, this should only be called if a low disk space
* notification is received from the OS, and things like the network
* cache have already been cleared.
*/
fun pruneDestructively()
/**
* Delete everything locally.
*
* This will not delete visits from remote devices, however it will
* prevent them from trickling in over time when future syncs occur.
*
* The difference between this and wipeLocal is that wipeLocal does
* not prevent the deleted visits from returning. For wipeLocal,
* the visits will return on the next full sync (which may be
* arbitrarially far in the future), wheras items which were
* deleted by deleteEverything (or potentially could have been)
* should not return.
*/
fun deleteEverything()
/**
* Deletes all information about the given URL. If the place has previously
* been synced, a tombstone will be written to the sync server, meaning
* the place should be deleted on all synced devices.
*
* The exception to this is if the place is duplicated on the sync server
* (duplicate server-side places are a form of corruption), in which case
* only the place whose GUID corresponds to the local GUID will be
* deleted. This is (hopefully) rare, and sadly there is not much we can
* do about it. It indicates a client-side bug that occurred at some
* point in the past.
*
* @param url the url to be removed.
*/
fun deletePlace(url: String)
/**
* Deletes all visits which occurred since the specified time. If the
* deletion removes the last visit for a place, the place itself will also
* be removed (and if the place has been synced, the deletion of the
* place will also be synced)
*
* @param start time for the deletion, unix timestamp in milliseconds.
*/
fun deleteVisitsSince(since: Long)
/**
* Imports bookmarks from a Fennec `browser.db` database.
*
* It has been designed exclusively for non-sync users.
*
* @param path Path to the `browser.db` file database.
*/
fun importBookmarksFromFennec(path: String)
/**
* Imports visits from a Fennec `browser.db` database.
*
* It has been designed exclusively for non-sync users and should
* be called before bookmarks import.
*
* @param path Path to the `browser.db` file database.
*/
fun importVisitsFromFennec(path: String)
/**
* Equivalent to deleteVisitsSince, but takes an `endTime` as well.
*
* Timestamps are in milliseconds since the unix epoch.
*
* See documentation for deleteVisitsSince for caveats.
*
* @param startTime Inclusive beginning of the time range to delete.
* @param endTime Inclusive end of the time range to delete.
*/
fun deleteVisitsBetween(startTime: Long, endTime: Long)
/**
* Delete the single visit that occurred at the provided timestamp.
*
* Note that this will not delete the visit on another device, unless this is the last
* remaining visit of that URL that this device is aware of.
*
* However, it should prevent this visit from being inserted again.
*
* @param url The URL of the place to delete.
* @param visitTimestamp The timestamp of the visit to delete, in MS since the unix epoch
*/
fun deleteVisit(url: String, visitTimestamp: Long)
/**
* Records an accepted autocomplete match, recording the query string,
* and chosen URL for subsequent matches.
*
* @param searchString The query string
* @param url The chosen URL string
*/
fun acceptResult(searchString: String, url: String)
}
class InterruptHandle internal constructor(raw: RawPlacesInterruptHandle) : AutoCloseable {
// We synchronize all accesses, so this probably doesn't need AtomicReference.
private val handle: AtomicReference<RawPlacesInterruptHandle?> = AtomicReference(raw)
@Synchronized
override fun close() {
val toFree = handle.getAndSet(null)
if (toFree != null) {
LibPlacesFFI.INSTANCE.places_interrupt_handle_destroy(toFree)
}
}
@Synchronized
fun interrupt() {
handle.get()?.let {
val e = RustError.ByReference()
LibPlacesFFI.INSTANCE.places_interrupt(it, e)
if (e.isFailure()) {
throw e.intoException()
}
}
}
}
open class PlacesException(msg: String) : Exception(msg)
open class InternalPanic(msg: String) : PlacesException(msg)
open class UrlParseFailed(msg: String) : PlacesException(msg)
open class PlacesConnectionBusy(msg: String) : PlacesException(msg)
open class OperationInterrupted(msg: String) : PlacesException(msg)
enum class VisitType(val type: Int) {
/** This isn't a visit, but a request to update meta data about a page */
UPDATE_PLACE(-1),
/** This transition type means the user followed a link. */
LINK(1),
/** This transition type means that the user typed the page's URL in the
* URL bar or selected it from UI (URL bar autocomplete results, etc).
*/
TYPED(2),
// TODO: rest of docs
BOOKMARK(3),
EMBED(4),
REDIRECT_PERMANENT(5),
REDIRECT_TEMPORARY(6),
DOWNLOAD(7),
FRAMED_LINK(8),
RELOAD(9)
}
private val intToVisitType: Map<Int, VisitType> = VisitType.values().associateBy(VisitType::type)
/**
* Encapsulates either information about a visit to a page, or meta information about the page,
* or both. Use [VisitType.UPDATE_PLACE] to differentiate an update from a visit.
*/
data class VisitObservation(
val url: String,
val visitType: VisitType,
val title: String? = null,
val isError: Boolean? = null,
val isRedirectSource: Boolean? = null,
val isPermanentRedirectSource: Boolean? = null,
/** Milliseconds */
val at: Long? = null,
val referrer: String? = null,
val isRemote: Boolean? = null
) {
fun toJSON(): JSONObject {
val o = JSONObject()
o.put("url", this.url)
// Absence of visit_type indicates that this is an update.
if (this.visitType != VisitType.UPDATE_PLACE) {
o.put("visit_type", this.visitType.type)
}
this.title?.let { o.put("title", it) }
this.isError?.let { o.put("is_error", it) }
this.isRedirectSource?.let { o.put("is_redirect_source", it) }
this.isPermanentRedirectSource?.let { o.put("is_permanent_redirect_source", it) }
this.at?.let { o.put("at", it) }
this.referrer?.let { o.put("referrer", it) }
this.isRemote?.let { o.put("is_remote", it) }
return o
}
}
fun stringOrNull(jsonObject: JSONObject, key: String): String? {
return try {
jsonObject.getString(key)
} catch (e: JSONException) {
null
}
}
data class SearchResult(
val searchString: String,
val url: String,
val title: String,
val frecency: Long,
val iconUrl: String? = null
// Skipping `reasons` for now...
) {
companion object {
fun fromJSON(jsonObject: JSONObject): SearchResult {
return SearchResult(
searchString = jsonObject.getString("search_string"),
url = jsonObject.getString("url"),
title = jsonObject.getString("title"),
frecency = jsonObject.getLong("frecency"),
iconUrl = stringOrNull(jsonObject, "icon_url")
)
}
fun fromJSONArray(jsonArrayText: String): List<SearchResult> {
val result: MutableList<SearchResult> = mutableListOf()
val array = JSONArray(jsonArrayText)
for (index in 0 until array.length()) {
result.add(fromJSON(array.getJSONObject(index)))
}
return result
}
}
}
/**
* Information about a history visit. Returned by `PlacesAPI.getVisitInfos`.
*/
data class VisitInfo(
/**
* The URL of the page that was visited.
*/
val url: String,
/**
* The title of the page that was visited, if known.
*/
val title: String?,
/**
* The time the page was visited in integer milliseconds since the unix epoch.
*/
val visitTime: Long,
/**
* What the transition type of the visit is.
*/
val visitType: VisitType
) {
companion object {
internal fun fromMessage(msg: MsgTypes.HistoryVisitInfos): List<VisitInfo> {
return msg.infosList.map {
VisitInfo(url = it.url,
title = it.title,
visitTime = it.timestamp,
visitType = intToVisitType[it.visitType]!!)
}
}
}
}