summaryrefslogtreecommitdiff
path: root/app/src/main/java/se/leap/bitmaskclient/eip/VpnNotificationManager.java
blob: b4d11f265f883871fb92c5c403b70b30344d96ea (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
335
336
337
338
339
/**
 * Copyright (c) 2018 LEAP Encryption Access Project and contributers
 *
 * 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/>.
 */
package se.leap.bitmaskclient.eip;

import static android.os.Build.VERSION_CODES.O;
import static android.text.TextUtils.isEmpty;
import static androidx.core.app.NotificationCompat.PRIORITY_DEFAULT;
import static androidx.core.app.NotificationCompat.PRIORITY_MAX;
import static de.blinkt.openvpn.core.ConnectionStatus.LEVEL_NONETWORK;
import static de.blinkt.openvpn.core.ConnectionStatus.LEVEL_WAITING_FOR_USER_INPUT;
import static se.leap.bitmaskclient.base.MainActivity.ACTION_SHOW_VPN_FRAGMENT;
import static se.leap.bitmaskclient.base.models.Constants.ASK_TO_CANCEL_VPN;
import static se.leap.bitmaskclient.base.models.Constants.EIP_ACTION_START;
import static se.leap.bitmaskclient.base.models.Constants.EIP_ACTION_STOP_BLOCKING_VPN;
import static se.leap.bitmaskclient.base.utils.ConfigHelper.getPendingIntentFlags;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.StyleSpan;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import de.blinkt.openvpn.LaunchVPN;
import de.blinkt.openvpn.core.ConnectionStatus;
import de.blinkt.openvpn.core.OpenVPNService;
import de.blinkt.openvpn.core.VpnStatus;
import se.leap.bitmaskclient.R;
import se.leap.bitmaskclient.base.MainActivity;
import se.leap.bitmaskclient.base.StartActivity;

/**
 * Created by cyberta on 14.01.18.
 */

public class VpnNotificationManager {

    private static final String TAG = VpnNotificationManager.class.getSimpleName();
    Context context;
    private final NotificationManagerCompat compatNotificationManager;

    public interface VpnServiceCallback {
        void onNotificationBuild(int notificationId, Notification notification);
    }

    public VpnNotificationManager(@NonNull Context context) {
       this.context = context;
       compatNotificationManager = NotificationManagerCompat.from(context);
    }

    public void buildVoidVpnNotification(final String msg, String tickerText, ConnectionStatus status, VpnServiceCallback callback) {
        //TODO: implement extra Dashboard.ACTION_ASK_TO_CANCEL_BLOCKING_VPN
        NotificationCompat.Action.Builder actionBuilder = new NotificationCompat.Action.Builder(R.drawable.ic_menu_close_clear_cancel,
                context.getString(R.string.vpn_button_turn_off_blocking), getStopVoidVpnIntent());

        buildVpnNotification(
                context.getString(R.string.void_vpn_title),
                msg,
                null,
                tickerText,
                status,
                VoidVpnService.NOTIFICATION_CHANNEL_NEWSTATUS_ID,
                PRIORITY_MAX,
                0,
                getMainActivityIntent(),
                actionBuilder.build(),
                callback
                );
    }


    public void buildForegroundServiceNotification(ConnectionStatus connectionStatus,
                                                   VpnServiceCallback callback) {
        String message = "";
        // if the app was killed by the system getLastCleanLogMessage returns an empty string
        // because the state doesn't get persisted. We can use LEVEL_NOTCONNECTED as an indicator for
        // that case because the openvpn service won't be connected then
        if (connectionStatus == ConnectionStatus.LEVEL_NOTCONNECTED) {
            message = context.getString(R.string.eip_state_not_connected);
        } else {
            message = VpnStatus.getLastCleanLogMessage(context);
        }

        NotificationCompat.Action.Builder actionBuilder = new NotificationCompat.Action.Builder(0,
                context.getString(R.string.vpn_button_turn_on), getStartOpenvpnIntent());

        buildVpnNotification(
                "",
                message,
                null,
                "",
                connectionStatus,
                OpenVPNService.NOTIFICATION_CHANNEL_NEWSTATUS_ID,
                PRIORITY_DEFAULT,
                0,
                getMainActivityIntent(),
                actionBuilder.build(),
                callback
                );
    }

    public void buildOpenVpnNotification(String profileName, boolean isObfuscated, String msg,
                                         String tickerText, ConnectionStatus status, long when,
                                         String channelId, VpnServiceCallback vpnServiceCallback) {
        String cancelString;
        CharSequence bigmessage = null;
        String bridgeIcon = new String(Character.toChars(0x1f309));

        switch (status) {
            // show cancel if no connection
            case LEVEL_START:
            case LEVEL_NONETWORK:
            case LEVEL_CONNECTING_SERVER_REPLIED:
            case LEVEL_CONNECTING_NO_SERVER_REPLY_YET:
                cancelString = context.getString(R.string.cancel);
                if (isObfuscated) {
                    Spannable spannable = new SpannableString(context.getString(R.string.obfuscated_connection_try));
                    spannable.setSpan(new StyleSpan(Typeface.ITALIC), 0, spannable.length() -1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    bigmessage = TextUtils.concat(spannable, " " + bridgeIcon + "\n" + msg);
                }
                break;

            // show disconnect if connection exists
            case LEVEL_CONNECTED:
                if (isObfuscated) {
                    Spannable spannable = new SpannableString(context.getString(R.string.obfuscated_connection));
                    spannable.setSpan(new StyleSpan(Typeface.ITALIC), 0, spannable.length() -1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    bigmessage = TextUtils.concat(spannable, " " + bridgeIcon + "\n" + msg);
                }
            default:
                cancelString = context.getString(R.string.cancel_connection);
        }

        if (isObfuscated) {
            msg =  bridgeIcon + " " + msg;
        }

        NotificationCompat.Action.Builder actionBuilder = new NotificationCompat.Action.
                Builder(R.drawable.ic_menu_close_clear_cancel, cancelString, getDisconnectIntent());
        String title;
        String appName = context.getString(R.string.app_name);
        if (isEmpty(profileName)) {
            title = appName;
        } else {
            title = context.getString(R.string.notifcation_title_bitmask, appName, profileName);
        }

        PendingIntent contentIntent;
        if (status == LEVEL_WAITING_FOR_USER_INPUT)
            contentIntent = getUserInputIntent(msg);
        else
            contentIntent = getMainActivityIntent();
        buildVpnNotification(
                title,
                msg,
                bigmessage,
                tickerText,
                status,
                channelId,
                PRIORITY_DEFAULT,
                when,
                contentIntent,
                actionBuilder.build(),
                vpnServiceCallback);
    }

    public void buildOpenVpnNotification(String profileName, boolean isObfuscated, String msg, String tickerText, ConnectionStatus status, long when, String notificationChannelNewstatusId) {
        buildOpenVpnNotification(profileName, isObfuscated, msg, tickerText, status, when, notificationChannelNewstatusId, null);
    }

    public void cancelAll() {
        compatNotificationManager.cancel(OpenVPNService.NOTIFICATION_CHANNEL_NEWSTATUS_ID.hashCode());
        compatNotificationManager.cancel(VoidVpnService.NOTIFICATION_CHANNEL_NEWSTATUS_ID.hashCode());
    }


    @TargetApi(O)
    public void createVoidVpnNotificationChannel() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            return;
        }

        // Connection status change messages
        NotificationChannel channel = compatNotificationManager.getNotificationChannel(VoidVpnService.NOTIFICATION_CHANNEL_NEWSTATUS_ID);
        if (channel == null) {
            CharSequence name = context.getString(R.string.channel_name_status);
            channel = new NotificationChannel(VoidVpnService.NOTIFICATION_CHANNEL_NEWSTATUS_ID,
                    name, NotificationManager.IMPORTANCE_DEFAULT);

            channel.setDescription(context.getString(R.string.channel_description_status));
            channel.enableLights(true);

            channel.setLightColor(Color.BLUE);
            channel.setSound(null, null);
            compatNotificationManager.createNotificationChannel(channel);
        }
    }

    @TargetApi(O)
    public void createOpenVpnNotificationChannel() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            return;
        }

        // Connection status change messages
        NotificationChannel channel = compatNotificationManager.getNotificationChannel(OpenVPNService.NOTIFICATION_CHANNEL_NEWSTATUS_ID);
        if (channel == null) {
            CharSequence name = context.getString(R.string.channel_name_status);
            channel = new NotificationChannel(OpenVPNService.NOTIFICATION_CHANNEL_NEWSTATUS_ID,
                    name, NotificationManager.IMPORTANCE_DEFAULT);

            channel.setDescription(context.getString(R.string.channel_description_status));
            channel.enableLights(true);

            channel.setSound(null, null);
            compatNotificationManager.createNotificationChannel(channel);
        }
    }

    private void buildVpnNotification(String title, String message, CharSequence bigMessage, String tickerText,
                                      ConnectionStatus status, String channelId, int priority,
                                      long when, PendingIntent contentIntent, NotificationCompat.Action notificationAction, VpnServiceCallback vpnServiceCallback) {
        NotificationCompat.Builder nCompatBuilder = new NotificationCompat.Builder(context, channelId);
        int icon = getIconByConnectionStatus(status);

        nCompatBuilder.setStyle(new NotificationCompat.BigTextStyle().
                setBigContentTitle(title).
                bigText(bigMessage));

        nCompatBuilder.addAction(notificationAction);
        nCompatBuilder.setContentTitle(title);
        nCompatBuilder.setCategory(NotificationCompat.CATEGORY_SERVICE);
        nCompatBuilder.setLocalOnly(true);
        nCompatBuilder.setContentText(message);
        nCompatBuilder.setOnlyAlertOnce(true);
        nCompatBuilder.setSmallIcon(icon);
        nCompatBuilder.setPriority(priority);
        nCompatBuilder.setOngoing(true);
        nCompatBuilder.setUsesChronometer(true);
        nCompatBuilder.setWhen(when);
        nCompatBuilder.setContentIntent(contentIntent);
        if (!isEmpty(tickerText)) {
            nCompatBuilder.setTicker(tickerText);
        }

        Notification notification = nCompatBuilder.build();
        int notificationId = channelId.hashCode();

        if (vpnServiceCallback != null) {
            vpnServiceCallback.onNotificationBuild(notificationId, notification);
        } else {
            compatNotificationManager.notify(notificationId, notification);

        }
    }

    private PendingIntent getMainActivityIntent() {
        Intent startActivity = new Intent(context, StartActivity.class);
        return PendingIntent.getActivity(context, 0, startActivity, getPendingIntentFlags());
    }

    private PendingIntent getStartOpenvpnIntent() {
        Intent startIntent = new Intent(context, EIP.class);
        startIntent.setAction(EIP_ACTION_START);
        return PendingIntent.getService(context, 0, startIntent, getPendingIntentFlags());
    }

    private PendingIntent getStopVoidVpnIntent() {
        Intent stopVoidVpnIntent = new Intent (context, VoidVpnService.class);
        stopVoidVpnIntent.setAction(EIP_ACTION_STOP_BLOCKING_VPN);
        return PendingIntent.getService(context, 0, stopVoidVpnIntent, getPendingIntentFlags());
    }

    private PendingIntent getDisconnectIntent() {
        Intent disconnectVPN = new Intent(context, MainActivity.class);
        disconnectVPN.setAction(ACTION_SHOW_VPN_FRAGMENT);
        disconnectVPN.putExtra(ASK_TO_CANCEL_VPN, true);
        disconnectVPN.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        return PendingIntent.getActivity(context, 0, disconnectVPN, getPendingIntentFlags());
    }

    private PendingIntent getUserInputIntent(String needed) {
        Intent intent = new Intent(context, LaunchVPN.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        intent.putExtra("need", needed);
        Bundle b = new Bundle();
        b.putString("need", needed);
        PendingIntent pIntent = PendingIntent.getActivity(context, 12, intent, getPendingIntentFlags());
        return pIntent;
    }

    private int getIconByConnectionStatus(ConnectionStatus level) {
        switch (level) {
            case LEVEL_CONNECTED:
                return R.drawable.ic_stat_vpn;
            case LEVEL_AUTH_FAILED:
            case LEVEL_NONETWORK:
            case LEVEL_NOTCONNECTED:
                return R.drawable.ic_stat_vpn_offline;
            case LEVEL_CONNECTING_NO_SERVER_REPLY_YET:
            case LEVEL_WAITING_FOR_USER_INPUT:
            case LEVEL_CONNECTING_SERVER_REPLIED:
                return R.drawable.ic_stat_vpn_outline;
            case LEVEL_BLOCKING:
                return R.drawable.ic_stat_vpn_blocking;
            case UNKNOWN_LEVEL:
            default:
                return R.drawable.ic_stat_vpn_offline;
        }
    }

}