aboutsummaryrefslogtreecommitdiff
path: root/app/src/main/kotlin/com/pitchedapps/frost/web/FrostRequestInterceptor.kt
blob: 45dc83aa10029dba049da1cf2b889b3fa5eb78ee (plain)
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
package com.pitchedapps.frost.web

import android.graphics.Bitmap.CompressFormat
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import ca.allanwang.kau.utils.use
import com.pitchedapps.frost.utils.GlideApp
import com.pitchedapps.frost.utils.L
import com.pitchedapps.frost.utils.Prefs
import okhttp3.HttpUrl
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream


/**
 * Created by Allan Wang on 2017-07-13.
 *
 * Handler to decide when a request should be done by us
 * This is the crux of Frost's optimizations for the web browser
 */
val blankResource: WebResourceResponse by lazy { WebResourceResponse("text/plain", "utf-8", ByteArrayInputStream("".toByteArray())) }

//these hosts will redirect to a blank resource
val blacklistHost: Set<String> by lazy {
    setOf(
            "edge-chat.facebook.com"
    )
}

//these hosts will return null and skip logging
val whitelistHost: Set<String> by lazy {
    setOf(
            "static.xx.fbcdn.net",
            "m.facebook.com",
            "touch.facebook.com"
    )
}

//these hosts will skip ad inspection
//this list does not have to include anything from the two above
val adWhitelistHost: Set<String> by lazy {
    setOf(
            "scontent-sea1-1.xx.fbcdn.net"
    )
}

var adblock: Set<String>? = null

fun shouldFrostInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
    val httpUrl = HttpUrl.parse(request.url?.toString() ?: return null) ?: return null
    val host = httpUrl.host()
    val url = httpUrl.toString()
    if (blacklistHost.contains(host)) return blankResource
    if (whitelistHost.contains(host)) return null
    if (!adWhitelistHost.contains(host)) {
        if (adblock == null) adblock = view.context.assets.open("adblock.txt").bufferedReader().use { it.readLines().toSet() }
        if (adblock?.any { url.contains(it) } ?: false) return blankResource
    }
    L.v("Intercept Request ${host} ${url}")
    return null
}

fun WebResourceResponse?.filterCss(request: WebResourceRequest): WebResourceResponse?
        = this ?: if (request.url.path.endsWith(".css")) blankResource else null