Further reduce code calling back to the CommonsApplication by pulling out a SessionManager to manage our current account.

This commit is contained in:
Paul Hawke 2017-09-09 14:03:00 -05:00
parent e7d0c647c2
commit 9c0cbe7ad5
25 changed files with 273 additions and 294 deletions

View file

@ -1,11 +1,5 @@
package fr.free.nrw.commons; package fr.free.nrw.commons;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
@ -20,13 +14,12 @@ import org.acra.ReportingInteractionMode;
import org.acra.annotation.ReportsCrashes; import org.acra.annotation.ReportsCrashes;
import java.io.File; import java.io.File;
import java.io.IOException;
import javax.inject.Inject; import javax.inject.Inject;
import dagger.android.AndroidInjector; import dagger.android.AndroidInjector;
import dagger.android.DaggerApplication; import dagger.android.DaggerApplication;
import fr.free.nrw.commons.auth.AccountUtil; import fr.free.nrw.commons.auth.SessionManager;
import fr.free.nrw.commons.contributions.Contribution; import fr.free.nrw.commons.contributions.Contribution;
import fr.free.nrw.commons.data.Category; import fr.free.nrw.commons.data.Category;
import fr.free.nrw.commons.data.DBOpenHelper; import fr.free.nrw.commons.data.DBOpenHelper;
@ -37,6 +30,8 @@ import fr.free.nrw.commons.modifications.ModifierSequence;
import fr.free.nrw.commons.mwapi.MediaWikiApi; import fr.free.nrw.commons.mwapi.MediaWikiApi;
import fr.free.nrw.commons.theme.NavigationBaseActivity; import fr.free.nrw.commons.theme.NavigationBaseActivity;
import fr.free.nrw.commons.utils.FileUtils; import fr.free.nrw.commons.utils.FileUtils;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import timber.log.Timber; import timber.log.Timber;
// TODO: Use ProGuard to rip out reporting when publishing // TODO: Use ProGuard to rip out reporting when publishing
@ -51,10 +46,9 @@ import timber.log.Timber;
public class CommonsApplication extends DaggerApplication { public class CommonsApplication extends DaggerApplication {
@Inject MediaWikiApi mediaWikiApi; @Inject MediaWikiApi mediaWikiApi;
@Inject AccountUtil accountUtil; @Inject SessionManager sessionManager;
@Inject DBOpenHelper dbOpenHelper; @Inject DBOpenHelper dbOpenHelper;
private Account currentAccount = null; // Unlike a savings account...
public static final String API_URL = "https://commons.wikimedia.org/w/api.php"; public static final String API_URL = "https://commons.wikimedia.org/w/api.php";
public static final String IMAGE_URL_BASE = "https://upload.wikimedia.org/wikipedia/commons"; public static final String IMAGE_URL_BASE = "https://upload.wikimedia.org/wikipedia/commons";
public static final String HOME_URL = "https://commons.wikimedia.org/wiki/"; public static final String HOME_URL = "https://commons.wikimedia.org/wiki/";
@ -113,39 +107,6 @@ public class CommonsApplication extends DaggerApplication {
return component; return component;
} }
/**
* @return Account|null
*/
public Account getCurrentAccount() {
if (currentAccount == null) {
AccountManager accountManager = AccountManager.get(this);
Account[] allAccounts = accountManager.getAccountsByType(accountUtil.accountType());
if (allAccounts.length != 0) {
currentAccount = allAccounts[0];
}
}
return currentAccount;
}
public Boolean revalidateAuthToken() {
AccountManager accountManager = AccountManager.get(this);
Account curAccount = getCurrentAccount();
if (curAccount == null) {
return false; // This should never happen
}
accountManager.invalidateAuthToken(accountUtil.accountType(), mediaWikiApi.getAuthCookie());
try {
String authCookie = accountManager.blockingGetAuthToken(curAccount, "", false);
mediaWikiApi.setAuthCookie(authCookie);
return true;
} catch (OperationCanceledException | NullPointerException | IOException | AuthenticatorException e) {
e.printStackTrace();
return false;
}
}
public void clearApplicationData(Context context, NavigationBaseActivity.LogoutListener logoutListener) { public void clearApplicationData(Context context, NavigationBaseActivity.LogoutListener logoutListener) {
File cacheDirectory = context.getCacheDir(); File cacheDirectory = context.getCacheDir();
File applicationDirectory = new File(cacheDirectory.getParent()); File applicationDirectory = new File(cacheDirectory.getParent());
@ -158,36 +119,10 @@ public class CommonsApplication extends DaggerApplication {
} }
} }
AccountManager accountManager = AccountManager.get(this); sessionManager.clearAllAccounts()
Account[] allAccounts = accountManager.getAccountsByType(accountUtil.accountType()); .subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
AccountManagerCallback<Boolean> amCallback = new AccountManagerCallback<Boolean>() { .subscribe(() -> {
private int index = 0;
void setIndex(int index) {
this.index = index;
}
int getIndex() {
return index;
}
@Override
public void run(AccountManagerFuture<Boolean> accountManagerFuture) {
setIndex(getIndex() + 1);
try {
if (accountManagerFuture != null) {
if (accountManagerFuture.getResult()) {
Timber.d("Account removed successfully.");
}
}
} catch (OperationCanceledException | IOException | AuthenticatorException e) {
e.printStackTrace();
}
if (getIndex() == allAccounts.length) {
Timber.d("All accounts have been removed"); Timber.d("All accounts have been removed");
//TODO: fix preference manager //TODO: fix preference manager
PreferenceManager.getDefaultSharedPreferences(CommonsApplication.this).edit().clear().commit(); PreferenceManager.getDefaultSharedPreferences(CommonsApplication.this).edit().clear().commit();
@ -197,22 +132,15 @@ public class CommonsApplication extends DaggerApplication {
context.getSharedPreferences("prefs", Context.MODE_PRIVATE).edit().clear().commit(); context.getSharedPreferences("prefs", Context.MODE_PRIVATE).edit().clear().commit();
preferences.edit().putBoolean("firstrun", false).apply(); preferences.edit().putBoolean("firstrun", false).apply();
updateAllDatabases(); updateAllDatabases();
currentAccount = null;
logoutListener.onLogoutComplete(); logoutListener.onLogoutComplete();
} });
}
};
for (Account account : allAccounts) {
accountManager.removeAccount(account, amCallback, null);
}
} }
/** /**
* Deletes all tables and re-creates them. * Deletes all tables and re-creates them.
*/ */
public void updateAllDatabases() { private void updateAllDatabases() {
dbOpenHelper.getReadableDatabase().close(); dbOpenHelper.getReadableDatabase().close();
SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); SQLiteDatabase db = dbOpenHelper.getWritableDatabase();

View file

@ -18,7 +18,6 @@ import fr.free.nrw.commons.mwapi.MediaWikiApi;
import timber.log.Timber; import timber.log.Timber;
public class MediaWikiImageView extends SimpleDraweeView { public class MediaWikiImageView extends SimpleDraweeView {
@Inject CommonsApplication application;
@Inject MediaWikiApi mwApi; @Inject MediaWikiApi mwApi;
@Inject LruCache<String, String> thumbnailUrlCache; @Inject LruCache<String, String> thumbnailUrlCache;

View file

@ -4,24 +4,21 @@ import android.accounts.Account;
import android.accounts.AccountAuthenticatorResponse; import android.accounts.AccountAuthenticatorResponse;
import android.accounts.AccountManager; import android.accounts.AccountManager;
import android.content.ContentResolver; import android.content.ContentResolver;
import android.content.Context;
import android.os.Bundle; import android.os.Bundle;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import javax.inject.Inject;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.contributions.ContributionsContentProvider; import fr.free.nrw.commons.contributions.ContributionsContentProvider;
import fr.free.nrw.commons.modifications.ModificationsContentProvider; import fr.free.nrw.commons.modifications.ModificationsContentProvider;
import timber.log.Timber; import timber.log.Timber;
public class AccountUtil { public class AccountUtil {
private final CommonsApplication application; private Context context;
@Inject public AccountUtil(Context context) {
public AccountUtil(CommonsApplication application) { this.context = context;
this.application = application;
} }
public void createAccount(@Nullable AccountAuthenticatorResponse response, public void createAccount(@Nullable AccountAuthenticatorResponse response,
@ -60,7 +57,7 @@ public class AccountUtil {
} }
private AccountManager accountManager() { private AccountManager accountManager() {
return AccountManager.get(application); return AccountManager.get(context);
} }
} }

View file

@ -7,8 +7,6 @@ import android.os.Bundle;
import javax.inject.Inject; import javax.inject.Inject;
import dagger.android.AndroidInjection;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.theme.NavigationBaseActivity; import fr.free.nrw.commons.theme.NavigationBaseActivity;
import io.reactivex.Single; import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.android.schedulers.AndroidSchedulers;
@ -17,8 +15,8 @@ import timber.log.Timber;
public abstract class AuthenticatedActivity extends NavigationBaseActivity { public abstract class AuthenticatedActivity extends NavigationBaseActivity {
@Inject CommonsApplication app;
@Inject AccountUtil accountUtil; @Inject AccountUtil accountUtil;
@Inject SessionManager sessionManager;
private String authCookie; private String authCookie;
@ -59,7 +57,7 @@ public abstract class AuthenticatedActivity extends NavigationBaseActivity {
return; return;
} }
AccountManager accountManager = AccountManager.get(this); AccountManager accountManager = AccountManager.get(this);
Account curAccount = app.getCurrentAccount(); Account curAccount = sessionManager.getCurrentAccount();
if(curAccount == null) { if(curAccount == null) {
addAccount(accountManager); addAccount(accountManager);
} else { } else {

View file

@ -19,11 +19,9 @@ import javax.inject.Inject;
import dagger.android.AndroidInjection; import dagger.android.AndroidInjection;
import fr.free.nrw.commons.BuildConfig; import fr.free.nrw.commons.BuildConfig;
import fr.free.nrw.commons.CommonsApplication; import fr.free.nrw.commons.PageTitle;
import fr.free.nrw.commons.R; import fr.free.nrw.commons.R;
import fr.free.nrw.commons.WelcomeActivity; import fr.free.nrw.commons.WelcomeActivity;
import fr.free.nrw.commons.PageTitle;
import fr.free.nrw.commons.contributions.ContributionsActivity; import fr.free.nrw.commons.contributions.ContributionsActivity;
import fr.free.nrw.commons.mwapi.MediaWikiApi; import fr.free.nrw.commons.mwapi.MediaWikiApi;
import timber.log.Timber; import timber.log.Timber;
@ -36,9 +34,9 @@ public class LoginActivity extends AccountAuthenticatorActivity {
public static final String PARAM_USERNAME = "fr.free.nrw.commons.login.username"; public static final String PARAM_USERNAME = "fr.free.nrw.commons.login.username";
@Inject CommonsApplication application;
@Inject MediaWikiApi mwApi; @Inject MediaWikiApi mwApi;
@Inject AccountUtil accountUtil; @Inject AccountUtil accountUtil;
@Inject SessionManager sessionManager;
private SharedPreferences prefs = null; private SharedPreferences prefs = null;
@ -114,7 +112,7 @@ public class LoginActivity extends AccountAuthenticatorActivity {
WelcomeActivity.startYourself(this); WelcomeActivity.startYourself(this);
prefs.edit().putBoolean("firstrun", false).apply(); prefs.edit().putBoolean("firstrun", false).apply();
} }
if (application.getCurrentAccount() != null) { if (sessionManager.getCurrentAccount() != null) {
startMainActivity(); startMainActivity();
} }
} }
@ -147,7 +145,7 @@ public class LoginActivity extends AccountAuthenticatorActivity {
canonicializeUsername(usernameEdit.getText().toString()), canonicializeUsername(usernameEdit.getText().toString()),
passwordEdit.getText().toString(), passwordEdit.getText().toString(),
twoFactorEdit.getText().toString(), twoFactorEdit.getText().toString(),
accountUtil, application, mwApi accountUtil, this, mwApi
); );
} }

View file

@ -3,6 +3,7 @@ package fr.free.nrw.commons.auth;
import android.accounts.AccountAuthenticatorResponse; import android.accounts.AccountAuthenticatorResponse;
import android.accounts.AccountManager; import android.accounts.AccountManager;
import android.app.ProgressDialog; import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
@ -21,16 +22,18 @@ class LoginTask extends AsyncTask<String, String, String> {
private String password; private String password;
private String twoFactorCode = ""; private String twoFactorCode = "";
private AccountUtil accountUtil; private AccountUtil accountUtil;
private CommonsApplication app; private Context context;
private MediaWikiApi mwApi; private MediaWikiApi mwApi;
public LoginTask(LoginActivity loginActivity, String username, String password, String twoFactorCode, AccountUtil accountUtil, CommonsApplication application, MediaWikiApi mwApi) { public LoginTask(LoginActivity loginActivity, String username, String password,
String twoFactorCode, AccountUtil accountUtil,
Context context, MediaWikiApi mwApi) {
this.loginActivity = loginActivity; this.loginActivity = loginActivity;
this.username = username; this.username = username;
this.password = password; this.password = password;
this.twoFactorCode = twoFactorCode; this.twoFactorCode = twoFactorCode;
this.accountUtil = accountUtil; this.accountUtil = accountUtil;
this.app = application; this.context = context;
this.mwApi = mwApi; this.mwApi = mwApi;
} }
@ -64,7 +67,7 @@ class LoginTask extends AsyncTask<String, String, String> {
super.onPostExecute(result); super.onPostExecute(result);
Timber.d("Login done!"); Timber.d("Login done!");
EventLog.schema(CommonsApplication.EVENT_LOGIN_ATTEMPT, app, mwApi) EventLog.schema(CommonsApplication.EVENT_LOGIN_ATTEMPT, context, mwApi)
.param("username", username) .param("username", username)
.param("result", result) .param("result", result)
.log(); .log();

View file

@ -0,0 +1,71 @@
package fr.free.nrw.commons.auth;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.content.Context;
import java.io.IOException;
import fr.free.nrw.commons.mwapi.MediaWikiApi;
import io.reactivex.Completable;
import io.reactivex.Observable;
/**
* Manage the current logged in user session.
*/
public class SessionManager {
private final Context context;
private final AccountUtil accountUtil;
private final MediaWikiApi mediaWikiApi;
private Account currentAccount; // Unlike a savings account... ;-)
public SessionManager(Context context, AccountUtil accountUtil, MediaWikiApi mediaWikiApi) {
this.context = context;
this.accountUtil = accountUtil;
this.mediaWikiApi = mediaWikiApi;
this.currentAccount = null;
}
/**
* @return Account|null
*/
public Account getCurrentAccount() {
if (currentAccount == null) {
AccountManager accountManager = AccountManager.get(context);
Account[] allAccounts = accountManager.getAccountsByType(accountUtil.accountType());
if (allAccounts.length != 0) {
currentAccount = allAccounts[0];
}
}
return currentAccount;
}
public Boolean revalidateAuthToken() {
AccountManager accountManager = AccountManager.get(context);
Account curAccount = getCurrentAccount();
if (curAccount == null) {
return false; // This should never happen
}
accountManager.invalidateAuthToken(accountUtil.accountType(), mediaWikiApi.getAuthCookie());
try {
String authCookie = accountManager.blockingGetAuthToken(curAccount, "", false);
mediaWikiApi.setAuthCookie(authCookie);
return true;
} catch (OperationCanceledException | NullPointerException | IOException | AuthenticatorException e) {
e.printStackTrace();
return false;
}
}
public Completable clearAllAccounts() {
AccountManager accountManager = AccountManager.get(context);
Account[] allAccounts = accountManager.getAccountsByType(accountUtil.accountType());
return Completable.fromObservable(Observable.fromArray(allAccounts)
.map(a -> accountManager.removeAccount(a, null, null).getResult()))
.doOnComplete(() -> currentAccount = null);
}
}

View file

@ -6,16 +6,11 @@ import android.webkit.WebView;
import android.webkit.WebViewClient; import android.webkit.WebViewClient;
import android.widget.Toast; import android.widget.Toast;
import javax.inject.Inject;
import dagger.android.AndroidInjection;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.theme.BaseActivity; import fr.free.nrw.commons.theme.BaseActivity;
import timber.log.Timber; import timber.log.Timber;
public class SignupActivity extends BaseActivity { public class SignupActivity extends BaseActivity {
@Inject CommonsApplication application;
private WebView webView; private WebView webView;
@Override @Override
@ -41,11 +36,8 @@ public class SignupActivity extends BaseActivity {
//Signup success, so clear cookies, notify user, and load LoginActivity again //Signup success, so clear cookies, notify user, and load LoginActivity again
Timber.d("Overriding URL %s", url); Timber.d("Overriding URL %s", url);
Toast toast = Toast.makeText( Toast toast = Toast.makeText(SignupActivity.this,
application, "Account created!", Toast.LENGTH_LONG);
"Account created!",
Toast.LENGTH_LONG
);
toast.show(); toast.show();
// terminate on task completion. // terminate on task completion.
finish(); finish();

View file

@ -13,7 +13,6 @@ import android.text.TextUtils;
import javax.inject.Inject; import javax.inject.Inject;
import dagger.android.AndroidInjection; import dagger.android.AndroidInjection;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.data.Category; import fr.free.nrw.commons.data.Category;
import fr.free.nrw.commons.data.DBOpenHelper; import fr.free.nrw.commons.data.DBOpenHelper;
import timber.log.Timber; import timber.log.Timber;
@ -39,7 +38,6 @@ public class CategoryContentProvider extends ContentProvider {
return Uri.parse(BASE_URI.toString() + "/" + id); return Uri.parse(BASE_URI.toString() + "/" + id);
} }
@Inject CommonsApplication application;
@Inject DBOpenHelper dbOpenHelper; @Inject DBOpenHelper dbOpenHelper;
@Override @Override

View file

@ -27,12 +27,11 @@ import java.util.ArrayList;
import javax.inject.Inject; import javax.inject.Inject;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import dagger.android.AndroidInjection;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.HandlerService; import fr.free.nrw.commons.HandlerService;
import fr.free.nrw.commons.Media; import fr.free.nrw.commons.Media;
import fr.free.nrw.commons.R; import fr.free.nrw.commons.R;
import fr.free.nrw.commons.auth.AuthenticatedActivity; import fr.free.nrw.commons.auth.AuthenticatedActivity;
import fr.free.nrw.commons.auth.SessionManager;
import fr.free.nrw.commons.media.MediaDetailPagerFragment; import fr.free.nrw.commons.media.MediaDetailPagerFragment;
import fr.free.nrw.commons.mwapi.MediaWikiApi; import fr.free.nrw.commons.mwapi.MediaWikiApi;
import fr.free.nrw.commons.settings.Prefs; import fr.free.nrw.commons.settings.Prefs;
@ -42,16 +41,15 @@ import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers; import io.reactivex.schedulers.Schedulers;
import timber.log.Timber; import timber.log.Timber;
public class ContributionsActivity public class ContributionsActivity extends AuthenticatedActivity
extends AuthenticatedActivity implements LoaderManager.LoaderCallbacks<Cursor>,
implements LoaderManager.LoaderCallbacks<Cursor>, AdapterView.OnItemClickListener,
AdapterView.OnItemClickListener, MediaDetailPagerFragment.MediaDetailProvider,
MediaDetailPagerFragment.MediaDetailProvider, FragmentManager.OnBackStackChangedListener,
FragmentManager.OnBackStackChangedListener, ContributionsListFragment.SourceRefresher {
ContributionsListFragment.SourceRefresher {
@Inject CommonsApplication application;
@Inject MediaWikiApi mediaWikiApi; @Inject MediaWikiApi mediaWikiApi;
@Inject SessionManager sessionManager;
private Cursor allContributions; private Cursor allContributions;
private ContributionsListFragment contributionsList; private ContributionsListFragment contributionsList;
@ -77,7 +75,7 @@ public class ContributionsActivity
private ServiceConnection uploadServiceConnection = new ServiceConnection() { private ServiceConnection uploadServiceConnection = new ServiceConnection() {
@Override @Override
public void onServiceConnected(ComponentName componentName, IBinder binder) { public void onServiceConnected(ComponentName componentName, IBinder binder) {
uploadService = (UploadService) ((HandlerService.HandlerServiceLocalBinder)binder).getService(); uploadService = (UploadService) ((HandlerService.HandlerServiceLocalBinder) binder).getService();
isUploadServiceConnected = true; isUploadServiceConnected = true;
} }
@ -93,7 +91,7 @@ public class ContributionsActivity
compositeDisposable.clear(); compositeDisposable.clear();
getSupportFragmentManager().removeOnBackStackChangedListener(this); getSupportFragmentManager().removeOnBackStackChangedListener(this);
super.onDestroy(); super.onDestroy();
if(isUploadServiceConnected) { if (isUploadServiceConnected) {
unbindService(uploadServiceConnection); unbindService(uploadServiceConnection);
} }
} }
@ -103,9 +101,9 @@ public class ContributionsActivity
super.onResume(); super.onResume();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean isSettingsChanged = boolean isSettingsChanged =
sharedPreferences.getBoolean(Prefs.IS_CONTRIBUTION_COUNT_CHANGED,false); sharedPreferences.getBoolean(Prefs.IS_CONTRIBUTION_COUNT_CHANGED, false);
SharedPreferences.Editor editor = sharedPreferences.edit(); SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(Prefs.IS_CONTRIBUTION_COUNT_CHANGED,false); editor.putBoolean(Prefs.IS_CONTRIBUTION_COUNT_CHANGED, false);
editor.apply(); editor.apply();
if (isSettingsChanged) { if (isSettingsChanged) {
refreshSource(); refreshSource();
@ -115,7 +113,7 @@ public class ContributionsActivity
@Override @Override
protected void onAuthCookieAcquired(String authCookie) { protected void onAuthCookieAcquired(String authCookie) {
// Do a sync everytime we get here! // Do a sync everytime we get here!
ContentResolver.requestSync(application.getCurrentAccount(), ContributionsContentProvider.AUTHORITY, new Bundle()); ContentResolver.requestSync(sessionManager.getCurrentAccount(), ContributionsContentProvider.AUTHORITY, new Bundle());
Intent uploadServiceIntent = new Intent(this, UploadService.class); Intent uploadServiceIntent = new Intent(this, UploadService.class);
uploadServiceIntent.setAction(UploadService.ACTION_START_SERVICE); uploadServiceIntent.setAction(UploadService.ACTION_START_SERVICE);
startService(uploadServiceIntent); startService(uploadServiceIntent);
@ -134,12 +132,12 @@ public class ContributionsActivity
// Activity can call methods in the fragment by acquiring a // Activity can call methods in the fragment by acquiring a
// reference to the Fragment from FragmentManager, using findFragmentById() // reference to the Fragment from FragmentManager, using findFragmentById()
contributionsList = (ContributionsListFragment)getSupportFragmentManager() contributionsList = (ContributionsListFragment) getSupportFragmentManager()
.findFragmentById(R.id.contributionsListFragment); .findFragmentById(R.id.contributionsListFragment);
getSupportFragmentManager().addOnBackStackChangedListener(this); getSupportFragmentManager().addOnBackStackChangedListener(this);
if (savedInstanceState != null) { if (savedInstanceState != null) {
mediaDetails = (MediaDetailPagerFragment)getSupportFragmentManager() mediaDetails = (MediaDetailPagerFragment) getSupportFragmentManager()
.findFragmentById(R.id.contributionsFragmentContainer); .findFragmentById(R.id.contributionsFragmentContainer);
} }
requestAuthToken(); requestAuthToken();
@ -153,11 +151,13 @@ public class ContributionsActivity
outState.putBoolean("mediaDetailsVisible", (mediaDetails != null && mediaDetails.isVisible())); outState.putBoolean("mediaDetailsVisible", (mediaDetails != null && mediaDetails.isVisible()));
} }
/** Replace whatever is in the current contributionsFragmentContainer view with mediaDetailPagerFragment, /**
/ and preserve previous state in back stack. * Replace whatever is in the current contributionsFragmentContainer view with mediaDetailPagerFragment,
/ Called when user selects a contribution. */ * / and preserve previous state in back stack.
* / Called when user selects a contribution.
*/
private void showDetail(int i) { private void showDetail(int i) {
if(mediaDetails == null ||!mediaDetails.isVisible()) { if (mediaDetails == null || !mediaDetails.isVisible()) {
mediaDetails = new MediaDetailPagerFragment(); mediaDetails = new MediaDetailPagerFragment();
this.getSupportFragmentManager() this.getSupportFragmentManager()
.beginTransaction() .beginTransaction()
@ -172,7 +172,7 @@ public class ContributionsActivity
public void retryUpload(int i) { public void retryUpload(int i) {
allContributions.moveToPosition(i); allContributions.moveToPosition(i);
Contribution c = Contribution.fromCursor(allContributions); Contribution c = Contribution.fromCursor(allContributions);
if(c.getState() == Contribution.STATE_FAILED) { if (c.getState() == Contribution.STATE_FAILED) {
uploadService.queue(UploadService.ACTION_UPLOAD_FILE, c); uploadService.queue(UploadService.ACTION_UPLOAD_FILE, c);
Timber.d("Restarting for %s", c.toContentValues()); Timber.d("Restarting for %s", c.toContentValues());
} else { } else {
@ -183,7 +183,7 @@ public class ContributionsActivity
public void deleteUpload(int i) { public void deleteUpload(int i) {
allContributions.moveToPosition(i); allContributions.moveToPosition(i);
Contribution c = Contribution.fromCursor(allContributions); Contribution c = Contribution.fromCursor(allContributions);
if(c.getState() == Contribution.STATE_FAILED) { if (c.getState() == Contribution.STATE_FAILED) {
Timber.d("Deleting failed contrib %s", c.toContentValues()); Timber.d("Deleting failed contrib %s", c.toContentValues());
c.setContentProviderClient(getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY)); c.setContentProviderClient(getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY));
c.delete(); c.delete();
@ -194,9 +194,9 @@ public class ContributionsActivity
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) { switch (item.getItemId()) {
case android.R.id.home: case android.R.id.home:
if(mediaDetails.isVisible()) { if (mediaDetails.isVisible()) {
getSupportFragmentManager().popBackStack(); getSupportFragmentManager().popBackStack();
} }
return true; return true;
@ -232,11 +232,11 @@ public class ContributionsActivity
@Override @Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
if(contributionsList.getAdapter() == null) { if (contributionsList.getAdapter() == null) {
contributionsList contributionsList
.setAdapter(new ContributionsListAdapter(getApplicationContext(), cursor, 0)); .setAdapter(new ContributionsListAdapter(getApplicationContext(), cursor, 0));
} else { } else {
((CursorAdapter)contributionsList.getAdapter()).swapCursor(cursor); ((CursorAdapter) contributionsList.getAdapter()).swapCursor(cursor);
} }
setUploadCount(); setUploadCount();
@ -256,14 +256,14 @@ public class ContributionsActivity
if (contributionsList.getAdapter() == null) { if (contributionsList.getAdapter() == null) {
// not yet ready to return data // not yet ready to return data
return null; return null;
} else { } else {
return Contribution.fromCursor((Cursor) contributionsList.getAdapter().getItem(i)); return Contribution.fromCursor((Cursor) contributionsList.getAdapter().getItem(i));
} }
} }
@Override @Override
public int getTotalMediaCount() { public int getTotalMediaCount() {
if(contributionsList.getAdapter() == null) { if (contributionsList.getAdapter() == null) {
return 0; return 0;
} }
return contributionsList.getAdapter().getCount(); return contributionsList.getAdapter().getCount();
@ -272,7 +272,7 @@ public class ContributionsActivity
private void setUploadCount() { private void setUploadCount() {
compositeDisposable.add( compositeDisposable.add(
mediaWikiApi mediaWikiApi
.getUploadCount(application.getCurrentAccount().name) .getUploadCount(sessionManager.getCurrentAccount().name)
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe( .subscribe(

View file

@ -13,7 +13,6 @@ import android.text.TextUtils;
import javax.inject.Inject; import javax.inject.Inject;
import dagger.android.AndroidInjection; import dagger.android.AndroidInjection;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.data.DBOpenHelper; import fr.free.nrw.commons.data.DBOpenHelper;
import timber.log.Timber; import timber.log.Timber;
@ -37,7 +36,6 @@ public class ContributionsContentProvider extends ContentProvider{
return Uri.parse(BASE_URI.toString() + "/" + id); return Uri.parse(BASE_URI.toString() + "/" + id);
} }
@Inject CommonsApplication application;
@Inject DBOpenHelper dbOpenHelper; @Inject DBOpenHelper dbOpenHelper;
@Override @Override

View file

@ -7,7 +7,6 @@ import android.content.pm.PackageManager;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat; import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater; import android.view.LayoutInflater;
@ -21,12 +20,9 @@ import android.widget.GridView;
import android.widget.ListAdapter; import android.widget.ListAdapter;
import android.widget.TextView; import android.widget.TextView;
import javax.inject.Inject;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import dagger.android.support.DaggerFragment; import dagger.android.support.DaggerFragment;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.R; import fr.free.nrw.commons.R;
import fr.free.nrw.commons.nearby.NearbyActivity; import fr.free.nrw.commons.nearby.NearbyActivity;
import timber.log.Timber; import timber.log.Timber;
@ -44,8 +40,6 @@ public class ContributionsListFragment extends DaggerFragment {
@BindView(R.id.waitingMessage) TextView waitingMessage; @BindView(R.id.waitingMessage) TextView waitingMessage;
@BindView(R.id.emptyMessage) TextView emptyMessage; @BindView(R.id.emptyMessage) TextView emptyMessage;
@Inject CommonsApplication application;
private ContributionController controller; private ContributionController controller;
@Override @Override

View file

@ -7,6 +7,8 @@ import javax.inject.Singleton;
import dagger.Module; import dagger.Module;
import dagger.Provides; import dagger.Provides;
import fr.free.nrw.commons.CommonsApplication; import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.auth.AccountUtil;
import fr.free.nrw.commons.auth.SessionManager;
import fr.free.nrw.commons.caching.CacheController; import fr.free.nrw.commons.caching.CacheController;
import fr.free.nrw.commons.data.DBOpenHelper; import fr.free.nrw.commons.data.DBOpenHelper;
import fr.free.nrw.commons.mwapi.ApacheHttpClientMediaWikiApi; import fr.free.nrw.commons.mwapi.ApacheHttpClientMediaWikiApi;
@ -22,8 +24,14 @@ public class CommonsApplicationModule {
} }
@Provides @Provides
public CommonsApplication providesCommonsApplication() { public AccountUtil providesAccountUtil() {
return application; return new AccountUtil(application);
}
@Provides
@Singleton
public SessionManager providesSessionManager(AccountUtil accountUtil, MediaWikiApi mediaWikiApi) {
return new SessionManager(application, accountUtil, mediaWikiApi);
} }
@Provides @Provides
@ -40,7 +48,7 @@ public class CommonsApplicationModule {
@Provides @Provides
@Singleton @Singleton
public DBOpenHelper provideDBOpenHelper(CommonsApplication application) { public DBOpenHelper provideDBOpenHelper() {
return new DBOpenHelper(application); return new DBOpenHelper(application);
} }

View file

@ -33,6 +33,7 @@ import dagger.android.support.DaggerFragment;
import fr.free.nrw.commons.CommonsApplication; import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.Media; import fr.free.nrw.commons.Media;
import fr.free.nrw.commons.R; import fr.free.nrw.commons.R;
import fr.free.nrw.commons.auth.SessionManager;
import fr.free.nrw.commons.contributions.Contribution; import fr.free.nrw.commons.contributions.Contribution;
import fr.free.nrw.commons.contributions.ContributionsActivity; import fr.free.nrw.commons.contributions.ContributionsActivity;
import fr.free.nrw.commons.mwapi.EventLog; import fr.free.nrw.commons.mwapi.EventLog;
@ -52,8 +53,8 @@ public class MediaDetailPagerFragment extends DaggerFragment implements ViewPage
void unregisterDataSetObserver(DataSetObserver observer); void unregisterDataSetObserver(DataSetObserver observer);
} }
@Inject CommonsApplication application;
@Inject MediaWikiApi mwApi; @Inject MediaWikiApi mwApi;
@Inject SessionManager sessionManager;
private ViewPager pager; private ViewPager pager;
private Boolean editable; private Boolean editable;
@ -85,7 +86,7 @@ public class MediaDetailPagerFragment extends DaggerFragment implements ViewPage
@Override @Override
public int getCount() { public int getCount() {
return ((MediaDetailProvider)getActivity()).getTotalMediaCount(); return ((MediaDetailProvider) getActivity()).getTotalMediaCount();
} }
} }
@ -131,13 +132,13 @@ public class MediaDetailPagerFragment extends DaggerFragment implements ViewPage
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
MediaDetailProvider provider = (MediaDetailProvider)getActivity(); MediaDetailProvider provider = (MediaDetailProvider) getActivity();
Media m = provider.getMediaAtPosition(pager.getCurrentItem()); Media m = provider.getMediaAtPosition(pager.getCurrentItem());
switch(item.getItemId()) { switch (item.getItemId()) {
case R.id.menu_share_current_image: case R.id.menu_share_current_image:
// Share - this is just logs it, intent set in onCreateOptionsMenu, around line 252 // Share - this is just logs it, intent set in onCreateOptionsMenu, around line 252
EventLog.schema(CommonsApplication.EVENT_SHARE_ATTEMPT, application, mwApi) EventLog.schema(CommonsApplication.EVENT_SHARE_ATTEMPT, getContext().getApplicationContext(), mwApi)
.param("username", application.getCurrentAccount().name) .param("username", sessionManager.getCurrentAccount().name)
.param("filename", m.getFilename()) .param("filename", m.getFilename())
.log(); .log();
return true; return true;
@ -154,12 +155,12 @@ public class MediaDetailPagerFragment extends DaggerFragment implements ViewPage
return true; return true;
case R.id.menu_retry_current_image: case R.id.menu_retry_current_image:
// Retry // Retry
((ContributionsActivity)getActivity()).retryUpload(pager.getCurrentItem()); ((ContributionsActivity) getActivity()).retryUpload(pager.getCurrentItem());
getActivity().getSupportFragmentManager().popBackStack(); getActivity().getSupportFragmentManager().popBackStack();
return true; return true;
case R.id.menu_cancel_current_image: case R.id.menu_cancel_current_image:
// todo: delete image // todo: delete image
((ContributionsActivity)getActivity()).deleteUpload(pager.getCurrentItem()); ((ContributionsActivity) getActivity()).deleteUpload(pager.getCurrentItem());
getActivity().getSupportFragmentManager().popBackStack(); getActivity().getSupportFragmentManager().popBackStack();
return true; return true;
default: default:
@ -175,7 +176,7 @@ public class MediaDetailPagerFragment extends DaggerFragment implements ViewPage
*/ */
private void downloadMedia(Media m) { private void downloadMedia(Media m) {
String imageUrl = m.getImageUrl(), String imageUrl = m.getImageUrl(),
fileName = m.getFilename(); fileName = m.getFilename();
// Strip 'File:' from beginning of filename, we really shouldn't store it // Strip 'File:' from beginning of filename, we really shouldn't store it
fileName = fileName.replaceFirst("^File:", ""); fileName = fileName.replaceFirst("^File:", "");
Uri imageUri = Uri.parse(imageUrl); Uri imageUri = Uri.parse(imageUrl);
@ -190,13 +191,16 @@ public class MediaDetailPagerFragment extends DaggerFragment implements ViewPage
req.allowScanningByMediaScanner(); req.allowScanningByMediaScanner();
req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !(ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
!(ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_GRANTED)) {
Snackbar.make(getView(), R.string.storage_permission_rationale, Snackbar.make(getView(), R.string.storage_permission_rationale,
Snackbar.LENGTH_INDEFINITE) Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.ok, view -> ActivityCompat.requestPermissions(getActivity(), .setAction(R.string.ok, view -> ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1)).show(); new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1)).show();
} else { } else {
final DownloadManager manager = (DownloadManager)getActivity().getSystemService(Context.DOWNLOAD_SERVICE); final DownloadManager manager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(req); manager.enqueue(req);
} }
} }
@ -207,7 +211,7 @@ public class MediaDetailPagerFragment extends DaggerFragment implements ViewPage
menu.clear(); // see http://stackoverflow.com/a/8495697/17865 menu.clear(); // see http://stackoverflow.com/a/8495697/17865
inflater.inflate(R.menu.fragment_image_detail, menu); inflater.inflate(R.menu.fragment_image_detail, menu);
if (pager != null) { if (pager != null) {
MediaDetailProvider provider = (MediaDetailProvider)getActivity(); MediaDetailProvider provider = (MediaDetailProvider) getActivity();
Media m = provider.getMediaAtPosition(pager.getCurrentItem()); Media m = provider.getMediaAtPosition(pager.getCurrentItem());
if (m != null) { if (m != null) {
// Enable default set of actions, then re-enable different set of actions only if it is a failed contrib // Enable default set of actions, then re-enable different set of actions only if it is a failed contrib
@ -230,8 +234,8 @@ public class MediaDetailPagerFragment extends DaggerFragment implements ViewPage
} }
if (m instanceof Contribution) { if (m instanceof Contribution) {
Contribution c = (Contribution)m; Contribution c = (Contribution) m;
switch(c.getState()) { switch (c.getState()) {
case Contribution.STATE_FAILED: case Contribution.STATE_FAILED:
menu.findItem(R.id.menu_retry_current_image).setEnabled(true).setVisible(true); menu.findItem(R.id.menu_retry_current_image).setEnabled(true).setVisible(true);
menu.findItem(R.id.menu_cancel_current_image).setEnabled(true).setVisible(true); menu.findItem(R.id.menu_cancel_current_image).setEnabled(true).setVisible(true);

View file

@ -13,7 +13,6 @@ import android.text.TextUtils;
import javax.inject.Inject; import javax.inject.Inject;
import dagger.android.AndroidInjection; import dagger.android.AndroidInjection;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.data.DBOpenHelper; import fr.free.nrw.commons.data.DBOpenHelper;
import timber.log.Timber; import timber.log.Timber;
@ -37,7 +36,6 @@ public class ModificationsContentProvider extends ContentProvider{
return Uri.parse(BASE_URI.toString() + "/" + id); return Uri.parse(BASE_URI.toString() + "/" + id);
} }
@Inject CommonsApplication application;
@Inject DBOpenHelper dbOpenHelper; @Inject DBOpenHelper dbOpenHelper;
@Override @Override

View file

@ -1,8 +1,8 @@
package fr.free.nrw.commons.mwapi; package fr.free.nrw.commons.mwapi;
import android.content.Context;
import android.os.Build; import android.os.Build;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.Utils; import fr.free.nrw.commons.Utils;
public class EventLog { public class EventLog {
@ -16,14 +16,14 @@ public class EventLog {
} }
} }
private static LogBuilder schema(String schema, long revision, CommonsApplication application, MediaWikiApi mwApi) { private static LogBuilder schema(String schema, long revision, Context context, MediaWikiApi mwApi) {
return new LogBuilder(schema, revision, application, mwApi); return new LogBuilder(schema, revision, context, mwApi);
} }
public static LogBuilder schema(Object[] scid, CommonsApplication application, MediaWikiApi mwApi) { public static LogBuilder schema(Object[] scid, Context context, MediaWikiApi mwApi) {
if (scid.length != 2) { if (scid.length != 2) {
throw new IllegalArgumentException("Needs an object array with schema as first param and revision as second"); throw new IllegalArgumentException("Needs an object array with schema as first param and revision as second");
} }
return schema((String) scid[0], (Long) scid[1], application, mwApi); return schema((String) scid[0], (Long) scid[1], context, mwApi);
} }
} }

View file

@ -1,5 +1,6 @@
package fr.free.nrw.commons.mwapi; package fr.free.nrw.commons.mwapi;
import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Build; import android.os.Build;
@ -18,17 +19,17 @@ import fr.free.nrw.commons.settings.Prefs;
@SuppressWarnings("WeakerAccess") @SuppressWarnings("WeakerAccess")
public class LogBuilder { public class LogBuilder {
private final CommonsApplication application; private final Context context;
private final MediaWikiApi mwApi; private final MediaWikiApi mwApi;
private final JSONObject data; private final JSONObject data;
private final long rev; private final long rev;
private final String schema; private final String schema;
LogBuilder(String schema, long revision, CommonsApplication application, MediaWikiApi mwApi) { LogBuilder(String schema, long revision, Context context, MediaWikiApi mwApi) {
this.data = new JSONObject(); this.data = new JSONObject();
this.schema = schema; this.schema = schema;
this.rev = revision; this.rev = revision;
this.application = application; this.context = context;
this.mwApi = mwApi; this.mwApi = mwApi;
} }
@ -61,7 +62,7 @@ public class LogBuilder {
// Use *only* for tracking the user preference change for EventLogging // Use *only* for tracking the user preference change for EventLogging
// Attempting to use anywhere else will cause kitten explosions // Attempting to use anywhere else will cause kitten explosions
public void log(boolean force) { public void log(boolean force) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(application); SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
if (!settings.getBoolean(Prefs.TRACKING_ENABLED, true) && !force) { if (!settings.getBoolean(Prefs.TRACKING_ENABLED, true) && !force) {
return; // User has disabled tracking return; // User has disabled tracking
} }

View file

@ -2,25 +2,19 @@ package fr.free.nrw.commons.settings;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.os.Bundle; import android.os.Bundle;
import android.preference.CheckBoxPreference; import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference; import android.preference.EditTextPreference;
import android.preference.ListPreference; import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment; import android.preference.PreferenceFragment;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import javax.inject.Inject;
import dagger.android.AndroidInjection; import dagger.android.AndroidInjection;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.R; import fr.free.nrw.commons.R;
import fr.free.nrw.commons.Utils; import fr.free.nrw.commons.Utils;
public class SettingsFragment extends PreferenceFragment { public class SettingsFragment extends PreferenceFragment {
@Inject CommonsApplication application;
@Override @Override
public void onAttach(Context context) { public void onAttach(Context context) {
@ -53,7 +47,7 @@ public class SettingsFragment extends PreferenceFragment {
final EditTextPreference uploadLimit = (EditTextPreference) findPreference("uploads"); final EditTextPreference uploadLimit = (EditTextPreference) findPreference("uploads");
final SharedPreferences sharedPref = PreferenceManager final SharedPreferences sharedPref = PreferenceManager
.getDefaultSharedPreferences(application); .getDefaultSharedPreferences(getActivity().getApplicationContext());
int uploads = sharedPref.getInt(Prefs.UPLOADS_SHOWING, 100); int uploads = sharedPref.getInt(Prefs.UPLOADS_SHOWING, 100);
uploadLimit.setText(uploads + ""); uploadLimit.setText(uploads + "");
uploadLimit.setSummary(uploads + ""); uploadLimit.setSummary(uploads + "");

View file

@ -120,18 +120,17 @@ public class NavigationBaseActivity extends BaseActivity
new AlertDialog.Builder(this) new AlertDialog.Builder(this)
.setMessage(R.string.logout_verification) .setMessage(R.string.logout_verification)
.setCancelable(false) .setCancelable(false)
.setPositiveButton(R.string.yes, (dialog, which) -> { .setPositiveButton(R.string.yes, (dialog, which) ->
((CommonsApplication) getApplicationContext()) ((CommonsApplication) getApplicationContext())
.clearApplicationData(NavigationBaseActivity.this, () -> { .clearApplicationData(NavigationBaseActivity.this, () -> {
Timber.d("Logout complete callback received."); Timber.d("Logout complete callback received.");
Intent nearbyIntent = new Intent( Intent nearbyIntent = new Intent(
NavigationBaseActivity.this, LoginActivity.class); NavigationBaseActivity.this, LoginActivity.class);
nearbyIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); nearbyIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
nearbyIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); nearbyIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(nearbyIntent); startActivity(nearbyIntent);
finish(); finish();
}); }))
})
.setNegativeButton(R.string.no, (dialog, which) -> dialog.cancel()) .setNegativeButton(R.string.no, (dialog, which) -> dialog.cancel())
.show(); .show();
return true; return true;

View file

@ -16,7 +16,6 @@ import android.support.annotation.RequiresApi;
import java.io.FileDescriptor; import java.io.FileDescriptor;
import java.io.IOException; import java.io.IOException;
import fr.free.nrw.commons.CommonsApplication;
import timber.log.Timber; import timber.log.Timber;
/** /**
@ -26,7 +25,7 @@ import timber.log.Timber;
*/ */
public class GPSExtractor { public class GPSExtractor {
private final CommonsApplication application; private final Context context;
private ExifInterface exif; private ExifInterface exif;
private double decLatitude; private double decLatitude;
private double decLongitude; private double decLongitude;
@ -39,30 +38,30 @@ public class GPSExtractor {
/** /**
* Construct from the file descriptor of the image (only for API 24 or newer). * Construct from the file descriptor of the image (only for API 24 or newer).
* @param fileDescriptor the file descriptor of the image * @param fileDescriptor the file descriptor of the image
* @param application the application * @param context the context
*/ */
@RequiresApi(24) @RequiresApi(24)
public GPSExtractor(@NonNull FileDescriptor fileDescriptor, CommonsApplication application) { public GPSExtractor(@NonNull FileDescriptor fileDescriptor, Context context) {
this.context = context;
try { try {
exif = new ExifInterface(fileDescriptor); exif = new ExifInterface(fileDescriptor);
} catch (IOException | IllegalArgumentException e) { } catch (IOException | IllegalArgumentException e) {
Timber.w(e); Timber.w(e);
} }
this.application = application;
} }
/** /**
* Construct from the file path of the image. * Construct from the file path of the image.
* @param path file path of the image * @param path file path of the image
* @param application the application * @param context the context
*/ */
public GPSExtractor(@NonNull String path, CommonsApplication application) { public GPSExtractor(@NonNull String path, Context context) {
try { try {
exif = new ExifInterface(path); exif = new ExifInterface(path);
} catch (IOException | IllegalArgumentException e) { } catch (IOException | IllegalArgumentException e) {
Timber.w(e); Timber.w(e);
} }
this.application = application; this.context = context;
} }
/** /**
@ -71,7 +70,7 @@ public class GPSExtractor {
*/ */
private boolean gpsPreferenceEnabled() { private boolean gpsPreferenceEnabled() {
SharedPreferences sharedPref SharedPreferences sharedPref
= PreferenceManager.getDefaultSharedPreferences(application); = PreferenceManager.getDefaultSharedPreferences(context);
boolean gpsPref = sharedPref.getBoolean("allowGps", false); boolean gpsPref = sharedPref.getBoolean("allowGps", false);
Timber.d("Gps pref set to: %b", gpsPref); Timber.d("Gps pref set to: %b", gpsPref);
return gpsPref; return gpsPref;
@ -81,8 +80,7 @@ public class GPSExtractor {
* Registers a LocationManager to listen for current location * Registers a LocationManager to listen for current location
*/ */
protected void registerLocationManager() { protected void registerLocationManager() {
locationManager = (LocationManager) application locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria(); Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true); String provider = locationManager.getBestProvider(criteria, true);
myLocationListener = new MyLocationListener(); myLocationListener = new MyLocationListener();

View file

@ -31,6 +31,7 @@ import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.Media; import fr.free.nrw.commons.Media;
import fr.free.nrw.commons.R; import fr.free.nrw.commons.R;
import fr.free.nrw.commons.auth.AuthenticatedActivity; import fr.free.nrw.commons.auth.AuthenticatedActivity;
import fr.free.nrw.commons.auth.SessionManager;
import fr.free.nrw.commons.category.CategorizationFragment; import fr.free.nrw.commons.category.CategorizationFragment;
import fr.free.nrw.commons.category.OnCategoriesSaveHandler; import fr.free.nrw.commons.category.OnCategoriesSaveHandler;
import fr.free.nrw.commons.contributions.Contribution; import fr.free.nrw.commons.contributions.Contribution;
@ -43,15 +44,15 @@ import fr.free.nrw.commons.mwapi.EventLog;
import fr.free.nrw.commons.mwapi.MediaWikiApi; import fr.free.nrw.commons.mwapi.MediaWikiApi;
import timber.log.Timber; import timber.log.Timber;
public class MultipleShareActivity public class MultipleShareActivity extends AuthenticatedActivity
extends AuthenticatedActivity implements MediaDetailPagerFragment.MediaDetailProvider,
implements MediaDetailPagerFragment.MediaDetailProvider, AdapterView.OnItemClickListener,
AdapterView.OnItemClickListener, FragmentManager.OnBackStackChangedListener,
FragmentManager.OnBackStackChangedListener, MultipleUploadListFragment.OnMultipleUploadInitiatedHandler,
MultipleUploadListFragment.OnMultipleUploadInitiatedHandler,
OnCategoriesSaveHandler { OnCategoriesSaveHandler {
@Inject CommonsApplication application;
@Inject MediaWikiApi mwApi; @Inject MediaWikiApi mwApi;
@Inject SessionManager sessionManager;
private ArrayList<Contribution> photosList = null; private ArrayList<Contribution> photosList = null;
@ -68,7 +69,7 @@ public class MultipleShareActivity
@Override @Override
public int getTotalMediaCount() { public int getTotalMediaCount() {
if(photosList == null) { if (photosList == null) {
return 0; return 0;
} }
return photosList.size(); return photosList.size();
@ -76,7 +77,7 @@ public class MultipleShareActivity
@Override @Override
public void notifyDatasetChanged() { public void notifyDatasetChanged() {
if(uploadsList != null) { if (uploadsList != null) {
uploadsList.notifyDatasetChanged(); uploadsList.notifyDatasetChanged();
} }
} }
@ -129,7 +130,7 @@ public class MultipleShareActivity
dialog.setTitle(getResources().getQuantityString(R.plurals.starting_multiple_uploads, photosList.size(), photosList.size())); dialog.setTitle(getResources().getQuantityString(R.plurals.starting_multiple_uploads, photosList.size(), photosList.size()));
dialog.show(); dialog.show();
for(int i = 0; i < photosList.size(); i++) { for (int i = 0; i < photosList.size(); i++) {
Contribution up = photosList.get(i); Contribution up = photosList.get(i);
final int uploadCount = i + 1; // Goddamn Java final int uploadCount = i + 1; // Goddamn Java
@ -137,11 +138,7 @@ public class MultipleShareActivity
dialog.setProgress(uploadCount); dialog.setProgress(uploadCount);
if (uploadCount == photosList.size()) { if (uploadCount == photosList.size()) {
dialog.dismiss(); dialog.dismiss();
Toast startingToast = Toast.makeText( Toast startingToast = Toast.makeText(this, R.string.uploading_started, Toast.LENGTH_LONG);
application,
R.string.uploading_started,
Toast.LENGTH_LONG
);
startingToast.show(); startingToast.show();
} }
}); });
@ -150,7 +147,7 @@ public class MultipleShareActivity
uploadsList.setImageOnlyMode(true); uploadsList.setImageOnlyMode(true);
categorizationFragment = (CategorizationFragment) getSupportFragmentManager().findFragmentByTag("categorization"); categorizationFragment = (CategorizationFragment) getSupportFragmentManager().findFragmentByTag("categorization");
if(categorizationFragment == null) { if (categorizationFragment == null) {
categorizationFragment = new CategorizationFragment(); categorizationFragment = new CategorizationFragment();
} }
// FIXME: Stops the keyboard from being shown 'stale' while moving out of this fragment into the next // FIXME: Stops the keyboard from being shown 'stale' while moving out of this fragment into the next
@ -167,9 +164,9 @@ public class MultipleShareActivity
@Override @Override
public void onCategoriesSave(List<String> categories) { public void onCategoriesSave(List<String> categories) {
if(categories.size() > 0) { if (categories.size() > 0) {
ContentProviderClient client = getContentResolver().acquireContentProviderClient(ModificationsContentProvider.AUTHORITY); ContentProviderClient client = getContentResolver().acquireContentProviderClient(ModificationsContentProvider.AUTHORITY);
for(Contribution contribution: photosList) { for (Contribution contribution : photosList) {
ModifierSequence categoriesSequence = new ModifierSequence(contribution.getContentUri()); ModifierSequence categoriesSequence = new ModifierSequence(contribution.getContentUri());
categoriesSequence.queueModifier(new CategoryModifier(categories.toArray(new String[]{}))); categoriesSequence.queueModifier(new CategoryModifier(categories.toArray(new String[]{})));
@ -181,9 +178,9 @@ public class MultipleShareActivity
} }
// FIXME: Make sure that the content provider is up // FIXME: Make sure that the content provider is up
// This is the wrong place for it, but bleh - better than not having it turned on by default for people who don't go throughl ogin // This is the wrong place for it, but bleh - better than not having it turned on by default for people who don't go throughl ogin
ContentResolver.setSyncAutomatically(application.getCurrentAccount(), ModificationsContentProvider.AUTHORITY, true); // Enable sync by default! ContentResolver.setSyncAutomatically(sessionManager.getCurrentAccount(), ModificationsContentProvider.AUTHORITY, true); // Enable sync by default!
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, application, mwApi) EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, getApplicationContext(), mwApi)
.param("username", application.getCurrentAccount().name) .param("username", sessionManager.getCurrentAccount().name)
.param("categories-count", categories.size()) .param("categories-count", categories.size())
.param("files-count", photosList.size()) .param("files-count", photosList.size())
.param("source", Contribution.SOURCE_EXTERNAL) .param("source", Contribution.SOURCE_EXTERNAL)
@ -194,9 +191,9 @@ public class MultipleShareActivity
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) { switch (item.getItemId()) {
case android.R.id.home: case android.R.id.home:
if(mediaDetails.isVisible()) { if (mediaDetails.isVisible()) {
getSupportFragmentManager().popBackStack(); getSupportFragmentManager().popBackStack();
} }
return true; return true;
@ -207,13 +204,13 @@ public class MultipleShareActivity
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
uploadController = new UploadController(application); uploadController = new UploadController(sessionManager, this);
setContentView(R.layout.activity_multiple_uploads); setContentView(R.layout.activity_multiple_uploads);
ButterKnife.bind(this); ButterKnife.bind(this);
initDrawer(); initDrawer();
if(savedInstanceState != null) { if (savedInstanceState != null) {
photosList = savedInstanceState.getParcelableArrayList("uploadsList"); photosList = savedInstanceState.getParcelableArrayList("uploadsList");
} }
@ -229,7 +226,7 @@ public class MultipleShareActivity
} }
private void showDetail(int i) { private void showDetail(int i) {
if(mediaDetails == null ||!mediaDetails.isVisible()) { if (mediaDetails == null || !mediaDetails.isVisible()) {
mediaDetails = new MediaDetailPagerFragment(true); mediaDetails = new MediaDetailPagerFragment(true);
getSupportFragmentManager() getSupportFragmentManager()
.beginTransaction() .beginTransaction()
@ -252,11 +249,11 @@ public class MultipleShareActivity
mwApi.setAuthCookie(authCookie); mwApi.setAuthCookie(authCookie);
Intent intent = getIntent(); Intent intent = getIntent();
if(intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE)) { if (intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
if(photosList == null) { if (photosList == null) {
photosList = new ArrayList<>(); photosList = new ArrayList<>();
ArrayList<Uri> urisList = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); ArrayList<Uri> urisList = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
for(int i=0; i < urisList.size(); i++) { for (int i = 0; i < urisList.size(); i++) {
Contribution up = new Contribution(); Contribution up = new Contribution();
Uri uri = urisList.get(i); Uri uri = urisList.get(i);
up.setLocalUri(uri); up.setLocalUri(uri);
@ -269,8 +266,8 @@ public class MultipleShareActivity
} }
uploadsList = (MultipleUploadListFragment) getSupportFragmentManager().findFragmentByTag("uploadsList"); uploadsList = (MultipleUploadListFragment) getSupportFragmentManager().findFragmentByTag("uploadsList");
if(uploadsList == null) { if (uploadsList == null) {
uploadsList = new MultipleUploadListFragment(); uploadsList = new MultipleUploadListFragment();
getSupportFragmentManager() getSupportFragmentManager()
.beginTransaction() .beginTransaction()
.add(R.id.uploadsFragmentContainer, uploadsList, "uploadsList") .add(R.id.uploadsFragmentContainer, uploadsList, "uploadsList")
@ -291,17 +288,17 @@ public class MultipleShareActivity
@Override @Override
public void onBackPressed() { public void onBackPressed() {
super.onBackPressed(); super.onBackPressed();
if(categorizationFragment != null && categorizationFragment.isVisible()) { if (categorizationFragment != null && categorizationFragment.isVisible()) {
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, application, mwApi) EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, getApplicationContext(), mwApi)
.param("username", application.getCurrentAccount().name) .param("username", sessionManager.getCurrentAccount().name)
.param("categories-count", categorizationFragment.getCurrentSelectedCount()) .param("categories-count", categorizationFragment.getCurrentSelectedCount())
.param("files-count", photosList.size()) .param("files-count", photosList.size())
.param("source", Contribution.SOURCE_EXTERNAL) .param("source", Contribution.SOURCE_EXTERNAL)
.param("result", "cancelled") .param("result", "cancelled")
.log(); .log();
} else { } else {
EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, application, mwApi) EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, getApplicationContext(), mwApi)
.param("username", application.getCurrentAccount().name) .param("username", sessionManager.getCurrentAccount().name)
.param("source", getIntent().getStringExtra(UploadService.EXTRA_SOURCE)) .param("source", getIntent().getStringExtra(UploadService.EXTRA_SOURCE))
.param("multiple", true) .param("multiple", true)
.param("result", "cancelled") .param("result", "cancelled")

View file

@ -1,5 +1,6 @@
package fr.free.nrw.commons.upload; package fr.free.nrw.commons.upload;
import android.content.Context;
import android.net.Uri; import android.net.Uri;
import com.android.volley.Cache; import com.android.volley.Cache;
@ -20,7 +21,6 @@ import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import fr.free.nrw.commons.CommonsApplication;
import timber.log.Timber; import timber.log.Timber;
/** /**
@ -37,11 +37,11 @@ public class MwVolleyApi {
private static List<String> categoryList; private static List<String> categoryList;
private static final String MWURL = "https://commons.wikimedia.org/"; private static final String MWURL = "https://commons.wikimedia.org/";
private final CommonsApplication application; private final Context context;
public MwVolleyApi(CommonsApplication application) { public MwVolleyApi(Context context) {
this.context = context;
categorySet = new HashSet<>(); categorySet = new HashSet<>();
this.application = application;
} }
public static List<String> getGpsCat() { public static List<String> getGpsCat() {
@ -95,7 +95,7 @@ public class MwVolleyApi {
private synchronized RequestQueue getQueue() { private synchronized RequestQueue getQueue() {
if (REQUEST_QUEUE == null) { if (REQUEST_QUEUE == null) {
REQUEST_QUEUE = Volley.newRequestQueue(application); REQUEST_QUEUE = Volley.newRequestQueue(context);
} }
return REQUEST_QUEUE; return REQUEST_QUEUE;
} }

View file

@ -39,6 +39,7 @@ import butterknife.ButterKnife;
import fr.free.nrw.commons.CommonsApplication; import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.R; import fr.free.nrw.commons.R;
import fr.free.nrw.commons.auth.AuthenticatedActivity; import fr.free.nrw.commons.auth.AuthenticatedActivity;
import fr.free.nrw.commons.auth.SessionManager;
import fr.free.nrw.commons.caching.CacheController; import fr.free.nrw.commons.caching.CacheController;
import fr.free.nrw.commons.category.CategorizationFragment; import fr.free.nrw.commons.category.CategorizationFragment;
import fr.free.nrw.commons.category.OnCategoriesSaveHandler; import fr.free.nrw.commons.category.OnCategoriesSaveHandler;
@ -69,9 +70,9 @@ public class ShareActivity
private static final int REQUEST_PERM_ON_SUBMIT_STORAGE = 4; private static final int REQUEST_PERM_ON_SUBMIT_STORAGE = 4;
private CategorizationFragment categorizationFragment; private CategorizationFragment categorizationFragment;
@Inject CommonsApplication application;
@Inject MediaWikiApi mwApi; @Inject MediaWikiApi mwApi;
@Inject CacheController cacheController; @Inject CacheController cacheController;
@Inject SessionManager sessionManager;
private String source; private String source;
private String mimeType; private String mimeType;
@ -132,11 +133,7 @@ public class ShareActivity
private void uploadBegins() { private void uploadBegins() {
getFileMetadata(locationPermitted); getFileMetadata(locationPermitted);
Toast startingToast = Toast.makeText( Toast startingToast = Toast.makeText(this, R.string.uploading_started, Toast.LENGTH_LONG);
application,
R.string.uploading_started,
Toast.LENGTH_LONG
);
startingToast.show(); startingToast.show();
if (!cacheFound) { if (!cacheFound) {
@ -173,10 +170,10 @@ public class ShareActivity
// FIXME: Make sure that the content provider is up // FIXME: Make sure that the content provider is up
// This is the wrong place for it, but bleh - better than not having it turned on by default for people who don't go throughl ogin // This is the wrong place for it, but bleh - better than not having it turned on by default for people who don't go throughl ogin
ContentResolver.setSyncAutomatically(application.getCurrentAccount(), ModificationsContentProvider.AUTHORITY, true); // Enable sync by default! ContentResolver.setSyncAutomatically(sessionManager.getCurrentAccount(), ModificationsContentProvider.AUTHORITY, true); // Enable sync by default!
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, application, mwApi) EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, getApplicationContext(), mwApi)
.param("username", application.getCurrentAccount().name) .param("username", sessionManager.getCurrentAccount().name)
.param("categories-count", categories.size()) .param("categories-count", categories.size())
.param("files-count", 1) .param("files-count", 1)
.param("source", contribution.getSource()) .param("source", contribution.getSource())
@ -197,16 +194,16 @@ public class ShareActivity
public void onBackPressed() { public void onBackPressed() {
super.onBackPressed(); super.onBackPressed();
if(categorizationFragment != null && categorizationFragment.isVisible()) { if(categorizationFragment != null && categorizationFragment.isVisible()) {
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, application, mwApi) EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, getApplicationContext(), mwApi)
.param("username", application.getCurrentAccount().name) .param("username", sessionManager.getCurrentAccount().name)
.param("categories-count", categorizationFragment.getCurrentSelectedCount()) .param("categories-count", categorizationFragment.getCurrentSelectedCount())
.param("files-count", 1) .param("files-count", 1)
.param("source", contribution.getSource()) .param("source", contribution.getSource())
.param("result", "cancelled") .param("result", "cancelled")
.log(); .log();
} else { } else {
EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, application, mwApi) EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, getApplicationContext(), mwApi)
.param("username", application.getCurrentAccount().name) .param("username", sessionManager.getCurrentAccount().name)
.param("source", getIntent().getStringExtra(UploadService.EXTRA_SOURCE)) .param("source", getIntent().getStringExtra(UploadService.EXTRA_SOURCE))
.param("multiple", true) .param("multiple", true)
.param("result", "cancelled") .param("result", "cancelled")
@ -229,7 +226,7 @@ public class ShareActivity
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
uploadController = new UploadController(application); uploadController = new UploadController(sessionManager, this);
setContentView(R.layout.activity_share); setContentView(R.layout.activity_share);
ButterKnife.bind(this); ButterKnife.bind(this);
initBack(); initBack();
@ -454,12 +451,12 @@ public class ShareActivity
= getContentResolver().openFileDescriptor(mediaUri, "r"); = getContentResolver().openFileDescriptor(mediaUri, "r");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
if (descriptor != null) { if (descriptor != null) {
imageObj = new GPSExtractor(descriptor.getFileDescriptor(), application); imageObj = new GPSExtractor(descriptor.getFileDescriptor(), this);
} }
} else { } else {
String filePath = getPathOfMediaOrCopy(); String filePath = getPathOfMediaOrCopy();
if (filePath != null) { if (filePath != null) {
imageObj = new GPSExtractor(filePath, application); imageObj = new GPSExtractor(filePath, this);
} }
} }
} }
@ -489,7 +486,7 @@ public class ShareActivity
cacheController.setQtPoint(decLongitude, decLatitude); cacheController.setQtPoint(decLongitude, decLatitude);
} }
MwVolleyApi apiCall = new MwVolleyApi(application); MwVolleyApi apiCall = new MwVolleyApi(this);
List<String> displayCatList = cacheController.findCategory(); List<String> displayCatList = cacheController.findCategory();
boolean catListEmpty = displayCatList.isEmpty(); boolean catListEmpty = displayCatList.isEmpty();

View file

@ -1,6 +1,7 @@
package fr.free.nrw.commons.upload; package fr.free.nrw.commons.upload;
import android.content.ComponentName; import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.ServiceConnection; import android.content.ServiceConnection;
@ -21,20 +22,23 @@ import java.util.concurrent.Executors;
import fr.free.nrw.commons.CommonsApplication; import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.HandlerService; import fr.free.nrw.commons.HandlerService;
import fr.free.nrw.commons.auth.SessionManager;
import fr.free.nrw.commons.contributions.Contribution; import fr.free.nrw.commons.contributions.Contribution;
import fr.free.nrw.commons.settings.Prefs; import fr.free.nrw.commons.settings.Prefs;
import timber.log.Timber; import timber.log.Timber;
public class UploadController { public class UploadController {
private UploadService uploadService; private UploadService uploadService;
private final CommonsApplication application; private SessionManager sessionManager;
private Context context;
public interface ContributionUploadProgress { public interface ContributionUploadProgress {
void onUploadStarted(Contribution contribution); void onUploadStarted(Contribution contribution);
} }
public UploadController(CommonsApplication application) { public UploadController(SessionManager sessionManager, Context context) {
this.application = application; this.sessionManager = sessionManager;
this.context = context;
} }
private boolean isUploadServiceConnected; private boolean isUploadServiceConnected;
@ -53,15 +57,15 @@ public class UploadController {
}; };
public void prepareService() { public void prepareService() {
Intent uploadServiceIntent = new Intent(application, UploadService.class); Intent uploadServiceIntent = new Intent(context, UploadService.class);
uploadServiceIntent.setAction(UploadService.ACTION_START_SERVICE); uploadServiceIntent.setAction(UploadService.ACTION_START_SERVICE);
application.startService(uploadServiceIntent); context.startService(uploadServiceIntent);
application.bindService(uploadServiceIntent, uploadServiceConnection, Context.BIND_AUTO_CREATE); context.bindService(uploadServiceIntent, uploadServiceConnection, Context.BIND_AUTO_CREATE);
} }
public void cleanup() { public void cleanup() {
if(isUploadServiceConnected) { if(isUploadServiceConnected) {
application.unbindService(uploadServiceConnection); context.unbindService(uploadServiceConnection);
} }
} }
@ -69,7 +73,9 @@ public class UploadController {
Contribution contribution; Contribution contribution;
//TODO: Modify this to include coords //TODO: Modify this to include coords
contribution = new Contribution(mediaUri, null, title, description, -1, null, null, application.getCurrentAccount().name, CommonsApplication.DEFAULT_EDIT_SUMMARY, decimalCoords); contribution = new Contribution(mediaUri, null, title, description, -1,
null, null, sessionManager.getCurrentAccount().name,
CommonsApplication.DEFAULT_EDIT_SUMMARY, decimalCoords);
contribution.setTag("mimeType", mimeType); contribution.setTag("mimeType", mimeType);
contribution.setSource(source); contribution.setSource(source);
@ -79,12 +85,11 @@ public class UploadController {
} }
public void startUpload(final Contribution contribution, final ContributionUploadProgress onComplete) { public void startUpload(final Contribution contribution, final ContributionUploadProgress onComplete) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(application);
//Set creator, desc, and license //Set creator, desc, and license
if(TextUtils.isEmpty(contribution.getCreator())) { if(TextUtils.isEmpty(contribution.getCreator())) {
contribution.setCreator(application.getCurrentAccount().name); contribution.setCreator(sessionManager.getCurrentAccount().name);
} }
if(contribution.getDescription() == null) { if(contribution.getDescription() == null) {
@ -103,14 +108,15 @@ public class UploadController {
@Override @Override
protected Contribution doInBackground(Void... voids /* stare into you */) { protected Contribution doInBackground(Void... voids /* stare into you */) {
long length; long length;
ContentResolver contentResolver = context.getContentResolver();
try { try {
if(contribution.getDataLength() <= 0) { if(contribution.getDataLength() <= 0) {
length = application.getContentResolver() length = contentResolver
.openAssetFileDescriptor(contribution.getLocalUri(), "r") .openAssetFileDescriptor(contribution.getLocalUri(), "r")
.getLength(); .getLength();
if(length == -1) { if(length == -1) {
// Let us find out the long way! // Let us find out the long way!
length = countBytes(application.getContentResolver() length = countBytes(contentResolver
.openInputStream(contribution.getLocalUri())); .openInputStream(contribution.getLocalUri()));
} }
contribution.setDataLength(length); contribution.setDataLength(length);
@ -127,7 +133,7 @@ public class UploadController {
Boolean imagePrefix = false; Boolean imagePrefix = false;
if (mimeType == null || TextUtils.isEmpty(mimeType) || mimeType.endsWith("*")) { if (mimeType == null || TextUtils.isEmpty(mimeType) || mimeType.endsWith("*")) {
mimeType = application.getContentResolver().getType(contribution.getLocalUri()); mimeType = contentResolver.getType(contribution.getLocalUri());
} }
if (mimeType != null) { if (mimeType != null) {
@ -138,7 +144,7 @@ public class UploadController {
if (imagePrefix && contribution.getDateCreated() == null) { if (imagePrefix && contribution.getDateCreated() == null) {
Timber.d("local uri " + contribution.getLocalUri()); Timber.d("local uri " + contribution.getLocalUri());
Cursor cursor = application.getContentResolver().query(contribution.getLocalUri(), Cursor cursor = contentResolver.query(contribution.getLocalUri(),
new String[]{MediaStore.Images.ImageColumns.DATE_TAKEN}, null, null, null); new String[]{MediaStore.Images.ImageColumns.DATE_TAKEN}, null, null, null);
if (cursor != null && cursor.getCount() != 0 && cursor.getColumnCount() != 0) { if (cursor != null && cursor.getCount() != 0 && cursor.getColumnCount() != 0) {
cursor.moveToFirst(); cursor.moveToFirst();

View file

@ -28,6 +28,7 @@ import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.HandlerService; import fr.free.nrw.commons.HandlerService;
import fr.free.nrw.commons.R; import fr.free.nrw.commons.R;
import fr.free.nrw.commons.Utils; import fr.free.nrw.commons.Utils;
import fr.free.nrw.commons.auth.SessionManager;
import fr.free.nrw.commons.contributions.Contribution; import fr.free.nrw.commons.contributions.Contribution;
import fr.free.nrw.commons.contributions.ContributionsActivity; import fr.free.nrw.commons.contributions.ContributionsActivity;
import fr.free.nrw.commons.contributions.ContributionsContentProvider; import fr.free.nrw.commons.contributions.ContributionsContentProvider;
@ -47,8 +48,8 @@ public class UploadService extends HandlerService<Contribution> {
public static final String EXTRA_SOURCE = EXTRA_PREFIX + ".source"; public static final String EXTRA_SOURCE = EXTRA_PREFIX + ".source";
public static final String EXTRA_CAMPAIGN = EXTRA_PREFIX + ".campaign"; public static final String EXTRA_CAMPAIGN = EXTRA_PREFIX + ".campaign";
@Inject CommonsApplication application;
@Inject MediaWikiApi mwApi; @Inject MediaWikiApi mwApi;
@Inject SessionManager sessionManager;
private NotificationManager notificationManager; private NotificationManager notificationManager;
private ContentProviderClient contributionsProviderClient; private ContentProviderClient contributionsProviderClient;
@ -221,7 +222,7 @@ public class UploadService extends HandlerService<Contribution> {
} }
if (!mwApi.validateLogin()) { if (!mwApi.validateLogin()) {
// Need to revalidate! // Need to revalidate!
if (application.revalidateAuthToken()) { if (sessionManager.revalidateAuthToken()) {
Timber.d("Successfully revalidated token!"); Timber.d("Successfully revalidated token!");
} else { } else {
Timber.d("Unable to revalidate :("); Timber.d("Unable to revalidate :(");
@ -246,8 +247,8 @@ public class UploadService extends HandlerService<Contribution> {
String resultStatus = uploadResult.getResultStatus(); String resultStatus = uploadResult.getResultStatus();
if (!resultStatus.equals("Success")) { if (!resultStatus.equals("Success")) {
showFailedNotification(contribution); showFailedNotification(contribution);
EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, application, mwApi) EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, getApplicationContext(), mwApi)
.param("username", application.getCurrentAccount().name) .param("username", sessionManager.getCurrentAccount().name)
.param("source", contribution.getSource()) .param("source", contribution.getSource())
.param("multiple", contribution.getMultiple()) .param("multiple", contribution.getMultiple())
.param("result", uploadResult.getErrorCode()) .param("result", uploadResult.getErrorCode())
@ -260,8 +261,8 @@ public class UploadService extends HandlerService<Contribution> {
contribution.setDateUploaded(uploadResult.getDateUploaded()); contribution.setDateUploaded(uploadResult.getDateUploaded());
contribution.save(); contribution.save();
EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, application, mwApi) EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, getApplicationContext(), mwApi)
.param("username", application.getCurrentAccount().name) .param("username", sessionManager.getCurrentAccount().name)
.param("source", contribution.getSource()) //FIXME .param("source", contribution.getSource()) //FIXME
.param("filename", contribution.getFilename()) .param("filename", contribution.getFilename())
.param("multiple", contribution.getMultiple()) .param("multiple", contribution.getMultiple())
@ -278,7 +279,7 @@ public class UploadService extends HandlerService<Contribution> {
toUpload--; toUpload--;
if (toUpload == 0) { if (toUpload == 0) {
// Sync modifications right after all uplaods are processed // Sync modifications right after all uplaods are processed
ContentResolver.requestSync(application.getCurrentAccount(), ModificationsContentProvider.AUTHORITY, new Bundle()); ContentResolver.requestSync(sessionManager.getCurrentAccount(), ModificationsContentProvider.AUTHORITY, new Bundle());
stopForeground(true); stopForeground(true);
} }
} }