use custom protocol for resources

This commit is contained in:
fkloft 2013-12-24 11:32:19 +01:00
parent 0c4cb8479e
commit 9208552e29
8 changed files with 339 additions and 251 deletions

View File

@ -3,10 +3,6 @@
// created a basic framework. All of these functions should only ever // created a basic framework. All of these functions should only ever
// be run once. // be run once.
// Used to disable on multitouch devices
window.showZoom = true;
window.showLayerChooser = true;
window.setupLargeImagePreview = function() { window.setupLargeImagePreview = function() {
$('#portaldetails').on('click', '.imgpreview', function() { $('#portaldetails').on('click', '.imgpreview', function() {
var img = $(this).find('img')[0]; var img = $(this).find('img')[0];
@ -137,7 +133,12 @@ window.setupMap = function() {
]; ];
// proper initial position is now delayed until all plugins are loaded and the base layer is set // proper initial position is now delayed until all plugins are loaded and the base layer is set
window.map = new L.Map('map', {center: [0,0], zoom: 1, zoomControl: window.showZoom, minZoom: 1}); window.map = new L.Map('map', {
center: [0,0],
zoom: 1,
zoomControl: (typeof android !== 'undefined' && android && android.showZoom) ? !android.showZoom() : true,
minZoom: 1
});
// add empty div to leaflet control areas - to force other leaflet controls to move around IITC UI elements // add empty div to leaflet control areas - to force other leaflet controls to move around IITC UI elements
// TODO? move the actual IITC DOM into the leaflet control areas, so dummy <div>s aren't needed // TODO? move the actual IITC DOM into the leaflet control areas, so dummy <div>s aren't needed
@ -428,7 +429,7 @@ window.setupQRLoadLib = function() {
window.setupLayerChooserApi = function() { window.setupLayerChooserApi = function() {
// hide layer chooser on mobile devices running desktop mode // hide layer chooser on mobile devices running desktop mode
if (!window.showLayerChooser) { if (typeof android !== 'undefined' && android && android.setLayers) {
$('.leaflet-control-layers').hide(); $('.leaflet-control-layers').hide();
} }

View File

@ -20,7 +20,6 @@
window.plugin.userLocation = function() {}; window.plugin.userLocation = function() {};
window.plugin.userLocation.locationLayer = new L.LayerGroup();
window.plugin.userLocation.follow = false; window.plugin.userLocation.follow = false;
window.plugin.userLocation.setup = function() { window.plugin.userLocation.setup = function() {
@ -52,6 +51,8 @@ window.plugin.userLocation.setup = function() {
clickable: false clickable: false
}); });
window.plugin.userLocation.locationLayer = new L.LayerGroup();
marker.addTo(window.plugin.userLocation.locationLayer); marker.addTo(window.plugin.userLocation.locationLayer);
window.plugin.userLocation.locationLayer.addTo(window.map); window.plugin.userLocation.locationLayer.addTo(window.map);
window.addLayerGroup('User location', window.plugin.userLocation.locationLayer, true); window.addLayerGroup('User location', window.plugin.userLocation.locationLayer, true);

View File

@ -0,0 +1,199 @@
package com.cradle.iitc_mobile;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.webkit.WebResourceResponse;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
public class IITC_FileManager {
private static final WebResourceResponse EMPTY =
new WebResourceResponse("text/plain", "UTF-8", new ByteArrayInputStream("".getBytes()));
private static final String WRAPPER_NEW = "wrapper(info);";
private static final String WRAPPER_OLD =
"script.appendChild(document.createTextNode('('+ wrapper +')('+JSON.stringify(info)+');'));\n"
+ "(document.body || document.head || document.documentElement).appendChild(script);";
public static HashMap<String, String> getScriptInfo(String js) {
HashMap<String, String> map = new HashMap<String, String>();
String header = "";
if (js != null) {
header = js.substring(js.indexOf("==UserScript=="),
js.indexOf("==/UserScript=="));
}
// remove new line comments
header = header.replace("\n//", " ");
// get a list of key-value
String[] attributes = header.split(" +");
// add default values
map.put("version", "not found");
map.put("name", "unknown");
map.put("description", "");
map.put("category", "Misc");
// add parsed values
for (int i = 0; i < attributes.length; i++) {
// search for attributes and use the value
if (attributes[i].equals("@version")) {
map.put("version", attributes[i + 1]);
}
if (attributes[i].equals("@name")) {
map.put("name", attributes[i + 1]);
}
if (attributes[i].equals("@description")) {
map.put("description", attributes[i + 1]);
}
if (attributes[i].equals("@category")) {
map.put("category", attributes[i + 1]);
}
}
return map;
}
private AssetManager mAssetManager;
private IITC_Mobile mIitc;
private String mIitcPath;
private SharedPreferences mPrefs;
public IITC_FileManager(IITC_Mobile iitc) {
mIitc = iitc;
mIitcPath = Environment.getExternalStorageDirectory().getPath() + "/IITC_Mobile/";
mPrefs = PreferenceManager.getDefaultSharedPreferences(iitc);
mAssetManager = mIitc.getAssets();
}
private InputStream getAssetFile(String filename) throws IOException {
if (mPrefs.getBoolean("pref_dev_checkbox", false)) {
File file = new File(mIitcPath + "dev/" + filename);
try {
return new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
String source = mPrefs.getString("pref_iitc_source", "local");
if (!source.equals("local")) {
// load iitc script from web or asset folder
if (source.contains("http")) {
try {
URL context = new URL(source);
URL url = new URL(context, filename);
return url.openStream();
} catch (IOException e) {
e.printStackTrace();
}
} else {
File file = new File(source + File.separatorChar + filename);
try {
return new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
// load plugins from asset folder
return mAssetManager.open(filename);
}
private WebResourceResponse getScript(Uri uri) {
InputStream stream;
try {
stream = getAssetFile(uri.getPath().substring(1));
} catch (IOException e) {
e.printStackTrace();
return EMPTY;
}
InputStream data = prepareUserScript(stream);
return new WebResourceResponse("application/x-javascript", "UTF-8", data);
}
private HashMap<String, String> getScriptInfo(InputStream stream) {
return getScriptInfo(readStream(stream));
}
private WebResourceResponse getUserPlugin(Uri uri) {
if (!mPrefs.getBoolean(uri.getPath(), false)) {
Log.e("iitcm", "Attempted to inject user script that is not enabled by user: " + uri.getPath());
return EMPTY;
}
InputStream stream;
try {
stream = new FileInputStream(new File(uri.getPath()));
} catch (IOException e) {
e.printStackTrace();
return EMPTY;
}
InputStream data = prepareUserScript(stream);
return new WebResourceResponse("application/x-javascript", "UTF-8", data);
}
private InputStream prepareUserScript(InputStream stream) {
String content = readStream(stream);
HashMap<String, String> info = getScriptInfo(content);
JSONObject jObject = new JSONObject(info);
String gmInfo = "var GM_info={\"script\":" + jObject.toString() + "}";
content = content.replace(WRAPPER_OLD, WRAPPER_NEW);
return new ByteArrayInputStream((gmInfo + content).getBytes());
}
private String readStream(InputStream stream) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
try {
while (true) {
int read = stream.read(buffer);
if (read == -1)
break;
os.write(buffer, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
return "";
}
return os.toString();
}
public String getIITCVersion() throws IOException {
InputStream stream = getAssetFile("total-conversion-build.user.js");
return getScriptInfo(stream).get("version");
}
public WebResourceResponse getResponse(String url) {
Uri uri = Uri.parse(url);
String host = uri.getHost();
if ("script".equals(host))
return getScript(uri);
if ("user-plugin".equals(host))
return getUserPlugin(uri);
Log.e("iitcm", "could not generate response for url: " + url);
return EMPTY;
}
}

View File

@ -190,6 +190,13 @@ public class IITC_JSInterface {
}); });
} }
public boolean showZoom() {
PackageManager pm = mIitc.getPackageManager();
boolean hasMultitouch = pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH);
boolean forcedZoom = mIitc.getPrefs().getBoolean("pref_user_zoom", false);
return forcedZoom || !hasMultitouch;
}
@JavascriptInterface @JavascriptInterface
public void setFollowMode(final boolean follow) { public void setFollowMode(final boolean follow) {
mIitc.runOnUiThread(new Runnable() { mIitc.runOnUiThread(new Runnable() {

View File

@ -40,6 +40,7 @@ public class IITC_Mobile extends Activity implements OnSharedPreferenceChangeLis
private static final String mIntelUrl = "https://www.ingress.com/intel"; private static final String mIntelUrl = "https://www.ingress.com/intel";
private SharedPreferences mSharedPrefs; private SharedPreferences mSharedPrefs;
private IITC_FileManager mFileManager;
private IITC_WebView mIitcWebView; private IITC_WebView mIitcWebView;
private IITC_UserLocation mUserLocation; private IITC_UserLocation mUserLocation;
private IITC_NavigationHelper mNavigationHelper; private IITC_NavigationHelper mNavigationHelper;
@ -87,6 +88,8 @@ public class IITC_Mobile extends Activity implements OnSharedPreferenceChangeLis
// get fullscreen status from settings // get fullscreen status from settings
mIitcWebView.updateFullscreenStatus(); mIitcWebView.updateFullscreenStatus();
mFileManager = new IITC_FileManager(this);
mUserLocation = new IITC_UserLocation(this); mUserLocation = new IITC_UserLocation(this);
mUserLocation.setLocationMode(Integer.parseInt(mSharedPrefs.getString("pref_user_location_mode", "0"))); mUserLocation.setLocationMode(Integer.parseInt(mSharedPrefs.getString("pref_user_location_mode", "0")));
@ -130,9 +133,8 @@ public class IITC_Mobile extends Activity implements OnSharedPreferenceChangeLis
} else if (key.equals("pref_press_twice_to_exit") } else if (key.equals("pref_press_twice_to_exit")
|| key.equals("pref_share_selected_tab") || key.equals("pref_share_selected_tab")
|| key.equals("pref_messages") || key.equals("pref_messages")
|| key.equals("pref_external_storage")) || key.equals("pref_external_storage")) {
// no reload needed // no reload needed
{
return; return;
} }
@ -466,8 +468,12 @@ public class IITC_Mobile extends Activity implements OnSharedPreferenceChangeLis
return true; return true;
case R.id.action_settings: // start settings activity case R.id.action_settings: // start settings activity
Intent intent = new Intent(this, IITC_PreferenceActivity.class); Intent intent = new Intent(this, IITC_PreferenceActivity.class);
intent.putExtra("iitc_version", mIitcWebView.getWebViewClient() try {
.getIITCVersion()); intent.putExtra("iitc_version", mFileManager.getIITCVersion());
} catch (IOException e) {
e.printStackTrace();
return true;
}
startActivity(intent); startActivity(intent);
return true; return true;
case R.id.menu_clear_cookies: case R.id.menu_clear_cookies:
@ -495,16 +501,6 @@ public class IITC_Mobile extends Activity implements OnSharedPreferenceChangeLis
mReloadNeeded = false; mReloadNeeded = false;
} }
private void loadIITC() {
try {
mIitcWebView.getWebViewClient().loadIITC_JS(this);
} catch (IOException e1) {
e1.printStackTrace();
} catch (NullPointerException e2) {
e2.printStackTrace();
}
}
// vp=f enables mDesktopMode mode...vp=m is the default mobile view // vp=f enables mDesktopMode mode...vp=m is the default mobile view
private String addUrlParam(String url) { private String addUrlParam(String url) {
if (mDesktopMode) { if (mDesktopMode) {
@ -519,7 +515,6 @@ public class IITC_Mobile extends Activity implements OnSharedPreferenceChangeLis
public void loadUrl(String url) { public void loadUrl(String url) {
setLoadingState(true); setLoadingState(true);
url = addUrlParam(url); url = addUrlParam(url);
loadIITC();
mIitcWebView.loadUrl(url); mIitcWebView.loadUrl(url);
} }
@ -649,6 +644,14 @@ public class IITC_Mobile extends Activity implements OnSharedPreferenceChangeLis
return mMapSettings; return mMapSettings;
} }
public IITC_FileManager getFileManager() {
return mFileManager;
}
public SharedPreferences getPrefs() {
return mSharedPrefs;
}
public IITC_UserLocation getUserLocation() { public IITC_UserLocation getUserLocation() {
return mUserLocation; return mUserLocation;
} }

View File

@ -157,14 +157,14 @@ public class IITC_PluginPreferenceActivity extends PreferenceActivity {
void setUpPluginPreferenceScreen() { void setUpPluginPreferenceScreen() {
// get all plugins from asset manager // get all plugins from asset manager
String[] asset_array = getAssetPlugins(); String[] assets = getAssetPlugins();
for (String anAsset_array : asset_array) { for (String asset : assets) {
// find user plugin name for user readable entries // find user plugin name for user readable entries
Scanner s = null; Scanner s = null;
String src = ""; String src = "";
try { try {
s = new Scanner(getAssets().open("plugins/" + anAsset_array)) s = new Scanner(getAssets().open("plugins/" + asset))
.useDelimiter("\\A"); .useDelimiter("\\A");
} catch (IOException e2) { } catch (IOException e2) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
@ -174,7 +174,7 @@ public class IITC_PluginPreferenceActivity extends PreferenceActivity {
src = s.hasNext() ? s.next() : ""; src = s.hasNext() ? s.next() : "";
} }
// now we have all stuff together and can build the pref screen // now we have all stuff together and can build the pref screen
addPluginPreference(src, anAsset_array, false); addPluginPreference(src, asset, false);
} }
// load user plugins from <storage-path>/IITC_Mobile/plugins/ // load user plugins from <storage-path>/IITC_Mobile/plugins/
@ -201,7 +201,7 @@ public class IITC_PluginPreferenceActivity extends PreferenceActivity {
// parse plugin name, description and category // parse plugin name, description and category
// we need default versions here otherwise iitcm may crash // we need default versions here otherwise iitcm may crash
HashMap<String,String> info = IITC_WebViewClient.getScriptInfo(src); HashMap<String,String> info = IITC_FileManager.getScriptInfo(src);
String plugin_name = info.get("name"); String plugin_name = info.get("name");
String plugin_cat = info.get("category"); String plugin_cat = info.get("category");
String plugin_desc = info.get("description"); String plugin_desc = info.get("description");

View File

@ -1,10 +1,7 @@
package com.cradle.iitc_mobile; package com.cradle.iitc_mobile;
import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.net.Uri; import android.net.Uri;
import android.net.http.SslError; import android.net.http.SslError;
import android.os.Environment; import android.os.Environment;
@ -14,23 +11,11 @@ import android.webkit.SslErrorHandler;
import android.webkit.WebResourceResponse; import android.webkit.WebResourceResponse;
import android.webkit.WebView; import android.webkit.WebView;
import android.webkit.WebViewClient; import android.webkit.WebViewClient;
import android.widget.Toast;
import com.cradle.iitc_mobile.async.UrlContentToString;
import org.json.JSONObject;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.File; import java.util.LinkedList;
import java.io.FileNotFoundException; import java.util.List;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class IITC_WebViewClient extends WebViewClient { public class IITC_WebViewClient extends WebViewClient {
@ -40,8 +25,7 @@ public class IITC_WebViewClient extends WebViewClient {
private static final ByteArrayInputStream EMPTY = new ByteArrayInputStream( private static final ByteArrayInputStream EMPTY = new ByteArrayInputStream(
"".getBytes()); "".getBytes());
private String mIitcScript = null; private String mIitcPath;
private String mIitcPath = null;
private boolean mIitcInjected = false; private boolean mIitcInjected = false;
private final IITC_Mobile mIitc; private final IITC_Mobile mIitc;
private final IITC_TileManager mTileManager; private final IITC_TileManager mTileManager;
@ -49,130 +33,18 @@ public class IITC_WebViewClient extends WebViewClient {
public IITC_WebViewClient(IITC_Mobile iitc) { public IITC_WebViewClient(IITC_Mobile iitc) {
this.mIitc = iitc; this.mIitc = iitc;
this.mTileManager = new IITC_TileManager(mIitc); this.mTileManager = new IITC_TileManager(mIitc);
this.mIitcPath = Environment.getExternalStorageDirectory().getPath() this.mIitcPath = Environment.getExternalStorageDirectory().getPath() + "/IITC_Mobile/";
+ "/IITC_Mobile/";
} }
public String getIITCVersion() { // TODO use somewhere else:
HashMap<String, String> map = getScriptInfo(mIitcScript); // Toast.makeText(mIitc, "File " + mIitcPath +
return map.get("version"); // "dev/total-conversion-build.user.js not found. " +
} // "Disable developer mode or add iitc files to the dev folder.",
// Toast.LENGTH_LONG).show();
// static method because we use it in IITC_PluginPreferenceActivity too
public static HashMap<String, String> getScriptInfo(String js) {
HashMap<String, String> map = new HashMap<String, String>();
String header = "";
if (js != null) {
header = js.substring(js.indexOf("==UserScript=="),
js.indexOf("==/UserScript=="));
}
// remove new line comments
header = header.replace("\n//", " ");
// get a list of key-value
String[] attributes = header.split(" +");
// add default values
map.put("version", "not found");
map.put("name", "unknown");
map.put("description", "");
map.put("category", "Misc");
// add parsed values
for (int i = 0; i < attributes.length; i++) {
// search for attributes and use the value
if (attributes[i].equals("@version")) {
map.put("version", attributes[i + 1]);
}
if (attributes[i].equals("@name")) {
map.put("name", attributes[i + 1]);
}
if (attributes[i].equals("@description")) {
map.put("description", attributes[i + 1]);
}
if (attributes[i].equals("@category")) {
map.put("category", attributes[i + 1]);
}
}
return map;
}
public String getGmInfoJson(HashMap<String, String> map) {
JSONObject jObject = new JSONObject(map);
return "{\"script\":" + jObject.toString() + "}";
}
public void loadIITC_JS(Context c) throws java.io.IOException {
// You are able to load the script from external source
// if a http address is given, use script from this address. else use
// the local script
SharedPreferences sharedPref = PreferenceManager
.getDefaultSharedPreferences(c);
String iitc_source = sharedPref.getString("pref_iitc_source", "local");
String js = "";
// if developer mode are enabled, load all iitc script from external
// storage
Log.d("iitcm", "adding iitc main script");
if (sharedPref.getBoolean("pref_dev_checkbox", false)) {
js = this.fileToString(mIitcPath
+ "dev/total-conversion-build.user.js", false);
if (js.equals("false")) {
Toast.makeText(mIitc, "File " + mIitcPath +
"dev/total-conversion-build.user.js not found. " +
"Disable developer mode or add iitc files to the dev folder.",
Toast.LENGTH_LONG).show();
return;
} else {
Toast.makeText(mIitc, "Developer mode enabled",
Toast.LENGTH_SHORT).show();
}
} else {
// load iitc script from web or asset folder
if (iitc_source.contains("http")) {
URL url = new URL(iitc_source);
// if parsing of the online iitc source timed out, use the script from assets
try {
js = new UrlContentToString().execute(url).get(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
js = this.fileToString("total-conversion-build.user.js", true);
} catch (ExecutionException e) {
e.printStackTrace();
js = this.fileToString("total-conversion-build.user.js", true);
} catch (TimeoutException e) {
e.printStackTrace();
js = this.fileToString("total-conversion-build.user.js", true);
}
} else {
js = this.fileToString("total-conversion-build.user.js", true);
}
mIitcInjected = false;
}
PackageManager pm = mIitc.getPackageManager();
boolean hasMultitouch = pm
.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH);
boolean forcedZoom = sharedPref.getBoolean("pref_user_zoom", false);
if (hasMultitouch && !forcedZoom) {
js = js.replace("window.showZoom = true;",
"window.showZoom = false;");
}
// hide layer chooser on desktop mode
// on mobile mode it is hidden via smartphone.css
boolean desktopMode = sharedPref.getBoolean("pref_force_desktop", false);
if (desktopMode) {
js = js.replace("window.showLayerChooser = true;",
"window.showLayerChooser = false");
}
String gmInfo = "GM_info=" + getGmInfoJson(getScriptInfo(js)) + "\n";
this.mIitcScript = gmInfo + js;
}
// enable https // enable https
@Override @Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
SslError error) {
handler.proceed(); handler.proceed();
} }
@ -182,13 +54,61 @@ public class IITC_WebViewClient extends WebViewClient {
|| url.startsWith("https://www.ingress.com/intel")) { || url.startsWith("https://www.ingress.com/intel")) {
if (mIitcInjected) return; if (mIitcInjected) return;
Log.d("iitcm", "injecting iitc.."); Log.d("iitcm", "injecting iitc..");
view.loadUrl("javascript: " + this.mIitcScript); loadScripts((IITC_WebView) view);
mIitcInjected = true; mIitcInjected = true;
loadPlugins(view);
} }
super.onPageFinished(view, url); super.onPageFinished(view, url);
} }
private void loadScripts(IITC_WebView view) {
List<String> scripts = new LinkedList<String>();
scripts.add("script/total-conversion-build.user.js");
// get the plugin preferences
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(mIitc);
Map<String, ?> all_prefs = sharedPref.getAll();
// iterate through all plugins
for (Map.Entry<String, ?> entry : all_prefs.entrySet()) {
String plugin = entry.getKey();
if (plugin.endsWith(".user.js") && entry.getValue().toString().equals("true")) {
if (plugin.startsWith(mIitcPath)) {
scripts.add("user-plugin" + plugin);
} else {
scripts.add("script/plugins/" + plugin);
}
}
}
// inject the user location script if enabled in settings
if (Integer.parseInt(sharedPref.getString("pref_user_location_mode", "0")) != 0) {
scripts.add("script/user-location.user.js");
}
String js = "(function(){['" + join(scripts, "','") + "'].forEach(function(src) {" +
"var script = document.createElement('script');script.src = 'iitcm://'+src;" +
"(document.body || document.head || document.documentElement).appendChild(script);" +
"});})();";
view.loadJS(js);
}
static public String join(List<String> list, String conjunction)
{
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String item : list)
{
if (first)
first = false;
else
sb.append(conjunction);
sb.append(item);
}
return sb.toString();
}
/** /**
* this method is called automatically when the Google login form is opened. * this method is called automatically when the Google login form is opened.
*/ */
@ -196,86 +116,41 @@ public class IITC_WebViewClient extends WebViewClient {
public void onReceivedLoginRequest(WebView view, String realm, String account, String args) { public void onReceivedLoginRequest(WebView view, String realm, String account, String args) {
Log.d("iitcm", "Login requested: " + realm + " " + account + " " + args); Log.d("iitcm", "Login requested: " + realm + " " + account + " " + args);
mIitcInjected = false; mIitcInjected = false;
//((IITC_Mobile) mContext).onReceivedLoginRequest(this, view, realm, account, args); // ((IITC_Mobile) mContext).onReceivedLoginRequest(this, view, realm, account, args);
}
public void loadPlugins(WebView view) {
// get the plugin preferences
SharedPreferences sharedPref = PreferenceManager
.getDefaultSharedPreferences(mIitc);
boolean dev_enabled = sharedPref.getBoolean("pref_dev_checkbox", false);
String path = (dev_enabled) ? mIitcPath + "dev/plugins/" : "plugins/";
Map<String, ?> all_prefs = sharedPref.getAll();
// iterate through all plugins
for (Map.Entry<String, ?> entry : all_prefs.entrySet()) {
String plugin = entry.getKey();
if (plugin.endsWith("user.js") && entry.getValue().toString().equals("true")) {
if (!plugin.startsWith(mIitcPath)) {
// load default iitc plugins
Log.d("iitcm", "adding plugin " + plugin);
loadJS(path + plugin, !dev_enabled, view);
} else {
// load user iitc plugins
Log.d("iitcm", "adding user plugin " + plugin);
loadJS(plugin, false, view);
}
}
}
// inject the user location script if enabled in settings
if (Integer.parseInt(sharedPref.getString("pref_user_location_mode", "0")) != 0) {
path = path.replace("plugins/", "");
loadJS(path + "user-location.user.js", !dev_enabled, view);
}
}
// read a file into a string
// load it as javascript
public boolean loadJS(String file, boolean asset, WebView view) {
String js = fileToString(file, asset);
if (js.equals("false")) {
return false;
} else {
String gmInfo = "GM_info=" + getGmInfoJson(getScriptInfo(js)) + "\n";
view.loadUrl("javascript:" + gmInfo + js);
}
return true;
} }
// read a file into a string // read a file into a string
// use the full path for File // use the full path for File
// if asset == true use the asset manager to open file // if asset == true use the asset manager to open file
public String fileToString(String file, boolean asset) { // public String fileToString(String file, boolean asset) {
Scanner s = null; // Scanner s = null;
String src = ""; // String src = "";
if (!asset) { // if (!asset) {
File js_file = new File(file); // File js_file = new File(file);
try { // try {
s = new Scanner(js_file).useDelimiter("\\A"); // s = new Scanner(js_file).useDelimiter("\\A");
} catch (FileNotFoundException e) { // } catch (FileNotFoundException e) {
e.printStackTrace(); // e.printStackTrace();
Log.d("iitcm", "failed to parse file " + file); // Log.d("iitcm", "failed to parse file " + file);
return "false"; // return "false";
} // }
} else { // } else {
// load plugins from asset folder // // load plugins from asset folder
AssetManager am = mIitc.getAssets(); // AssetManager am = mIitc.getAssets();
try { // try {
s = new Scanner(am.open(file)).useDelimiter("\\A"); // s = new Scanner(am.open(file)).useDelimiter("\\A");
} catch (IOException e) { // } catch (IOException e) {
e.printStackTrace(); // e.printStackTrace();
Log.d("iitcm", "failed to parse file assets/" + file); // Log.d("iitcm", "failed to parse file assets/" + file);
return "false"; // return "false";
} // }
} // }
//
if (s != null) { // if (s != null) {
src = s.hasNext() ? s.next() : ""; // src = s.hasNext() ? s.next() : "";
} // }
return src; // return src;
} // }
// Check every external resource if its okay to load it and maybe replace // Check every external resource if its okay to load it and maybe replace
// it // it
@ -283,8 +158,7 @@ public class IITC_WebViewClient extends WebViewClient {
// which arent required and to inject IITC early into the site. // which arent required and to inject IITC early into the site.
// via http://stackoverflow.com/a/8274881/1684530 // via http://stackoverflow.com/a/8274881/1684530
@Override @Override
public WebResourceResponse shouldInterceptRequest(final WebView view, public WebResourceResponse shouldInterceptRequest(final WebView view, String url) {
String url) {
// if any tiles are requested, handle it with IITC_TileManager // if any tiles are requested, handle it with IITC_TileManager
if (url.matches(".*tile.*jpg.*") // mapquest tiles | ovi tiles if (url.matches(".*tile.*jpg.*") // mapquest tiles | ovi tiles
|| url.matches(".*tile.*png.*") // cloudmade tiles || url.matches(".*tile.*png.*") // cloudmade tiles
@ -301,11 +175,11 @@ public class IITC_WebViewClient extends WebViewClient {
} }
} else if (url.contains("/css/common.css")) { } else if (url.contains("/css/common.css")) {
return new WebResourceResponse("text/css", "UTF-8", STYLE); return new WebResourceResponse("text/css", "UTF-8", STYLE);
// } else if (url.contains("gen_dashboard.js")) { // } else if (url.contains("gen_dashboard.js")) {
// // define initialize function to get rid of JS ReferenceError on intel page's 'onLoad' // // define initialize function to get rid of JS ReferenceError on intel page's 'onLoad'
// String gen_dashboard_replacement = "window.initialize = function() {}"; // String gen_dashboard_replacement = "window.initialize = function() {}";
// return new WebResourceResponse("text/javascript", "UTF-8", // return new WebResourceResponse("text/javascript", "UTF-8",
// new ByteArrayInputStream(gen_dashboard_replacement.getBytes())); // new ByteArrayInputStream(gen_dashboard_replacement.getBytes()));
} else if (url.contains("/css/ap_icons.css") } else if (url.contains("/css/ap_icons.css")
|| url.contains("/css/map_icons.css") || url.contains("/css/map_icons.css")
|| url.contains("/css/common.css") || url.contains("/css/common.css")
@ -317,6 +191,8 @@ public class IITC_WebViewClient extends WebViewClient {
|| url.contains("js/analytics.js") || url.contains("js/analytics.js")
|| url.contains("google-analytics.com/ga.js")) { || url.contains("google-analytics.com/ga.js")) {
return new WebResourceResponse("text/plain", "UTF-8", EMPTY); return new WebResourceResponse("text/plain", "UTF-8", EMPTY);
} else if (url.startsWith("iitcm:")) {
return mIitc.getFileManager().getResponse(url);
} else { } else {
return super.shouldInterceptRequest(view, url); return super.shouldInterceptRequest(view, url);
} }

View File

@ -29,6 +29,7 @@ public class MainSettings extends PreferenceFragment {
// set versions // set versions
String iitcVersion = getArguments().getString("iitc_version"); String iitcVersion = getArguments().getString("iitc_version");
String buildVersion = "unknown"; String buildVersion = "unknown";
PackageManager pm = getActivity().getPackageManager(); PackageManager pm = getActivity().getPackageManager();