This repository has been archived by the owner on Nov 1, 2022. It is now read-only.
/
GeckoEngineSession.kt
1278 lines (1129 loc) · 50.3 KB
/
GeckoEngineSession.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
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package mozilla.components.browser.engine.gecko
import android.annotation.SuppressLint
import android.net.Uri
import android.os.Build
import android.view.WindowManager
import androidx.annotation.VisibleForTesting
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import mozilla.components.browser.engine.gecko.ext.isExcludedForTrackingProtection
import mozilla.components.browser.engine.gecko.fetch.toResponse
import mozilla.components.browser.engine.gecko.media.GeckoMediaDelegate
import mozilla.components.browser.engine.gecko.mediasession.GeckoMediaSessionDelegate
import mozilla.components.browser.engine.gecko.permission.GeckoPermissionRequest
import mozilla.components.browser.engine.gecko.prompt.GeckoPromptDelegate
import mozilla.components.browser.engine.gecko.window.GeckoWindowRequest
import mozilla.components.browser.errorpages.ErrorType
import mozilla.components.concept.engine.EngineSession
import mozilla.components.concept.engine.EngineSession.LoadUrlFlags.Companion.ALLOW_JAVASCRIPT_URL
import mozilla.components.concept.engine.EngineSessionState
import mozilla.components.concept.engine.HitResult
import mozilla.components.concept.engine.Settings
import mozilla.components.concept.engine.content.blocking.Tracker
import mozilla.components.concept.engine.history.HistoryItem
import mozilla.components.concept.engine.history.HistoryTrackingDelegate
import mozilla.components.concept.engine.manifest.WebAppManifestParser
import mozilla.components.concept.engine.request.RequestInterceptor
import mozilla.components.concept.engine.request.RequestInterceptor.InterceptionResponse
import mozilla.components.concept.engine.window.WindowRequest
import mozilla.components.concept.fetch.Headers.Names.CONTENT_DISPOSITION
import mozilla.components.concept.fetch.Headers.Names.CONTENT_LENGTH
import mozilla.components.concept.fetch.Headers.Names.CONTENT_TYPE
import mozilla.components.concept.fetch.MutableHeaders
import mozilla.components.concept.fetch.Response
import mozilla.components.concept.storage.PageVisit
import mozilla.components.concept.storage.RedirectSource
import mozilla.components.concept.storage.VisitType
import mozilla.components.support.base.Component
import mozilla.components.support.base.facts.Action
import mozilla.components.support.base.facts.Fact
import mozilla.components.support.base.facts.collect
import mozilla.components.support.base.log.logger.Logger
import mozilla.components.support.ktx.kotlin.isEmail
import mozilla.components.support.ktx.kotlin.isExtensionUrl
import mozilla.components.support.ktx.kotlin.isGeoLocation
import mozilla.components.support.ktx.kotlin.isPhone
import mozilla.components.support.ktx.kotlin.sanitizeFileName
import mozilla.components.support.ktx.kotlin.tryGetHostFromUrl
import mozilla.components.support.utils.DownloadUtils
import mozilla.components.support.utils.DownloadUtils.RESPONSE_CODE_SUCCESS
import mozilla.components.support.utils.DownloadUtils.makePdfContentDisposition
import org.json.JSONObject
import org.mozilla.geckoview.AllowOrDeny
import org.mozilla.geckoview.ContentBlocking
import org.mozilla.geckoview.GeckoResult
import org.mozilla.geckoview.GeckoRuntime
import org.mozilla.geckoview.GeckoSession
import org.mozilla.geckoview.GeckoSession.NavigationDelegate
import org.mozilla.geckoview.GeckoSession.PermissionDelegate.ContentPermission
import org.mozilla.geckoview.GeckoSessionSettings
import org.mozilla.geckoview.WebRequestError
import org.mozilla.geckoview.WebResponse
import java.util.Locale
import kotlin.coroutines.CoroutineContext
/**
* Gecko-based EngineSession implementation.
*/
@Suppress("TooManyFunctions", "LargeClass")
class GeckoEngineSession(
private val runtime: GeckoRuntime,
private val privateMode: Boolean = false,
private val defaultSettings: Settings? = null,
contextId: String? = null,
private val geckoSessionProvider: () -> GeckoSession = {
val settings = GeckoSessionSettings.Builder()
.usePrivateMode(privateMode)
.contextId(contextId)
.build()
GeckoSession(settings)
},
private val context: CoroutineContext = Dispatchers.IO,
openGeckoSession: Boolean = true,
) : CoroutineScope, EngineSession() {
// This logger is temporary and parsed by FNPRMS for performance measurements. It can be
// removed once FNPRMS is replaced: https://github.com/mozilla-mobile/android-components/issues/8662
// It mimics GeckoView debug log statements, hence the unintuitive tag and messages.
private val fnprmsLogger = Logger("GeckoSession")
private val logger = Logger("GeckoEngineSession")
internal lateinit var geckoSession: GeckoSession
internal var currentUrl: String? = null
internal var currentTitle: String? = null
internal var lastLoadRequestUri: String? = null
internal var pageLoadingUrl: String? = null
internal var appRedirectUrl: String? = null
internal var scrollY: Int = 0
// The Gecko site permissions for the loaded site.
internal var geckoPermissions: List<ContentPermission> = emptyList()
internal var job: Job = Job()
private var canGoBack: Boolean = false
/**
* See [EngineSession.settings]
*/
override val settings: Settings = object : Settings() {
override var requestInterceptor: RequestInterceptor? = null
override var historyTrackingDelegate: HistoryTrackingDelegate? = null
override var userAgentString: String?
get() = geckoSession.settings.userAgentOverride
set(value) {
geckoSession.settings.userAgentOverride = value
}
override var suspendMediaWhenInactive: Boolean
get() = geckoSession.settings.suspendMediaWhenInactive
set(value) {
geckoSession.settings.suspendMediaWhenInactive = value
}
}
internal var initialLoad = true
override val coroutineContext: CoroutineContext
get() = context + job
init {
createGeckoSession(shouldOpen = openGeckoSession)
}
/**
* Represents a request to load a [url].
*
* @param url the url to load.
* @param parent the parent (referring) [EngineSession] i.e. the session that
* triggered creating this one.
* @param flags the [LoadUrlFlags] to use when loading the provided url.
* @param additionalHeaders the extra headers to use when loading the provided url.
**/
data class LoadRequest(
val url: String,
val parent: EngineSession?,
val flags: LoadUrlFlags,
val additionalHeaders: Map<String, String>?,
)
@VisibleForTesting
internal var initialLoadRequest: LoadRequest? = null
/**
* See [EngineSession.loadUrl]
*/
override fun loadUrl(
url: String,
parent: EngineSession?,
flags: LoadUrlFlags,
additionalHeaders: Map<String, String>?,
) {
val scheme = Uri.parse(url).normalizeScheme().scheme
if (BLOCKED_SCHEMES.contains(scheme) && !shouldLoadJSSchemes(scheme, flags)) {
logger.error("URL scheme not allowed. Aborting load.")
return
}
if (initialLoad) {
initialLoadRequest = LoadRequest(url, parent, flags, additionalHeaders)
}
val loader = GeckoSession.Loader()
.uri(url)
.flags(flags.getGeckoFlags())
if (additionalHeaders != null) {
loader.additionalHeaders(additionalHeaders)
.headerFilter(GeckoSession.HEADER_FILTER_CORS_SAFELISTED)
}
if (parent != null) {
loader.referrer((parent as GeckoEngineSession).geckoSession)
}
geckoSession.load(loader)
Fact(
Component.BROWSER_ENGINE_GECKO,
Action.IMPLEMENTATION_DETAIL,
"GeckoSession.load",
).collect()
}
private fun shouldLoadJSSchemes(
scheme: String?,
flags: LoadUrlFlags,
) = scheme?.startsWith(JS_SCHEME) == true && flags.contains(ALLOW_JAVASCRIPT_URL)
/**
* See [EngineSession.loadData]
*/
override fun loadData(data: String, mimeType: String, encoding: String) {
when (encoding) {
"base64" -> geckoSession.load(GeckoSession.Loader().data(data.toByteArray(), mimeType))
else -> geckoSession.load(GeckoSession.Loader().data(data, mimeType))
}
}
/**
* See [EngineSession.requestPdfToDownload]
*/
override fun requestPdfToDownload() {
geckoSession.saveAsPdf().then(
{ inputStream ->
if (inputStream == null) {
logger.error("No input stream available for Save to PDF.")
return@then GeckoResult<Void>()
}
val url = this.currentUrl ?: ""
val contentType = "application/pdf"
val disposition = currentTitle?.let { makePdfContentDisposition(it) }
// A successful status code suffices because the PDF is generated on device.
val responseStatus = RESPONSE_CODE_SUCCESS
// We do not know the size at this point; send 0 so consumers do not display it.
val contentLength = 0L
// NB: If the title is an empty string, there is a chance the PDF will not have a name.
// See https://github.com/mozilla-mobile/android-components/issues/12276
val fileName = DownloadUtils.guessFileName(
disposition,
destinationDirectory = null,
url = url,
mimeType = contentType,
)
val response = Response(
url = url,
status = responseStatus,
headers = MutableHeaders(),
body = Response.Body(inputStream),
)
notifyObservers {
onExternalResource(
url = url,
contentLength = contentLength,
contentType = contentType,
fileName = fileName,
response = response,
isPrivate = privateMode,
)
}
GeckoResult()
},
{ throwable ->
// Log the error. There is nothing we can do otherwise.
logger.error("Save to PDF failed.", throwable)
GeckoResult()
},
)
}
/**
* See [EngineSession.stopLoading]
*/
override fun stopLoading() {
geckoSession.stop()
}
/**
* See [EngineSession.reload]
*/
override fun reload(flags: LoadUrlFlags) {
initialLoadRequest?.let {
// We have a pending initial load request, which means we never
// successfully loaded a page. Calling reload now would just reload
// about:blank. To prevent that we trigger the initial load again.
loadUrl(it.url, it.parent, it.flags, it.additionalHeaders)
} ?: geckoSession.reload(flags.getGeckoFlags())
}
/**
* See [EngineSession.goBack]
*/
override fun goBack(userInteraction: Boolean) {
geckoSession.goBack(userInteraction)
if (canGoBack) {
notifyObservers { onNavigateBack() }
}
}
/**
* See [EngineSession.goForward]
*/
override fun goForward(userInteraction: Boolean) {
geckoSession.goForward(userInteraction)
}
/**
* See [EngineSession.goToHistoryIndex]
*/
override fun goToHistoryIndex(index: Int) {
geckoSession.gotoHistoryIndex(index)
}
/**
* See [EngineSession.restoreState]
*/
override fun restoreState(state: EngineSessionState): Boolean {
if (state !is GeckoEngineSessionState) {
throw IllegalStateException("Can only restore from GeckoEngineSessionState")
}
// Also checking if SessionState is empty as a workaround for:
// https://bugzilla.mozilla.org/show_bug.cgi?id=1687523
if (state.actualState.isNullOrEmpty()) {
return false
}
geckoSession.restoreState(state.actualState)
return true
}
/**
* See [EngineSession.updateTrackingProtection]
*/
override fun updateTrackingProtection(policy: TrackingProtectionPolicy) {
updateContentBlocking(policy)
val enabled = policy != TrackingProtectionPolicy.none()
etpEnabled = enabled
notifyObservers {
onTrackerBlockingEnabledChange(this, enabled)
}
}
@VisibleForTesting
internal fun updateContentBlocking(policy: TrackingProtectionPolicy) {
/**
* As described on https://bugzilla.mozilla.org/show_bug.cgi?id=1579264,useTrackingProtection
* is a misleading setting. When is set to true is blocking content (scripts/sub-resources).
* Instead of just turn on/off tracking protection. Until, this issue is fixed consumers need
* a way to indicate, if they want to block content or not, this is why we use
* [TrackingProtectionPolicy.TrackingCategory.SCRIPTS_AND_SUB_RESOURCES].
*/
val shouldBlockContent =
policy.contains(TrackingProtectionPolicy.TrackingCategory.SCRIPTS_AND_SUB_RESOURCES)
val enabledInBrowsingMode = if (privateMode) {
policy.useForPrivateSessions
} else {
policy.useForRegularSessions
}
geckoSession.settings.useTrackingProtection = enabledInBrowsingMode && shouldBlockContent
}
// This is a temporary solution to address
// https://github.com/mozilla-mobile/android-components/issues/8431
// until we eventually delete [EngineObserver] then this will not be needed.
@VisibleForTesting
internal var etpEnabled: Boolean? = null
override fun register(observer: Observer) {
super.register(observer)
etpEnabled?.let { enabled ->
onTrackerBlockingEnabledChange(observer, enabled)
}
}
private fun onTrackerBlockingEnabledChange(observer: Observer, enabled: Boolean) {
// We now register engine observers in a middleware using a dedicated
// store thread. Since this notification can be delayed until an observer
// is registered we switch to the main scope to make sure we're not notifying
// on the store thread.
MainScope().launch {
observer.onTrackerBlockingEnabledChange(enabled)
}
}
/**
* Indicates if this [EngineSession] should be ignored the tracking protection policies.
* @return if this [EngineSession] is in
* the exception list, true if it is in, otherwise false.
*/
internal fun isIgnoredForTrackingProtection(): Boolean {
return geckoPermissions.any { it.isExcludedForTrackingProtection }
}
/**
* See [EngineSession.settings]
*/
override fun toggleDesktopMode(enable: Boolean, reload: Boolean) {
val currentMode = geckoSession.settings.userAgentMode
val currentViewPortMode = geckoSession.settings.viewportMode
var overrideUrl: String? = null
val newMode = if (enable) {
GeckoSessionSettings.USER_AGENT_MODE_DESKTOP
} else {
GeckoSessionSettings.USER_AGENT_MODE_MOBILE
}
val newViewportMode = if (enable) {
overrideUrl = currentUrl?.let { checkForMobileSite(it) }
GeckoSessionSettings.VIEWPORT_MODE_DESKTOP
} else {
GeckoSessionSettings.VIEWPORT_MODE_MOBILE
}
if (newMode != currentMode || newViewportMode != currentViewPortMode) {
geckoSession.settings.userAgentMode = newMode
geckoSession.settings.viewportMode = newViewportMode
notifyObservers { onDesktopModeChange(enable) }
}
if (reload) {
if (overrideUrl == null) {
this.reload()
} else {
loadUrl(overrideUrl, flags = LoadUrlFlags.select(LoadUrlFlags.LOAD_FLAGS_REPLACE_HISTORY))
}
}
}
/**
* Checks and returns a non-mobile version of the url.
*/
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal fun checkForMobileSite(url: String): String? {
var overrideUrl: String? = null
val mPrefix = "m."
val mobilePrefix = "mobile."
val uri = Uri.parse(url)
val authority = uri.authority?.lowercase(Locale.ROOT) ?: return null
val foundPrefix = when {
authority.startsWith(mPrefix) -> mPrefix
authority.startsWith(mobilePrefix) -> mobilePrefix
else -> null
}
foundPrefix?.let {
val mobileUri = Uri.parse(url).buildUpon().authority(authority.substring(it.length))
overrideUrl = mobileUri.toString()
}
return overrideUrl
}
/**
* See [EngineSession.findAll]
*/
override fun findAll(text: String) {
notifyObservers { onFind(text) }
geckoSession.finder.find(text, 0).then { result: GeckoSession.FinderResult? ->
result?.let {
val activeMatchOrdinal = if (it.current > 0) it.current - 1 else it.current
notifyObservers { onFindResult(activeMatchOrdinal, it.total, true) }
}
GeckoResult<Void>()
}
}
/**
* See [EngineSession.findNext]
*/
@SuppressLint("WrongConstant") // FinderFindFlags annotation doesn't include a 0 value.
override fun findNext(forward: Boolean) {
val findFlags = if (forward) 0 else GeckoSession.FINDER_FIND_BACKWARDS
geckoSession.finder.find(null, findFlags).then { result: GeckoSession.FinderResult? ->
result?.let {
val activeMatchOrdinal = if (it.current > 0) it.current - 1 else it.current
notifyObservers { onFindResult(activeMatchOrdinal, it.total, true) }
}
GeckoResult<Void>()
}
}
/**
* See [EngineSession.clearFindMatches]
*/
override fun clearFindMatches() {
geckoSession.finder.clear()
}
/**
* See [EngineSession.exitFullScreenMode]
*/
override fun exitFullScreenMode() {
geckoSession.exitFullScreen()
}
/**
* See [EngineSession.markActiveForWebExtensions].
*/
override fun markActiveForWebExtensions(active: Boolean) {
runtime.webExtensionController.setTabActive(geckoSession, active)
}
/**
* See [EngineSession.updateSessionPriority].
*/
override fun updateSessionPriority(priority: SessionPriority) {
geckoSession.setPriorityHint(priority.id)
}
/**
* Purges the history for the session (back and forward history).
*/
override fun purgeHistory() {
geckoSession.purgeHistory()
}
/**
* See [EngineSession.close].
*/
override fun close() {
super.close()
job.cancel()
geckoSession.close()
}
override fun getBlockedSchemes(): List<String> {
return BLOCKED_SCHEMES
}
/**
* NavigationDelegate implementation for forwarding callbacks to observers of the session.
*/
@Suppress("ComplexMethod")
private fun createNavigationDelegate() = object : GeckoSession.NavigationDelegate {
override fun onLocationChange(
session: GeckoSession,
url: String?,
geckoPermissions: List<ContentPermission>,
) {
this@GeckoEngineSession.geckoPermissions = geckoPermissions
if (url == null) {
return // ¯\_(ツ)_/¯
}
// Ignore initial loads of about:blank, see:
// https://github.com/mozilla-mobile/android-components/issues/403
// https://github.com/mozilla-mobile/android-components/issues/6832
if (initialLoad && url == ABOUT_BLANK) {
return
}
appRedirectUrl?.let {
if (url == appRedirectUrl) {
goBack(false)
return
}
}
currentUrl = url
initialLoad = false
initialLoadRequest = null
notifyObservers {
onExcludedOnTrackingProtectionChange(isIgnoredForTrackingProtection())
}
notifyObservers { onLocationChange(url) }
}
override fun onLoadRequest(
session: GeckoSession,
request: NavigationDelegate.LoadRequest,
): GeckoResult<AllowOrDeny> {
// The process switch involved when loading extension pages will
// trigger an initial load of about:blank which we want to
// avoid:
// https://github.com/mozilla-mobile/android-components/issues/6832
// https://github.com/mozilla-mobile/android-components/issues/403
if (currentUrl?.isExtensionUrl() != request.uri.isExtensionUrl()) {
initialLoad = true
}
return when {
maybeInterceptRequest(request, false) != null ->
GeckoResult.fromValue(AllowOrDeny.DENY)
request.target == NavigationDelegate.TARGET_WINDOW_NEW ->
GeckoResult.fromValue(AllowOrDeny.ALLOW)
else -> {
notifyObservers {
onLoadRequest(
url = request.uri,
triggeredByRedirect = request.isRedirect,
triggeredByWebContent = request.hasUserGesture,
)
}
GeckoResult.fromValue(AllowOrDeny.ALLOW)
}
}
}
override fun onSubframeLoadRequest(
session: GeckoSession,
request: NavigationDelegate.LoadRequest,
): GeckoResult<AllowOrDeny> {
if (request.target == NavigationDelegate.TARGET_WINDOW_NEW) {
return GeckoResult.fromValue(AllowOrDeny.ALLOW)
}
return if (maybeInterceptRequest(request, true) != null) {
GeckoResult.fromValue(AllowOrDeny.DENY)
} else {
// Not notifying session observer because of performance concern and currently there
// is no use case.
GeckoResult.fromValue(AllowOrDeny.ALLOW)
}
}
override fun onCanGoForward(session: GeckoSession, canGoForward: Boolean) {
notifyObservers { onNavigationStateChange(canGoForward = canGoForward) }
}
override fun onCanGoBack(session: GeckoSession, canGoBack: Boolean) {
notifyObservers { onNavigationStateChange(canGoBack = canGoBack) }
this@GeckoEngineSession.canGoBack = canGoBack
}
override fun onNewSession(
session: GeckoSession,
uri: String,
): GeckoResult<GeckoSession> {
val newEngineSession =
GeckoEngineSession(runtime, privateMode, defaultSettings, openGeckoSession = false)
notifyObservers {
onWindowRequest(GeckoWindowRequest(uri, newEngineSession))
}
return GeckoResult.fromValue(newEngineSession.geckoSession)
}
override fun onLoadError(
session: GeckoSession,
uri: String?,
error: WebRequestError,
): GeckoResult<String> {
val response = settings.requestInterceptor?.onErrorRequest(
this@GeckoEngineSession,
geckoErrorToErrorType(error.code),
uri,
)
return GeckoResult.fromValue(response?.uri)
}
private fun maybeInterceptRequest(
request: NavigationDelegate.LoadRequest,
isSubframeRequest: Boolean,
): InterceptionResponse? {
val interceptor = settings.requestInterceptor
val interceptionResponse = if (
interceptor != null && (!request.isDirectNavigation || interceptor.interceptsAppInitiatedRequests())
) {
val engineSession = this@GeckoEngineSession
val isSameDomain =
engineSession.currentUrl?.tryGetHostFromUrl() == request.uri.tryGetHostFromUrl()
interceptor.onLoadRequest(
engineSession,
request.uri,
lastLoadRequestUri,
request.hasUserGesture,
isSameDomain,
request.isRedirect,
request.isDirectNavigation,
isSubframeRequest,
)?.apply {
when (this) {
is InterceptionResponse.Content -> loadData(data, mimeType, encoding)
is InterceptionResponse.Url -> loadUrl(url, flags = LoadUrlFlags.external())
is InterceptionResponse.AppIntent -> {
appRedirectUrl = lastLoadRequestUri
notifyObservers {
onLaunchIntentRequest(url = url, appIntent = appIntent)
}
}
else -> {
// no-op
}
}
}
} else {
null
}
if (interceptionResponse !is InterceptionResponse.AppIntent) {
appRedirectUrl = ""
lastLoadRequestUri = request.uri
}
// TODO fix root cause: https://github.com/mozilla-mobile/android-components/issues/12894
if (interceptor != null && interceptor.interceptsAppInitiatedRequests()) {
lastLoadRequestUri = request.uri
}
return interceptionResponse
}
}
/**
* ProgressDelegate implementation for forwarding callbacks to observers of the session.
*/
private fun createProgressDelegate() = object : GeckoSession.ProgressDelegate {
override fun onProgressChange(session: GeckoSession, progress: Int) {
notifyObservers { onProgress(progress) }
}
override fun onSecurityChange(
session: GeckoSession,
securityInfo: GeckoSession.ProgressDelegate.SecurityInformation,
) {
// Ignore initial load of about:blank (see https://github.com/mozilla-mobile/android-components/issues/403)
if (initialLoad && securityInfo.origin?.startsWith(MOZ_NULL_PRINCIPAL) == true) {
return
}
notifyObservers {
// TODO provide full certificate info: https://github.com/mozilla-mobile/android-components/issues/5557
onSecurityChange(
securityInfo.isSecure,
securityInfo.host,
securityInfo.getIssuerName(),
)
}
}
override fun onPageStart(session: GeckoSession, url: String) {
// This log statement is temporary and parsed by FNPRMS for performance measurements. It can be
// removed once FNPRMS is replaced: https://github.com/mozilla-mobile/android-components/issues/8662
fnprmsLogger.info("handleMessage GeckoView:PageStart uri=") // uri intentionally blank
pageLoadingUrl = url
// Ignore initial load of about:blank (see https://github.com/mozilla-mobile/android-components/issues/403)
if (initialLoad && url == ABOUT_BLANK) {
return
}
notifyObservers {
onProgress(PROGRESS_START)
onLoadingStateChange(true)
}
}
override fun onPageStop(session: GeckoSession, success: Boolean) {
// This log statement is temporary and parsed by FNPRMS for performance measurements. It can be
// removed once FNPRMS is replaced: https://github.com/mozilla-mobile/android-components/issues/8662
fnprmsLogger.info("handleMessage GeckoView:PageStop uri=null") // uri intentionally hard-coded to null
// by the time we reach here, any new request will come from web content.
// If it comes from the chrome, loadUrl(url) or loadData(string) will set it to
// false.
// Ignore initial load of about:blank (see https://github.com/mozilla-mobile/android-components/issues/403)
if (initialLoad && pageLoadingUrl == ABOUT_BLANK) {
return
}
notifyObservers {
onProgress(PROGRESS_STOP)
onLoadingStateChange(false)
}
}
override fun onSessionStateChange(session: GeckoSession, sessionState: GeckoSession.SessionState) {
notifyObservers {
onStateUpdated(GeckoEngineSessionState(sessionState))
}
}
}
@Suppress("ComplexMethod")
internal fun createHistoryDelegate() = object : GeckoSession.HistoryDelegate {
@SuppressWarnings("ReturnCount")
override fun onVisited(
session: GeckoSession,
url: String,
lastVisitedURL: String?,
flags: Int,
): GeckoResult<Boolean>? {
// Don't track:
// - private visits
// - error pages
// - non-top level visits (i.e. iframes).
if (privateMode ||
(flags and GeckoSession.HistoryDelegate.VISIT_TOP_LEVEL) == 0 ||
(flags and GeckoSession.HistoryDelegate.VISIT_UNRECOVERABLE_ERROR) != 0
) {
return GeckoResult.fromValue(false)
}
appRedirectUrl?.let {
if (url == appRedirectUrl) {
return GeckoResult.fromValue(false)
}
}
val delegate = settings.historyTrackingDelegate ?: return GeckoResult.fromValue(false)
// Check if the delegate wants this type of url.
if (!delegate.shouldStoreUri(url)) {
return GeckoResult.fromValue(false)
}
val isReload = lastVisitedURL?.let { it == url } ?: false
// Note the difference between `VISIT_REDIRECT_PERMANENT`,
// `VISIT_REDIRECT_TEMPORARY`, `VISIT_REDIRECT_SOURCE`, and
// `VISIT_REDIRECT_SOURCE_PERMANENT`.
//
// The former two indicate if the visited page is the *target*
// of a redirect; that is, another page redirected to it.
//
// The latter two indicate if the visited page is the *source*
// of a redirect: it's redirecting to another page, because the
// server returned an HTTP 3xy status code.
//
// So, we mark the **source** redirects as actual redirects, while treating **target**
// redirects as normal visits.
val visitType = when {
isReload -> VisitType.RELOAD
flags and GeckoSession.HistoryDelegate.VISIT_REDIRECT_SOURCE_PERMANENT != 0 ->
VisitType.REDIRECT_PERMANENT
flags and GeckoSession.HistoryDelegate.VISIT_REDIRECT_SOURCE != 0 ->
VisitType.REDIRECT_TEMPORARY
else -> VisitType.LINK
}
val redirectSource = when {
flags and GeckoSession.HistoryDelegate.VISIT_REDIRECT_SOURCE_PERMANENT != 0 ->
RedirectSource.PERMANENT
flags and GeckoSession.HistoryDelegate.VISIT_REDIRECT_SOURCE != 0 ->
RedirectSource.TEMPORARY
else -> null
}
return launchGeckoResult {
delegate.onVisited(url, PageVisit(visitType, redirectSource))
true
}
}
override fun getVisited(
session: GeckoSession,
urls: Array<out String>,
): GeckoResult<BooleanArray>? {
if (privateMode) {
return GeckoResult.fromValue(null)
}
val delegate = settings.historyTrackingDelegate ?: return GeckoResult.fromValue(null)
return launchGeckoResult {
val visits = delegate.getVisited(urls.toList())
visits.toBooleanArray()
}
}
override fun onHistoryStateChange(
session: GeckoSession,
historyList: GeckoSession.HistoryDelegate.HistoryList,
) {
val items = historyList.map {
// title is sometimes null despite the @NotNull annotation
// https://bugzilla.mozilla.org/show_bug.cgi?id=1660286
val title: String? = it.title
HistoryItem(
title = title ?: it.uri,
uri = it.uri,
)
}
notifyObservers { onHistoryStateChanged(items, historyList.currentIndex) }
}
}
@Suppress("ComplexMethod", "NestedBlockDepth")
internal fun createContentDelegate() = object : GeckoSession.ContentDelegate {
override fun onFirstComposite(session: GeckoSession) = Unit
override fun onFirstContentfulPaint(session: GeckoSession) {
notifyObservers { onFirstContentfulPaint() }
}
override fun onPaintStatusReset(session: GeckoSession) {
notifyObservers { onPaintStatusReset() }
}
override fun onContextMenu(
session: GeckoSession,
screenX: Int,
screenY: Int,
element: GeckoSession.ContentDelegate.ContextElement,
) {
val hitResult = handleLongClick(element.srcUri, element.type, element.linkUri, element.title)
hitResult?.let {
notifyObservers { onLongPress(it) }
}
}
override fun onCrash(session: GeckoSession) {
notifyObservers { onCrash() }
}
override fun onKill(session: GeckoSession) {
notifyObservers {
onProcessKilled()
}
}
override fun onFullScreen(session: GeckoSession, fullScreen: Boolean) {
notifyObservers { onFullScreenChange(fullScreen) }
}
override fun onExternalResponse(session: GeckoSession, webResponse: WebResponse) {
with(webResponse) {
val contentType = headers[CONTENT_TYPE]?.trim()
val contentLength = headers[CONTENT_LENGTH]?.trim()?.toLong()
val contentDisposition = headers[CONTENT_DISPOSITION]?.trim()
val url = uri
val fileName = DownloadUtils.guessFileName(
contentDisposition,
destinationDirectory = null,
url = url,
mimeType = contentType,
)
val response = webResponse.toResponse()
notifyObservers {
onExternalResource(
url = url,
contentLength = contentLength,
contentType = DownloadUtils.sanitizeMimeType(contentType),
fileName = fileName.sanitizeFileName(),
response = response,
isPrivate = privateMode,
)
}
}
}
override fun onCloseRequest(session: GeckoSession) {
notifyObservers {
onWindowRequest(
GeckoWindowRequest(
engineSession = this@GeckoEngineSession,
type = WindowRequest.Type.CLOSE,
),
)
}
}
override fun onTitleChange(session: GeckoSession, title: String?) {
if (appRedirectUrl.isNullOrEmpty()) {
if (!privateMode) {
currentUrl?.let { url ->
settings.historyTrackingDelegate?.let { delegate ->
if (delegate.shouldStoreUri(url)) {
// NB: There's no guarantee that the title change will be processed by the
// delegate before the session is closed (and the corresponding coroutine
// job is cancelled). Observers will always be notified of the title
// change though.
launch(coroutineContext) {
delegate.onTitleChanged(url, title ?: "")
}
}
}
}
}
this@GeckoEngineSession.currentTitle = title
notifyObservers { onTitleChange(title ?: "") }
}
}
override fun onPreviewImage(session: GeckoSession, previewImageUrl: String) {
if (!privateMode) {
currentUrl?.let { url ->
settings.historyTrackingDelegate?.let { delegate ->
if (delegate.shouldStoreUri(url)) {
launch(coroutineContext) {
delegate.onPreviewImageChange(url, previewImageUrl)
}
}
}
}
}
notifyObservers { onPreviewImageChange(previewImageUrl) }
}
override fun onFocusRequest(session: GeckoSession) = Unit
override fun onWebAppManifest(session: GeckoSession, manifest: JSONObject) {
val parsed = WebAppManifestParser().parse(manifest)
if (parsed is WebAppManifestParser.Result.Success) {
notifyObservers { onWebAppManifestLoaded(parsed.manifest) }