aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/fil/libre/repwifiapp/Commons.java
blob: 1603a763c04ab4caccaf500cc6320686dcdc8e47 (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
324
325
326
327
328
329
330
331
332
333
334
//
// Copyright 2017 Filippo "Fil" Bergamo <fil.bergamo@riseup.net>
// 
// This file is part of RepWifiApp.
//
// RepWifiApp 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.
// 
// RepWifiApp 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 RepWifiApp.  If not, see <http://www.gnu.org/licenses/>.
// 
// ********************************************************************

package fil.libre.repwifiapp;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Environment;
import android.preference.PreferenceManager;
import fil.libre.repwifiapp.activities.MainActivity;
import fil.libre.repwifiapp.helpers.ConnectionStatus;
import fil.libre.repwifiapp.helpers.Engine;
import fil.libre.repwifiapp.helpers.Engine6p0;
import fil.libre.repwifiapp.helpers.IEngine;
import fil.libre.repwifiapp.helpers.NetworkManager;
import fil.libre.repwifiapp.helpers.Utils;
import fil.libre.repwifiapp.helpers.WpaCli;
import fil.libre.repwifiapp.helpers.WpaSupplicant;

public abstract class Commons {

    private static Context currentContext;

    public static Context getContext() {
        return currentContext;
    }

    // ------------- Environment Constants -----------------
    public static final int EXCOD_ROOT_DISABLED = 255;
    public static final int EXCOD_ROOT_DENIED = 1;
    public static final int WAIT_ON_USB_ATTACHED = 1500;
    public static final int WAIT_FOR_GATEWAY = 4000;
    public static final String BSSID_NOT_AVAILABLE = "[BSSID-NOT-AVAILABLE]";
    public static final String v6p0 = "6.0";
    // ---------------------------------------------

    // ------------- Shared Engines -----------------------
    public static IEngine connectionEngine = null;
    public static NetworkManager storage = null;
    // ----------------------------------------------------

    // ------------- Shared Resources ---------------------
    public static int colorThemeDark;
    public static int colorThemeLight;
    public static int colorBlack;
    public static String dns1Default = "";
    public static String dns2Default = "";
    private static String APP_DATA_FOLDER;
    public static String msgNoSavedNetwork;

    public static String getNetworkStorageFile() {
        if (APP_DATA_FOLDER == null) {
            return null;
        } else {
            return APP_DATA_FOLDER + "/repwifi_storage.conf";
        }
    }
    
    @SuppressLint("SimpleDateFormat")
    public static String getLogDumpFile() {

        File f = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        if (f == null || !f.exists()) {
            return null;
        }

        String basefolder;
        try {
            basefolder = f.getCanonicalPath();
        } catch (Exception e) {
            Utils.logError("Exception while resolving canonical path for log dump file.", e);
            return null;
        }
        
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss", Locale.getDefault());
        String ts = dateFormat.format(Calendar.getInstance().getTime());
        return basefolder + "/repwifi_log_dump." + ts + ".log";
    }

    // --------------------------------------------------------

    private static final int NOTIFICATION_ID = 1;

    public static void updateNotification(Context context) {

        ConnectionStatus status = WpaCli.getConnectionStatus();

        Notification.Builder builder = new Notification.Builder(context);

        Intent intent = new Intent(context, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
        builder.setContentIntent(pendingIntent);

        int iconId = R.drawable.ic_stat_discon;
        String msg = "RepWifi";
        if (status != null) {
            if (status.isConnected()) {
                iconId = R.drawable.ic_stat_repwifi;
                msg += " - " + status.SSID;
            } else {
                msg += " - " + status.status;
            }

        }

        builder.setSmallIcon(iconId);

        builder.setContentTitle(msg);
        builder.setContentText(currentContext.getString(R.string.msg_touch_open));

        Notification n = builder.build();
        n.flags |= Notification.FLAG_NO_CLEAR;

        NotificationManager notificationManager = (NotificationManager) context
                        .getSystemService(Service.NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID, n);

    }

    public static void showMessage(String msg) {
        showMessage(msg, currentContext);
    }

    public static void showMessage(String msg, Context context) {

        AlertDialog.Builder dlgAlert = new AlertDialog.Builder(context,
                        R.style.Theme_RepWifiDialogTheme);
        dlgAlert.setMessage(msg);
        dlgAlert.setPositiveButton(currentContext.getString(android.R.string.ok),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int whichButton) {
                                return;
                            }
                        });

        dlgAlert.setCancelable(false);
        AlertDialog diag = dlgAlert.create();

        diag.show();

    }

    public static void resetSettingsDefault(Context context, boolean silent) {

        if (silent) {
            Editor e = getSettings().edit();
            e.clear();
            e.commit();
        } else {

            String msg = context.getString(R.string.confirm_reset_settings);
            AlertDialog.Builder dlgAlert = new AlertDialog.Builder(context,
                            R.style.Theme_RepWifiDialogTheme);
            dlgAlert.setMessage(msg);
            dlgAlert.setPositiveButton(context.getString(android.R.string.ok),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int whichButton) {
                                    resetSettingsDefault(null, true);
                                    return;
                                }
                            });
            dlgAlert.setNegativeButton(context.getString(android.R.string.cancel),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int whichButton) {
                                    return;
                                }
                            });

            dlgAlert.setCancelable(false);
            AlertDialog diag = dlgAlert.create();

            diag.show();

            return;
        }

    }

    public static void killBackEnd(Context context, boolean silent) {

        if (silent) {

            Engine.killDhcpcd();
            WpaSupplicant.kill();

        } else {

            String msg = context.getString(R.string.confirm_kill_backend);
            AlertDialog.Builder dlgAlert = new AlertDialog.Builder(context,
                            R.style.Theme_RepWifiDialogTheme);
            dlgAlert.setMessage(msg);
            dlgAlert.setPositiveButton(context.getString(android.R.string.ok),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int whichButton) {
                                    killBackEnd(null, true);
                                    return;
                                }
                            });
            dlgAlert.setNegativeButton(context.getString(android.R.string.cancel),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int whichButton) {
                                    return;
                                }
                            });

            dlgAlert.setCancelable(false);
            AlertDialog diag = dlgAlert.create();

            diag.show();
            return;

        }

    }

    public static int getLogPriority() {

        SharedPreferences sets = getSettings();
        return Integer.parseInt(sets.getString("debug_priority", "3"));

    }

    public static boolean isProgbarEnabled() {
        return getSettings().getBoolean("enable_progbar", true);
    }

    public static boolean isAutoConnectEnabled() {
        return getSettings().getBoolean("enable_autoconnect", false);
    }

    public static String[] getDnss() {

        String dns1 = getSettings().getString("dns1", dns1Default);
        String dns2 = getSettings().getString("dns2", dns2Default);

        if (dns1 == null || dns1.isEmpty()) {
            return null;
        }

        return new String[] { dns1, dns2 };

    }

    public static SharedPreferences getSettings() {

        return PreferenceManager.getDefaultSharedPreferences(currentContext);

    }

    // ----------------------------------------------------

    // ----------- Initialization methods ---------------------------
    public static boolean init(Context context) {

        currentContext = context;

        try {

            colorThemeDark = currentContext.getResources().getColor(R.color.ThemeDark);
            colorThemeLight = currentContext.getResources().getColor(R.color.ThemeLight);
            msgNoSavedNetwork = currentContext.getResources().getString(
                            R.string.msg_no_saved_network);
            colorBlack = currentContext.getResources().getColor(R.color.black);
            APP_DATA_FOLDER = currentContext.getExternalFilesDir(null).getAbsolutePath();
            dns1Default = currentContext.getResources().getString(R.string.dns1_default);
            dns2Default = currentContext.getResources().getString(R.string.dns2_default);

            initEngine();
            initNetworkStorage();

            return true;

        } catch (Exception e) {
            Utils.logError("Error initializing common resources.", e);
            return false;
        }
    }

    private static void initEngine() throws Exception {

        connectionEngine = new Engine6p0();

        String vers = android.os.Build.VERSION.RELEASE;

        if (!vers.startsWith(Commons.v6p0)) {
            showMessage(currentContext.getString(R.string.msg_os_unsupported));
        }

    }

    private static void initNetworkStorage() throws Exception {

        Commons.storage = new NetworkManager(getNetworkStorageFile());

    }
    // --------------------------------------------------------------

}