summaryrefslogtreecommitdiff
path: root/main/src/ui/java/de/blinkt/openvpn/fragments/Settings_Allowed_Apps.kt
blob: e38797752df23f2aa56b181c4e2a7738221027eb (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
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
/*
 * Copyright (c) 2012-2016 Arne Schwabe
 * Distributed under the GNU GPL v2 with additional terms. For full terms see the file doc/LICENSE.txt
 */

package de.blinkt.openvpn.fragments

import android.Manifest
import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.BaseAdapter
import android.widget.CompoundButton
import android.widget.Filter
import android.widget.Filterable
import android.widget.ImageView
import android.widget.ListView
import android.widget.SearchView
import android.widget.Switch
import android.widget.TextView
import androidx.fragment.app.Fragment

import java.util.Collections
import java.util.Locale
import java.util.Vector

import de.blinkt.openvpn.R
import de.blinkt.openvpn.VpnProfile
import de.blinkt.openvpn.core.ProfileManager
import org.jetbrains.anko.runOnUiThread

/**
 * Created by arne on 16.11.14.
 */
class Settings_Allowed_Apps : Fragment(), AdapterView.OnItemClickListener, CompoundButton.OnCheckedChangeListener, View.OnClickListener {
    private lateinit var mListView: ListView
    private lateinit var mProfile: VpnProfile
    private lateinit var mDefaultAllowTextView: TextView
    private lateinit var mListAdapter: PackageAdapter
    private lateinit var mSettingsView: View


    override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
        val avh = view.tag as AppViewHolder
        avh.checkBox.toggle()
    }

    override fun onClick(v: View) {

    }

    override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {
        val packageName = buttonView.tag as String
        if (isChecked) {
            mProfile.mAllowedAppsVpn.add(packageName)
        } else {
            mProfile.mAllowedAppsVpn.remove(packageName)
        }
    }

    override fun onResume() {
        super.onResume()
        changeDisallowText(mProfile.mAllowedAppsVpnAreDisallowed)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val profileUuid = requireArguments().getString(activity!!.packageName + ".profileUUID")
        mProfile = ProfileManager.get(activity, profileUuid)
        activity!!.title = getString(R.string.edit_profile_title, mProfile.name)
        setHasOptionsMenu(true)
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.allowed_apps, menu)

        val searchView = menu.findItem(R.id.app_search_widget).actionView as SearchView
        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String): Boolean {
                mListView.setFilterText(query)
                mListView.isTextFilterEnabled = true
                return true
            }

            override fun onQueryTextChange(newText: String): Boolean {
                mListView.setFilterText(newText)
                mListView.isTextFilterEnabled = !TextUtils.isEmpty(newText)

                return true
            }
        })
        searchView.setOnCloseListener {
            mListView.clearTextFilter()
            mListAdapter.filter.filter("")
            false
        }

        super.onCreateOptionsMenu(menu, inflater)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val v = inflater.inflate(R.layout.allowed_vpn_apps, container, false)

        mSettingsView = inflater.inflate(R.layout.allowed_application_settings, container, false)
        mDefaultAllowTextView = mSettingsView.findViewById<View>(R.id.default_allow_text) as TextView

        val vpnOnDefaultSwitch = mSettingsView.findViewById<View>(R.id.default_allow) as Switch

        vpnOnDefaultSwitch.setOnCheckedChangeListener { _, isChecked ->
            changeDisallowText(isChecked)
            mProfile.mAllowedAppsVpnAreDisallowed = isChecked
        }

        vpnOnDefaultSwitch.isChecked = mProfile.mAllowedAppsVpnAreDisallowed

        val vpnAllowBypassSwitch = mSettingsView.findViewById<View>(R.id.allow_bypass) as Switch

        vpnAllowBypassSwitch.setOnCheckedChangeListener { _, isChecked -> mProfile.mAllowAppVpnBypass = isChecked }

        vpnAllowBypassSwitch.isChecked = mProfile.mAllowAppVpnBypass

        mListView = v.findViewById<View>(android.R.id.list) as ListView

        mListAdapter = PackageAdapter(requireContext(), mProfile)
        mListView.adapter = mListAdapter
        mListView.onItemClickListener = this

        mListView.emptyView = v.findViewById(R.id.loading_container)

        Thread(Runnable { mListAdapter.populateList(requireContext()) }).start()

        return v
    }

    private fun changeDisallowText(selectedAreDisallowed: Boolean) {
        if (selectedAreDisallowed)
            mDefaultAllowTextView.setText(R.string.vpn_disallow_radio)
        else
            mDefaultAllowTextView.setText(R.string.vpn_allow_radio)
    }

    internal class AppViewHolder {
        var mInfo: ApplicationInfo? = null
        var rootView: View? = null
        lateinit var appName: TextView
        lateinit var appIcon: ImageView
        //public TextView appSize;
        //public TextView disabled;
        lateinit var checkBox: CompoundButton

        companion object {

            fun createOrRecycle(inflater: LayoutInflater, oldview: View?, parent: ViewGroup): AppViewHolder {
                var convertView = oldview
                if (convertView == null) {
                    convertView = inflater.inflate(R.layout.allowed_application_layout, parent, false)

                    // Creates a ViewHolder and store references to the two children views
                    // we want to bind data to.
                    val holder = AppViewHolder()
                    holder.rootView = convertView
                    holder.appName = convertView.findViewById<View>(R.id.app_name) as TextView
                    holder.appIcon = convertView.findViewById<View>(R.id.app_icon) as ImageView
                    //holder.appSize = (TextView) convertView.findViewById(R.id.app_size);
                    //holder.disabled = (TextView) convertView.findViewById(R.id.app_disabled);
                    holder.checkBox = convertView.findViewById<View>(R.id.app_selected) as CompoundButton
                    convertView.tag = holder


                    return holder
                } else {
                    // Get the ViewHolder back to get fast access to the TextView
                    // and the ImageView.
                    return convertView.tag as AppViewHolder
                }
            }
        }

    }

    internal inner class PackageAdapter(c: Context, vp: VpnProfile) : BaseAdapter(), Filterable {
        private val mInflater: LayoutInflater = LayoutInflater.from(c)
        private val mPm: PackageManager = c.packageManager
        private var mPackages: Vector<ApplicationInfo> = Vector()
        private val mFilter = ItemFilter()
        private var mFilteredData: Vector<ApplicationInfo> = mPackages
        private val mProfile = vp


        fun populateList(c: Context) {
            val installedPackages = mPm.getInstalledApplications(PackageManager.GET_META_DATA)

            // Remove apps not using Internet

            var androidSystemUid = 0
            val apps = Vector<ApplicationInfo>()

            try {
                val system = mPm.getApplicationInfo("android", PackageManager.GET_META_DATA)
                androidSystemUid = system.uid
                apps.add(system)
            } catch (e: PackageManager.NameNotFoundException) {
            }


            for (app in installedPackages) {

                if (mPm.checkPermission(Manifest.permission.INTERNET, app.packageName) == PackageManager.PERMISSION_GRANTED && app.uid != androidSystemUid) {

                    apps.add(app)
                }
            }

            Collections.sort(apps, ApplicationInfo.DisplayNameComparator(mPm))
            mPackages = apps
            mFilteredData = apps
            c.runOnUiThread { notifyDataSetChanged() }
        }

        override fun getCount(): Int {
            return mFilteredData.size + 1
        }

        override fun getItem(position: Int): Any {
            return mFilteredData[position - 1]
        }

        override fun getItemId(position: Int): Long {
            if (position == 0)
                return "settings".hashCode().toLong()
            return mFilteredData[position - 1].packageName.hashCode().toLong()
        }

        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
            if (position == 0) {
                return mSettingsView
            } else
                return getViewApp(position - 1, convertView, parent)

        }

        fun getViewApp(position: Int, convertView: View?, parent: ViewGroup): View? {
            val viewHolder = AppViewHolder.createOrRecycle(mInflater, convertView, parent)
            viewHolder.mInfo = mFilteredData[position]
            val mInfo = mFilteredData[position]


            var appName = mInfo.loadLabel(mPm)

            if (TextUtils.isEmpty(appName))
                appName = mInfo.packageName
            viewHolder.appName.text = appName
            viewHolder.appIcon.setImageDrawable(mInfo.loadIcon(mPm))
            viewHolder.checkBox.tag = mInfo.packageName
            viewHolder.checkBox.setOnCheckedChangeListener(this@Settings_Allowed_Apps)


            viewHolder.checkBox.isChecked = mProfile.mAllowedAppsVpn.contains(mInfo.packageName)
            return viewHolder.rootView
        }

        override fun getFilter(): Filter {
            return mFilter
        }

        override fun getViewTypeCount(): Int {
            return 2;
        }

        override fun getItemViewType(position: Int): Int {
            return if (position == 0) 0 else 1
        }

        private inner class ItemFilter : Filter() {
            override fun performFiltering(constraint: CharSequence): FilterResults {

                val filterString = constraint.toString().toLowerCase(Locale.getDefault())

                val results = FilterResults()


                val count = mPackages.size
                val nlist = Vector<ApplicationInfo>(count)

                for (i in 0 until count) {
                    val pInfo = mPackages[i]
                    var appName = pInfo.loadLabel(mPm)

                    if (TextUtils.isEmpty(appName))
                        appName = pInfo.packageName

                    if (appName is String) {
                        if (appName.toLowerCase(Locale.getDefault()).contains(filterString))
                            nlist.add(pInfo)
                    } else {
                        if (appName.toString().toLowerCase(Locale.getDefault()).contains(filterString))
                            nlist.add(pInfo)
                    }
                }
                results.values = nlist
                results.count = nlist.size

                return results
            }

            override fun publishResults(constraint: CharSequence, results: FilterResults) {
                mFilteredData = results.values as Vector<ApplicationInfo>
                notifyDataSetChanged()
            }

        }
    }
}