aboutsummaryrefslogtreecommitdiff
path: root/libs/editor/WordPressEditor/src/main/java/org/wordpress/android/editor/EditorWebViewAbstract.java
blob: 64ded937d6444feb9a9256192cd5886192e1e1fa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package org.wordpress.android.editor;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.ConsoleMessage.MessageLevel;
import android.webkit.JsResult;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import org.wordpress.android.util.AppLog;
import org.wordpress.android.util.AppLog.T;
import org.wordpress.android.util.HTTPUtils;
import org.wordpress.android.util.StringUtils;
import org.wordpress.android.util.ToastUtils;
import org.wordpress.android.util.UrlUtils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * A text editor WebView with support for JavaScript execution.
 */
public abstract class EditorWebViewAbstract extends WebView {
    public abstract void execJavaScriptFromString(String javaScript);

    private OnImeBackListener mOnImeBackListener;
    private AuthHeaderRequestListener mAuthHeaderRequestListener;
    private ErrorListener mErrorListener;
    private JsCallbackReceiver mJsCallbackReceiver;
    private boolean mDebugModeEnabled;

    private Map<String, String> mHeaderMap = new HashMap<>();

    public EditorWebViewAbstract(Context context, AttributeSet attrs) {
        super(context, attrs);
        configureWebView();
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void configureWebView() {
        WebSettings webSettings = this.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDefaultTextEncodingName("utf-8");

        this.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url != null && url.startsWith("callback") && mJsCallbackReceiver != null) {
                    String data = URLDecoder.decode(url);
                    String[] split = data.split(":", 2);
                    String callbackId = split[0];
                    String params = (split.length > 1 ? split[1] : "");
                    mJsCallbackReceiver.executeCallback(callbackId, params);
                }
                return true;
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                AppLog.e(T.EDITOR, description);
            }

            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                String url = request.getUrl().toString();

                if (!URLUtil.isNetworkUrl(url)) {
                    return super.shouldInterceptRequest(view, request);
                }

                // Request and add an authorization header for HTTPS resource requests.
                // Use https:// when requesting the auth header, in case the resource is incorrectly using http://.
                // If an auth header is returned, force https:// for the actual HTTP request.
                String authHeader = mAuthHeaderRequestListener.onAuthHeaderRequested(UrlUtils.makeHttps(url));
                if (StringUtils.notNullStr(authHeader).length() > 0) {
                    try {
                        url = UrlUtils.makeHttps(url);

                        // Keep any existing request headers from the WebResourceRequest
                        Map<String, String> headerMap = request.getRequestHeaders();
                        for (Map.Entry<String, String> entry : mHeaderMap.entrySet()) {
                            headerMap.put(entry.getKey(), entry.getValue());
                        }
                        headerMap.put("Authorization", authHeader);

                        HttpURLConnection conn = HTTPUtils.setupUrlConnection(url, headerMap);
                        return new WebResourceResponse(conn.getContentType(), conn.getContentEncoding(),
                                conn.getInputStream());
                    } catch (IOException e) {
                        AppLog.e(T.EDITOR, e);
                    }
                }

                return super.shouldInterceptRequest(view, request);
            }

            /**
             * Compatibility method for API < 21
             */
            @SuppressWarnings("deprecation")
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                if (!URLUtil.isNetworkUrl(url)) {
                    return super.shouldInterceptRequest(view, url);
                }

                // Request and add an authorization header for HTTPS resource requests.
                // Use https:// when requesting the auth header, in case the resource is incorrectly using http://.
                // If an auth header is returned, force https:// for the actual HTTP request.
                String authHeader = mAuthHeaderRequestListener.onAuthHeaderRequested(UrlUtils.makeHttps(url));
                if (StringUtils.notNullStr(authHeader).length() > 0) {
                    try {
                        url = UrlUtils.makeHttps(url);

                        Map<String, String> headerMap = new HashMap<>(mHeaderMap);
                        headerMap.put("Authorization", authHeader);

                        HttpURLConnection conn = HTTPUtils.setupUrlConnection(url, headerMap);
                        return new WebResourceResponse(conn.getContentType(), conn.getContentEncoding(),
                                conn.getInputStream());
                    } catch (IOException e) {
                        AppLog.e(T.EDITOR, e);
                    }
                }

                return super.shouldInterceptRequest(view, url);
            }
        });

        this.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onConsoleMessage(@NonNull ConsoleMessage cm) {
                if (cm.messageLevel() == MessageLevel.ERROR) {
                    if (mErrorListener != null) {
                        mErrorListener.onJavaScriptError(cm.sourceId(), cm.lineNumber(), cm.message());
                    }
                    AppLog.e(T.EDITOR, cm.message() + " -- From line " + cm.lineNumber() + " of " + cm.sourceId());
                } else {
                    AppLog.d(T.EDITOR, cm.message() + " -- From line " + cm.lineNumber() + " of " + cm.sourceId());
                }
                return true;
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                AppLog.d(T.EDITOR, message);
                if (mErrorListener != null) {
                    mErrorListener.onJavaScriptAlert(url, message);
                }
                return true;
            }
        });
    }

    @Override
    public boolean onCheckIsTextEditor() {
        return true;
    }

    @Override
    public void setVisibility(int visibility) {
        notifyVisibilityChanged(visibility == View.VISIBLE);
        super.setVisibility(visibility);
    }


    public boolean shouldSwitchToCompatibilityMode() {
        return false;
    }

    public void setDebugModeEnabled(boolean enabled) {
        mDebugModeEnabled = enabled;
    }

    /**
     * Handles events that should be triggered when the WebView is hidden or is shown to the user
     *
     * @param visible the new visibility status of the WebView
     */
    public void notifyVisibilityChanged(boolean visible) {
        if (!visible) {
            this.post(new Runnable() {
                @Override
                public void run() {
                    execJavaScriptFromString("ZSSEditor.pauseAllVideos();");
                }
            });
        }
    }

    public void setOnImeBackListener(OnImeBackListener listener) {
        mOnImeBackListener = listener;
    }

    public void setAuthHeaderRequestListener(AuthHeaderRequestListener listener) {
        mAuthHeaderRequestListener = listener;
    }

    /**
     * Used on API<17 to handle callbacks as a safe alternative to JavascriptInterface (which has security risks
     * at those API levels).
     */
    public void setJsCallbackReceiver(JsCallbackReceiver jsCallbackReceiver) {
        mJsCallbackReceiver = jsCallbackReceiver;
    }

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            if (mOnImeBackListener != null) {
                mOnImeBackListener.onImeBack();
            }
        }
        if (mDebugModeEnabled && event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP
            && event.getAction() == KeyEvent.ACTION_DOWN) {
            // Log the raw html
            execJavaScriptFromString("console.log(document.body.innerHTML);");
            ToastUtils.showToast(getContext(), "Debug: Raw HTML has been logged");
            return true;
        }
        return super.onKeyPreIme(keyCode, event);
    }

    public void setCustomHeader(String name, String value) {
        mHeaderMap.put(name, value);
    }

    public void setErrorListener(ErrorListener errorListener) {
        mErrorListener = errorListener;
    }

    public interface AuthHeaderRequestListener {
        String onAuthHeaderRequested(String url);
    }

    public interface ErrorListener {
        void onJavaScriptError(String sourceFile, int lineNumber, String message);
        void onJavaScriptAlert(String url, String message);
    }
}