Browse Source

firebase messaging implemented, and Validation API..

Khubaib 1 year ago
parent
commit
894fd41001

+ 3 - 0
app/build.gradle.kts

@@ -99,6 +99,9 @@ dependencies {
     implementation("io.coil-kt:coil-compose:1.3.1")
     implementation("com.google.accompanist:accompanist-drawablepainter:0.34.0")
     implementation("com.google.firebase:firebase-crashlytics:18.6.2")
+    implementation("com.google.firebase:firebase-messaging:23.4.1")
+//    implementation("com.firebase:firebase-jobdispatcher:0.8.5")
+
 
     testImplementation("junit:junit:4.13.2")
     androidTestImplementation("androidx.test.ext:junit:1.1.5")

+ 9 - 0
app/src/main/AndroidManifest.xml

@@ -39,6 +39,15 @@
             </intent-filter>
         </service>
 
+        <service
+            android:name=".fcm.PetsFirebaseMessagingService"
+            android:enabled="true"
+            android:exported="true">
+            <intent-filter>
+                <action android:name="com.google.firebase.MESSAGING_EVENT" />
+            </intent-filter>
+        </service>
+
     </application>
 
 </manifest>

+ 5 - 0
app/src/main/java/com/vpn/fastestvpnservice/application/App.java

@@ -6,6 +6,8 @@ import com.wireguard.android.backend.Backend;
 import com.wireguard.android.backend.Tunnel;
 import com.wireguard.config.Peer;
 
+import java.util.Random;
+
 import wireguard.WgTunnel;
 
 public class App extends Application {
@@ -17,6 +19,9 @@ public class App extends Application {
     public static Peer.Builder peerBuilder = new Peer.Builder();
     public static Backend backend;
 
+    public static final int NOTIFICATION_ID = new Random().nextInt(601) + 200;
+
+
     public static void setBackend(Backend backend1) {
         backend = backend1;
     }

+ 201 - 0
app/src/main/java/com/vpn/fastestvpnservice/fcm/PetsFirebaseMessagingService.java

@@ -0,0 +1,201 @@
+package com.vpn.fastestvpnservice.fcm;
+
+import android.app.NotificationChannel;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.Intent;
+import android.media.RingtoneManager;
+import android.net.Uri;
+import android.os.Build;
+import android.util.Log;
+
+import androidx.core.app.NotificationCompat;
+import com.google.firebase.messaging.FirebaseMessagingService;
+import com.google.firebase.messaging.RemoteMessage;
+import com.vpn.fastestvpnservice.MainActivity;
+import com.vpn.fastestvpnservice.R;
+import com.vpn.fastestvpnservice.application.App;
+import com.vpn.fastestvpnservice.helpers.BasePreferenceHelper;
+
+import kotlinx.coroutines.Job;
+
+
+/**
+ * Created by
+ * Mykhailo on 11/16/2016.
+ */
+
+public class PetsFirebaseMessagingService extends FirebaseMessagingService {
+
+    private static final String TAG = "MyFirebaseMsgService";
+    BasePreferenceHelper prefHelper;
+
+
+    /**
+     * Called when message is received.
+     *
+     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
+     */
+    // [START receive_message]
+    @Override
+    public void onMessageReceived(RemoteMessage remoteMessage) {
+        // [START_EXCLUDE]
+        // There are two types of messages data messages and notification messages. Data messages
+        // are handled
+        // here in onMessageReceived whether the app is in the foreground or background. Data
+        // messages are the type
+        // traditionally used with GCM. Notification messages are only received here in
+        // onMessageReceived when the app
+        // is in the foreground. When the app is in the background an automatically generated
+        // notification is displayed.
+        // When the user taps on the notification they are returned to the app. Messages
+        // containing both notification
+        // and data payloads are treated as notification messages. The Firebase console always
+        // sends notification
+        // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
+        // [END_EXCLUDE]
+
+        // TODO(developer): Handle FCM messages here.
+        // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
+        Log.d(TAG, "From: " + remoteMessage.getFrom());
+
+        // Check if message contains a data payload.
+        if (remoteMessage.getData().size() > 0) {
+            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
+            sendNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("body"));
+
+            if (/* Check if data needs to be processed by long running job */ false) { // by default true, using false to prevent crash on Android 13
+                // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
+                scheduleJob();
+            } else {
+                // Handle message within 10 seconds
+                handleNow();
+            }
+
+        }
+
+        // Check if message contains a notification payload.
+        if (remoteMessage.getNotification() != null) {
+            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
+            sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
+        }
+
+        // Also if you intend on generating your own notifications as a result of a received FCM
+        // message, here is where that should be initiated. See sendNotification method below.
+    }
+    // [END receive_message]
+
+
+    // [START on_new_token]
+
+    /**
+     * Called if InstanceID token is updated. This may occur if the security of
+     * the previous token had been compromised. Note that this is called when the InstanceID token
+     * is initially generated so this is where you would retrieve the token.
+     */
+    @Override
+    public void onNewToken(String token) {
+        Log.d(TAG, "Refreshed token: " + token);
+
+        prefHelper = new BasePreferenceHelper(App.getApplication());
+        prefHelper.saveFcmToken(token);
+
+
+        // If you want to send messages to this application instance or
+        // manage this apps subscriptions on the server side, send the
+        // Instance ID token to your app server.
+        sendRegistrationToServer(token);
+    }
+    // [END on_new_token]
+
+    /**
+     * Schedule a job using FirebaseJobDispatcher.
+     */
+    private void scheduleJob() {
+        // [START dispatch_job]
+//        FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
+//        Job myJob = dispatcher.newJobBuilder()
+//                .setService(MyJobService.class)
+//                .setTag("my-job-tag")
+//                .build();
+//        dispatcher.schedule(myJob);
+        // [END dispatch_job]
+    }
+
+    /**
+     * Handle time allotted to BroadcastReceivers.
+     */
+    private void handleNow() {
+        Log.d(TAG, "Short lived task is done.");
+    }
+
+    /**
+     * Persist token to third-party servers.
+     * <p>
+     * Modify this method to associate the user's FCM InstanceID token with any server-side account
+     * maintained by your application.
+     *
+     * @param token The new token.
+     */
+    private void sendRegistrationToServer(String token) {
+        // TODO: Implement this method to send token to your app server.
+    }
+
+    /**
+     * Create and show a simple notification containing the received FCM message.
+     *
+     * @param title
+     * @param messageBody FCM message body received.
+     */
+    private void sendNotification(String title, String messageBody) {
+        Intent intent = new Intent(this, MainActivity.class);
+        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
+//        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
+//                PendingIntent.FLAG_ONE_SHOT);
+//        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
+//                PendingIntent.FLAG_IMMUTABLE);
+        PendingIntent pendingIntent = null;
+
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+            pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
+                    PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
+        }
+//        else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+//            pendingIntent = PendingIntent.getForegroundService(this, 0, intent,
+//                    PendingIntent.FLAG_IMMUTABLE);
+//        }
+        else{
+            pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
+                    PendingIntent.FLAG_IMMUTABLE);
+        }
+
+        String channelId = getString(R.string.default_notification_channel_id);
+        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
+
+        NotificationCompat.Builder notificationBuilder =
+                new NotificationCompat.Builder(this, channelId)
+//                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_logo))
+                        .setSmallIcon(R.drawable.ic_logo_notify)
+                        .setColor(getResources().getColor(R.color.app_yellow_color))
+//                        .setContentTitle("New Message")
+                        .setContentTitle(title + "")
+                        .setContentText(messageBody)
+                        .setAutoCancel(true)
+                        .setSound(defaultSoundUri)
+                        .setContentIntent(pendingIntent);
+
+        NotificationManager notificationManager =
+                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
+
+        // Since android Oreo notification channel is needed.
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+            NotificationChannel channel = new NotificationChannel(channelId,
+                    "Channel human readable title",
+                    NotificationManager.IMPORTANCE_DEFAULT);
+            notificationManager.createNotificationChannel(channel);
+        }
+
+        notificationManager.notify(App.NOTIFICATION_ID /* ID of notification */, notificationBuilder.build());
+    }
+}

+ 2 - 1
app/src/main/java/com/vpn/fastestvpnservice/retrofit/Api.kt

@@ -62,9 +62,10 @@ interface Api {
     fun getProducts(): Call<Any>
 
     @FormUrlEncoded
-    @POST("create-subscription?test=313912")
+    @POST("create-subscription")
     fun createSubscription(
         @Field("transaction_id") transaction_id: String?, @Field("receipt_data") receipt_data: String?,
         @Field("productId") productId: String?
     ): Call<Any>
+
 }

+ 4 - 4
app/src/main/java/com/vpn/fastestvpnservice/screens/LoginScreen.kt

@@ -550,10 +550,10 @@ fun BoxScope.SignInButton(
 
 //                    upgradePriceViewModel.getProducts()
 
-//                    prefHelper.getFcmToken().let {
-//                        loginViewModel.sendFcmToken(it)
-//                        Log.d("fcm token get", prefHelper.getFcmToken())
-//                    }
+                    prefHelper.getFcmToken().let {
+                        loginViewModel.sendFcmToken(it)
+                        Log.d("Refreshed token: ", "Login: $it")
+                    }
 
                     prefHelper.saveRadioBtnSplitPos(0)
 

+ 4 - 4
app/src/main/java/com/vpn/fastestvpnservice/screens/SignUpScreen.kt

@@ -584,10 +584,10 @@ fun BoxScope.SignUpButton(
 
 //                    upgradePriceViewModel.getProducts()
 
-//                    prefHelper.getFcmToken().let {
-//                        loginViewModel.sendFcmToken(it)
-//                        Log.d("fcm token get", prefHelper.getFcmToken())
-//                    }
+                    prefHelper.getFcmToken().let {
+                        loginViewModel.sendFcmToken(it)
+                        Log.d("Refreshed token: ","SignUp: $it")
+                    }
 
                     prefHelper.saveRadioBtnSplitPos(0)
                 }

+ 16 - 0
app/src/main/java/com/vpn/fastestvpnservice/screens/bottomNavBarScreens/HomeScreen.kt

@@ -48,6 +48,7 @@ import androidx.compose.material3.Text
 import androidx.compose.runtime.Composable
 import androidx.compose.runtime.CompositionLocalProvider
 import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.LaunchedEffect
 import androidx.compose.runtime.remember
 import androidx.compose.ui.Alignment
 import androidx.compose.ui.Modifier
@@ -190,6 +191,21 @@ fun Home(navHostController: NavHostController, activity: ComponentActivity) {
         Log.d("test_api_response", "ip home = ${it.country}")
     }
 
+    val validateResponse = homeViewModel._mutableLiveDataValidate.observeAsState().value
+    validateResponse?.let {
+        Log.d("test_api_validate", it.message.toString())
+        homeViewModel._mutableLiveDataValidate.value = null
+    }
+
+    LaunchedEffect(key1 = Unit){
+        homeViewModel.validatePassword(
+            prefHelper.getUser()?.userinfo?.email.toString(),
+            prefHelper.getPassword().toString(),
+            "android",
+            android.os.Build.VERSION.RELEASE
+        )
+    }
+
     Box(
         modifier = Modifier
             .background(MaterialTheme.colorScheme.background)

+ 1 - 0
app/src/main/java/com/vpn/fastestvpnservice/viewmodels/HomeViewModel.kt

@@ -100,6 +100,7 @@ class HomeViewModel constructor(context: Context, scope: CoroutineScope): ViewMo
                         val type = object : TypeToken<DataResponse<TokenResponse?>?>() {}.type
                         val data = gson.fromJson<DataResponse<TokenResponse>>(jsonString, type)
                         _mutableLiveDataValidate.value = data
+                        Log.d("test_api_validate", "data = ${data.message}")
 
                     } catch (ex: Exception) {
                         Log.d("test_api_response", "validatePassword onSuccess: catch")

+ 3 - 0
app/src/main/java/com/vpn/fastestvpnservice/viewmodels/LoginViewModel.kt

@@ -91,6 +91,9 @@ class LoginViewModel: ViewModel() {
                             val type = object : TypeToken<DataResponse<Objects>>() {}.type
                             val data = gson.fromJson<DataResponse<Objects>>(jsonString, type)
                             mutableLiveDataFcm.value = data
+
+                            Log.d("Refreshed token: ","sendFcmToken Response: ${data.message}")
+
                         } catch (ex: Exception) {
                         }
                     }

+ 2 - 0
app/src/main/res/values/strings.xml

@@ -3,4 +3,6 @@
     <string name="chk_internet_connectivity">Please check your internet connection</string>
     <!-- TODO: Remove or change this placeholder text -->
     <string name="hello_blank_fragment">Hello blank fragment</string>
+    <string name="default_notification_channel_id" translatable="false">fcm_default_channel</string>
+
 </resources>