Search in sources :

Example 1 with IConnectionListener

use of de.vier_bier.habpanelviewer.openhab.IConnectionListener in project habpanelviewer by vbier.

the class ClientWebView method initialize.

synchronized void initialize(final IConnectionListener cl) {
    setWebChromeClient(new WebChromeClient() {

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            if (consoleMessage.message().contains("SSE error, closing EventSource")) {
                cl.disconnected();
            }
            return super.onConsoleMessage(consoleMessage);
        }
    });
    setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (isHabPanelUrl(url)) {
                evaluateJavascript("angular.element(document.body).scope().$root.kioskMode", s -> {
                    mKioskMode = Boolean.parseBoolean(s);
                    Log.d(TAG, "HABPanel page loaded. kioskMode=" + mKioskMode);
                });
            }
        }

        @Override
        public void onReceivedSslError(WebView view, final SslErrorHandler handler, final SslError error) {
            Log.d(TAG, "onReceivedSslError: " + error.getUrl());
            SslCertificate cert = error.getCertificate();
            if (ConnectionUtil.isTrusted(error.getCertificate())) {
                Log.d(TAG, "certificate is trusted: " + error.getUrl());
                handler.proceed();
                return;
            }
            String h;
            try {
                URL url = new URL(error.getUrl());
                h = url.getHost();
            } catch (MalformedURLException e) {
                h = getContext().getString(R.string.unknownHost);
            }
            final String host = h;
            String r = getContext().getString(R.string.notValid);
            switch(error.getPrimaryError()) {
                case SslError.SSL_DATE_INVALID:
                    r = getContext().getString(R.string.invalidDate);
                    break;
                case SslError.SSL_EXPIRED:
                    r = getContext().getString(R.string.expired);
                    break;
                case SslError.SSL_IDMISMATCH:
                    r = getContext().getString(R.string.hostnameMismatch);
                    break;
                case SslError.SSL_NOTYETVALID:
                    r = getContext().getString(R.string.notYetValid);
                    break;
                case SslError.SSL_UNTRUSTED:
                    r = getContext().getString(R.string.untrusted);
                    break;
            }
            final String reason = r;
            String c = getContext().getString(R.string.issuedBy) + cert.getIssuedBy().getDName() + "<br/>";
            c += getContext().getString(R.string.issuedTo) + cert.getIssuedTo().getDName() + "<br/>";
            c += getContext().getString(R.string.validFrom) + SimpleDateFormat.getDateInstance().format(cert.getValidNotBeforeDate()) + "<br/>";
            c += getContext().getString(R.string.validUntil) + SimpleDateFormat.getDateInstance().format(cert.getValidNotAfterDate()) + "<br/>";
            final String certInfo = c;
            new AlertDialog.Builder(ClientWebView.this.getContext()).setTitle(getContext().getString(R.string.certInvalid)).setMessage(getContext().getString(R.string.sslCert) + "https://" + host + " " + reason + ".\n\n" + certInfo.replaceAll("<br/>", "\n") + "\n" + getContext().getString(R.string.storeSecurityException)).setIcon(android.R.drawable.ic_dialog_alert).setPositiveButton(android.R.string.yes, (dialog, whichButton) -> {
                try {
                    ConnectionUtil.addCertificate(error.getCertificate());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                handler.proceed();
            }).setNegativeButton(android.R.string.no, (dialog, whichButton) -> loadData("<html><body><h1>" + getContext().getString(R.string.certInvalid) + "</h1><h2>" + getContext().getString(R.string.sslCert) + "https://" + host + " " + reason + ".</h2>" + certInfo + "</body></html>", "text/html", "UTF-8")).show();
        }

        @Override
        public void onReceivedHttpAuthRequest(WebView view, final HttpAuthHandler handler, final String host, final String realm) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(getContext()).setCancelable(false).setTitle(R.string.login_required).setMessage(getContext().getString(R.string.host_realm, host, realm)).setView(R.layout.dialog_login).setPositiveButton(R.string.okay, (dialog12, id) -> {
                EditText userT = ((AlertDialog) dialog12).findViewById(R.id.username);
                EditText passT = ((AlertDialog) dialog12).findViewById(R.id.password);
                handler.proceed(userT.getText().toString(), passT.getText().toString());
            }).setNegativeButton(R.string.cancel, (dialog1, which) -> handler.cancel());
            final AlertDialog alert = dialog.create();
            alert.show();
        }
    });
    setOnTouchListener((v, event) -> (event.getAction() == MotionEvent.ACTION_MOVE && mDraggingPrevented));
    CookieManager.getInstance().setAcceptCookie(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        CookieManager.getInstance().setAcceptThirdPartyCookies(this, true);
    }
    WebSettings webSettings = getSettings();
    webSettings.setDomStorageEnabled(true);
    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    getContext().registerReceiver(mNetworkReceiver, intentFilter);
}
Also used : Context(android.content.Context) WebViewDatabase(android.webkit.WebViewDatabase) ConsoleMessage(android.webkit.ConsoleMessage) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) IConnectionListener(de.vier_bier.habpanelviewer.openhab.IConnectionListener) SimpleDateFormat(java.text.SimpleDateFormat) Intent(android.content.Intent) SslErrorHandler(android.webkit.SslErrorHandler) AttributeSet(android.util.AttributeSet) WebSettings(android.webkit.WebSettings) MotionEvent(android.view.MotionEvent) CookieManager(android.webkit.CookieManager) WebViewClient(android.webkit.WebViewClient) View(android.view.View) URI(java.net.URI) Build(android.os.Build) WebView(android.webkit.WebView) TargetApi(android.annotation.TargetApi) Log(android.util.Log) WebChromeClient(android.webkit.WebChromeClient) HttpAuthHandler(android.webkit.HttpAuthHandler) ConnectivityManager(android.net.ConnectivityManager) SslError(android.net.http.SslError) MalformedURLException(java.net.MalformedURLException) IntentFilter(android.content.IntentFilter) NetworkInfo(android.net.NetworkInfo) InputType(android.text.InputType) BroadcastReceiver(android.content.BroadcastReceiver) ConnectionUtil(de.vier_bier.habpanelviewer.ssl.ConnectionUtil) AlertDialog(android.support.v7.app.AlertDialog) SharedPreferences(android.content.SharedPreferences) SslCertificate(android.net.http.SslCertificate) EditText(android.widget.EditText) AlertDialog(android.support.v7.app.AlertDialog) EditText(android.widget.EditText) SslErrorHandler(android.webkit.SslErrorHandler) IntentFilter(android.content.IntentFilter) MalformedURLException(java.net.MalformedURLException) SslError(android.net.http.SslError) ConsoleMessage(android.webkit.ConsoleMessage) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) MalformedURLException(java.net.MalformedURLException) SslCertificate(android.net.http.SslCertificate) HttpAuthHandler(android.webkit.HttpAuthHandler) WebSettings(android.webkit.WebSettings) WebChromeClient(android.webkit.WebChromeClient) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient)

Example 2 with IConnectionListener

use of de.vier_bier.habpanelviewer.openhab.IConnectionListener in project habpanelviewer by vbier.

the class MainActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    EventBus.getDefault().register(this);
    try {
        ConnectionUtil.initialize(this);
    } catch (Exception e) {
        Toast.makeText(MainActivity.this, R.string.sslFailed, Toast.LENGTH_LONG).show();
    }
    setContentView(R.layout.activity_main);
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    // inflate navigation header to make sure the textview holding the connection text is created
    NavigationView navigationView = findViewById(R.id.nav_view);
    LinearLayout navHeader = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.nav_header_main, null);
    navigationView.addHeaderView(navHeader);
    navigationView.setNavigationItemSelectedListener(this);
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
    if (mServerConnection == null) {
        mServerConnection = new ServerConnection(this);
        mServerConnection.addConnectionListener(this);
    }
    if (mConnections == null) {
        mConnections = new ConnectionStatistics(this);
    }
    if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && mFlashService == null) {
            try {
                mFlashService = new FlashHandler(this, (CameraManager) getSystemService(Context.CAMERA_SERVICE));
            } catch (CameraAccessException | IllegalAccessException e) {
                Log.d(TAG, "Could not create flash controller");
            }
        }
        if (mCam == null) {
            mCam = new Camera(this, findViewById(R.id.previewView), prefs);
        }
        if (mMotionVisualizer == null) {
            int scaledSize = getResources().getDimensionPixelSize(R.dimen.motionFontSize);
            final SurfaceView motionView = findViewById(R.id.motionView);
            mMotionVisualizer = new MotionVisualizer(motionView, navigationView, prefs, mCam.getSensorOrientation(), scaledSize);
            mMotionDetector = new MotionDetector(this, mCam, mMotionVisualizer, mServerConnection);
        }
    }
    if (mDiscovery == null) {
        mDiscovery = new ServerDiscovery((NsdManager) getSystemService(Context.NSD_SERVICE));
    }
    if (prefs.getBoolean("pref_first_start", true)) {
        SharedPreferences.Editor editor1 = prefs.edit();
        editor1.putBoolean("pref_first_start", false);
        editor1.putString("pref_app_version", BuildConfig.VERSION_NAME);
        editor1.apply();
        final String startText = ResourcesUtil.fetchFirstStart(this);
        UiUtil.showScrollDialog(this, "HABPanelViewer", getString(R.string.welcome), startText);
        if (prefs.getString("pref_server_url", "").isEmpty()) {
            mDiscovery.discover(new ServerDiscovery.DiscoveryListener() {

                @Override
                public void found(String serverUrl) {
                    SharedPreferences.Editor editor1 = prefs.edit();
                    editor1.putString("pref_server_url", serverUrl);
                    editor1.apply();
                }

                @Override
                public void notFound() {
                }
            }, true, true);
        }
    } else {
        // make sure old server url preference is used in case it is still set
        if (prefs.getString("pref_server_url", "").isEmpty()) {
            final String oldUrl = prefs.getString("pref_url", "");
            if (!oldUrl.isEmpty()) {
                SharedPreferences.Editor editor1 = prefs.edit();
                editor1.putString("pref_server_url", oldUrl);
                editor1.remove("pref_url");
                editor1.apply();
            }
        }
        String lastVersion = prefs.getString("pref_app_version", "0.9.2");
        if (!BuildConfig.VERSION_NAME.equals(lastVersion)) {
            SharedPreferences.Editor editor1 = prefs.edit();
            editor1.putString("pref_app_version", BuildConfig.VERSION_NAME);
            editor1.apply();
            final String relText = ResourcesUtil.fetchReleaseNotes(this, lastVersion);
            UiUtil.showScrollDialog(this, getString(R.string.updated), getString(R.string.updatedText), relText);
        }
    }
    if (mBatteryMonitor == null) {
        mBatteryMonitor = new BatteryMonitor(this, mServerConnection);
    }
    if (mVolumeMonitor == null) {
        mVolumeMonitor = new VolumeMonitor(this, (AudioManager) getSystemService(Context.AUDIO_SERVICE), mServerConnection);
    }
    if (mConnectedReporter == null) {
        mConnectedReporter = new ConnectedIndicator(this, mServerConnection);
    }
    SensorManager m = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    if (mProximityMonitor == null && getPackageManager().hasSystemFeature(PackageManager.FEATURE_SENSOR_PROXIMITY)) {
        try {
            mProximityMonitor = new ProximityMonitor(this, m, mServerConnection);
        } catch (SensorMissingException e) {
            Log.d(TAG, "Could not create proximity monitor");
        }
    }
    if (mBrightnessMonitor == null && getPackageManager().hasSystemFeature(PackageManager.FEATURE_SENSOR_LIGHT)) {
        try {
            mBrightnessMonitor = new BrightnessMonitor(this, m, mServerConnection);
        } catch (SensorMissingException e) {
            Log.d(TAG, "Could not create brightness monitor");
        }
    }
    if (mPressureMonitor == null && getPackageManager().hasSystemFeature(PackageManager.FEATURE_SENSOR_BAROMETER)) {
        try {
            mPressureMonitor = new PressureMonitor(this, m, mServerConnection);
        } catch (SensorMissingException e) {
            Log.d(TAG, "Could not create pressure monitor");
        }
    }
    if (mTemperatureMonitor == null && getPackageManager().hasSystemFeature(PackageManager.FEATURE_SENSOR_AMBIENT_TEMPERATURE)) {
        try {
            mTemperatureMonitor = new TemperatureMonitor(this, m, mServerConnection);
        } catch (SensorMissingException e) {
            Log.d(TAG, "Could not create temperature monitor");
        }
    }
    if (mCommandQueue == null) {
        ScreenHandler mScreenHandler = new ScreenHandler((PowerManager) getSystemService(POWER_SERVICE), this);
        mCommandQueue = new CommandQueue(this, mServerConnection);
        mCommandQueue.addHandler(new InternalCommandHandler(this, mMotionDetector, mServerConnection));
        mCommandQueue.addHandler(new AdminHandler(this));
        mCommandQueue.addHandler(new BluetoothHandler(this, (BluetoothManager) getSystemService(BLUETOOTH_SERVICE)));
        mCommandQueue.addHandler(mScreenHandler);
        mCommandQueue.addHandler(new VolumeHandler(this, (AudioManager) getSystemService(Context.AUDIO_SERVICE)));
        if (mFlashService != null) {
            mCommandQueue.addHandler(mFlashService);
        }
    }
    mRestartCount = getIntent().getIntExtra("restartCount", 0);
    showInitialToastMessage(mRestartCount);
    mTextView = navHeader.findViewById(R.id.textView);
    mWebView = findViewById(R.id.activity_main_webview);
    mWebView.initialize(new IConnectionListener() {

        @Override
        public void connected(String url) {
        }

        @Override
        public void disconnected() {
            if (prefs.getBoolean("pref_track_browser_connection", false)) {
                mServerConnection.reconnect();
            }
        }
    });
    mCommandQueue.addHandler(new WebViewHandler(mWebView));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        MediaProjectionManager projectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        startActivityForResult(projectionManager.createScreenCaptureIntent(), ScreenCapturer.REQUEST_MEDIA_PROJECTION);
    }
}
Also used : NavigationView(android.support.design.widget.NavigationView) FlashHandler(de.vier_bier.habpanelviewer.command.FlashHandler) ConnectedIndicator(de.vier_bier.habpanelviewer.reporting.ConnectedIndicator) MotionVisualizer(de.vier_bier.habpanelviewer.reporting.motion.MotionVisualizer) CommandQueue(de.vier_bier.habpanelviewer.command.CommandQueue) BluetoothManager(android.bluetooth.BluetoothManager) ServerDiscovery(de.vier_bier.habpanelviewer.openhab.ServerDiscovery) BatteryMonitor(de.vier_bier.habpanelviewer.reporting.BatteryMonitor) CameraAccessException(android.hardware.camera2.CameraAccessException) AudioManager(android.media.AudioManager) AdminHandler(de.vier_bier.habpanelviewer.command.AdminHandler) IMotionDetector(de.vier_bier.habpanelviewer.reporting.motion.IMotionDetector) MotionDetector(de.vier_bier.habpanelviewer.reporting.motion.MotionDetector) ScreenHandler(de.vier_bier.habpanelviewer.command.ScreenHandler) Camera(de.vier_bier.habpanelviewer.reporting.motion.Camera) NsdManager(android.net.nsd.NsdManager) SurfaceView(android.view.SurfaceView) VolumeHandler(de.vier_bier.habpanelviewer.command.VolumeHandler) WebViewHandler(de.vier_bier.habpanelviewer.command.WebViewHandler) SharedPreferences(android.content.SharedPreferences) BluetoothHandler(de.vier_bier.habpanelviewer.command.BluetoothHandler) BrightnessMonitor(de.vier_bier.habpanelviewer.reporting.BrightnessMonitor) ServerConnection(de.vier_bier.habpanelviewer.openhab.ServerConnection) CameraManager(android.hardware.camera2.CameraManager) ProximityMonitor(de.vier_bier.habpanelviewer.reporting.ProximityMonitor) SensorMissingException(de.vier_bier.habpanelviewer.reporting.SensorMissingException) CameraException(de.vier_bier.habpanelviewer.reporting.motion.CameraException) CameraAccessException(android.hardware.camera2.CameraAccessException) Point(android.graphics.Point) PressureMonitor(de.vier_bier.habpanelviewer.reporting.PressureMonitor) MediaProjectionManager(android.media.projection.MediaProjectionManager) SensorManager(android.hardware.SensorManager) IConnectionListener(de.vier_bier.habpanelviewer.openhab.IConnectionListener) TemperatureMonitor(de.vier_bier.habpanelviewer.reporting.TemperatureMonitor) SensorMissingException(de.vier_bier.habpanelviewer.reporting.SensorMissingException) VolumeMonitor(de.vier_bier.habpanelviewer.reporting.VolumeMonitor) InternalCommandHandler(de.vier_bier.habpanelviewer.command.InternalCommandHandler) LinearLayout(android.widget.LinearLayout)

Aggregations

SharedPreferences (android.content.SharedPreferences)2 IConnectionListener (de.vier_bier.habpanelviewer.openhab.IConnectionListener)2 TargetApi (android.annotation.TargetApi)1 BluetoothManager (android.bluetooth.BluetoothManager)1 BroadcastReceiver (android.content.BroadcastReceiver)1 Context (android.content.Context)1 Intent (android.content.Intent)1 IntentFilter (android.content.IntentFilter)1 Point (android.graphics.Point)1 SensorManager (android.hardware.SensorManager)1 CameraAccessException (android.hardware.camera2.CameraAccessException)1 CameraManager (android.hardware.camera2.CameraManager)1 AudioManager (android.media.AudioManager)1 MediaProjectionManager (android.media.projection.MediaProjectionManager)1 ConnectivityManager (android.net.ConnectivityManager)1 NetworkInfo (android.net.NetworkInfo)1 SslCertificate (android.net.http.SslCertificate)1 SslError (android.net.http.SslError)1 NsdManager (android.net.nsd.NsdManager)1 Build (android.os.Build)1