Finished removing coupling between classes around the getInstance() method.

This commit is contained in:
Paul Hawke 2017-08-25 21:40:50 -05:00 committed by Paul Hawke
parent dbcbeed822
commit ed1ae98d8e
18 changed files with 154 additions and 125 deletions

View file

@ -79,7 +79,6 @@ public class CommonsApplication extends DaggerApplication {
public static final String FEEDBACK_EMAIL = "commons-app-android@googlegroups.com"; public static final String FEEDBACK_EMAIL = "commons-app-android@googlegroups.com";
public static final String FEEDBACK_EMAIL_SUBJECT = "Commons Android App (%s) Feedback"; public static final String FEEDBACK_EMAIL_SUBJECT = "Commons Android App (%s) Feedback";
private static CommonsApplication instance = null;
private MediaWikiApi api = null; private MediaWikiApi api = null;
private LruCache<String, String> thumbnailUrlCache = new LruCache<>(1024); private LruCache<String, String> thumbnailUrlCache = new LruCache<>(1024);
private CacheController cacheData = null; private CacheController cacheData = null;
@ -87,21 +86,6 @@ public class CommonsApplication extends DaggerApplication {
private NearbyPlaces nearbyPlaces = null; private NearbyPlaces nearbyPlaces = null;
private CommonsApplicationComponent component; private CommonsApplicationComponent component;
/**
* This should not be called by ANY application code (other than the magic Android glue)
* Use CommonsApplication.getInstance() instead to get the singleton.
*/
public CommonsApplication() {
CommonsApplication.instance = this;
}
public static CommonsApplication getInstance() {
if (instance == null) {
instance = new CommonsApplication();
}
return instance;
}
public MediaWikiApi getMWApi() { public MediaWikiApi getMWApi() {
if (api == null) { if (api == null) {
api = new ApacheHttpClientMediaWikiApi(API_URL); api = new ApacheHttpClientMediaWikiApi(API_URL);

View file

@ -40,11 +40,12 @@ public class MediaWikiImageView extends SimpleDraweeView {
return; return;
} }
if (CommonsApplication.getInstance().getThumbnailUrlCache().get(media.getFilename()) != null) { CommonsApplication app = (CommonsApplication) getContext().getApplicationContext();
setImageUrl(CommonsApplication.getInstance().getThumbnailUrlCache().get(media.getFilename())); if (app.getThumbnailUrlCache().get(media.getFilename()) != null) {
setImageUrl(app.getThumbnailUrlCache().get(media.getFilename()));
} else { } else {
setImageUrl(null); setImageUrl(null);
MediaWikiApi mediaWikiApi = CommonsApplication.getInstance().getMWApi(); MediaWikiApi mediaWikiApi = app.getMWApi();
currentThumbnailTask = new ThumbnailFetchTask(media, mediaWikiApi); currentThumbnailTask = new ThumbnailFetchTask(media, mediaWikiApi);
currentThumbnailTask.execute(media.getFilename()); currentThumbnailTask.execute(media.getFilename());
} }
@ -87,7 +88,8 @@ public class MediaWikiImageView extends SimpleDraweeView {
} else { } else {
// only cache meaningful thumbnails received from network. // only cache meaningful thumbnails received from network.
try { try {
CommonsApplication.getInstance().getThumbnailUrlCache().put(media.getFilename(), result); CommonsApplication app = (CommonsApplication) getContext().getApplicationContext();
app.getThumbnailUrlCache().put(media.getFilename(), result);
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
Timber.e("error when adding pic to cache " + npe); Timber.e("error when adding pic to cache " + npe);

View file

@ -30,8 +30,11 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import dagger.android.support.DaggerFragment;
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.data.Category; import fr.free.nrw.commons.data.Category;
@ -48,7 +51,7 @@ import static fr.free.nrw.commons.category.CategoryContentProvider.AUTHORITY;
/** /**
* Displays the category suggestion and selection screen. Category search is initiated here. * Displays the category suggestion and selection screen. Category search is initiated here.
*/ */
public class CategorizationFragment extends Fragment { public class CategorizationFragment extends DaggerFragment {
public static final int SEARCH_CATS_LIMIT = 25; public static final int SEARCH_CATS_LIMIT = 25;
@ -63,6 +66,8 @@ public class CategorizationFragment extends Fragment {
@BindView(R.id.categoriesExplanation) @BindView(R.id.categoriesExplanation)
TextView categoriesSkip; TextView categoriesSkip;
@Inject CommonsApplication application;
private RVRendererAdapter<CategoryItem> categoriesAdapter; private RVRendererAdapter<CategoryItem> categoriesAdapter;
private OnCategoriesSaveHandler onCategoriesSaveHandler; private OnCategoriesSaveHandler onCategoriesSaveHandler;
private HashMap<String, ArrayList<String>> categoriesCache; private HashMap<String, ArrayList<String>> categoriesCache;
@ -202,7 +207,7 @@ public class CategorizationFragment extends Fragment {
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe( .subscribe(
s -> categoriesAdapter.add(s), s -> categoriesAdapter.add(s),
throwable -> Timber.e(throwable), Timber::e,
() -> { () -> {
categoriesAdapter.notifyDataSetChanged(); categoriesAdapter.notifyDataSetChanged();
categoriesSearchInProgress.setVisibility(View.GONE); categoriesSearchInProgress.setVisibility(View.GONE);
@ -248,7 +253,7 @@ public class CategorizationFragment extends Fragment {
SharedPreferences titleDesc = PreferenceManager.getDefaultSharedPreferences(getActivity()); SharedPreferences titleDesc = PreferenceManager.getDefaultSharedPreferences(getActivity());
String title = titleDesc.getString("Title", ""); String title = titleDesc.getString("Title", "");
return CommonsApplication.getInstance().getMWApi() return application.getMWApi()
.searchTitles(title, SEARCH_CATS_LIMIT) .searchTitles(title, SEARCH_CATS_LIMIT)
.map(name -> new CategoryItem(name, false)); .map(name -> new CategoryItem(name, false));
} }
@ -271,7 +276,7 @@ public class CategorizationFragment extends Fragment {
} }
//otherwise, search API for matching categories //otherwise, search API for matching categories
return CommonsApplication.getInstance().getMWApi() return application.getMWApi()
.allCategories(term, SEARCH_CATS_LIMIT) .allCategories(term, SEARCH_CATS_LIMIT)
.map(name -> new CategoryItem(name, false)); .map(name -> new CategoryItem(name, false));
} }
@ -282,7 +287,7 @@ public class CategorizationFragment extends Fragment {
return Observable.empty(); return Observable.empty();
} }
return CommonsApplication.getInstance().getMWApi() return application.getMWApi()
.searchCategories(term, SEARCH_CATS_LIMIT) .searchCategories(term, SEARCH_CATS_LIMIT)
.map(s -> new CategoryItem(s, false)); .map(s -> new CategoryItem(s, false));
} }

View file

@ -1,8 +1,6 @@
package fr.free.nrw.commons.contributions; package fr.free.nrw.commons.contributions;
import android.Manifest;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
@ -23,8 +21,11 @@ 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 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.nearby.NearbyActivity; import fr.free.nrw.commons.nearby.NearbyActivity;
@ -33,7 +34,7 @@ import timber.log.Timber;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE; import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.app.Activity.RESULT_OK; import static android.app.Activity.RESULT_OK;
public class ContributionsListFragment extends Fragment { public class ContributionsListFragment extends DaggerFragment {
public interface SourceRefresher { public interface SourceRefresher {
void refreshSource(); void refreshSource();
@ -43,6 +44,8 @@ public class ContributionsListFragment extends Fragment {
@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
@ -193,7 +196,7 @@ public class ContributionsListFragment extends Fragment {
menu.clear(); // See http://stackoverflow.com/a/8495697/17865 menu.clear(); // See http://stackoverflow.com/a/8495697/17865
inflater.inflate(R.menu.fragment_contributions_list, menu); inflater.inflate(R.menu.fragment_contributions_list, menu);
if (!CommonsApplication.getInstance().deviceHasCamera()) { if (!application.deviceHasCamera()) {
menu.findItem(R.id.menu_from_camera).setEnabled(false); menu.findItem(R.id.menu_from_camera).setEnabled(false);
} }
} }

View file

@ -10,6 +10,7 @@ import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.auth.WikiAccountAuthenticatorService; import fr.free.nrw.commons.auth.WikiAccountAuthenticatorService;
import fr.free.nrw.commons.contributions.ContributionsSyncAdapter; import fr.free.nrw.commons.contributions.ContributionsSyncAdapter;
import fr.free.nrw.commons.modifications.ModificationsSyncAdapter; import fr.free.nrw.commons.modifications.ModificationsSyncAdapter;
import fr.free.nrw.commons.upload.UploadService;
@Singleton @Singleton
@Component(modules = { @Component(modules = {
@ -24,6 +25,8 @@ public interface CommonsApplicationComponent extends AndroidInjector<CommonsAppl
void inject(WikiAccountAuthenticatorService service); void inject(WikiAccountAuthenticatorService service);
void inject(UploadService service);
void inject(ContributionsSyncAdapter syncAdapter); void inject(ContributionsSyncAdapter syncAdapter);
void inject(ModificationsSyncAdapter syncAdapter); void inject(ModificationsSyncAdapter syncAdapter);

View file

@ -22,6 +22,9 @@ import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.Locale; import java.util.Locale;
import javax.inject.Inject;
import dagger.android.support.DaggerFragment;
import fr.free.nrw.commons.CommonsApplication; import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.License; import fr.free.nrw.commons.License;
import fr.free.nrw.commons.LicenseList; import fr.free.nrw.commons.LicenseList;
@ -34,7 +37,7 @@ import fr.free.nrw.commons.location.LatLng;
import fr.free.nrw.commons.ui.widget.CompatTextView; import fr.free.nrw.commons.ui.widget.CompatTextView;
import timber.log.Timber; import timber.log.Timber;
public class MediaDetailFragment extends Fragment { public class MediaDetailFragment extends DaggerFragment {
private boolean editable; private boolean editable;
private MediaDetailPagerFragment.MediaDetailProvider detailProvider; private MediaDetailPagerFragment.MediaDetailProvider detailProvider;
@ -54,6 +57,8 @@ public class MediaDetailFragment extends Fragment {
return mf; return mf;
} }
@Inject CommonsApplication application;
private MediaWikiImageView image; private MediaWikiImageView image;
private MediaDetailSpacer spacer; private MediaDetailSpacer spacer;
private int initialListTop = 0; private int initialListTop = 0;
@ -70,7 +75,7 @@ public class MediaDetailFragment extends Fragment {
private boolean categoriesPresent = false; private boolean categoriesPresent = false;
private ViewTreeObserver.OnGlobalLayoutListener layoutListener; // for layout stuff, only used once! private ViewTreeObserver.OnGlobalLayoutListener layoutListener; // for layout stuff, only used once!
private ViewTreeObserver.OnScrollChangedListener scrollListener; private ViewTreeObserver.OnScrollChangedListener scrollListener;
DataSetObserver dataObserver; private DataSetObserver dataObserver;
private AsyncTask<Void,Void,Boolean> detailFetchTask; private AsyncTask<Void,Void,Boolean> detailFetchTask;
private LicenseList licenseList; private LicenseList licenseList;
@ -189,7 +194,7 @@ public class MediaDetailFragment extends Fragment {
@Override @Override
protected void onPreExecute() { protected void onPreExecute() {
extractor = new MediaDataExtractor(media.getFilename(), licenseList, CommonsApplication.getInstance().getMWApi()); extractor = new MediaDataExtractor(media.getFilename(), licenseList, application.getMWApi());
} }
@Override @Override

View file

@ -27,6 +27,9 @@ import android.view.MenuItem;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import javax.inject.Inject;
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;
@ -34,7 +37,7 @@ 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;
public class MediaDetailPagerFragment extends Fragment implements ViewPager.OnPageChangeListener { public class MediaDetailPagerFragment extends DaggerFragment implements ViewPager.OnPageChangeListener {
public interface MediaDetailProvider { public interface MediaDetailProvider {
Media getMediaAtPosition(int i); Media getMediaAtPosition(int i);
@ -48,9 +51,10 @@ public class MediaDetailPagerFragment extends Fragment implements ViewPager.OnPa
void unregisterDataSetObserver(DataSetObserver observer); void unregisterDataSetObserver(DataSetObserver observer);
} }
@Inject CommonsApplication application;
private ViewPager pager; private ViewPager pager;
private Boolean editable; private Boolean editable;
private CommonsApplication app;
public MediaDetailPagerFragment() { public MediaDetailPagerFragment() {
this(false); this(false);
@ -120,7 +124,6 @@ public class MediaDetailPagerFragment extends Fragment implements ViewPager.OnPa
if (savedInstanceState != null) { if (savedInstanceState != null) {
editable = savedInstanceState.getBoolean("editable"); editable = savedInstanceState.getBoolean("editable");
} }
app = CommonsApplication.getInstance();
setHasOptionsMenu(true); setHasOptionsMenu(true);
} }
@ -131,8 +134,8 @@ public class MediaDetailPagerFragment extends Fragment implements ViewPager.OnPa
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, CommonsApplication.getInstance()) EventLog.schema(CommonsApplication.EVENT_SHARE_ATTEMPT, application)
.param("username", app.getCurrentAccount().name) .param("username", application.getCurrentAccount().name)
.param("filename", m.getFilename()) .param("filename", m.getFilename())
.log(); .log();
return true; return true;

View file

@ -31,7 +31,6 @@ import javax.inject.Inject;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import dagger.android.AndroidInjection;
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.location.LatLng; import fr.free.nrw.commons.location.LatLng;
@ -95,7 +94,7 @@ public class NearbyActivity extends NavigationBaseActivity {
locationManager = new LocationServiceManager(this); locationManager = new LocationServiceManager(this);
locationManager.registerLocationManager(); locationManager.registerLocationManager();
curLatLang = locationManager.getLatestLocation(); curLatLang = locationManager.getLatestLocation();
nearbyAsyncTask = new NearbyAsyncTask(this, application); nearbyAsyncTask = new NearbyAsyncTask(this, new NearbyController(application));
nearbyAsyncTask.execute(); nearbyAsyncTask.execute();
} }
@ -234,7 +233,7 @@ public class NearbyActivity extends NavigationBaseActivity {
} }
private void refreshView() { private void refreshView() {
nearbyAsyncTask = new NearbyAsyncTask(this, application); nearbyAsyncTask = new NearbyAsyncTask(this, new NearbyController(application));
nearbyAsyncTask.execute(); nearbyAsyncTask.execute();
} }
@ -249,11 +248,11 @@ public class NearbyActivity extends NavigationBaseActivity {
private class NearbyAsyncTask extends AsyncTask<Void, Integer, List<Place>> { private class NearbyAsyncTask extends AsyncTask<Void, Integer, List<Place>> {
private final Context mContext; private final Context mContext;
private final CommonsApplication application; private final NearbyController nearbyController;
private NearbyAsyncTask(Context context, CommonsApplication application) { private NearbyAsyncTask(Context context, NearbyController nearbyController) {
mContext = context; this.mContext = context;
this.application = application; this.nearbyController = nearbyController;
} }
@Override @Override
@ -263,8 +262,7 @@ public class NearbyActivity extends NavigationBaseActivity {
@Override @Override
protected List<Place> doInBackground(Void... params) { protected List<Place> doInBackground(Void... params) {
return NearbyController return nearbyController.loadAttractionsFromLocation(curLatLang, application);
.loadAttractionsFromLocation(curLatLang, application);
} }
@Override @Override

View file

@ -10,7 +10,6 @@ import com.mapbox.mapboxsdk.annotations.IconFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@ -29,18 +28,24 @@ import static fr.free.nrw.commons.utils.LengthUtils.formatDistanceBetween;
public class NearbyController { public class NearbyController {
private static final int MAX_RESULTS = 1000; private static final int MAX_RESULTS = 1000;
private final CommonsApplication application;
public NearbyController(CommonsApplication application) {
this.application = application;
}
/** /**
* Prepares Place list to make their distance information update later. * Prepares Place list to make their distance information update later.
* @param curLatLng current location for user * @param curLatLng current location for user
* @param context context * @param context context
* @return Place list without distance information * @return Place list without distance information
*/ */
public static List<Place> loadAttractionsFromLocation(LatLng curLatLng, Context context) { public List<Place> loadAttractionsFromLocation(LatLng curLatLng, Context context) {
Timber.d("Loading attractions near %s", curLatLng); Timber.d("Loading attractions near %s", curLatLng);
if (curLatLng == null) { if (curLatLng == null) {
return Collections.emptyList(); return Collections.emptyList();
} }
NearbyPlaces nearbyPlaces = CommonsApplication.getInstance().getNearbyPlaces(); NearbyPlaces nearbyPlaces = application.getNearbyPlaces();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
List<Place> places = prefs.getBoolean("useWikidata", true) List<Place> places = prefs.getBoolean("useWikidata", true)
? nearbyPlaces.getFromWikidataQuery(curLatLng, Locale.getDefault().getLanguage()) ? nearbyPlaces.getFromWikidataQuery(curLatLng, Locale.getDefault().getLanguage())

View file

@ -1,6 +1,7 @@
package fr.free.nrw.commons.settings; package fr.free.nrw.commons.settings;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.os.Bundle; import android.os.Bundle;
@ -11,11 +12,22 @@ 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 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.Utils; import fr.free.nrw.commons.Utils;
public class SettingsFragment extends PreferenceFragment { public class SettingsFragment extends PreferenceFragment {
@Inject CommonsApplication application;
@Override
public void onAttach(Context context) {
AndroidInjection.inject(this);
super.onAttach(context);
}
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
@ -41,7 +53,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(CommonsApplication.getInstance()); .getDefaultSharedPreferences(application);
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

@ -1,14 +1,12 @@
package fr.free.nrw.commons.upload; package fr.free.nrw.commons.upload;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import java.io.IOException; import java.io.IOException;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.R; import fr.free.nrw.commons.R;
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;
@ -19,6 +17,7 @@ import timber.log.Timber;
* Displays a warning to the user if the file already exists on Commons * Displays a warning to the user if the file already exists on Commons
*/ */
public class ExistingFileAsync extends AsyncTask<Void, Void, Boolean> { public class ExistingFileAsync extends AsyncTask<Void, Void, Boolean> {
interface Callback { interface Callback {
void onResult(Result result); void onResult(Result result);
} }
@ -29,14 +28,16 @@ public class ExistingFileAsync extends AsyncTask<Void, Void, Boolean> {
DUPLICATE_CANCELLED DUPLICATE_CANCELLED
} }
private final MediaWikiApi api;
private final String fileSha1; private final String fileSha1;
private final Context context; private final Context context;
private final Callback callback; private final Callback callback;
public ExistingFileAsync(String fileSha1, Context context, Callback callback) { public ExistingFileAsync(String fileSha1, Context context, Callback callback, MediaWikiApi mwApi) {
this.fileSha1 = fileSha1; this.fileSha1 = fileSha1;
this.context = context; this.context = context;
this.callback = callback; this.callback = callback;
this.api = mwApi;
} }
@Override @Override
@ -46,7 +47,6 @@ public class ExistingFileAsync extends AsyncTask<Void, Void, Boolean> {
@Override @Override
protected Boolean doInBackground(Void... voids) { protected Boolean doInBackground(Void... voids) {
MediaWikiApi api = CommonsApplication.getInstance().getMWApi();
// https://commons.wikimedia.org/w/api.php?action=query&list=allimages&format=xml&aisha1=801957214aba50cb63bb6eb1b0effa50188900ba // https://commons.wikimedia.org/w/api.php?action=query&list=allimages&format=xml&aisha1=801957214aba50cb63bb6eb1b0effa50188900ba
boolean fileExists; boolean fileExists;

View file

@ -154,7 +154,7 @@ public class FileUtils {
} }
/** /**
* Check if the URI is owned by the current app. * Check if the URI is owned by the current application.
*/ */
public static boolean isSelfOwned(Context context, Uri uri) { public static boolean isSelfOwned(Context context, Uri uri) {
return uri.getAuthority().equals(context.getPackageName() + ".provider"); return uri.getAuthority().equals(context.getPackageName() + ".provider");

View file

@ -26,6 +26,7 @@ import timber.log.Timber;
*/ */
public class GPSExtractor { public class GPSExtractor {
private final CommonsApplication application;
private ExifInterface exif; private ExifInterface exif;
private double decLatitude; private double decLatitude;
private double decLongitude; private double decLongitude;
@ -38,26 +39,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
*/ */
@RequiresApi(24) @RequiresApi(24)
public GPSExtractor(@NonNull FileDescriptor fileDescriptor) { public GPSExtractor(@NonNull FileDescriptor fileDescriptor, CommonsApplication application) {
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
*/ */
public GPSExtractor(@NonNull String path) { public GPSExtractor(@NonNull String path, CommonsApplication application) {
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;
} }
/** /**
@ -66,7 +71,7 @@ public class GPSExtractor {
*/ */
private boolean gpsPreferenceEnabled() { private boolean gpsPreferenceEnabled() {
SharedPreferences sharedPref SharedPreferences sharedPref
= PreferenceManager.getDefaultSharedPreferences(CommonsApplication.getInstance()); = PreferenceManager.getDefaultSharedPreferences(application);
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;
@ -76,7 +81,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) CommonsApplication.getInstance() locationManager = (LocationManager) application
.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);

View file

@ -24,6 +24,8 @@ import android.widget.Toast;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.inject.Inject;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import fr.free.nrw.commons.CommonsApplication; import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.Media; import fr.free.nrw.commons.Media;
@ -47,7 +49,9 @@ public class MultipleShareActivity
FragmentManager.OnBackStackChangedListener, FragmentManager.OnBackStackChangedListener,
MultipleUploadListFragment.OnMultipleUploadInitiatedHandler, MultipleUploadListFragment.OnMultipleUploadInitiatedHandler,
OnCategoriesSaveHandler { OnCategoriesSaveHandler {
private CommonsApplication app; @Inject
CommonsApplication application;
private ArrayList<Contribution> photosList = null; private ArrayList<Contribution> photosList = null;
private MultipleUploadListFragment uploadsList; private MultipleUploadListFragment uploadsList;
@ -133,7 +137,7 @@ public class MultipleShareActivity
if (uploadCount == photosList.size()) { if (uploadCount == photosList.size()) {
dialog.dismiss(); dialog.dismiss();
Toast startingToast = Toast.makeText( Toast startingToast = Toast.makeText(
CommonsApplication.getInstance(), application,
R.string.uploading_started, R.string.uploading_started,
Toast.LENGTH_LONG Toast.LENGTH_LONG
); );
@ -176,9 +180,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(app.getCurrentAccount(), ModificationsContentProvider.AUTHORITY, true); // Enable sync by default! ContentResolver.setSyncAutomatically(application.getCurrentAccount(), ModificationsContentProvider.AUTHORITY, true); // Enable sync by default!
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, CommonsApplication.getInstance()) EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, application)
.param("username", app.getCurrentAccount().name) .param("username", application.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)
@ -202,10 +206,9 @@ public class MultipleShareActivity
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
uploadController = new UploadController(); uploadController = new UploadController(application);
setContentView(R.layout.activity_multiple_uploads); setContentView(R.layout.activity_multiple_uploads);
app = CommonsApplication.getInstance();
ButterKnife.bind(this); ButterKnife.bind(this);
initDrawer(); initDrawer();
@ -245,7 +248,7 @@ public class MultipleShareActivity
@Override @Override
protected void onAuthCookieAcquired(String authCookie) { protected void onAuthCookieAcquired(String authCookie) {
app.getMWApi().setAuthCookie(authCookie); application.getMWApi().setAuthCookie(authCookie);
Intent intent = getIntent(); Intent intent = getIntent();
if(intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE)) { if(intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
@ -288,16 +291,16 @@ public class MultipleShareActivity
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, CommonsApplication.getInstance()) EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, application)
.param("username", app.getCurrentAccount().name) .param("username", application.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, CommonsApplication.getInstance()) EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, application)
.param("username", app.getCurrentAccount().name) .param("username", application.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")
@ -307,11 +310,7 @@ public class MultipleShareActivity
@Override @Override
public void onBackStackChanged() { public void onBackStackChanged() {
if(mediaDetails != null && mediaDetails.isVisible()) { getSupportActionBar().setDisplayHomeAsUpEnabled(mediaDetails != null && mediaDetails.isVisible());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
} }
} }

View file

@ -33,13 +33,15 @@ public class MwVolleyApi {
private static RequestQueue REQUEST_QUEUE; private static RequestQueue REQUEST_QUEUE;
private static final Gson GSON = new GsonBuilder().create(); private static final Gson GSON = new GsonBuilder().create();
protected static Set<String> categorySet; private static Set<String> categorySet;
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;
public MwVolleyApi() { public MwVolleyApi(CommonsApplication application) {
categorySet = new HashSet<>(); categorySet = new HashSet<>();
this.application = application;
} }
public static List<String> getGpsCat() { public static List<String> getGpsCat() {
@ -93,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(CommonsApplication.getInstance()); REQUEST_QUEUE = Volley.newRequestQueue(application);
} }
return REQUEST_QUEUE; return REQUEST_QUEUE;
} }

View file

@ -30,6 +30,8 @@ import java.io.InputStream;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import javax.inject.Inject;
import butterknife.ButterKnife; 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;
@ -63,7 +65,7 @@ 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;
private CommonsApplication app; @Inject CommonsApplication application;
private String source; private String source;
private String mimeType; private String mimeType;
@ -114,7 +116,7 @@ public class ShareActivity
@RequiresApi(16) @RequiresApi(16)
private boolean needsToRequestStoragePermission() { private boolean needsToRequestStoragePermission() {
// We need to ask storage permission when // We need to ask storage permission when
// the file is not owned by this app, (e.g. shared from the Gallery) // the file is not owned by this application, (e.g. shared from the Gallery)
// and permission is not obtained. // and permission is not obtained.
return !FileUtils.isSelfOwned(getApplicationContext(), mediaUri) return !FileUtils.isSelfOwned(getApplicationContext(), mediaUri)
&& (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) && (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
@ -125,7 +127,7 @@ public class ShareActivity
getFileMetadata(locationPermitted); getFileMetadata(locationPermitted);
Toast startingToast = Toast.makeText( Toast startingToast = Toast.makeText(
CommonsApplication.getInstance(), application,
R.string.uploading_started, R.string.uploading_started,
Toast.LENGTH_LONG Toast.LENGTH_LONG
); );
@ -133,7 +135,7 @@ public class ShareActivity
if (!cacheFound) { if (!cacheFound) {
//Has to be called after apiCall.request() //Has to be called after apiCall.request()
app.getCacheData().cacheCategory(); application.getCacheData().cacheCategory();
Timber.d("Cache the categories found"); Timber.d("Cache the categories found");
} }
@ -165,10 +167,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(app.getCurrentAccount(), ModificationsContentProvider.AUTHORITY, true); // Enable sync by default! ContentResolver.setSyncAutomatically(application.getCurrentAccount(), ModificationsContentProvider.AUTHORITY, true); // Enable sync by default!
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, CommonsApplication.getInstance()) EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, application)
.param("username", app.getCurrentAccount().name) .param("username", application.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())
@ -189,16 +191,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, CommonsApplication.getInstance()) EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, application)
.param("username", app.getCurrentAccount().name) .param("username", application.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, CommonsApplication.getInstance()) EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, application)
.param("username", app.getCurrentAccount().name) .param("username", application.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")
@ -208,7 +210,7 @@ public class ShareActivity
@Override @Override
protected void onAuthCookieAcquired(String authCookie) { protected void onAuthCookieAcquired(String authCookie) {
app.getMWApi().setAuthCookie(authCookie); application.getMWApi().setAuthCookie(authCookie);
} }
@ -222,11 +224,10 @@ public class ShareActivity
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
uploadController = new UploadController(); uploadController = new UploadController(application);
setContentView(R.layout.activity_share); setContentView(R.layout.activity_share);
ButterKnife.bind(this); ButterKnife.bind(this);
initBack(); initBack();
app = CommonsApplication.getInstance();
backgroundImageView = (SimpleDraweeView)findViewById(R.id.backgroundImage); backgroundImageView = (SimpleDraweeView)findViewById(R.id.backgroundImage);
backgroundImageView.setHierarchy(GenericDraweeHierarchyBuilder backgroundImageView.setHierarchy(GenericDraweeHierarchyBuilder
.newInstance(getResources()) .newInstance(getResources())
@ -384,7 +385,7 @@ public class ShareActivity
Timber.d("%s duplicate check: %s", mediaUri.toString(), result); Timber.d("%s duplicate check: %s", mediaUri.toString(), result);
duplicateCheckPassed = (result == DUPLICATE_PROCEED duplicateCheckPassed = (result == DUPLICATE_PROCEED
|| result == NO_DUPLICATE); || result == NO_DUPLICATE);
}); }, application.getMWApi());
fileAsyncTask.execute(); fileAsyncTask.execute();
} catch (IOException e) { } catch (IOException e) {
Timber.d(e, "IO Exception: "); Timber.d(e, "IO Exception: ");
@ -448,12 +449,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()); imageObj = new GPSExtractor(descriptor.getFileDescriptor(), application);
} }
} else { } else {
String filePath = getPathOfMediaOrCopy(); String filePath = getPathOfMediaOrCopy();
if (filePath != null) { if (filePath != null) {
imageObj = new GPSExtractor(filePath); imageObj = new GPSExtractor(filePath, application);
} }
} }
} }
@ -480,12 +481,12 @@ public class ShareActivity
if (imageObj.imageCoordsExists) { if (imageObj.imageCoordsExists) {
double decLongitude = imageObj.getDecLongitude(); double decLongitude = imageObj.getDecLongitude();
double decLatitude = imageObj.getDecLatitude(); double decLatitude = imageObj.getDecLatitude();
app.getCacheData().setQtPoint(decLongitude, decLatitude); application.getCacheData().setQtPoint(decLongitude, decLatitude);
} }
MwVolleyApi apiCall = new MwVolleyApi(); MwVolleyApi apiCall = new MwVolleyApi(application);
List<String> displayCatList = app.getCacheData().findCategory(); List<String> displayCatList = application.getCacheData().findCategory();
boolean catListEmpty = displayCatList.isEmpty(); boolean catListEmpty = displayCatList.isEmpty();
// If no categories found in cache, call MediaWiki API to match image coords with nearby Commons categories // If no categories found in cache, call MediaWiki API to match image coords with nearby Commons categories

View file

@ -26,14 +26,14 @@ import timber.log.Timber;
public class UploadController { public class UploadController {
private UploadService uploadService; private UploadService uploadService;
private final CommonsApplication app; private final CommonsApplication application;
public interface ContributionUploadProgress { public interface ContributionUploadProgress {
void onUploadStarted(Contribution contribution); void onUploadStarted(Contribution contribution);
} }
public UploadController() { public UploadController(CommonsApplication application) {
app = CommonsApplication.getInstance(); this.application = application;
} }
private boolean isUploadServiceConnected; private boolean isUploadServiceConnected;
@ -52,15 +52,15 @@ public class UploadController {
}; };
public void prepareService() { public void prepareService() {
Intent uploadServiceIntent = new Intent(app, UploadService.class); Intent uploadServiceIntent = new Intent(application, UploadService.class);
uploadServiceIntent.setAction(UploadService.ACTION_START_SERVICE); uploadServiceIntent.setAction(UploadService.ACTION_START_SERVICE);
app.startService(uploadServiceIntent); application.startService(uploadServiceIntent);
app.bindService(uploadServiceIntent, uploadServiceConnection, Context.BIND_AUTO_CREATE); application.bindService(uploadServiceIntent, uploadServiceConnection, Context.BIND_AUTO_CREATE);
} }
public void cleanup() { public void cleanup() {
if(isUploadServiceConnected) { if(isUploadServiceConnected) {
app.unbindService(uploadServiceConnection); application.unbindService(uploadServiceConnection);
} }
} }
@ -68,7 +68,7 @@ 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, app.getCurrentAccount().name, CommonsApplication.DEFAULT_EDIT_SUMMARY, decimalCoords); contribution = new Contribution(mediaUri, null, title, description, -1, null, null, application.getCurrentAccount().name, CommonsApplication.DEFAULT_EDIT_SUMMARY, decimalCoords);
contribution.setTag("mimeType", mimeType); contribution.setTag("mimeType", mimeType);
contribution.setSource(source); contribution.setSource(source);
@ -79,11 +79,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(app); 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(app.getCurrentAccount().name); contribution.setCreator(application.getCurrentAccount().name);
} }
if(contribution.getDescription() == null) { if(contribution.getDescription() == null) {
@ -104,12 +104,12 @@ public class UploadController {
long length; long length;
try { try {
if(contribution.getDataLength() <= 0) { if(contribution.getDataLength() <= 0) {
length = app.getContentResolver() length = application.getContentResolver()
.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 = Utils.countBytes(app.getContentResolver() length = Utils.countBytes(application.getContentResolver()
.openInputStream(contribution.getLocalUri())); .openInputStream(contribution.getLocalUri()));
} }
contribution.setDataLength(length); contribution.setDataLength(length);
@ -126,7 +126,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 = app.getContentResolver().getType(contribution.getLocalUri()); mimeType = application.getContentResolver().getType(contribution.getLocalUri());
} }
if (mimeType != null) { if (mimeType != null) {
@ -137,7 +137,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 = app.getContentResolver().query(contribution.getLocalUri(), Cursor cursor = application.getContentResolver().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

@ -22,6 +22,8 @@ import java.util.Set;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import javax.inject.Inject;
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.R; import fr.free.nrw.commons.R;
@ -45,12 +47,11 @@ 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;
private NotificationManager notificationManager; private NotificationManager notificationManager;
private ContentProviderClient contributionsProviderClient; private ContentProviderClient contributionsProviderClient;
private CommonsApplication app;
private NotificationCompat.Builder curProgressNotification; private NotificationCompat.Builder curProgressNotification;
private int toUpload; private int toUpload;
// The file names of unfinished uploads, used to prevent overwriting // The file names of unfinished uploads, used to prevent overwriting
@ -115,10 +116,11 @@ public class UploadService extends HandlerService<Contribution> {
@Override @Override
public void onCreate() { public void onCreate() {
((CommonsApplication)getApplicationContext()).injector().inject(this);
super.onCreate(); super.onCreate();
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
app = CommonsApplication.getInstance();
contributionsProviderClient = this.getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY); contributionsProviderClient = this.getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY);
} }
@ -180,7 +182,7 @@ public class UploadService extends HandlerService<Contribution> {
@SuppressLint("StringFormatInvalid") @SuppressLint("StringFormatInvalid")
private void uploadContribution(Contribution contribution) { private void uploadContribution(Contribution contribution) {
MediaWikiApi api = app.getMWApi(); MediaWikiApi api = application.getMWApi();
InputStream file = null; InputStream file = null;
@ -222,7 +224,7 @@ public class UploadService extends HandlerService<Contribution> {
} }
if (!api.validateLogin()) { if (!api.validateLogin()) {
// Need to revalidate! // Need to revalidate!
if (app.revalidateAuthToken()) { if (application.revalidateAuthToken()) {
Timber.d("Successfully revalidated token!"); Timber.d("Successfully revalidated token!");
} else { } else {
Timber.d("Unable to revalidate :("); Timber.d("Unable to revalidate :(");
@ -247,8 +249,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, CommonsApplication.getInstance()) EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, application)
.param("username", app.getCurrentAccount().name) .param("username", application.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())
@ -261,8 +263,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, CommonsApplication.getInstance()) EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, application)
.param("username", app.getCurrentAccount().name) .param("username", application.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())
@ -279,7 +281,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((CommonsApplication.getInstance()).getCurrentAccount(), ModificationsContentProvider.AUTHORITY, new Bundle()); ContentResolver.requestSync(application.getCurrentAccount(), ModificationsContentProvider.AUTHORITY, new Bundle());
stopForeground(true); stopForeground(true);
} }
} }
@ -302,7 +304,7 @@ public class UploadService extends HandlerService<Contribution> {
} }
private String findUniqueFilename(String fileName) throws IOException { private String findUniqueFilename(String fileName) throws IOException {
MediaWikiApi api = app.getMWApi(); MediaWikiApi api = application.getMWApi();
String sequenceFileName; String sequenceFileName;
for (int sequenceNumber = 1; true; sequenceNumber++) { for (int sequenceNumber = 1; true; sequenceNumber++) {
if (sequenceNumber == 1) { if (sequenceNumber == 1) {