导航菜单

页面标题

页面副标题

Namma Yatri v3.3.7 - ChatService.java 源代码

正在查看: Namma Yatri v3.3.7 应用的 ChatService.java JAVA 源代码文件

本页面展示 JAVA 反编译生成的源代码文件,支持语法高亮显示。 仅供安全研究与技术分析使用,严禁用于任何非法用途。请遵守相关法律法规。


package in.juspay.mobility.app;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import androidx.core.app.m;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.crashlytics.FirebaseCrashlytics;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.j;
import com.google.firebase.firestore.p0;
import in.juspay.hypersdk.core.PaymentConstants;
import in.juspay.mobility.app.MessageOverlayService;
import in.juspay.mobility.app.MobilityAppBridge;
import in.juspay.mobility.app.callbacks.CallBack;
import in.juspay.mobility.app.callbacks.ShowNotificationCallBack;
import in.juspay.mobility.common.services.TLSSocketFactory;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.TimeZone;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONObject;

public class ChatService extends Service {
    private static final String LOG_TAG = "mobility_ChatService";
    public static String chatChannelID;
    public static String chatUserId;
    private String baseUrl;
    private com.google.firebase.firestore.Z chatListener;
    private Context context;
    public FirebaseAuth firebaseAuth;
    public FirebaseFirestore firestoreInstance;
    MobilityAppBridge.SendMessageCallBack sendMessageCallBack;
    MessageOverlayService.SendMessageCallBack sendMessageCallBackOverlay;
    private SharedPreferences sharedPrefs;
    private static final ArrayList<CallBack> callBack = new ArrayList<>();
    private static final ArrayList<ShowNotificationCallBack> inAppCallBacks = new ArrayList<>();
    private static boolean isChatServiceRunning = false;
    static Random random = new Random();
    final int serviceNotificationID = 19012023;
    public boolean sessionCreated = false;
    public boolean shouldNotify = true;
    private final ArrayList<Message> messages = new ArrayList<>();
    private String merchant = null;
    String merchantType = "";

    public static class AnonymousClass1 {
        static final int[] $SwitchMap$com$google$firebase$firestore$DocumentChange$Type;

        static {
            int[] iArr = new int[j.b.values().length];
            $SwitchMap$com$google$firebase$firestore$DocumentChange$Type = iArr;
            try {
                iArr[j.b.a.ordinal()] = 1;
            } catch (NoSuchFieldError unused) {
            }
            try {
                $SwitchMap$com$google$firebase$firestore$DocumentChange$Type[j.b.b.ordinal()] = 2;
            } catch (NoSuchFieldError unused2) {
            }
            try {
                $SwitchMap$com$google$firebase$firestore$DocumentChange$Type[j.b.c.ordinal()] = 3;
            } catch (NoSuchFieldError unused3) {
            }
        }
    }

    public static class Message {
        String message;
        String sentBy;
        String timestamp;

        public Message(String str, String str2, String str3) {
            this.message = str;
            this.sentBy = str2;
            this.timestamp = str3;
        }
    }

    private void addChatListener() {
        if (this.chatListener != null) {
            return;
        }
        try {
            if (N8.g.n(this.context).size() == 0) {
                N8.g.u(this.context);
            }
        } catch (Exception e) {
            android.util.Log.e(LOG_TAG, "Exception in Firebase Initialization" + e);
        }
        try {
            FirebaseFirestore firebaseFirestore = this.firestoreInstance;
            if (firebaseFirestore == null || chatChannelID == null) {
                return;
            }
            this.chatListener = firebaseFirestore.o("Chats").f0(chatChannelID).n("messages").G(PaymentConstants.TIMESTAMP, p0.c.a).g(new com.google.firebase.firestore.w() {
                public final void a(Object obj, com.google.firebase.firestore.P p) {
                    ChatService.this.lambda$addChatListener$2((com.google.firebase.firestore.r0) obj, p);
                }
            });
        } catch (Exception e2) {
            android.util.Log.e(LOG_TAG, "Error in listening to messages " + e2);
        }
    }

    private Message createMessageObj(Map<String, Object> map) {
        return new Message((String) map.get("message"), (String) map.get("sentBy"), getChatDate((Long) map.get(PaymentConstants.TIMESTAMP)));
    }

    private Notification createNotification() {
        createNotificationChannel();
        return new m.e(this, "Message").l(getString(R.string.chatting_is_enabled)).u(-2).t(true).j(PendingIntent.getActivity(this, 10, getPackageManager().getLaunchIntentForPackage(getPackageName()), 67108864)).b();
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= 26) {
            NotificationChannel a = k3.k.a("Message", "Chat Message Service", 1);
            k3.w.a(a, "Service Notification Channel");
            k3.x.a(a, "3_services");
            k3.o.a((NotificationManager) getSystemService(NotificationManager.class), a);
        }
    }

    public static void deRegisterCallback(CallBack callBack2) {
        callBack.remove(callBack2);
    }

    public static void deRegisterInAppCallback(ShowNotificationCallBack showNotificationCallBack) {
        inAppCallBacks.remove(showNotificationCallBack);
    }

    private String getChatDate(Long l) {
        Date date;
        try {
            date = new Date(l.longValue());
        } catch (Exception unused) {
            date = new Date(System.currentTimeMillis());
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss'Z'", Locale.ENGLISH);
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        return simpleDateFormat.format(date);
    }

    private String getCustomerApp(String str) {
        str.hashCode();
        switch (str) {
            case "Yatri Driver":
                return "Yatri";
            case "Namma Yatri Partner":
                return "Namma Yatri";
            case "Yatri Sathi Driver":
                return "Yatri Sathi";
            default:
                return "";
        }
    }

    private String getMessageFromKey(String str, String str2) {
        try {
            JSONObject jSONObject = new JSONObject(this.sharedPrefs.getString("SUGGESTIONS_DEFINITIONS", "null"));
            if (str2 == null) {
                str2 = this.sharedPrefs.getString("LANGUAGE_KEY", "null");
            }
            if (!jSONObject.has(str)) {
                return str;
            }
            JSONObject jSONObject2 = jSONObject.getJSONObject(str);
            return jSONObject2.has(str2.toLowerCase()) ? jSONObject2.getString(str2.toLowerCase()) : jSONObject2.getString("en_us");
        } catch (Exception e) {
            android.util.Log.e(LOG_TAG, "Error in getMessageFromKey : " + e);
            return "";
        }
    }

    private void handleMessage(Message message, String str) {
        try {
            String str2 = message.timestamp;
            String str3 = message.message;
            String str4 = message.sentBy;
            SharedPreferences sharedPreferences = this.sharedPrefs;
            String string = sharedPreferences != null ? sharedPreferences.getString("ACTIVITY_STATUS", "null") : "";
            SharedPreferences sharedPreferences2 = this.sharedPrefs;
            String string2 = sharedPreferences2 != null ? sharedPreferences2.getString("LOCAL_STAGE", "null") : "HomeScreen";
            String string3 = getApplicationContext().getResources().getString(R.string.app_name);
            String str5 = str4.equals("Driver") ? string3.equals("Yatri Driver") ? "yatriprovider" : string3.equals("Yatri Sathi Driver") ? "yatrisathiprovider" : "nammayatriprovider" : string3.equals("Yatri") ? "yatriconsumer" : string3.equals("Yatri Sathi") ? "yatrisathiconsumer" : "nammayatri";
            if (string.equals("onPause") || string.equals("onResume")) {
                int i = 0;
                while (true) {
                    try {
                        ArrayList<CallBack> arrayList = callBack;
                        if (i >= arrayList.size()) {
                            break;
                        }
                        arrayList.get(i).chatCallBack(str3, str4, str2, str);
                        i++;
                    } catch (Exception e) {
                        android.util.Log.e(LOG_TAG, "Error sending the message to jbridge : " + e);
                    }
                }
            }
            String messageFromKey = getMessageFromKey(str3, null);
            if (!this.merchant.equals(str5) && isChatServiceRunning && this.shouldNotify && !messageFromKey.equals("") && this.merchantType.equals("DRIVER")) {
                if (!string.equals("onDestroy") && !string.equals("onPause")) {
                    if (string.equals("onResume") && this.merchantType.equals("DRIVER") && !string2.equals("ChatWithCustomer")) {
                        String valueOf = String.valueOf(random.nextInt(1000000));
                        Iterator<ShowNotificationCallBack> it = inAppCallBacks.iterator();
                        while (it.hasNext()) {
                            it.next().showInAppNotification(Utils.createNotificationPayload("From " + getCustomerApp(string3) + " " + str4, messageFromKey, MobilityAppBridge.storeCallBackOpenChatScreen, "", "", "", "", valueOf, 5000), this.context);
                        }
                        return;
                    }
                    return;
                }
                if (NotificationUtils.overlayFeatureNotAvailable(this.context)) {
                    NotificationUtils.createChatNotification(str4, messageFromKey, this.context);
                } else {
                    startOverlayService(messageFromKey, str2);
                }
            }
        } catch (Exception e2) {
            android.util.Log.e(LOG_TAG, "Error in handleMessage : " + e2);
        }
    }

    private void handleMessages() {
        this.shouldNotify = false;
        isChatServiceRunning = false;
        int size = this.messages.size();
        Iterator<Message> it = this.messages.iterator();
        int i = 1;
        while (it.hasNext()) {
            Message next = it.next();
            if (i == size && !isChatServiceRunning) {
                isChatServiceRunning = true;
            }
            i++;
            handleMessage(next, String.valueOf(size - 1));
        }
    }

    private void isSessionCreated() {
        try {
            this.firestoreInstance.o("Chats").f0(chatChannelID).q().addOnCompleteListener(new OnCompleteListener() {
                public final void onComplete(Task task) {
                    ChatService.this.lambda$isSessionCreated$0(task);
                }
            });
        } catch (Exception e) {
            android.util.Log.e(LOG_TAG, "Error in isSessionCreated :: " + e);
        }
    }

    public void lambda$addChatListener$2(com.google.firebase.firestore.r0 r0Var, com.google.firebase.firestore.P p) {
        if (p != null) {
            android.util.Log.e(LOG_TAG, "listen:error", p);
            return;
        }
        if (r0Var == null) {
            return;
        }
        int i = 1;
        for (com.google.firebase.firestore.j jVar : r0Var.e()) {
            if (AnonymousClass1.$SwitchMap$com$google$firebase$firestore$DocumentChange$Type[jVar.e().ordinal()] == 1) {
                Message createMessageObj = createMessageObj(jVar.b().d());
                this.messages.add(createMessageObj);
                this.shouldNotify = true;
                if (i == r0Var.e().size() && !isChatServiceRunning) {
                    isChatServiceRunning = true;
                    if (i == r0Var.e().size() && i != 1) {
                        this.shouldNotify = false;
                    }
                }
                i++;
                handleMessage(createMessageObj, String.valueOf(r0Var.size() - 1));
            }
        }
    }

    public void lambda$isSessionCreated$0(Task task) {
        if (task.isSuccessful() && ((com.google.firebase.firestore.v) task.getResult()).a()) {
            this.sessionCreated = true;
        }
    }

    public void lambda$sendMessages$3(Task task) {
        if (task.isSuccessful()) {
            this.sessionCreated = true;
        }
    }

    public void lambda$signInAnonymously$1(Task task) {
        if (task.isSuccessful()) {
            startChatService();
        } else {
            android.util.Log.w(LOG_TAG, "signInAnonymously:failure", task.getException());
        }
    }

    public static void registerCallback(CallBack callBack2) {
        callBack.add(callBack2);
    }

    public static void registerInAppCallback(ShowNotificationCallBack showNotificationCallBack) {
        inAppCallBacks.add(showNotificationCallBack);
    }

    private void sendFCM(String str) {
        try {
            String str2 = this.baseUrl + "/onMessage";
            StringBuilder sb2 = new StringBuilder();
            String string = this.sharedPrefs.getString("REGISTERATION_TOKEN", "null");
            String string2 = this.sharedPrefs.getString("BUNDLE_VERSION", "null");
            String string3 = this.sharedPrefs.getString("VERSION_NAME", "null");
            String string4 = this.sharedPrefs.getString("SESSION_ID", "null");
            HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(str2).openConnection();
            if (httpURLConnection instanceof HttpsURLConnection) {
                ((HttpsURLConnection) httpURLConnection).setSSLSocketFactory(new TLSSocketFactory());
            }
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("x-client-version", string3);
            httpURLConnection.setRequestProperty("token", string);
            httpURLConnection.setRequestProperty("x-bundle-version", string2);
            httpURLConnection.setRequestProperty("session_id", string4);
            httpURLConnection.setConnectTimeout(20000);
            httpURLConnection.setReadTimeout(20000);
            httpURLConnection.setDoOutput(true);
            JSONObject jSONObject = new JSONObject();
            jSONObject.put("message", str);
            jSONObject.put("rideId", chatChannelID);
            httpURLConnection.getOutputStream().write(jSONObject.toString().getBytes());
            httpURLConnection.connect();
            int responseCode = httpURLConnection.getResponseCode();
            if ((responseCode >= 200 && responseCode < 300) || responseCode == 302) {
                return;
            }
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream()));
            while (true) {
                String readLine = bufferedReader.readLine();
                if (readLine == null) {
                    android.util.Log.e(LOG_TAG, "Error in calling send FCM API" + ((Object) sb2));
                    return;
                }
                sb2.append(readLine);
            }
        } catch (Exception e) {
            android.util.Log.e(LOG_TAG, "Error in sending FCM" + e);
        }
    }

    private void signInAnonymously() {
        try {
            this.firebaseAuth.C().addOnCompleteListener(new OnCompleteListener() {
                public final void onComplete(Task task) {
                    ChatService.this.lambda$signInAnonymously$1(task);
                }
            });
        } catch (Exception e) {
            android.util.Log.e(LOG_TAG, "Error in signInAnonymously" + e);
        }
    }

    private void startChatService() {
        addChatListener();
    }

    private void startOverlayService(String str, String str2) {
        if (this.merchantType.equals("DRIVER") && Settings.canDrawOverlays(getApplicationContext()) && !this.sharedPrefs.getString(getResources().getString(R.string.REGISTERATION_TOKEN), "null").equals("null")) {
            if (this.sharedPrefs.getString(getResources().getString(R.string.ACTIVITY_STATUS), "null").equals("onPause") || this.sharedPrefs.getString(getResources().getString(R.string.ACTIVITY_STATUS), "null").equals("onDestroy")) {
                try {
                    Locale locale = Locale.ENGLISH;
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", locale);
                    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                    SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("h:mm a", locale);
                    simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
                    Date parse = simpleDateFormat.parse(str2);
                    if (parse != null) {
                        str2 = simpleDateFormat2.format(parse);
                    }
                    Intent intent = new Intent(this.context, (Class<?>) MessageOverlayService.class);
                    intent.putExtra("message", str);
                    intent.putExtra(PaymentConstants.TIMESTAMP, str2);
                    this.context.startService(intent);
                    NotificationUtils.startMediaPlayer(this.context, R.raw.new_message, false);
                } catch (Exception e) {
                    android.util.Log.e(LOG_TAG, "Error in startOverlayService : " + e);
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        this.context = getApplicationContext();
        this.firestoreInstance = FirebaseFirestore.w();
        this.firebaseAuth = FirebaseAuth.getInstance();
        String string = getApplicationContext().getResources().getString(R.string.service);
        this.merchant = string;
        this.merchantType = (string.contains("partner") || this.merchant.contains("driver") || this.merchant.contains("provider")) ? "DRIVER" : "USER";
        this.sharedPrefs = this.context.getSharedPreferences(getString(R.string.preference_file_key), 0);
        try {
            if (Build.VERSION.SDK_INT >= 29) {
                startForeground(19012023, createNotification(), 1);
            } else {
                startForeground(19012023, createNotification());
            }
        } catch (Exception e) {
            FirebaseCrashlytics.getInstance().recordException(new Exception("Error in onCreate startForeground " + e));
            android.util.Log.e(LOG_TAG, "Error in onCreate ", e);
        }
        SharedPreferences sharedPreferences = this.sharedPrefs;
        if (sharedPreferences != null) {
            chatChannelID = sharedPreferences.getString("CHAT_CHANNEL_ID", "");
            this.baseUrl = this.sharedPrefs.getString("BASE_URL", "null");
        }
        isSessionCreated();
        MobilityAppBridge.SendMessageCallBack sendMessageCallBack = new MobilityAppBridge.SendMessageCallBack() {
            @Override
            public final void sendMessage(String str) {
                ChatService.this.sendMessages(str);
            }
        };
        this.sendMessageCallBack = sendMessageCallBack;
        MobilityAppBridge.registerSendMessageCallBack(sendMessageCallBack);
        MessageOverlayService.SendMessageCallBack sendMessageCallBack2 = new MessageOverlayService.SendMessageCallBack() {
            @Override
            public final void sendMessage(String str) {
                ChatService.this.sendMessages(str);
            }
        };
        this.sendMessageCallBackOverlay = sendMessageCallBack2;
        MessageOverlayService.registerSendMessageCallBack(sendMessageCallBack2);
        if (isChatServiceRunning) {
            return;
        }
        try {
            if (Build.VERSION.SDK_INT >= 29) {
                startForeground(19012023, createNotification(), 1);
            } else {
                startForeground(19012023, createNotification());
            }
        } catch (Exception e2) {
            FirebaseCrashlytics.getInstance().recordException(new Exception("Error in !isChatServiceRunning " + e2));
            android.util.Log.e(LOG_TAG, "Error in onCreate -> ", e2);
        }
        if (this.firebaseAuth.m() != null) {
            startChatService();
        } else {
            signInAnonymously();
        }
    }

    @Override
    public void onDestroy() {
        isChatServiceRunning = false;
        this.shouldNotify = true;
        this.sessionCreated = false;
        MobilityAppBridge.deRegisterSendMessageCallBack(this.sendMessageCallBack);
        MessageOverlayService.deRegisterSendMessageCallBack(this.sendMessageCallBackOverlay);
        stopForeground(true);
        com.google.firebase.firestore.Z z = this.chatListener;
        if (z != null) {
            z.remove();
        }
        this.messages.clear();
        stopSelf();
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int i, int i2) {
        try {
            if (Build.VERSION.SDK_INT >= 29) {
                startForeground(19012023, createNotification(), 1);
            } else {
                startForeground(19012023, createNotification());
            }
        } catch (Exception e) {
            FirebaseCrashlytics.getInstance().recordException(new Exception("Error in onStartCommand " + e));
            android.util.Log.e(LOG_TAG, "Error in onStartCommand ", e);
        }
        handleMessages();
        return 1;
    }

    public void sendMessages(String str) {
        HashMap hashMap = new HashMap();
        hashMap.put("message", str);
        hashMap.put("sentBy", chatUserId);
        hashMap.put(PaymentConstants.TIMESTAMP, Long.valueOf(System.currentTimeMillis()));
        SharedPreferences sharedPreferences = this.sharedPrefs;
        if (sharedPreferences != null) {
            chatChannelID = sharedPreferences.getString("CHAT_CHANNEL_ID", null);
        }
        if (chatChannelID != null) {
            try {
                if (!this.sessionCreated) {
                    HashMap hashMap2 = new HashMap();
                    hashMap2.put(PaymentConstants.TIMESTAMP, Long.valueOf(System.currentTimeMillis()));
                    this.firestoreInstance.o("Chats").f0(chatChannelID).H(hashMap2).addOnCompleteListener(new OnCompleteListener() {
                        public final void onComplete(Task task) {
                            ChatService.this.lambda$sendMessages$3(task);
                        }
                    });
                }
                this.firestoreInstance.o("Chats").f0(chatChannelID).n("messages").d0(hashMap);
                if (this.merchantType.equals("DRIVER")) {
                    String messageFromKey = getMessageFromKey(str, "EN_US");
                    if (messageFromKey.equals("")) {
                        return;
                    }
                    sendFCM(messageFromKey);
                }
            } catch (Exception e) {
                android.util.Log.e(LOG_TAG, "Error in sending a message" + e);
            }
        }
    }
}