导航菜单

页面标题

页面副标题

Delta Chat v1.58.3 - WebxdcActivity.java 源代码

正在查看: Delta Chat v1.58.3 应用的 WebxdcActivity.java JAVA 源代码文件

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


package org.thoughtcrime.securesms;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.SearchView;
import androidx.core.app.TaskStackBuilder;
import androidx.core.content.pm.ShortcutInfoCompat;
import androidx.core.content.pm.ShortcutManagerCompat;
import androidx.core.graphics.drawable.IconCompat;
import com.b44t.messenger.DcChat;
import com.b44t.messenger.DcContext;
import com.b44t.messenger.DcEvent;
import com.b44t.messenger.DcMsg;
import com.b44t.messenger.rpc.Rpc;
import com.b44t.messenger.rpc.RpcException;
import com.google.common.base.Charsets;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import org.json.JSONObject;
import org.thoughtcrime.securesms.connect.AccountManager;
import org.thoughtcrime.securesms.connect.DcEventCenter;
import org.thoughtcrime.securesms.connect.DcHelper;
import org.thoughtcrime.securesms.util.IntentUtils;
import org.thoughtcrime.securesms.util.JsonUtils;
import org.thoughtcrime.securesms.util.MediaUtil;
import org.thoughtcrime.securesms.util.Prefs;
import org.thoughtcrime.securesms.util.Util;

public class WebxdcActivity extends WebViewActivity implements DcEventCenter.DcEventDelegate {
    private static final String EXTRA_ACCOUNT_ID = "accountId";
    private static final String EXTRA_APP_MSG_ID = "appMessageId";
    private static final String EXTRA_HIDE_ACTION_BAR = "hideActionBar";
    private static final String EXTRA_HREF = "href";
    private static final int REQUEST_CODE_FILE_PICKER = 51426;
    private static final String TAG = "WebxdcActivity";
    private static long lastOpenTime;
    private String baseURL;
    private DcMsg dcAppMsg;
    private DcContext dcContext;
    private ValueCallback<Uri[]> filePathCallback;
    private Rpc rpc;
    private String selfAddr;
    private int sendUpdateInterval;
    private int sendUpdateMaxSize;
    private String sourceCodeUrl = "";
    private boolean internetAccess = false;
    private boolean hideActionBar = false;

    @Override
    public boolean runOnMain() {
        return DcEventCenter.DcEventDelegate.CC.$default$runOnMain(this);
    }

    public static void openMaps(Context context, int i) {
        DcContext context2 = DcHelper.getContext(context);
        int initWebxdcIntegration = context2.initWebxdcIntegration(i);
        if (initWebxdcIntegration == 0) {
            try {
                InputStream open = context.getResources().getAssets().open("webxdc/maps.xdc");
                String blobdirFile = DcHelper.getBlobdirFile(context2, "maps", ".xdc");
                Util.copy(open, new FileOutputStream(blobdirFile));
                context2.setWebxdcIntegration(blobdirFile);
                initWebxdcIntegration = context2.initWebxdcIntegration(i);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (initWebxdcIntegration == 0) {
                Toast.makeText(context, "Cannot get maps.xdc, see log for details.", 1).show();
                return;
            }
        }
        openWebxdcActivity(context, initWebxdcIntegration, true, "");
    }

    public static void openWebxdcActivity(Context context, DcMsg dcMsg) {
        openWebxdcActivity(context, dcMsg, "");
    }

    public static void openWebxdcActivity(Context context, DcMsg dcMsg, String str) {
        openWebxdcActivity(context, dcMsg.getId(), false, str);
    }

    public static void openWebxdcActivity(Context context, int i, boolean z, String str) {
        if (Util.isClickedRecently()) {
            return;
        }
        if (Prefs.isDeveloperModeEnabled(context)) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        context.startActivity(getWebxdcIntent(context, i, z, str));
    }

    private static Intent getWebxdcIntent(Context context, int i, boolean z, String str) {
        DcContext context2 = DcHelper.getContext(context);
        Intent intent = new Intent(context, (Class<?>) WebxdcActivity.class);
        intent.setAction("android.intent.action.VIEW");
        intent.putExtra(EXTRA_ACCOUNT_ID, context2.getAccountId());
        intent.putExtra(EXTRA_APP_MSG_ID, i);
        intent.putExtra(EXTRA_HIDE_ACTION_BAR, z);
        intent.putExtra(EXTRA_HREF, str);
        return intent;
    }

    private static Intent[] getWebxdcIntentWithParentStack(Context context, int i) {
        Intent action = new Intent(context, (Class<?>) ConversationActivity.class).putExtra("chat_id", DcHelper.getContext(context).getMsg(i).getChatId()).setAction("android.intent.action.VIEW");
        return TaskStackBuilder.create(context).addNextIntentWithParentStack(action).addNextIntent(getWebxdcIntent(context, i, false, "")).getIntents();
    }

    @Override
    protected void onCreate(Bundle bundle, boolean z) {
        super.onCreate(bundle, z);
        this.rpc = DcHelper.getRpc(this);
        Bundle extras = getIntent().getExtras();
        this.hideActionBar = extras.getBoolean(EXTRA_HIDE_ACTION_BAR, false);
        setScreenMode(getResources().getConfiguration());
        this.webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> valueCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                if (WebxdcActivity.this.filePathCallback != null) {
                    WebxdcActivity.this.filePathCallback.onReceiveValue(null);
                }
                WebxdcActivity.this.filePathCallback = valueCallback;
                Intent intent = new Intent("android.intent.action.GET_CONTENT");
                intent.addCategory("android.intent.category.OPENABLE");
                intent.setType("*/*");
                intent.putExtra("android.intent.extra.ALLOW_MULTIPLE", fileChooserParams.getMode() == 1);
                WebxdcActivity webxdcActivity = WebxdcActivity.this;
                webxdcActivity.startActivityForResult(Intent.createChooser(intent, webxdcActivity.getString(R.string.select)), WebxdcActivity.REQUEST_CODE_FILE_PICKER);
                return true;
            }
        });
        DcEventCenter eventCenter = DcHelper.getEventCenter(getApplicationContext());
        eventCenter.addObserver(2120, this);
        eventCenter.addObserver(2000, this);
        eventCenter.addObserver(2150, this);
        int i = extras.getInt(EXTRA_APP_MSG_ID);
        int i2 = extras.getInt(EXTRA_ACCOUNT_ID);
        DcContext context = DcHelper.getContext(getApplicationContext());
        this.dcContext = context;
        if (i2 != context.getAccountId()) {
            AccountManager.getInstance().switchAccount(getApplicationContext(), i2);
            this.dcContext = DcHelper.getContext(getApplicationContext());
        }
        DcMsg msg = this.dcContext.getMsg(i);
        this.dcAppMsg = msg;
        if (!msg.isOk()) {
            Toast.makeText((Context) this, (CharSequence) "Webxdc does no longer exist.", 1).show();
            finish();
            return;
        }
        this.baseURL = "https://acc" + this.dcContext.getAccountId() + "-msg" + i + ".localhost";
        final JSONObject webxdcInfo = this.dcAppMsg.getWebxdcInfo();
        this.internetAccess = JsonUtils.optBoolean(webxdcInfo, "internet_access");
        this.selfAddr = webxdcInfo.optString("self_addr");
        this.sendUpdateMaxSize = webxdcInfo.optInt("send_update_max_size");
        this.sendUpdateInterval = webxdcInfo.optInt("send_update_interval");
        toggleFakeProxy(!this.internetAccess);
        WebSettings settings = this.webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setAllowFileAccess(false);
        settings.setBlockNetworkLoads(!this.internetAccess);
        settings.setAllowContentAccess(false);
        settings.setGeolocationEnabled(false);
        settings.setAllowFileAccessFromFileURLs(false);
        settings.setAllowUniversalAccessFromFileURLs(false);
        settings.setDatabaseEnabled(true);
        settings.setDomStorageEnabled(true);
        this.webView.setNetworkAvailable(this.internetAccess);
        this.webView.addJavascriptInterface(new InternalJSApi(), "InternalJSApi");
        String str = "";
        String string = extras.getString(EXTRA_HREF, "");
        if (TextUtils.isEmpty(string)) {
            string = "index.html";
        }
        try {
            str = URLEncoder.encode(this.baseURL + "/" + string, Charsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        final long currentTimeMillis = System.currentTimeMillis() - lastOpenTime;
        StringBuilder sb = new StringBuilder();
        sb.append(this.baseURL);
        sb.append("/webxdc_bootstrap324567869.html?i=");
        sb.append(this.internetAccess ? "1" : "0");
        sb.append("&href=");
        sb.append(str);
        final String sb2 = sb.toString();
        Util.runOnAnyBackgroundThread(new Runnable() {
            @Override
            public final void run() {
                WebxdcActivity.this.m1315lambda$onCreate$1$orgthoughtcrimesecuresmsWebxdcActivity(currentTimeMillis, sb2);
            }
        });
        Util.runOnAnyBackgroundThread(new Runnable() {
            @Override
            public final void run() {
                WebxdcActivity.this.m1317lambda$onCreate$3$orgthoughtcrimesecuresmsWebxdcActivity(webxdcInfo);
            }
        });
    }

    void m1315lambda$onCreate$1$orgthoughtcrimesecuresmsWebxdcActivity(long j, final String str) {
        if (j < 2000) {
            Util.sleep(1000L);
        }
        Util.runOnMain(new Runnable() {
            @Override
            public final void run() {
                WebxdcActivity.this.m1314lambda$onCreate$0$orgthoughtcrimesecuresmsWebxdcActivity(str);
            }
        });
    }

    void m1314lambda$onCreate$0$orgthoughtcrimesecuresmsWebxdcActivity(String str) {
        this.webView.loadUrl(str);
    }

    void m1317lambda$onCreate$3$orgthoughtcrimesecuresmsWebxdcActivity(final JSONObject jSONObject) {
        final DcChat chat = this.dcContext.getChat(this.dcAppMsg.getChatId());
        Util.runOnMain(new Runnable() {
            @Override
            public final void run() {
                WebxdcActivity.this.m1316lambda$onCreate$2$orgthoughtcrimesecuresmsWebxdcActivity(jSONObject, chat);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        DcHelper.getNotificationCenter(this).updateVisibleWebxdc(this.dcContext.getAccountId(), this.dcAppMsg.getId());
    }

    @Override
    protected void onPause() {
        super.onPause();
        DcHelper.getNotificationCenter(this).clearVisibleWebxdc();
    }

    @Override
    protected void onDestroy() {
        lastOpenTime = System.currentTimeMillis();
        DcHelper.getEventCenter(getApplicationContext()).removeObservers(this);
        leaveRealtimeChannel();
        super.onDestroy();
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.clear();
        getMenuInflater().inflate(R.menu.webxdc, menu);
        menu.findItem(R.id.source_code).setVisible(!this.sourceCodeUrl.isEmpty());
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        super.onOptionsItemSelected(menuItem);
        int itemId = menuItem.getItemId();
        if (itemId == R.id.menu_add_to_home_screen) {
            addToHomeScreen(this, this.dcAppMsg.getId());
            return true;
        }
        if (itemId == R.id.source_code) {
            IntentUtils.showInBrowser(this, this.sourceCodeUrl);
            return true;
        }
        if (itemId != R.id.show_in_chat) {
            return false;
        }
        showInChat();
        return true;
    }

    public void onConfigurationChanged(Configuration configuration) {
        Log.i(TAG, "onConfigurationChanged(" + configuration.orientation + ")");
        super.onConfigurationChanged(configuration);
        setScreenMode(configuration);
    }

    private void setScreenMode(Configuration configuration) {
        boolean z = configuration.orientation == 2 && !getResources().getBoolean(R.bool.isBigScreen);
        getWindow().getDecorView().setSystemUiVisibility(z ? 4 : 0);
        ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            if (this.hideActionBar || z) {
                supportActionBar.hide();
            } else {
                supportActionBar.show();
            }
        }
    }

    @Override
    protected boolean openOnlineUrl(String str) {
        Log.i(TAG, "openOnlineUrl: " + str);
        if (str.startsWith("mailto:") || str.startsWith("openpgp4fpr:")) {
            return super.openOnlineUrl(str);
        }
        return !this.internetAccess;
    }

    @Override
    protected android.webkit.WebResourceResponse interceptRequest(java.lang.String r11) {
        throw new UnsupportedOperationException("Method not decompiled: org.thoughtcrime.securesms.WebxdcActivity.interceptRequest(java.lang.String):android.webkit.WebResourceResponse");
    }

    private void callJavaScriptFunction(String str) {
        this.webView.evaluateJavascript("document.getElementById('frame').contentWindow." + str + ";", null);
    }

    @Override
    public void handleEvent(DcEvent dcEvent) {
        int id = dcEvent.getId();
        if (id == 2120 && dcEvent.getData1Int() == this.dcAppMsg.getId()) {
            Log.i(TAG, "handling status update event");
            callJavaScriptFunction("__webxdcUpdate()");
            return;
        }
        if (id == 2150 && dcEvent.getData1Int() == this.dcAppMsg.getId()) {
            Log.i(TAG, "handling realtime data event");
            StringBuilder sb = new StringBuilder();
            for (byte b : dcEvent.getData2Blob()) {
                sb.append(((int) b) + ",");
            }
            callJavaScriptFunction("__webxdcRealtimeData([" + ((Object) sb) + "])");
            return;
        }
        if (id == 2000 && dcEvent.getData2Int() == this.dcAppMsg.getId()) {
            this.dcAppMsg = this.dcContext.getMsg(dcEvent.getData2Int());
            Util.runOnAnyBackgroundThread(new Runnable() {
                @Override
                public final void run() {
                    WebxdcActivity.this.m1313lambda$handleEvent$5$orgthoughtcrimesecuresmsWebxdcActivity();
                }
            });
        }
    }

    void m1313lambda$handleEvent$5$orgthoughtcrimesecuresmsWebxdcActivity() {
        final JSONObject webxdcInfo = this.dcAppMsg.getWebxdcInfo();
        final DcChat chat = this.dcContext.getChat(this.dcAppMsg.getChatId());
        Util.runOnMain(new Runnable() {
            @Override
            public final void run() {
                WebxdcActivity.this.m1312lambda$handleEvent$4$orgthoughtcrimesecuresmsWebxdcActivity(webxdcInfo, chat);
            }
        });
    }

    public void m1316lambda$onCreate$2$orgthoughtcrimesecuresmsWebxdcActivity(JSONObject jSONObject, DcChat dcChat) {
        String optString = JsonUtils.optString(jSONObject, "document");
        String optString2 = JsonUtils.optString(jSONObject, "name");
        String optString3 = JsonUtils.optString(jSONObject, "source_code_url");
        ActionBar supportActionBar = getSupportActionBar();
        StringBuilder sb = new StringBuilder();
        if (optString.isEmpty()) {
            optString = optString2;
        }
        sb.append(optString);
        sb.append(" – ");
        sb.append(dcChat.getName());
        supportActionBar.setTitle(sb.toString());
        if (this.sourceCodeUrl.equals(optString3)) {
            return;
        }
        this.sourceCodeUrl = optString3;
        invalidateOptionsMenu();
    }

    private void showInChat() {
        Intent intent = new Intent((Context) this, (Class<?>) ConversationActivity.class);
        intent.putExtra("chat_id", this.dcAppMsg.getChatId());
        intent.putExtra(ConversationActivity.STARTING_POSITION_EXTRA, DcMsg.getMessagePosition(this.dcAppMsg, this.dcContext));
        startActivity(intent);
    }

    public static void addToHomeScreen(Activity activity, int i) {
        Context applicationContext = activity.getApplicationContext();
        try {
            DcContext context = DcHelper.getContext(applicationContext);
            DcMsg msg = context.getMsg(i);
            JSONObject webxdcInfo = msg.getWebxdcInfo();
            String optString = JsonUtils.optString(webxdcInfo, "document");
            String optString2 = JsonUtils.optString(webxdcInfo, "name");
            Bitmap bitmap = ((BitmapDrawable) Drawable.createFromStream(new ByteArrayInputStream(msg.getWebxdcBlob(JsonUtils.optString(webxdcInfo, "icon"))), "icon")).getBitmap();
            ShortcutInfoCompat.Builder builder = new ShortcutInfoCompat.Builder(applicationContext, "xdc-" + context.getAccountId() + "-" + i);
            if (optString.isEmpty()) {
                optString = optString2;
            }
            ShortcutInfoCompat build = builder.setShortLabel(optString).setIcon(IconCompat.createWithBitmap(bitmap)).setIntents(getWebxdcIntentWithParentStack(applicationContext, i)).build();
            Toast.makeText(applicationContext, R.string.one_moment, 0).show();
            if (ShortcutManagerCompat.requestPinShortcut(applicationContext, build, (IntentSender) null)) {
                return;
            }
            Toast.makeText(applicationContext, "ErrAddToHomescreen: requestPinShortcut() failed", 1).show();
        } catch (Exception e) {
            Toast.makeText(applicationContext, "ErrAddToHomescreen: " + e, 1).show();
        }
    }

    public void onActivityResult(int i, int i2, Intent intent) {
        Uri[] uriArr;
        if (i == REQUEST_CODE_FILE_PICKER && this.filePathCallback != null) {
            if (i2 == -1 && intent != null) {
                try {
                    if (intent.getDataString() != null) {
                        uriArr = new Uri[]{Uri.parse(intent.getDataString())};
                    } else if (intent.getClipData() != null) {
                        int itemCount = intent.getClipData().getItemCount();
                        uriArr = new Uri[itemCount];
                        for (int i3 = 0; i3 < itemCount; i3++) {
                            try {
                                uriArr[i3] = intent.getClipData().getItemAt(i3).getUri();
                            } catch (Exception e) {
                                e = e;
                                e.printStackTrace();
                                this.filePathCallback.onReceiveValue(uriArr);
                                this.filePathCallback = null;
                                super.onActivityResult(i, i2, intent);
                            }
                        }
                    }
                } catch (Exception e2) {
                    e = e2;
                    uriArr = null;
                }
                this.filePathCallback.onReceiveValue(uriArr);
                this.filePathCallback = null;
            }
            uriArr = null;
            this.filePathCallback.onReceiveValue(uriArr);
            this.filePathCallback = null;
        }
        super.onActivityResult(i, i2, intent);
    }

    public void leaveRealtimeChannel() {
        try {
            this.rpc.leaveWebxdcRealtime(Integer.valueOf(this.dcContext.getAccountId()), Integer.valueOf(this.dcAppMsg.getId()));
        } catch (RpcException e) {
            e.printStackTrace();
        }
    }

    class InternalJSApi {
        InternalJSApi() {
        }

        @JavascriptInterface
        public int sendUpdateMaxSize() {
            return WebxdcActivity.this.sendUpdateMaxSize;
        }

        @JavascriptInterface
        public int sendUpdateInterval() {
            return WebxdcActivity.this.sendUpdateInterval;
        }

        @JavascriptInterface
        public String selfAddr() {
            return WebxdcActivity.this.selfAddr;
        }

        @JavascriptInterface
        public String selfName() {
            return WebxdcActivity.this.dcContext.getName();
        }

        @JavascriptInterface
        public boolean sendStatusUpdate(String str) {
            String lastError;
            Log.i(WebxdcActivity.TAG, "sendStatusUpdate");
            if (WebxdcActivity.this.dcContext.sendWebxdcStatusUpdate(WebxdcActivity.this.dcAppMsg.getId(), str)) {
                return true;
            }
            DcChat chat = WebxdcActivity.this.dcContext.getChat(WebxdcActivity.this.dcAppMsg.getChatId());
            SearchView.OnQueryTextListener onQueryTextListener = WebxdcActivity.this;
            if (!chat.isContactRequest()) {
                lastError = WebxdcActivity.this.dcContext.getLastError();
            } else {
                lastError = WebxdcActivity.this.getString(R.string.accept_request_first);
            }
            Toast.makeText((Context) onQueryTextListener, (CharSequence) lastError, 1).show();
            return false;
        }

        @JavascriptInterface
        public String getStatusUpdates(int i) {
            Log.i(WebxdcActivity.TAG, "getStatusUpdates");
            return WebxdcActivity.this.dcContext.getWebxdcStatusUpdates(WebxdcActivity.this.dcAppMsg.getId(), i);
        }

        @JavascriptInterface
        public String sendToChat(String str) {
            byte[] bArr;
            String str2;
            Log.i(WebxdcActivity.TAG, "sendToChat");
            try {
                JSONObject jSONObject = new JSONObject(str);
                if (jSONObject.has("base64")) {
                    bArr = Base64.decode(jSONObject.getString("base64"), 3);
                    str2 = jSONObject.getString("name");
                } else {
                    bArr = null;
                    str2 = null;
                }
                String string = jSONObject.has("text") ? jSONObject.getString("text") : null;
                if (TextUtils.isEmpty(string) && TextUtils.isEmpty(str2)) {
                    return "provided file is invalid, you need to set both name and base64 content";
                }
                DcHelper.sendToChat(WebxdcActivity.this, bArr, MediaUtil.OCTET, str2, string);
                return null;
            } catch (Exception e) {
                e.printStackTrace();
                return e.toString();
            }
        }

        @JavascriptInterface
        public void sendRealtimeAdvertisement() {
            try {
                WebxdcActivity.this.rpc.sendWebxdcRealtimeAdvertisement(Integer.valueOf(WebxdcActivity.this.dcContext.getAccountId()), Integer.valueOf(WebxdcActivity.this.dcAppMsg.getId()));
            } catch (RpcException e) {
                e.printStackTrace();
            }
        }

        @JavascriptInterface
        public void leaveRealtimeChannel() {
            WebxdcActivity.this.leaveRealtimeChannel();
        }

        @JavascriptInterface
        public void sendRealtimeData(String str) {
            int accountId = WebxdcActivity.this.dcContext.getAccountId();
            int id = WebxdcActivity.this.dcAppMsg.getId();
            try {
                WebxdcActivity.this.rpc.sendWebxdcRealtimeData(Integer.valueOf(accountId), Integer.valueOf(id), Arrays.asList((Integer[]) JsonUtils.fromJson(str, Integer[].class)));
            } catch (IOException | RpcException e) {
                e.printStackTrace();
            }
        }
    }
}