导航菜单

页面标题

页面副标题

Housing v14.7.8 - WebRTCCallService.java 源代码

正在查看: Housing v14.7.8 应用的 WebRTCCallService.java JAVA 源代码文件

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


package com.quickblox.reactnative.webrtc;

import android.app.ActivityManager;
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.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.camera.camera2.internal.t2;
import androidx.compose.foundation.text.selection.v0;
import androidx.core.app.q;
import androidx.core.app.s;
import coil.disk.c;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.newrelic.agent.android.instrumentation.BitmapFactoryInstrumentation;
import com.newrelic.agent.android.instrumentation.Instrumented;
import com.newrelic.agent.android.instrumentation.LogInstrumentation;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.QBSignaling;
import com.quickblox.chat.listeners.QBVideoChatSignalingManagerListener;
import com.quickblox.core.QBEntityCallback;
import com.quickblox.core.exception.QBResponseException;
import com.quickblox.customobjects.helper.QBRecordParameterQueryDecorator;
import com.quickblox.reactnative.R;
import com.quickblox.reactnative.helpers.EventsHelper;
import com.quickblox.reactnative.webrtc.QBAudioManager;
import com.quickblox.reactnative.webrtc.WebRTCConstants;
import com.quickblox.users.QBUsers;
import com.quickblox.users.model.QBUser;
import com.quickblox.videochat.webrtc.BaseSession;
import com.quickblox.videochat.webrtc.QBRTCCameraVideoCapturer;
import com.quickblox.videochat.webrtc.QBRTCClient;
import com.quickblox.videochat.webrtc.QBRTCConfig;
import com.quickblox.videochat.webrtc.QBRTCMediaConfig;
import com.quickblox.videochat.webrtc.QBRTCScreenCapturer;
import com.quickblox.videochat.webrtc.QBRTCSession;
import com.quickblox.videochat.webrtc.QBRTCTypes;
import com.quickblox.videochat.webrtc.callbacks.QBRTCClientSessionCallbacks;
import com.quickblox.videochat.webrtc.callbacks.QBRTCClientVideoTracksCallbacks;
import com.quickblox.videochat.webrtc.callbacks.QBRTCSessionConnectionCallbacks;
import com.quickblox.videochat.webrtc.view.QBRTCVideoTrack;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CopyOnWriteArraySet;
import m3.f;
import org.webrtc.v;

@Instrumented
public class WebRTCCallService extends Service {
    private static final String CHANNEL_ID = "Quickblox channel";
    private static final String CHANNEL_NAME = "Quickblox foreground service";
    private static final int MAX_OPPONENTS_COUNT = 6;
    private static final int SERVICE_ID = 787;
    private static final String TAG = "WebRTCCallService";
    private QBAudioManager appRTCAudioManager;
    private Context context;
    private QBRTCClient qbrtcClient;
    private QBRTCClientSessionCallbacks qbrtcClientEventListener;
    private ReactApplicationContext reactApplicationContext;
    private SessionConnectionListener sessionConnectionListener;
    private VideoTrackListener videoTrackListener;
    private final CallServiceBinder callServiceBinder = new CallServiceBinder();
    private final Set<QBRTCSession> sessionCache = new CopyOnWriteArraySet();
    private CallTimerTask callTimerTask = new CallTimerTask();
    private Timer callTimer = new Timer();

    public class CallServiceBinder extends Binder {
        public CallServiceBinder() {
        }

        public WebRTCCallService getService() {
            return WebRTCCallService.this;
        }
    }

    public class CallTimerTask extends TimerTask {
        private Long callTime = 1000L;

        public CallTimerTask() {
        }

        private String getCallTime() {
            if (this.callTime == null) {
                return "";
            }
            String format = String.format(WebRTCCallService.this.reactApplicationContext.getString(R.string.call_time_format), 2);
            long longValue = this.callTime.longValue() / 1000;
            String format2 = String.format(format, Long.valueOf(longValue % 60));
            String format3 = String.format(format, Long.valueOf((longValue % 3600) / 60));
            String format4 = String.format(format, Long.valueOf(longValue / 3600));
            return (TextUtils.isEmpty(format4) || format4 == "00") ? t2.D(format3, ":", format2) : v0.q(format4, ":", format3, ":", format2);
        }

        @Override
        public void run() {
            this.callTime = Long.valueOf(this.callTime.longValue() + 1000);
            String callTime = getCallTime();
            WebRTCCallService.this.updateNotification(WebRTCCallService.this.getString(R.string.notification_title_call), WebRTCCallService.this.getString(R.string.notification_text_call, callTime));
        }
    }

    @Instrumented
    public class CameraEventsListener implements v.a {
        public CameraEventsListener(WebRTCCallService webRTCCallService, int i) {
            this();
        }

        @Override
        public void onCameraClosed() {
            LogInstrumentation.e(WebRTCCallService.TAG, "CameraEventsListener = onCameraClosed");
        }

        @Override
        public void onCameraDisconnected() {
            LogInstrumentation.e(WebRTCCallService.TAG, "CameraEventsListener = onCameraDisconnected");
        }

        @Override
        public void onCameraError(String str) {
            c.t("CameraEventsListener = onCameraError: ", str, WebRTCCallService.TAG);
        }

        @Override
        public void onCameraFreezed(String str) {
            c.t("CameraEventsListener = onCameraFreezed: ", str, WebRTCCallService.TAG);
        }

        @Override
        public void onCameraOpening(String str) {
            c.t("CameraEventsListener = onCameraOpening: ", str, WebRTCCallService.TAG);
        }

        @Override
        public void onFirstFrameAvailable() {
            LogInstrumentation.e(WebRTCCallService.TAG, "CameraEventsListener = onFirstFrameAvailable");
        }

        private CameraEventsListener() {
        }
    }

    @Instrumented
    public class QBRTCClientEventListener implements QBRTCClientSessionCallbacks {
        public QBRTCClientEventListener(WebRTCCallService webRTCCallService, int i) {
            this();
        }

        @Override
        public void onCallAcceptByUser(QBRTCSession qBRTCSession, Integer num, Map<String, String> map) {
            String str = WebRTCConstants.EventType.ACCEPT.eventType;
            WritableNativeMap writableNativeMap = new WritableNativeMap();
            WritableMap qBRTCSessionToMap = WebRTCMapper.qBRTCSessionToMap(qBRTCSession);
            WritableMap userInfoToMap = WebRTCMapper.userInfoToMap(map);
            writableNativeMap.putMap("session", qBRTCSessionToMap);
            writableNativeMap.putInt("userId", num.intValue());
            writableNativeMap.putMap("userInfo", userInfoToMap);
            WebRTCCallService.this.sendEvent(str, EventsHelper.buildResult(str, writableNativeMap));
            WebRTCCallService.this.startCallTimer();
        }

        @Override
        public void onCallRejectByUser(QBRTCSession qBRTCSession, Integer num, Map<String, String> map) {
            String str = WebRTCConstants.EventType.REJECT.eventType;
            WritableNativeMap writableNativeMap = new WritableNativeMap();
            WritableMap qBRTCSessionToMap = WebRTCMapper.qBRTCSessionToMap(qBRTCSession);
            WritableMap userInfoToMap = WebRTCMapper.userInfoToMap(map);
            writableNativeMap.putMap("session", qBRTCSessionToMap);
            writableNativeMap.putInt("userId", num.intValue());
            writableNativeMap.putMap("userInfo", userInfoToMap);
            WebRTCCallService.this.sendEvent(str, EventsHelper.buildResult(str, writableNativeMap));
        }

        @Override
        public void onChangeReconnectionState(QBRTCSession qBRTCSession, Integer num, QBRTCTypes.QBRTCReconnectionState qBRTCReconnectionState) {
            WritableNativeMap writableNativeMap = new WritableNativeMap();
            writableNativeMap.putMap("session", WebRTCMapper.qBRTCSessionToMap(qBRTCSession));
            writableNativeMap.putInt("state", ReconnectionMapper.parseQBRTCReconnectionState(qBRTCReconnectionState));
            writableNativeMap.putInt("userId", num.intValue());
            String str = WebRTCConstants.EventType.RECONNECTION_STATE_CHANGED.eventType;
            WebRTCCallService.this.sendEvent(str, EventsHelper.buildResult(str, writableNativeMap));
        }

        @Override
        public void onReceiveHangUpFromUser(QBRTCSession qBRTCSession, Integer num, Map<String, String> map) {
            WebRTCCallService.this.stopCallTimer();
            WebRTCCallService.this.updateNotification(WebRTCCallService.this.getString(R.string.call_service_notification_title), WebRTCCallService.this.getString(R.string.call_service_notification_text));
            String str = WebRTCConstants.EventType.HANG_UP.eventType;
            WritableNativeMap writableNativeMap = new WritableNativeMap();
            WritableMap qBRTCSessionToMap = WebRTCMapper.qBRTCSessionToMap(qBRTCSession);
            WritableMap userInfoToMap = WebRTCMapper.userInfoToMap(map);
            writableNativeMap.putMap("session", qBRTCSessionToMap);
            writableNativeMap.putInt("userId", num.intValue());
            writableNativeMap.putMap("userInfo", userInfoToMap);
            WebRTCCallService.this.sendEvent(str, EventsHelper.buildResult(str, writableNativeMap));
        }

        @Override
        public void onReceiveNewSession(QBRTCSession qBRTCSession) {
            final Integer callerID = qBRTCSession.getCallerID();
            QBUsers.getUser(callerID.intValue()).performAsync(new QBEntityCallback<QBUser>() {
                @Override
                public void onError(QBResponseException qBResponseException) {
                    WebRTCCallService.this.updateNotification(WebRTCCallService.this.getString(R.string.notification_title_incoming), WebRTCCallService.this.getString(R.string.notification_text_incoming, String.valueOf(callerID)));
                }

                @Override
                public void onSuccess(QBUser qBUser, Bundle bundle) {
                    WebRTCCallService.this.updateNotification(WebRTCCallService.this.getString(R.string.notification_title_incoming), WebRTCCallService.this.getString(R.string.notification_text_incoming, TextUtils.isEmpty(qBUser.getFullName()) ? qBUser.getLogin() : qBUser.getFullName()));
                }
            });
            qBRTCSession.addSessionCallbacksListener(WebRTCCallService.this.sessionConnectionListener);
            qBRTCSession.addVideoTrackCallbacksListener(WebRTCCallService.this.videoTrackListener);
            WebRTCCallService.this.sessionCache.add(qBRTCSession);
            String str = WebRTCConstants.EventType.CALL.eventType;
            WritableNativeMap writableNativeMap = new WritableNativeMap();
            WritableMap qBRTCSessionToMap = WebRTCMapper.qBRTCSessionToMap(qBRTCSession);
            WritableMap userInfoToMap = WebRTCMapper.userInfoToMap(qBRTCSession);
            writableNativeMap.putMap("session", qBRTCSessionToMap);
            writableNativeMap.putInt("userId", qBRTCSession.getCallerID().intValue());
            writableNativeMap.putMap("userInfo", userInfoToMap);
            WebRTCCallService.this.sendEvent(str, EventsHelper.buildResult(str, writableNativeMap));
        }

        @Override
        public void onSessionClosed(QBRTCSession qBRTCSession) {
            WebRTCCallService.this.updateNotification(WebRTCCallService.this.getString(R.string.call_service_notification_title), WebRTCCallService.this.getString(R.string.call_service_notification_text));
            LogInstrumentation.e(WebRTCCallService.TAG, "QBRTCClientEventListener: onSessionClosed: " + qBRTCSession.getState());
            WebRTCCallService.this.switchAudioOutput(WebRTCConstants.AudioOutput.EARSPEAKER.value.intValue(), null);
            new Handler(WebRTCCallService.this.context.getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    WebRTCCallService.this.releaseAudioManager();
                }
            }, 500L);
            WebRTCCallService.this.sessionCache.remove(qBRTCSession);
            String str = WebRTCConstants.EventType.CALL_END.eventType;
            WritableNativeMap writableNativeMap = new WritableNativeMap();
            writableNativeMap.putMap("session", WebRTCMapper.qBRTCSessionToMap(qBRTCSession));
            WebRTCCallService.this.sendEvent(str, EventsHelper.buildResult(str, writableNativeMap));
        }

        @Override
        public void onSessionStartClose(QBRTCSession qBRTCSession) {
        }

        @Override
        public void onUserNoActions(QBRTCSession qBRTCSession, Integer num) {
            String str = WebRTCConstants.EventType.NOT_ANSWER.eventType;
            WritableNativeMap writableNativeMap = new WritableNativeMap();
            writableNativeMap.putMap("session", WebRTCMapper.qBRTCSessionToMap(qBRTCSession));
            writableNativeMap.putInt("userId", num.intValue());
            WebRTCCallService.this.sendEvent(str, EventsHelper.buildResult(str, writableNativeMap));
            qBRTCSession.hangUp(null);
        }

        @Override
        public void onUserNotAnswer(QBRTCSession qBRTCSession, Integer num) {
            String str = WebRTCConstants.EventType.NOT_ANSWER.eventType;
            WritableNativeMap writableNativeMap = new WritableNativeMap();
            writableNativeMap.putMap("session", WebRTCMapper.qBRTCSessionToMap(qBRTCSession));
            writableNativeMap.putInt("userId", num.intValue());
            WebRTCCallService.this.sendEvent(str, EventsHelper.buildResult(str, writableNativeMap));
        }

        private QBRTCClientEventListener() {
        }
    }

    public interface ServiceCallback<T> {
        void onError(String str);

        void onSuccess(T t);
    }

    @Instrumented
    public class SessionConnectionListener implements QBRTCSessionConnectionCallbacks {
        public SessionConnectionListener(WebRTCCallService webRTCCallService, int i) {
            this();
        }

        @Override
        public void onConnectionFailedWithUser(QBRTCSession qBRTCSession, Integer num) {
            WritableNativeMap writableNativeMap = new WritableNativeMap();
            WritableMap qBRTCSessionToMap = WebRTCMapper.qBRTCSessionToMap(qBRTCSession);
            String str = WebRTCConstants.EventType.PEER_CONNECTION_STATE_CHANGED.eventType;
            writableNativeMap.putMap("session", qBRTCSessionToMap);
            writableNativeMap.putInt("userId", num.intValue());
            writableNativeMap.putInt("state", WebRTCConstants.RTCPeerConnectionState.FAILED.eventType.intValue());
            WebRTCCallService.this.sendEvent(str, EventsHelper.buildResult(str, writableNativeMap));
        }

        @Override
        public void onDisconnectedTimeoutFromUser(QBRTCSession qBRTCSession, Integer num) {
        }

        @Override
        public void onStartConnectToUser(QBRTCSession qBRTCSession, Integer num) {
            WritableNativeMap writableNativeMap = new WritableNativeMap();
            WritableMap qBRTCSessionToMap = WebRTCMapper.qBRTCSessionToMap(qBRTCSession);
            String str = WebRTCConstants.EventType.PEER_CONNECTION_STATE_CHANGED.eventType;
            writableNativeMap.putMap("session", qBRTCSessionToMap);
            writableNativeMap.putInt("userId", num.intValue());
            writableNativeMap.putInt("state", WebRTCConstants.RTCPeerConnectionState.NEW.eventType.intValue());
            WebRTCCallService.this.sendEvent(str, EventsHelper.buildResult(str, writableNativeMap));
        }

        private SessionConnectionListener() {
        }

        @Override
        public void onConnectedToUser(QBRTCSession qBRTCSession, Integer num) {
            WritableNativeMap writableNativeMap = new WritableNativeMap();
            WritableMap qBRTCSessionToMap = WebRTCMapper.qBRTCSessionToMap(qBRTCSession);
            String str = WebRTCConstants.EventType.PEER_CONNECTION_STATE_CHANGED.eventType;
            writableNativeMap.putMap("session", qBRTCSessionToMap);
            writableNativeMap.putInt("userId", num.intValue());
            writableNativeMap.putInt("state", WebRTCConstants.RTCPeerConnectionState.CONNECTED.eventType.intValue());
            WebRTCCallService.this.sendEvent(str, EventsHelper.buildResult(str, writableNativeMap));
        }

        @Override
        public void onConnectionClosedForUser(QBRTCSession qBRTCSession, Integer num) {
            WritableNativeMap writableNativeMap = new WritableNativeMap();
            WritableMap qBRTCSessionToMap = WebRTCMapper.qBRTCSessionToMap(qBRTCSession);
            String str = WebRTCConstants.EventType.PEER_CONNECTION_STATE_CHANGED.eventType;
            writableNativeMap.putMap("session", qBRTCSessionToMap);
            writableNativeMap.putInt("userId", num.intValue());
            writableNativeMap.putInt("state", WebRTCConstants.RTCPeerConnectionState.CLOSED.eventType.intValue());
            WebRTCCallService.this.sendEvent(str, EventsHelper.buildResult(str, writableNativeMap));
        }

        @Override
        public void onDisconnectedFromUser(QBRTCSession qBRTCSession, Integer num) {
            WritableNativeMap writableNativeMap = new WritableNativeMap();
            WritableMap qBRTCSessionToMap = WebRTCMapper.qBRTCSessionToMap(qBRTCSession);
            String str = WebRTCConstants.EventType.PEER_CONNECTION_STATE_CHANGED.eventType;
            writableNativeMap.putMap("session", qBRTCSessionToMap);
            writableNativeMap.putInt("userId", num.intValue());
            writableNativeMap.putInt("state", WebRTCConstants.RTCPeerConnectionState.DISCONNECTED.eventType.intValue());
            WebRTCCallService.this.sendEvent(str, EventsHelper.buildResult(str, writableNativeMap));
        }

        @Override
        public void onStateChanged(QBRTCSession qBRTCSession, BaseSession.QBRTCSessionState qBRTCSessionState) {
            LogInstrumentation.e(WebRTCCallService.TAG + "_AUDIO_MANAGER", "SessionConnectionListener: onStateChanged: " + qBRTCSession.getState());
            if (qBRTCSessionState == BaseSession.QBRTCSessionState.QB_RTC_SESSION_CONNECTED) {
                WebRTCCallService.this.initAudioManager();
                if (qBRTCSession.getConferenceType().equals(QBRTCTypes.QBConferenceType.QB_CONFERENCE_TYPE_VIDEO)) {
                    WebRTCCallService.this.switchAudioOutput(WebRTCConstants.AudioOutput.LOUDSPEAKER.value.intValue(), null);
                } else {
                    WebRTCCallService.this.switchAudioOutput(WebRTCConstants.AudioOutput.EARSPEAKER.value.intValue(), null);
                }
            }
        }
    }

    @Instrumented
    public class VideoTrackListener implements QBRTCClientVideoTracksCallbacks<QBRTCSession> {
        public VideoTrackListener(WebRTCCallService webRTCCallService, int i) {
            this();
        }

        private VideoTrackListener() {
        }

        @Override
        public void onLocalVideoTrackReceive(QBRTCSession qBRTCSession, QBRTCVideoTrack qBRTCVideoTrack) {
            Integer id = QBChatService.getInstance().getUser().getId();
            id.intValue();
            LogInstrumentation.d(WebRTCCallService.TAG, "onLocalVideoTrackReceive() for session: " + qBRTCSession.getSessionID());
            WritableMap qBRTCVideoTrackToMap = WebRTCMapper.qBRTCVideoTrackToMap(qBRTCVideoTrack, id, qBRTCSession.getSessionID());
            WebRTCCallService webRTCCallService = WebRTCCallService.this;
            String str = WebRTCConstants.EventType.RECEIVED_VIDEO_TRACK.eventType;
            webRTCCallService.sendEvent(str, EventsHelper.buildResult(str, qBRTCVideoTrackToMap));
        }

        @Override
        public void onRemoteVideoTrackReceive(QBRTCSession qBRTCSession, QBRTCVideoTrack qBRTCVideoTrack, Integer num) {
            LogInstrumentation.d(WebRTCCallService.TAG, "onRemoteVideoTrackReceive for session:  " + qBRTCSession.getSessionID() + ", for user: " + num);
            WritableMap qBRTCVideoTrackToMap = WebRTCMapper.qBRTCVideoTrackToMap(qBRTCVideoTrack, num, qBRTCSession.getSessionID());
            WebRTCCallService webRTCCallService = WebRTCCallService.this;
            String str = WebRTCConstants.EventType.RECEIVED_VIDEO_TRACK.eventType;
            webRTCCallService.sendEvent(str, EventsHelper.buildResult(str, qBRTCVideoTrackToMap));
        }
    }

    private void addQBRTCClientEventListener() {
        QBRTCClientEventListener qBRTCClientEventListener = new QBRTCClientEventListener(this, 0);
        this.qbrtcClientEventListener = qBRTCClientEventListener;
        this.qbrtcClient.addSessionCallbacksListener(qBRTCClientEventListener);
    }

    private void addSessionConnectionListeners() {
        this.sessionConnectionListener = new SessionConnectionListener(this, 0);
        Iterator<QBRTCSession> it = this.sessionCache.iterator();
        while (it.hasNext()) {
            it.next().addSessionCallbacksListener(this.sessionConnectionListener);
        }
    }

    private void addVideoTrackListeners() {
        this.videoTrackListener = new VideoTrackListener(this, 0);
        Iterator<QBRTCSession> it = this.sessionCache.iterator();
        while (it.hasNext()) {
            it.next().addVideoTrackCallbacksListener(this.videoTrackListener);
        }
    }

    private Notification buildNotification(String str, String str2) {
        Intent intent = new Intent(this, (Class<?>) getActivityClass());
        intent.setAction("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.LAUNCHER");
        PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 67108864);
        q qVar = new q();
        qVar.h(str);
        qVar.g(str2);
        s sVar = new s(this, createNotificationChannel(CHANNEL_ID, CHANNEL_NAME));
        sVar.z(qVar);
        sVar.i(str);
        sVar.h(str2);
        sVar.F(System.currentTimeMillis());
        sVar.x(R.mipmap.ic_call_service_small);
        sVar.q(BitmapFactoryInstrumentation.decodeResource(getResources(), R.mipmap.ic_call_service_large));
        sVar.u(2);
        sVar.g(activity);
        return sVar.a();
    }

    @RequiresApi(26)
    private String createNotificationChannel(String str, String str2) {
        NotificationChannel notificationChannel = new NotificationChannel(str, str2, 2);
        notificationChannel.setLightColor(getColor(R.color.primary));
        notificationChannel.setLockscreenVisibility(1);
        ((NotificationManager) getSystemService("notification")).createNotificationChannel(notificationChannel);
        return str;
    }

    private Class getActivityClass() {
        try {
            return Class.forName(this.context.getPackageManager().getLaunchIntentForPackage(this.context.getPackageName()).getComponent().getClassName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    private QBRTCSession getSessionFromCache(String str) {
        for (QBRTCSession qBRTCSession : this.sessionCache) {
            if (qBRTCSession.getSessionID().toLowerCase().equals(str.toLowerCase())) {
                return qBRTCSession;
            }
        }
        return null;
    }

    public void initAudioManager() {
        StringBuilder sb = new StringBuilder();
        String str = TAG;
        sb.append(str);
        sb.append("_AUDIO_MANAGER");
        LogInstrumentation.e(sb.toString(), "initAudioManager: try to init...");
        if (this.appRTCAudioManager != null) {
            LogInstrumentation.e(str + "_AUDIO_MANAGER", "initAudioManager: the appRTCAudioManger != null, try to release");
            releaseAudioManager();
        }
        QBAudioManager create = QBAudioManager.create(this);
        this.appRTCAudioManager = create;
        create.setManageSpeakerPhoneByProximity(false);
        this.appRTCAudioManager.setOnWiredHeadsetStateListener(new QBAudioManager.OnWiredHeadsetStateListener() {
            @Override
            public void onWiredHeadsetStateChanged(boolean z, boolean z2) {
            }
        });
        this.appRTCAudioManager.setBluetoothAudioDeviceStateListener(new QBAudioManager.BluetoothAudioDeviceStateListener() {
            @Override
            public void onStateChanged(boolean z) {
            }
        });
        this.appRTCAudioManager.start(new QBAudioManager.AudioManagerEvents() {
            @Override
            public void onAudioDeviceChanged(QBAudioManager.AudioDevice audioDevice, Set<QBAudioManager.AudioDevice> set) {
            }
        });
        LogInstrumentation.e(str + "_AUDIO_MANAGER", "initAudioManager: success init");
    }

    private void initRTCClient() {
        QBRTCClient qBRTCClient = QBRTCClient.getInstance(this);
        this.qbrtcClient = qBRTCClient;
        qBRTCClient.setCameraErrorHandler(new CameraEventsListener(this, 0));
        QBRTCMediaConfig.VideoQuality videoQuality = QBRTCMediaConfig.VideoQuality.HD_VIDEO;
        QBRTCMediaConfig.setVideoWidth(videoQuality.width);
        QBRTCMediaConfig.setVideoHeight(videoQuality.height);
        QBRTCConfig.setMaxOpponentsCount(6);
        QBRTCConfig.setDebugEnabled(true);
        this.qbrtcClient.prepareToProcessCalls();
        if (QBChatService.getInstance() == null) {
            Toast.makeText((Context) this.reactApplicationContext, (CharSequence) "Error connecting to chat", 1).show();
            stop(this.reactApplicationContext);
            System.exit(0);
        }
        QBChatService.getInstance().getVideoChatWebRTCSignalingManager().addSignalingManagerListener(new QBVideoChatSignalingManagerListener() {
            @Override
            public void signalingCreated(QBSignaling qBSignaling, boolean z) {
                if (z) {
                    return;
                }
                WebRTCCallService.this.qbrtcClient.addSignaling(qBSignaling);
            }
        });
    }

    public static boolean isRunning(Context context) {
        Iterator<ActivityManager.RunningServiceInfo> it = ((ActivityManager) context.getSystemService("activity")).getRunningServices(Integer.MAX_VALUE).iterator();
        while (it.hasNext()) {
            if (WebRTCCallService.class.getName().equals(it.next().service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    private void removeQBRTCClientEventListener() {
        this.qbrtcClient.removeSessionsCallbacksListener(this.qbrtcClientEventListener);
    }

    private void removeSessionConnectionsListeners() {
        Iterator<QBRTCSession> it = this.sessionCache.iterator();
        while (it.hasNext()) {
            it.next().removeSessionCallbacksListener(this.sessionConnectionListener);
        }
    }

    public void sendEvent(String str, @Nullable WritableMap writableMap) {
        this.reactApplicationContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(str, writableMap);
    }

    public static void start(Context context) {
        context.startService(new Intent(context, (Class<?>) WebRTCCallService.class));
    }

    public static void stop(Context context) {
        context.stopService(new Intent(context, (Class<?>) WebRTCCallService.class));
    }

    public void stopCallTimer() {
        CallTimerTask callTimerTask = this.callTimerTask;
        if (callTimerTask != null) {
            callTimerTask.cancel();
        }
        Timer timer = this.callTimer;
        if (timer != null) {
            timer.cancel();
            this.callTimer.purge();
        }
    }

    public void updateNotification(String str, String str2) {
        ((NotificationManager) getSystemService("notification")).notify(SERVICE_ID, buildNotification(str, str2));
    }

    public void acceptCall(String str, Map<String, String> map, ServiceCallback<QBRTCSession> serviceCallback) {
        QBRTCSession sessionFromCache = getSessionFromCache(str);
        if (sessionFromCache == null) {
            serviceCallback.onError(t2.p("The session with id: ", str, " has not found"));
            return;
        }
        sessionFromCache.acceptCall(map);
        serviceCallback.onSuccess(sessionFromCache);
        startCallTimer();
    }

    public void getSession(String str, ServiceCallback<QBRTCSession> serviceCallback) {
        QBRTCSession sessionFromCache = getSessionFromCache(str);
        if (sessionFromCache != null) {
            serviceCallback.onSuccess(sessionFromCache);
        } else {
            serviceCallback.onError(t2.p("The session with id: ", str, " has not found"));
        }
    }

    public void getVideoTrack(String str, Integer num, ServiceCallback<QBRTCVideoTrack> serviceCallback) {
        QBRTCSession sessionFromCache = getSessionFromCache(str);
        if (sessionFromCache == null || sessionFromCache.getMediaStreamManager() == null) {
            serviceCallback.onError(t2.p("The session with id: ", str, " has not found"));
            return;
        }
        QBRTCVideoTrack localVideoTrack = num.intValue() == QBChatService.getInstance().getUser().getId().intValue() ? sessionFromCache.getMediaStreamManager().getLocalVideoTrack() : sessionFromCache.getMediaStreamManager().getVideoTrack(num);
        if (localVideoTrack != null) {
            serviceCallback.onSuccess(localVideoTrack);
        } else {
            serviceCallback.onError(f.i(num, "The video track for user", " has not found"));
        }
    }

    public void hangUpCall(String str, Map<String, String> map, ServiceCallback<QBRTCSession> serviceCallback) {
        QBRTCSession sessionFromCache = getSessionFromCache(str);
        if (sessionFromCache != null) {
            sessionFromCache.hangUp(map);
            switchAudioOutput(WebRTCConstants.AudioOutput.EARSPEAKER.value.intValue(), null);
            new Handler(this.context.getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    WebRTCCallService.this.releaseAudioManager();
                }
            }, 500L);
            this.sessionCache.remove(sessionFromCache);
            serviceCallback.onSuccess(sessionFromCache);
        } else {
            serviceCallback.onError(t2.p("The session with id: ", str, " has not found"));
        }
        stopCallTimer();
        updateNotification(getString(R.string.call_service_notification_title), getString(R.string.call_service_notification_text));
    }

    @Override
    @Nullable
    public IBinder onBind(Intent intent) {
        return this.callServiceBinder;
    }

    @Override
    public void onCreate() {
        this.context = getApplicationContext();
        initRTCClient();
        addQBRTCClientEventListener();
        addVideoTrackListeners();
        addSessionConnectionListeners();
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        removeQBRTCClientEventListener();
        removeVideoTrackListeners();
        removeSessionConnectionsListeners();
        releaseAudioManager();
        stopCallTimer();
        stopForeground(true);
    }

    @Override
    public int onStartCommand(Intent intent, int i, int i2) {
        startForeground(SERVICE_ID, buildNotification(getString(R.string.call_service_notification_title), getString(R.string.call_service_notification_text)));
        return super.onStartCommand(intent, i, i2);
    }

    public void rejectCall(String str, Map<String, String> map, ServiceCallback<QBRTCSession> serviceCallback) {
        QBRTCSession sessionFromCache = getSessionFromCache(str);
        if (sessionFromCache == null) {
            serviceCallback.onError(t2.p("The session with id: ", str, " has not found"));
        } else {
            sessionFromCache.rejectCall(map);
            serviceCallback.onSuccess(sessionFromCache);
        }
    }

    public void releaseAudioManager() {
        StringBuilder sb = new StringBuilder();
        String str = TAG;
        sb.append(str);
        sb.append("_AUDIO_MANAGER");
        LogInstrumentation.e(sb.toString(), "releaseAudioManager: try to release...");
        QBAudioManager qBAudioManager = this.appRTCAudioManager;
        if (qBAudioManager == null) {
            LogInstrumentation.e(str + "_AUDIO_MANAGER", "releaseAudioManager: the appRTCAudioManger == null (not initialized), not need to release");
            return;
        }
        qBAudioManager.stop();
        this.appRTCAudioManager = null;
        LogInstrumentation.e(str + "_AUDIO_MANAGER", "releaseAudioManager: the appRTCAudioManger is success released");
    }

    public void removeVideoTrackListeners() {
        Iterator<QBRTCSession> it = this.sessionCache.iterator();
        while (it.hasNext()) {
            it.next().removeVideoTrackCallbacksListener(this.videoTrackListener);
        }
    }

    public void setAudioEnabled(boolean z, String str, Integer num, ServiceCallback<Void> serviceCallback) {
        try {
            QBRTCSession sessionFromCache = getSessionFromCache(str);
            if (num != null) {
                sessionFromCache.getMediaStreamManager().getAudioTrack(num).setEnabled(z);
            } else {
                sessionFromCache.getMediaStreamManager().getLocalAudioTrack().setEnabled(z);
            }
            serviceCallback.onSuccess(null);
        } catch (Exception unused) {
            serviceCallback.onError("The session with id: " + str + " or audio track for user " + num + " has not found");
        }
    }

    public void setReactApplicationContext(ReactApplicationContext reactApplicationContext) {
        this.reactApplicationContext = reactApplicationContext;
    }

    public void setVideoEnabled(boolean z, String str, Integer num, ServiceCallback<Void> serviceCallback) {
        try {
            QBRTCSession sessionFromCache = getSessionFromCache(str);
            if (num != null) {
                sessionFromCache.getMediaStreamManager().getVideoTrack(num).setEnabled(z);
            } else {
                sessionFromCache.getMediaStreamManager().getLocalVideoTrack().setEnabled(z);
            }
            serviceCallback.onSuccess(null);
        } catch (Exception unused) {
            serviceCallback.onError("The session with id: " + str + " or video track for user " + num + " has not found");
        }
    }

    public void startCall(final List<Integer> list, QBRTCTypes.QBConferenceType qBConferenceType, Map<String, String> map, ServiceCallback<QBRTCSession> serviceCallback) {
        QBRTCClient qBRTCClient = this.qbrtcClient;
        if (qBRTCClient == null) {
            serviceCallback.onError("The RTC Client has not connected");
            return;
        }
        QBRTCSession createNewSessionWithOpponents = qBRTCClient.createNewSessionWithOpponents(list, qBConferenceType);
        createNewSessionWithOpponents.getSessionDescription().setUserInfo(map);
        createNewSessionWithOpponents.addSessionCallbacksListener(this.sessionConnectionListener);
        createNewSessionWithOpponents.addVideoTrackCallbacksListener(this.videoTrackListener);
        this.sessionCache.add(createNewSessionWithOpponents);
        createNewSessionWithOpponents.startCall(map);
        serviceCallback.onSuccess(createNewSessionWithOpponents);
        QBUsers.getUsersByIDs(list, null).performAsync(new QBEntityCallback<ArrayList<QBUser>>() {
            @Override
            public void onError(QBResponseException qBResponseException) {
                WebRTCCallService.this.updateNotification(WebRTCCallService.this.getString(R.string.notification_title_outgoing), WebRTCCallService.this.getString(R.string.notification_text_outgoing, Arrays.toString(list.toArray())));
            }

            @Override
            public void onSuccess(ArrayList<QBUser> arrayList, Bundle bundle) {
                ArrayList arrayList2 = new ArrayList();
                Iterator<QBUser> it = arrayList.iterator();
                while (it.hasNext()) {
                    QBUser next = it.next();
                    arrayList2.add(TextUtils.isEmpty(next.getFullName()) ? next.getLogin() : next.getFullName());
                }
                WebRTCCallService.this.updateNotification(WebRTCCallService.this.getString(R.string.notification_title_outgoing), WebRTCCallService.this.getString(R.string.notification_text_outgoing, Arrays.toString(arrayList2.toArray()).replace(QBRecordParameterQueryDecorator.LEFT_BRACKET, "").replace(QBRecordParameterQueryDecorator.RIGHT_BRACKET, "")));
            }
        });
    }

    public void startCallTimer() {
        CallTimerTask callTimerTask = this.callTimerTask;
        if (callTimerTask != null) {
            callTimerTask.cancel();
        }
        if (this.callTimer != null) {
            this.callTimer = new Timer();
        }
        CallTimerTask callTimerTask2 = new CallTimerTask();
        this.callTimerTask = callTimerTask2;
        this.callTimer.scheduleAtFixedRate(callTimerTask2, 0L, 1000L);
    }

    public void startScreenSharing(Intent intent, String str, ServiceCallback<Void> serviceCallback) {
        QBRTCSession sessionFromCache = getSessionFromCache(str);
        if (sessionFromCache == null) {
            serviceCallback.onError(t2.p("The session with id: ", str, " has not found"));
        } else {
            sessionFromCache.getMediaStreamManager().setVideoCapturer(new QBRTCScreenCapturer(intent, null));
            serviceCallback.onSuccess(null);
        }
    }

    public void stopScreenSharing(String str, ServiceCallback<Void> serviceCallback) {
        QBRTCSession sessionFromCache = getSessionFromCache(str);
        if (sessionFromCache == null) {
            serviceCallback.onError(t2.p("The session with id: ", str, " has not found"));
            return;
        }
        try {
            sessionFromCache.getMediaStreamManager().setVideoCapturer(new QBRTCCameraVideoCapturer(this, null));
            serviceCallback.onSuccess(null);
        } catch (QBRTCCameraVideoCapturer.QBRTCCameraCapturerException e) {
            serviceCallback.onError(e.getMessage());
        }
    }

    public void switchAudioOutput(final int i, final Promise promise) {
        new Handler(this.context.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                QBAudioManager.AudioDevice appRTCAudioDeviceFromValue = WebRTCMapper.appRTCAudioDeviceFromValue(i);
                LogInstrumentation.e(WebRTCCallService.TAG + "_AUDIO_MANAGER", "switchAudioOutput: try to switch...");
                if (WebRTCCallService.this.appRTCAudioManager == null) {
                    LogInstrumentation.e(WebRTCCallService.TAG, "switchAudioOutput = error: The audio manager is not init");
                    LogInstrumentation.e(WebRTCCallService.TAG + "_AUDIO_MANAGER", "switchAudioOutput: error switch appRTCAudioManager is null");
                    return;
                }
                if (WebRTCCallService.this.appRTCAudioManager.getAudioDevices().contains(appRTCAudioDeviceFromValue)) {
                    WebRTCCallService.this.appRTCAudioManager.selectAudioDevice(appRTCAudioDeviceFromValue);
                    Promise promise2 = promise;
                    if (promise2 != null) {
                        promise2.resolve((Object) null);
                    }
                    LogInstrumentation.e(WebRTCCallService.TAG + "_AUDIO_MANAGER", "switchAudioOutput: success switched to " + appRTCAudioDeviceFromValue);
                    return;
                }
                if (promise != null) {
                    String deviceNameFromValue = WebRTCMapper.getDeviceNameFromValue(Integer.valueOf(i));
                    if (TextUtils.isEmpty(deviceNameFromValue)) {
                        deviceNameFromValue = String.valueOf(i);
                    }
                    promise.reject(new Exception(t2.p("Switch Device of type ", deviceNameFromValue, " is not found")));
                }
                LogInstrumentation.e(WebRTCCallService.TAG + "_AUDIO_MANAGER", "switchAudioOutput: error, the device didn't fount " + appRTCAudioDeviceFromValue);
            }
        }, 500L);
    }

    public void switchCamera(String str, v.c cVar, ServiceCallback<Void> serviceCallback) {
        QBRTCSession sessionFromCache = getSessionFromCache(str);
        if (sessionFromCache == null) {
            serviceCallback.onError(t2.p("The session with id: ", str, " has not found"));
        } else {
            ((QBRTCCameraVideoCapturer) sessionFromCache.getMediaStreamManager().getVideoCapturer()).switchCamera(cVar);
            serviceCallback.onSuccess(null);
        }
    }
}