Removed dead code behind Campaigns feature

- Removed entire Campaigns folder and associated classes
- Removed associated code in other classes (mostly that test for
campaign == null). I am assuming we want  to keep the behaviour where
campaign == null (ie campaigns are disabled) and discard the behaviour
where campaign != null
- Refactored code to fix spacing
This commit is contained in:
misaochan 2015-10-21 19:29:08 +13:00
parent 235d290252
commit c64a64c905
48 changed files with 462 additions and 1137 deletions

View file

@ -85,7 +85,7 @@ public class CommonsApplication extends Application {
public DBOpenHelper getDbOpenHelper() { public DBOpenHelper getDbOpenHelper() {
if(dbOpenHelper == null) { if (dbOpenHelper == null) {
dbOpenHelper = new DBOpenHelper(this); dbOpenHelper = new DBOpenHelper(this);
} }
return dbOpenHelper; return dbOpenHelper;
@ -154,7 +154,7 @@ public class CommonsApplication extends Application {
private LruCache<String, Bitmap> imageCache; private LruCache<String, Bitmap> imageCache;
public com.android.volley.toolbox.ImageLoader getImageLoader() { 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() { imageLoader = new com.android.volley.toolbox.ImageLoader(volleyQueue, new com.android.volley.toolbox.ImageLoader.ImageCache() {
public Bitmap getBitmap(String key) { public Bitmap getBitmap(String key) {
return imageCache.get(key); return imageCache.get(key);
@ -174,10 +174,10 @@ public class CommonsApplication extends Application {
} }
public Account getCurrentAccount() { public Account getCurrentAccount() {
if(currentAccount == null) { if (currentAccount == null) {
AccountManager accountManager = AccountManager.get(this); AccountManager accountManager = AccountManager.get(this);
Account[] allAccounts = accountManager.getAccountsByType(WikiAccountAuthenticator.COMMONS_ACCOUNT_TYPE); Account[] allAccounts = accountManager.getAccountsByType(WikiAccountAuthenticator.COMMONS_ACCOUNT_TYPE);
if(allAccounts.length != 0) { if (allAccounts.length != 0) {
currentAccount = allAccounts[0]; currentAccount = allAccounts[0];
} }
} }
@ -188,7 +188,7 @@ public class CommonsApplication extends Application {
AccountManager accountManager = AccountManager.get(this); AccountManager accountManager = AccountManager.get(this);
Account curAccount = getCurrentAccount(); Account curAccount = getCurrentAccount();
if(curAccount == null) { if (curAccount == null) {
return false; // This should never happen return false; // This should never happen
} }

View file

@ -7,6 +7,7 @@ import android.util.*;
import in.yuvi.http.fluent.Http; import in.yuvi.http.fluent.Http;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.json.*; import org.json.*;
import java.io.IOException; import java.io.IOException;
import java.net.*; import java.net.*;
@ -19,16 +20,16 @@ public class EventLog {
@Override @Override
protected Boolean doInBackground(LogBuilder... logBuilders) { 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 // 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; HttpURLConnection conn;
try { try {
URL url = logBuilder.toUrl(); URL url = logBuilder.toUrl();
HttpResponse response = Http.get(url.toString()).use(CommonsApplication.createHttpClient()).asResponse(); HttpResponse response = Http.get(url.toString()).use(CommonsApplication.createHttpClient()).asResponse();
if(response.getStatusLine().getStatusCode() != 204) { if (response.getStatusLine().getStatusCode() != 204) {
allSuccess = false; allSuccess = false;
} }
Log.d("Commons", "EventLog hit " + url.toString()); Log.d("Commons", "EventLog hit " + url.toString());
@ -45,6 +46,7 @@ public class EventLog {
} }
private static final String DEVICE; private static final String DEVICE;
static { static {
if (Build.MODEL.startsWith(Build.MANUFACTURER)) { if (Build.MODEL.startsWith(Build.MANUFACTURER)) {
DEVICE = Utils.capitalize(Build.MODEL); DEVICE = Utils.capitalize(Build.MODEL);
@ -100,7 +102,7 @@ public class EventLog {
// Attempting to use anywhere else will cause kitten explosions // Attempting to use anywhere else will cause kitten explosions
public void log(boolean force) { public void log(boolean force) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(app); 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 return; // User has disabled tracking
} }
LogTask logTask = new LogTask(); LogTask logTask = new LogTask();
@ -118,9 +120,9 @@ public class EventLog {
} }
public static LogBuilder schema(Object[] scid) { 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"); 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 @Override
public void handleMessage(Message msg) { public void handleMessage(Message msg) {
handle(msg.what, (T)msg.obj); handle(msg.what, (T) msg.obj);
stopSelf(msg.arg1); stopSelf(msg.arg1);
} }
} }
@ -35,6 +35,7 @@ public abstract class HandlerService<T> extends Service {
} }
private final IBinder localBinder = new HandlerServiceLocalBinder(); private final IBinder localBinder = new HandlerServiceLocalBinder();
@Override @Override
public IBinder onBind(Intent intent) { public IBinder onBind(Intent intent) {
return localBinder; return localBinder;

View file

@ -34,14 +34,15 @@ public class Media implements Parcelable {
} }
public static Pattern displayTitlePattern = Pattern.compile("(.*)(\\.\\w+)", Pattern.CASE_INSENSITIVE); public static Pattern displayTitlePattern = Pattern.compile("(.*)(\\.\\w+)", Pattern.CASE_INSENSITIVE);
public String getDisplayTitle() {
if(filename == null) { public String getDisplayTitle() {
if (filename == null) {
return ""; return "";
} }
// FIXME: Gross hack bercause my regex skills suck maybe or I am too lazy who knows // FIXME: Gross hack bercause my regex skills suck maybe or I am too lazy who knows
String title = filename.replaceFirst("^File:", ""); String title = filename.replaceFirst("^File:", "");
Matcher matcher = displayTitlePattern.matcher(title); Matcher matcher = displayTitlePattern.matcher(title);
if(matcher.matches()) { if (matcher.matches()) {
return matcher.group(1); return matcher.group(1);
} else { } else {
return title; return title;
@ -58,7 +59,7 @@ public class Media implements Parcelable {
} }
public String getImageUrl() { public String getImageUrl() {
if(imageUrl == null) { if (imageUrl == null) {
imageUrl = Utils.makeThumbBaseUrl(this.getFilename()); imageUrl = Utils.makeThumbBaseUrl(this.getFilename());
} }
return imageUrl; return imageUrl;
@ -151,7 +152,7 @@ public class Media implements Parcelable {
protected Map<String, String> descriptions; // multilingual descriptions as loaded protected Map<String, String> descriptions; // multilingual descriptions as loaded
public ArrayList<String> getCategories() { public ArrayList<String> getCategories() {
return (ArrayList<String>)categories.clone(); // feels dirty return (ArrayList<String>) categories.clone(); // feels dirty
} }
public void setCategories(List<String> categories) { public void setCategories(List<String> categories) {
@ -159,7 +160,7 @@ public class Media implements Parcelable {
this.categories.addAll(categories); this.categories.addAll(categories);
} }
public void setDescriptions(Map<String,String> descriptions) { public void setDescriptions(Map<String, String> descriptions) {
for (String key : this.descriptions.keySet()) { for (String key : this.descriptions.keySet()) {
this.descriptions.remove(key); this.descriptions.remove(key);
} }
@ -223,7 +224,7 @@ public class Media implements Parcelable {
} }
public Media(Parcel in) { public Media(Parcel in) {
localUri = (Uri)in.readParcelable(Uri.class.getClassLoader()); localUri = (Uri) in.readParcelable(Uri.class.getClassLoader());
imageUrl = in.readString(); imageUrl = in.readString();
filename = in.readString(); filename = in.readString();
description = in.readString(); description = in.readString();
@ -231,7 +232,7 @@ public class Media implements Parcelable {
dateCreated = (Date) in.readSerializable(); dateCreated = (Date) in.readSerializable();
dateUploaded = (Date) in.readSerializable(); dateUploaded = (Date) in.readSerializable();
creator = in.readString(); creator = in.readString();
tags = (HashMap<String, Object>)in.readSerializable(); tags = (HashMap<String, Object>) in.readSerializable();
width = in.readInt(); width = in.readInt();
height = in.readInt(); height = in.readInt();
license = in.readString(); 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. * Fetch additional media data from the network that we don't store locally.
* * <p>
* This includes things like category lists and multilingual descriptions, * This includes things like category lists and multilingual descriptions,
* which are not intrinsic to the media and may change due to editing. * 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. * Actually fetch the data over the network.
* todo: use local caching? * todo: use local caching?
* * <p>
* Warning: synchronous i/o, call on a background thread * Warning: synchronous i/o, call on a background thread
*/ */
public void fetch() throws IOException { public void fetch() throws IOException {
@ -156,7 +156,7 @@ public class MediaDataExtractor {
} }
private Node findTemplate(Element parentNode, String title) throws IOException { private Node findTemplate(Element parentNode, String title) throws IOException {
String ucTitle= Utils.capitalize(title); String ucTitle = Utils.capitalize(title);
NodeList nodes = parentNode.getChildNodes(); NodeList nodes = parentNode.getChildNodes();
for (int i = 0, length = nodes.getLength(); i < length; i++) { for (int i = 0, length = nodes.getLength(); i < length; i++) {
Node node = nodes.item(i); Node node = nodes.item(i);
@ -200,7 +200,7 @@ public class MediaDataExtractor {
return findTemplateParameter(templateNode, new TemplateChildNodeComparator() { return findTemplateParameter(templateNode, new TemplateChildNodeComparator() {
@Override @Override
public boolean match(Node node) { public boolean match(Node node) {
Element el = (Element)node; Element el = (Element) node;
if (el.getTextContent().trim().equals(theIndex)) { if (el.getTextContent().trim().equals(theIndex)) {
return true; return true;
} else if (el.getAttribute("index") != null && el.getAttribute("index").trim().equals(theIndex)) { } else if (el.getAttribute("index") != null && el.getAttribute("index").trim().equals(theIndex)) {
@ -278,6 +278,7 @@ public class MediaDataExtractor {
/** /**
* Take our metadata and inject it into a live Media object. * Take our metadata and inject it into a live Media object.
* Media object might contain stale or cached data, or emptiness. * Media object might contain stale or cached data, or emptiness.
*
* @param media * @param media
*/ */
public void fill(Media media) { public void fill(Media media) {

View file

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

View file

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

View file

@ -72,8 +72,7 @@ public class Utils {
T... params) { T... params) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params); task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
} } else {
else {
task.execute(params); task.execute(params);
} }
} }
@ -83,16 +82,16 @@ public class Utils {
// FIXME: We're simply ignoring the executor on older androids // FIXME: We're simply ignoring the executor on older androids
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(executor, params); task.executeOnExecutor(executor, params);
} } else {
else {
task.execute(params); task.execute(params);
} }
} }
private static DisplayImageOptions.Builder defaultImageOptionsBuilder; private static DisplayImageOptions.Builder defaultImageOptionsBuilder;
public static DisplayImageOptions.Builder getGenericDisplayOptions() { public static DisplayImageOptions.Builder getGenericDisplayOptions() {
if(defaultImageOptionsBuilder == null) { if (defaultImageOptionsBuilder == null) {
defaultImageOptionsBuilder = new DisplayImageOptions.Builder().cacheInMemory() defaultImageOptionsBuilder = new DisplayImageOptions.Builder().cacheInMemory()
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2); .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
@ -122,7 +121,7 @@ public class Utils {
public static long countBytes(InputStream stream) throws IOException { public static long countBytes(InputStream stream) throws IOException {
long count = 0; long count = 0;
BufferedInputStream bis = new BufferedInputStream(stream); BufferedInputStream bis = new BufferedInputStream(stream);
while(bis.read() != -1) { while (bis.read() != -1) {
count++; count++;
} }
return count; return count;
@ -132,7 +131,7 @@ public class Utils {
// Ugly Hack! // Ugly Hack!
// Update: OH DEAR GOD WHAT A HORRIBLE HACK I AM SO SORRY // 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(" ", "_"); 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; return thumbUrl;
} else { } else {
return thumbUrl + ".png"; return thumbUrl + ".png";
@ -140,37 +139,37 @@ public class Utils {
} }
public static String capitalize(String string) { 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) { 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}}"; 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}}"; 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}}"; return "{{self|cc-zero}}";
} }
throw new RuntimeException("Unrecognized license value"); throw new RuntimeException("Unrecognized license value");
} }
public static int licenseNameFor(String license) { 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; 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; 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; return R.string.license_name_cc0;
} }
throw new RuntimeException("Unrecognized license value"); throw new RuntimeException("Unrecognized license value");
} }
public static String licenseUrlFor(String license) { 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/"; 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/"; 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/"; return "https://creativecommons.org/publicdomain/zero/1.0/";
} }
throw new RuntimeException("Unrecognized license value"); throw new RuntimeException("Unrecognized license value");

View file

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

View file

@ -20,13 +20,14 @@ public class AuthenticatedActivity extends SherlockFragmentActivity {
private String authCookie; private String authCookie;
public AuthenticatedActivity(String accountType) { public AuthenticatedActivity(String accountType) {
this.accountType = accountType; this.accountType = accountType;
} }
private class GetAuthCookieTask extends AsyncTask<Void, String, String> { private class GetAuthCookieTask extends AsyncTask<Void, String, String> {
private Account account; private Account account;
private AccountManager accountManager; private AccountManager accountManager;
public GetAuthCookieTask(Account account, AccountManager accountManager) { public GetAuthCookieTask(Account account, AccountManager accountManager) {
this.account = account; this.account = account;
this.accountManager = accountManager; this.accountManager = accountManager;
@ -35,7 +36,7 @@ public class AuthenticatedActivity extends SherlockFragmentActivity {
@Override @Override
protected void onPostExecute(String result) { protected void onPostExecute(String result) {
super.onPostExecute(result); super.onPostExecute(result);
if(result != null) { if (result != null) {
authCookie = result; authCookie = result;
onAuthCookieAcquired(result); onAuthCookieAcquired(result);
} else { } else {
@ -63,6 +64,7 @@ public class AuthenticatedActivity extends SherlockFragmentActivity {
private class AddAccountTask extends AsyncTask<Void, String, String> { private class AddAccountTask extends AsyncTask<Void, String, String> {
private AccountManager accountManager; private AccountManager accountManager;
public AddAccountTask(AccountManager accountManager) { public AddAccountTask(AccountManager accountManager) {
this.accountManager = accountManager; this.accountManager = accountManager;
} }
@ -70,8 +72,8 @@ public class AuthenticatedActivity extends SherlockFragmentActivity {
@Override @Override
protected void onPostExecute(String result) { protected void onPostExecute(String result) {
super.onPostExecute(result); super.onPostExecute(result);
if(result != null) { if (result != null) {
Account[] allAccounts =accountManager.getAccountsByType(accountType); Account[] allAccounts = accountManager.getAccountsByType(accountType);
Account curAccount = allAccounts[0]; Account curAccount = allAccounts[0];
GetAuthCookieTask getCookieTask = new GetAuthCookieTask(curAccount, accountManager); GetAuthCookieTask getCookieTask = new GetAuthCookieTask(curAccount, accountManager);
getCookieTask.execute(); getCookieTask.execute();
@ -98,7 +100,7 @@ public class AuthenticatedActivity extends SherlockFragmentActivity {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
if(result.containsKey(AccountManager.KEY_ACCOUNT_NAME)) { if (result.containsKey(AccountManager.KEY_ACCOUNT_NAME)) {
return result.getString(AccountManager.KEY_ACCOUNT_NAME); return result.getString(AccountManager.KEY_ACCOUNT_NAME);
} else { } else {
return null; return null;
@ -106,14 +108,15 @@ public class AuthenticatedActivity extends SherlockFragmentActivity {
} }
} }
protected void requestAuthToken() { protected void requestAuthToken() {
if(authCookie != null) { if (authCookie != null) {
onAuthCookieAcquired(authCookie); onAuthCookieAcquired(authCookie);
return; return;
} }
AccountManager accountManager = AccountManager.get(this); AccountManager accountManager = AccountManager.get(this);
Account curAccount = app.getCurrentAccount(); Account curAccount = app.getCurrentAccount();
if(curAccount == null) { if (curAccount == null) {
AddAccountTask addAccountTask = new AddAccountTask(accountManager); AddAccountTask addAccountTask = new AddAccountTask(accountManager);
// This AsyncTask blocks until the Login Activity returns // This AsyncTask blocks until the Login Activity returns
// And since in Android 4.x+ only one background thread runs all AsyncTasks // And since in Android 4.x+ only one background thread runs all AsyncTasks
@ -131,8 +134,8 @@ public class AuthenticatedActivity extends SherlockFragmentActivity {
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
app = (CommonsApplication)this.getApplicationContext(); app = (CommonsApplication) this.getApplicationContext();
if(savedInstanceState != null) { if (savedInstanceState != null) {
authCookie = savedInstanceState.getString("authCookie"); authCookie = savedInstanceState.getString("authCookie");
} }
} }
@ -146,6 +149,7 @@ public class AuthenticatedActivity extends SherlockFragmentActivity {
protected void onAuthCookieAcquired(String authCookie) { protected void onAuthCookieAcquired(String authCookie) {
} }
protected void onAuthFailure() { protected void onAuthFailure() {
} }

View file

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

View file

@ -13,6 +13,7 @@ public class WikiAccountAuthenticator extends AbstractAccountAuthenticator {
public static final String COMMONS_ACCOUNT_TYPE = "fr.free.nrw.commons"; public static final String COMMONS_ACCOUNT_TYPE = "fr.free.nrw.commons";
private Context context; private Context context;
public WikiAccountAuthenticator(Context context) { public WikiAccountAuthenticator(Context context) {
super(context); super(context);
this.context = context; this.context = context;
@ -43,12 +44,13 @@ public class WikiAccountAuthenticator extends AbstractAccountAuthenticator {
private String getAuthCookie(String username, String password) throws IOException { private String getAuthCookie(String username, String password) throws IOException {
MWApi api = CommonsApplication.createMWApi(); MWApi api = CommonsApplication.createMWApi();
String result = api.login(username, password); String result = api.login(username, password);
if(result.equals("Success")) { if (result.equals("Success")) {
return api.getAuthCookie(); return api.getAuthCookie();
} else { } else {
return null; return null;
} }
} }
@Override @Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException {
// Extract the username and password from the Account Manager, and ask // 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.content.*;
import android.os.*; import android.os.*;
public class WikiAccountAuthenticatorService extends Service{ public class WikiAccountAuthenticatorService extends Service {
private static WikiAccountAuthenticator wikiAccountAuthenticator = null; private static WikiAccountAuthenticator wikiAccountAuthenticator = null;
@Override @Override
public IBinder onBind(Intent intent) { public IBinder onBind(Intent intent) {
if (!intent.getAction().equals(android.accounts.AccountManager.ACTION_AUTHENTICATOR_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); wikiAccountAuthenticator = new WikiAccountAuthenticator(this);
} }
return wikiAccountAuthenticator.getIBinder(); return wikiAccountAuthenticator.getIBinder();

View file

@ -1,190 +0,0 @@
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

@ -1,59 +0,0 @@
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

@ -1,49 +0,0 @@
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

@ -1,206 +0,0 @@
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

@ -1,38 +0,0 @@
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

@ -1,90 +0,0 @@
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

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

View file

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

View file

@ -24,6 +24,7 @@ public class CategoryContentProvider extends ContentProvider {
public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH); public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);
private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static { static {
uriMatcher.addURI(AUTHORITY, BASE_PATH, CATEGORIES); uriMatcher.addURI(AUTHORITY, BASE_PATH, CATEGORIES);
uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", CATEGORIES_ID); uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", CATEGORIES_ID);
@ -35,9 +36,10 @@ public class CategoryContentProvider extends ContentProvider {
} }
private DBOpenHelper dbOpenHelper; private DBOpenHelper dbOpenHelper;
@Override @Override
public boolean onCreate() { public boolean onCreate() {
dbOpenHelper = ((CommonsApplication)this.getContext().getApplicationContext()).getDbOpenHelper(); dbOpenHelper = ((CommonsApplication) this.getContext().getApplicationContext()).getDbOpenHelper();
return false; return false;
} }
@ -51,7 +53,7 @@ public class CategoryContentProvider extends ContentProvider {
SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
Cursor cursor; Cursor cursor;
switch(uriType) { switch (uriType) {
case CATEGORIES: case CATEGORIES:
cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder); cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
break; break;
@ -59,7 +61,7 @@ public class CategoryContentProvider extends ContentProvider {
cursor = queryBuilder.query(db, cursor = queryBuilder.query(db,
Category.Table.ALL_FIELDS, Category.Table.ALL_FIELDS,
"_id = ?", "_id = ?",
new String[] { uri.getLastPathSegment() }, new String[]{uri.getLastPathSegment()},
null, null,
null, null,
sortOrder sortOrder
@ -108,7 +110,7 @@ public class CategoryContentProvider extends ContentProvider {
sqlDB.beginTransaction(); sqlDB.beginTransaction();
switch (uriType) { switch (uriType) {
case CATEGORIES: case CATEGORIES:
for(ContentValues value: values) { for (ContentValues value : values) {
Log.d("Commons", "Inserting! " + value.toString()); Log.d("Commons", "Inserting! " + value.toString());
sqlDB.insert(Category.Table.TABLE_NAME, null, value); sqlDB.insert(Category.Table.TABLE_NAME, null, value);
} }
@ -142,7 +144,7 @@ public class CategoryContentProvider extends ContentProvider {
rowsUpdated = sqlDB.update(Category.Table.TABLE_NAME, rowsUpdated = sqlDB.update(Category.Table.TABLE_NAME,
contentValues, contentValues,
Category.Table.COLUMN_ID + " = ?", Category.Table.COLUMN_ID + " = ?",
new String[] { String.valueOf(id) } ); new String[]{String.valueOf(id)});
} else { } else {
throw new IllegalArgumentException("Parameter `selection` should be empty when updating an ID"); 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) { public Contribution(Parcel in) {
super(in); super(in);
contentUri = (Uri)in.readParcelable(Uri.class.getClassLoader()); contentUri = (Uri) in.readParcelable(Uri.class.getClassLoader());
source = in.readString(); source = in.readString();
timestamp = (Date) in.readSerializable(); timestamp = (Date) in.readSerializable();
state = in.readInt(); state = in.readInt();
@ -125,21 +125,21 @@ public class Contribution extends Media {
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd");
buffer buffer
.append("== {{int:filedesc}} ==\n") .append("== {{int:filedesc}} ==\n")
.append("{{Information\n") .append("{{Information\n")
.append("|description=").append(getDescription()).append("\n") .append("|description=").append(getDescription()).append("\n")
.append("|source=").append("{{own}}\n") .append("|source=").append("{{own}}\n")
.append("|author=[[User:").append(creator).append("|").append(creator).append("]]\n"); .append("|author=[[User:").append(creator).append("|").append(creator).append("]]\n");
if(dateCreated != null) { if (dateCreated != null) {
buffer buffer
.append("|date={{According to EXIF data|").append(isoFormat.format(dateCreated)).append("}}\n"); .append("|date={{According to EXIF data|").append(isoFormat.format(dateCreated)).append("}}\n");
} }
buffer buffer
.append("}}").append("\n") .append("}}").append("\n")
.append("== {{int:license-header}} ==\n") .append("== {{int:license-header}} ==\n")
.append(Utils.licenseTemplateFor(getLicense())).append("\n\n") .append(Utils.licenseTemplateFor(getLicense())).append("\n\n")
.append("{{Uploaded from Mobile|platform=Android|version=").append(CommonsApplication.APPLICATION_VERSION).append("}}\n") .append("{{Uploaded from Mobile|platform=Android|version=").append(CommonsApplication.APPLICATION_VERSION).append("}}\n")
.append(getTrackingTemplates()); .append(getTrackingTemplates());
return buffer.toString(); return buffer.toString();
} }
@ -149,19 +149,19 @@ public class Contribution extends Media {
public void save() { public void save() {
try { try {
if(contentUri == null) { if (contentUri == null) {
contentUri = client.insert(ContributionsContentProvider.BASE_URI, this.toContentValues()); contentUri = client.insert(ContributionsContentProvider.BASE_URI, this.toContentValues());
} else { } else {
client.update(contentUri, toContentValues(), null, null); client.update(contentUri, toContentValues(), null, null);
} }
} catch(RemoteException e) { } catch (RemoteException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
public void delete() { public void delete() {
try { try {
if(contentUri == null) { if (contentUri == null) {
// noooo // noooo
throw new RuntimeException("tried to delete item with no content URI"); throw new RuntimeException("tried to delete item with no content URI");
} else { } else {
@ -176,20 +176,20 @@ public class Contribution extends Media {
public ContentValues toContentValues() { public ContentValues toContentValues() {
ContentValues cv = new ContentValues(); ContentValues cv = new ContentValues();
cv.put(Table.COLUMN_FILENAME, getFilename()); cv.put(Table.COLUMN_FILENAME, getFilename());
if(getLocalUri() != null) { if (getLocalUri() != null) {
cv.put(Table.COLUMN_LOCAL_URI, getLocalUri().toString()); cv.put(Table.COLUMN_LOCAL_URI, getLocalUri().toString());
} }
if(getImageUrl() != null) { if (getImageUrl() != null) {
cv.put(Table.COLUMN_IMAGE_URL, getImageUrl().toString()); 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_UPLOADED, getDateUploaded().getTime());
} }
cv.put(Table.COLUMN_LENGTH, getDataLength()); cv.put(Table.COLUMN_LENGTH, getDataLength());
cv.put(Table.COLUMN_TIMESTAMP, getTimestamp().getTime()); cv.put(Table.COLUMN_TIMESTAMP, getTimestamp().getTime());
cv.put(Table.COLUMN_STATE, getState()); cv.put(Table.COLUMN_STATE, getState());
cv.put(Table.COLUMN_TRANSFERRED, transferred); 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_DESCRIPTION, description);
cv.put(Table.COLUMN_CREATOR, creator); cv.put(Table.COLUMN_CREATOR, creator);
cv.put(Table.COLUMN_MULTIPLE, isMultiple ? 1 : 0); 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.timestamp = cursor.getLong(4) == 0 ? null : new Date(cursor.getLong(4));
c.state = cursor.getInt(5); c.state = cursor.getInt(5);
c.dataLength = cursor.getLong(6); 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.transferred = cursor.getLong(8);
c.source = cursor.getString(9); c.source = cursor.getString(9);
c.description = cursor.getString(10); c.description = cursor.getString(10);
@ -306,7 +306,7 @@ public class Contribution extends Media {
+ "width INTEGER," + "width INTEGER,"
+ "height INTEGER," + "height INTEGER,"
+ "LICENSE STRING" + "LICENSE STRING"
+ ");"; + ");";
public static void onCreate(SQLiteDatabase db) { 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) { public static void onUpdate(SQLiteDatabase db, int from, int to) {
if(from == to) { if (from == to) {
return; 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 description STRING;");
db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN creator STRING;"); db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN creator STRING;");
from++; from++;
onUpdate(db, from, to); onUpdate(db, from, to);
return; return;
} }
if(from == 2) { if (from == 2) {
db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN multiple INTEGER;"); db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN multiple INTEGER;");
db.execSQL("UPDATE " + TABLE_NAME + " SET multiple = 0"); db.execSQL("UPDATE " + TABLE_NAME + " SET multiple = 0");
from++; from++;
onUpdate(db, from, to); onUpdate(db, from, to);
return; return;
} }
if(from == 3) { if (from == 3) {
// Do nothing // Do nothing
from++; from++;
onUpdate(db, from, to); onUpdate(db, from, to);
return; return;
} }
if(from == 4) { if (from == 4) {
// Do nothing -- added Category // Do nothing -- added Category
from++; from++;
onUpdate(db, from, to); onUpdate(db, from, to);
return; return;
} }
if(from == 5) { if (from == 5) {
// Added width and height fields // Added width and height fields
db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN width INTEGER;"); db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN width INTEGER;");
db.execSQL("UPDATE " + TABLE_NAME + " SET width = 0"); db.execSQL("UPDATE " + TABLE_NAME + " SET width = 0");

View file

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

View file

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

View file

@ -22,20 +22,18 @@ import fr.free.nrw.commons.auth.*;
import fr.free.nrw.commons.CommonsApplication; import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.HandlerService; import fr.free.nrw.commons.HandlerService;
import fr.free.nrw.commons.Media; import fr.free.nrw.commons.Media;
import fr.free.nrw.commons.campaigns.Campaign;
import fr.free.nrw.commons.media.*; import fr.free.nrw.commons.media.*;
import fr.free.nrw.commons.upload.UploadService; import fr.free.nrw.commons.upload.UploadService;
import java.util.ArrayList; import java.util.ArrayList;
public class ContributionsActivity public class ContributionsActivity
extends AuthenticatedActivity extends AuthenticatedActivity
implements LoaderManager.LoaderCallbacks<Object>, implements LoaderManager.LoaderCallbacks<Object>,
AdapterView.OnItemClickListener, AdapterView.OnItemClickListener,
MediaDetailPagerFragment.MediaDetailProvider, MediaDetailPagerFragment.MediaDetailProvider,
ContributionsListFragment.CurrentCampaignProvider, FragmentManager.OnBackStackChangedListener,
FragmentManager.OnBackStackChangedListener, ContributionsListFragment.SourceRefresher {
ContributionsListFragment.SourceRefresher {
private Cursor allContributions; private Cursor allContributions;
@ -43,7 +41,6 @@ public class ContributionsActivity
private MediaDetailPagerFragment mediaDetails; private MediaDetailPagerFragment mediaDetails;
private ArrayList<DataSetObserver> observersWaitingForLoad = new ArrayList<DataSetObserver>(); private ArrayList<DataSetObserver> observersWaitingForLoad = new ArrayList<DataSetObserver>();
private Campaign campaign;
public ContributionsActivity() { public ContributionsActivity() {
super(WikiAccountAuthenticator.COMMONS_ACCOUNT_TYPE); super(WikiAccountAuthenticator.COMMONS_ACCOUNT_TYPE);
@ -53,7 +50,7 @@ public class ContributionsActivity
private boolean isUploadServiceConnected; private boolean isUploadServiceConnected;
private ServiceConnection uploadServiceConnection = new ServiceConnection() { private ServiceConnection uploadServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName componentName, IBinder binder) { public void onServiceConnected(ComponentName componentName, IBinder binder) {
uploadService = (UploadService) ((HandlerService.HandlerServiceLocalBinder)binder).getService(); uploadService = (UploadService) ((HandlerService.HandlerServiceLocalBinder) binder).getService();
isUploadServiceConnected = true; isUploadServiceConnected = true;
} }
@ -64,11 +61,10 @@ public class ContributionsActivity
}; };
@Override @Override
protected void onDestroy() { protected void onDestroy() {
super.onDestroy(); super.onDestroy();
if(isUploadServiceConnected) { if (isUploadServiceConnected) {
unbindService(uploadServiceConnection); unbindService(uploadServiceConnection);
} }
} }
@ -115,16 +111,11 @@ public class ContributionsActivity
setTitle(R.string.title_activity_contributions); setTitle(R.string.title_activity_contributions);
setContentView(R.layout.activity_contributions); setContentView(R.layout.activity_contributions);
if(getIntent().hasExtra("campaign")) { contributionsList = (ContributionsListFragment) getSupportFragmentManager().findFragmentById(R.id.contributionsListFragment);
this.campaign = (Campaign) getIntent().getSerializableExtra("campaign");
this.setTitle(campaign.getTitle());
}
contributionsList = (ContributionsListFragment)getSupportFragmentManager().findFragmentById(R.id.contributionsListFragment);
getSupportFragmentManager().addOnBackStackChangedListener(this); getSupportFragmentManager().addOnBackStackChangedListener(this);
if (savedInstanceState != null) { 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. // onBackStackChanged uses mediaDetails.isVisible() but this returns false now.
// Use the saved value from before pause or orientation change. // Use the saved value from before pause or orientation change.
if (mediaDetails != null && savedInstanceState.getBoolean("mediaDetailsVisible")) { if (mediaDetails != null && savedInstanceState.getBoolean("mediaDetailsVisible")) {
@ -143,7 +134,7 @@ public class ContributionsActivity
} }
private void showDetail(int i) { private void showDetail(int i) {
if(mediaDetails == null ||!mediaDetails.isVisible()) { if (mediaDetails == null || !mediaDetails.isVisible()) {
mediaDetails = new MediaDetailPagerFragment(); mediaDetails = new MediaDetailPagerFragment();
this.getSupportFragmentManager() this.getSupportFragmentManager()
.beginTransaction() .beginTransaction()
@ -158,7 +149,7 @@ public class ContributionsActivity
public void retryUpload(int i) { public void retryUpload(int i) {
allContributions.moveToPosition(i); allContributions.moveToPosition(i);
Contribution c = Contribution.fromCursor(allContributions); Contribution c = Contribution.fromCursor(allContributions);
if(c.getState() == Contribution.STATE_FAILED) { if (c.getState() == Contribution.STATE_FAILED) {
uploadService.queue(UploadService.ACTION_UPLOAD_FILE, c); uploadService.queue(UploadService.ACTION_UPLOAD_FILE, c);
Log.d("Commons", "Restarting for" + c.toContentValues().toString()); Log.d("Commons", "Restarting for" + c.toContentValues().toString());
} else { } else {
@ -169,7 +160,7 @@ public class ContributionsActivity
public void deleteUpload(int i) { public void deleteUpload(int i) {
allContributions.moveToPosition(i); allContributions.moveToPosition(i);
Contribution c = Contribution.fromCursor(allContributions); Contribution c = Contribution.fromCursor(allContributions);
if(c.getState() == Contribution.STATE_FAILED) { if (c.getState() == Contribution.STATE_FAILED) {
Log.d("Commons", "Deleting failed contrib " + c.toContentValues().toString()); Log.d("Commons", "Deleting failed contrib " + c.toContentValues().toString());
c.setContentProviderClient(getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY)); c.setContentProviderClient(getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY));
c.delete(); c.delete();
@ -180,9 +171,9 @@ public class ContributionsActivity
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) { switch (item.getItemId()) {
case android.R.id.home: case android.R.id.home:
if(mediaDetails.isVisible()) { if (mediaDetails.isVisible()) {
getSupportFragmentManager().popBackStack(); getSupportFragmentManager().popBackStack();
} }
return true; return true;
@ -208,54 +199,42 @@ public class ContributionsActivity
} }
public Loader onCreateLoader(int i, Bundle bundle) { public Loader onCreateLoader(int i, Bundle bundle) {
if(campaign == null) {
return new CursorLoader(this, ContributionsContentProvider.BASE_URI, Contribution.Table.ALL_FIELDS, CONTRIBUTION_SELECTION, null, CONTRIBUTION_SORT); 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) { 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);
}
getSupportActionBar().setSubtitle(getResources().getQuantityString(R.plurals.contributions_subtitle, cursor.getCount(), cursor.getCount())); Cursor cursor = (Cursor) result;
if (contributionsList.getAdapter() == null) {
contributionsList.setAdapter(new ContributionsListAdapter(this, cursor, 0));
} else { } else {
if(contributionsList.getAdapter() == null) { ((CursorAdapter) contributionsList.getAdapter()).swapCursor(cursor);
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(); notifyAndMigrateDataSetObservers();
} }
public void onLoaderReset(Loader cursorLoader) { public void onLoaderReset(Loader cursorLoader) {
if(campaign == null) {
((CursorAdapter) contributionsList.getAdapter()).swapCursor(null); ((CursorAdapter) contributionsList.getAdapter()).swapCursor(null);
} else {
contributionsList.setAdapter(null);
}
} }
public Media getMediaAtPosition(int i) { public Media getMediaAtPosition(int i) {
if (contributionsList.getAdapter() == null) { if (contributionsList.getAdapter() == null) {
// not yet ready to return data // not yet ready to return data
return null; return null;
} else if(campaign == null) {
return Contribution.fromCursor((Cursor) contributionsList.getAdapter().getItem(i));
} else { } else {
return (Media) contributionsList.getAdapter().getItem(i); return Contribution.fromCursor((Cursor) contributionsList.getAdapter().getItem(i));
} }
} }
public int getTotalMediaCount() { public int getTotalMediaCount() {
if(contributionsList.getAdapter() == null) { if (contributionsList.getAdapter() == null) {
return 0; return 0;
} }
return contributionsList.getAdapter().getCount(); return contributionsList.getAdapter().getCount();
@ -299,16 +278,13 @@ public class ContributionsActivity
} }
public void onBackStackChanged() { public void onBackStackChanged() {
if(mediaDetails != null && mediaDetails.isVisible()) { if (mediaDetails != null && mediaDetails.isVisible()) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} else { } else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false); getSupportActionBar().setDisplayHomeAsUpEnabled(false);
} }
} }
public Campaign getCurrentCampaign() {
return campaign;
}
public void refreshSource() { public void refreshSource() {
getSupportLoaderManager().restartLoader(0, null, this); 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.data.*;
import fr.free.nrw.commons.CommonsApplication; 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 = 1;
private static final int CONTRIBUTIONS_ID = 2; private static final int CONTRIBUTIONS_ID = 2;
@ -21,6 +21,7 @@ public class ContributionsContentProvider extends ContentProvider{
public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH); public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);
private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static { static {
uriMatcher.addURI(AUTHORITY, BASE_PATH, CONTRIBUTIONS); uriMatcher.addURI(AUTHORITY, BASE_PATH, CONTRIBUTIONS);
uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", CONTRIBUTIONS_ID); uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", CONTRIBUTIONS_ID);
@ -32,9 +33,10 @@ public class ContributionsContentProvider extends ContentProvider{
} }
private DBOpenHelper dbOpenHelper; private DBOpenHelper dbOpenHelper;
@Override @Override
public boolean onCreate() { public boolean onCreate() {
dbOpenHelper = ((CommonsApplication)this.getContext().getApplicationContext()).getDbOpenHelper(); dbOpenHelper = ((CommonsApplication) this.getContext().getApplicationContext()).getDbOpenHelper();
return false; return false;
} }
@ -48,7 +50,7 @@ public class ContributionsContentProvider extends ContentProvider{
SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
Cursor cursor; Cursor cursor;
switch(uriType) { switch (uriType) {
case CONTRIBUTIONS: case CONTRIBUTIONS:
cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder); cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
break; break;
@ -56,7 +58,7 @@ public class ContributionsContentProvider extends ContentProvider{
cursor = queryBuilder.query(db, cursor = queryBuilder.query(db,
Contribution.Table.ALL_FIELDS, Contribution.Table.ALL_FIELDS,
"_id = ?", "_id = ?",
new String[] { uri.getLastPathSegment() }, new String[]{uri.getLastPathSegment()},
null, null,
null, null,
sortOrder sortOrder
@ -99,12 +101,12 @@ public class ContributionsContentProvider extends ContentProvider{
SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
switch(uriType) { switch (uriType) {
case CONTRIBUTIONS_ID: case CONTRIBUTIONS_ID:
Log.d("Commons", "Deleting contribution id " + uri.getLastPathSegment()); Log.d("Commons", "Deleting contribution id " + uri.getLastPathSegment());
rows = db.delete(Contribution.Table.TABLE_NAME, rows = db.delete(Contribution.Table.TABLE_NAME,
"_id = ?", "_id = ?",
new String[] { uri.getLastPathSegment() } new String[]{uri.getLastPathSegment()}
); );
break; break;
default: default:
@ -122,7 +124,7 @@ public class ContributionsContentProvider extends ContentProvider{
sqlDB.beginTransaction(); sqlDB.beginTransaction();
switch (uriType) { switch (uriType) {
case CONTRIBUTIONS: case CONTRIBUTIONS:
for(ContentValues value: values) { for (ContentValues value : values) {
Log.d("Commons", "Inserting! " + value.toString()); Log.d("Commons", "Inserting! " + value.toString());
sqlDB.insert(Contribution.Table.TABLE_NAME, null, value); sqlDB.insert(Contribution.Table.TABLE_NAME, null, value);
} }
@ -162,7 +164,7 @@ public class ContributionsContentProvider extends ContentProvider{
rowsUpdated = sqlDB.update(Contribution.Table.TABLE_NAME, rowsUpdated = sqlDB.update(Contribution.Table.TABLE_NAME,
contentValues, contentValues,
Contribution.Table.COLUMN_ID + " = ?", Contribution.Table.COLUMN_ID + " = ?",
new String[] { String.valueOf(id) } ); new String[]{String.valueOf(id)});
} else { } else {
throw new IllegalArgumentException("Parameter `selection` should be empty when updating an ID"); throw new IllegalArgumentException("Parameter `selection` should be empty when updating an ID");
} }

View file

@ -19,7 +19,8 @@ import fr.free.nrw.commons.R;
class ContributionsListAdapter extends CursorAdapter { class ContributionsListAdapter extends CursorAdapter {
private DisplayImageOptions contributionDisplayOptions = Utils.getGenericDisplayOptions().build();; private DisplayImageOptions contributionDisplayOptions = Utils.getGenericDisplayOptions().build();
;
private Activity activity; private Activity activity;
public ContributionsListAdapter(Activity activity, Cursor c, int flags) { public ContributionsListAdapter(Activity activity, Cursor c, int flags) {
@ -36,14 +37,14 @@ class ContributionsListAdapter extends CursorAdapter {
@Override @Override
public void bindView(View view, Context context, Cursor cursor) { public void bindView(View view, Context context, Cursor cursor) {
final ContributionViewHolder views = (ContributionViewHolder)view.getTag(); final ContributionViewHolder views = (ContributionViewHolder) view.getTag();
final Contribution contribution = Contribution.fromCursor(cursor); final Contribution contribution = Contribution.fromCursor(cursor);
String actualUrl = (contribution.getLocalUri() != null && !TextUtils.isEmpty(contribution.getLocalUri().toString())) ? contribution.getLocalUri().toString() : contribution.getThumbnailUrl(640); String actualUrl = (contribution.getLocalUri() != null && !TextUtils.isEmpty(contribution.getLocalUri().toString())) ? contribution.getLocalUri().toString() : contribution.getThumbnailUrl(640);
if(views.url == null || !views.url.equals(actualUrl)) { if (views.url == null || !views.url.equals(actualUrl)) {
if(actualUrl.startsWith("http")) { if (actualUrl.startsWith("http")) {
MediaWikiImageView mwImageView = (MediaWikiImageView)views.imageView; MediaWikiImageView mwImageView = (MediaWikiImageView) views.imageView;
mwImageView.setMedia(contribution, ((CommonsApplication) activity.getApplicationContext()).getImageLoader()); mwImageView.setMedia(contribution, ((CommonsApplication) activity.getApplicationContext()).getImageLoader());
// FIXME: For transparent images // FIXME: For transparent images
} else { } else {
@ -51,7 +52,7 @@ class ContributionsListAdapter extends CursorAdapter {
@Override @Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if(loadedImage.hasAlpha()) { if (loadedImage.hasAlpha()) {
views.imageView.setBackgroundResource(android.R.color.white); views.imageView.setBackgroundResource(android.R.color.white);
} }
views.seqNumView.setVisibility(View.GONE); views.seqNumView.setVisibility(View.GONE);
@ -60,7 +61,7 @@ class ContributionsListAdapter extends CursorAdapter {
@Override @Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) { public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
super.onLoadingFailed(imageUri, view, failReason); super.onLoadingFailed(imageUri, view, failReason);
MediaWikiImageView mwImageView = (MediaWikiImageView)views.imageView; MediaWikiImageView mwImageView = (MediaWikiImageView) views.imageView;
mwImageView.setMedia(contribution, ((CommonsApplication) activity.getApplicationContext()).getImageLoader()); mwImageView.setMedia(contribution, ((CommonsApplication) activity.getApplicationContext()).getImageLoader());
} }
}); });
@ -68,8 +69,8 @@ class ContributionsListAdapter extends CursorAdapter {
views.url = actualUrl; views.url = actualUrl;
} }
BitmapDrawable actualImageDrawable = (BitmapDrawable)views.imageView.getDrawable(); BitmapDrawable actualImageDrawable = (BitmapDrawable) views.imageView.getDrawable();
if(actualImageDrawable != null && actualImageDrawable.getBitmap() != null && actualImageDrawable.getBitmap().hasAlpha()) { if (actualImageDrawable != null && actualImageDrawable.getBitmap() != null && actualImageDrawable.getBitmap().hasAlpha()) {
views.imageView.setBackgroundResource(android.R.color.white); views.imageView.setBackgroundResource(android.R.color.white);
} else { } else {
views.imageView.setBackgroundDrawable(null); views.imageView.setBackgroundDrawable(null);
@ -80,7 +81,7 @@ class ContributionsListAdapter extends CursorAdapter {
views.seqNumView.setText(String.valueOf(cursor.getPosition() + 1)); views.seqNumView.setText(String.valueOf(cursor.getPosition() + 1));
views.seqNumView.setVisibility(View.VISIBLE); views.seqNumView.setVisibility(View.VISIBLE);
switch(contribution.getState()) { switch (contribution.getState()) {
case Contribution.STATE_COMPLETED: case Contribution.STATE_COMPLETED:
views.stateView.setVisibility(View.GONE); views.stateView.setVisibility(View.GONE);
views.progressView.setVisibility(View.GONE); views.progressView.setVisibility(View.GONE);
@ -96,10 +97,10 @@ class ContributionsListAdapter extends CursorAdapter {
views.progressView.setVisibility(View.VISIBLE); views.progressView.setVisibility(View.VISIBLE);
long total = contribution.getDataLength(); long total = contribution.getDataLength();
long transferred = contribution.getTransferred(); long transferred = contribution.getTransferred();
if(transferred == 0 || transferred >= total) { if (transferred == 0 || transferred >= total) {
views.progressView.setIndeterminate(true); views.progressView.setIndeterminate(true);
} else { } else {
views.progressView.setProgress((int)(((double)transferred / (double)total) * 100)); views.progressView.setProgress((int) (((double) transferred / (double) total) * 100));
} }
break; break;
case Contribution.STATE_FAILED: case Contribution.STATE_FAILED:

View file

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

View file

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

View file

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

View file

@ -4,11 +4,10 @@ import android.content.*;
import android.database.sqlite.*; import android.database.sqlite.*;
import fr.free.nrw.commons.modifications.ModifierSequence; 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.category.Category;
import fr.free.nrw.commons.contributions.*; 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 String DATABASE_NAME = "commons.db";
private static final int DATABASE_VERSION = 6; private static final int DATABASE_VERSION = 6;
@ -22,7 +21,6 @@ public class DBOpenHelper extends SQLiteOpenHelper{
Contribution.Table.onCreate(sqLiteDatabase); Contribution.Table.onCreate(sqLiteDatabase);
ModifierSequence.Table.onCreate(sqLiteDatabase); ModifierSequence.Table.onCreate(sqLiteDatabase);
Category.Table.onCreate(sqLiteDatabase); Category.Table.onCreate(sqLiteDatabase);
Campaign.Table.onCreate(sqLiteDatabase);
} }
@Override @Override
@ -30,6 +28,5 @@ public class DBOpenHelper extends SQLiteOpenHelper{
Contribution.Table.onUpdate(sqLiteDatabase, from, to); Contribution.Table.onUpdate(sqLiteDatabase, from, to);
ModifierSequence.Table.onUpdate(sqLiteDatabase, from, to); ModifierSequence.Table.onUpdate(sqLiteDatabase, from, to);
Category.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.ArrayList;
import java.util.List; import java.util.List;
public class CategoryImagesLoader extends AsyncTaskLoader<List<Media>>{ public class CategoryImagesLoader extends AsyncTaskLoader<List<Media>> {
private final CommonsApplication app; private final CommonsApplication app;
private final String category; private final String category;
@ -49,7 +49,7 @@ public class CategoryImagesLoader extends AsyncTaskLoader<List<Media>>{
Log.d("Commons", Utils.getStringFromDOM(result.getDocument())); Log.d("Commons", Utils.getStringFromDOM(result.getDocument()));
List<ApiResult> members = result.getNodes("/api/query/categorymembers/cm"); List<ApiResult> members = result.getNodes("/api/query/categorymembers/cm");
for(ApiResult member : members) { for (ApiResult member : members) {
mediaList.add(new Media(member.getString("@title"))); mediaList.add(new Media(member.getString("@title")));
} }
return mediaList; 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.OnGlobalLayoutListener layoutListener; // for layout stuff, only used once!
private ViewTreeObserver.OnScrollChangedListener scrollListener; private ViewTreeObserver.OnScrollChangedListener scrollListener;
DataSetObserver dataObserver; DataSetObserver dataObserver;
private AsyncTask<Void,Void,Boolean> detailFetchTask; private AsyncTask<Void, Void, Boolean> detailFetchTask;
private LicenseList licenseList; private LicenseList licenseList;
@ -84,9 +84,9 @@ public class MediaDetailFragment extends SherlockFragment {
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 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"); editable = savedInstanceState.getBoolean("editable");
index = savedInstanceState.getInt("index"); index = savedInstanceState.getInt("index");
initialListTop = savedInstanceState.getInt("listTop"); initialListTop = savedInstanceState.getInt("listTop");
@ -169,9 +169,9 @@ public class MediaDetailFragment extends SherlockFragment {
private void displayMediaDetails(final Media media) { private void displayMediaDetails(final Media media) {
String actualUrl = (media.getLocalUri() != null && !TextUtils.isEmpty(media.getLocalUri().toString())) ? media.getLocalUri().toString() : media.getThumbnailUrl(640); String actualUrl = (media.getLocalUri() != null && !TextUtils.isEmpty(media.getLocalUri().toString())) ? media.getLocalUri().toString() : media.getThumbnailUrl(640);
if(actualUrl.startsWith("http")) { if (actualUrl.startsWith("http")) {
ImageLoader loader = ((CommonsApplication)getActivity().getApplicationContext()).getImageLoader(); ImageLoader loader = ((CommonsApplication) getActivity().getApplicationContext()).getImageLoader();
MediaWikiImageView mwImage = (MediaWikiImageView)image; MediaWikiImageView mwImage = (MediaWikiImageView) image;
mwImage.setLoadingView(loadingProgress); //FIXME: Set this as an attribute mwImage.setLoadingView(loadingProgress); //FIXME: Set this as an attribute
mwImage.setMedia(media, loader); mwImage.setMedia(media, loader);
Log.d("Volley", actualUrl); Log.d("Volley", actualUrl);
@ -241,7 +241,7 @@ public class MediaDetailFragment extends SherlockFragment {
loadingProgress.setVisibility(View.GONE); loadingProgress.setVisibility(View.GONE);
loadingFailed.setVisibility(View.GONE); loadingFailed.setVisibility(View.GONE);
image.setVisibility(View.VISIBLE); image.setVisibility(View.VISIBLE);
if(bitmap.hasAlpha()) { if (bitmap.hasAlpha()) {
image.setBackgroundResource(android.R.color.white); image.setBackgroundResource(android.R.color.white);
} }
} }
@ -276,7 +276,7 @@ public class MediaDetailFragment extends SherlockFragment {
} }
if (scrollListener != null) { if (scrollListener != null) {
getView().getViewTreeObserver().removeOnScrollChangedListener(scrollListener); getView().getViewTreeObserver().removeOnScrollChangedListener(scrollListener);
scrollListener = null; scrollListener = null;
} }
if (dataObserver != null) { if (dataObserver != null) {
detailProvider.unregisterDataSetObserver(dataObserver); detailProvider.unregisterDataSetObserver(dataObserver);
@ -296,7 +296,7 @@ public class MediaDetailFragment extends SherlockFragment {
private View buildCatLabel(String cat) { private View buildCatLabel(String cat) {
final String catName = cat; final String catName = cat;
final View item = getLayoutInflater(null).inflate(R.layout.detail_category_item, null, false); 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); textView.setText(cat);
if (categoriesLoaded && categoriesPresent) { if (categoriesLoaded && categoriesPresent) {
@ -317,7 +317,7 @@ public class MediaDetailFragment extends SherlockFragment {
// You must face the darkness alone // You must face the darkness alone
int scrollY = scrollView.getScrollY(); int scrollY = scrollView.getScrollY();
int scrollMax = getView().getHeight(); int scrollMax = getView().getHeight();
float scrollPercentage = (float)scrollY / (float)scrollMax; float scrollPercentage = (float) scrollY / (float) scrollMax;
final float transparencyMax = 0.75f; final float transparencyMax = 0.75f;
if (scrollPercentage > transparencyMax) { if (scrollPercentage > transparencyMax) {
scrollPercentage = transparencyMax; scrollPercentage = transparencyMax;

View file

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

View file

@ -14,7 +14,7 @@ public class CategoryModifier extends PageModifier {
public CategoryModifier(String... categories) { public CategoryModifier(String... categories) {
super(MODIFIER_NAME); super(MODIFIER_NAME);
JSONArray categoriesArray = new JSONArray(); JSONArray categoriesArray = new JSONArray();
for(String category: categories) { for (String category : categories) {
categoriesArray.put(category); categoriesArray.put(category);
} }
try { try {
@ -35,7 +35,7 @@ public class CategoryModifier extends PageModifier {
categories = params.optJSONArray(PARAM_CATEGORIES); categories = params.optJSONArray(PARAM_CATEGORIES);
StringBuffer categoriesString = new StringBuffer(); 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); String category = categories.optString(i);
categoriesString.append("\n[[Category:").append(category).append("]]"); 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.data.*;
import fr.free.nrw.commons.CommonsApplication; 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 = 1;
private static final int MODIFICATIONS_ID = 2; private static final int MODIFICATIONS_ID = 2;
@ -21,6 +21,7 @@ public class ModificationsContentProvider extends ContentProvider{
public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH); public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);
private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static { static {
uriMatcher.addURI(AUTHORITY, BASE_PATH, MODIFICATIONS); uriMatcher.addURI(AUTHORITY, BASE_PATH, MODIFICATIONS);
uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", MODIFICATIONS_ID); uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", MODIFICATIONS_ID);
@ -32,9 +33,10 @@ public class ModificationsContentProvider extends ContentProvider{
} }
private DBOpenHelper dbOpenHelper; private DBOpenHelper dbOpenHelper;
@Override @Override
public boolean onCreate() { public boolean onCreate() {
dbOpenHelper = ((CommonsApplication)this.getContext().getApplicationContext()).getDbOpenHelper(); dbOpenHelper = ((CommonsApplication) this.getContext().getApplicationContext()).getDbOpenHelper();
return false; return false;
} }
@ -45,7 +47,7 @@ public class ModificationsContentProvider extends ContentProvider{
int uriType = uriMatcher.match(uri); int uriType = uriMatcher.match(uri);
switch(uriType) { switch (uriType) {
case MODIFICATIONS: case MODIFICATIONS:
break; break;
default: default:
@ -90,8 +92,8 @@ public class ModificationsContentProvider extends ContentProvider{
String id = uri.getLastPathSegment(); String id = uri.getLastPathSegment();
sqlDB.delete(ModifierSequence.Table.TABLE_NAME, sqlDB.delete(ModifierSequence.Table.TABLE_NAME,
"_id = ?", "_id = ?",
new String[] { id } new String[]{id}
); );
return 1; return 1;
default: default:
throw new IllegalArgumentException("Unknown URI: " + uri); throw new IllegalArgumentException("Unknown URI: " + uri);
@ -106,7 +108,7 @@ public class ModificationsContentProvider extends ContentProvider{
sqlDB.beginTransaction(); sqlDB.beginTransaction();
switch (uriType) { switch (uriType) {
case MODIFICATIONS: case MODIFICATIONS:
for(ContentValues value: values) { for (ContentValues value : values) {
Log.d("Commons", "Inserting! " + value.toString()); Log.d("Commons", "Inserting! " + value.toString());
sqlDB.insert(ModifierSequence.Table.TABLE_NAME, null, value); sqlDB.insert(ModifierSequence.Table.TABLE_NAME, null, value);
} }
@ -146,7 +148,7 @@ public class ModificationsContentProvider extends ContentProvider{
rowsUpdated = sqlDB.update(ModifierSequence.Table.TABLE_NAME, rowsUpdated = sqlDB.update(ModifierSequence.Table.TABLE_NAME,
contentValues, contentValues,
ModifierSequence.Table.COLUMN_ID + " = ?", ModifierSequence.Table.COLUMN_ID + " = ?",
new String[] { String.valueOf(id) } ); new String[]{String.valueOf(id)});
} else { } else {
throw new IllegalArgumentException("Parameter `selection` should be empty when updating an ID"); 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 // 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"); Log.d("Commons", "No modifications to perform");
return; return;
} }
String authCookie; String authCookie;
try { try {
authCookie = AccountManager.get(getContext()).blockingGetAuthToken(account, "", false); authCookie = AccountManager.get(getContext()).blockingGetAuthToken(account, "", false);
} catch (OperationCanceledException e) { } catch (OperationCanceledException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} catch (IOException e) { } catch (IOException e) {
@ -75,7 +75,7 @@ public class ModificationsSyncAdapter extends AbstractThreadedSyncAdapter {
try { try {
contributionsClient = getContext().getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY); contributionsClient = getContext().getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY);
while(!allModifications.isAfterLast()) { while (!allModifications.isAfterLast()) {
ModifierSequence sequence = ModifierSequence.fromCursor(allModifications); ModifierSequence sequence = ModifierSequence.fromCursor(allModifications);
sequence.setContentProviderClient(contentProviderClient); sequence.setContentProviderClient(contentProviderClient);
Contribution contrib; Contribution contrib;
@ -89,7 +89,7 @@ public class ModificationsSyncAdapter extends AbstractThreadedSyncAdapter {
contributionCursor.moveToFirst(); contributionCursor.moveToFirst();
contrib = Contribution.fromCursor(contributionCursor); contrib = Contribution.fromCursor(contributionCursor);
if(contrib.getState() == Contribution.STATE_COMPLETED) { if (contrib.getState() == Contribution.STATE_COMPLETED) {
try { try {
requestResult = api.action("query") requestResult = api.action("query")
@ -104,7 +104,7 @@ public class ModificationsSyncAdapter extends AbstractThreadedSyncAdapter {
Log.d("Commons", "Page content is " + Utils.getStringFromDOM(requestResult.getDocument())); Log.d("Commons", "Page content is " + Utils.getStringFromDOM(requestResult.getDocument()));
String pageContent = requestResult.getString("/api/query/pages/page/revisions/rev"); 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 { try {
responseResult = api.action("edit") responseResult = api.action("edit")
@ -121,7 +121,7 @@ public class ModificationsSyncAdapter extends AbstractThreadedSyncAdapter {
Log.d("Commons", "Response is" + Utils.getStringFromDOM(responseResult.getDocument())); Log.d("Commons", "Response is" + Utils.getStringFromDOM(responseResult.getDocument()));
String result = responseResult.getString("/api/edit/@result"); String result = responseResult.getString("/api/edit/@result");
if(!result.equals("Success")) { if (!result.equals("Success")) {
// FIXME: Log this somewhere else // FIXME: Log this somewhere else
Log.d("Commons", "Non success result!" + result); Log.d("Commons", "Non success result!" + result);
} else { } else {
@ -132,7 +132,7 @@ public class ModificationsSyncAdapter extends AbstractThreadedSyncAdapter {
} }
} finally { } finally {
if(contributionsClient != null) { if (contributionsClient != null) {
contributionsClient.release(); contributionsClient.release();
} }

View file

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

View file

@ -7,9 +7,9 @@ public abstract class PageModifier {
public static PageModifier fromJSON(JSONObject data) { public static PageModifier fromJSON(JSONObject data) {
String name = data.optString("name"); String name = data.optString("name");
if(name.equals(CategoryModifier.MODIFIER_NAME)) { if (name.equals(CategoryModifier.MODIFIER_NAME)) {
return new CategoryModifier(data.optJSONObject("data")); 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")); 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); Pattern templateStartPattern = Pattern.compile("\\{\\{" + templateNormalized, Pattern.CASE_INSENSITIVE);
Matcher matcher = templateStartPattern.matcher(pageContents); Matcher matcher = templateStartPattern.matcher(pageContents);
while(matcher.find()) { while (matcher.find()) {
int braceCount = 1; int braceCount = 1;
int startIndex = matcher.start(); int startIndex = matcher.start();
int curIndex = matcher.end(); int curIndex = matcher.end();
Matcher openMatch = PATTERN_TEMPLATE_OPEN.matcher(pageContents); Matcher openMatch = PATTERN_TEMPLATE_OPEN.matcher(pageContents);
Matcher closeMatch = PATTERN_TEMPLATE_CLOSE.matcher(pageContents); Matcher closeMatch = PATTERN_TEMPLATE_CLOSE.matcher(pageContents);
while(curIndex < pageContents.length()) { while (curIndex < pageContents.length()) {
boolean openFound = openMatch.find(curIndex); boolean openFound = openMatch.find(curIndex);
boolean closeFound = closeMatch.find(curIndex); boolean closeFound = closeMatch.find(curIndex);
if(openFound && (!closeFound || openMatch.start() < closeMatch.start())) { if (openFound && (!closeFound || openMatch.start() < closeMatch.start())) {
braceCount++; braceCount++;
curIndex = openMatch.end(); curIndex = openMatch.end();
} else if (closeFound) { } else if (closeFound) {
@ -72,8 +72,8 @@ public class TemplateRemoveModifier extends PageModifier {
} }
// Strip trailing whitespace // Strip trailing whitespace
while(curIndex < pageContents.length()) { while (curIndex < pageContents.length()) {
if(pageContents.charAt(curIndex) == ' ' || pageContents.charAt(curIndex) == '\n') { if (pageContents.charAt(curIndex) == ' ' || pageContents.charAt(curIndex) == '\n') {
curIndex++; curIndex++;
} else { } else {
break; 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.contributions.*;
import fr.free.nrw.commons.media.*; import fr.free.nrw.commons.media.*;
public class MultipleShareActivity public class MultipleShareActivity
extends AuthenticatedActivity extends AuthenticatedActivity
implements MediaDetailPagerFragment.MediaDetailProvider, implements MediaDetailPagerFragment.MediaDetailProvider,
AdapterView.OnItemClickListener, AdapterView.OnItemClickListener,
FragmentManager.OnBackStackChangedListener, FragmentManager.OnBackStackChangedListener,
MultipleUploadListFragment.OnMultipleUploadInitiatedHandler, MultipleUploadListFragment.OnMultipleUploadInitiatedHandler,
CategorizationFragment.OnCategoriesSaveHandler { CategorizationFragment.OnCategoriesSaveHandler {
private CommonsApplication app; private CommonsApplication app;
private ArrayList<Contribution> photosList = null; private ArrayList<Contribution> photosList = null;
@ -51,14 +51,14 @@ public class MultipleShareActivity
} }
public int getTotalMediaCount() { public int getTotalMediaCount() {
if(photosList == null) { if (photosList == null) {
return 0; return 0;
} }
return photosList.size(); return photosList.size();
} }
public void notifyDatasetChanged() { public void notifyDatasetChanged() {
if(uploadsList != null) { if (uploadsList != null) {
uploadsList.notifyDatasetChanged(); uploadsList.notifyDatasetChanged();
} }
} }
@ -84,14 +84,14 @@ public class MultipleShareActivity
dialog.setTitle(getResources().getQuantityString(R.plurals.starting_multiple_uploads, photosList.size(), photosList.size())); dialog.setTitle(getResources().getQuantityString(R.plurals.starting_multiple_uploads, photosList.size(), photosList.size()));
dialog.show(); dialog.show();
for(int i = 0; i < photosList.size(); i++) { for (int i = 0; i < photosList.size(); i++) {
Contribution up = photosList.get(i); Contribution up = photosList.get(i);
final int uploadCount = i + 1; // Goddamn Java final int uploadCount = i + 1; // Goddamn Java
uploadController.startUpload(up, new UploadController.ContributionUploadProgress() { uploadController.startUpload(up, new UploadController.ContributionUploadProgress() {
public void onUploadStarted(Contribution contribution) { public void onUploadStarted(Contribution contribution) {
dialog.setProgress(uploadCount); dialog.setProgress(uploadCount);
if(uploadCount == photosList.size()) { if (uploadCount == photosList.size()) {
dialog.dismiss(); dialog.dismiss();
Toast startingToast = Toast.makeText(getApplicationContext(), R.string.uploading_started, Toast.LENGTH_LONG); Toast startingToast = Toast.makeText(getApplicationContext(), R.string.uploading_started, Toast.LENGTH_LONG);
startingToast.show(); startingToast.show();
@ -103,7 +103,7 @@ public class MultipleShareActivity
uploadsList.setImageOnlyMode(true); uploadsList.setImageOnlyMode(true);
categorizationFragment = (CategorizationFragment) this.getSupportFragmentManager().findFragmentByTag("categorization"); categorizationFragment = (CategorizationFragment) this.getSupportFragmentManager().findFragmentByTag("categorization");
if(categorizationFragment == null) { if (categorizationFragment == null) {
categorizationFragment = new CategorizationFragment(); categorizationFragment = new CategorizationFragment();
} }
// FIXME: Stops the keyboard from being shown 'stale' while moving out of this fragment into the next // FIXME: Stops the keyboard from being shown 'stale' while moving out of this fragment into the next
@ -118,9 +118,9 @@ public class MultipleShareActivity
} }
public void onCategoriesSave(ArrayList<String> categories) { public void onCategoriesSave(ArrayList<String> categories) {
if(categories.size() > 0) { if (categories.size() > 0) {
ContentProviderClient client = getContentResolver().acquireContentProviderClient(ModificationsContentProvider.AUTHORITY); ContentProviderClient client = getContentResolver().acquireContentProviderClient(ModificationsContentProvider.AUTHORITY);
for(Contribution contribution: photosList) { for (Contribution contribution : photosList) {
ModifierSequence categoriesSequence = new ModifierSequence(contribution.getContentUri()); ModifierSequence categoriesSequence = new ModifierSequence(contribution.getContentUri());
categoriesSequence.queueModifier(new CategoryModifier(categories.toArray(new String[]{}))); categoriesSequence.queueModifier(new CategoryModifier(categories.toArray(new String[]{})));
@ -145,9 +145,9 @@ public class MultipleShareActivity
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) { switch (item.getItemId()) {
case android.R.id.home: case android.R.id.home:
if(mediaDetails.isVisible()) { if (mediaDetails.isVisible()) {
getSupportFragmentManager().popBackStack(); getSupportFragmentManager().popBackStack();
} }
return true; return true;
@ -161,9 +161,9 @@ public class MultipleShareActivity
uploadController = new UploadController(this); uploadController = new UploadController(this);
setContentView(R.layout.activity_multiple_uploads); setContentView(R.layout.activity_multiple_uploads);
app = (CommonsApplication)this.getApplicationContext(); app = (CommonsApplication) this.getApplicationContext();
if(savedInstanceState != null) { if (savedInstanceState != null) {
photosList = savedInstanceState.getParcelableArrayList("uploadsList"); photosList = savedInstanceState.getParcelableArrayList("uploadsList");
} }
@ -180,7 +180,7 @@ public class MultipleShareActivity
} }
private void showDetail(int i) { private void showDetail(int i) {
if(mediaDetails == null ||!mediaDetails.isVisible()) { if (mediaDetails == null || !mediaDetails.isVisible()) {
mediaDetails = new MediaDetailPagerFragment(true); mediaDetails = new MediaDetailPagerFragment(true);
this.getSupportFragmentManager() this.getSupportFragmentManager()
.beginTransaction() .beginTransaction()
@ -203,11 +203,11 @@ public class MultipleShareActivity
app.getApi().setAuthCookie(authCookie); app.getApi().setAuthCookie(authCookie);
Intent intent = getIntent(); Intent intent = getIntent();
if(intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE)) { if (intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
if(photosList == null) { if (photosList == null) {
photosList = new ArrayList<Contribution>(); photosList = new ArrayList<Contribution>();
ArrayList<Uri> urisList = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); ArrayList<Uri> urisList = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
for(int i=0; i < urisList.size(); i++) { for (int i = 0; i < urisList.size(); i++) {
Contribution up = new Contribution(); Contribution up = new Contribution();
Uri uri = urisList.get(i); Uri uri = urisList.get(i);
up.setLocalUri(uri); up.setLocalUri(uri);
@ -220,8 +220,8 @@ public class MultipleShareActivity
} }
uploadsList = (MultipleUploadListFragment) getSupportFragmentManager().findFragmentByTag("uploadsList"); uploadsList = (MultipleUploadListFragment) getSupportFragmentManager().findFragmentByTag("uploadsList");
if(uploadsList == null) { if (uploadsList == null) {
uploadsList = new MultipleUploadListFragment(); uploadsList = new MultipleUploadListFragment();
this.getSupportFragmentManager() this.getSupportFragmentManager()
.beginTransaction() .beginTransaction()
.add(R.id.uploadsFragmentContainer, uploadsList, "uploadsList") .add(R.id.uploadsFragmentContainer, uploadsList, "uploadsList")
@ -245,7 +245,7 @@ public class MultipleShareActivity
@Override @Override
public void onBackPressed() { public void onBackPressed() {
super.onBackPressed(); super.onBackPressed();
if(categorizationFragment != null && categorizationFragment.isVisible()) { if (categorizationFragment != null && categorizationFragment.isVisible()) {
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT) EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT)
.param("username", app.getCurrentAccount().name) .param("username", app.getCurrentAccount().name)
.param("categories-count", categorizationFragment.getCurrentSelectedCount()) .param("categories-count", categorizationFragment.getCurrentSelectedCount())
@ -264,7 +264,7 @@ public class MultipleShareActivity
} }
public void onBackStackChanged() { public void onBackStackChanged() {
if(mediaDetails != null && mediaDetails.isVisible()) { if (mediaDetails != null && mediaDetails.isVisible()) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} else { } else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false); getSupportActionBar().setDisplayHomeAsUpEnabled(false);

View file

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

View file

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

View file

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

View file

@ -15,8 +15,7 @@ import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.HandlerService; import fr.free.nrw.commons.HandlerService;
import fr.free.nrw.commons.Prefs; import fr.free.nrw.commons.Prefs;
import fr.free.nrw.commons.Utils; 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.io.IOException;
import java.util.Date; import java.util.Date;
@ -25,7 +24,6 @@ public class UploadController {
private UploadService uploadService; private UploadService uploadService;
private final Activity activity; private final Activity activity;
private Campaign campaign;
final CommonsApplication app; final CommonsApplication app;
public interface ContributionUploadProgress { public interface ContributionUploadProgress {
@ -34,18 +32,14 @@ public class UploadController {
public UploadController(Activity activity) { public UploadController(Activity activity) {
this.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 boolean isUploadServiceConnected;
private ServiceConnection uploadServiceConnection = new ServiceConnection() { private ServiceConnection uploadServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName componentName, IBinder binder) { public void onServiceConnected(ComponentName componentName, IBinder binder) {
uploadService = (UploadService) ((HandlerService.HandlerServiceLocalBinder)binder).getService(); uploadService = (UploadService) ((HandlerService.HandlerServiceLocalBinder) binder).getService();
isUploadServiceConnected = true; isUploadServiceConnected = true;
} }
@ -63,7 +57,7 @@ public class UploadController {
} }
public void cleanup() { public void cleanup() {
if(isUploadServiceConnected) { if (isUploadServiceConnected) {
activity.unbindService(uploadServiceConnection); activity.unbindService(uploadServiceConnection);
} }
} }
@ -77,15 +71,13 @@ public class UploadController {
if (extension != null && extension.toLowerCase().equals("jpeg")) { if (extension != null && extension.toLowerCase().equals("jpeg")) {
extension = "jpg"; extension = "jpg";
} }
if(extension != null && !title.toLowerCase().endsWith(extension.toLowerCase())) { if (extension != null && !title.toLowerCase().endsWith(extension.toLowerCase())) {
title += "." + extension; title += "." + extension;
} }
if(campaign == null) {
contribution = new Contribution(mediaUri, null, title, description, -1, null, null, app.getCurrentAccount().name, CommonsApplication.DEFAULT_EDIT_SUMMARY); 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.setTag("mimeType", mimeType);
contribution.setSource(source); contribution.setSource(source);
@ -95,11 +87,11 @@ public class UploadController {
public void startUpload(final Contribution contribution, final ContributionUploadProgress onComplete) { public void startUpload(final Contribution contribution, final ContributionUploadProgress onComplete) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
if(TextUtils.isEmpty(contribution.getCreator())) { if (TextUtils.isEmpty(contribution.getCreator())) {
contribution.setCreator(app.getCurrentAccount().name); contribution.setCreator(app.getCurrentAccount().name);
} }
if(contribution.getDescription() == null) { if (contribution.getDescription() == null) {
contribution.setDescription(""); contribution.setDescription("");
} }
@ -115,30 +107,30 @@ public class UploadController {
protected Contribution doInBackground(Void... voids /* stare into you */) { protected Contribution doInBackground(Void... voids /* stare into you */) {
long length; long length;
try { try {
if(contribution.getDataLength() <= 0) { if (contribution.getDataLength() <= 0) {
length = activity.getContentResolver().openAssetFileDescriptor(contribution.getLocalUri(), "r").getLength(); length = activity.getContentResolver().openAssetFileDescriptor(contribution.getLocalUri(), "r").getLength();
if(length == -1) { if (length == -1) {
// Let us find out the long way! // Let us find out the long way!
length = Utils.countBytes(activity.getContentResolver().openInputStream(contribution.getLocalUri())); length = Utils.countBytes(activity.getContentResolver().openInputStream(contribution.getLocalUri()));
} }
contribution.setDataLength(length); contribution.setDataLength(length);
} }
} catch(IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
String mimeType = (String)contribution.getTag("mimeType"); String mimeType = (String) contribution.getTag("mimeType");
if(mimeType == null || TextUtils.isEmpty(mimeType) || mimeType.endsWith("*")) { if (mimeType == null || TextUtils.isEmpty(mimeType) || mimeType.endsWith("*")) {
mimeType = activity.getContentResolver().getType(contribution.getLocalUri()); mimeType = activity.getContentResolver().getType(contribution.getLocalUri());
if(mimeType != null) { if (mimeType != null) {
contribution.setTag("mimeType", mimeType); 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(), Cursor cursor = activity.getContentResolver().query(contribution.getLocalUri(),
new String[]{MediaStore.Images.ImageColumns.DATE_TAKEN}, null, null, null); new String[]{MediaStore.Images.ImageColumns.DATE_TAKEN}, null, null, null);
if(cursor != null && cursor.getCount() != 0) { if (cursor != null && cursor.getCount() != 0) {
cursor.moveToFirst(); cursor.moveToFirst();
contribution.setDateCreated(new Date(cursor.getLong(0))); contribution.setDateCreated(new Date(cursor.getLong(0)));
} // FIXME: Alternate way of setting dateCreated if this data is not found } // 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 @Override
public void onProgress(long transferred, long total) { public void onProgress(long transferred, long total) {
Log.d("Commons", String.format("Uploaded %d of %d", transferred, total)); Log.d("Commons", String.format("Uploaded %d of %d", transferred, total));
if(!notificationTitleChanged) { if (!notificationTitleChanged) {
curProgressNotification.setContentTitle(notificationProgressTitle); curProgressNotification.setContentTitle(notificationProgressTitle);
notificationTitleChanged = true; notificationTitleChanged = true;
contribution.setState(Contribution.STATE_IN_PROGRESS); contribution.setState(Contribution.STATE_IN_PROGRESS);
} }
if(transferred == total) { if (transferred == total) {
// Completed! // Completed!
curProgressNotification.setContentTitle(notificationFinishingTitle); curProgressNotification.setContentTitle(notificationFinishingTitle);
curProgressNotification.setProgress(0, 100, true); curProgressNotification.setProgress(0, 100, true);
@ -110,7 +110,7 @@ public class UploadService extends HandlerService<Contribution> {
@Override @Override
protected void handle(int what, Contribution contribution) { protected void handle(int what, Contribution contribution) {
switch(what) { switch (what) {
case ACTION_UPLOAD_FILE: case ACTION_UPLOAD_FILE:
uploadContribution(contribution); uploadContribution(contribution);
break; break;
@ -148,14 +148,14 @@ public class UploadService extends HandlerService<Contribution> {
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { 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(); ContentValues failedValues = new ContentValues();
failedValues.put(Contribution.Table.COLUMN_STATE, Contribution.STATE_FAILED); failedValues.put(Contribution.Table.COLUMN_STATE, Contribution.STATE_FAILED);
int updated = getContentResolver().update(ContributionsContentProvider.BASE_URI, int updated = getContentResolver().update(ContributionsContentProvider.BASE_URI,
failedValues, failedValues,
Contribution.Table.COLUMN_STATE + " = ? OR " + Contribution.Table.COLUMN_STATE + " = ?", 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", "Set " + updated + " uploads to failed");
Log.d("Commons", "Flags is" + flags + " id is" + startId); Log.d("Commons", "Flags is" + flags + " id is" + startId);
@ -175,7 +175,7 @@ public class UploadService extends HandlerService<Contribution> {
try { try {
file = this.getContentResolver().openInputStream(contribution.getLocalUri()); file = this.getContentResolver().openInputStream(contribution.getLocalUri());
} catch(FileNotFoundException e) { } catch (FileNotFoundException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -195,9 +195,9 @@ public class UploadService extends HandlerService<Contribution> {
try { try {
String filename = findUniqueFilename(contribution.getFilename()); String filename = findUniqueFilename(contribution.getFilename());
if(!api.validateLogin()) { if (!api.validateLogin()) {
// Need to revalidate! // Need to revalidate!
if(app.revalidateAuthToken()) { if (app.revalidateAuthToken()) {
Log.d("Commons", "Successfully revalidated token!"); Log.d("Commons", "Successfully revalidated token!");
} else { } else {
Log.d("Commons", "Unable to revalidate :("); Log.d("Commons", "Unable to revalidate :(");
@ -222,7 +222,7 @@ public class UploadService extends HandlerService<Contribution> {
String resultStatus = result.getString("/api/upload/@result"); String resultStatus = result.getString("/api/upload/@result");
if(!resultStatus.equals("Success")) { if (!resultStatus.equals("Success")) {
String errorCode = result.getString("/api/error/@code"); String errorCode = result.getString("/api/error/@code");
showFailedNotification(contribution); showFailedNotification(contribution);
fr.free.nrw.commons.EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT) fr.free.nrw.commons.EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT)
@ -251,13 +251,13 @@ public class UploadService extends HandlerService<Contribution> {
.param("result", "success") .param("result", "success")
.log(); .log();
} }
} catch(IOException e) { } catch (IOException e) {
Log.d("Commons", "I have a network fuckup"); Log.d("Commons", "I have a network fuckup");
showFailedNotification(contribution); showFailedNotification(contribution);
return; return;
} finally { } finally {
toUpload--; toUpload--;
if(toUpload == 0) { if (toUpload == 0) {
// Sync modifications right after all uplaods are processed // Sync modifications right after all uplaods are processed
ContentResolver.requestSync(((CommonsApplication) getApplicationContext()).getCurrentAccount(), ModificationsContentProvider.AUTHORITY, new Bundle()); ContentResolver.requestSync(((CommonsApplication) getApplicationContext()).getCurrentAccount(), ModificationsContentProvider.AUTHORITY, new Bundle());
stopForeground(true); stopForeground(true);
@ -285,7 +285,7 @@ public class UploadService extends HandlerService<Contribution> {
return findUniqueFilename(fileName, 1); return findUniqueFilename(fileName, 1);
} }
private String findUniqueFilename(String fileName, int sequenceNumber) throws IOException { private String findUniqueFilename(String fileName, int sequenceNumber) throws IOException {
String sequenceFileName; String sequenceFileName;
if (sequenceNumber == 1) { if (sequenceNumber == 1) {
sequenceFileName = fileName; sequenceFileName = fileName;