<commit_before>/*
 * WebViewActivity.java
 * SDKLauncher-Android
 *
 * Created by <NAME> (Mantano) on 2013-07-10.
 */
//  Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//  Redistribution and use in source and binary forms, with or without modification, 
//  are permitted provided that the following conditions are met:
//  1. Redistributions of source code must retain the above copyright notice, this 
//  list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice, 
//  this list of conditions and the following disclaimer in the documentation and/or 
//  other materials provided with the distribution.
//  3. Neither the name of the organization nor the names of its contributors may be 
//  used to endorse or promote products derived from this software without specific 
//  prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
//  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
//  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
//  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
//  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
//  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
//  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
//  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
//  OF THE POSSIBILITY OF SUCH DAMAGE

package org.readium.sdk.android.launcher;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.readium.sdk.android.Container;
import org.readium.sdk.android.ManifestItem;
import org.readium.sdk.android.Package;
import org.readium.sdk.android.SpineItem;
import org.readium.sdk.android.launcher.model.BookmarkDatabase;
import org.readium.sdk.android.launcher.model.OpenPageRequest;
import org.readium.sdk.android.launcher.model.Page;
import org.readium.sdk.android.launcher.model.PaginationInfo;
import org.readium.sdk.android.launcher.model.ReadiumJSApi;
import org.readium.sdk.android.launcher.model.ViewerSettings;
import org.readium.sdk.android.launcher.util.EpubServer;
import org.readium.sdk.android.launcher.util.EpubServer.DataPreProcessor;
import org.readium.sdk.android.launcher.util.HTMLUtil;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.VideoView;

public class WebViewActivity extends FragmentActivity implements
		ViewerSettingsDialog.OnViewerSettingsChange {

	private final boolean quiet = false;

	private static final String TAG = "WebViewActivity";
	private static final String ASSET_PREFIX = "file:///android_asset/readium-shared-js/";
	private static final String READER_SKELETON = "file:///android_asset/readium-shared-js/reader.html";

	// Installs "hook" function so that top-level window (application) can later
	// inject the window.navigator.epubReadingSystem into this HTML document's
	// iframe
	private static final String INJECT_EPUB_RSO_SCRIPT_1 = ""
			+ "window.readium_set_epubReadingSystem = function (obj) {"
			+ "\nwindow.navigator.epubReadingSystem = obj;"
			+ "\nwindow.readium_set_epubReadingSystem = undefined;"
			+ "\nvar el1 = document.getElementById(\"readium_epubReadingSystem_inject1\");"
			+ "\nif (el1 && el1.parentNode) { el1.parentNode.removeChild(el1); }"
			+ "\nvar el2 = document.getElementById(\"readium_epubReadingSystem_inject2\");"
			+ "\nif (el2 && el2.parentNode) { el2.parentNode.removeChild(el2); }"
			+ "\n};";

	// Iterate top-level iframes, inject global
	// window.navigator.epubReadingSystem if the expected hook function exists (
	// readium_set_epubReadingSystem() ).
	private static final String INJECT_EPUB_RSO_SCRIPT_2 = ""
			+ "var epubRSInject =\nfunction(win) {"
			+ "\nvar ret = '';"
			+ "\nret += win.location.href;"
			+ "\nret += ' ---- ';"
			+
			// "\nret += JSON.stringify(win.navigator.epubReadingSystem);" +
			// "\nret += ' ---- ';" +
			"\nif (win.frames)"
			+ "\n{"
			+ "\nfor (var i = 0; i < win.frames.length; i++)"
			+ "\n{"
			+ "\nvar iframe = win.frames[i];"
			+ "\nret += ' IFRAME ';"
			+ "\nif (iframe.readium_set_epubReadingSystem)"
			+ "\n{"
			+ "\nret += ' EPBRS ';"
			+ "\niframe.readium_set_epubReadingSystem(window.navigator.epubReadingSystem);"
			+ "\n}" + "\nret += epubRSInject(iframe);" + "\n}" + "\n}"
			+ "\nreturn ret;" + "\n};" + "\nepubRSInject(window);";

	// Script tag to inject the "hook" function installer script, added to the
	// head of every epub iframe document
	private static final String INJECT_HEAD_EPUB_RSO_1 = ""
			+ "<script id=\"readium_epubReadingSystem_inject1\" type=\"text/javascript\">\n"
			+ "//<![CDATA[\n" + INJECT_EPUB_RSO_SCRIPT_1 + "\n" + "//]]>\n"
			+ "</script>";
	// Script tag that generates an HTTP request to a fake script => triggers
	// push of window.navigator.epubReadingSystem into this HTML document's
	// iframe
	private static final String INJECT_HEAD_EPUB_RSO_2 = ""
			+ "<script id=\"readium_epubReadingSystem_inject2\" type=\"text/javascript\" "
			+ "src=\"/%d/readium_epubReadingSystem_inject.js\"> </script>";
	// Script tag to load the mathjax script payload, added to the head of epub
	// iframe documents, only if <math> tags are detected
	private static final String INJECT_HEAD_MATHJAX = "<script type=\"text/javascript\" src=\"/readium_MathJax.js\"> </script>";

	// Location of payloads in the asset folder
	private static final String PAYLOAD_MATHJAX_ASSET = "reader-payloads/MathJax.js";
	private static final String PAYLOAD_ANNOTATIONS_CSS_ASSET = "reader-payloads/annotations.css";

	private final DataPreProcessor dataPreProcessor = new DataPreProcessor() {

		@Override
		public byte[] handle(byte[] data, String mime, String uriPath,
				ManifestItem item) {
			if (mime == null
					|| (mime != "text/html" && mime != "application/xhtml+xml")) {
				return null;
			}<commit_msg>Android launcher: added try+catch for navigator.epubReadingSystem injection, see https://github.com/readium/SDKLauncher-Android/issues/128<commit_after>/*
 * WebViewActivity.java
 * SDKLauncher-Android
 *
 * Created by <NAME> (Mantano) on 2013-07-10.
 */
//  Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//  Redistribution and use in source and binary forms, with or without modification, 
//  are permitted provided that the following conditions are met:
//  1. Redistributions of source code must retain the above copyright notice, this 
//  list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice, 
//  this list of conditions and the following disclaimer in the documentation and/or 
//  other materials provided with the distribution.
//  3. Neither the name of the organization nor the names of its contributors may be 
//  used to endorse or promote products derived from this software without specific 
//  prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
//  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
//  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
//  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
//  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
//  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
//  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
//  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
//  OF THE POSSIBILITY OF SUCH DAMAGE

package org.readium.sdk.android.launcher;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.readium.sdk.android.Container;
import org.readium.sdk.android.ManifestItem;
import org.readium.sdk.android.Package;
import org.readium.sdk.android.SpineItem;
import org.readium.sdk.android.launcher.model.BookmarkDatabase;
import org.readium.sdk.android.launcher.model.OpenPageRequest;
import org.readium.sdk.android.launcher.model.Page;
import org.readium.sdk.android.launcher.model.PaginationInfo;
import org.readium.sdk.android.launcher.model.ReadiumJSApi;
import org.readium.sdk.android.launcher.model.ViewerSettings;
import org.readium.sdk.android.launcher.util.EpubServer;
import org.readium.sdk.android.launcher.util.EpubServer.DataPreProcessor;
import org.readium.sdk.android.launcher.util.HTMLUtil;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.VideoView;

public class WebViewActivity extends FragmentActivity implements
		ViewerSettingsDialog.OnViewerSettingsChange {

	private final boolean quiet = false;

	private static final String TAG = "WebViewActivity";
	private static final String ASSET_PREFIX = "file:///android_asset/readium-shared-js/";
	private static final String READER_SKELETON = "file:///android_asset/readium-shared-js/reader.html";

	// Installs "hook" function so that top-level window (application) can later
	// inject the window.navigator.epubReadingSystem into this HTML document's
	// iframe
	private static final String INJECT_EPUB_RSO_SCRIPT_1 = ""
			+ "window.readium_set_epubReadingSystem = function (obj) {"
			+ "\nwindow.navigator.epubReadingSystem = obj;"
			+ "\nwindow.readium_set_epubReadingSystem = undefined;"
			+ "\nvar el1 = document.getElementById(\"readium_epubReadingSystem_inject1\");"
			+ "\nif (el1 && el1.parentNode) { el1.parentNode.removeChild(el1); }"
			+ "\nvar el2 = document.getElementById(\"readium_epubReadingSystem_inject2\");"
			+ "\nif (el2 && el2.parentNode) { el2.parentNode.removeChild(el2); }"
			+ "\n};";

	// Iterate top-level iframes, inject global
	// window.navigator.epubReadingSystem if the expected hook function exists (
	// readium_set_epubReadingSystem() ).
	private static final String INJECT_EPUB_RSO_SCRIPT_2 = ""
			+ "var epubRSInject =\nfunction(win) {" // 1
			+ "\nvar ret = '';"
			+ "\nret += win.location.href;"
			+ "\nret += ' ---- ';"
			// "\nret += JSON.stringify(win.navigator.epubReadingSystem);" +
			// "\nret += ' ---- ';" +
			+ "\nif (win.frames)"
			+ "\n{" // 2
			+ "\nfor (var i = 0; i < win.frames.length; i++)"
			+ "\n{" // 3
			+ "\nvar iframe = win.frames[i];"
			+ "\nret += ' IFRAME ';"
			+ "\ntry {\n" // 4
			+ "\nif (iframe.readium_set_epubReadingSystem)"
			+ "\n{" // 5
			+ "\nret += ' EPBRS ';"
			+ "\niframe.readium_set_epubReadingSystem(window.navigator.epubReadingSystem);"
			+ "\n}" // 5
			+ "\nret += epubRSInject(iframe);"
			+ "\n} catch(err) { console.log(err); }" // 4
			+ "\n}" // 3
			+ "\n}" // 2
			+ "\nreturn ret;"
			+ "\n};" // 1
			+ "\nepubRSInject(window);";

	// Script tag to inject the "hook" function installer script, added to the
	// head of every epub iframe document
	private static final String INJECT_HEAD_EPUB_RSO_1 = ""
			+ "<script id=\"readium_epubReadingSystem_inject1\" type=\"text/javascript\">\n"
			+ "//<![CDATA[\n" + INJECT_EPUB_RSO_SCRIPT_1 + "\n" + "//]]>\n"
			+ "</script>";
	// Script tag that generates an HTTP request to a fake script => triggers
	// push of window.navigator.epubReadingSystem into this HTML document's
	// iframe
	private static final String INJECT_HEAD_EPUB_RSO_2 = ""
			+ "<script id=\"readium_epubReadingSystem_inject2\" type=\"text/javascript\" "
			+ "src=\"/%d/readium_epubReadingSystem_inject.js\"> </script>";
	// Script tag to load the mathjax script payload, added to the head of epub
	// iframe documents, only if <math> tags are detected
	private static final String INJECT_HEAD_MATHJAX = "<script type=\"text/javascript\" src=\"/readium_MathJax.js\"> </script>";

	// Location of payloads in the asset folder
	private static final String PAYLOAD_MATHJAX_ASSET = "reader-payloads/MathJax.js";
	private static final String PAYLOAD_ANNOTATIONS_CSS_ASSET = "reader-payloads/annotations.css";

	private final DataPreProcessor dataPreProcessor = new DataPreProcessor() {

		@Override
		public byte[] handle(byte[] data, String mime, String uriPath,
				ManifestItem item) {
			if (mime == null
					|| (mime != "text/html" && mime != "application/xhtml+xml")) {
				return null;
			}
{'fraction_non_alphanumeric': 0.11864635297290009, 'fraction_numerical': 0.0061345557503033575, 'mean_word_length': 4.3344120819848975, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 23, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, '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': '6004538', 'n_tokens_mistral': 4891, 'n_tokens_neox': 4499, 'n_words': 1245}