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;
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.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
@ -20,13 +14,12 @@ import org.acra.ReportingInteractionMode;
import org.acra.annotation.ReportsCrashes;
import java.io.File;
import java.io.IOException;
import javax.inject.Inject;
import dagger.android.AndroidInjector;
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.data.Category;
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.theme.NavigationBaseActivity;
import fr.free.nrw.commons.utils.FileUtils;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import timber.log.Timber;
// TODO: Use ProGuard to rip out reporting when publishing
@ -51,10 +46,9 @@ import timber.log.Timber;
public class CommonsApplication extends DaggerApplication {
@Inject MediaWikiApi mediaWikiApi;
@Inject AccountUtil accountUtil;
@Inject SessionManager sessionManager;
@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 IMAGE_URL_BASE = "https://upload.wikimedia.org/wikipedia/commons";
public static final String HOME_URL = "https://commons.wikimedia.org/wiki/";
@ -113,39 +107,6 @@ public class CommonsApplication extends DaggerApplication {
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) {
File cacheDirectory = context.getCacheDir();
File applicationDirectory = new File(cacheDirectory.getParent());
@ -158,36 +119,10 @@ public class CommonsApplication extends DaggerApplication {
}
}
AccountManager accountManager = AccountManager.get(this);
Account[] allAccounts = accountManager.getAccountsByType(accountUtil.accountType());
AccountManagerCallback<Boolean> amCallback = new AccountManagerCallback<Boolean>() {
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) {
sessionManager.clearAllAccounts()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(() -> {
Timber.d("All accounts have been removed");
//TODO: fix preference manager
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();
preferences.edit().putBoolean("firstrun", false).apply();
updateAllDatabases();
currentAccount = null;
logoutListener.onLogoutComplete();
}
}
};
for (Account account : allAccounts) {
accountManager.removeAccount(account, amCallback, null);
}
});
}
/**
* Deletes all tables and re-creates them.
*/
public void updateAllDatabases() {
private void updateAllDatabases() {
dbOpenHelper.getReadableDatabase().close();
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();

View file

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

View file

@ -4,24 +4,21 @@ import android.accounts.Account;
import android.accounts.AccountAuthenticatorResponse;
import android.accounts.AccountManager;
import android.content.ContentResolver;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
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.modifications.ModificationsContentProvider;
import timber.log.Timber;
public class AccountUtil {
private final CommonsApplication application;
private Context context;
@Inject
public AccountUtil(CommonsApplication application) {
this.application = application;
public AccountUtil(Context context) {
this.context = context;
}
public void createAccount(@Nullable AccountAuthenticatorResponse response,
@ -60,7 +57,7 @@ public class AccountUtil {
}
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 dagger.android.AndroidInjection;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.theme.NavigationBaseActivity;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
@ -17,8 +15,8 @@ import timber.log.Timber;
public abstract class AuthenticatedActivity extends NavigationBaseActivity {
@Inject CommonsApplication app;
@Inject AccountUtil accountUtil;
@Inject SessionManager sessionManager;
private String authCookie;
@ -59,7 +57,7 @@ public abstract class AuthenticatedActivity extends NavigationBaseActivity {
return;
}
AccountManager accountManager = AccountManager.get(this);
Account curAccount = app.getCurrentAccount();
Account curAccount = sessionManager.getCurrentAccount();
if(curAccount == null) {
addAccount(accountManager);
} else {

View file

@ -19,11 +19,9 @@ import javax.inject.Inject;
import dagger.android.AndroidInjection;
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.WelcomeActivity;
import fr.free.nrw.commons.PageTitle;
import fr.free.nrw.commons.contributions.ContributionsActivity;
import fr.free.nrw.commons.mwapi.MediaWikiApi;
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";
@Inject CommonsApplication application;
@Inject MediaWikiApi mwApi;
@Inject AccountUtil accountUtil;
@Inject SessionManager sessionManager;
private SharedPreferences prefs = null;
@ -114,7 +112,7 @@ public class LoginActivity extends AccountAuthenticatorActivity {
WelcomeActivity.startYourself(this);
prefs.edit().putBoolean("firstrun", false).apply();
}
if (application.getCurrentAccount() != null) {
if (sessionManager.getCurrentAccount() != null) {
startMainActivity();
}
}
@ -147,7 +145,7 @@ public class LoginActivity extends AccountAuthenticatorActivity {
canonicializeUsername(usernameEdit.getText().toString()),
passwordEdit.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.AccountManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
@ -21,16 +22,18 @@ class LoginTask extends AsyncTask<String, String, String> {
private String password;
private String twoFactorCode = "";
private AccountUtil accountUtil;
private CommonsApplication app;
private Context context;
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.username = username;
this.password = password;
this.twoFactorCode = twoFactorCode;
this.accountUtil = accountUtil;
this.app = application;
this.context = context;
this.mwApi = mwApi;
}
@ -64,7 +67,7 @@ class LoginTask extends AsyncTask<String, String, String> {
super.onPostExecute(result);
Timber.d("Login done!");
EventLog.schema(CommonsApplication.EVENT_LOGIN_ATTEMPT, app, mwApi)
EventLog.schema(CommonsApplication.EVENT_LOGIN_ATTEMPT, context, mwApi)
.param("username", username)
.param("result", result)
.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.widget.Toast;
import javax.inject.Inject;
import dagger.android.AndroidInjection;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.theme.BaseActivity;
import timber.log.Timber;
public class SignupActivity extends BaseActivity {
@Inject CommonsApplication application;
private WebView webView;
@Override
@ -41,11 +36,8 @@ public class SignupActivity extends BaseActivity {
//Signup success, so clear cookies, notify user, and load LoginActivity again
Timber.d("Overriding URL %s", url);
Toast toast = Toast.makeText(
application,
"Account created!",
Toast.LENGTH_LONG
);
Toast toast = Toast.makeText(SignupActivity.this,
"Account created!", Toast.LENGTH_LONG);
toast.show();
// terminate on task completion.
finish();

View file

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

View file

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

View file

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

View file

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

View file

@ -7,6 +7,8 @@ import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
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.data.DBOpenHelper;
import fr.free.nrw.commons.mwapi.ApacheHttpClientMediaWikiApi;
@ -22,8 +24,14 @@ public class CommonsApplicationModule {
}
@Provides
public CommonsApplication providesCommonsApplication() {
return application;
public AccountUtil providesAccountUtil() {
return new AccountUtil(application);
}
@Provides
@Singleton
public SessionManager providesSessionManager(AccountUtil accountUtil, MediaWikiApi mediaWikiApi) {
return new SessionManager(application, accountUtil, mediaWikiApi);
}
@Provides
@ -40,7 +48,7 @@ public class CommonsApplicationModule {
@Provides
@Singleton
public DBOpenHelper provideDBOpenHelper(CommonsApplication application) {
public DBOpenHelper provideDBOpenHelper() {
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.Media;
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.ContributionsActivity;
import fr.free.nrw.commons.mwapi.EventLog;
@ -52,8 +53,8 @@ public class MediaDetailPagerFragment extends DaggerFragment implements ViewPage
void unregisterDataSetObserver(DataSetObserver observer);
}
@Inject CommonsApplication application;
@Inject MediaWikiApi mwApi;
@Inject SessionManager sessionManager;
private ViewPager pager;
private Boolean editable;
@ -85,7 +86,7 @@ public class MediaDetailPagerFragment extends DaggerFragment implements ViewPage
@Override
public int getCount() {
return ((MediaDetailProvider)getActivity()).getTotalMediaCount();
return ((MediaDetailProvider) getActivity()).getTotalMediaCount();
}
}
@ -131,13 +132,13 @@ public class MediaDetailPagerFragment extends DaggerFragment implements ViewPage
@Override
public boolean onOptionsItemSelected(MenuItem item) {
MediaDetailProvider provider = (MediaDetailProvider)getActivity();
MediaDetailProvider provider = (MediaDetailProvider) getActivity();
Media m = provider.getMediaAtPosition(pager.getCurrentItem());
switch(item.getItemId()) {
switch (item.getItemId()) {
case R.id.menu_share_current_image:
// Share - this is just logs it, intent set in onCreateOptionsMenu, around line 252
EventLog.schema(CommonsApplication.EVENT_SHARE_ATTEMPT, application, mwApi)
.param("username", application.getCurrentAccount().name)
EventLog.schema(CommonsApplication.EVENT_SHARE_ATTEMPT, getContext().getApplicationContext(), mwApi)
.param("username", sessionManager.getCurrentAccount().name)
.param("filename", m.getFilename())
.log();
return true;
@ -154,12 +155,12 @@ public class MediaDetailPagerFragment extends DaggerFragment implements ViewPage
return true;
case R.id.menu_retry_current_image:
// Retry
((ContributionsActivity)getActivity()).retryUpload(pager.getCurrentItem());
((ContributionsActivity) getActivity()).retryUpload(pager.getCurrentItem());
getActivity().getSupportFragmentManager().popBackStack();
return true;
case R.id.menu_cancel_current_image:
// todo: delete image
((ContributionsActivity)getActivity()).deleteUpload(pager.getCurrentItem());
((ContributionsActivity) getActivity()).deleteUpload(pager.getCurrentItem());
getActivity().getSupportFragmentManager().popBackStack();
return true;
default:
@ -175,7 +176,7 @@ public class MediaDetailPagerFragment extends DaggerFragment implements ViewPage
*/
private void downloadMedia(Media m) {
String imageUrl = m.getImageUrl(),
fileName = m.getFilename();
fileName = m.getFilename();
// Strip 'File:' from beginning of filename, we really shouldn't store it
fileName = fileName.replaceFirst("^File:", "");
Uri imageUri = Uri.parse(imageUrl);
@ -190,13 +191,16 @@ public class MediaDetailPagerFragment extends DaggerFragment implements ViewPage
req.allowScanningByMediaScanner();
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.LENGTH_INDEFINITE)
.setAction(R.string.ok, view -> ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1)).show();
} else {
final DownloadManager manager = (DownloadManager)getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
final DownloadManager manager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(req);
}
}
@ -207,7 +211,7 @@ public class MediaDetailPagerFragment extends DaggerFragment implements ViewPage
menu.clear(); // see http://stackoverflow.com/a/8495697/17865
inflater.inflate(R.menu.fragment_image_detail, menu);
if (pager != null) {
MediaDetailProvider provider = (MediaDetailProvider)getActivity();
MediaDetailProvider provider = (MediaDetailProvider) getActivity();
Media m = provider.getMediaAtPosition(pager.getCurrentItem());
if (m != null) {
// 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) {
Contribution c = (Contribution)m;
switch(c.getState()) {
Contribution c = (Contribution) m;
switch (c.getState()) {
case Contribution.STATE_FAILED:
menu.findItem(R.id.menu_retry_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 dagger.android.AndroidInjection;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.data.DBOpenHelper;
import timber.log.Timber;
@ -37,7 +36,6 @@ public class ModificationsContentProvider extends ContentProvider{
return Uri.parse(BASE_URI.toString() + "/" + id);
}
@Inject CommonsApplication application;
@Inject DBOpenHelper dbOpenHelper;
@Override

View file

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

View file

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

View file

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

View file

@ -16,7 +16,6 @@ import android.support.annotation.RequiresApi;
import java.io.FileDescriptor;
import java.io.IOException;
import fr.free.nrw.commons.CommonsApplication;
import timber.log.Timber;
/**
@ -26,7 +25,7 @@ import timber.log.Timber;
*/
public class GPSExtractor {
private final CommonsApplication application;
private final Context context;
private ExifInterface exif;
private double decLatitude;
private double decLongitude;
@ -39,30 +38,30 @@ public class GPSExtractor {
/**
* Construct from the file descriptor of the image (only for API 24 or newer).
* @param fileDescriptor the file descriptor of the image
* @param application the application
* @param context the context
*/
@RequiresApi(24)
public GPSExtractor(@NonNull FileDescriptor fileDescriptor, CommonsApplication application) {
public GPSExtractor(@NonNull FileDescriptor fileDescriptor, Context context) {
this.context = context;
try {
exif = new ExifInterface(fileDescriptor);
} catch (IOException | IllegalArgumentException e) {
Timber.w(e);
}
this.application = application;
}
/**
* Construct from the 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 {
exif = new ExifInterface(path);
} catch (IOException | IllegalArgumentException e) {
Timber.w(e);
}
this.application = application;
this.context = context;
}
/**
@ -71,7 +70,7 @@ public class GPSExtractor {
*/
private boolean gpsPreferenceEnabled() {
SharedPreferences sharedPref
= PreferenceManager.getDefaultSharedPreferences(application);
= PreferenceManager.getDefaultSharedPreferences(context);
boolean gpsPref = sharedPref.getBoolean("allowGps", false);
Timber.d("Gps pref set to: %b", gpsPref);
return gpsPref;
@ -81,8 +80,7 @@ public class GPSExtractor {
* Registers a LocationManager to listen for current location
*/
protected void registerLocationManager() {
locationManager = (LocationManager) application
.getSystemService(Context.LOCATION_SERVICE);
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
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.R;
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.OnCategoriesSaveHandler;
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 timber.log.Timber;
public class MultipleShareActivity
extends AuthenticatedActivity
implements MediaDetailPagerFragment.MediaDetailProvider,
AdapterView.OnItemClickListener,
FragmentManager.OnBackStackChangedListener,
MultipleUploadListFragment.OnMultipleUploadInitiatedHandler,
public class MultipleShareActivity extends AuthenticatedActivity
implements MediaDetailPagerFragment.MediaDetailProvider,
AdapterView.OnItemClickListener,
FragmentManager.OnBackStackChangedListener,
MultipleUploadListFragment.OnMultipleUploadInitiatedHandler,
OnCategoriesSaveHandler {
@Inject CommonsApplication application;
@Inject MediaWikiApi mwApi;
@Inject SessionManager sessionManager;
private ArrayList<Contribution> photosList = null;
@ -68,7 +69,7 @@ public class MultipleShareActivity
@Override
public int getTotalMediaCount() {
if(photosList == null) {
if (photosList == null) {
return 0;
}
return photosList.size();
@ -76,7 +77,7 @@ public class MultipleShareActivity
@Override
public void notifyDatasetChanged() {
if(uploadsList != null) {
if (uploadsList != null) {
uploadsList.notifyDatasetChanged();
}
}
@ -129,7 +130,7 @@ public class MultipleShareActivity
dialog.setTitle(getResources().getQuantityString(R.plurals.starting_multiple_uploads, photosList.size(), photosList.size()));
dialog.show();
for(int i = 0; i < photosList.size(); i++) {
for (int i = 0; i < photosList.size(); i++) {
Contribution up = photosList.get(i);
final int uploadCount = i + 1; // Goddamn Java
@ -137,11 +138,7 @@ public class MultipleShareActivity
dialog.setProgress(uploadCount);
if (uploadCount == photosList.size()) {
dialog.dismiss();
Toast startingToast = Toast.makeText(
application,
R.string.uploading_started,
Toast.LENGTH_LONG
);
Toast startingToast = Toast.makeText(this, R.string.uploading_started, Toast.LENGTH_LONG);
startingToast.show();
}
});
@ -150,7 +147,7 @@ public class MultipleShareActivity
uploadsList.setImageOnlyMode(true);
categorizationFragment = (CategorizationFragment) getSupportFragmentManager().findFragmentByTag("categorization");
if(categorizationFragment == null) {
if (categorizationFragment == null) {
categorizationFragment = new CategorizationFragment();
}
// 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
public void onCategoriesSave(List<String> categories) {
if(categories.size() > 0) {
ContentProviderClient client = getContentResolver().acquireContentProviderClient(ModificationsContentProvider.AUTHORITY);
for(Contribution contribution: photosList) {
if (categories.size() > 0) {
ContentProviderClient client = getContentResolver().acquireContentProviderClient(ModificationsContentProvider.AUTHORITY);
for (Contribution contribution : photosList) {
ModifierSequence categoriesSequence = new ModifierSequence(contribution.getContentUri());
categoriesSequence.queueModifier(new CategoryModifier(categories.toArray(new String[]{})));
@ -181,9 +178,9 @@ public class MultipleShareActivity
}
// 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
ContentResolver.setSyncAutomatically(application.getCurrentAccount(), ModificationsContentProvider.AUTHORITY, true); // Enable sync by default!
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, application, mwApi)
.param("username", application.getCurrentAccount().name)
ContentResolver.setSyncAutomatically(sessionManager.getCurrentAccount(), ModificationsContentProvider.AUTHORITY, true); // Enable sync by default!
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, getApplicationContext(), mwApi)
.param("username", sessionManager.getCurrentAccount().name)
.param("categories-count", categories.size())
.param("files-count", photosList.size())
.param("source", Contribution.SOURCE_EXTERNAL)
@ -194,9 +191,9 @@ public class MultipleShareActivity
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
switch (item.getItemId()) {
case android.R.id.home:
if(mediaDetails.isVisible()) {
if (mediaDetails.isVisible()) {
getSupportFragmentManager().popBackStack();
}
return true;
@ -207,13 +204,13 @@ public class MultipleShareActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uploadController = new UploadController(application);
uploadController = new UploadController(sessionManager, this);
setContentView(R.layout.activity_multiple_uploads);
ButterKnife.bind(this);
initDrawer();
if(savedInstanceState != null) {
if (savedInstanceState != null) {
photosList = savedInstanceState.getParcelableArrayList("uploadsList");
}
@ -229,7 +226,7 @@ public class MultipleShareActivity
}
private void showDetail(int i) {
if(mediaDetails == null ||!mediaDetails.isVisible()) {
if (mediaDetails == null || !mediaDetails.isVisible()) {
mediaDetails = new MediaDetailPagerFragment(true);
getSupportFragmentManager()
.beginTransaction()
@ -252,11 +249,11 @@ public class MultipleShareActivity
mwApi.setAuthCookie(authCookie);
Intent intent = getIntent();
if(intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
if(photosList == null) {
if (intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
if (photosList == null) {
photosList = new ArrayList<>();
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();
Uri uri = urisList.get(i);
up.setLocalUri(uri);
@ -269,8 +266,8 @@ public class MultipleShareActivity
}
uploadsList = (MultipleUploadListFragment) getSupportFragmentManager().findFragmentByTag("uploadsList");
if(uploadsList == null) {
uploadsList = new MultipleUploadListFragment();
if (uploadsList == null) {
uploadsList = new MultipleUploadListFragment();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.uploadsFragmentContainer, uploadsList, "uploadsList")
@ -291,17 +288,17 @@ public class MultipleShareActivity
@Override
public void onBackPressed() {
super.onBackPressed();
if(categorizationFragment != null && categorizationFragment.isVisible()) {
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, application, mwApi)
.param("username", application.getCurrentAccount().name)
if (categorizationFragment != null && categorizationFragment.isVisible()) {
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, getApplicationContext(), mwApi)
.param("username", sessionManager.getCurrentAccount().name)
.param("categories-count", categorizationFragment.getCurrentSelectedCount())
.param("files-count", photosList.size())
.param("source", Contribution.SOURCE_EXTERNAL)
.param("result", "cancelled")
.log();
} else {
EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, application, mwApi)
.param("username", application.getCurrentAccount().name)
EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, getApplicationContext(), mwApi)
.param("username", sessionManager.getCurrentAccount().name)
.param("source", getIntent().getStringExtra(UploadService.EXTRA_SOURCE))
.param("multiple", true)
.param("result", "cancelled")

View file

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

View file

@ -39,6 +39,7 @@ import butterknife.ButterKnife;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.R;
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.category.CategorizationFragment;
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 CategorizationFragment categorizationFragment;
@Inject CommonsApplication application;
@Inject MediaWikiApi mwApi;
@Inject CacheController cacheController;
@Inject SessionManager sessionManager;
private String source;
private String mimeType;
@ -132,11 +133,7 @@ public class ShareActivity
private void uploadBegins() {
getFileMetadata(locationPermitted);
Toast startingToast = Toast.makeText(
application,
R.string.uploading_started,
Toast.LENGTH_LONG
);
Toast startingToast = Toast.makeText(this, R.string.uploading_started, Toast.LENGTH_LONG);
startingToast.show();
if (!cacheFound) {
@ -173,10 +170,10 @@ public class ShareActivity
// 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
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)
.param("username", application.getCurrentAccount().name)
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, getApplicationContext(), mwApi)
.param("username", sessionManager.getCurrentAccount().name)
.param("categories-count", categories.size())
.param("files-count", 1)
.param("source", contribution.getSource())
@ -197,16 +194,16 @@ public class ShareActivity
public void onBackPressed() {
super.onBackPressed();
if(categorizationFragment != null && categorizationFragment.isVisible()) {
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, application, mwApi)
.param("username", application.getCurrentAccount().name)
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, getApplicationContext(), mwApi)
.param("username", sessionManager.getCurrentAccount().name)
.param("categories-count", categorizationFragment.getCurrentSelectedCount())
.param("files-count", 1)
.param("source", contribution.getSource())
.param("result", "cancelled")
.log();
} else {
EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, application, mwApi)
.param("username", application.getCurrentAccount().name)
EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, getApplicationContext(), mwApi)
.param("username", sessionManager.getCurrentAccount().name)
.param("source", getIntent().getStringExtra(UploadService.EXTRA_SOURCE))
.param("multiple", true)
.param("result", "cancelled")
@ -229,7 +226,7 @@ public class ShareActivity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uploadController = new UploadController(application);
uploadController = new UploadController(sessionManager, this);
setContentView(R.layout.activity_share);
ButterKnife.bind(this);
initBack();
@ -454,12 +451,12 @@ public class ShareActivity
= getContentResolver().openFileDescriptor(mediaUri, "r");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
if (descriptor != null) {
imageObj = new GPSExtractor(descriptor.getFileDescriptor(), application);
imageObj = new GPSExtractor(descriptor.getFileDescriptor(), this);
}
} else {
String filePath = getPathOfMediaOrCopy();
if (filePath != null) {
imageObj = new GPSExtractor(filePath, application);
imageObj = new GPSExtractor(filePath, this);
}
}
}
@ -489,7 +486,7 @@ public class ShareActivity
cacheController.setQtPoint(decLongitude, decLatitude);
}
MwVolleyApi apiCall = new MwVolleyApi(application);
MwVolleyApi apiCall = new MwVolleyApi(this);
List<String> displayCatList = cacheController.findCategory();
boolean catListEmpty = displayCatList.isEmpty();

View file

@ -1,6 +1,7 @@
package fr.free.nrw.commons.upload;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
@ -21,20 +22,23 @@ import java.util.concurrent.Executors;
import fr.free.nrw.commons.CommonsApplication;
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.settings.Prefs;
import timber.log.Timber;
public class UploadController {
private UploadService uploadService;
private final CommonsApplication application;
private SessionManager sessionManager;
private Context context;
public interface ContributionUploadProgress {
void onUploadStarted(Contribution contribution);
}
public UploadController(CommonsApplication application) {
this.application = application;
public UploadController(SessionManager sessionManager, Context context) {
this.sessionManager = sessionManager;
this.context = context;
}
private boolean isUploadServiceConnected;
@ -53,15 +57,15 @@ public class UploadController {
};
public void prepareService() {
Intent uploadServiceIntent = new Intent(application, UploadService.class);
Intent uploadServiceIntent = new Intent(context, UploadService.class);
uploadServiceIntent.setAction(UploadService.ACTION_START_SERVICE);
application.startService(uploadServiceIntent);
application.bindService(uploadServiceIntent, uploadServiceConnection, Context.BIND_AUTO_CREATE);
context.startService(uploadServiceIntent);
context.bindService(uploadServiceIntent, uploadServiceConnection, Context.BIND_AUTO_CREATE);
}
public void cleanup() {
if(isUploadServiceConnected) {
application.unbindService(uploadServiceConnection);
context.unbindService(uploadServiceConnection);
}
}
@ -69,7 +73,9 @@ public class UploadController {
Contribution contribution;
//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.setSource(source);
@ -79,12 +85,11 @@ public class UploadController {
}
public void startUpload(final Contribution contribution, final ContributionUploadProgress onComplete) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(application);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
//Set creator, desc, and license
if(TextUtils.isEmpty(contribution.getCreator())) {
contribution.setCreator(application.getCurrentAccount().name);
contribution.setCreator(sessionManager.getCurrentAccount().name);
}
if(contribution.getDescription() == null) {
@ -103,14 +108,15 @@ public class UploadController {
@Override
protected Contribution doInBackground(Void... voids /* stare into you */) {
long length;
ContentResolver contentResolver = context.getContentResolver();
try {
if(contribution.getDataLength() <= 0) {
length = application.getContentResolver()
length = contentResolver
.openAssetFileDescriptor(contribution.getLocalUri(), "r")
.getLength();
if(length == -1) {
// Let us find out the long way!
length = countBytes(application.getContentResolver()
length = countBytes(contentResolver
.openInputStream(contribution.getLocalUri()));
}
contribution.setDataLength(length);
@ -127,7 +133,7 @@ public class UploadController {
Boolean imagePrefix = false;
if (mimeType == null || TextUtils.isEmpty(mimeType) || mimeType.endsWith("*")) {
mimeType = application.getContentResolver().getType(contribution.getLocalUri());
mimeType = contentResolver.getType(contribution.getLocalUri());
}
if (mimeType != null) {
@ -138,7 +144,7 @@ public class UploadController {
if (imagePrefix && contribution.getDateCreated() == null) {
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);
if (cursor != null && cursor.getCount() != 0 && cursor.getColumnCount() != 0) {
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.R;
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.ContributionsActivity;
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_CAMPAIGN = EXTRA_PREFIX + ".campaign";
@Inject CommonsApplication application;
@Inject MediaWikiApi mwApi;
@Inject SessionManager sessionManager;
private NotificationManager notificationManager;
private ContentProviderClient contributionsProviderClient;
@ -221,7 +222,7 @@ public class UploadService extends HandlerService<Contribution> {
}
if (!mwApi.validateLogin()) {
// Need to revalidate!
if (application.revalidateAuthToken()) {
if (sessionManager.revalidateAuthToken()) {
Timber.d("Successfully revalidated token!");
} else {
Timber.d("Unable to revalidate :(");
@ -246,8 +247,8 @@ public class UploadService extends HandlerService<Contribution> {
String resultStatus = uploadResult.getResultStatus();
if (!resultStatus.equals("Success")) {
showFailedNotification(contribution);
EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, application, mwApi)
.param("username", application.getCurrentAccount().name)
EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, getApplicationContext(), mwApi)
.param("username", sessionManager.getCurrentAccount().name)
.param("source", contribution.getSource())
.param("multiple", contribution.getMultiple())
.param("result", uploadResult.getErrorCode())
@ -260,8 +261,8 @@ public class UploadService extends HandlerService<Contribution> {
contribution.setDateUploaded(uploadResult.getDateUploaded());
contribution.save();
EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, application, mwApi)
.param("username", application.getCurrentAccount().name)
EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, getApplicationContext(), mwApi)
.param("username", sessionManager.getCurrentAccount().name)
.param("source", contribution.getSource()) //FIXME
.param("filename", contribution.getFilename())
.param("multiple", contribution.getMultiple())
@ -278,7 +279,7 @@ public class UploadService extends HandlerService<Contribution> {
toUpload--;
if (toUpload == 0) {
// 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);
}
}