aboutsummaryrefslogtreecommitdiff
path: root/app/src/main/kotlin/org/pacien/tincapp/activities/StatusActivity.kt
blob: 68e008e6517c5d4441afcb25a9a6f6911955e165 (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
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
/*
 * Tinc App, an Android binding and user interface for the tinc mesh VPN daemon
 * Copyright (C) 2017-2018 Pacien TRAN-GIRARD
 *
 * 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 <https://www.gnu.org/licenses/>.
 */

package org.pacien.tincapp.activities

import android.content.Intent
import android.os.Bundle
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.app.AlertDialog
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.TextView
import java8.util.concurrent.CompletableFuture
import kotlinx.android.synthetic.main.base.*
import kotlinx.android.synthetic.main.dialog_node_details.view.*
import kotlinx.android.synthetic.main.fragment_list_view.*
import kotlinx.android.synthetic.main.fragment_network_status_header.*
import org.pacien.tincapp.R
import org.pacien.tincapp.commands.Executor
import org.pacien.tincapp.commands.Tinc
import org.pacien.tincapp.data.VpnInterfaceConfiguration
import org.pacien.tincapp.extensions.Android.setElements
import org.pacien.tincapp.extensions.Android.setText
import org.pacien.tincapp.intent.Actions
import org.pacien.tincapp.intent.BroadcastMapper
import org.pacien.tincapp.service.TincVpnService
import java.util.*
import kotlin.concurrent.timerTask

/**
 * @author pacien
 */
class StatusActivity : BaseActivity(), AdapterView.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener {
  private val broadcastMapper = BroadcastMapper(mapOf(Actions.EVENT_DISCONNECTED to this::onVpnShutdown))
  private var shutdownDialog: AlertDialog? = null
  private var nodeListAdapter: ArrayAdapter<String>? = null
  private var refreshTimer: Timer? = null
  private var listNetworksAfterExit = true

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    nodeListAdapter = ArrayAdapter(this, R.layout.fragment_list_item)

    layoutInflater.inflate(R.layout.fragment_list_view, main_content)
    list_wrapper.setOnRefreshListener(this)
    list.addHeaderView(layoutInflater.inflate(R.layout.fragment_network_status_header, list, false), null, false)
    list.addFooterView(View(this), null, false)
    list.onItemClickListener = this
    list.adapter = nodeListAdapter

    if (intent.action == Actions.ACTION_DISCONNECT) {
      listNetworksAfterExit = false
      stopVpn()
    } else {
      listNetworksAfterExit = true
    }
  }

  override fun onCreateOptionsMenu(m: Menu): Boolean {
    menuInflater.inflate(R.menu.menu_status, m)
    return super.onCreateOptionsMenu(m)
  }

  override fun onDestroy() {
    super.onDestroy()
    nodeListAdapter = null
    refreshTimer = null
  }

  override fun onStart() {
    super.onStart()
    refreshTimer = Timer(true)
    refreshTimer?.schedule(timerTask { updateView() }, NOW, REFRESH_RATE)
    writeNetworkInfo(TincVpnService.getCurrentInterfaceCfg() ?: VpnInterfaceConfiguration())
  }

  override fun onStop() {
    refreshTimer?.cancel()
    super.onStop()
  }

  override fun onResume() {
    super.onResume()
    broadcastMapper.register()
    updateView()
    handleRecentCrash()
  }

  override fun onPause() {
    broadcastMapper.unregister()
    super.onPause()
  }

  override fun onRefresh() {
    refreshTimer?.schedule(timerTask { updateView() }, NOW)
  }

  override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) = when (view) {
    is TextView -> showNodeInfo(view.text.toString())
    else -> Unit
  }

  private fun onVpnShutdown() {
    shutdownDialog?.dismiss()
    if (listNetworksAfterExit) openStartActivity()
    finish()
  }

  fun stopVpn(@Suppress("UNUSED_PARAMETER") i: MenuItem? = null) {
    refreshTimer?.cancel()
    list_wrapper.isRefreshing = false
    shutdownDialog = showProgressDialog(R.string.message_disconnecting_vpn)
    TincVpnService.disconnect()
  }

  fun openLogViewer(@Suppress("UNUSED_PARAMETER") i: MenuItem) =
    startActivity(Intent(this, ViewLogActivity::class.java))

  private fun writeNetworkInfo(cfg: VpnInterfaceConfiguration) {
    text_network_name.text = TincVpnService.getCurrentNetName() ?: getString(R.string.value_none)
    text_network_ip_addresses.setText(cfg.addresses.map { it.toSlashSeparated() })
    text_network_routes.setText(cfg.routes.map { it.toSlashSeparated() })
    text_network_dns_servers.setText(cfg.dnsServers)
    text_network_search_domains.setText(cfg.searchDomains)
    text_network_allow_bypass.text = getString(if (cfg.allowBypass) R.string.value_yes else R.string.value_no)
    block_network_allowed_applications.visibility = if (cfg.allowedApplications.isNotEmpty()) View.VISIBLE else View.GONE
    text_network_allowed_applications.setText(cfg.allowedApplications)
    block_network_disallowed_applications.visibility = if (cfg.disallowedApplications.isNotEmpty()) View.VISIBLE else View.GONE
    text_network_disallowed_applications.setText(cfg.disallowedApplications)
  }

  private fun writeNodeList(nodeList: List<String>) {
    nodeListAdapter?.setElements(nodeList)
    node_list_placeholder.visibility = View.GONE
    list_wrapper.isRefreshing = false
  }

  private fun updateNodeList() {
    getNodeNames().thenAccept { nodeList -> runOnUiThread { writeNodeList(nodeList) } }
  }

  private fun showNodeInfo(nodeName: String) {
    val dialogTextView = layoutInflater.inflate(R.layout.dialog_node_details, main_content, false)

    runOnUiThread {
      AlertDialog.Builder(this)
        .setTitle(R.string.title_node_info)
        .setView(dialogTextView)
        .setPositiveButton(R.string.action_close) { _, _ -> Unit }
        .show()
    }

    TincVpnService.getCurrentNetName()?.let { netName ->
      Tinc.info(netName, nodeName).thenAccept { nodeInfo ->
        runOnUiThread { dialogTextView.dialog_node_details.text = nodeInfo }
      }
    }
  }

  private fun updateView() = when {
    TincVpnService.isConnected() -> updateNodeList()
    else -> openStartActivity()
  }

  private fun openStartActivity() {
    startActivity(Intent(this, StartActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
    finish()
  }

  companion object {
    private const val REFRESH_RATE = 5000L
    private const val NOW = 0L

    fun getNodeNames(): CompletableFuture<List<String>> = TincVpnService.getCurrentNetName()?.let { netName ->
      Tinc.dumpNodes(netName).thenApply<List<String>> { list -> list.map { it.substringBefore(' ') } }
    } ?: Executor.supplyAsyncTask<List<String>> { emptyList() }
  }
}