Revert "Removed dead code behind Campaigns feature"

This reverts commit c64a64c905.

Conflicts:

	commons/src/main/java/fr/free/nrw/commons/contributions/ContributionsListAdapter.java

Changed version number

In preparation for uploading to Google Play
This commit is contained in:
misaochan 2015-10-28 15:00:44 +13:00
parent 6225e04f9a
commit 3972ab9fd3
48 changed files with 1127 additions and 451 deletions

View file

@ -1,7 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="fr.free.nrw.commons"
android:versionCode="17"
android:versionName="1.2" >
android:versionCode="18"
android:versionName="1.3" >
<uses-sdk
android:minSdkVersion="9"

View file

@ -58,7 +58,7 @@ public class CommonsApplication extends Application {
public static final Object[] EVENT_LOGIN_ATTEMPT = {"MobileAppLoginAttempts", 5257721L};
public static final Object[] EVENT_SHARE_ATTEMPT = {"MobileAppShareAttempts", 5346170L};
public static final Object[] EVENT_CATEGORIZATION_ATTEMPT = {"MobileAppCategorizationAttempts", 5359208L};
public static final String DEFAULT_EDIT_SUMMARY = "Uploaded using Android Commons app";
@ -85,7 +85,7 @@ public class CommonsApplication extends Application {
public DBOpenHelper getDbOpenHelper() {
if (dbOpenHelper == null) {
if(dbOpenHelper == null) {
dbOpenHelper = new DBOpenHelper(this);
}
return dbOpenHelper;
@ -154,7 +154,7 @@ public class CommonsApplication extends Application {
private LruCache<String, Bitmap> imageCache;
public com.android.volley.toolbox.ImageLoader getImageLoader() {
if (imageLoader == null) {
if(imageLoader == null) {
imageLoader = new com.android.volley.toolbox.ImageLoader(volleyQueue, new com.android.volley.toolbox.ImageLoader.ImageCache() {
public Bitmap getBitmap(String key) {
return imageCache.get(key);
@ -168,30 +168,30 @@ public class CommonsApplication extends Application {
}
return imageLoader;
}
public MWApi getApi() {
return api;
}
public Account getCurrentAccount() {
if (currentAccount == null) {
if(currentAccount == null) {
AccountManager accountManager = AccountManager.get(this);
Account[] allAccounts = accountManager.getAccountsByType(WikiAccountAuthenticator.COMMONS_ACCOUNT_TYPE);
if (allAccounts.length != 0) {
if(allAccounts.length != 0) {
currentAccount = allAccounts[0];
}
}
return currentAccount;
}
public Boolean revalidateAuthToken() {
AccountManager accountManager = AccountManager.get(this);
Account curAccount = getCurrentAccount();
if (curAccount == null) {
if(curAccount == null) {
return false; // This should never happen
}
accountManager.invalidateAuthToken(WikiAccountAuthenticator.COMMONS_ACCOUNT_TYPE, api.getAuthCookie());
try {
String authCookie = accountManager.blockingGetAuthToken(curAccount, "", false);

View file

@ -7,7 +7,6 @@ import android.util.*;
import in.yuvi.http.fluent.Http;
import org.apache.http.HttpResponse;
import org.json.*;
import java.io.IOException;
import java.net.*;
@ -20,16 +19,16 @@ public class EventLog {
@Override
protected Boolean doInBackground(LogBuilder... logBuilders) {
boolean allSuccess = true;
boolean allSuccess = true;
// Not using the default URL connection, since that seems to have different behavior than the rest of the code
for (LogBuilder logBuilder : logBuilders) {
for(LogBuilder logBuilder: logBuilders) {
HttpURLConnection conn;
try {
URL url = logBuilder.toUrl();
HttpResponse response = Http.get(url.toString()).use(CommonsApplication.createHttpClient()).asResponse();
if (response.getStatusLine().getStatusCode() != 204) {
if(response.getStatusLine().getStatusCode() != 204) {
allSuccess = false;
}
Log.d("Commons", "EventLog hit " + url.toString());
@ -46,7 +45,6 @@ public class EventLog {
}
private static final String DEVICE;
static {
if (Build.MODEL.startsWith(Build.MANUFACTURER)) {
DEVICE = Utils.capitalize(Build.MODEL);
@ -102,7 +100,7 @@ public class EventLog {
// Attempting to use anywhere else will cause kitten explosions
public void log(boolean force) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(app);
if (!settings.getBoolean(Prefs.TRACKING_ENABLED, true) && !force) {
if(!settings.getBoolean(Prefs.TRACKING_ENABLED, true) && !force) {
return; // User has disabled tracking
}
LogTask logTask = new LogTask();
@ -120,9 +118,9 @@ public class EventLog {
}
public static LogBuilder schema(Object[] scid) {
if (scid.length != 2) {
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]);
return schema((String)scid[0], (Long)scid[1]);
}
}

View file

@ -16,7 +16,7 @@ public abstract class HandlerService<T> extends Service {
@Override
public void handleMessage(Message msg) {
handle(msg.what, (T) msg.obj);
handle(msg.what, (T)msg.obj);
stopSelf(msg.arg1);
}
}
@ -35,7 +35,6 @@ public abstract class HandlerService<T> extends Service {
}
private final IBinder localBinder = new HandlerServiceLocalBinder();
@Override
public IBinder onBind(Intent intent) {
return localBinder;

View file

@ -34,15 +34,14 @@ public class Media implements Parcelable {
}
public static Pattern displayTitlePattern = Pattern.compile("(.*)(\\.\\w+)", Pattern.CASE_INSENSITIVE);
public String getDisplayTitle() {
if (filename == null) {
public String getDisplayTitle() {
if(filename == null) {
return "";
}
// FIXME: Gross hack bercause my regex skills suck maybe or I am too lazy who knows
String title = filename.replaceFirst("^File:", "");
Matcher matcher = displayTitlePattern.matcher(title);
if (matcher.matches()) {
if(matcher.matches()) {
return matcher.group(1);
} else {
return title;
@ -59,7 +58,7 @@ public class Media implements Parcelable {
}
public String getImageUrl() {
if (imageUrl == null) {
if(imageUrl == null) {
imageUrl = Utils.makeThumbBaseUrl(this.getFilename());
}
return imageUrl;
@ -152,7 +151,7 @@ public class Media implements Parcelable {
protected Map<String, String> descriptions; // multilingual descriptions as loaded
public ArrayList<String> getCategories() {
return (ArrayList<String>) categories.clone(); // feels dirty
return (ArrayList<String>)categories.clone(); // feels dirty
}
public void setCategories(List<String> categories) {
@ -160,7 +159,7 @@ public class Media implements Parcelable {
this.categories.addAll(categories);
}
public void setDescriptions(Map<String, String> descriptions) {
public void setDescriptions(Map<String,String> descriptions) {
for (String key : this.descriptions.keySet()) {
this.descriptions.remove(key);
}
@ -224,7 +223,7 @@ public class Media implements Parcelable {
}
public Media(Parcel in) {
localUri = (Uri) in.readParcelable(Uri.class.getClassLoader());
localUri = (Uri)in.readParcelable(Uri.class.getClassLoader());
imageUrl = in.readString();
filename = in.readString();
description = in.readString();
@ -232,7 +231,7 @@ public class Media implements Parcelable {
dateCreated = (Date) in.readSerializable();
dateUploaded = (Date) in.readSerializable();
creator = in.readString();
tags = (HashMap<String, Object>) in.readSerializable();
tags = (HashMap<String, Object>)in.readSerializable();
width = in.readInt();
height = in.readInt();
license = in.readString();

View file

@ -20,7 +20,7 @@ import java.util.regex.Pattern;
/**
* Fetch additional media data from the network that we don't store locally.
* <p>
*
* This includes things like category lists and multilingual descriptions,
* which are not intrinsic to the media and may change due to editing.
*/
@ -51,7 +51,7 @@ public class MediaDataExtractor {
/**
* Actually fetch the data over the network.
* todo: use local caching?
* <p>
*
* Warning: synchronous i/o, call on a background thread
*/
public void fetch() throws IOException {
@ -156,7 +156,7 @@ public class MediaDataExtractor {
}
private Node findTemplate(Element parentNode, String title) throws IOException {
String ucTitle = Utils.capitalize(title);
String ucTitle= Utils.capitalize(title);
NodeList nodes = parentNode.getChildNodes();
for (int i = 0, length = nodes.getLength(); i < length; i++) {
Node node = nodes.item(i);
@ -200,7 +200,7 @@ public class MediaDataExtractor {
return findTemplateParameter(templateNode, new TemplateChildNodeComparator() {
@Override
public boolean match(Node node) {
Element el = (Element) node;
Element el = (Element)node;
if (el.getTextContent().trim().equals(theIndex)) {
return true;
} else if (el.getAttribute("index") != null && el.getAttribute("index").trim().equals(theIndex)) {
@ -278,7 +278,6 @@ public class MediaDataExtractor {
/**
* Take our metadata and inject it into a live Media object.
* Media object might contain stale or cached data, or emptiness.
*
* @param media
*/
public void fill(Media media) {

View file

@ -1,12 +1,12 @@
/**
* Copyright (C) 2013 The Android Open Source Project
* <p>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -85,29 +85,29 @@ public class MediaWikiImageView extends ImageView {
return;
}
if (mMedia == null) {
if(mMedia == null) {
return;
}
// Do not count for density when loading thumbnails.
// FIXME: Use another 'algorithm' that doesn't punish low res devices
if (isThumbnail) {
float dpFactor = Math.max(getResources().getDisplayMetrics().density, 1.0f);
if(isThumbnail) {
float dpFactor = Math.max(getResources().getDisplayMetrics().density, 1.0f);
width = (int) (width / dpFactor);
height = (int) (height / dpFactor);
}
final String mUrl;
if (tryOriginal) {
final String mUrl;
if(tryOriginal) {
mUrl = mMedia.getImageUrl();
} else {
// Round it to the nearest 320
// Possible a similar size image has already been generated.
// Reduces Server cache fragmentation, also increases chance of cache hit
// If width is less than 320, we round up to 320
int bucketedWidth = width <= 320 ? 320 : Math.round((float) width / 320.0f) * 320;
if (mMedia.getWidth() != 0 && mMedia.getWidth() < bucketedWidth) {
int bucketedWidth = width <= 320 ? 320 : Math.round((float)width / 320.0f) * 320;
if(mMedia.getWidth() != 0 && mMedia.getWidth() < bucketedWidth) {
// If we know that the width of the image is lesser than the required width
// We don't even try to load the thumbnai, go directly to the source
loadImageIfNecessary(isInLayoutPass, true);
@ -137,10 +137,10 @@ public class MediaWikiImageView extends ImageView {
} else {
// if there is a pre-existing request, cancel it if it's fetching a different URL.
mImageContainer.cancelRequest();
BitmapDrawable actualDrawable = (BitmapDrawable) getDrawable();
if (actualDrawable != null && actualDrawable.getBitmap() != null) {
BitmapDrawable actualDrawable = (BitmapDrawable)getDrawable();
if(actualDrawable != null && actualDrawable.getBitmap() != null) {
setImageBitmap(null);
if (loadingView != null) {
if(loadingView != null) {
loadingView.setVisibility(View.VISIBLE);
}
}
@ -153,7 +153,7 @@ public class MediaWikiImageView extends ImageView {
new ImageListener() {
@Override
public void onErrorResponse(final VolleyError error) {
if (!tryOriginal) {
if(!tryOriginal) {
post(new Runnable() {
public void run() {
loadImageIfNecessary(false, true);
@ -181,14 +181,14 @@ public class MediaWikiImageView extends ImageView {
if (response.getBitmap() != null) {
setImageBitmap(response.getBitmap());
if (tryOriginal && mMedia instanceof Contribution && (response.getBitmap().getWidth() > mMedia.getWidth() || response.getBitmap().getHeight() > mMedia.getHeight())) {
if(tryOriginal && mMedia instanceof Contribution && (response.getBitmap().getWidth() > mMedia.getWidth() || response.getBitmap().getHeight() > mMedia.getHeight())) {
// If there is no width information for this image, save it. This speeds up image loading massively for smaller images
mMedia.setHeight(response.getBitmap().getHeight());
mMedia.setWidth(response.getBitmap().getWidth());
((Contribution) mMedia).setContentProviderClient(MediaWikiImageView.this.getContext().getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY));
((Contribution) mMedia).save();
((Contribution)mMedia).setContentProviderClient(MediaWikiImageView.this.getContext().getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY));
((Contribution)mMedia).save();
}
if (loadingView != null) {
if(loadingView != null) {
loadingView.setVisibility(View.GONE);
}
} else {

View file

@ -9,7 +9,6 @@ import com.actionbarsherlock.app.SherlockPreferenceActivity;
public class SettingsActivity extends SherlockPreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
CommonsApplication app;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -30,12 +29,12 @@ public class SettingsActivity extends SherlockPreferenceActivity implements Shar
licensePreference.setSummary(getString(Utils.licenseNameFor(licensePreference.getValue())));
licensePreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
preference.setSummary(getString(Utils.licenseNameFor((String) newValue)));
preference.setSummary(getString(Utils.licenseNameFor((String)newValue)));
return true;
}
});
app = (CommonsApplication) getApplicationContext();
app = (CommonsApplication)getApplicationContext();
}
@Override

View file

@ -72,7 +72,8 @@ public class Utils {
T... params) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
} else {
}
else {
task.execute(params);
}
}
@ -82,16 +83,16 @@ public class Utils {
// FIXME: We're simply ignoring the executor on older androids
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(executor, params);
} else {
}
else {
task.execute(params);
}
}
private static DisplayImageOptions.Builder defaultImageOptionsBuilder;
public static DisplayImageOptions.Builder getGenericDisplayOptions() {
if (defaultImageOptionsBuilder == null) {
if(defaultImageOptionsBuilder == null) {
defaultImageOptionsBuilder = new DisplayImageOptions.Builder().cacheInMemory()
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
@ -121,7 +122,7 @@ public class Utils {
public static long countBytes(InputStream stream) throws IOException {
long count = 0;
BufferedInputStream bis = new BufferedInputStream(stream);
while (bis.read() != -1) {
while(bis.read() != -1) {
count++;
}
return count;
@ -131,7 +132,7 @@ public class Utils {
// Ugly Hack!
// Update: OH DEAR GOD WHAT A HORRIBLE HACK I AM SO SORRY
String thumbUrl = imageUrl.replaceFirst("test/", "test/thumb/").replace("commons/", "commons/thumb/") + "/" + width + "px-" + filename.replaceAll("File:", "").replaceAll(" ", "_");
if (thumbUrl.endsWith("jpg") || thumbUrl.endsWith("png") || thumbUrl.endsWith("jpeg")) {
if(thumbUrl.endsWith("jpg") || thumbUrl.endsWith("png") || thumbUrl.endsWith("jpeg")) {
return thumbUrl;
} else {
return thumbUrl + ".png";
@ -139,37 +140,37 @@ public class Utils {
}
public static String capitalize(String string) {
return string.substring(0, 1).toUpperCase() + string.substring(1);
return string.substring(0,1).toUpperCase() + string.substring(1);
}
public static String licenseTemplateFor(String license) {
if (license.equals(Prefs.Licenses.CC_BY)) {
if(license.equals(Prefs.Licenses.CC_BY)) {
return "{{self|cc-by-3.0}}";
} else if (license.equals(Prefs.Licenses.CC_BY_SA)) {
} else if(license.equals(Prefs.Licenses.CC_BY_SA)) {
return "{{self|cc-by-sa-3.0}}";
} else if (license.equals(Prefs.Licenses.CC0)) {
} else if(license.equals(Prefs.Licenses.CC0)) {
return "{{self|cc-zero}}";
}
throw new RuntimeException("Unrecognized license value");
}
public static int licenseNameFor(String license) {
if (license.equals(Prefs.Licenses.CC_BY)) {
if(license.equals(Prefs.Licenses.CC_BY)) {
return R.string.license_name_cc_by;
} else if (license.equals(Prefs.Licenses.CC_BY_SA)) {
} else if(license.equals(Prefs.Licenses.CC_BY_SA)) {
return R.string.license_name_cc_by_sa;
} else if (license.equals(Prefs.Licenses.CC0)) {
} else if(license.equals(Prefs.Licenses.CC0)) {
return R.string.license_name_cc0;
}
throw new RuntimeException("Unrecognized license value");
}
public static String licenseUrlFor(String license) {
if (license.equals(Prefs.Licenses.CC_BY)) {
if(license.equals(Prefs.Licenses.CC_BY)) {
return "https://creativecommons.org/licenses/by/3.0/";
} else if (license.equals(Prefs.Licenses.CC_BY_SA)) {
} else if(license.equals(Prefs.Licenses.CC_BY_SA)) {
return "https://creativecommons.org/licenses/by-sa/3.0/";
} else if (license.equals(Prefs.Licenses.CC0)) {
} else if(license.equals(Prefs.Licenses.CC0)) {
return "https://creativecommons.org/publicdomain/zero/1.0/";
}
throw new RuntimeException("Unrecognized license value");

View file

@ -14,7 +14,7 @@ public class WelcomeActivity extends Activity {
static final int PAGE_WIKIPEDIA = 0,
PAGE_COPYRIGHT = 1,
PAGE_FINAL = 2;
static final int[] pageLayouts = new int[]{
static final int[] pageLayouts = new int[] {
R.layout.welcome_wikipedia,
R.layout.welcome_copyright,
R.layout.welcome_final
@ -28,7 +28,7 @@ public class WelcomeActivity extends Activity {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
pager = (ViewPager) findViewById(R.id.welcomePager);
pager = (ViewPager)findViewById(R.id.welcomePager);
pager.setAdapter(new PagerAdapter() {
@Override
public int getCount() {
@ -45,7 +45,7 @@ public class WelcomeActivity extends Activity {
View view = getLayoutInflater().inflate(pageLayouts[position], null);
container.addView(view);
if (position == PAGE_FINAL) {
yesButton = (Button) view.findViewById(R.id.welcomeYesButton);
yesButton = (Button)view.findViewById(R.id.welcomeYesButton);
yesButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
finish();
@ -58,11 +58,11 @@ public class WelcomeActivity extends Activity {
@Override
public void destroyItem(ViewGroup container, int position, Object obj) {
yesButton = null;
container.removeView((View) obj);
container.removeView((View)obj);
}
});
CirclePageIndicator indicator = (CirclePageIndicator) findViewById(R.id.welcomePagerIndicator);
CirclePageIndicator indicator = (CirclePageIndicator)findViewById(R.id.welcomePagerIndicator);
indicator.setViewPager(pager);
}
}

View file

@ -12,31 +12,30 @@ import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.Utils;
public class AuthenticatedActivity extends SherlockFragmentActivity {
String accountType;
CommonsApplication app;
private String authCookie;
public AuthenticatedActivity(String accountType) {
this.accountType = accountType;
this.accountType = accountType;
}
private class GetAuthCookieTask extends AsyncTask<Void, String, String> {
private Account account;
private AccountManager accountManager;
public GetAuthCookieTask(Account account, AccountManager accountManager) {
this.account = account;
this.accountManager = accountManager;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
if(result != null) {
authCookie = result;
onAuthCookieAcquired(result);
} else {
@ -60,20 +59,19 @@ public class AuthenticatedActivity extends SherlockFragmentActivity {
}
}
}
private class AddAccountTask extends AsyncTask<Void, String, String> {
private AccountManager accountManager;
public AddAccountTask(AccountManager accountManager) {
this.accountManager = accountManager;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
Account[] allAccounts = accountManager.getAccountsByType(accountType);
if(result != null) {
Account[] allAccounts =accountManager.getAccountsByType(accountType);
Account curAccount = allAccounts[0];
GetAuthCookieTask getCookieTask = new GetAuthCookieTask(curAccount, accountManager);
getCookieTask.execute();
@ -100,23 +98,22 @@ public class AuthenticatedActivity extends SherlockFragmentActivity {
e.printStackTrace();
return null;
}
if (result.containsKey(AccountManager.KEY_ACCOUNT_NAME)) {
if(result.containsKey(AccountManager.KEY_ACCOUNT_NAME)) {
return result.getString(AccountManager.KEY_ACCOUNT_NAME);
} else {
return null;
}
}
}
protected void requestAuthToken() {
if (authCookie != null) {
if(authCookie != null) {
onAuthCookieAcquired(authCookie);
return;
}
AccountManager accountManager = AccountManager.get(this);
Account curAccount = app.getCurrentAccount();
if (curAccount == null) {
if(curAccount == null) {
AddAccountTask addAccountTask = new AddAccountTask(accountManager);
// This AsyncTask blocks until the Login Activity returns
// And since in Android 4.x+ only one background thread runs all AsyncTasks
@ -130,12 +127,12 @@ public class AuthenticatedActivity extends SherlockFragmentActivity {
task.execute();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = (CommonsApplication) this.getApplicationContext();
if (savedInstanceState != null) {
app = (CommonsApplication)this.getApplicationContext();
if(savedInstanceState != null) {
authCookie = savedInstanceState.getString("authCookie");
}
}
@ -147,10 +144,9 @@ public class AuthenticatedActivity extends SherlockFragmentActivity {
}
protected void onAuthCookieAcquired(String authCookie) {
}
protected void onAuthFailure() {
}
}

View file

@ -17,6 +17,7 @@ import android.support.v4.app.NavUtils;
import fr.free.nrw.commons.*;
import fr.free.nrw.commons.WelcomeActivity;
import fr.free.nrw.commons.campaigns.CampaignsContentProvider;
import fr.free.nrw.commons.modifications.ModificationsContentProvider;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.EventLog;
@ -71,20 +72,21 @@ public class LoginActivity extends AccountAuthenticatorActivity {
// FIXME: If the user turns it off, it shouldn't be auto turned back on
ContentResolver.setSyncAutomatically(account, ContributionsContentProvider.AUTHORITY, true); // Enable sync by default!
ContentResolver.setSyncAutomatically(account, ModificationsContentProvider.AUTHORITY, true); // Enable sync by default!
ContentResolver.setSyncAutomatically(account, CampaignsContentProvider.AUTHORITY, true); // Enable sync by default!
context.finish();
} else {
int response;
if (result.equals("NetworkFailure")) {
if(result.equals("NetworkFailure")) {
response = R.string.login_failed_network;
} else if (result.equals("NotExists") || result.equals("Illegal") || result.equals("NotExists")) {
} else if(result.equals("NotExists") || result.equals("Illegal") || result.equals("NotExists")) {
response = R.string.login_failed_username;
passwordEdit.setText("");
} else if (result.equals("EmptyPass") || result.equals("WrongPass")) {
} else if(result.equals("EmptyPass") || result.equals("WrongPass")) {
response = R.string.login_failed_password;
passwordEdit.setText("");
} else if (result.equals("Throttled")) {
} else if(result.equals("Throttled")) {
response = R.string.login_failed_throttled;
} else if (result.equals("Blocked")) {
} else if(result.equals("Blocked")) {
response = R.string.login_failed_blocked;
} else {
// Should never really happen
@ -137,14 +139,12 @@ public class LoginActivity extends AccountAuthenticatorActivity {
final LoginActivity that = this;
TextWatcher loginEnabler = new TextWatcher() {
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
}
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) { }
public void onTextChanged(CharSequence charSequence, int start, int count, int after) {
}
public void onTextChanged(CharSequence charSequence, int start, int count, int after) { }
public void afterTextChanged(Editable editable) {
if (usernameEdit.getText().length() != 0 && passwordEdit.getText().length() != 0) {
if(usernameEdit.getText().length() != 0 && passwordEdit.getText().length() != 0) {
loginButton.setEnabled(true);
} else {
loginButton.setEnabled(false);
@ -190,7 +190,7 @@ public class LoginActivity extends AccountAuthenticatorActivity {
private void performLogin() {
String username = usernameEdit.getText().toString();
// Because Mediawiki is upercase-first-char-then-case-sensitive :)
String canonicalUsername = username.substring(0, 1).toUpperCase() + username.substring(1);
String canonicalUsername = username.substring(0,1).toUpperCase() + username.substring(1);
String password = passwordEdit.getText().toString();
@ -208,9 +208,9 @@ public class LoginActivity extends AccountAuthenticatorActivity {
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}

View file

@ -13,7 +13,6 @@ public class WikiAccountAuthenticator extends AbstractAccountAuthenticator {
public static final String COMMONS_ACCOUNT_TYPE = "fr.free.nrw.commons";
private Context context;
public WikiAccountAuthenticator(Context context) {
super(context);
this.context = context;
@ -44,13 +43,12 @@ public class WikiAccountAuthenticator extends AbstractAccountAuthenticator {
private String getAuthCookie(String username, String password) throws IOException {
MWApi api = CommonsApplication.createMWApi();
String result = api.login(username, password);
if (result.equals("Success")) {
if(result.equals("Success")) {
return api.getAuthCookie();
} else {
return null;
}
}
@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException {
// Extract the username and password from the Account Manager, and ask

View file

@ -4,17 +4,17 @@ import android.app.*;
import android.content.*;
import android.os.*;
public class WikiAccountAuthenticatorService extends Service {
public class WikiAccountAuthenticatorService extends Service{
private static WikiAccountAuthenticator wikiAccountAuthenticator = null;
@Override
public IBinder onBind(Intent intent) {
if (!intent.getAction().equals(android.accounts.AccountManager.ACTION_AUTHENTICATOR_INTENT)) {
return null;
return null;
}
if (wikiAccountAuthenticator == null) {
if(wikiAccountAuthenticator == null) {
wikiAccountAuthenticator = new WikiAccountAuthenticator(this);
}
return wikiAccountAuthenticator.getIBinder();

View file

@ -0,0 +1,190 @@
package fr.free.nrw.commons.campaigns;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.ArrayList;
// FIXME: Implement Parcelable
public class Campaign implements Serializable {
private boolean enabled;
private String autoAddWikitext;
private ArrayList<String> autoAddCategories;
private String name;
private String ownWorkLicenseDefault;
private String defaultDescription;
private JSONObject config;
private String body;
private boolean isParsed;
private String trackingCategory;
private String description;
private String title;
public boolean isEnabled() {
return enabled;
}
public String getAutoAddWikitext() {
if(!this.isParsed) {
this.parseConfig();
}
return autoAddWikitext;
}
public ArrayList<String> getAutoAddCategories() {
if(!this.isParsed) {
this.parseConfig();
}
return autoAddCategories;
}
public String getName() {
return name;
}
public String getOwnWorkLicenseDefault() {
if(!this.isParsed) {
this.parseConfig();
}
return ownWorkLicenseDefault;
}
public String getDefaultDescription() {
if(!this.isParsed) {
this.parseConfig();
}
return defaultDescription;
}
public JSONObject getConfig() {
if(!this.isParsed) {
this.parseConfig();
}
return config;
}
private void parseConfig() {
try {
this.config = new JSONObject(body);
} catch (JSONException e) {
throw new RuntimeException(e); // because what else are you gonna do?
}
if(config.has("autoAdd")) {
this.autoAddWikitext = config.optJSONObject("autoAdd").optString("wikitext", null);
if(config.optJSONObject("autoAdd").has("categories")) {
this.autoAddCategories = new ArrayList<String>();
JSONArray catsArray = config.optJSONObject("autoAdd").optJSONArray("categories");
for(int i=0; i < catsArray.length(); i++) {
autoAddCategories.add(catsArray.optString(i));
}
}
}
this.title = config.optString("title", name);
this.description = config.optString("description", "");
this.isParsed = true;
}
private Campaign(String name, String body, String trackingCategory) {
this.name = name;
this.body = body;
this.trackingCategory = trackingCategory;
}
public ContentValues toContentValues() {
ContentValues cv = new ContentValues();
cv.put(Table.COLUMN_NAME, this.getName());
cv.put(Table.COLUMN_ENABLED, this.isEnabled() ? 1 : 0);
cv.put(Table.COLUMN_TITLE, this.getTitle());
cv.put(Table.COLUMN_DESCRIPTION, this.getDescription());
cv.put(Table.COLUMN_TRACKING_CATEGORY, this.getTrackingCategory());
cv.put(Table.COLUMN_BODY, this.body);
return cv;
}
public static Campaign parse(String name, String body, String trackingCategory) {
Campaign c = new Campaign(name, body, trackingCategory);
c.parseConfig();
return c;
}
public static Campaign fromCursor(Cursor cursor) {
String name = cursor.getString(1);
Boolean enabled = cursor.getInt(2) == 1;
String title = cursor.getString(3);
String description = cursor.getString(4);
String trackingCategory = cursor.getString(5);
String body = cursor.getString(6);
Campaign c = new Campaign(name, body, trackingCategory);
c.title = title;
c.description = description;
c.enabled = enabled;
return c;
}
public String getTrackingCategory() {
return trackingCategory;
}
public String getDescription() {
return description;
}
public String getTitle() {
return title;
}
public static class Table {
public static final String TABLE_NAME = "campaigns";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_ENABLED = "enabled";
public static final String COLUMN_TITLE = "title";
public static final String COLUMN_DESCRIPTION = "description";
public static final String COLUMN_TRACKING_CATEGORY = "tracking_category";
public static final String COLUMN_BODY = "body";
// NOTE! KEEP IN SAME ORDER AS THEY ARE DEFINED UP THERE. HELPS HARD CODE COLUMN INDICES.
public static final String[] ALL_FIELDS = {
COLUMN_ID,
COLUMN_NAME,
COLUMN_ENABLED,
COLUMN_TITLE,
COLUMN_DESCRIPTION,
COLUMN_TRACKING_CATEGORY,
COLUMN_BODY
};
private static final String CREATE_TABLE_STATEMENT = "CREATE TABLE " + TABLE_NAME + " ("
+ "_id INTEGER PRIMARY KEY,"
+ "name STRING,"
+ "enabled INTEGER,"
+ "title STRING,"
+ "description STRING,"
+ "tracking_category STRING,"
+ "body STRING"
+ ");";
public static void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_STATEMENT);
}
public static void onUpdate(SQLiteDatabase db, int from, int to) {
if(to <= 6) {
onCreate(db);
return;
}
return;
}
}
}

View file

@ -0,0 +1,59 @@
package fr.free.nrw.commons.campaigns;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import fr.free.nrw.commons.contributions.ContributionsActivity;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.R;
public class CampaignActivity
extends SherlockFragmentActivity
implements LoaderManager.LoaderCallbacks<Cursor> {
private ListView campaignsListView;
private CampaignsListAdapter campaignsListAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_campaigns);
ContentResolver.setSyncAutomatically(((CommonsApplication)getApplicationContext()).getCurrentAccount(), CampaignsContentProvider.AUTHORITY, true); // Enable sync by default!
campaignsListView = (ListView) findViewById(R.id.campaignsList);
campaignsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Campaign c = Campaign.fromCursor((Cursor) adapterView.getItemAtPosition(i));
Intent intent = new Intent(CampaignActivity.this, ContributionsActivity.class);
intent.putExtra("campaign", c);
startActivity(intent);
}
});
getSupportLoaderManager().initLoader(0, null, this);
}
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this, CampaignsContentProvider.BASE_URI, Campaign.Table.ALL_FIELDS, "", null, "");
}
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
if(campaignsListAdapter == null) {
campaignsListAdapter = new CampaignsListAdapter(this, cursor, 0);
campaignsListView.setAdapter(campaignsListAdapter);
} else {
campaignsListAdapter.swapCursor(cursor);
}
}
public void onLoaderReset(Loader<Cursor> cursorLoader) {
campaignsListAdapter.swapCursor(null);
}
}

View file

@ -0,0 +1,49 @@
package fr.free.nrw.commons.campaigns;
import android.net.Uri;
import fr.free.nrw.commons.contributions.Contribution;
import java.util.ArrayList;
import java.util.Date;
public class CampaignContribution extends Contribution {
private Campaign campaign;
private ArrayList<String> fieldValues;
public CampaignContribution(Uri localUri, String remoteUri, String filename, String description, long dataLength, Date dateCreated, Date dateUploaded, String creator, String editSummary, Campaign campaign) {
super(localUri, remoteUri, filename, description, dataLength, dateCreated, dateUploaded, creator, editSummary);
this.campaign = campaign;
}
public Campaign getCampaign() {
return campaign;
}
public void setCampaign(Campaign campaign) {
this.campaign = campaign;
}
@Override
public String getTrackingTemplates() {
StringBuffer buffer = new StringBuffer();
if(campaign.getAutoAddWikitext() != null) {
buffer.append(campaign.getAutoAddWikitext()).append("\n");
}
if(campaign.getAutoAddCategories() != null && campaign.getAutoAddCategories().size() != 0) {
for(String cat : campaign.getAutoAddCategories()) {
buffer.append("[[Category:").append(cat).append("]]").append("\n");
}
} else {
buffer.append("{{subst:unc}}\n");
}
buffer.append("[[Category:").append(campaign.getTrackingCategory()).append("]]").append("\n");
return buffer.toString();
}
@Override
public String getDescription() {
return super.getDescription();
}
}

View file

@ -0,0 +1,206 @@
package fr.free.nrw.commons.campaigns;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.data.DBOpenHelper;
public class CampaignsContentProvider extends ContentProvider{
private static final int CAMPAIGNS = 1;
private static final int CAMPAIGNS_ID = 2;
public static final String AUTHORITY = "fr.free.nrw.commons.campaigns.contentprovider";
private static final String BASE_PATH = "campiagns";
public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);
private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
uriMatcher.addURI(AUTHORITY, BASE_PATH, CAMPAIGNS);
uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", CAMPAIGNS_ID);
}
public static Uri uriForId(int id) {
return Uri.parse(BASE_URI.toString() + "/" + id);
}
private DBOpenHelper dbOpenHelper;
@Override
public boolean onCreate() {
dbOpenHelper = ((CommonsApplication)this.getContext().getApplicationContext()).getDbOpenHelper();
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(Campaign.Table.TABLE_NAME);
int uriType = uriMatcher.match(uri);
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
Cursor cursor;
switch(uriType) {
case CAMPAIGNS:
cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
break;
case CAMPAIGNS_ID:
cursor = queryBuilder.query(db,
Campaign.Table.ALL_FIELDS,
"_id = ?",
new String[] { uri.getLastPathSegment() },
null,
null,
sortOrder
);
break;
default:
throw new IllegalArgumentException("Unknown URI" + uri);
}
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues contentValues) {
int uriType = uriMatcher.match(uri);
SQLiteDatabase sqlDB = dbOpenHelper.getWritableDatabase();
long id = 0;
switch (uriType) {
case CAMPAIGNS:
sqlDB.beginTransaction();
// if the campaign already exists, rip it out and then re-insert
if(campaignExists(sqlDB, contentValues)) {
sqlDB.delete(
Campaign.Table.TABLE_NAME,
Campaign.Table.COLUMN_NAME + " = ?",
new String[]{contentValues.getAsString(Campaign.Table.COLUMN_NAME)}
);
}
id = sqlDB.insert(Campaign.Table.TABLE_NAME, null, contentValues);
sqlDB.endTransaction();
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return Uri.parse(BASE_URI + "/" + id);
}
@Override
public int delete(Uri uri, String s, String[] strings) {
int rows = 0;
int uriType = uriMatcher.match(uri);
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
switch(uriType) {
case CAMPAIGNS_ID:
rows = db.delete(Campaign.Table.TABLE_NAME,
"_id = ?",
new String[] { uri.getLastPathSegment() }
);
break;
default:
throw new IllegalArgumentException("Unknown URI" + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rows;
}
private boolean campaignExists(SQLiteDatabase db, ContentValues campaign) {
Cursor cr = db.query(
Campaign.Table.TABLE_NAME,
new String[]{Campaign.Table.COLUMN_NAME},
Campaign.Table.COLUMN_NAME + " = ?",
new String[]{campaign.getAsString(Campaign.Table.COLUMN_NAME)},
"", "", ""
);
return cr != null && cr.getCount() != 0;
}
@Override
public int bulkInsert(Uri uri, ContentValues[] values) {
Log.d("Commons", "Hello, bulk insert!");
int uriType = uriMatcher.match(uri);
SQLiteDatabase sqlDB = dbOpenHelper.getWritableDatabase();
sqlDB.beginTransaction();
switch (uriType) {
case CAMPAIGNS:
for(ContentValues value: values) {
Log.d("Commons", "Inserting! " + value.toString());
// if the campaign already exists, rip it out and then re-insert
if(campaignExists(sqlDB, value)) {
sqlDB.delete(
Campaign.Table.TABLE_NAME,
Campaign.Table.COLUMN_NAME + " = ?",
new String[]{value.getAsString(Campaign.Table.COLUMN_NAME)}
);
}
sqlDB.insert(Campaign.Table.TABLE_NAME, null, value);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
sqlDB.setTransactionSuccessful();
sqlDB.endTransaction();
getContext().getContentResolver().notifyChange(uri, null);
return values.length;
}
@Override
public int update(Uri uri, ContentValues contentValues, String selection, String[] selectionArgs) {
/*
SQL Injection warnings: First, note that we're not exposing this to the outside world (exported="false")
Even then, we should make sure to sanitize all user input appropriately. Input that passes through ContentValues
should be fine. So only issues are those that pass in via concating.
In here, the only concat created argument is for id. It is cast to an int, and will error out otherwise.
*/
int uriType = uriMatcher.match(uri);
SQLiteDatabase sqlDB = dbOpenHelper.getWritableDatabase();
int rowsUpdated = 0;
switch (uriType) {
case CAMPAIGNS:
rowsUpdated = sqlDB.update(Campaign.Table.TABLE_NAME,
contentValues,
selection,
selectionArgs);
break;
case CAMPAIGNS_ID:
int id = Integer.valueOf(uri.getLastPathSegment());
if (TextUtils.isEmpty(selection)) {
rowsUpdated = sqlDB.update(Campaign.Table.TABLE_NAME,
contentValues,
Campaign.Table.COLUMN_ID + " = ?",
new String[] { String.valueOf(id) } );
} else {
throw new IllegalArgumentException("Parameter `selection` should be empty when updating an ID");
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri + " with type " + uriType);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsUpdated;
}
}

View file

@ -0,0 +1,38 @@
package fr.free.nrw.commons.campaigns;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import fr.free.nrw.commons.Utils;
class CampaignsListAdapter extends CursorAdapter {
private DisplayImageOptions contributionDisplayOptions = Utils.getGenericDisplayOptions().build();;
private Activity activity;
public CampaignsListAdapter(Activity activity, Cursor c, int flags) {
super(activity, c, flags);
this.activity = activity;
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
View parent = activity.getLayoutInflater().inflate(android.R.layout.simple_list_item_1, viewGroup, false);
return parent;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView campaignName = (TextView)view.findViewById(android.R.id.text1);
Campaign campaign = Campaign.fromCursor(cursor);
campaignName.setText(campaign.getTitle());
}
}

View file

@ -0,0 +1,90 @@
package fr.free.nrw.commons.campaigns;
import android.accounts.Account;
import android.content.*;
import android.os.Bundle;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import org.mediawiki.api.ApiResult;
import org.mediawiki.api.MWApi;
import fr.free.nrw.commons.CommonsApplication;
import java.io.IOException;
import java.util.ArrayList;
public class CampaignsSyncAdapter extends AbstractThreadedSyncAdapter {
private static int COMMIT_THRESHOLD = 10;
public CampaignsSyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
}
private int getLimit() {
return 500; // FIXME: Parameterize!
}
@Override
public void onPerformSync(Account account, Bundle bundle, String s, ContentProviderClient contentProviderClient, SyncResult syncResult) {
// This code is fraught with possibilities of race conditions, but lalalalala I can't hear you!
String user = account.name;
MWApi api = CommonsApplication.createMWApi();
ApiResult result;
Boolean done = false;
String queryContinue = null;
while(!done) {
try {
MWApi.RequestBuilder builder = api.action("query")
.param("list", "allcampaigns")
// Disabled, since we want to modify local state if the campaign was disabled
// FIXME: To be more effecient, delete the disabled campaigns locally
//.param("ucenabledonly", "true")
.param("uclimit", getLimit());
if(!TextUtils.isEmpty(queryContinue)) {
builder.param("uccontinue", queryContinue);
}
result = builder.get();
} catch (IOException e) {
// There isn't really much we can do, eh?
// FIXME: Perhaps add EventLogging?
syncResult.stats.numIoExceptions += 1; // Not sure if this does anything. Shitty docs
Log.d("Commons", "Syncing failed due to " + e.toString());
return;
}
ArrayList<ApiResult> campaigns = result.getNodes("/api/query/allcampaigns/campaign");
Log.d("Commons", campaigns.size() + " results!");
ArrayList<ContentValues> campaignValues = new ArrayList<ContentValues>();
for(ApiResult campaignItem: campaigns) {
String name = campaignItem.getString("@name");
String body = campaignItem.getString(".");
Log.d("Commons", "Campaign body is " + body);
String trackingCat = campaignItem.getString("@trackingCategory");
Campaign campaign = Campaign.parse(name, body, trackingCat);
campaignValues.add(campaign.toContentValues());
if(campaignValues.size() % COMMIT_THRESHOLD == 0) {
try {
contentProviderClient.bulkInsert(CampaignsContentProvider.BASE_URI, campaignValues.toArray(new ContentValues[]{}));
} catch (RemoteException e) {
throw new RuntimeException(e);
}
campaignValues.clear();
}
}
if(campaignValues.size() != 0) {
try {
contentProviderClient.bulkInsert(CampaignsContentProvider.BASE_URI, campaignValues.toArray(new ContentValues[]{}));
} catch (RemoteException e) {
throw new RuntimeException(e);
}
}
queryContinue = result.getString("/api/query-continue/allcampaigns/@uccontinue");
if(TextUtils.isEmpty(queryContinue)) {
done = true;
}
}
}
}

View file

@ -0,0 +1,26 @@
package fr.free.nrw.commons.campaigns;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class CampaignsSyncService extends Service {
private static final Object sSyncAdapterLock = new Object();
private static CampaignsSyncAdapter sSyncAdapter = null;
@Override
public void onCreate() {
synchronized (sSyncAdapterLock) {
if (sSyncAdapter == null) {
sSyncAdapter = new CampaignsSyncAdapter(getApplicationContext(), true);
}
}
}
@Override
public IBinder onBind(Intent intent) {
return sSyncAdapter.getSyncAdapterBinder();
}
}

View file

@ -26,7 +26,7 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.concurrent.ScheduledThreadPoolExecutor;
public class CategorizationFragment extends SherlockFragment {
public class CategorizationFragment extends SherlockFragment{
public static interface OnCategoriesSaveHandler {
public void onCategoriesSave(ArrayList<String> categories);
}
@ -86,7 +86,6 @@ public class CategorizationFragment extends SherlockFragment {
private class CategoriesUpdater extends AsyncTask<Void, Void, ArrayList<String>> {
private String filter;
@Override
protected void onPreExecute() {
super.onPreExecute();
@ -102,14 +101,14 @@ public class CategorizationFragment extends SherlockFragment {
super.onPostExecute(categories);
ArrayList<CategoryItem> items = new ArrayList<CategoryItem>();
HashSet<String> existingKeys = new HashSet<String>();
for (CategoryItem item : categoriesAdapter.getItems()) {
if (item.selected) {
for(CategoryItem item : categoriesAdapter.getItems()) {
if(item.selected) {
items.add(item);
existingKeys.add(item.name);
}
}
for (String category : categories) {
if (!existingKeys.contains(category)) {
for(String category : categories) {
if(!existingKeys.contains(category)) {
items.add(new CategoryItem(category, false));
}
}
@ -117,7 +116,7 @@ public class CategorizationFragment extends SherlockFragment {
categoriesAdapter.notifyDataSetInvalidated();
categoriesSearchInProgress.setVisibility(View.GONE);
if (categories.size() == 0) {
if (TextUtils.isEmpty(filter)) {
if(TextUtils.isEmpty(filter)) {
// If we found no recent cats, show the skip message!
categoriesSkip.setVisibility(View.VISIBLE);
} else {
@ -131,7 +130,7 @@ public class CategorizationFragment extends SherlockFragment {
@Override
protected ArrayList<String> doInBackground(Void... voids) {
if (TextUtils.isEmpty(filter)) {
if(TextUtils.isEmpty(filter)) {
ArrayList<String> items = new ArrayList<String>();
try {
Cursor cursor = client.query(
@ -151,7 +150,7 @@ public class CategorizationFragment extends SherlockFragment {
}
return items;
}
if (categoriesCache.containsKey(filter)) {
if(categoriesCache.containsKey(filter)) {
return categoriesCache.get(filter);
}
MWApi api = CommonsApplication.createMWApi();
@ -168,7 +167,7 @@ public class CategorizationFragment extends SherlockFragment {
}
ArrayList<ApiResult> categoryNodes = result.getNodes("/api/query/allcategories/c");
for (ApiResult categoryNode : categoryNodes) {
for(ApiResult categoryNode: categoryNodes) {
categories.add(categoryNode.getDocument().getTextContent());
}
@ -211,7 +210,7 @@ public class CategorizationFragment extends SherlockFragment {
public View getView(int i, View view, ViewGroup viewGroup) {
CheckedTextView checkedView;
if (view == null) {
if(view == null) {
checkedView = (CheckedTextView) getSherlockActivity().getLayoutInflater().inflate(R.layout.layout_categories_item, null);
} else {
@ -229,8 +228,8 @@ public class CategorizationFragment extends SherlockFragment {
public int getCurrentSelectedCount() {
int count = 0;
for (CategoryItem item : categoriesAdapter.getItems()) {
if (item.selected) {
for(CategoryItem item: categoriesAdapter.getItems()) {
if(item.selected) {
count++;
}
}
@ -243,7 +242,7 @@ public class CategorizationFragment extends SherlockFragment {
CategoryContentProvider.BASE_URI,
Category.Table.ALL_FIELDS,
Category.Table.COLUMN_NAME + "=?",
new String[]{name},
new String[] {name},
null);
if (cursor.moveToFirst()) {
Category cat = Category.fromCursor(cursor);
@ -303,7 +302,7 @@ public class CategorizationFragment extends SherlockFragment {
});
ArrayList<CategoryItem> items;
if (savedInstanceState == null) {
if(savedInstanceState == null) {
items = new ArrayList<CategoryItem>();
categoriesCache = new HashMap<String, ArrayList<String>>();
} else {
@ -381,11 +380,11 @@ public class CategorizationFragment extends SherlockFragment {
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
switch(menuItem.getItemId()) {
case R.id.menu_save_categories:
ArrayList<String> selectedCategories = new ArrayList<String>();
for (CategoryItem item : categoriesAdapter.getItems()) {
if (item.selected) {
for(CategoryItem item: categoriesAdapter.getItems()) {
if(item.selected) {
selectedCategories.add(item.name);
}
}

View file

@ -28,12 +28,12 @@ public class Category {
public Date getLastUsed() {
// warning: Date objects are mutable.
return (Date) lastUsed.clone();
return (Date)lastUsed.clone();
}
public void setLastUsed(Date lastUsed) {
// warning: Date objects are mutable.
this.lastUsed = (Date) lastUsed.clone();
this.lastUsed = (Date)lastUsed.clone();
}
public void touch() {
@ -60,12 +60,12 @@ public class Category {
public void save() {
try {
if (contentUri == null) {
if(contentUri == null) {
contentUri = client.insert(CategoryContentProvider.BASE_URI, this.toContentValues());
} else {
client.update(contentUri, toContentValues(), null, null);
}
} catch (RemoteException e) {
} catch(RemoteException e) {
throw new RuntimeException(e);
}
}
@ -118,23 +118,23 @@ public class Category {
}
public static void onUpdate(SQLiteDatabase db, int from, int to) {
if (from == to) {
if(from == to) {
return;
}
if (from < 4) {
if(from < 4) {
// doesn't exist yet
from++;
onUpdate(db, from, to);
return;
}
if (from == 4) {
if(from == 4) {
// table added in version 5
onCreate(db);
from++;
onUpdate(db, from, to);
return;
}
if (from == 5) {
if(from == 5) {
from++;
onUpdate(db, from, to);
return;

View file

@ -24,7 +24,6 @@ public class CategoryContentProvider extends ContentProvider {
public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);
private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
uriMatcher.addURI(AUTHORITY, BASE_PATH, CATEGORIES);
uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", CATEGORIES_ID);
@ -36,10 +35,9 @@ public class CategoryContentProvider extends ContentProvider {
}
private DBOpenHelper dbOpenHelper;
@Override
public boolean onCreate() {
dbOpenHelper = ((CommonsApplication) this.getContext().getApplicationContext()).getDbOpenHelper();
dbOpenHelper = ((CommonsApplication)this.getContext().getApplicationContext()).getDbOpenHelper();
return false;
}
@ -53,7 +51,7 @@ public class CategoryContentProvider extends ContentProvider {
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
Cursor cursor;
switch (uriType) {
switch(uriType) {
case CATEGORIES:
cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
break;
@ -61,7 +59,7 @@ public class CategoryContentProvider extends ContentProvider {
cursor = queryBuilder.query(db,
Category.Table.ALL_FIELDS,
"_id = ?",
new String[]{uri.getLastPathSegment()},
new String[] { uri.getLastPathSegment() },
null,
null,
sortOrder
@ -110,7 +108,7 @@ public class CategoryContentProvider extends ContentProvider {
sqlDB.beginTransaction();
switch (uriType) {
case CATEGORIES:
for (ContentValues value : values) {
for(ContentValues value: values) {
Log.d("Commons", "Inserting! " + value.toString());
sqlDB.insert(Category.Table.TABLE_NAME, null, value);
}
@ -144,7 +142,7 @@ public class CategoryContentProvider extends ContentProvider {
rowsUpdated = sqlDB.update(Category.Table.TABLE_NAME,
contentValues,
Category.Table.COLUMN_ID + " = ?",
new String[]{String.valueOf(id)});
new String[] { String.valueOf(id) } );
} else {
throw new IllegalArgumentException("Parameter `selection` should be empty when updating an ID");
}

View file

@ -68,7 +68,7 @@ public class Contribution extends Media {
public Contribution(Parcel in) {
super(in);
contentUri = (Uri) in.readParcelable(Uri.class.getClassLoader());
contentUri = (Uri)in.readParcelable(Uri.class.getClassLoader());
source = in.readString();
timestamp = (Date) in.readSerializable();
state = in.readInt();
@ -125,21 +125,21 @@ public class Contribution extends Media {
StringBuffer buffer = new StringBuffer();
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd");
buffer
.append("== {{int:filedesc}} ==\n")
.append("== {{int:filedesc}} ==\n")
.append("{{Information\n")
.append("|description=").append(getDescription()).append("\n")
.append("|source=").append("{{own}}\n")
.append("|author=[[User:").append(creator).append("|").append(creator).append("]]\n");
if (dateCreated != null) {
.append("|description=").append(getDescription()).append("\n")
.append("|source=").append("{{own}}\n")
.append("|author=[[User:").append(creator).append("|").append(creator).append("]]\n");
if(dateCreated != null) {
buffer
.append("|date={{According to EXIF data|").append(isoFormat.format(dateCreated)).append("}}\n");
}
buffer
.append("}}").append("\n")
.append("== {{int:license-header}} ==\n")
.append("== {{int:license-header}} ==\n")
.append(Utils.licenseTemplateFor(getLicense())).append("\n\n")
.append("{{Uploaded from Mobile|platform=Android|version=").append(CommonsApplication.APPLICATION_VERSION).append("}}\n")
.append(getTrackingTemplates());
.append("{{Uploaded from Mobile|platform=Android|version=").append(CommonsApplication.APPLICATION_VERSION).append("}}\n")
.append(getTrackingTemplates());
return buffer.toString();
}
@ -149,19 +149,19 @@ public class Contribution extends Media {
public void save() {
try {
if (contentUri == null) {
if(contentUri == null) {
contentUri = client.insert(ContributionsContentProvider.BASE_URI, this.toContentValues());
} else {
client.update(contentUri, toContentValues(), null, null);
}
} catch (RemoteException e) {
} catch(RemoteException e) {
throw new RuntimeException(e);
}
}
public void delete() {
try {
if (contentUri == null) {
if(contentUri == null) {
// noooo
throw new RuntimeException("tried to delete item with no content URI");
} else {
@ -176,20 +176,20 @@ public class Contribution extends Media {
public ContentValues toContentValues() {
ContentValues cv = new ContentValues();
cv.put(Table.COLUMN_FILENAME, getFilename());
if (getLocalUri() != null) {
if(getLocalUri() != null) {
cv.put(Table.COLUMN_LOCAL_URI, getLocalUri().toString());
}
if (getImageUrl() != null) {
if(getImageUrl() != null) {
cv.put(Table.COLUMN_IMAGE_URL, getImageUrl().toString());
}
if (getDateUploaded() != null) {
if(getDateUploaded() != null) {
cv.put(Table.COLUMN_UPLOADED, getDateUploaded().getTime());
}
cv.put(Table.COLUMN_LENGTH, getDataLength());
cv.put(Table.COLUMN_TIMESTAMP, getTimestamp().getTime());
cv.put(Table.COLUMN_STATE, getState());
cv.put(Table.COLUMN_TRANSFERRED, transferred);
cv.put(Table.COLUMN_SOURCE, source);
cv.put(Table.COLUMN_SOURCE, source);
cv.put(Table.COLUMN_DESCRIPTION, description);
cv.put(Table.COLUMN_CREATOR, creator);
cv.put(Table.COLUMN_MULTIPLE, isMultiple ? 1 : 0);
@ -222,7 +222,7 @@ public class Contribution extends Media {
c.timestamp = cursor.getLong(4) == 0 ? null : new Date(cursor.getLong(4));
c.state = cursor.getInt(5);
c.dataLength = cursor.getLong(6);
c.dateUploaded = cursor.getLong(7) == 0 ? null : new Date(cursor.getLong(7));
c.dateUploaded = cursor.getLong(7) == 0 ? null : new Date(cursor.getLong(7));
c.transferred = cursor.getLong(8);
c.source = cursor.getString(9);
c.description = cursor.getString(10);
@ -306,7 +306,7 @@ public class Contribution extends Media {
+ "width INTEGER,"
+ "height INTEGER,"
+ "LICENSE STRING"
+ ");";
+ ");";
public static void onCreate(SQLiteDatabase db) {
@ -314,36 +314,36 @@ public class Contribution extends Media {
}
public static void onUpdate(SQLiteDatabase db, int from, int to) {
if (from == to) {
if(from == to) {
return;
}
if (from == 1) {
if(from == 1) {
db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN description STRING;");
db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN creator STRING;");
from++;
onUpdate(db, from, to);
return;
}
if (from == 2) {
if(from == 2) {
db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN multiple INTEGER;");
db.execSQL("UPDATE " + TABLE_NAME + " SET multiple = 0");
from++;
onUpdate(db, from, to);
return;
}
if (from == 3) {
if(from == 3) {
// Do nothing
from++;
onUpdate(db, from, to);
return;
}
if (from == 4) {
if(from == 4) {
// Do nothing -- added Category
from++;
onUpdate(db, from, to);
return;
}
if (from == 5) {
if(from == 5) {
// Added width and height fields
db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN width INTEGER;");
db.execSQL("UPDATE " + TABLE_NAME + " SET width = 0");

View file

@ -10,7 +10,7 @@ import android.util.Log;
import com.actionbarsherlock.app.SherlockFragment;
import fr.free.nrw.commons.upload.ShareActivity;
import fr.free.nrw.commons.upload.UploadService;
import fr.free.nrw.commons.campaigns.Campaign;
import java.io.File;
import java.io.IOException;
@ -19,15 +19,15 @@ import java.util.Date;
public class ContributionController {
private SherlockFragment fragment;
private Activity activity;
private Campaign campaign;
private final static int SELECT_FROM_GALLERY = 1;
private final static int SELECT_FROM_CAMERA = 2;
public ContributionController(SherlockFragment fragment) {
public ContributionController(SherlockFragment fragment, Campaign campaign) {
this.fragment = fragment;
this.activity = fragment.getActivity();
this.campaign = campaign;
}
// See http://stackoverflow.com/a/5054673/17865 for why this is done
@ -35,12 +35,12 @@ public class ContributionController {
private Uri reGenerateImageCaptureURI() {
String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
if(storageState.equals(Environment.MEDIA_MOUNTED)) {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Commons/images/" + new Date().getTime() + ".jpg";
File _photoFile = new File(path);
try {
if (_photoFile.exists() == false) {
if(_photoFile.exists() == false) {
_photoFile.getParentFile().mkdirs();
_photoFile.createNewFile();
}
@ -50,7 +50,7 @@ public class ContributionController {
}
return Uri.fromFile(_photoFile);
} else {
} else {
throw new RuntimeException("No external storage found!");
}
}
@ -71,7 +71,8 @@ public class ContributionController {
public void handleImagePicked(int requestCode, Intent data) {
Intent shareIntent = new Intent(activity, ShareActivity.class);
shareIntent.setAction(Intent.ACTION_SEND);
switch (requestCode) {
shareIntent.putExtra(UploadService.EXTRA_CAMPAIGN, campaign);
switch(requestCode) {
case SELECT_FROM_GALLERY:
shareIntent.setType(activity.getContentResolver().getType(data.getData()));
shareIntent.putExtra(Intent.EXTRA_STREAM, data.getData());
@ -88,11 +89,13 @@ public class ContributionController {
public void saveState(Bundle outState) {
outState.putParcelable("lastGeneratedCaptureURI", lastGeneratedCaptureURI);
outState.putSerializable("campaign", campaign);
}
public void loadState(Bundle savedInstanceState) {
if (savedInstanceState != null) {
if(savedInstanceState != null) {
lastGeneratedCaptureURI = (Uri) savedInstanceState.getParcelable("lastGeneratedCaptureURI");
campaign = (Campaign) savedInstanceState.getSerializable("campaign");
}
}

View file

@ -17,9 +17,9 @@ class ContributionViewHolder {
ContributionViewHolder(View parent) {
imageView = (MediaWikiImageView) parent.findViewById(R.id.contributionImage);
titleView = (TextView) parent.findViewById(R.id.contributionTitle);
stateView = (TextView) parent.findViewById(R.id.contributionState);
seqNumView = (TextView) parent.findViewById(R.id.contributionSequenceNumber);
progressView = (ProgressBar) parent.findViewById(R.id.contributionProgress);
titleView = (TextView)parent.findViewById(R.id.contributionTitle);
stateView = (TextView)parent.findViewById(R.id.contributionState);
seqNumView = (TextView)parent.findViewById(R.id.contributionSequenceNumber);
progressView = (ProgressBar)parent.findViewById(R.id.contributionProgress);
}
}

View file

@ -22,18 +22,20 @@ import fr.free.nrw.commons.auth.*;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.HandlerService;
import fr.free.nrw.commons.Media;
import fr.free.nrw.commons.campaigns.Campaign;
import fr.free.nrw.commons.media.*;
import fr.free.nrw.commons.upload.UploadService;
import java.util.ArrayList;
public class ContributionsActivity
extends AuthenticatedActivity
implements LoaderManager.LoaderCallbacks<Object>,
AdapterView.OnItemClickListener,
MediaDetailPagerFragment.MediaDetailProvider,
FragmentManager.OnBackStackChangedListener,
ContributionsListFragment.SourceRefresher {
public class ContributionsActivity
extends AuthenticatedActivity
implements LoaderManager.LoaderCallbacks<Object>,
AdapterView.OnItemClickListener,
MediaDetailPagerFragment.MediaDetailProvider,
ContributionsListFragment.CurrentCampaignProvider,
FragmentManager.OnBackStackChangedListener,
ContributionsListFragment.SourceRefresher {
private Cursor allContributions;
@ -41,6 +43,7 @@ public class ContributionsActivity
private MediaDetailPagerFragment mediaDetails;
private ArrayList<DataSetObserver> observersWaitingForLoad = new ArrayList<DataSetObserver>();
private Campaign campaign;
public ContributionsActivity() {
super(WikiAccountAuthenticator.COMMONS_ACCOUNT_TYPE);
@ -50,7 +53,7 @@ public class ContributionsActivity
private boolean isUploadServiceConnected;
private ServiceConnection uploadServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName componentName, IBinder binder) {
uploadService = (UploadService) ((HandlerService.HandlerServiceLocalBinder) binder).getService();
uploadService = (UploadService) ((HandlerService.HandlerServiceLocalBinder)binder).getService();
isUploadServiceConnected = true;
}
@ -61,10 +64,11 @@ public class ContributionsActivity
};
@Override
protected void onDestroy() {
super.onDestroy();
if (isUploadServiceConnected) {
if(isUploadServiceConnected) {
unbindService(uploadServiceConnection);
}
}
@ -111,11 +115,16 @@ public class ContributionsActivity
setTitle(R.string.title_activity_contributions);
setContentView(R.layout.activity_contributions);
contributionsList = (ContributionsListFragment) getSupportFragmentManager().findFragmentById(R.id.contributionsListFragment);
if(getIntent().hasExtra("campaign")) {
this.campaign = (Campaign) getIntent().getSerializableExtra("campaign");
this.setTitle(campaign.getTitle());
}
contributionsList = (ContributionsListFragment)getSupportFragmentManager().findFragmentById(R.id.contributionsListFragment);
getSupportFragmentManager().addOnBackStackChangedListener(this);
if (savedInstanceState != null) {
mediaDetails = (MediaDetailPagerFragment) getSupportFragmentManager().findFragmentById(R.id.contributionsFragmentContainer);
mediaDetails = (MediaDetailPagerFragment)getSupportFragmentManager().findFragmentById(R.id.contributionsFragmentContainer);
// onBackStackChanged uses mediaDetails.isVisible() but this returns false now.
// Use the saved value from before pause or orientation change.
if (mediaDetails != null && savedInstanceState.getBoolean("mediaDetailsVisible")) {
@ -134,7 +143,7 @@ public class ContributionsActivity
}
private void showDetail(int i) {
if (mediaDetails == null || !mediaDetails.isVisible()) {
if(mediaDetails == null ||!mediaDetails.isVisible()) {
mediaDetails = new MediaDetailPagerFragment();
this.getSupportFragmentManager()
.beginTransaction()
@ -149,7 +158,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);
Log.d("Commons", "Restarting for" + c.toContentValues().toString());
} else {
@ -160,7 +169,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) {
Log.d("Commons", "Deleting failed contrib " + c.toContentValues().toString());
c.setContentProviderClient(getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY));
c.delete();
@ -171,9 +180,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;
@ -199,42 +208,54 @@ public class ContributionsActivity
}
public Loader onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this, ContributionsContentProvider.BASE_URI, Contribution.Table.ALL_FIELDS, CONTRIBUTION_SELECTION, null, CONTRIBUTION_SORT);
if(campaign == null) {
return new CursorLoader(this, ContributionsContentProvider.BASE_URI, Contribution.Table.ALL_FIELDS, CONTRIBUTION_SELECTION, null, CONTRIBUTION_SORT);
} else {
return new CategoryImagesLoader(this, campaign.getTrackingCategory());
}
}
public void onLoadFinished(Loader cursorLoader, Object result) {
if(campaign == null) {
Cursor cursor = (Cursor) result;
if(contributionsList.getAdapter() == null) {
contributionsList.setAdapter(new ContributionsListAdapter(this, cursor, 0));
} else {
((CursorAdapter)contributionsList.getAdapter()).swapCursor(cursor);
}
Cursor cursor = (Cursor) result;
if (contributionsList.getAdapter() == null) {
contributionsList.setAdapter(new ContributionsListAdapter(this, cursor, 0));
getSupportActionBar().setSubtitle(getResources().getQuantityString(R.plurals.contributions_subtitle, cursor.getCount(), cursor.getCount()));
} else {
((CursorAdapter) contributionsList.getAdapter()).swapCursor(cursor);
if(contributionsList.getAdapter() == null) {
contributionsList.setAdapter(new MediaListAdapter(this, (ArrayList<Media>) result));
} else {
((MediaListAdapter)contributionsList.getAdapter()).updateMediaList((ArrayList<Media>) result);
}
}
getSupportActionBar().setSubtitle(getResources().getQuantityString(R.plurals.contributions_subtitle, cursor.getCount(), cursor.getCount()));
notifyAndMigrateDataSetObservers();
}
public void onLoaderReset(Loader cursorLoader) {
((CursorAdapter) contributionsList.getAdapter()).swapCursor(null);
if(campaign == null) {
((CursorAdapter) contributionsList.getAdapter()).swapCursor(null);
} else {
contributionsList.setAdapter(null);
}
}
public Media getMediaAtPosition(int i) {
if (contributionsList.getAdapter() == null) {
// not yet ready to return data
return null;
} else {
} else if(campaign == null) {
return Contribution.fromCursor((Cursor) contributionsList.getAdapter().getItem(i));
} else {
return (Media) contributionsList.getAdapter().getItem(i);
}
}
public int getTotalMediaCount() {
if (contributionsList.getAdapter() == null) {
if(contributionsList.getAdapter() == null) {
return 0;
}
return contributionsList.getAdapter().getCount();
@ -278,13 +299,16 @@ public class ContributionsActivity
}
public void onBackStackChanged() {
if (mediaDetails != null && mediaDetails.isVisible()) {
if(mediaDetails != null && mediaDetails.isVisible()) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
}
public Campaign getCurrentCampaign() {
return campaign;
}
public void refreshSource() {
getSupportLoaderManager().restartLoader(0, null, this);

View file

@ -10,7 +10,7 @@ import android.util.*;
import fr.free.nrw.commons.data.*;
import fr.free.nrw.commons.CommonsApplication;
public class ContributionsContentProvider extends ContentProvider {
public class ContributionsContentProvider extends ContentProvider{
private static final int CONTRIBUTIONS = 1;
private static final int CONTRIBUTIONS_ID = 2;
@ -21,7 +21,6 @@ public class ContributionsContentProvider extends ContentProvider {
public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);
private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
uriMatcher.addURI(AUTHORITY, BASE_PATH, CONTRIBUTIONS);
uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", CONTRIBUTIONS_ID);
@ -33,10 +32,9 @@ public class ContributionsContentProvider extends ContentProvider {
}
private DBOpenHelper dbOpenHelper;
@Override
public boolean onCreate() {
dbOpenHelper = ((CommonsApplication) this.getContext().getApplicationContext()).getDbOpenHelper();
dbOpenHelper = ((CommonsApplication)this.getContext().getApplicationContext()).getDbOpenHelper();
return false;
}
@ -50,7 +48,7 @@ public class ContributionsContentProvider extends ContentProvider {
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
Cursor cursor;
switch (uriType) {
switch(uriType) {
case CONTRIBUTIONS:
cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
break;
@ -58,7 +56,7 @@ public class ContributionsContentProvider extends ContentProvider {
cursor = queryBuilder.query(db,
Contribution.Table.ALL_FIELDS,
"_id = ?",
new String[]{uri.getLastPathSegment()},
new String[] { uri.getLastPathSegment() },
null,
null,
sortOrder
@ -101,12 +99,12 @@ public class ContributionsContentProvider extends ContentProvider {
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
switch (uriType) {
switch(uriType) {
case CONTRIBUTIONS_ID:
Log.d("Commons", "Deleting contribution id " + uri.getLastPathSegment());
rows = db.delete(Contribution.Table.TABLE_NAME,
"_id = ?",
new String[]{uri.getLastPathSegment()}
new String[] { uri.getLastPathSegment() }
);
break;
default:
@ -124,7 +122,7 @@ public class ContributionsContentProvider extends ContentProvider {
sqlDB.beginTransaction();
switch (uriType) {
case CONTRIBUTIONS:
for (ContentValues value : values) {
for(ContentValues value: values) {
Log.d("Commons", "Inserting! " + value.toString());
sqlDB.insert(Contribution.Table.TABLE_NAME, null, value);
}
@ -164,7 +162,7 @@ public class ContributionsContentProvider extends ContentProvider {
rowsUpdated = sqlDB.update(Contribution.Table.TABLE_NAME,
contentValues,
Contribution.Table.COLUMN_ID + " = ?",
new String[]{String.valueOf(id)});
new String[] { String.valueOf(id) } );
} else {
throw new IllegalArgumentException("Parameter `selection` should be empty when updating an ID");
}

View file

@ -20,9 +20,13 @@ import fr.free.nrw.commons.R;
import fr.free.nrw.commons.AboutActivity;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.SettingsActivity;
import fr.free.nrw.commons.campaigns.Campaign;
public class ContributionsListFragment extends SherlockFragment {
public interface CurrentCampaignProvider {
Campaign getCurrentCampaign();
}
public interface SourceRefresher {
void refreshSource();
@ -31,7 +35,7 @@ public class ContributionsListFragment extends SherlockFragment {
private GridView contributionsList;
private TextView waitingMessage;
private TextView emptyMessage;
private Campaign campaign;
private ContributionController controller;
@ -58,7 +62,7 @@ public class ContributionsListFragment extends SherlockFragment {
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if(resultCode == Activity.RESULT_OK) {
controller.handleImagePicked(requestCode, data);
}
}
@ -66,7 +70,7 @@ public class ContributionsListFragment extends SherlockFragment {
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
switch(item.getItemId()) {
case R.id.menu_from_gallery:
controller.startGalleryPick();
return true;
@ -78,18 +82,18 @@ public class ContributionsListFragment extends SherlockFragment {
startActivity(settingsIntent);
return true;
case R.id.menu_about:
Intent aboutIntent = new Intent(getActivity(), AboutActivity.class);
Intent aboutIntent = new Intent(getActivity(), AboutActivity.class);
startActivity(aboutIntent);
return true;
case R.id.menu_feedback:
Intent feedbackIntent = new Intent(Intent.ACTION_SEND);
feedbackIntent.setType("message/rfc822");
feedbackIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{CommonsApplication.FEEDBACK_EMAIL});
feedbackIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { CommonsApplication.FEEDBACK_EMAIL });
feedbackIntent.putExtra(Intent.EXTRA_SUBJECT, String.format(CommonsApplication.FEEDBACK_EMAIL_SUBJECT, CommonsApplication.APPLICATION_VERSION));
startActivity(feedbackIntent);
return true;
case R.id.menu_refresh:
((SourceRefresher) getActivity()).refreshSource();
((SourceRefresher)getActivity()).refreshSource();
return true;
default:
return super.onOptionsItemSelected(item);
@ -101,13 +105,13 @@ public class ContributionsListFragment extends SherlockFragment {
menu.clear(); // See http://stackoverflow.com/a/8495697/17865
inflater.inflate(R.menu.fragment_contributions_list, menu);
CommonsApplication app = (CommonsApplication) getActivity().getApplicationContext();
CommonsApplication app = (CommonsApplication)getActivity().getApplicationContext();
if (!app.deviceHasCamera()) {
menu.findItem(R.id.menu_from_camera).setEnabled(false);
}
menu.findItem(R.id.menu_refresh).setVisible(false);
if(campaign == null) {
menu.findItem(R.id.menu_refresh).setVisible(false);
}
}
@Override
@ -125,16 +129,16 @@ public class ContributionsListFragment extends SherlockFragment {
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
controller = new ContributionController(this);
campaign = ((CurrentCampaignProvider)getActivity()).getCurrentCampaign();
controller = new ContributionController(this, campaign);
controller.loadState(savedInstanceState);
contributionsList = (GridView) getView().findViewById(R.id.contributionsList);
waitingMessage = (TextView) getView().findViewById(R.id.waitingMessage);
emptyMessage = (TextView) getView().findViewById(R.id.waitingMessage);
contributionsList = (GridView)getView().findViewById(R.id.contributionsList);
waitingMessage = (TextView)getView().findViewById(R.id.waitingMessage);
emptyMessage = (TextView)getView().findViewById(R.id.waitingMessage);
contributionsList.setOnItemClickListener((AdapterView.OnItemClickListener) getActivity());
if (savedInstanceState != null) {
contributionsList.setOnItemClickListener((AdapterView.OnItemClickListener)getActivity());
if(savedInstanceState != null) {
Log.d("Commons", "Scrolling to " + savedInstanceState.getInt("grid-position"));
contributionsList.setSelection(savedInstanceState.getInt("grid-position"));
}

View file

@ -18,7 +18,6 @@ import fr.free.nrw.commons.Utils;
public class ContributionsSyncAdapter extends AbstractThreadedSyncAdapter {
private static int COMMIT_THRESHOLD = 10;
public ContributionsSyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
}
@ -27,16 +26,15 @@ public class ContributionsSyncAdapter extends AbstractThreadedSyncAdapter {
return 500; // FIXME: Parameterize!
}
private static final String[] existsQuery = {Contribution.Table.COLUMN_FILENAME};
private static final String[] existsQuery = { Contribution.Table.COLUMN_FILENAME };
private static final String existsSelection = Contribution.Table.COLUMN_FILENAME + " = ?";
private boolean fileExists(ContentProviderClient client, String filename) {
Cursor cursor = null;
try {
cursor = client.query(ContributionsContentProvider.BASE_URI,
existsQuery,
existsSelection,
new String[]{filename},
new String[] { filename },
""
);
} catch (RemoteException e) {
@ -56,7 +54,7 @@ public class ContributionsSyncAdapter extends AbstractThreadedSyncAdapter {
ApiResult result;
Boolean done = false;
String queryContinue = null;
while (!done) {
while(!done) {
try {
MWApi.RequestBuilder builder = api.action("query")
@ -65,10 +63,10 @@ public class ContributionsSyncAdapter extends AbstractThreadedSyncAdapter {
.param("leprop", "title|timestamp")
.param("leuser", user)
.param("lelimit", getLimit());
if (!TextUtils.isEmpty(lastModified)) {
if(!TextUtils.isEmpty(lastModified)) {
builder.param("leend", lastModified);
}
if (!TextUtils.isEmpty(queryContinue)) {
if(!TextUtils.isEmpty(queryContinue)) {
builder.param("lestart", queryContinue);
}
result = builder.get();
@ -84,9 +82,9 @@ public class ContributionsSyncAdapter extends AbstractThreadedSyncAdapter {
ArrayList<ApiResult> uploads = result.getNodes("/api/query/logevents/item");
Log.d("Commons", uploads.size() + " results!");
ArrayList<ContentValues> imageValues = new ArrayList<ContentValues>();
for (ApiResult image : uploads) {
for(ApiResult image: uploads) {
String filename = image.getString("@title");
if (fileExists(contentProviderClient, filename)) {
if(fileExists(contentProviderClient, filename)) {
Log.d("Commons", "Skipping " + filename);
continue;
}
@ -96,7 +94,7 @@ public class ContributionsSyncAdapter extends AbstractThreadedSyncAdapter {
contrib.setState(Contribution.STATE_COMPLETED);
imageValues.add(contrib.toContentValues());
if (imageValues.size() % COMMIT_THRESHOLD == 0) {
if(imageValues.size() % COMMIT_THRESHOLD == 0) {
try {
contentProviderClient.bulkInsert(ContributionsContentProvider.BASE_URI, imageValues.toArray(new ContentValues[]{}));
} catch (RemoteException e) {
@ -106,7 +104,7 @@ public class ContributionsSyncAdapter extends AbstractThreadedSyncAdapter {
}
}
if (imageValues.size() != 0) {
if(imageValues.size() != 0) {
try {
contentProviderClient.bulkInsert(ContributionsContentProvider.BASE_URI, imageValues.toArray(new ContentValues[]{}));
} catch (RemoteException e) {
@ -114,7 +112,7 @@ public class ContributionsSyncAdapter extends AbstractThreadedSyncAdapter {
}
}
queryContinue = result.getString("/api/query-continue/logevents/@lestart");
if (TextUtils.isEmpty(queryContinue)) {
if(TextUtils.isEmpty(queryContinue)) {
done = true;
}
}

View file

@ -21,20 +21,19 @@ public class MediaListAdapter extends BaseAdapter {
public void updateMediaList(ArrayList<Media> newMediaList) {
// FIXME: Hack for now, replace with something more efficient later on
for (Media newMedia : newMediaList) {
for(Media newMedia: newMediaList) {
boolean isDuplicate = false;
for (Media oldMedia : mediaList) {
if (newMedia.getFilename().equals(oldMedia.getFilename())) {
for(Media oldMedia: mediaList ) {
if(newMedia.getFilename().equals(oldMedia.getFilename())) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
if(!isDuplicate) {
mediaList.add(0, newMedia);
}
}
}
public int getCount() {
return mediaList.size();
}
@ -48,14 +47,14 @@ public class MediaListAdapter extends BaseAdapter {
}
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
if(view == null) {
view = activity.getLayoutInflater().inflate(R.layout.layout_contribution, null, false);
view.setTag(new ContributionViewHolder(view));
}
Media m = (Media) getItem(i);
ContributionViewHolder holder = (ContributionViewHolder) view.getTag();
holder.imageView.setMedia(m, ((CommonsApplication) activity.getApplicationContext()).getImageLoader());
holder.imageView.setMedia(m, ((CommonsApplication)activity.getApplicationContext()).getImageLoader());
holder.titleView.setText(m.getDisplayTitle());
return view;
}

View file

@ -4,10 +4,11 @@ import android.content.*;
import android.database.sqlite.*;
import fr.free.nrw.commons.modifications.ModifierSequence;
import fr.free.nrw.commons.campaigns.Campaign;
import fr.free.nrw.commons.category.Category;
import fr.free.nrw.commons.contributions.*;
public class DBOpenHelper extends SQLiteOpenHelper {
public class DBOpenHelper extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "commons.db";
private static final int DATABASE_VERSION = 6;
@ -21,6 +22,7 @@ public class DBOpenHelper extends SQLiteOpenHelper {
Contribution.Table.onCreate(sqLiteDatabase);
ModifierSequence.Table.onCreate(sqLiteDatabase);
Category.Table.onCreate(sqLiteDatabase);
Campaign.Table.onCreate(sqLiteDatabase);
}
@Override
@ -28,5 +30,6 @@ public class DBOpenHelper extends SQLiteOpenHelper {
Contribution.Table.onUpdate(sqLiteDatabase, from, to);
ModifierSequence.Table.onUpdate(sqLiteDatabase, from, to);
Category.Table.onUpdate(sqLiteDatabase, from, to);
Campaign.Table.onUpdate(sqLiteDatabase, from, to);
}
}

View file

@ -12,7 +12,7 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CategoryImagesLoader extends AsyncTaskLoader<List<Media>> {
public class CategoryImagesLoader extends AsyncTaskLoader<List<Media>>{
private final CommonsApplication app;
private final String category;
@ -49,7 +49,7 @@ public class CategoryImagesLoader extends AsyncTaskLoader<List<Media>> {
Log.d("Commons", Utils.getStringFromDOM(result.getDocument()));
List<ApiResult> members = result.getNodes("/api/query/categorymembers/cm");
for (ApiResult member : members) {
for(ApiResult member : members) {
mediaList.add(new Media(member.getString("@title")));
}
return mediaList;

View file

@ -64,7 +64,7 @@ public class MediaDetailFragment extends SherlockFragment {
private ViewTreeObserver.OnGlobalLayoutListener layoutListener; // for layout stuff, only used once!
private ViewTreeObserver.OnScrollChangedListener scrollListener;
DataSetObserver dataObserver;
private AsyncTask<Void, Void, Boolean> detailFetchTask;
private AsyncTask<Void,Void,Boolean> detailFetchTask;
private LicenseList licenseList;
@ -84,9 +84,9 @@ public class MediaDetailFragment extends SherlockFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
detailProvider = (MediaDetailPagerFragment.MediaDetailProvider) getActivity();
detailProvider = (MediaDetailPagerFragment.MediaDetailProvider)getActivity();
if (savedInstanceState != null) {
if(savedInstanceState != null) {
editable = savedInstanceState.getBoolean("editable");
index = savedInstanceState.getInt("index");
initialListTop = savedInstanceState.getInt("listTop");
@ -169,9 +169,9 @@ public class MediaDetailFragment extends SherlockFragment {
private void displayMediaDetails(final Media media) {
String actualUrl = (media.getLocalUri() != null && !TextUtils.isEmpty(media.getLocalUri().toString())) ? media.getLocalUri().toString() : media.getThumbnailUrl(640);
if (actualUrl.startsWith("http")) {
ImageLoader loader = ((CommonsApplication) getActivity().getApplicationContext()).getImageLoader();
MediaWikiImageView mwImage = (MediaWikiImageView) image;
if(actualUrl.startsWith("http")) {
ImageLoader loader = ((CommonsApplication)getActivity().getApplicationContext()).getImageLoader();
MediaWikiImageView mwImage = (MediaWikiImageView)image;
mwImage.setLoadingView(loadingProgress); //FIXME: Set this as an attribute
mwImage.setMedia(media, loader);
Log.d("Volley", actualUrl);
@ -241,7 +241,7 @@ public class MediaDetailFragment extends SherlockFragment {
loadingProgress.setVisibility(View.GONE);
loadingFailed.setVisibility(View.GONE);
image.setVisibility(View.VISIBLE);
if (bitmap.hasAlpha()) {
if(bitmap.hasAlpha()) {
image.setBackgroundResource(android.R.color.white);
}
}
@ -276,7 +276,7 @@ public class MediaDetailFragment extends SherlockFragment {
}
if (scrollListener != null) {
getView().getViewTreeObserver().removeOnScrollChangedListener(scrollListener);
scrollListener = null;
scrollListener = null;
}
if (dataObserver != null) {
detailProvider.unregisterDataSetObserver(dataObserver);
@ -296,7 +296,7 @@ public class MediaDetailFragment extends SherlockFragment {
private View buildCatLabel(String cat) {
final String catName = cat;
final View item = getLayoutInflater(null).inflate(R.layout.detail_category_item, null, false);
final TextView textView = (TextView) item.findViewById(R.id.mediaDetailCategoryItemText);
final TextView textView = (TextView)item.findViewById(R.id.mediaDetailCategoryItemText);
textView.setText(cat);
if (categoriesLoaded && categoriesPresent) {
@ -317,7 +317,7 @@ public class MediaDetailFragment extends SherlockFragment {
// You must face the darkness alone
int scrollY = scrollView.getScrollY();
int scrollMax = getView().getHeight();
float scrollPercentage = (float) scrollY / (float) scrollMax;
float scrollPercentage = (float)scrollY / (float)scrollMax;
final float transparencyMax = 0.75f;
if (scrollPercentage > transparencyMax) {
scrollPercentage = transparencyMax;

View file

@ -42,16 +42,11 @@ public class MediaDetailPagerFragment extends SherlockFragment implements ViewPa
public interface MediaDetailProvider {
public Media getMediaAtPosition(int i);
public int getTotalMediaCount();
public void notifyDatasetChanged();
public void registerDataSetObserver(DataSetObserver observer);
public void unregisterDataSetObserver(DataSetObserver observer);
}
private class MediaDetailAdapter extends FragmentStatePagerAdapter {
public MediaDetailAdapter(FragmentManager fm) {
@ -60,7 +55,7 @@ public class MediaDetailPagerFragment extends SherlockFragment implements ViewPa
@Override
public Fragment getItem(int i) {
if (i == 0) {
if(i == 0) {
// See bug https://code.google.com/p/android/issues/detail?id=27526
pager.postDelayed(new Runnable() {
public void run() {
@ -73,7 +68,7 @@ public class MediaDetailPagerFragment extends SherlockFragment implements ViewPa
@Override
public int getCount() {
return ((MediaDetailProvider) getActivity()).getTotalMediaCount();
return ((MediaDetailProvider)getActivity()).getTotalMediaCount();
}
}
@ -90,7 +85,7 @@ public class MediaDetailPagerFragment extends SherlockFragment implements ViewPa
View view = inflater.inflate(R.layout.fragment_media_detail_pager, container, false);
pager = (ViewPager) view.findViewById(R.id.mediaDetailsPager);
pager.setOnPageChangeListener(this);
if (savedInstanceState != null) {
if(savedInstanceState != null) {
final int pageNumber = savedInstanceState.getInt("current-page");
// Adapter doesn't seem to be loading immediately.
// Dear God, please forgive us for our sins
@ -117,18 +112,18 @@ public class MediaDetailPagerFragment extends SherlockFragment implements ViewPa
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
if(savedInstanceState != null) {
editable = savedInstanceState.getBoolean("editable");
}
app = (CommonsApplication) getActivity().getApplicationContext();
app = (CommonsApplication)getActivity().getApplicationContext();
setHasOptionsMenu(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
MediaDetailProvider provider = (MediaDetailProvider) getSherlockActivity();
MediaDetailProvider provider = (MediaDetailProvider)getSherlockActivity();
Media m = provider.getMediaAtPosition(pager.getCurrentItem());
switch (item.getItemId()) {
switch(item.getItemId()) {
case R.id.menu_share_current_image:
EventLog.schema(CommonsApplication.EVENT_SHARE_ATTEMPT)
.param("username", app.getCurrentAccount().name)
@ -151,12 +146,12 @@ public class MediaDetailPagerFragment extends SherlockFragment implements ViewPa
return true;
case R.id.menu_retry_current_image:
// Is this... sane? :)
((ContributionsActivity) getActivity()).retryUpload(pager.getCurrentItem());
((ContributionsActivity)getActivity()).retryUpload(pager.getCurrentItem());
getSherlockActivity().getSupportFragmentManager().popBackStack();
return true;
case R.id.menu_cancel_current_image:
// todo: delete image
((ContributionsActivity) getActivity()).deleteUpload(pager.getCurrentItem());
((ContributionsActivity)getActivity()).deleteUpload(pager.getCurrentItem());
getSherlockActivity().getSupportFragmentManager().popBackStack();
return true;
default:
@ -172,7 +167,7 @@ public class MediaDetailPagerFragment extends SherlockFragment implements ViewPa
*/
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:", "");
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
@ -199,7 +194,7 @@ public class MediaDetailPagerFragment extends SherlockFragment implements ViewPa
}
}
final DownloadManager manager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
final DownloadManager manager = (DownloadManager)getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
final long downloadId = manager.enqueue(req);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
@ -209,8 +204,8 @@ public class MediaDetailPagerFragment extends SherlockFragment implements ViewPa
public void onReceive(Context context, Intent intent) {
// Check if the download has completed...
Cursor c = manager.query(new DownloadManager.Query()
.setFilterById(downloadId)
.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL | DownloadManager.STATUS_FAILED)
.setFilterById(downloadId)
.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL | DownloadManager.STATUS_FAILED)
);
if (c.moveToFirst()) {
int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
@ -234,13 +229,13 @@ public class MediaDetailPagerFragment extends SherlockFragment implements ViewPa
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (!editable) { // Disable menu options for editable views
if(!editable) { // Disable menu options for editable views
menu.clear(); // see http://stackoverflow.com/a/8495697/17865
inflater.inflate(R.menu.fragment_image_detail, menu);
if (pager != null) {
MediaDetailProvider provider = (MediaDetailProvider) getSherlockActivity();
if(pager != null) {
MediaDetailProvider provider = (MediaDetailProvider)getSherlockActivity();
Media m = provider.getMediaAtPosition(pager.getCurrentItem());
if (m != null) {
if(m != null) {
// Enable default set of actions, then re-enable different set of actions only if it is a failed contrib
menu.findItem(R.id.menu_retry_current_image).setEnabled(false).setVisible(false);
menu.findItem(R.id.menu_cancel_current_image).setEnabled(false).setVisible(false);
@ -248,9 +243,9 @@ public class MediaDetailPagerFragment extends SherlockFragment implements ViewPa
menu.findItem(R.id.menu_share_current_image).setEnabled(true).setVisible(true);
menu.findItem(R.id.menu_download_current_image).setEnabled(true).setVisible(true);
if (m instanceof Contribution) {
Contribution c = (Contribution) m;
switch (c.getState()) {
if(m instanceof Contribution) {
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

@ -14,7 +14,7 @@ public class CategoryModifier extends PageModifier {
public CategoryModifier(String... categories) {
super(MODIFIER_NAME);
JSONArray categoriesArray = new JSONArray();
for (String category : categories) {
for(String category: categories) {
categoriesArray.put(category);
}
try {
@ -35,7 +35,7 @@ public class CategoryModifier extends PageModifier {
categories = params.optJSONArray(PARAM_CATEGORIES);
StringBuffer categoriesString = new StringBuffer();
for (int i = 0; i < categories.length(); i++) {
for(int i=0; i < categories.length(); i++) {
String category = categories.optString(i);
categoriesString.append("\n[[Category:").append(category).append("]]");
}

View file

@ -10,7 +10,7 @@ import android.util.*;
import fr.free.nrw.commons.data.*;
import fr.free.nrw.commons.CommonsApplication;
public class ModificationsContentProvider extends ContentProvider {
public class ModificationsContentProvider extends ContentProvider{
private static final int MODIFICATIONS = 1;
private static final int MODIFICATIONS_ID = 2;
@ -21,7 +21,6 @@ public class ModificationsContentProvider extends ContentProvider {
public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);
private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
uriMatcher.addURI(AUTHORITY, BASE_PATH, MODIFICATIONS);
uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", MODIFICATIONS_ID);
@ -33,10 +32,9 @@ public class ModificationsContentProvider extends ContentProvider {
}
private DBOpenHelper dbOpenHelper;
@Override
public boolean onCreate() {
dbOpenHelper = ((CommonsApplication) this.getContext().getApplicationContext()).getDbOpenHelper();
dbOpenHelper = ((CommonsApplication)this.getContext().getApplicationContext()).getDbOpenHelper();
return false;
}
@ -47,7 +45,7 @@ public class ModificationsContentProvider extends ContentProvider {
int uriType = uriMatcher.match(uri);
switch (uriType) {
switch(uriType) {
case MODIFICATIONS:
break;
default:
@ -92,8 +90,8 @@ public class ModificationsContentProvider extends ContentProvider {
String id = uri.getLastPathSegment();
sqlDB.delete(ModifierSequence.Table.TABLE_NAME,
"_id = ?",
new String[]{id}
);
new String[] { id }
);
return 1;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
@ -108,7 +106,7 @@ public class ModificationsContentProvider extends ContentProvider {
sqlDB.beginTransaction();
switch (uriType) {
case MODIFICATIONS:
for (ContentValues value : values) {
for(ContentValues value: values) {
Log.d("Commons", "Inserting! " + value.toString());
sqlDB.insert(ModifierSequence.Table.TABLE_NAME, null, value);
}
@ -148,7 +146,7 @@ public class ModificationsContentProvider extends ContentProvider {
rowsUpdated = sqlDB.update(ModifierSequence.Table.TABLE_NAME,
contentValues,
ModifierSequence.Table.COLUMN_ID + " = ?",
new String[]{String.valueOf(id)});
new String[] { String.valueOf(id) } );
} else {
throw new IllegalArgumentException("Parameter `selection` should be empty when updating an ID");
}

View file

@ -37,14 +37,14 @@ public class ModificationsSyncAdapter extends AbstractThreadedSyncAdapter {
}
// Exit early if nothing to do
if (allModifications == null || allModifications.getCount() == 0) {
if(allModifications == null || allModifications.getCount() == 0) {
Log.d("Commons", "No modifications to perform");
return;
}
String authCookie;
try {
authCookie = AccountManager.get(getContext()).blockingGetAuthToken(account, "", false);
authCookie = AccountManager.get(getContext()).blockingGetAuthToken(account, "", false);
} catch (OperationCanceledException e) {
throw new RuntimeException(e);
} catch (IOException e) {
@ -75,7 +75,7 @@ public class ModificationsSyncAdapter extends AbstractThreadedSyncAdapter {
try {
contributionsClient = getContext().getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY);
while (!allModifications.isAfterLast()) {
while(!allModifications.isAfterLast()) {
ModifierSequence sequence = ModifierSequence.fromCursor(allModifications);
sequence.setContentProviderClient(contentProviderClient);
Contribution contrib;
@ -89,7 +89,7 @@ public class ModificationsSyncAdapter extends AbstractThreadedSyncAdapter {
contributionCursor.moveToFirst();
contrib = Contribution.fromCursor(contributionCursor);
if (contrib.getState() == Contribution.STATE_COMPLETED) {
if(contrib.getState() == Contribution.STATE_COMPLETED) {
try {
requestResult = api.action("query")
@ -104,7 +104,7 @@ public class ModificationsSyncAdapter extends AbstractThreadedSyncAdapter {
Log.d("Commons", "Page content is " + Utils.getStringFromDOM(requestResult.getDocument()));
String pageContent = requestResult.getString("/api/query/pages/page/revisions/rev");
String processedPageContent = sequence.executeModifications(contrib.getFilename(), pageContent);
String processedPageContent = sequence.executeModifications(contrib.getFilename(), pageContent);
try {
responseResult = api.action("edit")
@ -121,7 +121,7 @@ public class ModificationsSyncAdapter extends AbstractThreadedSyncAdapter {
Log.d("Commons", "Response is" + Utils.getStringFromDOM(responseResult.getDocument()));
String result = responseResult.getString("/api/edit/@result");
if (!result.equals("Success")) {
if(!result.equals("Success")) {
// FIXME: Log this somewhere else
Log.d("Commons", "Non success result!" + result);
} else {
@ -132,7 +132,7 @@ public class ModificationsSyncAdapter extends AbstractThreadedSyncAdapter {
}
} finally {
if (contributionsClient != null) {
if(contributionsClient != null) {
contributionsClient.release();
}

View file

@ -26,7 +26,7 @@ public class ModifierSequence {
public ModifierSequence(Uri mediaUri, JSONObject data) {
this(mediaUri);
JSONArray modifiersJSON = data.optJSONArray("modifiers");
for (int i = 0; i < modifiersJSON.length(); i++) {
for(int i=0; i< modifiersJSON.length(); i++) {
modifiers.add(PageModifier.fromJSON(modifiersJSON.optJSONObject(i)));
}
}
@ -40,15 +40,15 @@ public class ModifierSequence {
}
public String executeModifications(String pageName, String pageContents) {
for (PageModifier modifier : modifiers) {
pageContents = modifier.doModification(pageName, pageContents);
for(PageModifier modifier: modifiers) {
pageContents = modifier.doModification(pageName, pageContents);
}
return pageContents;
}
public String getEditSummary() {
StringBuffer editSummary = new StringBuffer();
for (PageModifier modifier : modifiers) {
for(PageModifier modifier: modifiers) {
editSummary.append(modifier.getEditSumary()).append(" ");
}
editSummary.append("Via Commons Mobile App");
@ -59,7 +59,7 @@ public class ModifierSequence {
JSONObject data = new JSONObject();
try {
JSONArray modifiersJSON = new JSONArray();
for (PageModifier modifier : modifiers) {
for(PageModifier modifier: modifiers) {
modifiersJSON.put(modifier.toJSON());
}
data.put("modifiers", modifiersJSON);
@ -91,12 +91,12 @@ public class ModifierSequence {
public void save() {
try {
if (contentUri == null) {
if(contentUri == null) {
contentUri = client.insert(ModificationsContentProvider.BASE_URI, this.toContentValues());
} else {
client.update(contentUri, toContentValues(), null, null);
}
} catch (RemoteException e) {
} catch(RemoteException e) {
throw new RuntimeException(e);
}
}

View file

@ -7,9 +7,9 @@ public abstract class PageModifier {
public static PageModifier fromJSON(JSONObject data) {
String name = data.optString("name");
if (name.equals(CategoryModifier.MODIFIER_NAME)) {
if(name.equals(CategoryModifier.MODIFIER_NAME)) {
return new CategoryModifier(data.optJSONObject("data"));
} else if (name.equals(TemplateRemoveModifier.MODIFIER_NAME)) {
} else if(name.equals(TemplateRemoveModifier.MODIFIER_NAME)) {
return new TemplateRemoveModifier(data.optJSONObject("data"));
}

View file

@ -42,18 +42,18 @@ public class TemplateRemoveModifier extends PageModifier {
Pattern templateStartPattern = Pattern.compile("\\{\\{" + templateNormalized, Pattern.CASE_INSENSITIVE);
Matcher matcher = templateStartPattern.matcher(pageContents);
while (matcher.find()) {
while(matcher.find()) {
int braceCount = 1;
int startIndex = matcher.start();
int curIndex = matcher.end();
Matcher openMatch = PATTERN_TEMPLATE_OPEN.matcher(pageContents);
Matcher closeMatch = PATTERN_TEMPLATE_CLOSE.matcher(pageContents);
while (curIndex < pageContents.length()) {
while(curIndex < pageContents.length()) {
boolean openFound = openMatch.find(curIndex);
boolean closeFound = closeMatch.find(curIndex);
if (openFound && (!closeFound || openMatch.start() < closeMatch.start())) {
if(openFound && (!closeFound || openMatch.start() < closeMatch.start())) {
braceCount++;
curIndex = openMatch.end();
} else if (closeFound) {
@ -72,8 +72,8 @@ public class TemplateRemoveModifier extends PageModifier {
}
// Strip trailing whitespace
while (curIndex < pageContents.length()) {
if (pageContents.charAt(curIndex) == ' ' || pageContents.charAt(curIndex) == '\n') {
while(curIndex < pageContents.length()) {
if(pageContents.charAt(curIndex) == ' ' || pageContents.charAt(curIndex) == '\n') {
curIndex++;
} else {
break;

View file

@ -26,12 +26,12 @@ import fr.free.nrw.commons.modifications.TemplateRemoveModifier;
import fr.free.nrw.commons.contributions.*;
import fr.free.nrw.commons.media.*;
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,
CategorizationFragment.OnCategoriesSaveHandler {
private CommonsApplication app;
private ArrayList<Contribution> photosList = null;
@ -51,14 +51,14 @@ public class MultipleShareActivity
}
public int getTotalMediaCount() {
if (photosList == null) {
if(photosList == null) {
return 0;
}
return photosList.size();
}
public void notifyDatasetChanged() {
if (uploadsList != null) {
if(uploadsList != null) {
uploadsList.notifyDatasetChanged();
}
}
@ -84,14 +84,14 @@ 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
uploadController.startUpload(up, new UploadController.ContributionUploadProgress() {
public void onUploadStarted(Contribution contribution) {
dialog.setProgress(uploadCount);
if (uploadCount == photosList.size()) {
if(uploadCount == photosList.size()) {
dialog.dismiss();
Toast startingToast = Toast.makeText(getApplicationContext(), R.string.uploading_started, Toast.LENGTH_LONG);
startingToast.show();
@ -103,7 +103,7 @@ public class MultipleShareActivity
uploadsList.setImageOnlyMode(true);
categorizationFragment = (CategorizationFragment) this.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
@ -118,9 +118,9 @@ public class MultipleShareActivity
}
public void onCategoriesSave(ArrayList<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[]{})));
@ -145,9 +145,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;
@ -161,9 +161,9 @@ public class MultipleShareActivity
uploadController = new UploadController(this);
setContentView(R.layout.activity_multiple_uploads);
app = (CommonsApplication) this.getApplicationContext();
app = (CommonsApplication)this.getApplicationContext();
if (savedInstanceState != null) {
if(savedInstanceState != null) {
photosList = savedInstanceState.getParcelableArrayList("uploadsList");
}
@ -180,7 +180,7 @@ public class MultipleShareActivity
}
private void showDetail(int i) {
if (mediaDetails == null || !mediaDetails.isVisible()) {
if(mediaDetails == null ||!mediaDetails.isVisible()) {
mediaDetails = new MediaDetailPagerFragment(true);
this.getSupportFragmentManager()
.beginTransaction()
@ -203,11 +203,11 @@ public class MultipleShareActivity
app.getApi().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<Contribution>();
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);
@ -220,8 +220,8 @@ public class MultipleShareActivity
}
uploadsList = (MultipleUploadListFragment) getSupportFragmentManager().findFragmentByTag("uploadsList");
if (uploadsList == null) {
uploadsList = new MultipleUploadListFragment();
if(uploadsList == null) {
uploadsList = new MultipleUploadListFragment();
this.getSupportFragmentManager()
.beginTransaction()
.add(R.id.uploadsFragmentContainer, uploadsList, "uploadsList")
@ -245,7 +245,7 @@ public class MultipleShareActivity
@Override
public void onBackPressed() {
super.onBackPressed();
if (categorizationFragment != null && categorizationFragment.isVisible()) {
if(categorizationFragment != null && categorizationFragment.isVisible()) {
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT)
.param("username", app.getCurrentAccount().name)
.param("categories-count", categorizationFragment.getCurrentSelectedCount())
@ -264,7 +264,7 @@ public class MultipleShareActivity
}
public void onBackStackChanged() {
if (mediaDetails != null && mediaDetails.isVisible()) {
if(mediaDetails != null && mediaDetails.isVisible()) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);

View file

@ -64,7 +64,7 @@ public class MultipleUploadListFragment extends SherlockFragment {
public View getView(int i, View view, ViewGroup viewGroup) {
UploadHolderView holder;
if (view == null) {
if(view == null) {
view = getLayoutInflater(null).inflate(R.layout.layout_upload_item, null);
holder = new UploadHolderView();
holder.image = (ImageView) view.findViewById(R.id.uploadImage);
@ -75,18 +75,18 @@ public class MultipleUploadListFragment extends SherlockFragment {
view.setTag(holder);
} else {
holder = (UploadHolderView) view.getTag();
holder = (UploadHolderView)view.getTag();
}
Contribution up = (Contribution) this.getItem(i);
Contribution up = (Contribution)this.getItem(i);
if (holder.imageUri == null || !holder.imageUri.equals(up.getLocalUri())) {
if(holder.imageUri == null || !holder.imageUri.equals(up.getLocalUri())) {
ImageLoader.getInstance().displayImage(up.getLocalUri().toString(), holder.image, uploadDisplayOptions);
holder.imageUri = up.getLocalUri();
}
if (!imageOnlyMode) {
if(!imageOnlyMode) {
holder.overlay.setVisibility(View.VISIBLE);
holder.title.setText(up.getFilename());
} else {
@ -117,21 +117,21 @@ public class MultipleUploadListFragment extends SherlockFragment {
int screenHeight = screenMetrics.heightPixels;
int picWidth = Math.min((int) Math.sqrt(screenWidth * screenHeight / count), screenWidth);
picWidth = Math.min((int) (192 * screenMetrics.density), Math.max((int) (120 * screenMetrics.density), picWidth / 48 * 48));
int picHeight = Math.min(picWidth, (int) (192 * screenMetrics.density)); // Max Height is same as Contributions list
picWidth = Math.min((int)(192 * screenMetrics.density), Math.max((int) (120 * screenMetrics.density), picWidth / 48 * 48));
int picHeight = Math.min(picWidth, (int)(192 * screenMetrics.density)); // Max Height is same as Contributions list
return new Point(picWidth, picHeight);
}
public void notifyDatasetChanged() {
if (photosAdapter != null) {
if(photosAdapter != null) {
photosAdapter.notifyDataSetChanged();
}
}
public void setImageOnlyMode(boolean mode) {
imageOnlyMode = mode;
if (imageOnlyMode) {
if(imageOnlyMode) {
baseTitle.setVisibility(View.GONE);
} else {
baseTitle.setVisibility(View.VISIBLE);
@ -143,13 +143,13 @@ public class MultipleUploadListFragment extends SherlockFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_multiple_uploads_list, null);
photosGrid = (GridView) view.findViewById(R.id.multipleShareBackground);
baseTitle = (EditText) view.findViewById(R.id.multipleBaseTitle);
photosGrid = (GridView)view.findViewById(R.id.multipleShareBackground);
baseTitle = (EditText)view.findViewById(R.id.multipleBaseTitle);
photosAdapter = new PhotoDisplayAdapter();
photosGrid.setAdapter(photosAdapter);
photosGrid.setOnItemClickListener((AdapterView.OnItemClickListener) getActivity());
photosGrid.setOnItemClickListener((AdapterView.OnItemClickListener)getActivity());
photoSize = calculatePicDimension(detailProvider.getTotalMediaCount());
photosGrid.setColumnWidth(photoSize.x);
@ -159,12 +159,12 @@ public class MultipleUploadListFragment extends SherlockFragment {
}
public void onTextChanged(CharSequence charSequence, int i1, int i2, int i3) {
for (int i = 0; i < detailProvider.getTotalMediaCount(); i++) {
for(int i = 0; i < detailProvider.getTotalMediaCount(); i++) {
Contribution up = (Contribution) detailProvider.getMediaAtPosition(i);
Boolean isDirty = (Boolean) up.getTag("isDirty");
if (isDirty == null || !isDirty) {
if (!TextUtils.isEmpty(charSequence)) {
up.setFilename(charSequence.toString() + " - " + ((Integer) up.getTag("sequence") + 1));
Boolean isDirty = (Boolean)up.getTag("isDirty");
if(isDirty == null || !isDirty) {
if(!TextUtils.isEmpty(charSequence)) {
up.setFilename(charSequence.toString() + " - " + ((Integer)up.getTag("sequence") + 1));
} else {
up.setFilename("");
}
@ -191,7 +191,7 @@ public class MultipleUploadListFragment extends SherlockFragment {
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
switch(item.getItemId()) {
case R.id.menu_upload_multiple:
multipleUploadInitiatedHandler.OnMultipleUploadInitiated();
return true;
@ -204,7 +204,7 @@ public class MultipleUploadListFragment extends SherlockFragment {
super.onCreate(savedInstanceState);
uploadDisplayOptions = Utils.getGenericDisplayOptions().build();
detailProvider = (MediaDetailPagerFragment.MediaDetailProvider) getActivity();
detailProvider = (MediaDetailPagerFragment.MediaDetailProvider)getActivity();
multipleUploadInitiatedHandler = (OnMultipleUploadInitiatedHandler) getActivity();
setHasOptionsMenu(true);

View file

@ -13,6 +13,7 @@ import fr.free.nrw.commons.modifications.CategoryModifier;
import fr.free.nrw.commons.modifications.TemplateRemoveModifier;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.EventLog;
import fr.free.nrw.commons.campaigns.Campaign;
import fr.free.nrw.commons.category.CategorizationFragment;
import fr.free.nrw.commons.contributions.*;
import fr.free.nrw.commons.auth.*;
@ -22,9 +23,9 @@ import fr.free.nrw.commons.modifications.ModifierSequence;
import java.util.ArrayList;
public class ShareActivity
extends AuthenticatedActivity
implements SingleUploadFragment.OnUploadActionInitiated,
public class ShareActivity
extends AuthenticatedActivity
implements SingleUploadFragment.OnUploadActionInitiated,
CategorizationFragment.OnCategoriesSaveHandler {
private SingleUploadFragment shareView;
@ -50,7 +51,7 @@ public class ShareActivity
public void uploadActionInitiated(String title, String description) {
Toast startingToast = Toast.makeText(getApplicationContext(), R.string.uploading_started, Toast.LENGTH_LONG);
startingToast.show();
uploadController.startUpload(title, mediaUri, description, mimeType, source, new UploadController.ContributionUploadProgress() {
uploadController.startUpload(title, mediaUri, description, mimeType, source, new UploadController.ContributionUploadProgress() {
public void onUploadStarted(Contribution contribution) {
ShareActivity.this.contribution = contribution;
showPostUpload();
@ -59,7 +60,7 @@ public class ShareActivity
}
private void showPostUpload() {
if (categorizationFragment == null) {
if(categorizationFragment == null) {
categorizationFragment = new CategorizationFragment();
}
getSupportFragmentManager().beginTransaction()
@ -68,7 +69,7 @@ public class ShareActivity
}
public void onCategoriesSave(ArrayList<String> categories) {
if (categories.size() > 0) {
if(categories.size() > 0) {
ModifierSequence categoriesSequence = new ModifierSequence(contribution.getContentUri());
categoriesSequence.queueModifier(new CategoryModifier(categories.toArray(new String[]{})));
@ -94,7 +95,7 @@ public class ShareActivity
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (contribution != null) {
if(contribution != null) {
outState.putParcelable("contribution", contribution);
}
}
@ -102,7 +103,7 @@ public class ShareActivity
@Override
public void onBackPressed() {
super.onBackPressed();
if (categorizationFragment != null && categorizationFragment.isVisible()) {
if(categorizationFragment != null && categorizationFragment.isVisible()) {
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT)
.param("username", app.getCurrentAccount().name)
.param("categories-count", categorizationFragment.getCurrentSelectedCount())
@ -128,12 +129,12 @@ public class ShareActivity
shareView = (SingleUploadFragment) getSupportFragmentManager().findFragmentByTag("shareView");
categorizationFragment = (CategorizationFragment) getSupportFragmentManager().findFragmentByTag("categorization");
if (shareView == null && categorizationFragment == null) {
shareView = new SingleUploadFragment();
this.getSupportFragmentManager()
.beginTransaction()
.add(R.id.single_upload_fragment_container, shareView, "shareView")
.commit();
if(shareView == null && categorizationFragment == null) {
shareView = new SingleUploadFragment();
this.getSupportFragmentManager()
.beginTransaction()
.add(R.id.single_upload_fragment_container, shareView, "shareView")
.commit();
}
uploadController.prepareService();
@ -150,19 +151,22 @@ public class ShareActivity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uploadController = new UploadController(this);
Campaign campaign = null;
if(getIntent().hasExtra(UploadService.EXTRA_CAMPAIGN)) {
campaign = (Campaign) getIntent().getSerializableExtra(UploadService.EXTRA_CAMPAIGN);
}
uploadController = new UploadController(this, campaign);
setContentView(R.layout.activity_share);
app = (CommonsApplication) this.getApplicationContext();
backgroundImageView = (ImageView) findViewById(R.id.backgroundImage);
app = (CommonsApplication)this.getApplicationContext();
backgroundImageView = (ImageView)findViewById(R.id.backgroundImage);
Intent intent = getIntent();
if (intent.getAction().equals(Intent.ACTION_SEND)) {
if(intent.getAction().equals(Intent.ACTION_SEND)) {
mediaUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (intent.hasExtra(UploadService.EXTRA_SOURCE)) {
if(intent.hasExtra(UploadService.EXTRA_SOURCE)) {
source = intent.getStringExtra(UploadService.EXTRA_SOURCE);
} else {
source = Contribution.SOURCE_EXTERNAL;
@ -173,7 +177,7 @@ public class ShareActivity
ImageLoader.getInstance().displayImage(mediaUri.toString(), backgroundImageView);
if (savedInstanceState != null) {
if(savedInstanceState != null) {
contribution = savedInstanceState.getParcelable("contribution");
}

View file

@ -39,7 +39,7 @@ public class SingleUploadFragment extends SherlockFragment {
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.activity_share, menu);
if (titleEdit != null) {
if(titleEdit != null) {
menu.findItem(R.id.menu_upload_single).setEnabled(titleEdit.getText().length() != 0);
}
}
@ -59,19 +59,17 @@ public class SingleUploadFragment extends SherlockFragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_single_upload, null);
titleEdit = (EditText) rootView.findViewById(R.id.titleEdit);
descEdit = (EditText) rootView.findViewById(R.id.descEdit);
licenseSummaryView = (TextView) rootView.findViewById(R.id.share_license_summary);
titleEdit = (EditText)rootView.findViewById(R.id.titleEdit);
descEdit = (EditText)rootView.findViewById(R.id.descEdit);
licenseSummaryView = (TextView)rootView.findViewById(R.id.share_license_summary);
TextWatcher uploadEnabler = new TextWatcher() {
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { }
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {}
public void afterTextChanged(Editable editable) {
if (getSherlockActivity() != null) {
if(getSherlockActivity() != null) {
getSherlockActivity().invalidateOptionsMenu();
}
}

View file

@ -15,7 +15,8 @@ import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.HandlerService;
import fr.free.nrw.commons.Prefs;
import fr.free.nrw.commons.Utils;
import fr.free.nrw.commons.campaigns.Campaign;
import fr.free.nrw.commons.campaigns.CampaignContribution;
import java.io.IOException;
import java.util.Date;
@ -24,6 +25,7 @@ public class UploadController {
private UploadService uploadService;
private final Activity activity;
private Campaign campaign;
final CommonsApplication app;
public interface ContributionUploadProgress {
@ -32,14 +34,18 @@ public class UploadController {
public UploadController(Activity activity) {
this.activity = activity;
app = (CommonsApplication) activity.getApplicationContext();
app = (CommonsApplication)activity.getApplicationContext();
}
public UploadController(Activity activity, Campaign campaign) {
this(activity);
this.campaign = campaign;
}
private boolean isUploadServiceConnected;
private ServiceConnection uploadServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName componentName, IBinder binder) {
uploadService = (UploadService) ((HandlerService.HandlerServiceLocalBinder) binder).getService();
uploadService = (UploadService) ((HandlerService.HandlerServiceLocalBinder)binder).getService();
isUploadServiceConnected = true;
}
@ -57,7 +63,7 @@ public class UploadController {
}
public void cleanup() {
if (isUploadServiceConnected) {
if(isUploadServiceConnected) {
activity.unbindService(uploadServiceConnection);
}
}
@ -71,13 +77,15 @@ public class UploadController {
if (extension != null && extension.toLowerCase().equals("jpeg")) {
extension = "jpg";
}
if (extension != null && !title.toLowerCase().endsWith(extension.toLowerCase())) {
if(extension != null && !title.toLowerCase().endsWith(extension.toLowerCase())) {
title += "." + extension;
}
contribution = new Contribution(mediaUri, null, title, description, -1, null, null, app.getCurrentAccount().name, CommonsApplication.DEFAULT_EDIT_SUMMARY);
if(campaign == null) {
contribution = new Contribution(mediaUri, null, title, description, -1, null, null, app.getCurrentAccount().name, CommonsApplication.DEFAULT_EDIT_SUMMARY);
} else {
contribution = new CampaignContribution(mediaUri, null, title, description, -1, null, null, app.getCurrentAccount().name, CommonsApplication.DEFAULT_EDIT_SUMMARY, campaign);
}
contribution.setTag("mimeType", mimeType);
contribution.setSource(source);
@ -87,11 +95,11 @@ public class UploadController {
public void startUpload(final Contribution contribution, final ContributionUploadProgress onComplete) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
if (TextUtils.isEmpty(contribution.getCreator())) {
if(TextUtils.isEmpty(contribution.getCreator())) {
contribution.setCreator(app.getCurrentAccount().name);
}
if (contribution.getDescription() == null) {
if(contribution.getDescription() == null) {
contribution.setDescription("");
}
@ -107,30 +115,30 @@ public class UploadController {
protected Contribution doInBackground(Void... voids /* stare into you */) {
long length;
try {
if (contribution.getDataLength() <= 0) {
if(contribution.getDataLength() <= 0) {
length = activity.getContentResolver().openAssetFileDescriptor(contribution.getLocalUri(), "r").getLength();
if (length == -1) {
if(length == -1) {
// Let us find out the long way!
length = Utils.countBytes(activity.getContentResolver().openInputStream(contribution.getLocalUri()));
}
contribution.setDataLength(length);
}
} catch (IOException e) {
} catch(IOException e) {
throw new RuntimeException(e);
}
String mimeType = (String) contribution.getTag("mimeType");
if (mimeType == null || TextUtils.isEmpty(mimeType) || mimeType.endsWith("*")) {
String mimeType = (String)contribution.getTag("mimeType");
if(mimeType == null || TextUtils.isEmpty(mimeType) || mimeType.endsWith("*")) {
mimeType = activity.getContentResolver().getType(contribution.getLocalUri());
if (mimeType != null) {
if(mimeType != null) {
contribution.setTag("mimeType", mimeType);
}
}
if (mimeType.startsWith("image/") && contribution.getDateCreated() == null) {
if(mimeType.startsWith("image/") && contribution.getDateCreated() == null) {
Cursor cursor = activity.getContentResolver().query(contribution.getLocalUri(),
new String[]{MediaStore.Images.ImageColumns.DATE_TAKEN}, null, null, null);
if (cursor != null && cursor.getCount() != 0) {
if(cursor != null && cursor.getCount() != 0) {
cursor.moveToFirst();
contribution.setDateCreated(new Date(cursor.getLong(0)));
} // FIXME: Alternate way of setting dateCreated if this data is not found

View file

@ -72,12 +72,12 @@ public class UploadService extends HandlerService<Contribution> {
@Override
public void onProgress(long transferred, long total) {
Log.d("Commons", String.format("Uploaded %d of %d", transferred, total));
if (!notificationTitleChanged) {
if(!notificationTitleChanged) {
curProgressNotification.setContentTitle(notificationProgressTitle);
notificationTitleChanged = true;
contribution.setState(Contribution.STATE_IN_PROGRESS);
}
if (transferred == total) {
if(transferred == total) {
// Completed!
curProgressNotification.setContentTitle(notificationFinishingTitle);
curProgressNotification.setProgress(0, 100, true);
@ -110,7 +110,7 @@ public class UploadService extends HandlerService<Contribution> {
@Override
protected void handle(int what, Contribution contribution) {
switch (what) {
switch(what) {
case ACTION_UPLOAD_FILE:
uploadContribution(contribution);
break;
@ -148,14 +148,14 @@ public class UploadService extends HandlerService<Contribution> {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction() == ACTION_START_SERVICE && freshStart) {
if(intent.getAction() == ACTION_START_SERVICE && freshStart) {
ContentValues failedValues = new ContentValues();
failedValues.put(Contribution.Table.COLUMN_STATE, Contribution.STATE_FAILED);
int updated = getContentResolver().update(ContributionsContentProvider.BASE_URI,
failedValues,
Contribution.Table.COLUMN_STATE + " = ? OR " + Contribution.Table.COLUMN_STATE + " = ?",
new String[]{String.valueOf(Contribution.STATE_QUEUED), String.valueOf(Contribution.STATE_IN_PROGRESS)}
new String[]{ String.valueOf(Contribution.STATE_QUEUED), String.valueOf(Contribution.STATE_IN_PROGRESS) }
);
Log.d("Commons", "Set " + updated + " uploads to failed");
Log.d("Commons", "Flags is" + flags + " id is" + startId);
@ -175,7 +175,7 @@ public class UploadService extends HandlerService<Contribution> {
try {
file = this.getContentResolver().openInputStream(contribution.getLocalUri());
} catch (FileNotFoundException e) {
} catch(FileNotFoundException e) {
throw new RuntimeException(e);
}
@ -195,9 +195,9 @@ public class UploadService extends HandlerService<Contribution> {
try {
String filename = findUniqueFilename(contribution.getFilename());
if (!api.validateLogin()) {
if(!api.validateLogin()) {
// Need to revalidate!
if (app.revalidateAuthToken()) {
if(app.revalidateAuthToken()) {
Log.d("Commons", "Successfully revalidated token!");
} else {
Log.d("Commons", "Unable to revalidate :(");
@ -222,7 +222,7 @@ public class UploadService extends HandlerService<Contribution> {
String resultStatus = result.getString("/api/upload/@result");
if (!resultStatus.equals("Success")) {
if(!resultStatus.equals("Success")) {
String errorCode = result.getString("/api/error/@code");
showFailedNotification(contribution);
fr.free.nrw.commons.EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT)
@ -251,13 +251,13 @@ public class UploadService extends HandlerService<Contribution> {
.param("result", "success")
.log();
}
} catch (IOException e) {
} catch(IOException e) {
Log.d("Commons", "I have a network fuckup");
showFailedNotification(contribution);
return;
} finally {
toUpload--;
if (toUpload == 0) {
if(toUpload == 0) {
// Sync modifications right after all uplaods are processed
ContentResolver.requestSync(((CommonsApplication) getApplicationContext()).getCurrentAccount(), ModificationsContentProvider.AUTHORITY, new Bundle());
stopForeground(true);
@ -285,7 +285,7 @@ public class UploadService extends HandlerService<Contribution> {
return findUniqueFilename(fileName, 1);
}
private String findUniqueFilename(String fileName, int sequenceNumber) throws IOException {
private String findUniqueFilename(String fileName, int sequenceNumber) throws IOException {
String sequenceFileName;
if (sequenceNumber == 1) {
sequenceFileName = fileName;