1
0
Fork 0
mirror of https://github.com/gsantner/dandelion synced 2024-11-25 22:02:08 +01:00

Merge branch 'master' of github.com:Diaspora-for-Android/diaspora-android

This commit is contained in:
Gregor Santner 2016-09-11 17:53:25 +02:00
commit 5ba8675c39
5 changed files with 180 additions and 57 deletions

View file

@ -40,9 +40,9 @@ dependencies {
testCompile 'junit:junit:4.12' testCompile 'junit:junit:4.12'
// Android standard libs // Android standard libs
compile 'com.android.support:appcompat-v7:24.1.1' compile 'com.android.support:appcompat-v7:24.2.0'
compile 'com.android.support:design:24.1.1' compile 'com.android.support:design:24.2.0'
compile 'com.android.support:support-v4:24.1.1' compile 'com.android.support:support-v4:24.2.0'
// More libraries // More libraries
compile 'com.jakewharton:butterknife:8.0.1' compile 'com.jakewharton:butterknife:8.0.1'

View file

@ -111,7 +111,7 @@ public class MainActivity extends AppCompatActivity
private static final int INPUT_FILE_REQUEST_CODE_NEW = 1; private static final int INPUT_FILE_REQUEST_CODE_NEW = 1;
private static final int INPUT_FILE_REQUEST_CODE_OLD = 2; private static final int INPUT_FILE_REQUEST_CODE_OLD = 2;
private static final int REQUEST_CODE_ASK_PERMISSIONS = 123; private static final int REQUEST_CODE_ASK_PERMISSIONS = 123;
public static final int REQUEST_CODE_ASK_PERMISSIONS_SAVE_IMAGE = 124; public static final int REQUEST_CODE__ACCESS_EXTERNAL_STORAGE = 124;
public static final String ACTION_OPEN_URL = "com.github.dfa.diaspora_android.MainActivity.open_url"; public static final String ACTION_OPEN_URL = "com.github.dfa.diaspora_android.MainActivity.open_url";
public static final String ACTION_CHANGE_ACCOUNT = "com.github.dfa.diaspora_android.MainActivity.change_account"; public static final String ACTION_CHANGE_ACCOUNT = "com.github.dfa.diaspora_android.MainActivity.change_account";
@ -178,42 +178,47 @@ public class MainActivity extends AppCompatActivity
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
Log.d(App.TAG, "onCreate"); Log.d(App.TAG, "onCreate()");
// Bind UI // Bind UI
setContentView(R.layout.main__activity); setContentView(R.layout.main__activity);
app = (App) getApplication(); if ((app = (App) getApplication()) == null) Log.e(App.TAG, "App is null!");
appSettings = app.getSettings(); if ((appSettings = app.getSettings()) == null) Log.e(App.TAG, "AppSettings is null!");
podUserProfile = app.getPodUserProfile(); if ((podUserProfile = app.getPodUserProfile()) == null) Log.e(App.TAG, "PodUserProfile is null!");
podUserProfile.setCallbackHandler(uiHandler); podUserProfile.setCallbackHandler(uiHandler);
podUserProfile.setListener(this); podUserProfile.setListener(this);
urls = new DiasporaUrlHelper(appSettings); urls = new DiasporaUrlHelper(appSettings);
setupUI(savedInstanceState);
if (appSettings.isProxyEnabled()) { if (appSettings.isProxyEnabled()) {
if (!setProxy(appSettings.getProxyHost(), appSettings.getProxyPort())) { if (!setProxy(appSettings.getProxyHost(), appSettings.getProxyPort())) {
Log.d(App.TAG, "Could not enable Proxy");
Toast.makeText(MainActivity.this, R.string.toast_set_proxy_failed, Toast.LENGTH_SHORT).show(); Toast.makeText(MainActivity.this, R.string.toast_set_proxy_failed, Toast.LENGTH_SHORT).show();
} }
} else if (appSettings.wasProxyEnabled()) { } else if (appSettings.wasProxyEnabled()) {
resetProxy(); resetProxy();
} }
setupUI(savedInstanceState);
} }
private void setupUI(Bundle savedInstanceState) { private void setupUI(Bundle savedInstanceState) {
Log.i(App.TAG, "MainActivity.setupUI()");
boolean newWebView = (webView == null); boolean newWebView = (webView == null);
if(newWebView) { if(newWebView) {
Log.d(App.TAG, "Webview was null. Create new one."); Log.v(App.TAG, "Webview was null. Create new one.");
View webviewHolder = getLayoutInflater().inflate(R.layout.webview, this.contentLayout, false); View webviewHolder = getLayoutInflater().inflate(R.layout.webview, this.contentLayout, false);
webView = (ContextMenuWebView) webviewHolder.findViewById(R.id.webView); webView = (ContextMenuWebView) webviewHolder.findViewById(R.id.webView);
((LinearLayout)webView.getParent()).removeView(webView); ((LinearLayout)webView.getParent()).removeView(webView);
setupWebView(savedInstanceState); setupWebView(savedInstanceState);
} else {
Log.v(App.TAG, "Reuse old WebView to avoid reloading page");
} }
ButterKnife.bind(this); ButterKnife.bind(this);
if (webviewPlaceholder.getChildCount() != 0) { if (webviewPlaceholder.getChildCount() != 0) {
webviewPlaceholder.removeAllViews(); webviewPlaceholder.removeAllViews();
} }
Log.v(App.TAG, "Add WebView to placeholder");
webviewPlaceholder.addView(webView); webviewPlaceholder.addView(webView);
// Setup toolbar // Setup toolbar
setSupportActionBar(toolbarTop); setSupportActionBar(toolbarTop);
@ -266,19 +271,23 @@ public class MainActivity extends AppCompatActivity
} }
if (!appSettings.isIntellihideToolbars()) { if (!appSettings.isIntellihideToolbars()) {
Log.v(App.TAG, "Disable intelligent hiding of toolbars");
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) toolbarTop.getLayoutParams(); AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) toolbarTop.getLayoutParams();
params.setScrollFlags(0); // clear all scroll flags params.setScrollFlags(0); // clear all scroll flags
} }
Log.v(App.TAG, "UI successfully set up");
handleIntent(getIntent()); handleIntent(getIntent());
} }
@Override @Override
public void onConfigurationChanged(Configuration newConfig) public void onConfigurationChanged(Configuration newConfig)
{ {
Log.i(App.TAG, "onConfigurationChanged()");
if (webView != null) if (webView != null)
{ {
// Remove the WebView from the old placeholder // Remove the WebView from the old placeholder
Log.v(App.TAG, "removeView from placeholder in order to prevent recreation");
webviewPlaceholder.removeView(webView); webviewPlaceholder.removeView(webView);
} }
@ -288,6 +297,7 @@ public class MainActivity extends AppCompatActivity
setContentView(R.layout.main__activity); setContentView(R.layout.main__activity);
// Reinitialize the UI // Reinitialize the UI
Log.v(App.TAG, "Rebuild the UI");
setupUI(null); setupUI(null);
} }
@ -304,6 +314,7 @@ public class MainActivity extends AppCompatActivity
webSettings.setAppCacheEnabled(true); webSettings.setAppCacheEnabled(true);
if (savedInstanceState != null) { if (savedInstanceState != null) {
Log.v(App.TAG, "restore WebView state");
webView.restoreState(savedInstanceState); webView.restoreState(savedInstanceState);
} }
@ -355,17 +366,18 @@ public class MainActivity extends AppCompatActivity
progressBar.setVisibility(progress == 100 ? View.GONE : View.VISIBLE); progressBar.setVisibility(progress == 100 ? View.GONE : View.VISIBLE);
} }
//For Android 4.1/4.2 only. DONT REMOVE //For Android 4.1/4.2 only. DO NOT REMOVE!
@SuppressWarnings("unused") @SuppressWarnings("unused")
protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
{ {
Log.d(App.TAG, "openFileChooser(ValCallback<Uri>, String, String"); Log.v(App.TAG, "openFileChooser(ValCallback<Uri>, String, String");
imageUploadFilePathCallbackOld = uploadMsg; imageUploadFilePathCallbackOld = uploadMsg;
Intent intent = new Intent(); Intent intent = new Intent();
intent.setType("image/*"); intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT); intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("return-data", true); intent.putExtra("return-data", true);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
Log.v(App.TAG, "startActivityForResult");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), INPUT_FILE_REQUEST_CODE_OLD); startActivityForResult(Intent.createChooser(intent, "Select Picture"), INPUT_FILE_REQUEST_CODE_OLD);
} }
@ -478,17 +490,19 @@ public class MainActivity extends AppCompatActivity
if (!appSettings.getPodDomain().equals("")) { if (!appSettings.getPodDomain().equals("")) {
navheaderDescription.setText(appSettings.getPodDomain()); navheaderDescription.setText(appSettings.getPodDomain());
} }
if (!appSettings.getAvatarUrl().equals("")) { String avatarUrl = appSettings.getAvatarUrl();
Log.d(App.TAG, "AVATAR URL != \"\": "+appSettings.getAvatarUrl()); if (!avatarUrl.equals("")) {
//Display app launcher icon instead of default avatar asset //Display app launcher icon instead of default avatar asset
//(Which would by the way not load because of missing pod domain prefix in the url) //(Which would by the way not load because of missing pod domain prefix in the url)
if(appSettings.getAvatarUrl().startsWith("/assets/user/default")) { if(avatarUrl.startsWith("/assets/user/default")) {
Log.v(App.TAG, "Avatar appears to be an asset. Display launcher icon instead (avatarUrl="+avatarUrl+")");
navheaderImage.setImageResource(R.drawable.ic_launcher); navheaderImage.setImageResource(R.drawable.ic_launcher);
} else { } else {
// Try to load image // Try to load image
if (!app.getAvatarImageLoader().loadToImageView(navheaderImage)) { if (!app.getAvatarImageLoader().loadToImageView(navheaderImage)) {
// If not yet loaded, start download // If not yet loaded, start download
app.getAvatarImageLoader().startImageDownload(navheaderImage, appSettings.getAvatarUrl()); Log.v(App.TAG, "Avatar not cached. Start download: "+avatarUrl);
app.getAvatarImageLoader().startImageDownload(navheaderImage, avatarUrl);
} }
} }
} }
@ -509,6 +523,7 @@ public class MainActivity extends AppCompatActivity
@OnClick(R.id.toolbar) @OnClick(R.id.toolbar)
public void onToolBarClicked(View view) { public void onToolBarClicked(View view) {
Log.i(App.TAG, "MainActivity.onToolBarClicked()");
onNavigationItemSelected(navView.getMenu().findItem(R.id.nav_stream)); onNavigationItemSelected(navView.getMenu().findItem(R.id.nav_stream));
} }
@ -520,14 +535,16 @@ public class MainActivity extends AppCompatActivity
} }
private void handleIntent(Intent intent) { private void handleIntent(Intent intent) {
Log.i(App.TAG, "MainActivity.handleIntent()");
if (intent == null) { if (intent == null) {
Log.v(App.TAG, "Intent was null");
return; return;
} }
String action = intent.getAction(); String action = intent.getAction();
String type = intent.getType(); String type = intent.getType();
String loadUrl = null; String loadUrl = null;
Log.v(App.TAG, "Action: "+action+" Type: "+type);
if (ACTION_OPEN_URL.equals(action)) { if (ACTION_OPEN_URL.equals(action)) {
loadUrl = intent.getStringExtra(URL_MESSAGE); loadUrl = intent.getStringExtra(URL_MESSAGE);
} else if (Intent.ACTION_VIEW.equals(action) && intent.getDataString() != null) { } else if (Intent.ACTION_VIEW.equals(action) && intent.getDataString() != null) {
@ -539,11 +556,14 @@ public class MainActivity extends AppCompatActivity
loadUrl = intent.getDataString(); loadUrl = intent.getDataString();
} }
} else if (ACTION_CHANGE_ACCOUNT.equals(action)) { } else if (ACTION_CHANGE_ACCOUNT.equals(action)) {
Log.v(App.TAG, "Reset pod data and animate to PodSelectionActivity");
app.resetPodData(webView); app.resetPodData(webView);
Helpers.animateToActivity(MainActivity.this, PodSelectionActivity.class, true); Helpers.animateToActivity(MainActivity.this, PodSelectionActivity.class, true);
} else if (ACTION_CLEAR_CACHE.equals(action)) { } else if (ACTION_CLEAR_CACHE.equals(action)) {
Log.v(App.TAG, "Clear WebView cache");
webView.clearCache(true); webView.clearCache(true);
} else if (ACTION_RELOAD_ACTIVITY.equals(action)) { } else if (ACTION_RELOAD_ACTIVITY.equals(action)) {
Log.v(App.TAG, "Recreate activity");
recreate(); recreate();
return; return;
} else if (Intent.ACTION_SEND.equals(action) && type != null) { } else if (Intent.ACTION_SEND.equals(action) && type != null) {
@ -572,10 +592,10 @@ public class MainActivity extends AppCompatActivity
@Override @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(App.TAG,"onActivityResult:"); Log.d(App.TAG,"MainActivity.onActivityResult()");
switch (requestCode) { switch (requestCode) {
case INPUT_FILE_REQUEST_CODE_NEW: { case INPUT_FILE_REQUEST_CODE_NEW: {
Log.d(App.TAG,"INPUT_FILE_REQUEST_CODE_NEW:"); Log.v(App.TAG,"Upload image using recent method (Lollipop+)");
if (imageUploadFilePathCallbackNew == null || resultCode != Activity.RESULT_OK) { if (imageUploadFilePathCallbackNew == null || resultCode != Activity.RESULT_OK) {
Log.e(App.TAG, "Callback is null: " + (imageUploadFilePathCallbackNew == null) Log.e(App.TAG, "Callback is null: " + (imageUploadFilePathCallbackNew == null)
+ " resultCode: " + resultCode); + " resultCode: " + resultCode);
@ -584,20 +604,26 @@ public class MainActivity extends AppCompatActivity
Uri[] results = null; Uri[] results = null;
if (data == null) { if (data == null) {
if (mCameraPhotoPath != null) { if (mCameraPhotoPath != null) {
Log.v(App.TAG, "Intent data is null. Try to parse cameraPhotoPath");
results = new Uri[]{Uri.parse(mCameraPhotoPath)}; results = new Uri[]{Uri.parse(mCameraPhotoPath)};
} else {
Log.w(App.TAG, "Intent data is null and cameraPhotoPath is null");
} }
} else { } else {
String dataString = data.getDataString(); String dataString = data.getDataString();
if (dataString != null) { if (dataString != null) {
Log.v(App.TAG, "Intent has data. Try to parse dataString");
results = new Uri[]{Uri.parse(dataString)}; results = new Uri[]{Uri.parse(dataString)};
} }
Log.w(App.TAG, "dataString is null");
} }
Log.v(App.TAG, "handle received result over to callback");
imageUploadFilePathCallbackNew.onReceiveValue(results); imageUploadFilePathCallbackNew.onReceiveValue(results);
imageUploadFilePathCallbackNew = null; imageUploadFilePathCallbackNew = null;
return; return;
} }
case INPUT_FILE_REQUEST_CODE_OLD: { case INPUT_FILE_REQUEST_CODE_OLD: {
Log.d(App.TAG,"INPUT_FILE_REQUEST_CODE_OLD:"); Log.v(App.TAG, "Upload image using legacy method (Jelly Bean, Kitkat)");
if (imageUploadFilePathCallbackOld == null || resultCode != Activity.RESULT_OK) { if (imageUploadFilePathCallbackOld == null || resultCode != Activity.RESULT_OK) {
Log.e(App.TAG, "Callback is null: " + (imageUploadFilePathCallbackOld == null) Log.e(App.TAG, "Callback is null: " + (imageUploadFilePathCallbackOld == null)
+ " resultCode: " + resultCode); + " resultCode: " + resultCode);
@ -606,14 +632,21 @@ public class MainActivity extends AppCompatActivity
Uri results = null; Uri results = null;
if (data == null) { if (data == null) {
if (mCameraPhotoPath != null) { if (mCameraPhotoPath != null) {
Log.v(App.TAG, "Intent has no data. Try to parse cameraPhotoPath");
results = Uri.parse(mCameraPhotoPath); results = Uri.parse(mCameraPhotoPath);
} else {
Log.w(App.TAG, "Intent has no data and cameraPhotoPath is null");
} }
} else { } else {
String dataString = data.getDataString(); String dataString = data.getDataString();
if (dataString != null) { if (dataString != null) {
Log.v(App.TAG, "Intent has data. Try to parse dataString");
results = Uri.parse(dataString); results = Uri.parse(dataString);
} else {
Log.w(App.TAG, "dataString is null");
} }
} }
Log.v(App.TAG, "handle received result over to callback");
imageUploadFilePathCallbackOld.onReceiveValue(results); imageUploadFilePathCallbackOld.onReceiveValue(results);
imageUploadFilePathCallbackOld = null; imageUploadFilePathCallbackOld = null;
return; return;
@ -624,25 +657,23 @@ public class MainActivity extends AppCompatActivity
@Override @Override
protected void onSaveInstanceState(Bundle outState) { protected void onSaveInstanceState(Bundle outState) {
Log.v(App.TAG, "MainActivity.onSaveInstanceState()");
super.onSaveInstanceState(outState); super.onSaveInstanceState(outState);
Log.v(App.TAG, "Save WebView state");
webView.saveState(outState); webView.saveState(outState);
} }
@Override @Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) { protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
Helpers.printBundle(savedInstanceState,""); Log.v(App.TAG, "MainActivity.onRestoreInstanceState()");
super.onRestoreInstanceState(savedInstanceState); super.onRestoreInstanceState(savedInstanceState);
Log.v(App.TAG, "Restore state of WebView");
webView.restoreState(savedInstanceState); webView.restoreState(savedInstanceState);
} }
@Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(brSetTitle, new IntentFilter(ACTION_UPDATE_TITLE_FROM_URL));
}
@Override @Override
public void onBackPressed() { public void onBackPressed() {
Log.v(App.TAG, "MainActivity.onBackPressed()");
if (navDrawer.isDrawerOpen(navView)) { if (navDrawer.isDrawerOpen(navView)) {
navDrawer.closeDrawer(navView); navDrawer.closeDrawer(navView);
return; return;
@ -658,12 +689,16 @@ public class MainActivity extends AppCompatActivity
} }
} }
/**
* BroadcastReceiver that updates the title of the activity based on which url is currently loaded
*/
private final BroadcastReceiver brSetTitle = new BroadcastReceiver() { private final BroadcastReceiver brSetTitle = new BroadcastReceiver() {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
String url = intent.getStringExtra(EXTRA_URL); String url = intent.getStringExtra(EXTRA_URL);
if (url != null && url.startsWith(urls.getPodUrl())) { if (url != null && url.startsWith(urls.getPodUrl())) {
String subUrl = url.substring((urls.getPodUrl()).length()); String subUrl = url.substring((urls.getPodUrl()).length());
Log.v(App.TAG, "MainActivity.brSetTitle.onReceive(): Set title for subUrl "+subUrl);
if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_STREAM)) { if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_STREAM)) {
setTitle(R.string.nav_stream); setTitle(R.string.nav_stream);
} else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_POSTS)) { } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_POSTS)) {
@ -689,26 +724,39 @@ public class MainActivity extends AppCompatActivity
} else if (urls.isAspectUrl(url)){ } else if (urls.isAspectUrl(url)){
setTitle(urls.getAspectNameFromUrl(url, app)); setTitle(urls.getAspectNameFromUrl(url, app));
} }
} else {
Log.w(App.TAG, "MainActivity.brSetTitle.onReceive(): Invalid url: "+url);
} }
} }
}; };
@Override @Override
protected void onPause() { protected void onPause() {
Log.v(App.TAG, "MainActivity.onPause()");
Log.v(App.TAG, "Unregister BroadcastReceivers");
LocalBroadcastManager.getInstance(this).unregisterReceiver(brSetTitle); LocalBroadcastManager.getInstance(this).unregisterReceiver(brSetTitle);
super.onPause(); super.onPause();
} }
@Override
protected void onResume() {
Log.v(App.TAG, "MainActivity.onResume()");
super.onResume();
Log.v(App.TAG, "Register BroadcastReceivers");
LocalBroadcastManager.getInstance(this).registerReceiver(brSetTitle, new IntentFilter(ACTION_UPDATE_TITLE_FROM_URL));
}
@Override @Override
public boolean onCreateOptionsMenu(Menu menu) { public boolean onCreateOptionsMenu(Menu menu) {
Log.v(App.TAG, "MainActivity.onCreateOptionsMenu()");
getMenuInflater().inflate(R.menu.main__menu_top, menu); getMenuInflater().inflate(R.menu.main__menu_top, menu);
return super.onCreateOptionsMenu(menu); return super.onCreateOptionsMenu(menu);
} }
@Override @Override
public boolean onPrepareOptionsMenu(Menu menu) { public boolean onPrepareOptionsMenu(Menu menu) {
Log.i(App.TAG, "MainActivity.onPrepareOptionsMenu()");
MenuItem item; MenuItem item;
if ((item = menu.findItem(R.id.action_notifications)) != null) { if ((item = menu.findItem(R.id.action_notifications)) != null) {
LayerDrawable icon = (LayerDrawable) item.getIcon(); LayerDrawable icon = (LayerDrawable) item.getIcon();
BadgeDrawable.setBadgeCount(this, icon, podUserProfile.getNotificationCount()); BadgeDrawable.setBadgeCount(this, icon, podUserProfile.getNotificationCount());
@ -723,6 +771,7 @@ public class MainActivity extends AppCompatActivity
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
Log.i(App.TAG, "MainActivity.onOptionsItemSelected()");
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.action_notifications: { case R.id.action_notifications: {
if (WebHelper.isOnline(MainActivity.this)) { if (WebHelper.isOnline(MainActivity.this)) {
@ -805,7 +854,7 @@ public class MainActivity extends AppCompatActivity
if (WebHelper.isOnline(MainActivity.this)) { if (WebHelper.isOnline(MainActivity.this)) {
final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
View layout = getLayoutInflater().inflate(R.layout.dialog_search__people_tags, contentLayout, false); View layout = getLayoutInflater().inflate(R.layout.dialog_search__people_tags, null, false);
final EditText input = (EditText) layout.findViewById(R.id.dialog_search__input); final EditText input = (EditText) layout.findViewById(R.id.dialog_search__input);
final DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() { final DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
@Override @Override
@ -857,6 +906,7 @@ public class MainActivity extends AppCompatActivity
@SuppressWarnings("ResultOfMethodCallIgnored") @SuppressWarnings("ResultOfMethodCallIgnored")
private boolean makeScreenshotOfWebView(boolean hasToShareScreenshot) { private boolean makeScreenshotOfWebView(boolean hasToShareScreenshot) {
Log.i(App.TAG, "MainActivity.makeScreenshotOfWebView()");
if (android.os.Build.VERSION.SDK_INT >= 23) { if (android.os.Build.VERSION.SDK_INT >= 23) {
int hasWRITE_EXTERNAL_STORAGE = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE); int hasWRITE_EXTERNAL_STORAGE = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (hasWRITE_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) { if (hasWRITE_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
@ -887,7 +937,9 @@ public class MainActivity extends AppCompatActivity
String fileSaveName = hasToShareScreenshot ? ".DfA_share.jpg" : String.format("DfA_%s.jpg", dateFormat.format(dateNow)); String fileSaveName = hasToShareScreenshot ? ".DfA_share.jpg" : String.format("DfA_%s.jpg", dateFormat.format(dateNow));
if (!fileSaveDirectory.exists()) { if (!fileSaveDirectory.exists()) {
fileSaveDirectory.mkdirs(); if(!fileSaveDirectory.mkdirs()) {
Log.w(App.TAG, "Could not mkdir "+fileSaveDirectory.getAbsolutePath());
}
} }
if (!hasToShareScreenshot) { if (!hasToShareScreenshot) {
@ -936,21 +988,33 @@ public class MainActivity extends AppCompatActivity
@Override @Override
public void onUserProfileNameChanged(String name) { public void onUserProfileNameChanged(String name) {
Log.i(App.TAG, "MainActivity.onUserProfileNameChanged()");
navheaderTitle.setText(name); navheaderTitle.setText(name);
} }
@Override @Override
public void onUserProfileAvatarChanged(String avatarUrl) { public void onUserProfileAvatarChanged(String avatarUrl) {
Log.i(App.TAG, "MainActivity.onUserProfileAvatarChanged()");
app.getAvatarImageLoader().startImageDownload(navheaderImage, avatarUrl); app.getAvatarImageLoader().startImageDownload(navheaderImage, avatarUrl);
} }
private void handleHashtag(Intent intent) { private void handleHashtag(Intent intent) {
Log.v(App.TAG, "handleHashtag()");
try {
setSharedTexts(null, intent.getData().toString().split("/")[3]); setSharedTexts(null, intent.getData().toString().split("/")[3]);
} catch (Exception e) {
Log.e(App.TAG, e.toString());
}
webView.loadUrlNew(urls.getNewPostUrl()); webView.loadUrlNew(urls.getNewPostUrl());
} }
private void handleSendText(Intent intent) { private void handleSendText(Intent intent) {
Log.v(App.TAG, "handleSendText()");
try {
setSharedTexts(null, intent.getStringExtra(Intent.EXTRA_TEXT)); setSharedTexts(null, intent.getStringExtra(Intent.EXTRA_TEXT));
} catch (Exception e) {
Log.e(App.TAG, e.toString());
}
webView.loadUrlNew(urls.getBlankUrl()); webView.loadUrlNew(urls.getBlankUrl());
webView.loadUrlNew(urls.getNewPostUrl()); webView.loadUrlNew(urls.getNewPostUrl());
} }
@ -961,8 +1025,13 @@ public class MainActivity extends AppCompatActivity
* @param intent intent * @param intent intent
*/ */
private void handleSendSubject(Intent intent) { private void handleSendSubject(Intent intent) {
Log.v(App.TAG, "handleSendSubject()");
try {
setSharedTexts(intent.getStringExtra(Intent.EXTRA_SUBJECT), intent.getStringExtra(Intent.EXTRA_TEXT)); setSharedTexts(intent.getStringExtra(Intent.EXTRA_SUBJECT), intent.getStringExtra(Intent.EXTRA_TEXT));
webView.loadUrlNew(urls.getBlankUrl()); } catch (Exception e) {
Log.e(App.TAG, e.toString());
}
webView.loadUrlNew(urls.getBlankUrl()); //TODO: Necessary?
webView.loadUrlNew(urls.getNewPostUrl()); webView.loadUrlNew(urls.getNewPostUrl());
} }
@ -975,15 +1044,19 @@ public class MainActivity extends AppCompatActivity
* @param sharedBody post text * @param sharedBody post text
*/ */
private void setSharedTexts(String sharedSubject, String sharedBody) { private void setSharedTexts(String sharedSubject, String sharedBody) {
Log.i(App.TAG, "MainActivity.setSharedTexts()");
String body = WebHelper.replaceUrlWithMarkdown(sharedBody); String body = WebHelper.replaceUrlWithMarkdown(sharedBody);
if (appSettings.isAppendSharedViaApp()) { if (appSettings.isAppendSharedViaApp()) {
Log.v(App.TAG, "Append app reference to shared text");
body = body + "\n\n" + getString(R.string.shared_by_diaspora_android); body = body + "\n\n" + getString(R.string.shared_by_diaspora_android);
} }
final String escapedBody = WebHelper.escapeHtmlText(body); final String escapedBody = WebHelper.escapeHtmlText(body);
if(sharedSubject != null) { if(sharedSubject != null) {
Log.v(App.TAG, "Append subject to shared text");
String escapedSubject = WebHelper.escapeHtmlText(WebHelper.replaceUrlWithMarkdown(sharedSubject)); String escapedSubject = WebHelper.escapeHtmlText(WebHelper.replaceUrlWithMarkdown(sharedSubject));
textToBeShared = "**" + escapedSubject + "** " + escapedBody; textToBeShared = "**" + escapedSubject + "** " + escapedBody;
} else { } else {
Log.v(App.TAG, "Set shared text; Subject: \""+sharedSubject+"\" Body: \""+sharedBody+"\"");
textToBeShared = escapedBody; textToBeShared = escapedBody;
} }
@ -992,9 +1065,13 @@ public class MainActivity extends AppCompatActivity
//TODO: Implement? //TODO: Implement?
private void handleSendImage(Intent intent) { private void handleSendImage(Intent intent) {
Log.i(App.TAG, "MainActivity.handleSendImage()");
final Uri imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM); final Uri imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (imageUri != null) { if (imageUri != null) {
Log.v(App.TAG, "imageUri is not null. Handle shared image");
// TODO: Update UI to reflect text being shared // TODO: Update UI to reflect text being shared
} else {
Log.w(App.TAG, "imageUri is null. Cannot precede.");
} }
Toast.makeText(this, "Not yet implemented.", Toast.LENGTH_SHORT).show(); Toast.makeText(this, "Not yet implemented.", Toast.LENGTH_SHORT).show();
} }
@ -1002,6 +1079,7 @@ public class MainActivity extends AppCompatActivity
// TODO: Move from Javascript interface // TODO: Move from Javascript interface
@Override @Override
public void onNotificationCountChanged(int notificationCount) { public void onNotificationCountChanged(int notificationCount) {
Log.i(App.TAG, "MainActivity.onNotificationCountChanged()");
// Count saved in PodUserProfile // Count saved in PodUserProfile
invalidateOptionsMenu(); invalidateOptionsMenu();
@ -1014,9 +1092,9 @@ public class MainActivity extends AppCompatActivity
// TODO: Move from Javascript interface // TODO: Move from Javascript interface
@Override @Override
public void onUnreadMessageCountChanged(int unreadMessageCount) { public void onUnreadMessageCountChanged(int unreadMessageCount) {
Log.i(App.TAG, "MainActivity.onUnreadMessageCountChanged()");
// Count saved in PodUserProfile // Count saved in PodUserProfile
invalidateOptionsMenu(); invalidateOptionsMenu();
if (unreadMessageCount > 0 && !snackbarNewNotification.isShown() if (unreadMessageCount > 0 && !snackbarNewNotification.isShown()
&& !webView.getUrl().equals(urls.getNotificationsUrl())) { && !webView.getUrl().equals(urls.getNotificationsUrl())) {
snackbarNewNotification.show(); snackbarNewNotification.show();
@ -1026,8 +1104,12 @@ public class MainActivity extends AppCompatActivity
private class JavaScriptInterface { private class JavaScriptInterface {
@JavascriptInterface @JavascriptInterface
public void setUserProfile(final String webMessage) throws JSONException { public void setUserProfile(final String webMessage) throws JSONException {
Log.i(App.TAG, "MainActivity.JavaScriptInterface.setUserProfile()");
if (podUserProfile.isRefreshNeeded()) { if (podUserProfile.isRefreshNeeded()) {
Log.v(App.TAG, "PodUserProfile needs refresh; Try to parse JSON");
podUserProfile.parseJson(webMessage); podUserProfile.parseJson(webMessage);
} else {
Log.v(App.TAG, "No PodUserProfile refresh needed");
} }
} }
@ -1040,6 +1122,7 @@ public class MainActivity extends AppCompatActivity
@SuppressWarnings("StatementWithEmptyBody") @SuppressWarnings("StatementWithEmptyBody")
@Override @Override
public boolean onNavigationItemSelected(MenuItem item) { public boolean onNavigationItemSelected(MenuItem item) {
Log.i(App.TAG, "MainActivity.onNavigationItemsSelected()");
// Handle navigation view item clicks here. // Handle navigation view item clicks here.
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.nav_stream: { case R.id.nav_stream: {
@ -1150,10 +1233,12 @@ public class MainActivity extends AppCompatActivity
@Override @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) { switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS_SAVE_IMAGE: case REQUEST_CODE__ACCESS_EXTERNAL_STORAGE:
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i(App.TAG, "MainActivity.onRequestPermissionsResult: Permission to access external storage granted");
Toast.makeText(this, R.string.permission_granted_try_again, Toast.LENGTH_SHORT).show(); Toast.makeText(this, R.string.permission_granted_try_again, Toast.LENGTH_SHORT).show();
} else { } else {
Log.w(App.TAG, "MainActivity.onRequestPermissionsResult: Permission to access external storage denied");
Toast.makeText(this, R.string.permission_denied, Toast.LENGTH_SHORT).show(); Toast.makeText(this, R.string.permission_denied, Toast.LENGTH_SHORT).show();
} }
return; return;
@ -1174,25 +1259,35 @@ public class MainActivity extends AppCompatActivity
* @throws IllegalArgumentException if arguments do not fit specifications above * @throws IllegalArgumentException if arguments do not fit specifications above
*/ */
private boolean setProxy(final String host, final int port) { private boolean setProxy(final String host, final int port) {
Log.i(App.TAG, "MainActivity.setProxy()");
if (host != null && !host.equals("") && port >= 0) { if (host != null && !host.equals("") && port >= 0) {
Log.i(App.TAG, "Set proxy to "+host+":"+port);
//Temporary change thread policy //Temporary change thread policy
Log.v(App.TAG, "Set temporary ThreadPolicy");
StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy(); StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy();
StrictMode.ThreadPolicy tmp = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.ThreadPolicy tmp = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(tmp); StrictMode.setThreadPolicy(tmp);
Log.v(App.TAG, "Apply NetCipher proxy settings");
NetCipher.setProxy(host, port); //Proxy for HttpsUrlConnections NetCipher.setProxy(host, port); //Proxy for HttpsUrlConnections
try { try {
//Proxy for the webview //Proxy for the webview
Log.v(App.TAG, "Apply Webkit proxy settings");
WebkitProxy.setProxy(MainActivity.class.getName(), getApplicationContext(), null, host, port); WebkitProxy.setProxy(MainActivity.class.getName(), getApplicationContext(), null, host, port);
} catch (Exception e) { /*Nothing we can do*/ } } catch (Exception e) {
Log.e(App.TAG, "Could not apply WebKit proxy settings:\n"+e.toString());
}
Log.v(App.TAG, "Save changes in appSettings");
appSettings.setProxyEnabled(true); appSettings.setProxyEnabled(true);
appSettings.setProxyWasEnabled(true); appSettings.setProxyWasEnabled(true);
Log.v(App.TAG, "Reset old ThreadPolicy");
StrictMode.setThreadPolicy(old); StrictMode.setThreadPolicy(old);
Log.i(App.TAG, "Success! Reload WebView");
webView.reload(); webView.reload();
return true; return true;
} else { } else {
Log.w(App.TAG, "Invalid proxy configuration. Host: "+host+" Port: "+port+"\nRefuse to set proxy");
return false; return false;
} }
} }
@ -1202,22 +1297,30 @@ public class MainActivity extends AppCompatActivity
} }
private void resetProxy() { private void resetProxy() {
Log.i(App.TAG, "MainActivity.resetProxy()");
Log.v(App.TAG, "write changes to appSettings");
appSettings.setProxyEnabled(false); appSettings.setProxyEnabled(false);
appSettings.setProxyWasEnabled(false); appSettings.setProxyWasEnabled(false);
//Temporary change thread policy //Temporary change thread policy
Log.v(App.TAG, "Set temporary ThreadPolicy");
StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy(); StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy();
StrictMode.ThreadPolicy tmp = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.ThreadPolicy tmp = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(tmp); StrictMode.setThreadPolicy(tmp);
Log.v(App.TAG, "clear NetCipher proxy");
NetCipher.clearProxy(); NetCipher.clearProxy();
try { try {
Log.v(App.TAG, "clear WebKit proxy");
WebkitProxy.resetProxy(MainActivity.class.getName(), this); WebkitProxy.resetProxy(MainActivity.class.getName(), this);
} catch (Exception e) {/*Nothing*/} } catch (Exception e) {
Log.e(App.TAG, "Could not clear WebKit proxy:\n"+e.toString());
}
Log.v(App.TAG, "Reset old ThreadPolicy");
StrictMode.setThreadPolicy(old); StrictMode.setThreadPolicy(old);
//Restart app //Restart app
Log.i(App.TAG, "Success! Restart app due to proxy reset");
Intent restartActivity = new Intent(this, MainActivity.class); Intent restartActivity = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 12374, restartActivity, PendingIntent.FLAG_CANCEL_CURRENT); PendingIntent pendingIntent = PendingIntent.getActivity(this, 12374, restartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE); AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

View file

@ -19,17 +19,14 @@
package com.github.dfa.diaspora_android.activity; package com.github.dfa.diaspora_android.activity;
import android.content.res.TypedArray;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import com.github.dfa.diaspora_android.App; import com.github.dfa.diaspora_android.App;
import com.github.dfa.diaspora_android.R; import com.github.dfa.diaspora_android.R;
import com.github.dfa.diaspora_android.util.Helpers; import com.github.dfa.diaspora_android.util.Helpers;
import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;

View file

@ -96,14 +96,14 @@ public class ContextMenuWebView extends NestedWebView {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
if (android.os.Build.VERSION.SDK_INT >= 23) if (android.os.Build.VERSION.SDK_INT >= 23)
parentActivity.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, parentActivity.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MainActivity.REQUEST_CODE_ASK_PERMISSIONS_SAVE_IMAGE); MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
} }
}) })
.setNegativeButton(context.getText(android.R.string.no), null) .setNegativeButton(context.getText(android.R.string.no), null)
.show(); .show();
} }
parentActivity.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, parentActivity.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MainActivity.REQUEST_CODE_ASK_PERMISSIONS_SAVE_IMAGE); MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
} }
} }
if (writeToStoragePermitted) { if (writeToStoragePermitted) {

View file

@ -1,6 +1,6 @@
package com.github.dfa.diaspora_android.util; package com.github.dfa.diaspora_android.util;
import com.github.dfa.diaspora_android.App; import com.github.dfa.diaspora_android.data.AppSettings;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
@ -14,13 +14,24 @@ import java.util.Observer;
* Created by vanitas on 09.09.16. * Created by vanitas on 09.09.16.
*/ */
public class Log extends Observable { public class Log extends Observable {
public static final int MAX_BUFFER_SIZE = 100;
public static Log instance; public static Log instance;
private AppSettings appSettings;
private SimpleDateFormat dateFormat; private SimpleDateFormat dateFormat;
private ArrayList<String> logBuffer; private ArrayList<String> logBuffer;
private ArrayList<Observer> observers; private ArrayList<Observer> observers;
private Log() { private Log() {
this(null);
}
private Log(AppSettings appSettings) {
if(appSettings != null) {
//TODO: Store/Restore logBuffer between app starts
logBuffer = new ArrayList<>(); logBuffer = new ArrayList<>();
} else {
logBuffer = new ArrayList<>();
}
dateFormat = new SimpleDateFormat("HH:mm:ss"); dateFormat = new SimpleDateFormat("HH:mm:ss");
observers = new ArrayList<>(); observers = new ArrayList<>();
} }
@ -30,6 +41,11 @@ public class Log extends Observable{
return instance; return instance;
} }
public static Log getInstance(AppSettings appSettings) {
if(instance == null) instance = new Log(appSettings);
return instance;
}
private static String time() { private static String time() {
return getInstance().dateFormat.format(new Date())+": "; return getInstance().dateFormat.format(new Date())+": ";
} }
@ -37,50 +53,50 @@ public class Log extends Observable{
public static void d(String tag, String msg) { public static void d(String tag, String msg) {
Log l = getInstance(); Log l = getInstance();
android.util.Log.d(tag, msg); android.util.Log.d(tag, msg);
l.logBuffer.add(time()+msg); l.addLogEntry(msg);
l.notifyLogBufferChanged(); l.notifyLogBufferChanged();
} }
public static void e(String tag, String msg) { public static void e(String tag, String msg) {
Log l = getInstance(); Log l = getInstance();
android.util.Log.e(tag, msg); android.util.Log.e(tag, msg);
l.logBuffer.add(time()+msg); l.addLogEntry(msg);
l.notifyLogBufferChanged(); l.notifyLogBufferChanged();
} }
public static void i(String tag, String msg) { public static void i(String tag, String msg) {
Log l = getInstance(); Log l = getInstance();
android.util.Log.i(tag, msg); android.util.Log.i(tag, msg);
l.logBuffer.add(time()+msg); l.addLogEntry(msg);
l.notifyLogBufferChanged(); l.notifyLogBufferChanged();
} }
public static void v(String tag, String msg) { public static void v(String tag, String msg) {
Log l = getInstance(); Log l = getInstance();
android.util.Log.v(tag, msg); android.util.Log.v(tag, msg);
l.logBuffer.add(time()+msg); l.addLogEntry(msg);
l.notifyLogBufferChanged(); l.notifyLogBufferChanged();
} }
public static void w(String tag, String msg) { public static void w(String tag, String msg) {
Log l = getInstance(); Log l = getInstance();
android.util.Log.w(tag, msg); android.util.Log.w(tag, msg);
l.logBuffer.add(time()+msg); l.addLogEntry(msg);
l.notifyLogBufferChanged(); l.notifyLogBufferChanged();
} }
public static void wtf(String tag, String msg) { public static void wtf(String tag, String msg) {
Log l = getInstance(); Log l = getInstance();
android.util.Log.wtf(tag, msg); android.util.Log.wtf(tag, msg);
l.logBuffer.add(time()+msg); l.addLogEntry(msg);
l.notifyLogBufferChanged(); l.notifyLogBufferChanged();
} }
public static ArrayList<String> getLogBufferArray() { public synchronized static ArrayList<String> getLogBufferArray() {
return getInstance().logBuffer; return getInstance().logBuffer;
} }
public static String getLogBuffer() { public synchronized static String getLogBuffer() {
String out = ""; String out = "";
for(String s : getInstance().logBuffer) { for(String s : getInstance().logBuffer) {
out = out + s + "\n"; out = out + s + "\n";
@ -97,6 +113,13 @@ public class Log extends Observable{
} }
} }
private synchronized void addLogEntry(String msg) {
logBuffer.add(time()+msg);
while (logBuffer.size() > MAX_BUFFER_SIZE) {
logBuffer.remove(0);
}
}
public static void addLogObserver(Observer observer) { public static void addLogObserver(Observer observer) {
getInstance().observers.add(observer); getInstance().observers.add(observer);
} }