ConfigureActivity.kt 12.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
package com.frostnerd.smokescreen.tasker

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.EditText
13
14
import com.frostnerd.dnstunnelproxy.DnsServerInformation
import com.frostnerd.encrypteddnstunnelproxy.HttpsDnsServerInformation
15
16
import com.frostnerd.lifecyclemanagement.BaseActivity
import com.frostnerd.smokescreen.R
17
import com.frostnerd.smokescreen.activity.BackgroundVpnConfigureActivity
18
import com.frostnerd.smokescreen.dialog.NewServerDialog
19
20
21
import com.frostnerd.smokescreen.fromServerUrls
import com.frostnerd.smokescreen.hasHttpsServer
import com.frostnerd.smokescreen.tlsServerFromHosts
22
23
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
24
25
import kotlinx.android.synthetic.main.activity_tasker_configure.*

Daniel Wolf's avatar
Daniel Wolf committed
26
27
/*
 * Copyright (C) 2019 Daniel Wolf (Ch4t4r)
28
 *
Daniel Wolf's avatar
Daniel Wolf committed
29
30
31
32
33
34
35
36
37
38
39
40
41
42
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * You can contact the developer at daniel.wolf@frostnerd.com.
43
44
 */
class ConfigureActivity : BaseActivity() {
45
46
    private var validationRegex = NewServerDialog.SERVER_URL_REGEX

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
    override fun getConfiguration(): Configuration {
        return Configuration.withDefaults()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_tasker_configure)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        createLayout()
        applyOldConfiguration()
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            saveConfiguration()
            finish()
        }
        return super.onOptionsItemSelected(item)
    }

    private fun applyOldConfiguration() {
        if (intent != null && intent.extras != null) {
            val settings = intent.extras!!.getBundle(TaskerHelper.EXTRAS_BUNDLE_KEY)
            if (settings != null) {
                val action = settings.getString(TaskerHelper.DATA_KEY_ACTION, "start")
                when (action) {
                    "stop" -> {
74
                        actionType.setSelection(1)
75
76
                    }
                    "start" -> {
77
                        actionType.setSelection(0)
78
                        startIfRunning.isChecked = settings.getBoolean(TaskerHelper.DATA_KEY_STARTIFRUNNING, true)
79
80
81
82
                        useServersFromConfig.isChecked =
                            !settings.containsKey(TaskerHelper.DATA_KEY_PRIMARYSERVER) && !settings.containsKey(
                                BackgroundVpnConfigureActivity.extraKeyServerConfig
                            )
83
                        if (!useServersFromConfig.isChecked) {
84
85
86
87
88
89
90
91
92
93
94
95
                            if (settings.containsKey(TaskerHelper.DATA_KEY_PRIMARYSERVER)) {
                                serverType.setSelection(0)
                                primaryServer.setText(settings.getString(TaskerHelper.DATA_KEY_PRIMARYSERVER))
                                secondaryServer.setText(settings.getString(TaskerHelper.DATA_KEY_SECONDARYSERVER))
                            } else {
                                val info = BackgroundVpnConfigureActivity.readServerInfoFromIntent(settings)
                                if (info != null) {
                                    if (info.hasHttpsServer()) {
                                        validationRegex = NewServerDialog.SERVER_URL_REGEX
                                        serverType.setSelection(0)
                                        val httpsInfo = info as HttpsDnsServerInformation
                                        val configs = httpsInfo.serverConfigurations.values.toTypedArray()
96
97
                                        primaryServer.setText(configs.getOrNull(0)?.urlCreator?.address?.getUrl(true))
                                        secondaryServer.setText(configs.getOrNull(1)?.urlCreator?.address?.getUrl(true))
98
99
100
                                    } else {
                                        validationRegex = NewServerDialog.TLS_REGEX
                                        serverType.setSelection(1)
Daniel Wolf's avatar
Daniel Wolf committed
101
102
                                        primaryServer.setText(info.servers.getOrNull(0)?.address?.host)
                                        secondaryServer.setText(info.servers.getOrNull(1)?.address?.host)
103
104
105
                                    }
                                }
                            }
106
                        }
107
                        setHints()
108
109
110
111
112
113
114
115
116
117
                    }
                }
            }
        }
    }

    private fun createLayout() {
        useServersFromConfig.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                serverConfigWrap.visibility = View.GONE
118
                serverType.visibility = View.GONE
119
            } else {
120
                serverType.visibility = View.VISIBLE
121
122
123
124
125
126
127
128
129
                serverConfigWrap.visibility = View.VISIBLE
            }
        }
        val adapter: ArrayAdapter<CharSequence> = ArrayAdapter.createFromResource(
            this,
            R.array.tasker_action_values,
            R.layout.item_tasker_action_spinner_item
        )
        adapter.setDropDownViewResource(R.layout.item_tasker_action_spinner_dropdown_item)
130
131
        actionType.adapter = adapter
        actionType.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
132
133
134
135
136
137
138
139
140
141
142
            override fun onNothingSelected(parent: AdapterView<*>?) {
            }

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                if (position == 0) {
                    startConfigWrap.visibility = View.VISIBLE
                } else {
                    startConfigWrap.visibility = View.GONE
                }
            }
        }
143
        val typeAdapter = ArrayAdapter<String>(
144
145
146
147
148
149
            this, android.R.layout.simple_spinner_item,
            arrayListOf(
                this.getString(R.string.dialog_serverconfiguration_https),
                this.getString(R.string.dialog_serverconfiguration_tls)
            )
        )
150
151
        typeAdapter.setDropDownViewResource(R.layout.item_tasker_action_spinner_dropdown_item)
        serverType.adapter = typeAdapter
152
153
154
155
156
157
158
        serverType.setSelection(0)
        serverType.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {}
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                validationRegex = if (position == 0) NewServerDialog.SERVER_URL_REGEX else NewServerDialog.TLS_REGEX
                primaryServer.text = primaryServer.text
                secondaryServer.text = secondaryServer.text
159
                setHints()
160
161
            }
        }
162
163
        addUrlTextWatcher(primaryServerWrap, primaryServer, false)
        addUrlTextWatcher(secondaryServerWrap, secondaryServer, true)
164
        setHints()
165
166
    }

167
168
169
170
171
172
173
174
175
176
177
178
179
180
    private fun setHints() {
        val doh = serverType.selectedItemPosition == 0
        println("DOH: $doh")
        primaryServer.hint = if(primaryServer.hasFocus() || primaryServerWrap.error != null) {
            if(doh) getString(R.string.dialog_newserver_primaryserver_hint)
            else getString(R.string.dialog_newserver_primaryserver_hint_dot)
        } else null
        secondaryServer.hint = if(secondaryServer.hasFocus()) {
            if(doh) getString(R.string.dialog_newserver_secondaryserver_hint)
            else getString(R.string.dialog_newserver_secondaryserver_hint_dot)
        } else null
    }

    private fun addUrlTextWatcher(input: TextInputLayout, editText: TextInputEditText, emptyAllowed: Boolean) {
181
182
        editText.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable) {
183
                val valid = (emptyAllowed && s.isBlank()) || validationRegex.matches(s.toString())
184

185
186
187
                input.error = if (valid) {
                    null
                } else getString(R.string.error_invalid_url)
188
189
190
191
192
193
194
195
196
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

        })
197
198
199
        editText.setOnFocusChangeListener { _, hasFocus ->
            setHints()
        }
200
201
202
203
204
205
206
207
208
    }

    override fun onBackPressed() {
        saveConfiguration()
        super.onBackPressed()
    }

    private fun saveConfiguration() {
        var valid = true
209
        val action = if (actionType.selectedItemPosition == 0) "start" else "stop"
210
211
212
213
214
        val resultIntent = Intent()
        val settings = Bundle()
        settings.putString(TaskerHelper.DATA_KEY_ACTION, action)
        resultIntent.putExtra(
            TaskerHelper.EXTRAS_BLURB_KEY,
215
            resources.getStringArray(R.array.tasker_action_values)[actionType.selectedItemPosition]
216
217
218
219
        )
        if (action == "start") {
            settings.putBoolean(TaskerHelper.DATA_KEY_STARTIFRUNNING, startIfRunning.isChecked)
            if (!useServersFromConfig.isChecked) {
220
221
                if (primaryServerWrap.error == null &&
                    secondaryServerWrap.error == null
222
223
224
                ) {
                    var primary = primaryServer.text.toString()
                    var secondary = if (secondaryServer.text.isNullOrBlank()) null else secondaryServer.text.toString()
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
                    if (primary.startsWith("https")) primary = primary.replace("https://", "")
                    if (secondary != null && secondary.startsWith("https")) secondary =
                        secondary.replace("https://", "")
                    val mode:String

                    if (serverType.selectedItemPosition == 1) {
                        mode = getString(R.string.tasker_mode_dot)
                        BackgroundVpnConfigureActivity.writeServerInfoToIntent(
                            DnsServerInformation.tlsServerFromHosts(
                                primary,
                                secondary
                            ), settings
                        )
                    } else {
                        mode = getString(R.string.tasker_mode_doh)
                        BackgroundVpnConfigureActivity.writeServerInfoToIntent(
                            HttpsDnsServerInformation.fromServerUrls(
                                primary,
                                secondary
                            ), settings
                        )
                    }
247
248
249
250

                    if (secondary != null) {
                        resultIntent.putExtra(
                            TaskerHelper.EXTRAS_BLURB_KEY,
251
                            getString(R.string.tasker_start_app_custom_urls, primary, secondary, mode)
252
253
254
255
                        )
                    } else {
                        resultIntent.putExtra(
                            TaskerHelper.EXTRAS_BLURB_KEY,
256
                            getString(R.string.tasker_start_app_custom_url, primary, mode)
257
258
259
260
261
262
263
264
265
266
267
268
269
270
                        )
                    }
                    settings.putBoolean(TaskerHelper.DATA_KEY_STARTIFRUNNING, startIfRunning.isChecked)
                } else {
                    valid = false
                }
            }
        }
        if (valid) {
            resultIntent.putExtra(TaskerHelper.EXTRAS_BUNDLE_KEY, settings)
            setResult(Activity.RESULT_OK, resultIntent)
        } else setResult(Activity.RESULT_CANCELED)
    }
}