<commit_before>package org.edx.mobile.view.custom;

import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import org.apache.http.protocol.HTTP;
import org.edx.mobile.logger.Logger;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by rohan on 2/2/15.
 *
 * This class represents a custom {@link android.webkit.WebViewClient}.
 * This class is responsible for setting up a given {@link android.webkit.WebView}, assign itself
 * as a {@link android.webkit.WebViewClient} delegate and to intercept URLs being loaded.
 * Depending on the form of URL, this client may forward URL back to the app.
 *
 * This implementation detects host of the first URL being loaded. Further, if any URL intercepted has a different host
 * than the current one, then treats it as an external link and may open in external browser.
 *
 */
public abstract class URLInterceptorWebViewClient extends WebViewClient {

    // URL forms to be intercepted
    private static final String URL_TYPE_ENROLL         = "edxapp://enroll";
    private static final String URL_TYPE_COURSE_INFO    = "edxapp://course_info";
    public static final String PARAM_PATH_ID           = "path_id";
    public static final String COURSE                  = "course/";

    private Logger logger = new Logger(URLInterceptorWebViewClient.class);
    private IActionListener actionListener;
    private IPageStatusListener pageStatusListener;
    private String hostForThisPage = null;

    public URLInterceptorWebViewClient(WebView webView) {
        setupWebView(webView);
    }

    /**
     * Sets action listener for this client. Use this method to get callbacks
     * of actions as declared in {@link org.edx.mobile.view.custom.URLInterceptorWebViewClient.IActionListener}.
     * @param actionListener
     */
    public void setActionListener(IActionListener actionListener) {
        this.actionListener = actionListener;
    }

    /**
     * Gives page status callbacks like page loading started, finished or error.
     * @param pageStatusListener
     */
    public void setPageStatusListener(IPageStatusListener pageStatusListener) {
        this.pageStatusListener = pageStatusListener;
    }

    /**
     * Sets up the WeView, applies minimal required settings and
     * sets this class itself as WebViewClient.
     * @param webView
     */
    private void setupWebView(WebView webView) {
        webView.setWebViewClient(this);
        //We need to hide the loading progress if the Page starts rendering.
        webView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                if (progress > 50) {
                    if (pageStatusListener != null) {
                        pageStatusListener.onPagePartiallyLoaded();
                    }
                }
            }
        });
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);

        try {
            // hold on the host of this page, just once
            if (this.hostForThisPage == null) {
                this.hostForThisPage = Uri.parse(url).getHost();
            }
        } catch(Exception ex) {
            logger.error(ex);
        }

        if (pageStatusListener != null) {
            pageStatusListener.onPageStarted();
        }
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

        if (pageStatusListener != null) {
            pageStatusListener.onPageFinished();
        }
    }

    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);
        if (pageStatusListener != null) {
            pageStatusListener.onPageLoadError();
        }
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        try {
            if (actionListener == null) {
                logger.warn("you have not set IActionLister to this WebViewClient, " +
                        "you might miss some event");
            }
            logger.debug("loading: " + url);

            if (isCourseInfoLink(url)) {
                // we handled this URL
                return true;
            } else if(isEnrollLink(url)) {
                // we handled this URL
                return true;
            } else if (isExternalLink(url)) {
                // open URL in external web browser
                // return true means the host application handles the url
                // this should open the URL in the browser with user's confirmation
                view.stopLoading();
                // let activity handle this
                onOpenExternalURL(url);
                return false;
            } else {
                // return false means the current WebView handles the url.
                return false;
            }
        } catch(Exception ex) {
            logger.error(ex);
        }
        return super.shouldOverrideUrlLoading(view, url);
    }

    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
        if (isExternalLink(url)) {
            return new WebResourceResponse("text/html", HTTP.UTF_8, null);
        }
        return super.shouldInterceptRequest(view, url);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        if (isExternalLink(request.getUrl().toString())) {
            return new WebResourceResponse("text/html", HTTP.UTF_8, null);
        }
        return super.shouldInterceptRequest(view, request);
    }

    /**
     * Checks if the URL pattern matches with that of COURSE_INFO URL.<commit_msg>Suppress links only when zero rated network<commit_after>package org.edx.mobile.view.custom;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import org.apache.http.protocol.HTTP;
import org.edx.mobile.logger.Logger;
import org.edx.mobile.util.NetworkUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by rohan on 2/2/15.
 *
 * This class represents a custom {@link android.webkit.WebViewClient}.
 * This class is responsible for setting up a given {@link android.webkit.WebView}, assign itself
 * as a {@link android.webkit.WebViewClient} delegate and to intercept URLs being loaded.
 * Depending on the form of URL, this client may forward URL back to the app.
 *
 * This implementation detects host of the first URL being loaded. Further, if any URL intercepted has a different host
 * than the current one, then treats it as an external link and may open in external browser.
 *
 */
public abstract class URLInterceptorWebViewClient extends WebViewClient {

    // URL forms to be intercepted
    private static final String URL_TYPE_ENROLL         = "edxapp://enroll";
    private static final String URL_TYPE_COURSE_INFO    = "edxapp://course_info";
    public static final String PARAM_PATH_ID           = "path_id";
    public static final String COURSE                  = "course/";

    private Logger logger = new Logger(URLInterceptorWebViewClient.class);
    private IActionListener actionListener;
    private IPageStatusListener pageStatusListener;
    private String hostForThisPage = null;

    public URLInterceptorWebViewClient(WebView webView) {
        setupWebView(webView);
    }

    /**
     * Sets action listener for this client. Use this method to get callbacks
     * of actions as declared in {@link org.edx.mobile.view.custom.URLInterceptorWebViewClient.IActionListener}.
     * @param actionListener
     */
    public void setActionListener(IActionListener actionListener) {
        this.actionListener = actionListener;
    }

    /**
     * Gives page status callbacks like page loading started, finished or error.
     * @param pageStatusListener
     */
    public void setPageStatusListener(IPageStatusListener pageStatusListener) {
        this.pageStatusListener = pageStatusListener;
    }

    /**
     * Sets up the WeView, applies minimal required settings and
     * sets this class itself as WebViewClient.
     * @param webView
     */
    private void setupWebView(WebView webView) {
        webView.setWebViewClient(this);
        //We need to hide the loading progress if the Page starts rendering.
        webView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                if (progress > 50) {
                    if (pageStatusListener != null) {
                        pageStatusListener.onPagePartiallyLoaded();
                    }
                }
            }
        });
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);

        try {
            // hold on the host of this page, just once
            if (this.hostForThisPage == null) {
                this.hostForThisPage = Uri.parse(url).getHost();
            }
        } catch(Exception ex) {
            logger.error(ex);
        }

        if (pageStatusListener != null) {
            pageStatusListener.onPageStarted();
        }
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

        if (pageStatusListener != null) {
            pageStatusListener.onPageFinished();
        }
    }

    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);
        if (pageStatusListener != null) {
            pageStatusListener.onPageLoadError();
        }
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        try {
            if (actionListener == null) {
                logger.warn("you have not set IActionLister to this WebViewClient, " +
                        "you might miss some event");
            }
            logger.debug("loading: " + url);

            if (isCourseInfoLink(url)) {
                // we handled this URL
                return true;
            } else if(isEnrollLink(url)) {
                // we handled this URL
                return true;
            } else if (isExternalLink(url)) {
                // open URL in external web browser
                // return true means the host application handles the url
                // this should open the URL in the browser with user's confirmation
                view.stopLoading();
                // let activity handle this
                onOpenExternalURL(url);
                return false;
            } else {
                // return false means the current WebView handles the url.
                return false;
            }
        } catch(Exception ex) {
            logger.error(ex);
        }
        return super.shouldOverrideUrlLoading(view, url);
    }

    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
        Context context = view.getContext().getApplicationContext();

        if (isExternalLink(url)
                && NetworkUtil.isOnZeroRatedNetwork(context)
                && NetworkUtil.isConnectedMobile(context)) {
            return new WebResourceResponse("text/html", HTTP.UTF_8, null);
        }
        return super.shouldInterceptRequest(view, url);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        Context context = view.getContext().getApplicationContext();

        if (isExternalLink(request.getUrl().toString())
                && NetworkUtil.isOnZeroRatedNetwork(context)
                && NetworkUtil.isConnectedMobile(context)) {
            return new WebResourceResponse("text/html", HTTP.UTF_8, null);
        }
        return super.shouldInterceptRequest(view, request);
    }

    /**
     * Checks if the URL pattern matches with that of COURSE_INFO URL.
{'fraction_non_alphanumeric': 0.07988072818581293, 'fraction_numerical': 0.0012554927809165098, 'mean_word_length': 2.356597313668686, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6545060', 'n_tokens_mistral': 3322, 'n_tokens_neox': 3196, 'n_words': 965}