diff --git a/libraries/DragSortListView b/libraries/DragSortListView index 67c6b1600..ac2a08c10 160000 --- a/libraries/DragSortListView +++ b/libraries/DragSortListView @@ -1 +1 @@ -Subproject commit 67c6b1600c27ea38c4b7e601e69ccfbdb6a3cfbf +Subproject commit ac2a08c10b37162c730f44acab67b284bcd0a52d diff --git a/libraries/MenuComponent b/libraries/MenuComponent index e29a94571..72c6fc5c5 160000 --- a/libraries/MenuComponent +++ b/libraries/MenuComponent @@ -1 +1 @@ -Subproject commit e29a94571fc82349d46b2911729a55e7ab9e34c4 +Subproject commit 72c6fc5c5ffa2b0dd882fc9f929ad39a7ca26c9b diff --git a/libraries/RefreshNow b/libraries/RefreshNow index 92cc3efc8..48af37e2d 160000 --- a/libraries/RefreshNow +++ b/libraries/RefreshNow @@ -1 +1 @@ -Subproject commit 92cc3efc8aa4a842b8601a918a33d4d1fe78d8dc +Subproject commit 48af37e2d62bd86366eebc58eba5cf4e79555b4c diff --git a/libraries/SlidingMenu b/libraries/SlidingMenu index f5078e926..040037fc1 160000 --- a/libraries/SlidingMenu +++ b/libraries/SlidingMenu @@ -1 +1 @@ -Subproject commit f5078e9266d2f5222bef3493bf50e3e0aebcf69e +Subproject commit 040037fc11af14f85994791d5619542261df1513 diff --git a/twidere.wear/build.gradle b/twidere.wear/build.gradle index a8d740d42..7e49dcb9c 100644 --- a/twidere.wear/build.gradle +++ b/twidere.wear/build.gradle @@ -3,7 +3,7 @@ apply plugin: 'com.android.application' android { compileSdkVersion 20 - buildToolsVersion "21.0.2" + buildToolsVersion "21.1" defaultConfig { applicationId "org.mariotaku.twidere" diff --git a/twidere/build.gradle b/twidere/build.gradle index 08e459b03..3715d1e95 100644 --- a/twidere/build.gradle +++ b/twidere/build.gradle @@ -2,7 +2,7 @@ apply plugin: 'com.android.application' android { compileSdkVersion 21 - buildToolsVersion '21.0.2' + buildToolsVersion '21.1' defaultConfig { applicationId "org.mariotaku.twidere" @@ -10,6 +10,7 @@ android { targetSdkVersion 21 versionCode 96 versionName "0.3.0-dev" + } compileOptions { sourceCompatibility JavaVersion.VERSION_1_7 @@ -67,8 +68,12 @@ android { abortOnError false } productFlavors { - google {} - fdroid {} + google { + versionName = android.defaultConfig.versionName + '-google' + } + fdroid { + versionName = android.defaultConfig.versionName + '-fdroid' + } } } @@ -79,14 +84,16 @@ dependencies { compile 'com.android.support:recyclerview-v7:21.0.0' compile 'com.etsy.android.grid:library:1.0.5' compile 'com.sothree.slidinguppanel:library:2.0.0' - compile 'it.sephiroth.android.library.imagezoom:imagezoom:+' + compile 'it.sephiroth.android.library.imagezoom:imagezoom:1.0.5' compile 'com.twitter:twitter-text:1.9.9' compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.3' compile 'org.apache.httpcomponents:httpclient-android:4.3.5' compile 'org.apache.httpcomponents:httpmime:4.3.5' compile 'ch.acra:acra:4.5.0' compile 'com.google.android.apps.dashclock:dashclock-api:2.0.0' - googleCompile 'com.google.android.gms:play-services:6.1.11' + compile 'me.grantland:autofittextview:0.2.0' + compile 'com.pkmmte.view:circularimageview:1.1' + googleCompile 'com.google.android.gms:play-services:6.1.71' fdroidCompile 'org.osmdroid:osmdroid-android:4.2' fdroidCompile 'org.slf4j:slf4j-simple:1.6.1' compile project(':SlidingMenu') diff --git a/twidere/src/main/java/org/mariotaku/querybuilder/Where.java b/twidere/src/main/java/org/mariotaku/querybuilder/Where.java index 3e1c55ed4..6f395a0dd 100644 --- a/twidere/src/main/java/org/mariotaku/querybuilder/Where.java +++ b/twidere/src/main/java/org/mariotaku/querybuilder/Where.java @@ -48,19 +48,19 @@ public class Where implements SQLLang { } public static Where equals(final Column l, final Column r) { - return new Where(String.format(Locale.US, "%s = %s", l.getSQL(), r.getSQL())); + return new Where(String.format(Locale.ROOT, "%s = %s", l.getSQL(), r.getSQL())); } public static Where equals(final Column l, final long r) { - return new Where(String.format(Locale.US, "%s = %d", l.getSQL(), r)); + return new Where(String.format(Locale.ROOT, "%s = %d", l.getSQL(), r)); } public static Where equals(final Column l, final String r) { - return new Where(String.format(Locale.US, "%s = '%s'", l.getSQL(), r)); + return new Where(String.format(Locale.ROOT, "%s = '%s'", l.getSQL(), r)); } public static Where equals(final String l, final long r) { - return new Where(String.format(Locale.US, "%s = %d", l, r)); + return new Where(String.format(Locale.ROOT, "%s = %d", l, r)); } public static Where in(final Column column, final Selectable in) { @@ -68,7 +68,7 @@ public class Where implements SQLLang { } public static Where notEquals(final String l, final long r) { - return new Where(String.format(Locale.US, "%s != %d", l, r)); + return new Where(String.format(Locale.ROOT, "%s != %d", l, r)); } public static Where notEquals(final String l, final String r) { diff --git a/twidere/src/main/java/org/mariotaku/twidere/activity/support/ComposeActivity.java b/twidere/src/main/java/org/mariotaku/twidere/activity/support/ComposeActivity.java index e3c3b3e30..e6be310ec 100644 --- a/twidere/src/main/java/org/mariotaku/twidere/activity/support/ComposeActivity.java +++ b/twidere/src/main/java/org/mariotaku/twidere/activity/support/ComposeActivity.java @@ -65,7 +65,6 @@ import android.widget.GridView; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.ScrollView; -import android.widget.StackView; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import android.widget.Toast; @@ -178,9 +177,8 @@ public class ComposeActivity extends BaseSupportDialogActivity implements TextWa private IColorLabelView mColorIndicator; private EditText mEditText; private ProgressBar mProgress; - private StackView mAccountStack; - private View mSendView, mBottomSendView; - private StatusTextCountView mSendTextCountView, mBottomSendTextCountView; + private View mSendView; + private StatusTextCountView mSendTextCountView; private View mSelectAccount; private MediaPreviewAdapter mMediaPreviewAdapter; @@ -199,8 +197,6 @@ public class ComposeActivity extends BaseSupportDialogActivity implements TextWa private long mInReplyToStatusId; private String mOriginalText; - private boolean mBottomSendButton; - private final Rect mWindowDecorHitRect = new Rect(); @Override @@ -437,13 +433,10 @@ public class ComposeActivity extends BaseSupportDialogActivity implements TextWa mMediasPreviewGrid = (GridView) findViewById(R.id.medias_thumbnail_preview); mMenuBar = (MenuBar) findViewById(R.id.menu_bar); mProgress = (ProgressBar) findViewById(R.id.actionbar_progress_indeterminate); - mAccountStack = (StackView) findViewById(R.id.accounts_stack); final View composeActionBar = findViewById(R.id.compose_actionbar); final View composeBottomBar = findViewById(R.id.compose_bottombar); - mSendView = composeActionBar.findViewById(R.id.send); - mBottomSendView = composeBottomBar.findViewById(R.id.send); + mSendView = composeBottomBar.findViewById(R.id.send); mSendTextCountView = (StatusTextCountView) mSendView.findViewById(R.id.status_text_count); - mBottomSendTextCountView = (StatusTextCountView) mBottomSendView.findViewById(R.id.status_text_count); mSelectAccount = composeActionBar.findViewById(R.id.select_account); ViewAccessor.setBackground(findViewById(R.id.compose_content), getWindowContentOverlayForCompose(this)); ViewAccessor.setBackground(composeActionBar, getActionBarBackground(this, getCurrentThemeResourceId())); @@ -491,7 +484,7 @@ public class ComposeActivity extends BaseSupportDialogActivity implements TextWa public boolean onLongClick(final View v) { switch (v.getId()) { case R.id.send: { - showMenuItemToast(v, getString(R.string.send), mBottomSendButton); + showMenuItemToast(v, getString(R.string.send), true); return true; } } @@ -579,7 +572,6 @@ public class ComposeActivity extends BaseSupportDialogActivity implements TextWa super.onCreate(savedInstanceState); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mPreferences = SharedPreferencesWrapper.getInstance(this, SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); - mBottomSendButton = mPreferences.getBoolean(KEY_BOTTOM_SEND_BUTTON, false); mTwitterWrapper = getTwidereApplication().getTwitterWrapper(); mResolver = getContentResolver(); mValidator = new TwidereValidator(this); @@ -599,7 +591,6 @@ public class ComposeActivity extends BaseSupportDialogActivity implements TextWa mEditText.setOnEditorActionListener(mPreferences.getBoolean(KEY_QUICK_SEND, false) ? this : null); mEditText.addTextChangedListener(this); mAccountSelectorAdapter = new AccountSelectorAdapter(this); - mAccountStack.setAdapter(mAccountSelectorAdapter); mAccountSelectorAdapter.addAll(Account.getAccountsList(this, false)); mSelectAccount.setOnClickListener(this); // mAccountSelector.setOnItemClickListener(this); @@ -648,12 +639,8 @@ public class ComposeActivity extends BaseSupportDialogActivity implements TextWa } mMenuBar.inflate(R.menu.menu_compose); - mSendView.setVisibility(mBottomSendButton ? View.GONE : View.VISIBLE); - mBottomSendView.setVisibility(mBottomSendButton ? View.VISIBLE : View.GONE); mSendView.setOnClickListener(this); - mBottomSendView.setOnClickListener(this); mSendView.setOnLongClickListener(this); - mBottomSendView.setOnLongClickListener(this); final Menu menu = mMenuBar.getMenu(); final Intent composeExtensionsIntent = new Intent(INTENT_ACTION_EXTENSION_COMPOSE); addIntentToMenu(this, menu, composeExtensionsIntent, MENU_GROUP_COMPOSE_EXTENSION); @@ -1128,14 +1115,12 @@ public class ComposeActivity extends BaseSupportDialogActivity implements TextWa } private void updateTextCount() { - final StatusTextCountView textCountView = mBottomSendButton ? mBottomSendTextCountView : mSendTextCountView; - if (textCountView != null && mEditText != null) { - final String textOrig = parseString(mEditText.getText()); - final String text = hasMedia() && textOrig != null ? mImageUploaderUsed ? getImageUploadStatus(this, - new String[]{FAKE_IMAGE_LINK}, textOrig) : textOrig + " " + FAKE_IMAGE_LINK : textOrig; - final int validatedCount = text != null ? mValidator.getTweetLength(text) : 0; - textCountView.setTextCount(validatedCount); - } + if (mSendTextCountView == null || mEditText == null) return; + final String textOrig = parseString(mEditText.getText()); + final String text = hasMedia() && textOrig != null ? mImageUploaderUsed ? getImageUploadStatus(this, + new String[]{FAKE_IMAGE_LINK}, textOrig) : textOrig + " " + FAKE_IMAGE_LINK : textOrig; + final int validatedCount = text != null ? mValidator.getTweetLength(text) : 0; + mSendTextCountView.setTextCount(validatedCount); } @Override diff --git a/twidere/src/main/java/org/mariotaku/twidere/constant/IntentConstants.java b/twidere/src/main/java/org/mariotaku/twidere/constant/IntentConstants.java index 66d0178a5..645c8c294 100644 --- a/twidere/src/main/java/org/mariotaku/twidere/constant/IntentConstants.java +++ b/twidere/src/main/java/org/mariotaku/twidere/constant/IntentConstants.java @@ -76,7 +76,6 @@ public interface IntentConstants { public static final String BROADCAST_TASK_STATE_CHANGED = INTENT_PACKAGE_PREFIX + "TASK_STATE_CHANGED"; public static final String BROADCAST_NOTIFICATION_DELETED = INTENT_PACKAGE_PREFIX + "NOTIFICATION_DELETED"; public static final String BROADCAST_FRIENDSHIP_CHANGED = INTENT_PACKAGE_PREFIX + "FRIENDSHIP_CHANGED"; - public static final String BROADCAST_BLOCKSTATE_CHANGED = INTENT_PACKAGE_PREFIX + "BLOCKSTATE_CHANGED"; public static final String BROADCAST_PROFILE_UPDATED = INTENT_PACKAGE_PREFIX + "PROFILE_UPDATED"; public static final String BROADCAST_PROFILE_IMAGE_UPDATED = INTENT_PACKAGE_PREFIX + "PROFILE_IMAGE_UPDATED"; public static final String BROADCAST_PROFILE_BANNER_UPDATED = INTENT_PACKAGE_PREFIX + "PROFILE_BANNER_UPDATED"; @@ -147,7 +146,7 @@ public interface IntentConstants { public static final String EXTRA_TEXT = "text"; public static final String EXTRA_TITLE = "title"; public static final String EXTRA_TYPE = "type"; - public static final String EXTRA_SUCCEED = "succeed"; +// public static final String EXTRA_SUCCEED = "succeed"; public static final String EXTRA_IDS = "ids"; public static final String EXTRA_IS_SHARE = "is_share"; public static final String EXTRA_STATUS = "status"; diff --git a/twidere/src/main/java/org/mariotaku/twidere/constant/SharedPreferenceConstants.java b/twidere/src/main/java/org/mariotaku/twidere/constant/SharedPreferenceConstants.java index 8db17a1cc..f970580f9 100644 --- a/twidere/src/main/java/org/mariotaku/twidere/constant/SharedPreferenceConstants.java +++ b/twidere/src/main/java/org/mariotaku/twidere/constant/SharedPreferenceConstants.java @@ -141,12 +141,8 @@ public interface SharedPreferenceConstants { @Preference(type = BOOLEAN, hasDefault = true, defaultBoolean = false) public static final String KEY_DISPLAY_IMAGE_PREVIEW = "display_image_preview"; @Preference(type = BOOLEAN) - public static final String KEY_BOTTOM_COMPOSE_BUTTON = "bottom_compose_button"; - @Preference(type = BOOLEAN) public static final String KEY_LEFTSIDE_COMPOSE_BUTTON = "leftside_compose_button"; @Preference(type = BOOLEAN) - public static final String KEY_BOTTOM_SEND_BUTTON = "bottom_send_button"; - @Preference(type = BOOLEAN) public static final String KEY_ATTACH_LOCATION = "attach_location"; @Preference(type = BOOLEAN, hasDefault = true, defaultBoolean = true) public static final String KEY_GZIP_COMPRESSING = "gzip_compressing"; diff --git a/twidere/src/main/java/org/mariotaku/twidere/fragment/support/AccountsDrawerFragment.java b/twidere/src/main/java/org/mariotaku/twidere/fragment/support/AccountsDrawerFragment.java index 74bfecb70..ffcd326ed 100644 --- a/twidere/src/main/java/org/mariotaku/twidere/fragment/support/AccountsDrawerFragment.java +++ b/twidere/src/main/java/org/mariotaku/twidere/fragment/support/AccountsDrawerFragment.java @@ -175,7 +175,7 @@ public class AccountsDrawerFragment extends BaseSupportListFragment implements L @Override public Loader onCreateLoader(final int id, final Bundle args) { - return new CursorLoader(getActivity(), Accounts.CONTENT_URI, Accounts.COLUMNS, null, null, null); + return new CursorLoader(getActivity(), Accounts.CONTENT_URI, Accounts.COLUMNS, null, null, Accounts.SORT_POSITION); } @Override @@ -426,7 +426,7 @@ public class AccountsDrawerFragment extends BaseSupportListFragment implements L private static final ArrayList sOptionsDefault = new ArrayList<>(); static { - sOptions.add(new OptionItem(R.string.view_user_profile, R.drawable.ic_action_user, MENU_VIEW_PROFILE)); + sOptions.add(new OptionItem(R.string.view_user_profile, R.drawable.ic_action_profile, MENU_VIEW_PROFILE)); sOptions.add(new OptionItem(android.R.string.search_go, R.drawable.ic_action_search, MENU_SEARCH)); sOptions.add(new OptionItem(R.string.statuses, R.drawable.ic_action_quote, MENU_STATUSES)); sOptions.add(new OptionItem(R.string.favorites, R.drawable.ic_action_star, MENU_FAVORITES)); @@ -437,7 +437,7 @@ public class AccountsDrawerFragment extends BaseSupportListFragment implements L sOptions.add(new OptionItem(R.string.set_as_default, R.drawable.ic_action_ok, MENU_SET_AS_DEFAULT)); sOptions.add(new OptionItem(R.string.delete, R.drawable.ic_action_delete, MENU_DELETE)); - sOptionsDefault.add(new OptionItem(R.string.view_user_profile, R.drawable.ic_action_user, + sOptionsDefault.add(new OptionItem(R.string.view_user_profile, R.drawable.ic_action_profile, MENU_VIEW_PROFILE)); sOptionsDefault.add(new OptionItem(android.R.string.search_go, R.drawable.ic_action_search, MENU_SEARCH)); diff --git a/twidere/src/main/java/org/mariotaku/twidere/fragment/support/CreateUserMuteDialogFragment.java b/twidere/src/main/java/org/mariotaku/twidere/fragment/support/CreateUserMuteDialogFragment.java new file mode 100644 index 000000000..b8a6118db --- /dev/null +++ b/twidere/src/main/java/org/mariotaku/twidere/fragment/support/CreateUserMuteDialogFragment.java @@ -0,0 +1,84 @@ +/* + * Twidere - Twitter client for Android + * + * Copyright (C) 2012-2014 Mariotaku Lee + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.mariotaku.twidere.fragment.support; + +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.DialogInterface; +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.v4.app.FragmentManager; + +import org.mariotaku.twidere.R; +import org.mariotaku.twidere.model.ParcelableUser; +import org.mariotaku.twidere.util.AsyncTwitterWrapper; +import org.mariotaku.twidere.util.ThemeUtils; +import org.mariotaku.twidere.util.Utils; + +public class CreateUserMuteDialogFragment extends BaseSupportDialogFragment implements DialogInterface.OnClickListener { + + public static final String FRAGMENT_TAG = "create_user_mute"; + + @Override + public void onClick(final DialogInterface dialog, final int which) { + switch (which) { + case DialogInterface.BUTTON_POSITIVE: + final ParcelableUser user = getUser(); + final AsyncTwitterWrapper twitter = getTwitterWrapper(); + if (user == null || twitter == null) return; + twitter.createMuteAsync(user.account_id, user.id); + break; + default: + break; + } + } + + @NonNull + @Override + public Dialog onCreateDialog(final Bundle savedInstanceState) { + final Context wrapped = ThemeUtils.getDialogThemedContext(getActivity()); + final AlertDialog.Builder builder = new AlertDialog.Builder(wrapped); + final ParcelableUser user = getUser(); + if (user != null) { + final String displayName = Utils.getDisplayName(wrapped, user.id, user.name, user.screen_name); + builder.setTitle(getString(R.string.mute_user, displayName)); + builder.setMessage(getString(R.string.mute_user_confirm_message, displayName)); + } + builder.setPositiveButton(android.R.string.ok, this); + builder.setNegativeButton(android.R.string.cancel, null); + return builder.create(); + } + + private ParcelableUser getUser() { + final Bundle args = getArguments(); + if (!args.containsKey(EXTRA_USER)) return null; + return args.getParcelable(EXTRA_USER); + } + + public static CreateUserMuteDialogFragment show(final FragmentManager fm, final ParcelableUser user) { + final Bundle args = new Bundle(); + args.putParcelable(EXTRA_USER, user); + final CreateUserMuteDialogFragment f = new CreateUserMuteDialogFragment(); + f.setArguments(args); + f.show(fm, FRAGMENT_TAG); + return f; + } +} diff --git a/twidere/src/main/java/org/mariotaku/twidere/fragment/support/ParcelableStatusesListFragment.java b/twidere/src/main/java/org/mariotaku/twidere/fragment/support/ParcelableStatusesListFragment.java index c9f051bc6..e21b3e040 100644 --- a/twidere/src/main/java/org/mariotaku/twidere/fragment/support/ParcelableStatusesListFragment.java +++ b/twidere/src/main/java/org/mariotaku/twidere/fragment/support/ParcelableStatusesListFragment.java @@ -19,8 +19,6 @@ package org.mariotaku.twidere.fragment.support; -import static org.mariotaku.twidere.util.Utils.encodeQueryParams; - import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; @@ -40,190 +38,191 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; +import static org.mariotaku.twidere.util.Utils.encodeQueryParams; + public abstract class ParcelableStatusesListFragment extends BaseStatusesListFragment> { - protected SharedPreferences mPreferences; + protected SharedPreferences mPreferences; - private boolean mStatusesRestored; - private boolean mIsFirstCreated; + private boolean mStatusesRestored; + private boolean mIsFirstCreated; - private final BroadcastReceiver mStateReceiver = new BroadcastReceiver() { + private final BroadcastReceiver mStateReceiver = new BroadcastReceiver() { - @Override - public void onReceive(final Context context, final Intent intent) { - if (getActivity() == null || !isAdded() || isDetached()) return; - final String action = intent.getAction(); - if (BROADCAST_STATUS_DESTROYED.equals(action)) { - final long status_id = intent.getLongExtra(EXTRA_STATUS_ID, -1); - final boolean succeed = intent.getBooleanExtra(EXTRA_SUCCEED, false); - if (status_id > 0 && succeed) { - deleteStatus(status_id); - } - } else if (BROADCAST_RETWEET_CHANGED.equals(action)) { - final long status_id = intent.getLongExtra(EXTRA_STATUS_ID, -1); - final boolean retweeted = intent.getBooleanExtra(EXTRA_RETWEETED, false); - if (status_id > 0 && !retweeted) { - deleteStatus(status_id); - } - } else if (BROADCAST_MULTI_MUTESTATE_CHANGED.equals(action)) { - final Bundle args = getArguments(); - final long account_id = args != null ? args.getLong(EXTRA_ACCOUNT_ID, -1) : -1; - if (account_id <= 0) return; - getStatuses(new long[] { account_id }, null, null); - } + @Override + public void onReceive(final Context context, final Intent intent) { + if (getActivity() == null || !isAdded() || isDetached()) return; + final String action = intent.getAction(); + if (BROADCAST_STATUS_DESTROYED.equals(action)) { + final long statusId = intent.getLongExtra(EXTRA_STATUS_ID, -1); + if (statusId > 0) { + deleteStatus(statusId); + } + } else if (BROADCAST_RETWEET_CHANGED.equals(action)) { + final long status_id = intent.getLongExtra(EXTRA_STATUS_ID, -1); + final boolean retweeted = intent.getBooleanExtra(EXTRA_RETWEETED, false); + if (status_id > 0 && !retweeted) { + deleteStatus(status_id); + } + } else if (BROADCAST_MULTI_MUTESTATE_CHANGED.equals(action)) { + final Bundle args = getArguments(); + final long account_id = args != null ? args.getLong(EXTRA_ACCOUNT_ID, -1) : -1; + if (account_id <= 0) return; + getStatuses(new long[]{account_id}, null, null); + } - } + } - }; + }; - public final void deleteStatus(final long status_id) { - final List data = getData(); - if (status_id <= 0 || data == null) return; - final ArrayList data_to_remove = new ArrayList(); - for (final ParcelableStatus status : data) { - if (status.id == status_id || status.retweet_id > 0 && status.retweet_id == status_id) { - data_to_remove.add(status); - } - } - data.removeAll(data_to_remove); - getListAdapter().setData(data); - } + public final void deleteStatus(final long status_id) { + final List data = getData(); + if (status_id <= 0 || data == null) return; + final ArrayList data_to_remove = new ArrayList(); + for (final ParcelableStatus status : data) { + if (status.id == status_id || status.retweet_id > 0 && status.retweet_id == status_id) { + data_to_remove.add(status); + } + } + data.removeAll(data_to_remove); + getListAdapter().setData(data); + } - @Override - public final int getStatuses(final long[] account_ids, final long[] max_ids, final long[] since_ids) { - mStatusesRestored = true; - final long max_id = max_ids != null && max_ids.length == 1 ? max_ids[0] : -1; - final long since_id = since_ids != null && since_ids.length == 1 ? since_ids[0] : -1; - final Bundle args = new Bundle(getArguments()); - args.putLong(EXTRA_MAX_ID, max_id); - args.putLong(EXTRA_SINCE_ID, since_id); - getLoaderManager().restartLoader(0, args, this); - return -1; - } + @Override + public final int getStatuses(final long[] account_ids, final long[] max_ids, final long[] since_ids) { + mStatusesRestored = true; + final long max_id = max_ids != null && max_ids.length == 1 ? max_ids[0] : -1; + final long since_id = since_ids != null && since_ids.length == 1 ? since_ids[0] : -1; + final Bundle args = new Bundle(getArguments()); + args.putLong(EXTRA_MAX_ID, max_id); + args.putLong(EXTRA_SINCE_ID, since_id); + getLoaderManager().restartLoader(0, args, this); + return -1; + } - @Override - public void onActivityCreated(final Bundle savedInstanceState) { - mStatusesRestored = false; - if (savedInstanceState != null) { - final List saved = savedInstanceState.getParcelableArrayList(EXTRA_DATA); - if (saved != null) { - setData(saved); - } - } - super.onActivityCreated(savedInstanceState); - mPreferences = getSharedPreferences(); - mIsFirstCreated = savedInstanceState == null; - } + @Override + public void onActivityCreated(final Bundle savedInstanceState) { + mStatusesRestored = false; + if (savedInstanceState != null) { + final List saved = savedInstanceState.getParcelableArrayList(EXTRA_DATA); + if (saved != null) { + setData(saved); + } + } + super.onActivityCreated(savedInstanceState); + mPreferences = getSharedPreferences(); + mIsFirstCreated = savedInstanceState == null; + } - @Override - public final Loader> onCreateLoader(final int id, final Bundle args) { - setProgressBarIndeterminateVisibility(true); - final List data = getData(); - if (isInstanceStateSaved() && data != null && !mStatusesRestored) - return new DummyParcelableStatusesLoader(getActivity(), data); - final Loader> loader = newLoaderInstance(getActivity(), args); - return loader != null ? loader : new DummyParcelableStatusesLoader(getActivity()); - } + @Override + public final Loader> onCreateLoader(final int id, final Bundle args) { + setProgressBarIndeterminateVisibility(true); + final List data = getData(); + if (isInstanceStateSaved() && data != null && !mStatusesRestored) + return new DummyParcelableStatusesLoader(getActivity(), data); + final Loader> loader = newLoaderInstance(getActivity(), args); + return loader != null ? loader : new DummyParcelableStatusesLoader(getActivity()); + } - @Override - public void onLoadFinished(final Loader> loader, final List data) { - super.onLoadFinished(loader, data); - if (mIsFirstCreated && mPreferences.getBoolean(KEY_REFRESH_ON_START, false)) { - onRefreshFromStart(); - } - } + @Override + public void onLoadFinished(final Loader> loader, final List data) { + super.onLoadFinished(loader, data); + if (mIsFirstCreated && mPreferences.getBoolean(KEY_REFRESH_ON_START, false)) { + onRefreshFromStart(); + } + } - @Override - public void onRefreshFromStart() { - if (isRefreshing()) return; - final IStatusesAdapter> adapter = getListAdapter(); - final int count = adapter.getCount(); - final ParcelableStatus status = count > 0 ? adapter.getStatus(0) : null; - if (status != null) { - getStatuses(new long[] { status.account_id }, null, new long[] { status.id }); - } else { - getStatuses(null, null, null); - } - } + @Override + public void onRefreshFromStart() { + if (isRefreshing()) return; + final IStatusesAdapter> adapter = getListAdapter(); + final int count = adapter.getCount(); + final ParcelableStatus status = count > 0 ? adapter.getStatus(0) : null; + if (status != null) { + getStatuses(new long[]{status.account_id}, null, new long[]{status.id}); + } else { + getStatuses(null, null, null); + } + } - @Override - public void onSaveInstanceState(final Bundle outState) { - final List data = getData(); - if (data != null) { - outState.putParcelableArrayList(EXTRA_DATA, new ArrayList(data)); - } - super.onSaveInstanceState(outState); - } + @Override + public void onSaveInstanceState(final Bundle outState) { + final List data = getData(); + if (data != null) { + outState.putParcelableArrayList(EXTRA_DATA, new ArrayList(data)); + } + super.onSaveInstanceState(outState); + } - @Override - public void onStart() { - super.onStart(); - final IntentFilter filter = new IntentFilter(BROADCAST_STATUS_DESTROYED); - filter.addAction(BROADCAST_RETWEET_CHANGED); - registerReceiver(mStateReceiver, filter); - } + @Override + public void onStart() { + super.onStart(); + final IntentFilter filter = new IntentFilter(BROADCAST_STATUS_DESTROYED); + filter.addAction(BROADCAST_RETWEET_CHANGED); + registerReceiver(mStateReceiver, filter); + } - @Override - public void onStop() { - unregisterReceiver(mStateReceiver); - super.onStop(); - } + @Override + public void onStop() { + unregisterReceiver(mStateReceiver); + super.onStop(); + } - @Override - protected final long[] getNewestStatusIds() { - final IStatusesAdapter> adapter = getListAdapter(); - final long last_id = adapter.getCount() > 0 ? adapter.getStatus(0).id : -1; - return last_id > 0 ? new long[] { last_id } : null; - } + @Override + protected final long[] getNewestStatusIds() { + final IStatusesAdapter> adapter = getListAdapter(); + final long last_id = adapter.getCount() > 0 ? adapter.getStatus(0).id : -1; + return last_id > 0 ? new long[]{last_id} : null; + } - @Override - protected final long[] getOldestStatusIds() { - final IStatusesAdapter> adapter = getListAdapter(); - final ParcelableStatus status = adapter.getLastStatus(); - final long last_id = status != null ? status.id : -1; - return last_id > 0 ? new long[] { last_id } : null; - } + @Override + protected final long[] getOldestStatusIds() { + final IStatusesAdapter> adapter = getListAdapter(); + final ParcelableStatus status = adapter.getLastStatus(); + final long last_id = status != null ? status.id : -1; + return last_id > 0 ? new long[]{last_id} : null; + } - @Override - protected final String getPositionKey() { - final Object[] args = getSavedStatusesFileArgs(); - if (args == null || args.length <= 0) return null; - try { - return encodeQueryParams(ArrayUtils.toString(args, '.', false) + "." + getTabPosition()); - } catch (final IOException e) { - e.printStackTrace(); - } - return null; - } + @Override + protected final String getPositionKey() { + final Object[] args = getSavedStatusesFileArgs(); + if (args == null || args.length <= 0) return null; + try { + return encodeQueryParams(ArrayUtils.toString(args, '.', false) + "." + getTabPosition()); + } catch (final IOException e) { + e.printStackTrace(); + } + return null; + } - protected abstract Object[] getSavedStatusesFileArgs(); + protected abstract Object[] getSavedStatusesFileArgs(); - @Override - protected void loadMoreStatuses() { - if (isRefreshing()) return; - final IStatusesAdapter> adapter = getListAdapter(); - final ParcelableStatus status = adapter.getLastStatus(); - if (status != null) { - getStatuses(new long[] { status.account_id }, new long[] { status.id }, null); - } - } + @Override + protected void loadMoreStatuses() { + if (isRefreshing()) return; + final IStatusesAdapter> adapter = getListAdapter(); + final ParcelableStatus status = adapter.getLastStatus(); + if (status != null) { + getStatuses(new long[]{status.account_id}, new long[]{status.id}, null); + } + } - @Override - protected ParcelableStatusesAdapter newAdapterInstance(final boolean compact, final boolean plain) { - return new ParcelableStatusesAdapter(getActivity(), compact, plain); - } + @Override + protected ParcelableStatusesAdapter newAdapterInstance(final boolean compact, final boolean plain) { + return new ParcelableStatusesAdapter(getActivity(), compact, plain); + } - protected abstract Loader> newLoaderInstance(Context context, Bundle args); + protected abstract Loader> newLoaderInstance(Context context, Bundle args); - @Override - protected void updateRefreshState() { - if (getActivity() == null || !getUserVisibleHint() || !isVisible()) return; - final LoaderManager lm = getLoaderManager(); - final boolean hasRunningLoaders = lm.hasRunningLoaders(); - if (!hasRunningLoaders) { - setRefreshing(true); - } - setRefreshing(hasRunningLoaders); - } + @Override + protected void updateRefreshState() { + if (getActivity() == null || !getUserVisibleHint() || !isVisible()) return; + final LoaderManager lm = getLoaderManager(); + final boolean hasRunningLoaders = lm.hasRunningLoaders(); + if (!hasRunningLoaders) { + setRefreshing(true); + } + setRefreshing(hasRunningLoaders); + } } diff --git a/twidere/src/main/java/org/mariotaku/twidere/fragment/support/StatusFragment.java b/twidere/src/main/java/org/mariotaku/twidere/fragment/support/StatusFragment.java index af76659b4..9da1393d6 100644 --- a/twidere/src/main/java/org/mariotaku/twidere/fragment/support/StatusFragment.java +++ b/twidere/src/main/java/org/mariotaku/twidere/fragment/support/StatusFragment.java @@ -188,21 +188,27 @@ public class StatusFragment extends ParcelableStatusesListFragment implements On public void onReceive(final Context context, final Intent intent) { if (getActivity() == null || !isAdded() || isDetached()) return; final String action = intent.getAction(); - if (BROADCAST_FRIENDSHIP_CHANGED.equals(action)) { - if (mStatus != null && mStatus.user_id == intent.getLongExtra(EXTRA_USER_ID, -1) - && intent.getBooleanExtra(EXTRA_SUCCEED, false)) { - showFollowInfo(true); + switch (action) { + case BROADCAST_FRIENDSHIP_CHANGED: { + if (mStatus != null && mStatus.user_id == intent.getLongExtra(EXTRA_USER_ID, -1)) { + showFollowInfo(true); + } + break; } - } else if (BROADCAST_FAVORITE_CHANGED.equals(action)) { - final ParcelableStatus status = intent.getParcelableExtra(EXTRA_STATUS); - if (mStatus != null && status != null && isSameAccount(context, status.account_id, mStatus.account_id) - && status.id == getStatusId()) { - getStatus(true); + case BROADCAST_FAVORITE_CHANGED: { + final ParcelableStatus status = intent.getParcelableExtra(EXTRA_STATUS); + if (mStatus != null && status != null && isSameAccount(context, status.account_id, mStatus.account_id) + && status.id == getStatusId()) { + getStatus(true); + } + break; } - } else if (BROADCAST_RETWEET_CHANGED.equals(action)) { - final long status_id = intent.getLongExtra(EXTRA_STATUS_ID, -1); - if (status_id > 0 && status_id == getStatusId()) { - getStatus(true); + case BROADCAST_RETWEET_CHANGED: { + final long status_id = intent.getLongExtra(EXTRA_STATUS_ID, -1); + if (status_id > 0 && status_id == getStatusId()) { + getStatus(true); + } + break; } } } diff --git a/twidere/src/main/java/org/mariotaku/twidere/fragment/support/UserListDetailsFragment.java b/twidere/src/main/java/org/mariotaku/twidere/fragment/support/UserListDetailsFragment.java index 8400ae5a1..56f264b57 100644 --- a/twidere/src/main/java/org/mariotaku/twidere/fragment/support/UserListDetailsFragment.java +++ b/twidere/src/main/java/org/mariotaku/twidere/fragment/support/UserListDetailsFragment.java @@ -54,8 +54,6 @@ import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; -import org.mariotaku.menucomponent.widget.MenuBar; -import org.mariotaku.menucomponent.widget.MenuBar.MenuBarListener; import org.mariotaku.twidere.R; import org.mariotaku.twidere.activity.support.UserListSelectorActivity; import org.mariotaku.twidere.adapter.ListActionAdapter; @@ -121,15 +119,15 @@ public class UserListDetailsFragment extends BaseSupportListFragment implements public void onReceive(final Context context, final Intent intent) { if (getActivity() == null || !isAdded() || isDetached()) return; final String action = intent.getAction(); - final ParcelableUserList user_list = intent.getParcelableExtra(EXTRA_USER_LIST); - if (user_list == null || mUserList == null || !intent.getBooleanExtra(EXTRA_SUCCEED, false)) + final ParcelableUserList userList = intent.getParcelableExtra(EXTRA_USER_LIST); + if (userList == null || mUserList == null) return; if (BROADCAST_USER_LIST_DETAILS_UPDATED.equals(action)) { - if (user_list.id == mUserList.id) { + if (userList.id == mUserList.id) { getUserListInfo(true); } } else if (BROADCAST_USER_LIST_SUBSCRIBED.equals(action) || BROADCAST_USER_LIST_UNSUBSCRIBED.equals(action)) { - if (user_list.id == mUserList.id) { + if (userList.id == mUserList.id) { getUserListInfo(true); } } diff --git a/twidere/src/main/java/org/mariotaku/twidere/fragment/support/UserListMembersFragment.java b/twidere/src/main/java/org/mariotaku/twidere/fragment/support/UserListMembersFragment.java index 83221e661..6cd44343b 100644 --- a/twidere/src/main/java/org/mariotaku/twidere/fragment/support/UserListMembersFragment.java +++ b/twidere/src/main/java/org/mariotaku/twidere/fragment/support/UserListMembersFragment.java @@ -19,8 +19,6 @@ package org.mariotaku.twidere.fragment.support; -import static org.mariotaku.twidere.util.Utils.getTwitterInstance; - import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; @@ -40,137 +38,138 @@ import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.UserList; +import static org.mariotaku.twidere.util.Utils.getTwitterInstance; + public class UserListMembersFragment extends CursorSupportUsersListFragment implements OnMenuItemClickListener { - private ParcelableUserList mUserList; + private ParcelableUserList mUserList; - private final BroadcastReceiver mStatusReceiver = new BroadcastReceiver() { + private final BroadcastReceiver mStatusReceiver = new BroadcastReceiver() { - @Override - public void onReceive(final Context context, final Intent intent) { - if (getActivity() == null || !isAdded() || isDetached()) return; - final String action = intent.getAction(); - if (BROADCAST_USER_LIST_MEMBERS_DELETED.equals(action)) { - if (!intent.getBooleanExtra(EXTRA_SUCCEED, false)) return; - final ParcelableUserList list = intent.getParcelableExtra(EXTRA_USER_LIST); - if (mUserList != null && list != null && list.id == mUserList.id) { - removeUsers(intent.getLongArrayExtra(EXTRA_USER_IDS)); - } - } - } - }; + @Override + public void onReceive(final Context context, final Intent intent) { + if (getActivity() == null || !isAdded() || isDetached()) return; + final String action = intent.getAction(); + if (BROADCAST_USER_LIST_MEMBERS_DELETED.equals(action)) { + final ParcelableUserList list = intent.getParcelableExtra(EXTRA_USER_LIST); + if (mUserList != null && list != null && list.id == mUserList.id) { + removeUsers(intent.getLongArrayExtra(EXTRA_USER_IDS)); + } + } + } + }; - @Override - public CursorSupportUsersLoader newLoaderInstance(final Context context, final Bundle args) { - if (args == null) return null; - final int list_id = args.getInt(EXTRA_LIST_ID, -1); - final long account_id = args.getLong(EXTRA_ACCOUNT_ID, -1); - final long user_id = args.getLong(EXTRA_USER_ID, -1); - final String screen_name = args.getString(EXTRA_SCREEN_NAME); - final String list_name = args.getString(EXTRA_LIST_NAME); - return new UserListMembersLoader(context, account_id, list_id, user_id, screen_name, list_name, - getNextCursor(), getData()); - } + @Override + public CursorSupportUsersLoader newLoaderInstance(final Context context, final Bundle args) { + if (args == null) return null; + final int list_id = args.getInt(EXTRA_LIST_ID, -1); + final long account_id = args.getLong(EXTRA_ACCOUNT_ID, -1); + final long user_id = args.getLong(EXTRA_USER_ID, -1); + final String screen_name = args.getString(EXTRA_SCREEN_NAME); + final String list_name = args.getString(EXTRA_LIST_NAME); + return new UserListMembersLoader(context, account_id, list_id, user_id, screen_name, list_name, + getNextCursor(), getData()); + } - @Override - public void onActivityCreated(final Bundle savedInstanceState) { - final Bundle args = getArguments(); - if (savedInstanceState != null) { - mUserList = savedInstanceState.getParcelable(EXTRA_USER_LIST); - } else if (args != null) { - mUserList = args.getParcelable(EXTRA_USER_LIST); - } - super.onActivityCreated(savedInstanceState); - if (mUserList == null && args != null) { - final int list_id = args.getInt(EXTRA_LIST_ID, -1); - final long account_id = args.getLong(EXTRA_ACCOUNT_ID, -1); - final long user_id = args.getLong(EXTRA_USER_ID, -1); - final String screen_name = args.getString(EXTRA_SCREEN_NAME); - final String list_name = args.getString(EXTRA_LIST_NAME); - new GetUserListTask(account_id, list_id, list_name, user_id, screen_name).execute(); - } - } + @Override + public void onActivityCreated(final Bundle savedInstanceState) { + final Bundle args = getArguments(); + if (savedInstanceState != null) { + mUserList = savedInstanceState.getParcelable(EXTRA_USER_LIST); + } else if (args != null) { + mUserList = args.getParcelable(EXTRA_USER_LIST); + } + super.onActivityCreated(savedInstanceState); + if (mUserList == null && args != null) { + final int list_id = args.getInt(EXTRA_LIST_ID, -1); + final long account_id = args.getLong(EXTRA_ACCOUNT_ID, -1); + final long user_id = args.getLong(EXTRA_USER_ID, -1); + final String screen_name = args.getString(EXTRA_SCREEN_NAME); + final String list_name = args.getString(EXTRA_LIST_NAME); + new GetUserListTask(account_id, list_id, list_name, user_id, screen_name).execute(); + } + } - @Override - public boolean onMenuItemClick(final MenuItem item) { - final ParcelableUser user = getSelectedUser(); - if (user == null || mUserList == null) return false; - switch (item.getItemId()) { - case MENU_DELETE_FROM_LIST: { - DeleteUserListMembersDialogFragment.show(getFragmentManager(), mUserList, user); - break; - } - default: { - return super.onMenuItemClick(item); - } - } - return true; - } + @Override + public boolean onMenuItemClick(final MenuItem item) { + final ParcelableUser user = getSelectedUser(); + if (user == null || mUserList == null) return false; + switch (item.getItemId()) { + case MENU_DELETE_FROM_LIST: { + DeleteUserListMembersDialogFragment.show(getFragmentManager(), mUserList, user); + break; + } + default: { + return super.onMenuItemClick(item); + } + } + return true; + } - @Override - public void onSaveInstanceState(final Bundle outState) { - outState.putParcelable(EXTRA_USER_LIST, mUserList); - super.onSaveInstanceState(outState); - } + @Override + public void onSaveInstanceState(final Bundle outState) { + outState.putParcelable(EXTRA_USER_LIST, mUserList); + super.onSaveInstanceState(outState); + } - @Override - public void onStart() { - super.onStart(); - final IntentFilter filter = new IntentFilter(BROADCAST_USER_LIST_MEMBERS_DELETED); - registerReceiver(mStatusReceiver, filter); - } + @Override + public void onStart() { + super.onStart(); + final IntentFilter filter = new IntentFilter(BROADCAST_USER_LIST_MEMBERS_DELETED); + registerReceiver(mStatusReceiver, filter); + } - @Override - public void onStop() { - unregisterReceiver(mStatusReceiver); - super.onStop(); - } + @Override + public void onStop() { + unregisterReceiver(mStatusReceiver); + super.onStop(); + } - @Override - protected int getUserMenuResource() { - return R.menu.action_user_list_member; - } + @Override + protected int getUserMenuResource() { + return R.menu.action_user_list_member; + } - private class GetUserListTask extends AsyncTask { + private class GetUserListTask extends AsyncTask { - private final long account_id, user_id; - private final int list_id; - private final String screen_name, list_name; + private final long account_id, user_id; + private final int list_id; + private final String screen_name, list_name; - private GetUserListTask(final long account_id, final int list_id, final String list_name, final long user_id, - final String screen_name) { - this.account_id = account_id; - this.user_id = user_id; - this.list_id = list_id; - this.screen_name = screen_name; - this.list_name = list_name; - } + private GetUserListTask(final long account_id, final int list_id, final String list_name, final long user_id, + final String screen_name) { + this.account_id = account_id; + this.user_id = user_id; + this.list_id = list_id; + this.screen_name = screen_name; + this.list_name = list_name; + } - @Override - protected ParcelableUserList doInBackground(final Void... params) { - final Twitter twitter = getTwitterInstance(getActivity(), account_id, true); - if (twitter == null) return null; - try { - final UserList list; - if (list_id > 0) { - list = twitter.showUserList(list_id); - } else if (user_id > 0) { - list = twitter.showUserList(list_name, user_id); - } else if (screen_name != null) { - list = twitter.showUserList(list_name, screen_name); - } else - return null; - return new ParcelableUserList(list, account_id); - } catch (final TwitterException e) { - e.printStackTrace(); - return null; - } - } + @Override + protected ParcelableUserList doInBackground(final Void... params) { + final Twitter twitter = getTwitterInstance(getActivity(), account_id, true); + if (twitter == null) return null; + try { + final UserList list; + if (list_id > 0) { + list = twitter.showUserList(list_id); + } else if (user_id > 0) { + list = twitter.showUserList(list_name, user_id); + } else if (screen_name != null) { + list = twitter.showUserList(list_name, screen_name); + } else + return null; + return new ParcelableUserList(list, account_id); + } catch (final TwitterException e) { + e.printStackTrace(); + return null; + } + } - @Override - protected void onPostExecute(final ParcelableUserList result) { - if (mUserList != null) return; - mUserList = result; - } - } + @Override + protected void onPostExecute(final ParcelableUserList result) { + if (mUserList != null) return; + mUserList = result; + } + } } diff --git a/twidere/src/main/java/org/mariotaku/twidere/fragment/support/UserListsListFragment.java b/twidere/src/main/java/org/mariotaku/twidere/fragment/support/UserListsListFragment.java index f477180b3..b36adc009 100644 --- a/twidere/src/main/java/org/mariotaku/twidere/fragment/support/UserListsListFragment.java +++ b/twidere/src/main/java/org/mariotaku/twidere/fragment/support/UserListsListFragment.java @@ -49,7 +49,7 @@ public class UserListsListFragment extends BaseUserListsListFragment { final String action = intent.getAction(); if (BROADCAST_USER_LIST_DELETED.equals(action)) { final ParcelableUserList list = intent.getParcelableExtra(EXTRA_USER_LIST); - if (list != null && intent.getBooleanExtra(EXTRA_SUCCEED, false)) { + if (list != null) { removeUserList(list.id); } } diff --git a/twidere/src/main/java/org/mariotaku/twidere/fragment/support/UserProfileFragment.java b/twidere/src/main/java/org/mariotaku/twidere/fragment/support/UserProfileFragment.java index 9e145bf46..ed0ffbb4a 100644 --- a/twidere/src/main/java/org/mariotaku/twidere/fragment/support/UserProfileFragment.java +++ b/twidere/src/main/java/org/mariotaku/twidere/fragment/support/UserProfileFragment.java @@ -31,8 +31,6 @@ import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.res.Resources; import android.graphics.Color; -import android.graphics.PorterDuff; -import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Parcelable; @@ -64,6 +62,7 @@ import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; +import org.mariotaku.menucomponent.internal.menu.MenuUtils; import org.mariotaku.querybuilder.Where; import org.mariotaku.twidere.R; import org.mariotaku.twidere.activity.support.AccountSelectorActivity; @@ -89,6 +88,8 @@ import org.mariotaku.twidere.util.ParseUtils; import org.mariotaku.twidere.util.ThemeUtils; import org.mariotaku.twidere.util.TwidereLinkify; import org.mariotaku.twidere.util.TwidereLinkify.OnLinkClickListener; +import org.mariotaku.twidere.util.Utils; +import org.mariotaku.twidere.util.menu.TwidereMenuInfo; import org.mariotaku.twidere.view.ColorLabelLinearLayout; import org.mariotaku.twidere.view.ExtendedFrameLayout; import org.mariotaku.twidere.view.ProfileImageView; @@ -180,27 +181,31 @@ public class UserProfileFragment extends BaseSupportListFragment implements OnCl if (getActivity() == null || !isAdded() || isDetached()) return; if (mUser == null) return; final String action = intent.getAction(); - if (BROADCAST_FRIENDSHIP_CHANGED.equals(action)) { - if (intent.getLongExtra(EXTRA_USER_ID, -1) == mUser.id && intent.getBooleanExtra(EXTRA_SUCCEED, false)) { - getFriendship(); + switch (action) { + case BROADCAST_FRIENDSHIP_CHANGED: { + if (intent.getLongExtra(EXTRA_USER_ID, -1) == mUser.id) { + getFriendship(); + } + break; } - } else if (BROADCAST_BLOCKSTATE_CHANGED.equals(action)) { - if (intent.getLongExtra(EXTRA_USER_ID, -1) == mUser.id && intent.getBooleanExtra(EXTRA_SUCCEED, false)) { - getFriendship(); + case BROADCAST_PROFILE_UPDATED: + case BROADCAST_PROFILE_IMAGE_UPDATED: + case BROADCAST_PROFILE_BANNER_UPDATED: { + if (intent.getLongExtra(EXTRA_USER_ID, -1) == mUser.id) { + getUserInfo(true); + } + break; } - } else if (BROADCAST_PROFILE_UPDATED.equals(action) || BROADCAST_PROFILE_IMAGE_UPDATED.equals(action) - || BROADCAST_PROFILE_BANNER_UPDATED.equals(action)) { - if (intent.getLongExtra(EXTRA_USER_ID, -1) == mUser.id && intent.getBooleanExtra(EXTRA_SUCCEED, false)) { - getUserInfo(true); + case BROADCAST_TASK_STATE_CHANGED: { + final AsyncTwitterWrapper twitter = getTwitterWrapper(); + final boolean is_creating_friendship = twitter != null + && twitter.isCreatingFriendship(mUser.account_id, mUser.id); + final boolean is_destroying_friendship = twitter != null + && twitter.isDestroyingFriendship(mUser.account_id, mUser.id); + setProgressBarIndeterminateVisibility(is_creating_friendship || is_destroying_friendship); + invalidateOptionsMenu(); + break; } - } else if (BROADCAST_TASK_STATE_CHANGED.equals(action)) { - final AsyncTwitterWrapper twitter = getTwitterWrapper(); - final boolean is_creating_friendship = twitter != null - && twitter.isCreatingFriendship(mUser.account_id, mUser.id); - final boolean is_destroying_friendship = twitter != null - && twitter.isDestroyingFriendship(mUser.account_id, mUser.id); - setProgressBarIndeterminateVisibility(is_creating_friendship || is_destroying_friendship); - invalidateOptionsMenu(); } } }; @@ -697,7 +702,6 @@ public class UserProfileFragment extends BaseSupportListFragment implements OnCl super.onStart(); final IntentFilter filter = new IntentFilter(BROADCAST_TASK_STATE_CHANGED); filter.addAction(BROADCAST_FRIENDSHIP_CHANGED); - filter.addAction(BROADCAST_BLOCKSTATE_CHANGED); filter.addAction(BROADCAST_PROFILE_UPDATED); filter.addAction(BROADCAST_PROFILE_IMAGE_UPDATED); filter.addAction(BROADCAST_PROFILE_BANNER_UPDATED); @@ -791,10 +795,27 @@ public class UserProfileFragment extends BaseSupportListFragment implements OnCl break; } case MENU_ADD_TO_FILTER: { - final ContentResolver resolver = getContentResolver(); - resolver.delete(Filters.Users.CONTENT_URI, Where.equals(Filters.Users.USER_ID, user.id).getSQL(), null); - resolver.insert(Filters.Users.CONTENT_URI, ContentValuesCreator.makeFilteredUserContentValues(user)); - showInfoMessage(getActivity(), R.string.message_user_muted, false); + final boolean filtering = Utils.isFilteringUser(getActivity(), user.id); + final ContentResolver cr = getContentResolver(); + if (filtering) { + final Where where = Where.equals(Filters.Users.USER_ID, user.id); + cr.delete(Filters.Users.CONTENT_URI, where.getSQL(), null); + showInfoMessage(getActivity(), R.string.message_user_unmuted, false); + } else { + cr.insert(Filters.Users.CONTENT_URI, ContentValuesCreator.makeFilteredUserContentValues(user)); + showInfoMessage(getActivity(), R.string.message_user_muted, false); + } + setMenu(mMenuBar.getMenu()); + break; + } + case MENU_MUTE_USER: { + if (mRelationship != null) { + if (mRelationship.isSourceMutingTarget()) { + twitter.destroyMuteAsync(user.account_id, user.id); + } else { + CreateUserMuteDialogFragment.show(getFragmentManager(), user); + } + } break; } case MENU_MENTION: { @@ -889,7 +910,6 @@ public class UserProfileFragment extends BaseSupportListFragment implements OnCl final ParcelableUser user = mUser; final Relationship relationship = mRelationship; if (twitter == null || user == null) return; - final int activatedColor = ThemeUtils.getUserAccentColor(getActivity()); final boolean isMyself = user.account_id == user.id; final boolean isFollowing = relationship != null && relationship.isSourceFollowingTarget(); final boolean isProtected = user.is_protected; @@ -912,17 +932,24 @@ public class UserProfileFragment extends BaseSupportListFragment implements OnCl if (user.id != user.account_id && relationship != null) { setMenuItemAvailability(menu, MENU_SEND_DIRECT_MESSAGE, relationship.canSourceDMTarget()); setMenuItemAvailability(menu, MENU_BLOCK, true); + setMenuItemAvailability(menu, MENU_MUTE_USER, true); final MenuItem blockItem = menu.findItem(MENU_BLOCK); if (blockItem != null) { - final Drawable blockIcon = blockItem.getIcon(); - if (relationship.isSourceBlockingTarget()) { - blockItem.setTitle(R.string.unblock); - blockIcon.mutate(); - blockIcon.setColorFilter(activatedColor, PorterDuff.Mode.SRC_ATOP); - } else { - blockItem.setTitle(R.string.block); - blockIcon.clearColorFilter(); - } + final boolean blocking = relationship.isSourceBlockingTarget(); + MenuUtils.setMenuInfo(blockItem, new TwidereMenuInfo(blocking)); + blockItem.setTitle(blocking ? R.string.unblock : R.string.block); + } + final MenuItem muteItem = menu.findItem(MENU_MUTE_USER); + if (muteItem != null) { + final boolean muting = relationship.isSourceMutingTarget(); + MenuUtils.setMenuInfo(muteItem, new TwidereMenuInfo(muting)); + muteItem.setTitle(muting ? R.string.unmute : R.string.mute); + } + final MenuItem filterItem = menu.findItem(MENU_ADD_TO_FILTER); + if (filterItem != null) { + final boolean filtering = Utils.isFilteringUser(getActivity(), user.id); + MenuUtils.setMenuInfo(filterItem, new TwidereMenuInfo(filtering)); + filterItem.setTitle(filtering ? R.string.remove_from_filter : R.string.add_to_filter); } } else { setMenuItemAvailability(menu, MENU_SEND_DIRECT_MESSAGE, false); diff --git a/twidere/src/main/java/org/mariotaku/twidere/util/AsyncTwitterWrapper.java b/twidere/src/main/java/org/mariotaku/twidere/util/AsyncTwitterWrapper.java index 06d1145ca..856823ef3 100644 --- a/twidere/src/main/java/org/mariotaku/twidere/util/AsyncTwitterWrapper.java +++ b/twidere/src/main/java/org/mariotaku/twidere/util/AsyncTwitterWrapper.java @@ -19,24 +19,6 @@ package org.mariotaku.twidere.util; -import static org.mariotaku.twidere.provider.TweetStore.STATUSES_URIS; -import static org.mariotaku.twidere.util.ContentValuesCreator.makeDirectMessageContentValues; -import static org.mariotaku.twidere.util.ContentValuesCreator.makeStatusContentValues; -import static org.mariotaku.twidere.util.ContentValuesCreator.makeTrendsContentValues; -import static org.mariotaku.twidere.util.Utils.appendQueryParameters; -import static org.mariotaku.twidere.util.Utils.getActivatedAccountIds; -import static org.mariotaku.twidere.util.Utils.getAllStatusesIds; -import static org.mariotaku.twidere.util.Utils.getDefaultAccountId; -import static org.mariotaku.twidere.util.Utils.getNewestMessageIdsFromDatabase; -import static org.mariotaku.twidere.util.Utils.getNewestStatusIdsFromDatabase; -import static org.mariotaku.twidere.util.Utils.getStatusIdsInDatabase; -import static org.mariotaku.twidere.util.Utils.getTwitterInstance; -import static org.mariotaku.twidere.util.Utils.getUserName; -import static org.mariotaku.twidere.util.Utils.truncateMessages; -import static org.mariotaku.twidere.util.Utils.truncateStatuses; -import static org.mariotaku.twidere.util.content.ContentResolverUtils.bulkDelete; -import static org.mariotaku.twidere.util.content.ContentResolverUtils.bulkInsert; - import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; @@ -46,8 +28,6 @@ import android.content.res.Resources; import android.net.Uri; import android.os.Bundle; -import edu.ucdavis.earlybird.ProfilingUtil; - import org.mariotaku.querybuilder.Columns.Column; import org.mariotaku.querybuilder.RawItemArray; import org.mariotaku.querybuilder.Where; @@ -75,6 +55,14 @@ import org.mariotaku.twidere.task.AsyncTask; import org.mariotaku.twidere.task.CacheUsersStatusesTask; import org.mariotaku.twidere.task.ManagedAsyncTask; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import edu.ucdavis.earlybird.ProfilingUtil; import twitter4j.DirectMessage; import twitter4j.Paging; import twitter4j.ResponseList; @@ -86,2268 +74,2276 @@ import twitter4j.User; import twitter4j.UserList; import twitter4j.http.HttpResponseCode; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Set; +import static org.mariotaku.twidere.provider.TweetStore.STATUSES_URIS; +import static org.mariotaku.twidere.util.ContentValuesCreator.makeDirectMessageContentValues; +import static org.mariotaku.twidere.util.ContentValuesCreator.makeStatusContentValues; +import static org.mariotaku.twidere.util.ContentValuesCreator.makeTrendsContentValues; +import static org.mariotaku.twidere.util.Utils.appendQueryParameters; +import static org.mariotaku.twidere.util.Utils.getActivatedAccountIds; +import static org.mariotaku.twidere.util.Utils.getDefaultAccountId; +import static org.mariotaku.twidere.util.Utils.getNewestMessageIdsFromDatabase; +import static org.mariotaku.twidere.util.Utils.getNewestStatusIdsFromDatabase; +import static org.mariotaku.twidere.util.Utils.getStatusIdsInDatabase; +import static org.mariotaku.twidere.util.Utils.getTwitterInstance; +import static org.mariotaku.twidere.util.Utils.getUserName; +import static org.mariotaku.twidere.util.Utils.truncateMessages; +import static org.mariotaku.twidere.util.Utils.truncateStatuses; +import static org.mariotaku.twidere.util.content.ContentResolverUtils.bulkDelete; +import static org.mariotaku.twidere.util.content.ContentResolverUtils.bulkInsert; public class AsyncTwitterWrapper extends TwitterWrapper { - private static AsyncTwitterWrapper sInstance; - - private final Context mContext; - private final AsyncTaskManager mAsyncTaskManager; - private final SharedPreferences mPreferences; - private final MessagesManager mMessagesManager; - private final ContentResolver mResolver; - - private int mGetHomeTimelineTaskId, mGetMentionsTaskId; - private int mGetReceivedDirectMessagesTaskId, mGetSentDirectMessagesTaskId; - private int mGetLocalTrendsTaskId; - - public AsyncTwitterWrapper(final Context context) { - mContext = context; - final TwidereApplication app = TwidereApplication.getInstance(context); - mAsyncTaskManager = app.getAsyncTaskManager(); - mMessagesManager = app.getMessagesManager(); - mPreferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); - mResolver = context.getContentResolver(); - } - - public int acceptFriendshipAsync(final long accountId, final long userId) { - final AcceptFriendshipTask task = new AcceptFriendshipTask(accountId, userId); - return mAsyncTaskManager.add(task, true); - } - - public int addUserListMembersAsync(final long accountId, final long listId, final ParcelableUser... users) { - final AddUserListMembersTask task = new AddUserListMembersTask(accountId, listId, users); - return mAsyncTaskManager.add(task, true); - } - - public void clearNotificationAsync(final int notificationType) { - clearNotificationAsync(notificationType, 0); - } - - public void clearNotificationAsync(final int notificationId, final long notificationAccount) { - final ClearNotificationTask task = new ClearNotificationTask(notificationId, notificationAccount); - task.execute(); - } - - public void clearUnreadCountAsync(final int position) { - final ClearUnreadCountTask task = new ClearUnreadCountTask(position); - task.execute(); - } - - public int createBlockAsync(final long accountId, final long user_id) { - final CreateBlockTask task = new CreateBlockTask(accountId, user_id); - return mAsyncTaskManager.add(task, true); - } - - public int createFavoriteAsync(final long accountId, final long status_id) { - final CreateFavoriteTask task = new CreateFavoriteTask(accountId, status_id); - return mAsyncTaskManager.add(task, true); - } - - public int createFriendshipAsync(final long accountId, final long userId) { - final CreateFriendshipTask task = new CreateFriendshipTask(accountId, userId); - return mAsyncTaskManager.add(task, true); - } - - public int createMultiBlockAsync(final long accountId, final long[] userIds) { - final CreateMultiBlockTask task = new CreateMultiBlockTask(accountId, userIds); - return mAsyncTaskManager.add(task, true); - } - - public int createSavedSearchAsync(final long accountId, final String query) { - final CreateSavedSearchTask task = new CreateSavedSearchTask(accountId, query); - return mAsyncTaskManager.add(task, true); - } - - public int createUserListAsync(final long accountId, final String list_name, final boolean is_public, - final String description) { - final CreateUserListTask task = new CreateUserListTask(accountId, list_name, is_public, description); - return mAsyncTaskManager.add(task, true); - } - - public int createUserListSubscriptionAsync(final long accountId, final long listId) { - final CreateUserListSubscriptionTask task = new CreateUserListSubscriptionTask(accountId, listId); - return mAsyncTaskManager.add(task, true); - } - - public int deleteUserListMembersAsync(final long accountId, final long listId, final ParcelableUser... users) { - final DeleteUserListMembersTask task = new DeleteUserListMembersTask(accountId, listId, users); - return mAsyncTaskManager.add(task, true); - } - - public int denyFriendshipAsync(final long accountId, final long userId) { - final DenyFriendshipTask task = new DenyFriendshipTask(accountId, userId); - return mAsyncTaskManager.add(task, true); - } - - public int destroyBlockAsync(final long accountId, final long user_id) { - final DestroyBlockTask task = new DestroyBlockTask(accountId, user_id); - return mAsyncTaskManager.add(task, true); - } - - public int destroyDirectMessageAsync(final long accountId, final long message_id) { - final DestroyDirectMessageTask task = new DestroyDirectMessageTask(accountId, message_id); - return mAsyncTaskManager.add(task, true); - } - - public int destroyFavoriteAsync(final long accountId, final long status_id) { - final DestroyFavoriteTask task = new DestroyFavoriteTask(accountId, status_id); - return mAsyncTaskManager.add(task, true); - } - - public int destroyFriendshipAsync(final long accountId, final long user_id) { - final DestroyFriendshipTask task = new DestroyFriendshipTask(accountId, user_id); - return mAsyncTaskManager.add(task, true); - } - - public int destroySavedSearchAsync(final long accountId, final int searchId) { - final DestroySavedSearchTask task = new DestroySavedSearchTask(accountId, searchId); - return mAsyncTaskManager.add(task, true); - } - - public int destroyStatusAsync(final long accountId, final long status_id) { - final DestroyStatusTask task = new DestroyStatusTask(accountId, status_id); - return mAsyncTaskManager.add(task, true); - } - - public int destroyUserListAsync(final long accountId, final long listId) { - final DestroyUserListTask task = new DestroyUserListTask(accountId, listId); - return mAsyncTaskManager.add(task, true); - } - - public int destroyUserListSubscriptionAsync(final long accountId, final long listId) { - final DestroyUserListSubscriptionTask task = new DestroyUserListSubscriptionTask(accountId, listId); - return mAsyncTaskManager.add(task, true); - } - - public int getHomeTimelineAsync(final long[] accountIds, final long[] max_ids, final long[] since_ids) { - mAsyncTaskManager.cancel(mGetHomeTimelineTaskId); - final GetHomeTimelineTask task = new GetHomeTimelineTask(accountIds, max_ids, since_ids); - return mGetHomeTimelineTaskId = mAsyncTaskManager.add(task, true); - } - - public int getLocalTrendsAsync(final long accountId, final int woeid) { - mAsyncTaskManager.cancel(mGetLocalTrendsTaskId); - final GetLocalTrendsTask task = new GetLocalTrendsTask(accountId, woeid); - return mGetLocalTrendsTaskId = mAsyncTaskManager.add(task, true); - } - - public int getMentionsAsync(final long[] accountIds, final long[] max_ids, final long[] since_ids) { - mAsyncTaskManager.cancel(mGetMentionsTaskId); - final GetMentionsTask task = new GetMentionsTask(accountIds, max_ids, since_ids); - return mGetMentionsTaskId = mAsyncTaskManager.add(task, true); - } - - public int getReceivedDirectMessagesAsync(final long[] accountIds, final long[] max_ids, final long[] since_ids) { - mAsyncTaskManager.cancel(mGetReceivedDirectMessagesTaskId); - final GetReceivedDirectMessagesTask task = new GetReceivedDirectMessagesTask(accountIds, max_ids, since_ids); - return mGetReceivedDirectMessagesTaskId = mAsyncTaskManager.add(task, true); - } - - public int getSentDirectMessagesAsync(final long[] accountIds, final long[] max_ids, final long[] since_ids) { - mAsyncTaskManager.cancel(mGetSentDirectMessagesTaskId); - final GetSentDirectMessagesTask task = new GetSentDirectMessagesTask(accountIds, max_ids, since_ids); - return mGetSentDirectMessagesTaskId = mAsyncTaskManager.add(task, true); - } - - public boolean hasActivatedTask() { - return mAsyncTaskManager.hasRunningTask(); - } - - public boolean isCreatingFriendship(final long accountId, final long user_id) { - for (final ManagedAsyncTask task : mAsyncTaskManager.getTaskSpecList()) { - if (task instanceof CreateFriendshipTask) { - final CreateFriendshipTask create_friendship = (CreateFriendshipTask) task; - if (create_friendship.getStatus() == AsyncTask.Status.RUNNING - && create_friendship.getAccountId() == accountId && create_friendship.getUserId() == user_id) - return true; - } - } - return false; - } - - public boolean isDestroyingFriendship(final long accountId, final long user_id) { - for (final ManagedAsyncTask task : mAsyncTaskManager.getTaskSpecList()) { - if (task instanceof DestroyFriendshipTask) { - final DestroyFriendshipTask create_friendship = (DestroyFriendshipTask) task; - if (create_friendship.getStatus() == AsyncTask.Status.RUNNING - && create_friendship.getAccountId() == accountId && create_friendship.getUserId() == user_id) - return true; - } - } - return false; - } - - public boolean isHomeTimelineRefreshing() { - return mAsyncTaskManager.hasRunningTasksForTag(TASK_TAG_GET_HOME_TIMELINE) - || mAsyncTaskManager.hasRunningTasksForTag(TASK_TAG_STORE_HOME_TIMELINE); - } - - public boolean isLocalTrendsRefreshing() { - return mAsyncTaskManager.hasRunningTasksForTag(TASK_TAG_GET_TRENDS) - || mAsyncTaskManager.hasRunningTasksForTag(TASK_TAG_STORE_TRENDS); - } - - public boolean isMentionsRefreshing() { - return mAsyncTaskManager.hasRunningTasksForTag(TASK_TAG_GET_MENTIONS) - || mAsyncTaskManager.hasRunningTasksForTag(TASK_TAG_STORE_MENTIONS); - } - - public boolean isReceivedDirectMessagesRefreshing() { - return mAsyncTaskManager.hasRunningTasksForTag(TASK_TAG_GET_RECEIVED_DIRECT_MESSAGES) - || mAsyncTaskManager.hasRunningTasksForTag(TASK_TAG_STORE_RECEIVED_DIRECT_MESSAGES); - } - - public boolean isSentDirectMessagesRefreshing() { - return mAsyncTaskManager.hasRunningTasksForTag(TASK_TAG_GET_SENT_DIRECT_MESSAGES) - || mAsyncTaskManager.hasRunningTasksForTag(TASK_TAG_STORE_SENT_DIRECT_MESSAGES); - } - - public int refreshAll() { - final long[] accountIds = getActivatedAccountIds(mContext); - return refreshAll(accountIds); - } - - public int refreshAll(final long[] accountIds) { - if (mPreferences.getBoolean(KEY_HOME_REFRESH_MENTIONS, HomeRefreshContentPreference.DEFAULT_ENABLE_MENTIONS)) { - final long[] sinceIds = getNewestStatusIdsFromDatabase(mContext, Mentions.CONTENT_URI, accountIds); - getMentionsAsync(accountIds, null, sinceIds); - } - if (mPreferences.getBoolean(KEY_HOME_REFRESH_DIRECT_MESSAGES, - HomeRefreshContentPreference.DEFAULT_ENABLE_DIRECT_MESSAGES)) { - final long[] sinceIds = getNewestMessageIdsFromDatabase(mContext, DirectMessages.Inbox.CONTENT_URI, - accountIds); - getReceivedDirectMessagesAsync(accountIds, null, sinceIds); - getSentDirectMessagesAsync(accountIds, null, null); - } - if (mPreferences.getBoolean(KEY_HOME_REFRESH_TRENDS, HomeRefreshContentPreference.DEFAULT_ENABLE_TRENDS)) { - final long accountId = getDefaultAccountId(mContext); - final int woeId = mPreferences.getInt(KEY_LOCAL_TRENDS_WOEID, 1); - getLocalTrendsAsync(accountId, woeId); - } - final long[] statusSinceIds = getNewestStatusIdsFromDatabase(mContext, Statuses.CONTENT_URI, accountIds); - return getHomeTimelineAsync(accountIds, null, statusSinceIds); - } - - public void removeUnreadCountsAsync(final int position, final Map> counts) { - final RemoveUnreadCountsTask task = new RemoveUnreadCountsTask(position, counts); - task.execute(); - } - - public int reportMultiSpam(final long accountId, final long[] user_ids) { - final ReportMultiSpamTask task = new ReportMultiSpamTask(accountId, user_ids); - return mAsyncTaskManager.add(task, true); - } - - public int reportSpamAsync(final long accountId, final long user_id) { - final ReportSpamTask task = new ReportSpamTask(accountId, user_id); - return mAsyncTaskManager.add(task, true); - } - - public int retweetStatus(final long accountId, final long status_id) { - final RetweetStatusTask task = new RetweetStatusTask(accountId, status_id); - return mAsyncTaskManager.add(task, true); - } - - public int sendDirectMessageAsync(final long accountId, final long recipientId, final String text, - final String imageUri) { - final Intent intent = new Intent(mContext, BackgroundOperationService.class); - intent.setAction(INTENT_ACTION_SEND_DIRECT_MESSAGE); - intent.putExtra(EXTRA_ACCOUNT_ID, accountId); - intent.putExtra(EXTRA_RECIPIENT_ID, recipientId); - intent.putExtra(EXTRA_TEXT, text); - intent.putExtra(EXTRA_IMAGE_URI, imageUri); - mContext.startService(intent); - return 0; - } - - public int updateProfile(final long accountId, final String name, final String url, final String location, - final String description) { - final UpdateProfileTask task = new UpdateProfileTask(mContext, mAsyncTaskManager, accountId, name, url, - location, description); - return mAsyncTaskManager.add(task, true); - } - - public int updateProfileBannerImage(final long accountId, final Uri image_uri, final boolean delete_image) { - final UpdateProfileBannerImageTask task = new UpdateProfileBannerImageTask(mContext, mAsyncTaskManager, - accountId, image_uri, delete_image); - return mAsyncTaskManager.add(task, true); - } - - public int updateProfileImage(final long accountId, final Uri imageUri, final boolean deleteImage) { - final UpdateProfileImageTask task = new UpdateProfileImageTask(mContext, mAsyncTaskManager, accountId, - imageUri, deleteImage); - return mAsyncTaskManager.add(task, true); - } - - public int updateStatusAsync(final long[] accountIds, final String text, final ParcelableLocation location, - final ParcelableMediaUpdate[] medias, final long inReplyToStatusId, final boolean isPossiblySensitive) { - final ParcelableStatusUpdate.Builder builder = new ParcelableStatusUpdate.Builder(); - builder.accounts(Account.getAccounts(mContext, accountIds)); - builder.text(text); - builder.location(location); - builder.medias(medias); - builder.inReplyToStatusId(inReplyToStatusId); - builder.isPossiblySensitive(isPossiblySensitive); - return updateStatusesAsync(builder.build()); - } - - public int updateStatusesAsync(final ParcelableStatusUpdate... statuses) { - final Intent intent = new Intent(mContext, BackgroundOperationService.class); - intent.setAction(INTENT_ACTION_UPDATE_STATUS); - intent.putExtra(EXTRA_STATUSES, statuses); - mContext.startService(intent); - return 0; - } - - public int updateUserListDetails(final long accountId, final long listId, final boolean isPublic, - final String name, final String description) { - final UpdateUserListDetailsTask task = new UpdateUserListDetailsTask(accountId, listId, isPublic, name, - description); - return mAsyncTaskManager.add(task, true); - } - - public static AsyncTwitterWrapper getInstance(final Context context) { - if (sInstance != null) return sInstance; - return sInstance = new AsyncTwitterWrapper(context); - } - - public static class UpdateProfileBannerImageTask extends ManagedAsyncTask> { - - private final long mAccountId; - private final Uri mImageUri; - private final boolean mDeleteImage; - private final Context mContext; - - public UpdateProfileBannerImageTask(final Context context, final AsyncTaskManager manager, - final long account_id, final Uri image_uri, final boolean delete_image) { - super(context, manager); - mContext = context; - mAccountId = account_id; - mImageUri = image_uri; - mDeleteImage = delete_image; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - return TwitterWrapper.updateProfileBannerImage(mContext, mAccountId, mImageUri, mDeleteImage); - } - - @Override - protected void onPostExecute(final SingleResponse result) { - if (result.hasData() && result.getData()) { - Utils.showOkMessage(mContext, R.string.profile_banner_image_updated, false); - } else { - Utils.showErrorMessage(mContext, R.string.action_updating_profile_banner_image, result.getException(), - true); - } - final Intent intent = new Intent(BROADCAST_PROFILE_BANNER_UPDATED); - intent.putExtra(EXTRA_USER_ID, mAccountId); - intent.putExtra(EXTRA_SUCCEED, result.hasData()); - mContext.sendBroadcast(intent); - super.onPostExecute(result); - } - - } - - public static class UpdateProfileImageTask extends ManagedAsyncTask> { - - private final long account_id; - private final Uri image_uri; - private final boolean delete_image; - private final Context context; - - public UpdateProfileImageTask(final Context context, final AsyncTaskManager manager, final long account_id, - final Uri image_uri, final boolean delete_image) { - super(context, manager); - this.context = context; - this.account_id = account_id; - this.image_uri = image_uri; - this.delete_image = delete_image; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - return TwitterWrapper.updateProfileImage(context, account_id, image_uri, delete_image); - } - - @Override - protected void onPostExecute(final SingleResponse result) { - if (result.hasData()) { - Utils.showOkMessage(context, R.string.profile_image_updated, false); - } else { - Utils.showErrorMessage(context, R.string.action_updating_profile_image, result.getException(), true); - } - final Intent intent = new Intent(BROADCAST_PROFILE_UPDATED); - intent.putExtra(EXTRA_USER_ID, account_id); - intent.putExtra(EXTRA_SUCCEED, result.hasData()); - context.sendBroadcast(intent); - super.onPostExecute(result); - } - - } - - public static class UpdateProfileTask extends ManagedAsyncTask> { - - private final long account_id; - private final String name, url, location, description; - private final Context context; - - public UpdateProfileTask(final Context context, final AsyncTaskManager manager, final long account_id, - final String name, final String url, final String location, final String description) { - super(context, manager); - this.context = context; - this.account_id = account_id; - this.name = name; - this.url = url; - this.location = location; - this.description = description; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - return updateProfile(context, account_id, name, url, location, description); - } - - @Override - protected void onPostExecute(final SingleResponse result) { - if (result.hasData()) { - Utils.showOkMessage(context, R.string.profile_updated, false); - } else { - Utils.showErrorMessage(context, context.getString(R.string.action_updating_profile), - result.getException(), true); - } - final Intent intent = new Intent(BROADCAST_PROFILE_IMAGE_UPDATED); - intent.putExtra(EXTRA_USER_ID, account_id); - intent.putExtra(EXTRA_SUCCEED, result.hasData()); - context.sendBroadcast(intent); - super.onPostExecute(result); - } - - } - - class AcceptFriendshipTask extends ManagedAsyncTask> { - - private final long mAccountId; - private final long mUserId; - - public AcceptFriendshipTask(final long account_id, final long user_id) { - super(mContext, mAsyncTaskManager); - mAccountId = account_id; - mUserId = user_id; - } - - public long getAccountId() { - return mAccountId; - } - - public long getUserId() { - return mUserId; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - - final Twitter twitter = getTwitterInstance(mContext, mAccountId, false); - if (twitter == null) return SingleResponse.getInstance(); - try { - final User user = twitter.acceptFriendship(mUserId); - return SingleResponse.getInstance(user, null); - } catch (final TwitterException e) { - return SingleResponse.getInstance(null, e); - } - } - - @Override - protected void onPostExecute(final SingleResponse result) { - if (result.hasData()) { - final User user = result.getData(); - final String message = mContext.getString(R.string.accepted_users_follow_request, - getUserName(mContext, user)); - mMessagesManager.showOkMessage(message, false); - } else { - mMessagesManager.showErrorMessage(R.string.action_accepting_follow_request, result.getException(), - false); - } - final Intent intent = new Intent(BROADCAST_FRIENDSHIP_ACCEPTED); - intent.putExtra(EXTRA_USER_ID, mUserId); - intent.putExtra(EXTRA_SUCCEED, result.hasData()); - mContext.sendBroadcast(intent); - super.onPostExecute(result); - } - - } - - class AddUserListMembersTask extends ManagedAsyncTask> { - - private final long accountId; - private final long listId; - private final ParcelableUser[] users; - - public AddUserListMembersTask(final long accountId, final long listId, final ParcelableUser[] users) { - super(mContext, mAsyncTaskManager); - this.accountId = accountId; - this.listId = listId; - this.users = users; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - final Twitter twitter = getTwitterInstance(mContext, accountId, false); - if (twitter == null || users == null) return SingleResponse.getInstance(); - try { - final long[] userIds = new long[users.length]; - for (int i = 0, j = users.length; i < j; i++) { - userIds[i] = users[i].id; - } - final ParcelableUserList list = new ParcelableUserList(twitter.addUserListMembers(listId, userIds), - accountId); - return SingleResponse.getInstance(list, null); - } catch (final TwitterException e) { - return SingleResponse.getInstance(null, e); - } - } - - @Override - protected void onPostExecute(final SingleResponse result) { - final boolean succeed = result.hasData() && result.getData().id > 0; - if (succeed) { - final String message; - if (users.length == 1) { - final ParcelableUser user = users[0]; - final String displayName = Utils.getDisplayName(mContext, user.id, user.name, user.screen_name); - message = mContext.getString(R.string.added_user_to_list, displayName, result.getData().name); - } else { - final Resources res = mContext.getResources(); - message = res.getQuantityString(R.plurals.added_N_users_to_list, users.length, users.length, - result.getData().name); - } - mMessagesManager.showOkMessage(message, false); - } else { - mMessagesManager.showErrorMessage(R.string.action_adding_member, result.getException(), true); - } - final Intent intent = new Intent(BROADCAST_USER_LIST_MEMBERS_ADDED); - intent.putExtra(EXTRA_USER_LIST, result.getData()); - intent.putExtra(EXTRA_USERS, users); - intent.putExtra(EXTRA_SUCCEED, succeed); - mContext.sendBroadcast(intent); - super.onPostExecute(result); - } - - } - - final class ClearNotificationTask extends AsyncTask { - private final int notificationType; - private final long accountId; - - ClearNotificationTask(final int notificationType, final long accountId) { - this.notificationType = notificationType; - this.accountId = accountId; - } - - @Override - protected Integer doInBackground(final Void... params) { - return clearNotification(mContext, notificationType, accountId); - } - - } - - final class ClearUnreadCountTask extends AsyncTask { - private final int position; - - ClearUnreadCountTask(final int position) { - this.position = position; - } - - @Override - protected Integer doInBackground(final Void... params) { - return clearUnreadCount(mContext, position); - } - - } - - class CreateBlockTask extends ManagedAsyncTask> { - - private final long account_id, user_id; - - public CreateBlockTask(final long account_id, final long user_id) { - super(mContext, mAsyncTaskManager); - this.account_id = account_id; - this.user_id = user_id; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - final Twitter twitter = getTwitterInstance(mContext, account_id, false); - if (twitter == null) return SingleResponse.getInstance(); - try { - final User user = twitter.createBlock(user_id); - for (final Uri uri : STATUSES_URIS) { - final String where = Statuses.ACCOUNT_ID + " = " + account_id + " AND " + Statuses.USER_ID + " = " - + user_id; - mResolver.delete(uri, where, null); - - } - // I bet you don't want to see this user in your auto - // complete - // list. - final String where = CachedUsers.USER_ID + " = " + user_id; - mResolver.delete(CachedUsers.CONTENT_URI, where, null); - return SingleResponse.getInstance(user, null); - } catch (final TwitterException e) { - return SingleResponse.getInstance(null, e); - } - } - - @Override - protected void onPostExecute(final SingleResponse result) { - if (result.hasData() && result.getData().getId() > 0) { - final String message = mContext.getString(R.string.blocked_user, - getUserName(mContext, result.getData())); - mMessagesManager.showInfoMessage(message, false); - } else { - mMessagesManager.showErrorMessage(R.string.action_blocking, result.getException(), true); - } - final Intent intent = new Intent(BROADCAST_BLOCKSTATE_CHANGED); - intent.putExtra(EXTRA_USER_ID, user_id); - intent.putExtra(EXTRA_SUCCEED, result.hasData()); - mContext.sendBroadcast(intent); - super.onPostExecute(result); - } - - } - - class CreateFavoriteTask extends ManagedAsyncTask> { - - private final long account_id, status_id; - - public CreateFavoriteTask(final long account_id, final long status_id) { - super(mContext, mAsyncTaskManager); - this.account_id = account_id; - this.status_id = status_id; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - if (account_id < 0) return SingleResponse.getInstance(); - final Twitter twitter = getTwitterInstance(mContext, account_id, false); - if (twitter == null) return SingleResponse.getInstance(); - try { - final twitter4j.Status status = twitter.createFavorite(status_id); - final ContentValues values = new ContentValues(); - values.put(Statuses.IS_FAVORITE, true); - final StringBuilder where = new StringBuilder(); - where.append(Statuses.ACCOUNT_ID + " = " + account_id); - where.append(" AND "); - where.append("("); - where.append(Statuses.STATUS_ID + " = " + status_id); - where.append(" OR "); - where.append(Statuses.RETWEET_ID + " = " + status_id); - where.append(")"); - for (final Uri uri : TweetStore.STATUSES_URIS) { - mResolver.update(uri, values, where.toString(), null); - } - return SingleResponse.getInstance(new ParcelableStatus(status, account_id, false)); - } catch (final TwitterException e) { - return SingleResponse.getInstance(e); - } - } - - @Override - protected void onPostExecute(final SingleResponse result) { - if (result.hasData()) { - final Intent intent = new Intent(BROADCAST_FAVORITE_CHANGED); - intent.putExtra(EXTRA_STATUS, result.getData()); - intent.putExtra(EXTRA_FAVORITED, true); - mContext.sendBroadcast(intent); - mMessagesManager.showOkMessage(R.string.status_favorited, false); - } else { - mMessagesManager.showErrorMessage(R.string.action_favoriting, result.getException(), true); - } - super.onPostExecute(result); - } - - } - - class CreateFriendshipTask extends ManagedAsyncTask> { - - private final long account_id; - private final long user_id; - - public CreateFriendshipTask(final long account_id, final long user_id) { - super(mContext, mAsyncTaskManager); - this.account_id = account_id; - this.user_id = user_id; - } - - public long getAccountId() { - return account_id; - } - - public long getUserId() { - return user_id; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - - final Twitter twitter = getTwitterInstance(mContext, account_id, false); - if (twitter == null) return SingleResponse.getInstance(); - try { - final User user = twitter.createFriendship(user_id); - return SingleResponse.getInstance(user, null); - } catch (final TwitterException e) { - return SingleResponse.getInstance(null, e); - } - } - - @Override - protected void onPostExecute(final SingleResponse result) { - if (result.hasData()) { - final User user = result.getData(); - final String message; - if (user.isProtected()) { - message = mContext.getString(R.string.sent_follow_request_to_user, getUserName(mContext, user)); - } else { - message = mContext.getString(R.string.followed_user, getUserName(mContext, user)); - } - mMessagesManager.showOkMessage(message, false); - } else { - mMessagesManager.showErrorMessage(R.string.action_following, result.getException(), false); - } - final Intent intent = new Intent(BROADCAST_FRIENDSHIP_CHANGED); - intent.putExtra(EXTRA_USER_ID, user_id); - intent.putExtra(EXTRA_SUCCEED, result.hasData()); - mContext.sendBroadcast(intent); - super.onPostExecute(result); - } - - } - - class CreateMultiBlockTask extends ManagedAsyncTask> { - - private final long account_id; - private final long[] user_ids; - - public CreateMultiBlockTask(final long account_id, final long[] user_ids) { - super(mContext, mAsyncTaskManager); - this.account_id = account_id; - this.user_ids = user_ids; - } - - @Override - protected ListResponse doInBackground(final Void... params) { - final List blocked_users = new ArrayList(); - final Twitter twitter = getTwitterInstance(mContext, account_id, false); - if (twitter != null) { - for (final long user_id : user_ids) { - try { - final User user = twitter.createBlock(user_id); - if (user == null || user.getId() <= 0) { - continue; - } - blocked_users.add(user.getId()); - } catch (final TwitterException e) { - deleteCaches(blocked_users); - return new ListResponse(null, e, null); - } - } - } - deleteCaches(blocked_users); - return new ListResponse(blocked_users, null, null); - } - - @Override - protected void onPostExecute(final ListResponse result) { - if (result.list != null) { - mMessagesManager.showInfoMessage(R.string.users_blocked, false); - } else { - mMessagesManager.showErrorMessage(R.string.action_blocking, result.getException(), true); - } - final Intent intent = new Intent(BROADCAST_MULTI_BLOCKSTATE_CHANGED); - intent.putExtra(EXTRA_USER_ID, user_ids); - intent.putExtra(EXTRA_SUCCEED, result.list != null); - mContext.sendBroadcast(intent); - super.onPostExecute(result); - } - - private void deleteCaches(final List list) { - for (final Uri uri : STATUSES_URIS) { - bulkDelete(mResolver, uri, Statuses.USER_ID, list, Statuses.ACCOUNT_ID + " = " + account_id, false); - } - // I bet you don't want to see these users in your auto complete - // list. - bulkDelete(mResolver, CachedUsers.CONTENT_URI, CachedUsers.USER_ID, list, null, false); - } - } - - class CreateSavedSearchTask extends ManagedAsyncTask> { - - private final long mAccountId; - private final String mQuery; - - CreateSavedSearchTask(final long accountId, final String query) { - super(mContext, mAsyncTaskManager); - mAccountId = accountId; - mQuery = query; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - final Twitter twitter = getTwitterInstance(mContext, mAccountId, false); - if (twitter == null) return null; - try { - return SingleResponse.getInstance(twitter.createSavedSearch(mQuery)); - } catch (final TwitterException e) { - return SingleResponse.getInstance(e); - } - } - - @Override - protected void onPostExecute(final SingleResponse result) { - if (result.hasData()) { - final String message = mContext.getString(R.string.search_name_saved, result.getData().getQuery()); - mMessagesManager.showOkMessage(message, false); - } else { - mMessagesManager.showErrorMessage(R.string.action_saving_search, result.getException(), false); - } - super.onPostExecute(result); - } - - } - - class CreateUserListSubscriptionTask extends ManagedAsyncTask> { - - private final long accountId; - private final long listId; - - public CreateUserListSubscriptionTask(final long accountId, final long listId) { - super(mContext, mAsyncTaskManager); - this.accountId = accountId; - this.listId = listId; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - final Twitter twitter = getTwitterInstance(mContext, accountId, false); - if (twitter == null) return SingleResponse.getInstance(); - - try { - final ParcelableUserList list = new ParcelableUserList(twitter.createUserListSubscription(listId), - accountId); - return new SingleResponse(list, null); - } catch (final TwitterException e) { - return SingleResponse.getInstance(e); - } - } - - @Override - protected void onPostExecute(final SingleResponse result) { - final boolean succeed = result.hasData(); - if (succeed) { - final String message = mContext.getString(R.string.subscribed_to_list, result.getData().name); - mMessagesManager.showOkMessage(message, false); - } else { - mMessagesManager.showErrorMessage(R.string.action_subscribing_to_list, result.getException(), true); - } - final Intent intent = new Intent(BROADCAST_USER_LIST_SUBSCRIBED); - intent.putExtra(EXTRA_USER_LIST, result.getData()); - intent.putExtra(EXTRA_SUCCEED, succeed); - mContext.sendBroadcast(intent); - super.onPostExecute(result); - } - - } - - class CreateUserListTask extends ManagedAsyncTask> { - - private final long account_id; - private final String list_name, description; - private final boolean is_public; - - public CreateUserListTask(final long account_id, final String list_name, final boolean is_public, - final String description) { - super(mContext, mAsyncTaskManager); - this.account_id = account_id; - this.list_name = list_name; - this.description = description; - this.is_public = is_public; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - final Twitter twitter = getTwitterInstance(mContext, account_id, false); - if (twitter == null || list_name == null) return SingleResponse.getInstance(); - try { - final UserList list = twitter.createUserList(list_name, is_public, description); - return SingleResponse.getInstance(list, null); - } catch (final TwitterException e) { - return SingleResponse.getInstance(null, e); - } - } - - @Override - protected void onPostExecute(final SingleResponse result) { - final boolean succeed = result.hasData() && result.getData().getId() > 0; - if (succeed) { - final String message = mContext.getString(R.string.created_list, result.getData().getName()); - mMessagesManager.showOkMessage(message, false); - } else { - mMessagesManager.showErrorMessage(R.string.action_creating_list, result.getException(), true); - } - final Intent intent = new Intent(BROADCAST_USER_LIST_CREATED); - intent.putExtra(EXTRA_SUCCEED, succeed); - mContext.sendBroadcast(intent); - super.onPostExecute(result); - } - - } - - class DeleteUserListMembersTask extends ManagedAsyncTask> { - - private final long mAccountId; - private final long mUserListId; - private final ParcelableUser[] users; - - public DeleteUserListMembersTask(final long accountId, final long userListId, final ParcelableUser[] users) { - super(mContext, mAsyncTaskManager); - mAccountId = accountId; - mUserListId = userListId; - this.users = users; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - final Twitter twitter = getTwitterInstance(mContext, mAccountId, false); - if (twitter == null) return SingleResponse.getInstance(); - try { - final long[] userIds = new long[users.length]; - for (int i = 0, j = users.length; i < j; i++) { - userIds[i] = users[i].id; - } - final ParcelableUserList list = new ParcelableUserList(twitter.deleteUserListMembers(mUserListId, - userIds), mAccountId); - return SingleResponse.getInstance(list, null); - } catch (final TwitterException e) { - return SingleResponse.getInstance(null, e); - } - } - - @Override - protected void onPostExecute(final SingleResponse result) { - final boolean succeed = result.hasData() && result.getData().id > 0; - final String message; - if (succeed) { - if (users.length == 1) { - final ParcelableUser user = users[0]; - final String displayName = Utils.getDisplayName(mContext, user.id, user.name, user.screen_name); - message = mContext.getString(R.string.deleted_user_from_list, displayName, result.getData().name); - } else { - final Resources res = mContext.getResources(); - message = res.getQuantityString(R.plurals.deleted_N_users_from_list, users.length, users.length, - result.getData().name); - } - mMessagesManager.showInfoMessage(message, false); - } else { - mMessagesManager.showErrorMessage(R.string.action_deleting, result.getException(), true); - } - final Intent intent = new Intent(BROADCAST_USER_LIST_MEMBERS_DELETED); - intent.putExtra(EXTRA_USER_LIST, result.getData()); - intent.putExtra(EXTRA_USERS, users); - intent.putExtra(EXTRA_SUCCEED, succeed); - mContext.sendBroadcast(intent); - super.onPostExecute(result); - } - - } - - class DenyFriendshipTask extends ManagedAsyncTask> { - - private final long mAccountId; - private final long mUserId; - - public DenyFriendshipTask(final long account_id, final long user_id) { - super(mContext, mAsyncTaskManager); - mAccountId = account_id; - mUserId = user_id; - } - - public long getAccountId() { - return mAccountId; - } - - public long getUserId() { - return mUserId; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - - final Twitter twitter = getTwitterInstance(mContext, mAccountId, false); - if (twitter == null) return SingleResponse.getInstance(); - try { - final User user = twitter.denyFriendship(mUserId); - return SingleResponse.getInstance(user, null); - } catch (final TwitterException e) { - return SingleResponse.getInstance(null, e); - } - } - - @Override - protected void onPostExecute(final SingleResponse result) { - if (result.hasData()) { - final User user = result.getData(); - final String message = mContext.getString(R.string.denied_users_follow_request, - getUserName(mContext, user)); - mMessagesManager.showOkMessage(message, false); - } else { - mMessagesManager.showErrorMessage(R.string.action_denying_follow_request, result.getException(), false); - } - final Intent intent = new Intent(BROADCAST_FRIENDSHIP_DENIED); - intent.putExtra(EXTRA_USER_ID, mUserId); - intent.putExtra(EXTRA_SUCCEED, result.hasData()); - mContext.sendBroadcast(intent); - super.onPostExecute(result); - } - - } - - class DestroyBlockTask extends ManagedAsyncTask> { - - private final long mAccountId; - private final long mUserId; - - public DestroyBlockTask(final long accountId, final long userId) { - super(mContext, mAsyncTaskManager); - mAccountId = accountId; - mUserId = userId; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - final Twitter twitter = getTwitterInstance(mContext, mAccountId, false); - if (twitter == null) return SingleResponse.getInstance(); - try { - final User user = twitter.destroyBlock(mUserId); - return SingleResponse.getInstance(user, null); - } catch (final TwitterException e) { - return SingleResponse.getInstance(null, e); - } - - } - - @Override - protected void onPostExecute(final SingleResponse result) { - if (result.hasData()) { - final String message = mContext.getString(R.string.unblocked_user, - getUserName(mContext, result.getData())); - mMessagesManager.showInfoMessage(message, false); - } else { - mMessagesManager.showErrorMessage(R.string.action_unblocking, result.getException(), true); - } - final Intent intent = new Intent(BROADCAST_BLOCKSTATE_CHANGED); - intent.putExtra(EXTRA_USER_ID, mUserId); - intent.putExtra(EXTRA_SUCCEED, result.hasData()); - mContext.sendBroadcast(intent); - super.onPostExecute(result); - } - - } - - class DestroyDirectMessageTask extends ManagedAsyncTask> { - - private final long message_id; - private final long account_id; - - public DestroyDirectMessageTask(final long account_id, final long message_id) { - super(mContext, mAsyncTaskManager); - - this.account_id = account_id; - this.message_id = message_id; - } - - @Override - protected SingleResponse doInBackground(final Void... args) { - final Twitter twitter = getTwitterInstance(mContext, account_id, false); - if (twitter == null) return SingleResponse.getInstance(); - try { - final DirectMessage message = twitter.destroyDirectMessage(message_id); - deleteMessages(message_id); - return SingleResponse.getInstance(message, null); - } catch (final TwitterException e) { - if (isMessageNotFound(e)) { - deleteMessages(message_id); - } - return SingleResponse.getInstance(null, e); - } - } - - @Override - protected void onPostExecute(final SingleResponse result) { - super.onPostExecute(result); - if (result == null) return; - if (result.hasData() || isMessageNotFound(result.getException())) { - mMessagesManager.showInfoMessage(R.string.direct_message_deleted, false); - } else { - mMessagesManager.showErrorMessage(R.string.action_deleting, result.getException(), true); - } - } - - private void deleteMessages(final long message_id) { - final String where = DirectMessages.MESSAGE_ID + " = " + message_id; - mResolver.delete(DirectMessages.Inbox.CONTENT_URI, where, null); - mResolver.delete(DirectMessages.Outbox.CONTENT_URI, where, null); - } - - private boolean isMessageNotFound(final Exception e) { - if (!(e instanceof TwitterException)) return false; - final TwitterException te = (TwitterException) e; - return te.getErrorCode() == StatusCodeMessageUtils.PAGE_NOT_FOUND - || te.getStatusCode() == HttpResponseCode.NOT_FOUND; - } - } - - class DestroyFavoriteTask extends ManagedAsyncTask> { - - private final long account_id; - - private final long status_id; - - public DestroyFavoriteTask(final long account_id, final long status_id) { - super(mContext, mAsyncTaskManager); - this.account_id = account_id; - this.status_id = status_id; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - if (account_id < 0) return SingleResponse.getInstance(); - final Twitter twitter = getTwitterInstance(mContext, account_id, false); - if (twitter != null) { - try { - final twitter4j.Status status = twitter.destroyFavorite(status_id); - final ContentValues values = new ContentValues(); - values.put(Statuses.IS_FAVORITE, 0); - final StringBuilder where = new StringBuilder(); - where.append(Statuses.ACCOUNT_ID + " = " + account_id); - where.append(" AND "); - where.append("("); - where.append(Statuses.STATUS_ID + " = " + status_id); - where.append(" OR "); - where.append(Statuses.RETWEET_ID + " = " + status_id); - where.append(")"); - for (final Uri uri : TweetStore.STATUSES_URIS) { - mResolver.update(uri, values, where.toString(), null); - } - return new SingleResponse(new ParcelableStatus(status, account_id, false), null); - } catch (final TwitterException e) { - return SingleResponse.getInstance(e); - } - } - return SingleResponse.getInstance(); - } - - @Override - protected void onPostExecute(final SingleResponse result) { - if (result.hasData()) { - final Intent intent = new Intent(BROADCAST_FAVORITE_CHANGED); - intent.putExtra(EXTRA_STATUS, result.getData()); - intent.putExtra(EXTRA_FAVORITED, false); - mContext.sendBroadcast(intent); - mMessagesManager.showInfoMessage(R.string.status_unfavorited, false); - } else { - mMessagesManager.showErrorMessage(R.string.action_unfavoriting, result.getException(), true); - } - super.onPostExecute(result); - } - - } - - class DestroyFriendshipTask extends ManagedAsyncTask> { - - private final long account_id; - private final long user_id; - - public DestroyFriendshipTask(final long account_id, final long user_id) { - super(mContext, mAsyncTaskManager); - this.account_id = account_id; - this.user_id = user_id; - } - - public long getAccountId() { - return account_id; - } - - public long getUserId() { - return user_id; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - - final Twitter twitter = getTwitterInstance(mContext, account_id, false); - if (twitter != null) { - try { - final User user = twitter.destroyFriendship(user_id); - // remove user tweets and retweets - final String where - = Statuses.ACCOUNT_ID + " = " + account_id - + " AND (" + Statuses.USER_ID + " = " + user_id - + " OR " + Statuses.RETWEETED_BY_USER_ID + " = " + user_id - + ")"; - mResolver.delete(Statuses.CONTENT_URI, where, null); - return SingleResponse.getInstance(user, null); - } catch (final TwitterException e) { - return SingleResponse.getInstance(null, e); - } - } - return SingleResponse.getInstance(); - } - - @Override - protected void onPostExecute(final SingleResponse result) { - if (result.hasData()) { - final String message = mContext.getString(R.string.unfollowed_user, - getUserName(mContext, result.getData())); - mMessagesManager.showInfoMessage(message, false); - } else { - mMessagesManager.showErrorMessage(R.string.action_unfollowing, result.getException(), true); - } - final Intent intent = new Intent(BROADCAST_FRIENDSHIP_CHANGED); - intent.putExtra(EXTRA_USER_ID, user_id); - intent.putExtra(EXTRA_SUCCEED, result.hasData()); - mContext.sendBroadcast(intent); - super.onPostExecute(result); - } - - } - - class DestroySavedSearchTask extends ManagedAsyncTask> { - - private final long mAccountId; - private final int mSearchId; - - DestroySavedSearchTask(final long accountId, final int searchId) { - super(mContext, mAsyncTaskManager); - mAccountId = accountId; - mSearchId = searchId; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - final Twitter twitter = getTwitterInstance(mContext, mAccountId, false); - if (twitter == null) return SingleResponse.getInstance(); - try { - return SingleResponse.getInstance(twitter.destroySavedSearch(mSearchId)); - } catch (final TwitterException e) { - return SingleResponse.getInstance(e); - } - } - - @Override - protected void onPostExecute(final SingleResponse result) { - if (result.hasData()) { - final String message = mContext.getString(R.string.search_name_deleted, result.getData().getQuery()); - mMessagesManager.showOkMessage(message, false); - } else { - mMessagesManager.showErrorMessage(R.string.action_deleting_search, result.getException(), false); - } - super.onPostExecute(result); - } - - } - - class DestroyStatusTask extends ManagedAsyncTask> { - - private final long account_id; - - private final long status_id; - - public DestroyStatusTask(final long account_id, final long status_id) { - super(mContext, mAsyncTaskManager); - this.account_id = account_id; - this.status_id = status_id; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - final Twitter twitter = getTwitterInstance(mContext, account_id, false); - if (twitter == null) return SingleResponse.getInstance(); - try { - final twitter4j.Status status = twitter.destroyStatus(status_id); - final ContentValues values = new ContentValues(); - values.put(Statuses.MY_RETWEET_ID, -1); - for (final Uri uri : TweetStore.STATUSES_URIS) { - mResolver.delete(uri, Statuses.STATUS_ID + " = " + status_id, null); - mResolver.update(uri, values, Statuses.MY_RETWEET_ID + " = " + status_id, null); - } - return SingleResponse.getInstance(status, null); - } catch (final TwitterException e) { - return SingleResponse.getInstance(null, e); - } - } - - @Override - protected void onPostExecute(final SingleResponse result) { - final Intent intent = new Intent(BROADCAST_STATUS_DESTROYED); - if (result.hasData() && result.getData().getId() > 0) { - intent.putExtra(EXTRA_STATUS_ID, status_id); - intent.putExtra(EXTRA_SUCCEED, true); - if (result.getData().getRetweetedStatus() != null) { - mMessagesManager.showInfoMessage(R.string.retweet_cancelled, false); - } else { - mMessagesManager.showInfoMessage(R.string.status_deleted, false); - } - } else { - mMessagesManager.showErrorMessage(R.string.action_deleting, result.getException(), true); - } - mContext.sendBroadcast(intent); - super.onPostExecute(result); - } - - } - - class DestroyUserListSubscriptionTask extends ManagedAsyncTask> { - - private final long mAccountId; - private final long mListId; - - public DestroyUserListSubscriptionTask(final long accountId, final long listId) { - super(mContext, mAsyncTaskManager); - mAccountId = accountId; - mListId = listId; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - - final Twitter twitter = getTwitterInstance(mContext, mAccountId, false); - if (twitter != null) { - try { - final ParcelableUserList list = new ParcelableUserList( - twitter.destroyUserListSubscription(mListId), mAccountId); - return SingleResponse.getInstance(list, null); - } catch (final TwitterException e) { - return SingleResponse.getInstance(null, e); - } - } - return SingleResponse.getInstance(); - } - - @Override - protected void onPostExecute(final SingleResponse result) { - final boolean succeed = result.hasData(); - if (succeed) { - final String message = mContext.getString(R.string.unsubscribed_from_list, result.getData().name); - mMessagesManager.showOkMessage(message, false); - } else { - mMessagesManager.showErrorMessage(R.string.action_unsubscribing_from_list, result.getException(), true); - } - final Intent intent = new Intent(BROADCAST_USER_LIST_UNSUBSCRIBED); - intent.putExtra(EXTRA_USER_LIST, result.getData()); - intent.putExtra(EXTRA_SUCCEED, succeed); - mContext.sendBroadcast(intent); - super.onPostExecute(result); - } - - } - - class DestroyUserListTask extends ManagedAsyncTask> { - - private final long mAccountId; - private final long mListId; - - public DestroyUserListTask(final long accountId, final long listId) { - super(mContext, mAsyncTaskManager); - mAccountId = accountId; - mListId = listId; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - - final Twitter twitter = getTwitterInstance(mContext, mAccountId, false); - if (twitter != null) { - try { - if (mListId > 0) { - final ParcelableUserList list = new ParcelableUserList(twitter.destroyUserList(mListId), - mAccountId); - return new SingleResponse(list, null); - } - } catch (final TwitterException e) { - return SingleResponse.getInstance(e); - } - } - return SingleResponse.getInstance(); - } - - @Override - protected void onPostExecute(final SingleResponse result) { - final boolean succeed = result.hasData(); - if (succeed) { - final String message = mContext.getString(R.string.deleted_list, result.getData().name); - mMessagesManager.showInfoMessage(message, false); - } else { - mMessagesManager.showErrorMessage(R.string.action_deleting, result.getException(), true); - } - final Intent intent = new Intent(BROADCAST_USER_LIST_DELETED); - intent.putExtra(EXTRA_SUCCEED, succeed); - intent.putExtra(EXTRA_USER_LIST, result.getData()); - mContext.sendBroadcast(intent); - super.onPostExecute(result); - } - - } - - abstract class GetDirectMessagesTask extends ManagedAsyncTask> { - - private final long[] account_ids, max_ids, since_ids; - - public GetDirectMessagesTask(final long[] account_ids, final long[] max_ids, final long[] since_ids, - final String tag) { - super(mContext, mAsyncTaskManager, tag); - this.account_ids = account_ids; - this.max_ids = max_ids; - this.since_ids = since_ids; - } - - public abstract ResponseList getDirectMessages(Twitter twitter, Paging paging) - throws TwitterException; - - @Override - protected List doInBackground(final Void... params) { - - final List result = new ArrayList(); - - if (account_ids == null) return result; - - int idx = 0; - final int load_item_limit = mPreferences.getInt(KEY_LOAD_ITEM_LIMIT, DEFAULT_LOAD_ITEM_LIMIT); - for (final long account_id : account_ids) { - final Twitter twitter = getTwitterInstance(mContext, account_id, true); - if (twitter != null) { - try { - final Paging paging = new Paging(); - paging.setCount(load_item_limit); - long max_id = -1, since_id = -1; - if (isMaxIdsValid() && max_ids[idx] > 0) { - max_id = max_ids[idx]; - paging.setMaxId(max_id); - } - if (isSinceIdsValid() && since_ids[idx] > 0) { - since_id = since_ids[idx]; - paging.setSinceId(since_id - 1); - } - final List messages = new ArrayList(); - final boolean truncated = truncateMessages(getDirectMessages(twitter, paging), messages, - since_id); - result.add(new MessageListResponse(account_id, max_id, since_id, load_item_limit, messages, - truncated)); - } catch (final TwitterException e) { - result.add(new MessageListResponse(account_id, e)); - } - } - idx++; - } - return result; - - } - - @Override - protected void onPostExecute(final List result) { - super.onPostExecute(result); - for (final TwitterListResponse response : result) { - if (response.list == null) { - mMessagesManager.showErrorMessage(R.string.action_refreshing_direct_messages, - response.getException(), true); - } - } - } - - final boolean isMaxIdsValid() { - return max_ids != null && max_ids.length == account_ids.length; - } - - final boolean isSinceIdsValid() { - return since_ids != null && since_ids.length == account_ids.length; - } - - } - - class GetHomeTimelineTask extends GetStatusesTask { - - public GetHomeTimelineTask(final long[] account_ids, final long[] max_ids, final long[] since_ids) { - super(account_ids, max_ids, since_ids, TASK_TAG_GET_HOME_TIMELINE); - } - - @Override - public ResponseList getStatuses(final Twitter twitter, final Paging paging) - throws TwitterException { - return twitter.getHomeTimeline(paging); - } - - @Override - protected void onPostExecute(final List responses) { - super.onPostExecute(responses); - mAsyncTaskManager.add(new StoreHomeTimelineTask(responses, !isMaxIdsValid()), true); - mGetHomeTimelineTaskId = -1; - for (final StatusListResponse response : responses) { - if (response.list == null) { - mMessagesManager.showErrorMessage(R.string.action_refreshing_home_timeline, - response.getException(), true); - break; - } - } - } - - @Override - protected void onPreExecute() { - final Intent intent = new Intent(BROADCAST_RESCHEDULE_HOME_TIMELINE_REFRESHING); - mContext.sendBroadcast(intent); - super.onPreExecute(); - } - - } - - class GetLocalTrendsTask extends GetTrendsTask { - - private final int woeid; - - public GetLocalTrendsTask(final long account_id, final int woeid) { - super(account_id); - this.woeid = woeid; - } - - @Override - public List getTrends(final Twitter twitter) throws TwitterException { - final ArrayList trends_list = new ArrayList(); - if (twitter != null) { - trends_list.add(twitter.getLocationTrends(woeid)); - } - return trends_list; - } - - @Override - protected void onPostExecute(final ListResponse result) { - mAsyncTaskManager.add(new StoreLocalTrendsTask(result), true); - super.onPostExecute(result); - - } - - } - - class GetMentionsTask extends GetStatusesTask { - - public GetMentionsTask(final long[] account_ids, final long[] max_ids, final long[] since_ids) { - super(account_ids, max_ids, since_ids, TASK_TAG_GET_MENTIONS); - } - - @Override - public ResponseList getStatuses(final Twitter twitter, final Paging paging) - throws TwitterException { - return twitter.getMentionsTimeline(paging); - } - - @Override - protected void onPostExecute(final List responses) { - super.onPostExecute(responses); - mAsyncTaskManager.add(new StoreMentionsTask(responses, !isMaxIdsValid()), true); - mGetMentionsTaskId = -1; - for (final StatusListResponse response : responses) { - if (response.list == null) { - mMessagesManager.showErrorMessage(R.string.action_refreshing_mentions, response.getException(), - true); - break; - } - } - } - - @Override - protected void onPreExecute() { - - final Intent intent = new Intent(BROADCAST_RESCHEDULE_MENTIONS_REFRESHING); - mContext.sendBroadcast(intent); - super.onPreExecute(); - } - - } - - class GetReceivedDirectMessagesTask extends GetDirectMessagesTask { - - public GetReceivedDirectMessagesTask(final long[] account_ids, final long[] max_ids, final long[] since_ids) { - super(account_ids, max_ids, since_ids, TASK_TAG_GET_RECEIVED_DIRECT_MESSAGES); - } - - @Override - public ResponseList getDirectMessages(final Twitter twitter, final Paging paging) - throws TwitterException { - return twitter.getDirectMessages(paging); - } - - @Override - protected void onPostExecute(final List responses) { - super.onPostExecute(responses); - mAsyncTaskManager.add(new StoreReceivedDirectMessagesTask(responses, !isMaxIdsValid()), true); - mGetReceivedDirectMessagesTaskId = -1; - } - - @Override - protected void onPreExecute() { - final Intent intent = new Intent(BROADCAST_RESCHEDULE_DIRECT_MESSAGES_REFRESHING); - mContext.sendBroadcast(intent); - super.onPreExecute(); - } - - } - - class GetSentDirectMessagesTask extends GetDirectMessagesTask { - - public GetSentDirectMessagesTask(final long[] account_ids, final long[] max_ids, final long[] since_ids) { - super(account_ids, max_ids, since_ids, TASK_TAG_GET_SENT_DIRECT_MESSAGES); - } - - @Override - public ResponseList getDirectMessages(final Twitter twitter, final Paging paging) - throws TwitterException { - return twitter.getSentDirectMessages(paging); - } - - @Override - protected void onPostExecute(final List responses) { - super.onPostExecute(responses); - mAsyncTaskManager.add(new StoreSentDirectMessagesTask(responses, !isMaxIdsValid()), true); - mGetSentDirectMessagesTaskId = -1; - } - - } - - abstract class GetStatusesTask extends ManagedAsyncTask> { - - private final long[] mAccountIds, mMaxIds, mSinceIds; - - public GetStatusesTask(final long[] account_ids, final long[] max_ids, final long[] since_ids, final String tag) { - super(mContext, mAsyncTaskManager, tag); - mAccountIds = account_ids; - mMaxIds = max_ids; - mSinceIds = since_ids; - } - - public abstract ResponseList getStatuses(Twitter twitter, Paging paging) - throws TwitterException; - - @Override - protected List doInBackground(final Void... params) { - - final List result = new ArrayList(); - - if (mAccountIds == null) return result; - - int idx = 0; - final int load_item_limit = mPreferences.getInt(KEY_LOAD_ITEM_LIMIT, DEFAULT_LOAD_ITEM_LIMIT); - for (final long account_id : mAccountIds) { - final Twitter twitter = getTwitterInstance(mContext, account_id, true); - if (twitter != null) { - try { - final Paging paging = new Paging(); - paging.setCount(load_item_limit); - final long maxId, sinceId; - if (isMaxIdsValid() && mMaxIds[idx] > 0) { - maxId = mMaxIds[idx]; - paging.setMaxId(maxId); - } else { - maxId = -1; - } - if (isSinceIdsValid() && mSinceIds[idx] > 0) { - sinceId = mSinceIds[idx]; - paging.setSinceId(sinceId - 1); - } else { - sinceId = -1; - } - final List statuses = new ArrayList(); - final boolean truncated = truncateStatuses(getStatuses(twitter, paging), statuses, sinceId); - result.add(new StatusListResponse(account_id, maxId, sinceId, load_item_limit, statuses, - truncated)); - } catch (final TwitterException e) { - result.add(new StatusListResponse(account_id, e)); - } - } - idx++; - } - return result; - } - - final boolean isMaxIdsValid() { - return mMaxIds != null && mMaxIds.length == mAccountIds.length; - } - - final boolean isSinceIdsValid() { - return mSinceIds != null && mSinceIds.length == mAccountIds.length; - } - - } - - abstract class GetTrendsTask extends ManagedAsyncTask> { - - private final long account_id; - - public GetTrendsTask(final long account_id) { - super(mContext, mAsyncTaskManager, TASK_TAG_GET_TRENDS); - this.account_id = account_id; - } - - public abstract List getTrends(Twitter twitter) throws TwitterException; - - @Override - protected ListResponse doInBackground(final Void... params) { - final Twitter twitter = getTwitterInstance(mContext, account_id, false); - final Bundle extras = new Bundle(); - extras.putLong(EXTRA_ACCOUNT_ID, account_id); - if (twitter != null) { - try { - return new ListResponse(getTrends(twitter), null, extras); - } catch (final TwitterException e) { - return new ListResponse(null, e, extras); - } - } - return new ListResponse(null, null, extras); - } - - } - - final class RemoveUnreadCountsTask extends AsyncTask { - private final int position; - private final Map> counts; - - RemoveUnreadCountsTask(final int position, final Map> counts) { - this.position = position; - this.counts = counts; - } - - @Override - protected Integer doInBackground(final Void... params) { - return removeUnreadCounts(mContext, position, counts); - } - - } - - class ReportMultiSpamTask extends ManagedAsyncTask> { - - private final long account_id; - private final long[] user_ids; - - public ReportMultiSpamTask(final long account_id, final long[] user_ids) { - super(mContext, mAsyncTaskManager); - this.account_id = account_id; - this.user_ids = user_ids; - } - - @Override - protected ListResponse doInBackground(final Void... params) { - - final Bundle extras = new Bundle(); - extras.putLong(EXTRA_ACCOUNT_ID, account_id); - final List reported_users = new ArrayList(); - final Twitter twitter = getTwitterInstance(mContext, account_id, false); - if (twitter != null) { - for (final long user_id : user_ids) { - try { - final User user = twitter.reportSpam(user_id); - if (user == null || user.getId() <= 0) { - continue; - } - reported_users.add(user.getId()); - } catch (final TwitterException e) { - return new ListResponse(null, e, extras); - } - } - } - return new ListResponse(reported_users, null, extras); - } - - @Override - protected void onPostExecute(final ListResponse result) { - if (result != null) { - final String user_id_where = ListUtils.toString(result.list, ',', false); - for (final Uri uri : STATUSES_URIS) { - final String where = Statuses.ACCOUNT_ID + " = " + account_id + " AND " + Statuses.USER_ID - + " IN (" + user_id_where + ")"; - mResolver.delete(uri, where, null); - } - mMessagesManager.showInfoMessage(R.string.reported_users_for_spam, false); - } - final Intent intent = new Intent(BROADCAST_MULTI_BLOCKSTATE_CHANGED); - intent.putExtra(EXTRA_USER_IDS, user_ids); - intent.putExtra(EXTRA_ACCOUNT_ID, account_id); - intent.putExtra(EXTRA_SUCCEED, result != null); - mContext.sendBroadcast(intent); - super.onPostExecute(result); - } - - } - - class ReportSpamTask extends ManagedAsyncTask> { - - private final long account_id; - private final long user_id; - - public ReportSpamTask(final long account_id, final long user_id) { - super(mContext, mAsyncTaskManager); - this.account_id = account_id; - this.user_id = user_id; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - final Twitter twitter = getTwitterInstance(mContext, account_id, false); - if (twitter != null) { - try { - final User user = twitter.reportSpam(user_id); - return SingleResponse.getInstance(user, null); - } catch (final TwitterException e) { - return SingleResponse.getInstance(null, e); - } - } - return SingleResponse.getInstance(); - } - - @Override - protected void onPostExecute(final SingleResponse result) { - if (result.hasData() && result.getData().getId() > 0) { - for (final Uri uri : STATUSES_URIS) { - final String where = Statuses.ACCOUNT_ID + " = " + account_id + " AND " + Statuses.USER_ID + " = " - + user_id; - mResolver.delete(uri, where, null); - } - mMessagesManager.showInfoMessage(R.string.reported_user_for_spam, false); - } else { - mMessagesManager.showErrorMessage(R.string.action_reporting_for_spam, result.getException(), true); - } - final Intent intent = new Intent(BROADCAST_BLOCKSTATE_CHANGED); - intent.putExtra(EXTRA_USER_ID, user_id); - intent.putExtra(EXTRA_SUCCEED, result.hasData()); - mContext.sendBroadcast(intent); - super.onPostExecute(result); - } - - } - - class RetweetStatusTask extends ManagedAsyncTask> { - - private final long account_id; - - private final long status_id; - - public RetweetStatusTask(final long account_id, final long status_id) { - super(mContext, mAsyncTaskManager); - this.account_id = account_id; - this.status_id = status_id; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - - if (account_id < 0) return SingleResponse.getInstance(); - - final Twitter twitter = getTwitterInstance(mContext, account_id, false); - if (twitter != null) { - try { - final twitter4j.Status status = twitter.retweetStatus(status_id); - return SingleResponse.getInstance(status, null); - } catch (final TwitterException e) { - return SingleResponse.getInstance(null, e); - } - } - return SingleResponse.getInstance(); - } - - @Override - protected void onPostExecute(final SingleResponse result) { - - if (result.hasData() && result.getData().getId() > 0) { - final ContentValues values = new ContentValues(); - values.put(Statuses.MY_RETWEET_ID, result.getData().getId()); - final String where = Statuses.STATUS_ID + " = " + status_id + " OR " + Statuses.RETWEET_ID + " = " - + status_id; - for (final Uri uri : STATUSES_URIS) { - mResolver.update(uri, values, where, null); - } - final Intent intent = new Intent(BROADCAST_RETWEET_CHANGED); - intent.putExtra(EXTRA_STATUS_ID, status_id); - intent.putExtra(EXTRA_RETWEETED, true); - mContext.sendBroadcast(intent); - mMessagesManager.showOkMessage(R.string.status_retweeted, false); - } else { - mMessagesManager.showErrorMessage(R.string.action_retweeting, result.getException(), true); - } - - super.onPostExecute(result); - } - - } - - class SendDirectMessageTask extends ManagedAsyncTask> { - - private final long user_id; - private final String screen_name; - private final String message; - private final long account_id; - - public SendDirectMessageTask(final long account_id, final String screen_name, final long user_id, - final String message) { - super(mContext, mAsyncTaskManager); - this.account_id = account_id; - this.user_id = user_id; - this.screen_name = screen_name; - this.message = message; - } - - @Override - protected SingleResponse doInBackground(final Void... args) { - final Twitter twitter = getTwitterInstance(mContext, account_id, true, true); - if (twitter == null) return SingleResponse.getInstance(); - try { - if (user_id > 0) - return SingleResponse.getInstance(twitter.sendDirectMessage(user_id, message), null); - else if (screen_name != null) - return SingleResponse.getInstance(twitter.sendDirectMessage(screen_name, message), null); - } catch (final TwitterException e) { - return SingleResponse.getInstance(null, e); - } - return SingleResponse.getInstance(); - } - - @Override - protected void onPostExecute(final SingleResponse result) { - super.onPostExecute(result); - if (result.hasData() && result.getData().getId() > 0) { - final ContentValues values = makeDirectMessageContentValues(result.getData(), account_id, true); - final String delete_where = DirectMessages.ACCOUNT_ID + " = " + account_id + " AND " - + DirectMessages.MESSAGE_ID + " = " + result.getData().getId(); - mResolver.delete(DirectMessages.Outbox.CONTENT_URI, delete_where, null); - mResolver.insert(DirectMessages.Outbox.CONTENT_URI, values); - mMessagesManager.showOkMessage(R.string.direct_message_sent, false); - } else { - mMessagesManager.showErrorMessage(R.string.action_sending_direct_message, result.getException(), true); - } - } - - } - - abstract class StoreDirectMessagesTask extends ManagedAsyncTask> { - - private final List responses; - private final Uri uri; - private final boolean notify; - - public StoreDirectMessagesTask(final List result, final Uri uri, final boolean notify, - final String tag) { - super(mContext, mAsyncTaskManager, tag); - responses = result; - this.uri = uri; - this.notify = notify; - } - - @Override - protected SingleResponse doInBackground(final Void... args) { - - boolean succeed = false; - for (final TwitterListResponse response : responses) { - final long account_id = response.account_id; - final List messages = response.list; - if (messages != null) { - final ContentValues[] values_array = new ContentValues[messages.size()]; - final long[] message_ids = new long[messages.size()]; - - for (int i = 0, j = messages.size(); i < j; i++) { - final DirectMessage message = messages.get(i); - message_ids[i] = message.getId(); - values_array[i] = makeDirectMessageContentValues(message, account_id, isOutgoing()); - } - - // Delete all rows conflicting before new data inserted. - { - final StringBuilder delete_where = new StringBuilder(); - delete_where.append(DirectMessages.ACCOUNT_ID + " = " + account_id); - delete_where.append(" AND "); - delete_where.append(Where.in(new Column(DirectMessages.MESSAGE_ID), - new RawItemArray(message_ids)).getSQL()); - final Uri delete_uri = appendQueryParameters(uri, new NameValuePairImpl(QUERY_PARAM_NOTIFY, - false)); - mResolver.delete(delete_uri, delete_where.toString(), null); - } - - // Insert previously fetched items. - final Uri insert_uri = appendQueryParameters(uri, new NameValuePairImpl(QUERY_PARAM_NOTIFY, notify)); - bulkInsert(mResolver, insert_uri, values_array); - - } - succeed = true; - } - final Bundle bundle = new Bundle(); - bundle.putBoolean(EXTRA_SUCCEED, succeed); - return SingleResponse.getInstance(bundle, null); - } - - abstract boolean isOutgoing(); - - } - - class StoreHomeTimelineTask extends StoreStatusesTask { - - public StoreHomeTimelineTask(final List result, final boolean notify) { - super(result, Statuses.CONTENT_URI, notify, TASK_TAG_STORE_HOME_TIMELINE); - } - - @Override - protected void onPostExecute(final SingleResponse response) { - final boolean succeed = response != null && response.hasData() - && response.getData().getBoolean(EXTRA_SUCCEED); - final Bundle extras = new Bundle(); - extras.putBoolean(EXTRA_SUCCEED, succeed); - mContext.sendBroadcast(new Intent(BROADCAST_HOME_TIMELINE_REFRESHED).putExtras(extras)); - super.onPostExecute(response); - } - - } - - class StoreLocalTrendsTask extends StoreTrendsTask { - - public StoreLocalTrendsTask(final ListResponse result) { - super(result, CachedTrends.Local.CONTENT_URI); - } - - } - - class StoreMentionsTask extends StoreStatusesTask { - - public StoreMentionsTask(final List result, final boolean notify) { - super(result, Mentions.CONTENT_URI, notify, TASK_TAG_STORE_MENTIONS); - } - - @Override - protected void onPostExecute(final SingleResponse response) { - final boolean succeed = response != null && response.hasData() - && response.getData().getBoolean(EXTRA_SUCCEED); - final Bundle extras = new Bundle(); - extras.putBoolean(EXTRA_SUCCEED, succeed); - mContext.sendBroadcast(new Intent(BROADCAST_MENTIONS_REFRESHED).putExtras(extras)); - super.onPostExecute(response); - } - - } - - class StoreReceivedDirectMessagesTask extends StoreDirectMessagesTask { - - public StoreReceivedDirectMessagesTask(final List result, final boolean notify) { - super(result, DirectMessages.Inbox.CONTENT_URI, notify, TASK_TAG_STORE_RECEIVED_DIRECT_MESSAGES); - } - - @Override - boolean isOutgoing() { - return false; - } - - } - - class StoreSentDirectMessagesTask extends StoreDirectMessagesTask { - - public StoreSentDirectMessagesTask(final List result, final boolean notify) { - super(result, DirectMessages.Outbox.CONTENT_URI, notify, TASK_TAG_STORE_SENT_DIRECT_MESSAGES); - } - - @Override - boolean isOutgoing() { - return true; - } - - } - - abstract class StoreStatusesTask extends ManagedAsyncTask> { - - private final List responses; - private final Uri uri; - private final ArrayList all_statuses = new ArrayList(); - private final boolean notify; - - public StoreStatusesTask(final List result, final Uri uri, final boolean notify, - final String tag) { - super(mContext, mAsyncTaskManager, tag); - responses = result; - this.uri = uri; - this.notify = notify; - } - - @Override - protected SingleResponse doInBackground(final Void... args) { - boolean succeed = false; - for (final StatusListResponse response : responses) { - final long account_id = response.account_id; - final List statuses = response.list; - if (statuses == null || statuses.isEmpty()) { - continue; - } - final ArrayList ids_in_db = getStatusIdsInDatabase(mContext, uri, account_id); - final boolean noItemsBefore = ids_in_db.isEmpty(); - final ContentValues[] values = new ContentValues[statuses.size()]; - final long[] statusIds = new long[statuses.size()]; - for (int i = 0, j = statuses.size(); i < j; i++) { - final twitter4j.Status status = statuses.get(i); - values[i] = makeStatusContentValues(status, account_id); - statusIds[i] = status.getId(); - } - // Delete all rows conflicting before new data inserted. - final Where accountWhere = Where.equals(Statuses.ACCOUNT_ID, account_id); - final Where statusWhere = Where.in(new Column(Statuses.STATUS_ID), new RawItemArray(statusIds)); - final String deleteWhere = Where.and(accountWhere, statusWhere).getSQL(); - final Uri deleteUri = appendQueryParameters(uri, new NameValuePairImpl(QUERY_PARAM_NOTIFY, false)); - final int rowsDeleted = mResolver.delete(deleteUri, deleteWhere, null); - // UCD - ProfilingUtil.profile(mContext, account_id, - "Download tweets, " + ArrayUtils.toString(statusIds, ',', true)); - all_statuses.addAll(Arrays.asList(values)); - // Insert previously fetched items. - final Uri insertUri = appendQueryParameters(uri, new NameValuePairImpl(QUERY_PARAM_NOTIFY, notify)); - bulkInsert(mResolver, insertUri, values); - - // Insert a gap. - final long min_id = statusIds.length != 0 ? ArrayUtils.min(statusIds) : -1; - final boolean deletedOldGap = rowsDeleted > 0 && ArrayUtils.contains(statusIds, response.max_id); - final boolean noRowsDeleted = rowsDeleted == 0; - final boolean insertGap = min_id > 0 && (noRowsDeleted || deletedOldGap) && !response.truncated - && !noItemsBefore && statuses.size() > 1; - if (insertGap) { - final ContentValues gap_value = new ContentValues(); - gap_value.put(Statuses.IS_GAP, 1); - final StringBuilder where = new StringBuilder(); - where.append(Statuses.ACCOUNT_ID + " = " + account_id); - where.append(" AND " + Statuses.STATUS_ID + " = " + min_id); - final Uri update_uri = appendQueryParameters(uri, new NameValuePairImpl(QUERY_PARAM_NOTIFY, true)); - mResolver.update(update_uri, gap_value, where.toString(), null); - } - succeed = true; - } - final Bundle bundle = new Bundle(); - bundle.putBoolean(EXTRA_SUCCEED, succeed); - getAllStatusesIds(mContext, uri); - return SingleResponse.getInstance(bundle, null); - } - - @Override - protected void onPreExecute() { - super.onPreExecute(); - final StatusListResponse[] array = new StatusListResponse[responses.size()]; - new CacheUsersStatusesTask(mContext, responses.toArray(array)).execute(); - } - - } - - class StoreTrendsTask extends ManagedAsyncTask> { - - private final ListResponse response; - private final Uri uri; - - public StoreTrendsTask(final ListResponse result, final Uri uri) { - super(mContext, mAsyncTaskManager, TASK_TAG_STORE_TRENDS); - response = result; - this.uri = uri; - } - - @Override - protected SingleResponse doInBackground(final Void... args) { - final Bundle bundle = new Bundle(); - if (response != null) { - - final List messages = response.list; - final ArrayList hashtags = new ArrayList(); - final ArrayList hashtag_values = new ArrayList(); - if (messages != null && messages.size() > 0) { - final ContentValues[] values_array = makeTrendsContentValues(messages); - for (final ContentValues values : values_array) { - final String hashtag = values.getAsString(CachedTrends.NAME).replaceFirst("#", ""); - if (hashtags.contains(hashtag)) { - continue; - } - hashtags.add(hashtag); - final ContentValues hashtag_value = new ContentValues(); - hashtag_value.put(CachedHashtags.NAME, hashtag); - hashtag_values.add(hashtag_value); - } - mResolver.delete(uri, null, null); - bulkInsert(mResolver, uri, values_array); - bulkDelete(mResolver, CachedHashtags.CONTENT_URI, CachedHashtags.NAME, hashtags, null, true); - bulkInsert(mResolver, CachedHashtags.CONTENT_URI, - hashtag_values.toArray(new ContentValues[hashtag_values.size()])); - bundle.putBoolean(EXTRA_SUCCEED, true); - } - } - return new SingleResponse(bundle, null); - } - - @Override - protected void onPostExecute(final SingleResponse response) { - // if (response != null && response.data != null && - // response.data.getBoolean(EXTRA_SUCCEED)) { - // final Intent intent = new Intent(BROADCAST_TRENDS_UPDATED); - // intent.putExtra(EXTRA_SUCCEED, true); - // mContext.sendBroadcast(intent); - // } - super.onPostExecute(response); - } - - } - - class UpdateUserListDetailsTask extends ManagedAsyncTask> { - - private final long accountId; - private final long listId; - private final boolean isPublic; - private final String name, description; - - public UpdateUserListDetailsTask(final long accountId, final long listId, final boolean isPublic, - final String name, final String description) { - super(mContext, mAsyncTaskManager); - this.accountId = accountId; - this.listId = listId; - this.name = name; - this.isPublic = isPublic; - this.description = description; - } - - @Override - protected SingleResponse doInBackground(final Void... params) { - - final Twitter twitter = getTwitterInstance(mContext, accountId, false); - if (twitter != null) { - try { - final UserList list = twitter.updateUserList(listId, name, isPublic, description); - return new SingleResponse(new ParcelableUserList(list, accountId), null); - } catch (final TwitterException e) { - return SingleResponse.getInstance(e); - } - } - return SingleResponse.getInstance(); - } - - @Override - protected void onPostExecute(final SingleResponse result) { - final Intent intent = new Intent(BROADCAST_USER_LIST_DETAILS_UPDATED); - intent.putExtra(EXTRA_LIST_ID, listId); - if (result.hasData() && result.getData().id > 0) { - final String message = mContext.getString(R.string.updated_list_details, result.getData().name); - mMessagesManager.showOkMessage(message, false); - intent.putExtra(EXTRA_SUCCEED, true); - } else { - mMessagesManager.showErrorMessage(R.string.action_updating_details, result.getException(), true); - } - mContext.sendBroadcast(intent); - super.onPostExecute(result); - } - - } + private static AsyncTwitterWrapper sInstance; + + private final Context mContext; + private final AsyncTaskManager mAsyncTaskManager; + private final SharedPreferences mPreferences; + private final MessagesManager mMessagesManager; + private final ContentResolver mResolver; + + private int mGetHomeTimelineTaskId, mGetMentionsTaskId; + private int mGetReceivedDirectMessagesTaskId, mGetSentDirectMessagesTaskId; + private int mGetLocalTrendsTaskId; + + public AsyncTwitterWrapper(final Context context) { + mContext = context; + final TwidereApplication app = TwidereApplication.getInstance(context); + mAsyncTaskManager = app.getAsyncTaskManager(); + mMessagesManager = app.getMessagesManager(); + mPreferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); + mResolver = context.getContentResolver(); + } + + public int acceptFriendshipAsync(final long accountId, final long userId) { + final AcceptFriendshipTask task = new AcceptFriendshipTask(accountId, userId); + return mAsyncTaskManager.add(task, true); + } + + public int addUserListMembersAsync(final long accountId, final long listId, final ParcelableUser... users) { + final AddUserListMembersTask task = new AddUserListMembersTask(accountId, listId, users); + return mAsyncTaskManager.add(task, true); + } + + public void clearNotificationAsync(final int notificationType) { + clearNotificationAsync(notificationType, 0); + } + + public void clearNotificationAsync(final int notificationId, final long notificationAccount) { + final ClearNotificationTask task = new ClearNotificationTask(notificationId, notificationAccount); + task.execute(); + } + + public void clearUnreadCountAsync(final int position) { + final ClearUnreadCountTask task = new ClearUnreadCountTask(position); + task.execute(); + } + + public int createBlockAsync(final long accountId, final long user_id) { + final CreateBlockTask task = new CreateBlockTask(accountId, user_id); + return mAsyncTaskManager.add(task, true); + } + + public int createMuteAsync(final long accountId, final long user_id) { + final CreateMuteTask task = new CreateMuteTask(accountId, user_id); + return mAsyncTaskManager.add(task, true); + } + + public int createFavoriteAsync(final long accountId, final long status_id) { + final CreateFavoriteTask task = new CreateFavoriteTask(accountId, status_id); + return mAsyncTaskManager.add(task, true); + } + + public int createFriendshipAsync(final long accountId, final long userId) { + final CreateFriendshipTask task = new CreateFriendshipTask(accountId, userId); + return mAsyncTaskManager.add(task, true); + } + + public int createMultiBlockAsync(final long accountId, final long[] userIds) { + final CreateMultiBlockTask task = new CreateMultiBlockTask(accountId, userIds); + return mAsyncTaskManager.add(task, true); + } + + public int createSavedSearchAsync(final long accountId, final String query) { + final CreateSavedSearchTask task = new CreateSavedSearchTask(accountId, query); + return mAsyncTaskManager.add(task, true); + } + + public int createUserListAsync(final long accountId, final String list_name, final boolean is_public, + final String description) { + final CreateUserListTask task = new CreateUserListTask(accountId, list_name, is_public, description); + return mAsyncTaskManager.add(task, true); + } + + public int createUserListSubscriptionAsync(final long accountId, final long listId) { + final CreateUserListSubscriptionTask task = new CreateUserListSubscriptionTask(accountId, listId); + return mAsyncTaskManager.add(task, true); + } + + public int deleteUserListMembersAsync(final long accountId, final long listId, final ParcelableUser... users) { + final DeleteUserListMembersTask task = new DeleteUserListMembersTask(accountId, listId, users); + return mAsyncTaskManager.add(task, true); + } + + public int denyFriendshipAsync(final long accountId, final long userId) { + final DenyFriendshipTask task = new DenyFriendshipTask(accountId, userId); + return mAsyncTaskManager.add(task, true); + } + + public int destroyBlockAsync(final long accountId, final long user_id) { + final DestroyBlockTask task = new DestroyBlockTask(accountId, user_id); + return mAsyncTaskManager.add(task, true); + } + + public int destroyMuteAsync(final long accountId, final long user_id) { + final DestroyMuteTask task = new DestroyMuteTask(accountId, user_id); + return mAsyncTaskManager.add(task, true); + } + + public int destroyDirectMessageAsync(final long accountId, final long message_id) { + final DestroyDirectMessageTask task = new DestroyDirectMessageTask(accountId, message_id); + return mAsyncTaskManager.add(task, true); + } + + public int destroyFavoriteAsync(final long accountId, final long status_id) { + final DestroyFavoriteTask task = new DestroyFavoriteTask(accountId, status_id); + return mAsyncTaskManager.add(task, true); + } + + public int destroyFriendshipAsync(final long accountId, final long user_id) { + final DestroyFriendshipTask task = new DestroyFriendshipTask(accountId, user_id); + return mAsyncTaskManager.add(task, true); + } + + public int destroySavedSearchAsync(final long accountId, final int searchId) { + final DestroySavedSearchTask task = new DestroySavedSearchTask(accountId, searchId); + return mAsyncTaskManager.add(task, true); + } + + public int destroyStatusAsync(final long accountId, final long status_id) { + final DestroyStatusTask task = new DestroyStatusTask(accountId, status_id); + return mAsyncTaskManager.add(task, true); + } + + public int destroyUserListAsync(final long accountId, final long listId) { + final DestroyUserListTask task = new DestroyUserListTask(accountId, listId); + return mAsyncTaskManager.add(task, true); + } + + public int destroyUserListSubscriptionAsync(final long accountId, final long listId) { + final DestroyUserListSubscriptionTask task = new DestroyUserListSubscriptionTask(accountId, listId); + return mAsyncTaskManager.add(task, true); + } + + public int getHomeTimelineAsync(final long[] accountIds, final long[] max_ids, final long[] since_ids) { + mAsyncTaskManager.cancel(mGetHomeTimelineTaskId); + final GetHomeTimelineTask task = new GetHomeTimelineTask(accountIds, max_ids, since_ids); + return mGetHomeTimelineTaskId = mAsyncTaskManager.add(task, true); + } + + public int getLocalTrendsAsync(final long accountId, final int woeid) { + mAsyncTaskManager.cancel(mGetLocalTrendsTaskId); + final GetLocalTrendsTask task = new GetLocalTrendsTask(accountId, woeid); + return mGetLocalTrendsTaskId = mAsyncTaskManager.add(task, true); + } + + public int getMentionsAsync(final long[] accountIds, final long[] max_ids, final long[] since_ids) { + mAsyncTaskManager.cancel(mGetMentionsTaskId); + final GetMentionsTask task = new GetMentionsTask(accountIds, max_ids, since_ids); + return mGetMentionsTaskId = mAsyncTaskManager.add(task, true); + } + + public int getReceivedDirectMessagesAsync(final long[] accountIds, final long[] max_ids, final long[] since_ids) { + mAsyncTaskManager.cancel(mGetReceivedDirectMessagesTaskId); + final GetReceivedDirectMessagesTask task = new GetReceivedDirectMessagesTask(accountIds, max_ids, since_ids); + return mGetReceivedDirectMessagesTaskId = mAsyncTaskManager.add(task, true); + } + + public int getSentDirectMessagesAsync(final long[] accountIds, final long[] max_ids, final long[] since_ids) { + mAsyncTaskManager.cancel(mGetSentDirectMessagesTaskId); + final GetSentDirectMessagesTask task = new GetSentDirectMessagesTask(accountIds, max_ids, since_ids); + return mGetSentDirectMessagesTaskId = mAsyncTaskManager.add(task, true); + } + + public boolean hasActivatedTask() { + return mAsyncTaskManager.hasRunningTask(); + } + + public boolean isCreatingFriendship(final long accountId, final long user_id) { + for (final ManagedAsyncTask task : mAsyncTaskManager.getTaskSpecList()) { + if (task instanceof CreateFriendshipTask) { + final CreateFriendshipTask create_friendship = (CreateFriendshipTask) task; + if (create_friendship.getStatus() == AsyncTask.Status.RUNNING + && create_friendship.getAccountId() == accountId && create_friendship.getUserId() == user_id) + return true; + } + } + return false; + } + + public boolean isDestroyingFriendship(final long accountId, final long user_id) { + for (final ManagedAsyncTask task : mAsyncTaskManager.getTaskSpecList()) { + if (task instanceof DestroyFriendshipTask) { + final DestroyFriendshipTask create_friendship = (DestroyFriendshipTask) task; + if (create_friendship.getStatus() == AsyncTask.Status.RUNNING + && create_friendship.getAccountId() == accountId && create_friendship.getUserId() == user_id) + return true; + } + } + return false; + } + + public boolean isHomeTimelineRefreshing() { + return mAsyncTaskManager.hasRunningTasksForTag(TASK_TAG_GET_HOME_TIMELINE) + || mAsyncTaskManager.hasRunningTasksForTag(TASK_TAG_STORE_HOME_TIMELINE); + } + + public boolean isLocalTrendsRefreshing() { + return mAsyncTaskManager.hasRunningTasksForTag(TASK_TAG_GET_TRENDS) + || mAsyncTaskManager.hasRunningTasksForTag(TASK_TAG_STORE_TRENDS); + } + + public boolean isMentionsRefreshing() { + return mAsyncTaskManager.hasRunningTasksForTag(TASK_TAG_GET_MENTIONS) + || mAsyncTaskManager.hasRunningTasksForTag(TASK_TAG_STORE_MENTIONS); + } + + public boolean isReceivedDirectMessagesRefreshing() { + return mAsyncTaskManager.hasRunningTasksForTag(TASK_TAG_GET_RECEIVED_DIRECT_MESSAGES) + || mAsyncTaskManager.hasRunningTasksForTag(TASK_TAG_STORE_RECEIVED_DIRECT_MESSAGES); + } + + public boolean isSentDirectMessagesRefreshing() { + return mAsyncTaskManager.hasRunningTasksForTag(TASK_TAG_GET_SENT_DIRECT_MESSAGES) + || mAsyncTaskManager.hasRunningTasksForTag(TASK_TAG_STORE_SENT_DIRECT_MESSAGES); + } + + public int refreshAll() { + final long[] accountIds = getActivatedAccountIds(mContext); + return refreshAll(accountIds); + } + + public int refreshAll(final long[] accountIds) { + if (mPreferences.getBoolean(KEY_HOME_REFRESH_MENTIONS, HomeRefreshContentPreference.DEFAULT_ENABLE_MENTIONS)) { + final long[] sinceIds = getNewestStatusIdsFromDatabase(mContext, Mentions.CONTENT_URI, accountIds); + getMentionsAsync(accountIds, null, sinceIds); + } + if (mPreferences.getBoolean(KEY_HOME_REFRESH_DIRECT_MESSAGES, + HomeRefreshContentPreference.DEFAULT_ENABLE_DIRECT_MESSAGES)) { + final long[] sinceIds = getNewestMessageIdsFromDatabase(mContext, DirectMessages.Inbox.CONTENT_URI, + accountIds); + getReceivedDirectMessagesAsync(accountIds, null, sinceIds); + getSentDirectMessagesAsync(accountIds, null, null); + } + if (mPreferences.getBoolean(KEY_HOME_REFRESH_TRENDS, HomeRefreshContentPreference.DEFAULT_ENABLE_TRENDS)) { + final long accountId = getDefaultAccountId(mContext); + final int woeId = mPreferences.getInt(KEY_LOCAL_TRENDS_WOEID, 1); + getLocalTrendsAsync(accountId, woeId); + } + final long[] statusSinceIds = getNewestStatusIdsFromDatabase(mContext, Statuses.CONTENT_URI, accountIds); + return getHomeTimelineAsync(accountIds, null, statusSinceIds); + } + + public void removeUnreadCountsAsync(final int position, final Map> counts) { + final RemoveUnreadCountsTask task = new RemoveUnreadCountsTask(position, counts); + task.execute(); + } + + public int reportMultiSpam(final long accountId, final long[] user_ids) { + final ReportMultiSpamTask task = new ReportMultiSpamTask(accountId, user_ids); + return mAsyncTaskManager.add(task, true); + } + + public int reportSpamAsync(final long accountId, final long user_id) { + final ReportSpamTask task = new ReportSpamTask(accountId, user_id); + return mAsyncTaskManager.add(task, true); + } + + public int retweetStatus(final long accountId, final long status_id) { + final RetweetStatusTask task = new RetweetStatusTask(accountId, status_id); + return mAsyncTaskManager.add(task, true); + } + + public int sendDirectMessageAsync(final long accountId, final long recipientId, final String text, + final String imageUri) { + final Intent intent = new Intent(mContext, BackgroundOperationService.class); + intent.setAction(INTENT_ACTION_SEND_DIRECT_MESSAGE); + intent.putExtra(EXTRA_ACCOUNT_ID, accountId); + intent.putExtra(EXTRA_RECIPIENT_ID, recipientId); + intent.putExtra(EXTRA_TEXT, text); + intent.putExtra(EXTRA_IMAGE_URI, imageUri); + mContext.startService(intent); + return 0; + } + + public int updateProfile(final long accountId, final String name, final String url, final String location, + final String description) { + final UpdateProfileTask task = new UpdateProfileTask(mContext, mAsyncTaskManager, accountId, name, url, + location, description); + return mAsyncTaskManager.add(task, true); + } + + public int updateProfileBannerImage(final long accountId, final Uri image_uri, final boolean delete_image) { + final UpdateProfileBannerImageTask task = new UpdateProfileBannerImageTask(mContext, mAsyncTaskManager, + accountId, image_uri, delete_image); + return mAsyncTaskManager.add(task, true); + } + + public int updateProfileImage(final long accountId, final Uri imageUri, final boolean deleteImage) { + final UpdateProfileImageTask task = new UpdateProfileImageTask(mContext, mAsyncTaskManager, accountId, + imageUri, deleteImage); + return mAsyncTaskManager.add(task, true); + } + + public int updateStatusAsync(final long[] accountIds, final String text, final ParcelableLocation location, + final ParcelableMediaUpdate[] medias, final long inReplyToStatusId, final boolean isPossiblySensitive) { + final ParcelableStatusUpdate.Builder builder = new ParcelableStatusUpdate.Builder(); + builder.accounts(Account.getAccounts(mContext, accountIds)); + builder.text(text); + builder.location(location); + builder.medias(medias); + builder.inReplyToStatusId(inReplyToStatusId); + builder.isPossiblySensitive(isPossiblySensitive); + return updateStatusesAsync(builder.build()); + } + + public int updateStatusesAsync(final ParcelableStatusUpdate... statuses) { + final Intent intent = new Intent(mContext, BackgroundOperationService.class); + intent.setAction(INTENT_ACTION_UPDATE_STATUS); + intent.putExtra(EXTRA_STATUSES, statuses); + mContext.startService(intent); + return 0; + } + + public int updateUserListDetails(final long accountId, final long listId, final boolean isPublic, + final String name, final String description) { + final UpdateUserListDetailsTask task = new UpdateUserListDetailsTask(accountId, listId, isPublic, name, + description); + return mAsyncTaskManager.add(task, true); + } + + public static AsyncTwitterWrapper getInstance(final Context context) { + if (sInstance != null) return sInstance; + return sInstance = new AsyncTwitterWrapper(context); + } + + public static class UpdateProfileBannerImageTask extends ManagedAsyncTask> { + + private final long mAccountId; + private final Uri mImageUri; + private final boolean mDeleteImage; + private final Context mContext; + + public UpdateProfileBannerImageTask(final Context context, final AsyncTaskManager manager, + final long account_id, final Uri image_uri, final boolean delete_image) { + super(context, manager); + mContext = context; + mAccountId = account_id; + mImageUri = image_uri; + mDeleteImage = delete_image; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + return TwitterWrapper.updateProfileBannerImage(mContext, mAccountId, mImageUri, mDeleteImage); + } + + @Override + protected void onPostExecute(final SingleResponse result) { + if (Boolean.TRUE.equals(result.getData())) { + Utils.showOkMessage(mContext, R.string.profile_banner_image_updated, false); + } else { + Utils.showErrorMessage(mContext, R.string.action_updating_profile_banner_image, result.getException(), + true); + } + final Intent intent = new Intent(BROADCAST_PROFILE_BANNER_UPDATED); + intent.putExtra(EXTRA_USER_ID, mAccountId); + mContext.sendBroadcast(intent); + super.onPostExecute(result); + } + + } + + public static class UpdateProfileImageTask extends ManagedAsyncTask> { + + private final long account_id; + private final Uri image_uri; + private final boolean delete_image; + private final Context context; + + public UpdateProfileImageTask(final Context context, final AsyncTaskManager manager, final long account_id, + final Uri image_uri, final boolean delete_image) { + super(context, manager); + this.context = context; + this.account_id = account_id; + this.image_uri = image_uri; + this.delete_image = delete_image; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + return TwitterWrapper.updateProfileImage(context, account_id, image_uri, delete_image); + } + + @Override + protected void onPostExecute(final SingleResponse result) { + if (result.hasData()) { + Utils.showOkMessage(context, R.string.profile_image_updated, false); + } else { + Utils.showErrorMessage(context, R.string.action_updating_profile_image, result.getException(), true); + } + final Intent intent = new Intent(BROADCAST_PROFILE_UPDATED); + intent.putExtra(EXTRA_USER_ID, account_id); + context.sendBroadcast(intent); + super.onPostExecute(result); + } + + } + + public static class UpdateProfileTask extends ManagedAsyncTask> { + + private final long account_id; + private final String name, url, location, description; + private final Context context; + + public UpdateProfileTask(final Context context, final AsyncTaskManager manager, final long account_id, + final String name, final String url, final String location, final String description) { + super(context, manager); + this.context = context; + this.account_id = account_id; + this.name = name; + this.url = url; + this.location = location; + this.description = description; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + return updateProfile(context, account_id, name, url, location, description); + } + + @Override + protected void onPostExecute(final SingleResponse result) { + if (result.hasData()) { + Utils.showOkMessage(context, R.string.profile_updated, false); + } else { + Utils.showErrorMessage(context, context.getString(R.string.action_updating_profile), + result.getException(), true); + } + final Intent intent = new Intent(BROADCAST_PROFILE_IMAGE_UPDATED); + intent.putExtra(EXTRA_USER_ID, account_id); + context.sendBroadcast(intent); + super.onPostExecute(result); + } + + } + + class AcceptFriendshipTask extends ManagedAsyncTask> { + + private final long mAccountId; + private final long mUserId; + + public AcceptFriendshipTask(final long account_id, final long user_id) { + super(mContext, mAsyncTaskManager); + mAccountId = account_id; + mUserId = user_id; + } + + public long getAccountId() { + return mAccountId; + } + + public long getUserId() { + return mUserId; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + + final Twitter twitter = getTwitterInstance(mContext, mAccountId, false); + if (twitter == null) return SingleResponse.getInstance(); + try { + final User user = twitter.acceptFriendship(mUserId); + return SingleResponse.getInstance(user, null); + } catch (final TwitterException e) { + return SingleResponse.getInstance(null, e); + } + } + + @Override + protected void onPostExecute(final SingleResponse result) { + if (result.hasData()) { + final User user = result.getData(); + final String message = mContext.getString(R.string.accepted_users_follow_request, + getUserName(mContext, user)); + mMessagesManager.showOkMessage(message, false); + } else { + mMessagesManager.showErrorMessage(R.string.action_accepting_follow_request, result.getException(), + false); + } + final Intent intent = new Intent(BROADCAST_FRIENDSHIP_ACCEPTED); + intent.putExtra(EXTRA_USER_ID, mUserId); + mContext.sendBroadcast(intent); + super.onPostExecute(result); + } + + } + + class AddUserListMembersTask extends ManagedAsyncTask> { + + private final long accountId; + private final long listId; + private final ParcelableUser[] users; + + public AddUserListMembersTask(final long accountId, final long listId, final ParcelableUser[] users) { + super(mContext, mAsyncTaskManager); + this.accountId = accountId; + this.listId = listId; + this.users = users; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + final Twitter twitter = getTwitterInstance(mContext, accountId, false); + if (twitter == null || users == null) return SingleResponse.getInstance(); + try { + final long[] userIds = new long[users.length]; + for (int i = 0, j = users.length; i < j; i++) { + userIds[i] = users[i].id; + } + final ParcelableUserList list = new ParcelableUserList(twitter.addUserListMembers(listId, userIds), + accountId); + return SingleResponse.getInstance(list, null); + } catch (final TwitterException e) { + return SingleResponse.getInstance(null, e); + } + } + + @Override + protected void onPostExecute(final SingleResponse result) { + final boolean succeed = result.hasData() && result.getData().id > 0; + if (succeed) { + final String message; + if (users.length == 1) { + final ParcelableUser user = users[0]; + final String displayName = Utils.getDisplayName(mContext, user.id, user.name, user.screen_name); + message = mContext.getString(R.string.added_user_to_list, displayName, result.getData().name); + } else { + final Resources res = mContext.getResources(); + message = res.getQuantityString(R.plurals.added_N_users_to_list, users.length, users.length, + result.getData().name); + } + mMessagesManager.showOkMessage(message, false); + } else { + mMessagesManager.showErrorMessage(R.string.action_adding_member, result.getException(), true); + } + final Intent intent = new Intent(BROADCAST_USER_LIST_MEMBERS_ADDED); + intent.putExtra(EXTRA_USER_LIST, result.getData()); + intent.putExtra(EXTRA_USERS, users); + mContext.sendBroadcast(intent); + super.onPostExecute(result); + } + + } + + final class ClearNotificationTask extends AsyncTask { + private final int notificationType; + private final long accountId; + + ClearNotificationTask(final int notificationType, final long accountId) { + this.notificationType = notificationType; + this.accountId = accountId; + } + + @Override + protected Integer doInBackground(final Void... params) { + return clearNotification(mContext, notificationType, accountId); + } + + } + + final class ClearUnreadCountTask extends AsyncTask { + private final int position; + + ClearUnreadCountTask(final int position) { + this.position = position; + } + + @Override + protected Integer doInBackground(final Void... params) { + return clearUnreadCount(mContext, position); + } + + } + + class CreateBlockTask extends ManagedAsyncTask> { + + private final long account_id, user_id; + + public CreateBlockTask(final long account_id, final long user_id) { + super(mContext, mAsyncTaskManager); + this.account_id = account_id; + this.user_id = user_id; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + final Twitter twitter = getTwitterInstance(mContext, account_id, false); + if (twitter == null) return SingleResponse.getInstance(); + try { + final User user = twitter.createBlock(user_id); + for (final Uri uri : STATUSES_URIS) { + final Where where = Where.and(Where.equals(Statuses.ACCOUNT_ID, account_id), + Where.equals(Statuses.USER_ID, user_id)); + mResolver.delete(uri, where.getSQL(), null); + + } + // I bet you don't want to see this user in your auto + // complete + // list. + final Where where = Where.equals(CachedUsers.USER_ID, user_id); + mResolver.delete(CachedUsers.CONTENT_URI, where.getSQL(), null); + return SingleResponse.getInstance(user, null); + } catch (final TwitterException e) { + return SingleResponse.getInstance(null, e); + } + } + + @Override + protected void onPostExecute(final SingleResponse result) { + if (result.hasData() && result.getData().getId() > 0) { + final String message = mContext.getString(R.string.blocked_user, + getUserName(mContext, result.getData())); + mMessagesManager.showInfoMessage(message, false); + final Intent intent = new Intent(BROADCAST_FRIENDSHIP_CHANGED); + intent.putExtra(EXTRA_USER_ID, user_id); + mContext.sendBroadcast(intent); + } else { + mMessagesManager.showErrorMessage(R.string.action_blocking, result.getException(), true); + } + super.onPostExecute(result); + } + + } + + class CreateMuteTask extends ManagedAsyncTask> { + + private final long mAccountId, mUserId; + + public CreateMuteTask(final long accountId, final long userId) { + super(mContext, mAsyncTaskManager); + this.mAccountId = accountId; + this.mUserId = userId; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + final Twitter twitter = getTwitterInstance(mContext, mAccountId, false); + if (twitter == null) return SingleResponse.getInstance(); + try { + final User user = twitter.createMute(mUserId); + final Where where = Where.and(Where.equals(Statuses.ACCOUNT_ID, mAccountId), + Where.equals(Statuses.USER_ID, mUserId)); + mResolver.delete(Statuses.CONTENT_URI, where.getSQL(), null); + + return SingleResponse.getInstance(user, null); + } catch (final TwitterException e) { + return SingleResponse.getInstance(null, e); + } + } + + @Override + protected void onPostExecute(final SingleResponse result) { + if (result.hasData() && result.getData().getId() > 0) { + final String message = mContext.getString(R.string.muted_user, + getUserName(mContext, result.getData())); + mMessagesManager.showInfoMessage(message, false); + final Intent intent = new Intent(BROADCAST_FRIENDSHIP_CHANGED); + intent.putExtra(EXTRA_USER_ID, mUserId); + mContext.sendBroadcast(intent); + } else { + mMessagesManager.showErrorMessage(R.string.action_muting, result.getException(), true); + } + super.onPostExecute(result); + } + + } + + class CreateFavoriteTask extends ManagedAsyncTask> { + + private final long account_id, status_id; + + public CreateFavoriteTask(final long account_id, final long status_id) { + super(mContext, mAsyncTaskManager); + this.account_id = account_id; + this.status_id = status_id; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + if (account_id < 0) return SingleResponse.getInstance(); + final Twitter twitter = getTwitterInstance(mContext, account_id, false); + if (twitter == null) return SingleResponse.getInstance(); + try { + final twitter4j.Status status = twitter.createFavorite(status_id); + final ContentValues values = new ContentValues(); + values.put(Statuses.IS_FAVORITE, true); + final Where where = Where.and(Where.equals(Statuses.ACCOUNT_ID, account_id), + Where.or(Where.equals(Statuses.STATUS_ID, status_id), + Where.equals(Statuses.RETWEET_ID, status_id))); + for (final Uri uri : TweetStore.STATUSES_URIS) { + mResolver.update(uri, values, where.getSQL(), null); + } + return SingleResponse.getInstance(new ParcelableStatus(status, account_id, false)); + } catch (final TwitterException e) { + return SingleResponse.getInstance(e); + } + } + + @Override + protected void onPostExecute(final SingleResponse result) { + if (result.hasData()) { + final Intent intent = new Intent(BROADCAST_FAVORITE_CHANGED); + intent.putExtra(EXTRA_STATUS, result.getData()); + intent.putExtra(EXTRA_FAVORITED, true); + mContext.sendBroadcast(intent); + mMessagesManager.showOkMessage(R.string.status_favorited, false); + } else { + mMessagesManager.showErrorMessage(R.string.action_favoriting, result.getException(), true); + } + super.onPostExecute(result); + } + + } + + class CreateFriendshipTask extends ManagedAsyncTask> { + + private final long account_id; + private final long user_id; + + public CreateFriendshipTask(final long account_id, final long user_id) { + super(mContext, mAsyncTaskManager); + this.account_id = account_id; + this.user_id = user_id; + } + + public long getAccountId() { + return account_id; + } + + public long getUserId() { + return user_id; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + + final Twitter twitter = getTwitterInstance(mContext, account_id, false); + if (twitter == null) return SingleResponse.getInstance(); + try { + final User user = twitter.createFriendship(user_id); + return SingleResponse.getInstance(user, null); + } catch (final TwitterException e) { + return SingleResponse.getInstance(null, e); + } + } + + @Override + protected void onPostExecute(final SingleResponse result) { + if (result.hasData()) { + final User user = result.getData(); + final String message; + if (user.isProtected()) { + message = mContext.getString(R.string.sent_follow_request_to_user, getUserName(mContext, user)); + } else { + message = mContext.getString(R.string.followed_user, getUserName(mContext, user)); + } + mMessagesManager.showOkMessage(message, false); + } else { + mMessagesManager.showErrorMessage(R.string.action_following, result.getException(), false); + } + final Intent intent = new Intent(BROADCAST_FRIENDSHIP_CHANGED); + intent.putExtra(EXTRA_USER_ID, user_id); + mContext.sendBroadcast(intent); + super.onPostExecute(result); + } + + } + + class CreateMultiBlockTask extends ManagedAsyncTask> { + + private final long account_id; + private final long[] user_ids; + + public CreateMultiBlockTask(final long account_id, final long[] user_ids) { + super(mContext, mAsyncTaskManager); + this.account_id = account_id; + this.user_ids = user_ids; + } + + @Override + protected ListResponse doInBackground(final Void... params) { + final List blocked_users = new ArrayList<>(); + final Twitter twitter = getTwitterInstance(mContext, account_id, false); + if (twitter != null) { + for (final long user_id : user_ids) { + try { + final User user = twitter.createBlock(user_id); + if (user == null || user.getId() <= 0) { + continue; + } + blocked_users.add(user.getId()); + } catch (final TwitterException e) { + deleteCaches(blocked_users); + return new ListResponse<>(null, e, null); + } + } + } + deleteCaches(blocked_users); + return new ListResponse<>(blocked_users, null, null); + } + + @Override + protected void onPostExecute(final ListResponse result) { + if (result.list != null) { + mMessagesManager.showInfoMessage(R.string.users_blocked, false); + } else { + mMessagesManager.showErrorMessage(R.string.action_blocking, result.getException(), true); + } + final Intent intent = new Intent(BROADCAST_MULTI_BLOCKSTATE_CHANGED); + intent.putExtra(EXTRA_USER_ID, user_ids); + mContext.sendBroadcast(intent); + super.onPostExecute(result); + } + + private void deleteCaches(final List list) { + for (final Uri uri : STATUSES_URIS) { + bulkDelete(mResolver, uri, Statuses.USER_ID, list, Statuses.ACCOUNT_ID + " = " + account_id, false); + } + // I bet you don't want to see these users in your auto complete + // list. + bulkDelete(mResolver, CachedUsers.CONTENT_URI, CachedUsers.USER_ID, list, null, false); + } + } + + class CreateSavedSearchTask extends ManagedAsyncTask> { + + private final long mAccountId; + private final String mQuery; + + CreateSavedSearchTask(final long accountId, final String query) { + super(mContext, mAsyncTaskManager); + mAccountId = accountId; + mQuery = query; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + final Twitter twitter = getTwitterInstance(mContext, mAccountId, false); + if (twitter == null) return null; + try { + return SingleResponse.getInstance(twitter.createSavedSearch(mQuery)); + } catch (final TwitterException e) { + return SingleResponse.getInstance(e); + } + } + + @Override + protected void onPostExecute(final SingleResponse result) { + if (result.hasData()) { + final String message = mContext.getString(R.string.search_name_saved, result.getData().getQuery()); + mMessagesManager.showOkMessage(message, false); + } else { + mMessagesManager.showErrorMessage(R.string.action_saving_search, result.getException(), false); + } + super.onPostExecute(result); + } + + } + + class CreateUserListSubscriptionTask extends ManagedAsyncTask> { + + private final long accountId; + private final long listId; + + public CreateUserListSubscriptionTask(final long accountId, final long listId) { + super(mContext, mAsyncTaskManager); + this.accountId = accountId; + this.listId = listId; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + final Twitter twitter = getTwitterInstance(mContext, accountId, false); + if (twitter == null) return SingleResponse.getInstance(); + + try { + final ParcelableUserList list = new ParcelableUserList(twitter.createUserListSubscription(listId), + accountId); + return SingleResponse.getInstance(list); + } catch (final TwitterException e) { + return SingleResponse.getInstance(e); + } + } + + @Override + protected void onPostExecute(final SingleResponse result) { + final boolean succeed = result.hasData(); + if (succeed) { + final String message = mContext.getString(R.string.subscribed_to_list, result.getData().name); + mMessagesManager.showOkMessage(message, false); + final Intent intent = new Intent(BROADCAST_USER_LIST_SUBSCRIBED); + intent.putExtra(EXTRA_USER_LIST, result.getData()); + mContext.sendBroadcast(intent); + } else { + mMessagesManager.showErrorMessage(R.string.action_subscribing_to_list, result.getException(), true); + } + super.onPostExecute(result); + } + + } + + class CreateUserListTask extends ManagedAsyncTask> { + + private final long account_id; + private final String list_name, description; + private final boolean is_public; + + public CreateUserListTask(final long account_id, final String list_name, final boolean is_public, + final String description) { + super(mContext, mAsyncTaskManager); + this.account_id = account_id; + this.list_name = list_name; + this.description = description; + this.is_public = is_public; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + final Twitter twitter = getTwitterInstance(mContext, account_id, false); + if (twitter == null || list_name == null) return SingleResponse.getInstance(); + try { + final UserList list = twitter.createUserList(list_name, is_public, description); + return SingleResponse.getInstance(list, null); + } catch (final TwitterException e) { + return SingleResponse.getInstance(null, e); + } + } + + @Override + protected void onPostExecute(final SingleResponse result) { + if (result.hasData()) { + final UserList userList = result.getData(); + final String message = mContext.getString(R.string.created_list, userList.getName()); + mMessagesManager.showOkMessage(message, false); + final Intent intent = new Intent(BROADCAST_USER_LIST_CREATED); + intent.putExtra(EXTRA_USER_LIST, new ParcelableUserList(userList, account_id)); + mContext.sendBroadcast(intent); + } else { + mMessagesManager.showErrorMessage(R.string.action_creating_list, result.getException(), true); + } + super.onPostExecute(result); + } + + } + + class DeleteUserListMembersTask extends ManagedAsyncTask> { + + private final long mAccountId; + private final long mUserListId; + private final ParcelableUser[] users; + + public DeleteUserListMembersTask(final long accountId, final long userListId, final ParcelableUser[] users) { + super(mContext, mAsyncTaskManager); + mAccountId = accountId; + mUserListId = userListId; + this.users = users; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + final Twitter twitter = getTwitterInstance(mContext, mAccountId, false); + if (twitter == null) return SingleResponse.getInstance(); + try { + final long[] userIds = new long[users.length]; + for (int i = 0, j = users.length; i < j; i++) { + userIds[i] = users[i].id; + } + final ParcelableUserList list = new ParcelableUserList(twitter.deleteUserListMembers(mUserListId, + userIds), mAccountId); + return SingleResponse.getInstance(list, null); + } catch (final TwitterException e) { + return SingleResponse.getInstance(null, e); + } + } + + @Override + protected void onPostExecute(final SingleResponse result) { + final boolean succeed = result.hasData() && result.getData().id > 0; + final String message; + if (succeed) { + if (users.length == 1) { + final ParcelableUser user = users[0]; + final String displayName = Utils.getDisplayName(mContext, user.id, user.name, user.screen_name); + message = mContext.getString(R.string.deleted_user_from_list, displayName, result.getData().name); + } else { + final Resources res = mContext.getResources(); + message = res.getQuantityString(R.plurals.deleted_N_users_from_list, users.length, users.length, + result.getData().name); + } + mMessagesManager.showInfoMessage(message, false); + final Intent intent = new Intent(BROADCAST_USER_LIST_MEMBERS_DELETED); + intent.putExtra(EXTRA_USER_LIST, result.getData()); + intent.putExtra(EXTRA_USERS, users); + mContext.sendBroadcast(intent); + } else { + mMessagesManager.showErrorMessage(R.string.action_deleting, result.getException(), true); + } + super.onPostExecute(result); + } + + } + + class DenyFriendshipTask extends ManagedAsyncTask> { + + private final long mAccountId; + private final long mUserId; + + public DenyFriendshipTask(final long account_id, final long user_id) { + super(mContext, mAsyncTaskManager); + mAccountId = account_id; + mUserId = user_id; + } + + public long getAccountId() { + return mAccountId; + } + + public long getUserId() { + return mUserId; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + + final Twitter twitter = getTwitterInstance(mContext, mAccountId, false); + if (twitter == null) return SingleResponse.getInstance(); + try { + final User user = twitter.denyFriendship(mUserId); + return SingleResponse.getInstance(user, null); + } catch (final TwitterException e) { + return SingleResponse.getInstance(null, e); + } + } + + @Override + protected void onPostExecute(final SingleResponse result) { + if (result.hasData()) { + final User user = result.getData(); + final String message = mContext.getString(R.string.denied_users_follow_request, + getUserName(mContext, user)); + mMessagesManager.showOkMessage(message, false); + } else { + mMessagesManager.showErrorMessage(R.string.action_denying_follow_request, result.getException(), false); + } + final Intent intent = new Intent(BROADCAST_FRIENDSHIP_DENIED); + intent.putExtra(EXTRA_USER_ID, mUserId); + mContext.sendBroadcast(intent); + super.onPostExecute(result); + } + + } + + class DestroyBlockTask extends ManagedAsyncTask> { + + private final long mAccountId; + private final long mUserId; + + public DestroyBlockTask(final long accountId, final long userId) { + super(mContext, mAsyncTaskManager); + mAccountId = accountId; + mUserId = userId; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + final Twitter twitter = getTwitterInstance(mContext, mAccountId, false); + if (twitter == null) return SingleResponse.getInstance(); + try { + final User user = twitter.destroyBlock(mUserId); + return SingleResponse.getInstance(user, null); + } catch (final TwitterException e) { + return SingleResponse.getInstance(null, e); + } + + } + + @Override + protected void onPostExecute(final SingleResponse result) { + if (result.hasData()) { + final String message = mContext.getString(R.string.unblocked_user, + getUserName(mContext, result.getData())); + mMessagesManager.showInfoMessage(message, false); + final Intent intent = new Intent(BROADCAST_FRIENDSHIP_CHANGED); + intent.putExtra(EXTRA_USER_ID, mUserId); + mContext.sendBroadcast(intent); + } else { + mMessagesManager.showErrorMessage(R.string.action_unblocking, result.getException(), true); + } + super.onPostExecute(result); + } + + } + + class DestroyMuteTask extends ManagedAsyncTask> { + + private final long mAccountId; + private final long mUserId; + + public DestroyMuteTask(final long accountId, final long userId) { + super(mContext, mAsyncTaskManager); + mAccountId = accountId; + mUserId = userId; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + final Twitter twitter = getTwitterInstance(mContext, mAccountId, false); + if (twitter == null) return SingleResponse.getInstance(); + try { + final User user = twitter.destroyMute(mUserId); + return SingleResponse.getInstance(user, null); + } catch (final TwitterException e) { + return SingleResponse.getInstance(null, e); + } + + } + + @Override + protected void onPostExecute(final SingleResponse result) { + if (result.hasData()) { + final String message = mContext.getString(R.string.unmuted_user, + getUserName(mContext, result.getData())); + mMessagesManager.showInfoMessage(message, false); + final Intent intent = new Intent(BROADCAST_FRIENDSHIP_CHANGED); + intent.putExtra(EXTRA_USER_ID, mUserId); + mContext.sendBroadcast(intent); + } else { + mMessagesManager.showErrorMessage(R.string.action_unmuting, result.getException(), true); + } + super.onPostExecute(result); + } + + } + + class DestroyDirectMessageTask extends ManagedAsyncTask> { + + private final long message_id; + private final long account_id; + + public DestroyDirectMessageTask(final long account_id, final long message_id) { + super(mContext, mAsyncTaskManager); + + this.account_id = account_id; + this.message_id = message_id; + } + + @Override + protected SingleResponse doInBackground(final Void... args) { + final Twitter twitter = getTwitterInstance(mContext, account_id, false); + if (twitter == null) return SingleResponse.getInstance(); + try { + final DirectMessage message = twitter.destroyDirectMessage(message_id); + deleteMessages(message_id); + return SingleResponse.getInstance(message, null); + } catch (final TwitterException e) { + if (isMessageNotFound(e)) { + deleteMessages(message_id); + } + return SingleResponse.getInstance(null, e); + } + } + + @Override + protected void onPostExecute(final SingleResponse result) { + super.onPostExecute(result); + if (result == null) return; + if (result.hasData() || isMessageNotFound(result.getException())) { + mMessagesManager.showInfoMessage(R.string.direct_message_deleted, false); + } else { + mMessagesManager.showErrorMessage(R.string.action_deleting, result.getException(), true); + } + } + + private void deleteMessages(final long message_id) { + final String where = DirectMessages.MESSAGE_ID + " = " + message_id; + mResolver.delete(DirectMessages.Inbox.CONTENT_URI, where, null); + mResolver.delete(DirectMessages.Outbox.CONTENT_URI, where, null); + } + + private boolean isMessageNotFound(final Exception e) { + if (!(e instanceof TwitterException)) return false; + final TwitterException te = (TwitterException) e; + return te.getErrorCode() == StatusCodeMessageUtils.PAGE_NOT_FOUND + || te.getStatusCode() == HttpResponseCode.NOT_FOUND; + } + } + + class DestroyFavoriteTask extends ManagedAsyncTask> { + + private final long account_id; + + private final long status_id; + + public DestroyFavoriteTask(final long account_id, final long status_id) { + super(mContext, mAsyncTaskManager); + this.account_id = account_id; + this.status_id = status_id; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + if (account_id < 0) return SingleResponse.getInstance(); + final Twitter twitter = getTwitterInstance(mContext, account_id, false); + if (twitter != null) { + try { + final twitter4j.Status status = twitter.destroyFavorite(status_id); + final ContentValues values = new ContentValues(); + values.put(Statuses.IS_FAVORITE, 0); + final Where where = Where.and(Where.equals(Statuses.ACCOUNT_ID, account_id), + Where.or(Where.equals(Statuses.STATUS_ID, status_id), Where.equals(Statuses.RETWEET_ID, status_id))); + for (final Uri uri : TweetStore.STATUSES_URIS) { + mResolver.update(uri, values, where.getSQL(), null); + } + return SingleResponse.getInstance(new ParcelableStatus(status, account_id, false)); + } catch (final TwitterException e) { + return SingleResponse.getInstance(e); + } + } + return SingleResponse.getInstance(); + } + + @Override + protected void onPostExecute(final SingleResponse result) { + if (result.hasData()) { + final Intent intent = new Intent(BROADCAST_FAVORITE_CHANGED); + intent.putExtra(EXTRA_STATUS, result.getData()); + intent.putExtra(EXTRA_FAVORITED, false); + mContext.sendBroadcast(intent); + mMessagesManager.showInfoMessage(R.string.status_unfavorited, false); + } else { + mMessagesManager.showErrorMessage(R.string.action_unfavoriting, result.getException(), true); + } + super.onPostExecute(result); + } + + } + + class DestroyFriendshipTask extends ManagedAsyncTask> { + + private final long account_id; + private final long user_id; + + public DestroyFriendshipTask(final long account_id, final long user_id) { + super(mContext, mAsyncTaskManager); + this.account_id = account_id; + this.user_id = user_id; + } + + public long getAccountId() { + return account_id; + } + + public long getUserId() { + return user_id; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + + final Twitter twitter = getTwitterInstance(mContext, account_id, false); + if (twitter != null) { + try { + final User user = twitter.destroyFriendship(user_id); + // remove user tweets and retweets + final Where where = Where.and(Where.equals(Statuses.ACCOUNT_ID, account_id), + Where.or(Where.equals(Statuses.USER_ID, user_id), + Where.equals(Statuses.RETWEETED_BY_USER_ID, user_id))); + mResolver.delete(Statuses.CONTENT_URI, where.getSQL(), null); + return SingleResponse.getInstance(user, null); + } catch (final TwitterException e) { + return SingleResponse.getInstance(null, e); + } + } + return SingleResponse.getInstance(); + } + + @Override + protected void onPostExecute(final SingleResponse result) { + if (result.hasData()) { + final String message = mContext.getString(R.string.unfollowed_user, + getUserName(mContext, result.getData())); + mMessagesManager.showInfoMessage(message, false); + final Intent intent = new Intent(BROADCAST_FRIENDSHIP_CHANGED); + intent.putExtra(EXTRA_USER_ID, user_id); + mContext.sendBroadcast(intent); + } else { + mMessagesManager.showErrorMessage(R.string.action_unfollowing, result.getException(), true); + } + super.onPostExecute(result); + } + + } + + class DestroySavedSearchTask extends ManagedAsyncTask> { + + private final long mAccountId; + private final int mSearchId; + + DestroySavedSearchTask(final long accountId, final int searchId) { + super(mContext, mAsyncTaskManager); + mAccountId = accountId; + mSearchId = searchId; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + final Twitter twitter = getTwitterInstance(mContext, mAccountId, false); + if (twitter == null) return SingleResponse.getInstance(); + try { + return SingleResponse.getInstance(twitter.destroySavedSearch(mSearchId)); + } catch (final TwitterException e) { + return SingleResponse.getInstance(e); + } + } + + @Override + protected void onPostExecute(final SingleResponse result) { + if (result.hasData()) { + final String message = mContext.getString(R.string.search_name_deleted, result.getData().getQuery()); + mMessagesManager.showOkMessage(message, false); + } else { + mMessagesManager.showErrorMessage(R.string.action_deleting_search, result.getException(), false); + } + super.onPostExecute(result); + } + + } + + class DestroyStatusTask extends ManagedAsyncTask> { + + private final long account_id; + + private final long status_id; + + public DestroyStatusTask(final long account_id, final long status_id) { + super(mContext, mAsyncTaskManager); + this.account_id = account_id; + this.status_id = status_id; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + final Twitter twitter = getTwitterInstance(mContext, account_id, false); + if (twitter == null) return SingleResponse.getInstance(); + try { + final twitter4j.Status status = twitter.destroyStatus(status_id); + final ContentValues values = new ContentValues(); + values.put(Statuses.MY_RETWEET_ID, -1); + for (final Uri uri : TweetStore.STATUSES_URIS) { + mResolver.delete(uri, Statuses.STATUS_ID + " = " + status_id, null); + mResolver.update(uri, values, Statuses.MY_RETWEET_ID + " = " + status_id, null); + } + return SingleResponse.getInstance(status, null); + } catch (final TwitterException e) { + return SingleResponse.getInstance(null, e); + } + } + + @Override + protected void onPostExecute(final SingleResponse result) { + if (result.hasData() && result.getData().getId() > 0) { + if (result.getData().getRetweetedStatus() != null) { + mMessagesManager.showInfoMessage(R.string.retweet_cancelled, false); + } else { + mMessagesManager.showInfoMessage(R.string.status_deleted, false); + } + final Intent intent = new Intent(BROADCAST_STATUS_DESTROYED); + intent.putExtra(EXTRA_STATUS_ID, status_id); + mContext.sendBroadcast(intent); + } else { + mMessagesManager.showErrorMessage(R.string.action_deleting, result.getException(), true); + } + super.onPostExecute(result); + } + + } + + class DestroyUserListSubscriptionTask extends ManagedAsyncTask> { + + private final long mAccountId; + private final long mListId; + + public DestroyUserListSubscriptionTask(final long accountId, final long listId) { + super(mContext, mAsyncTaskManager); + mAccountId = accountId; + mListId = listId; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + + final Twitter twitter = getTwitterInstance(mContext, mAccountId, false); + if (twitter != null) { + try { + final ParcelableUserList list = new ParcelableUserList( + twitter.destroyUserListSubscription(mListId), mAccountId); + return SingleResponse.getInstance(list, null); + } catch (final TwitterException e) { + return SingleResponse.getInstance(null, e); + } + } + return SingleResponse.getInstance(); + } + + @Override + protected void onPostExecute(final SingleResponse result) { + final boolean succeed = result.hasData(); + if (succeed) { + final String message = mContext.getString(R.string.unsubscribed_from_list, result.getData().name); + mMessagesManager.showOkMessage(message, false); + final Intent intent = new Intent(BROADCAST_USER_LIST_UNSUBSCRIBED); + intent.putExtra(EXTRA_USER_LIST, result.getData()); + mContext.sendBroadcast(intent); + } else { + mMessagesManager.showErrorMessage(R.string.action_unsubscribing_from_list, result.getException(), true); + } + super.onPostExecute(result); + } + + } + + class DestroyUserListTask extends ManagedAsyncTask> { + + private final long mAccountId; + private final long mListId; + + public DestroyUserListTask(final long accountId, final long listId) { + super(mContext, mAsyncTaskManager); + mAccountId = accountId; + mListId = listId; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + + final Twitter twitter = getTwitterInstance(mContext, mAccountId, false); + if (twitter != null) { + try { + if (mListId > 0) { + final ParcelableUserList list = new ParcelableUserList(twitter.destroyUserList(mListId), + mAccountId); + return SingleResponse.getInstance(list); + } + } catch (final TwitterException e) { + return SingleResponse.getInstance(e); + } + } + return SingleResponse.getInstance(); + } + + @Override + protected void onPostExecute(final SingleResponse result) { + final boolean succeed = result.hasData(); + if (succeed) { + final String message = mContext.getString(R.string.deleted_list, result.getData().name); + mMessagesManager.showInfoMessage(message, false); + final Intent intent = new Intent(BROADCAST_USER_LIST_DELETED); + intent.putExtra(EXTRA_USER_LIST, result.getData()); + mContext.sendBroadcast(intent); + } else { + mMessagesManager.showErrorMessage(R.string.action_deleting, result.getException(), true); + } + super.onPostExecute(result); + } + + } + + abstract class GetDirectMessagesTask extends ManagedAsyncTask> { + + private final long[] account_ids, max_ids, since_ids; + + public GetDirectMessagesTask(final long[] account_ids, final long[] max_ids, final long[] since_ids, + final String tag) { + super(mContext, mAsyncTaskManager, tag); + this.account_ids = account_ids; + this.max_ids = max_ids; + this.since_ids = since_ids; + } + + public abstract ResponseList getDirectMessages(Twitter twitter, Paging paging) + throws TwitterException; + + @Override + protected List doInBackground(final Void... params) { + + final List result = new ArrayList(); + + if (account_ids == null) return result; + + int idx = 0; + final int load_item_limit = mPreferences.getInt(KEY_LOAD_ITEM_LIMIT, DEFAULT_LOAD_ITEM_LIMIT); + for (final long account_id : account_ids) { + final Twitter twitter = getTwitterInstance(mContext, account_id, true); + if (twitter != null) { + try { + final Paging paging = new Paging(); + paging.setCount(load_item_limit); + long max_id = -1, since_id = -1; + if (isMaxIdsValid() && max_ids[idx] > 0) { + max_id = max_ids[idx]; + paging.setMaxId(max_id); + } + if (isSinceIdsValid() && since_ids[idx] > 0) { + since_id = since_ids[idx]; + paging.setSinceId(since_id - 1); + } + final List messages = new ArrayList<>(); + final boolean truncated = truncateMessages(getDirectMessages(twitter, paging), messages, + since_id); + result.add(new MessageListResponse(account_id, max_id, since_id, load_item_limit, messages, + truncated)); + } catch (final TwitterException e) { + result.add(new MessageListResponse(account_id, e)); + } + } + idx++; + } + return result; + + } + + @Override + protected void onPostExecute(final List result) { + super.onPostExecute(result); + for (final TwitterListResponse response : result) { + if (response.list == null) { + mMessagesManager.showErrorMessage(R.string.action_refreshing_direct_messages, + response.getException(), true); + } + } + } + + final boolean isMaxIdsValid() { + return max_ids != null && max_ids.length == account_ids.length; + } + + final boolean isSinceIdsValid() { + return since_ids != null && since_ids.length == account_ids.length; + } + + } + + class GetHomeTimelineTask extends GetStatusesTask { + + public GetHomeTimelineTask(final long[] account_ids, final long[] max_ids, final long[] since_ids) { + super(account_ids, max_ids, since_ids, TASK_TAG_GET_HOME_TIMELINE); + } + + @Override + public ResponseList getStatuses(final Twitter twitter, final Paging paging) + throws TwitterException { + return twitter.getHomeTimeline(paging); + } + + @Override + protected void onPostExecute(final List responses) { + super.onPostExecute(responses); + mAsyncTaskManager.add(new StoreHomeTimelineTask(responses, !isMaxIdsValid()), true); + mGetHomeTimelineTaskId = -1; + for (final StatusListResponse response : responses) { + if (response.list == null) { + mMessagesManager.showErrorMessage(R.string.action_refreshing_home_timeline, + response.getException(), true); + break; + } + } + } + + @Override + protected void onPreExecute() { + final Intent intent = new Intent(BROADCAST_RESCHEDULE_HOME_TIMELINE_REFRESHING); + mContext.sendBroadcast(intent); + super.onPreExecute(); + } + + } + + class GetLocalTrendsTask extends GetTrendsTask { + + private final int woeid; + + public GetLocalTrendsTask(final long account_id, final int woeid) { + super(account_id); + this.woeid = woeid; + } + + @Override + public List getTrends(final Twitter twitter) throws TwitterException { + final ArrayList trends_list = new ArrayList<>(); + if (twitter != null) { + trends_list.add(twitter.getLocationTrends(woeid)); + } + return trends_list; + } + + @Override + protected void onPostExecute(final ListResponse result) { + mAsyncTaskManager.add(new StoreLocalTrendsTask(result), true); + super.onPostExecute(result); + + } + + } + + class GetMentionsTask extends GetStatusesTask { + + public GetMentionsTask(final long[] account_ids, final long[] max_ids, final long[] since_ids) { + super(account_ids, max_ids, since_ids, TASK_TAG_GET_MENTIONS); + } + + @Override + public ResponseList getStatuses(final Twitter twitter, final Paging paging) + throws TwitterException { + return twitter.getMentionsTimeline(paging); + } + + @Override + protected void onPostExecute(final List responses) { + super.onPostExecute(responses); + mAsyncTaskManager.add(new StoreMentionsTask(responses, !isMaxIdsValid()), true); + mGetMentionsTaskId = -1; + for (final StatusListResponse response : responses) { + if (response.list == null) { + mMessagesManager.showErrorMessage(R.string.action_refreshing_mentions, response.getException(), + true); + break; + } + } + } + + @Override + protected void onPreExecute() { + + final Intent intent = new Intent(BROADCAST_RESCHEDULE_MENTIONS_REFRESHING); + mContext.sendBroadcast(intent); + super.onPreExecute(); + } + + } + + class GetReceivedDirectMessagesTask extends GetDirectMessagesTask { + + public GetReceivedDirectMessagesTask(final long[] account_ids, final long[] max_ids, final long[] since_ids) { + super(account_ids, max_ids, since_ids, TASK_TAG_GET_RECEIVED_DIRECT_MESSAGES); + } + + @Override + public ResponseList getDirectMessages(final Twitter twitter, final Paging paging) + throws TwitterException { + return twitter.getDirectMessages(paging); + } + + @Override + protected void onPostExecute(final List responses) { + super.onPostExecute(responses); + mAsyncTaskManager.add(new StoreReceivedDirectMessagesTask(responses, !isMaxIdsValid()), true); + mGetReceivedDirectMessagesTaskId = -1; + } + + @Override + protected void onPreExecute() { + final Intent intent = new Intent(BROADCAST_RESCHEDULE_DIRECT_MESSAGES_REFRESHING); + mContext.sendBroadcast(intent); + super.onPreExecute(); + } + + } + + class GetSentDirectMessagesTask extends GetDirectMessagesTask { + + public GetSentDirectMessagesTask(final long[] account_ids, final long[] max_ids, final long[] since_ids) { + super(account_ids, max_ids, since_ids, TASK_TAG_GET_SENT_DIRECT_MESSAGES); + } + + @Override + public ResponseList getDirectMessages(final Twitter twitter, final Paging paging) + throws TwitterException { + return twitter.getSentDirectMessages(paging); + } + + @Override + protected void onPostExecute(final List responses) { + super.onPostExecute(responses); + mAsyncTaskManager.add(new StoreSentDirectMessagesTask(responses, !isMaxIdsValid()), true); + mGetSentDirectMessagesTaskId = -1; + } + + } + + abstract class GetStatusesTask extends ManagedAsyncTask> { + + private final long[] mAccountIds, mMaxIds, mSinceIds; + + public GetStatusesTask(final long[] account_ids, final long[] max_ids, final long[] since_ids, final String tag) { + super(mContext, mAsyncTaskManager, tag); + mAccountIds = account_ids; + mMaxIds = max_ids; + mSinceIds = since_ids; + } + + public abstract ResponseList getStatuses(Twitter twitter, Paging paging) + throws TwitterException; + + @Override + protected List doInBackground(final Void... params) { + + final List result = new ArrayList<>(); + + if (mAccountIds == null) return result; + + int idx = 0; + final int load_item_limit = mPreferences.getInt(KEY_LOAD_ITEM_LIMIT, DEFAULT_LOAD_ITEM_LIMIT); + for (final long account_id : mAccountIds) { + final Twitter twitter = getTwitterInstance(mContext, account_id, true); + if (twitter != null) { + try { + final Paging paging = new Paging(); + paging.setCount(load_item_limit); + final long maxId, sinceId; + if (isMaxIdsValid() && mMaxIds[idx] > 0) { + maxId = mMaxIds[idx]; + paging.setMaxId(maxId); + } else { + maxId = -1; + } + if (isSinceIdsValid() && mSinceIds[idx] > 0) { + sinceId = mSinceIds[idx]; + paging.setSinceId(sinceId - 1); + } else { + sinceId = -1; + } + final List statuses = new ArrayList<>(); + final boolean truncated = truncateStatuses(getStatuses(twitter, paging), statuses, sinceId); + result.add(new StatusListResponse(account_id, maxId, sinceId, load_item_limit, statuses, + truncated)); + } catch (final TwitterException e) { + result.add(new StatusListResponse(account_id, e)); + } + } + idx++; + } + return result; + } + + final boolean isMaxIdsValid() { + return mMaxIds != null && mMaxIds.length == mAccountIds.length; + } + + final boolean isSinceIdsValid() { + return mSinceIds != null && mSinceIds.length == mAccountIds.length; + } + + } + + abstract class GetTrendsTask extends ManagedAsyncTask> { + + private final long account_id; + + public GetTrendsTask(final long account_id) { + super(mContext, mAsyncTaskManager, TASK_TAG_GET_TRENDS); + this.account_id = account_id; + } + + public abstract List getTrends(Twitter twitter) throws TwitterException; + + @Override + protected ListResponse doInBackground(final Void... params) { + final Twitter twitter = getTwitterInstance(mContext, account_id, false); + final Bundle extras = new Bundle(); + extras.putLong(EXTRA_ACCOUNT_ID, account_id); + if (twitter != null) { + try { + return new ListResponse<>(getTrends(twitter), null, extras); + } catch (final TwitterException e) { + return new ListResponse<>(null, e, extras); + } + } + return new ListResponse<>(null, null, extras); + } + + } + + final class RemoveUnreadCountsTask extends AsyncTask { + private final int position; + private final Map> counts; + + RemoveUnreadCountsTask(final int position, final Map> counts) { + this.position = position; + this.counts = counts; + } + + @Override + protected Integer doInBackground(final Void... params) { + return removeUnreadCounts(mContext, position, counts); + } + + } + + class ReportMultiSpamTask extends ManagedAsyncTask> { + + private final long account_id; + private final long[] user_ids; + + public ReportMultiSpamTask(final long account_id, final long[] user_ids) { + super(mContext, mAsyncTaskManager); + this.account_id = account_id; + this.user_ids = user_ids; + } + + @Override + protected ListResponse doInBackground(final Void... params) { + + final Bundle extras = new Bundle(); + extras.putLong(EXTRA_ACCOUNT_ID, account_id); + final List reported_users = new ArrayList<>(); + final Twitter twitter = getTwitterInstance(mContext, account_id, false); + if (twitter != null) { + for (final long user_id : user_ids) { + try { + final User user = twitter.reportSpam(user_id); + if (user == null || user.getId() <= 0) { + continue; + } + reported_users.add(user.getId()); + } catch (final TwitterException e) { + return new ListResponse<>(null, e, extras); + } + } + } + return new ListResponse<>(reported_users, null, extras); + } + + @Override + protected void onPostExecute(final ListResponse result) { + if (result != null) { + final String user_id_where = ListUtils.toString(result.list, ',', false); + for (final Uri uri : STATUSES_URIS) { + final Where where = Where.and(Where.equals(Statuses.ACCOUNT_ID, account_id), + new Where(String.format(Locale.ROOT, "%s IN (%s)", Statuses.USER_ID, user_id_where))); + mResolver.delete(uri, where.getSQL(), null); + } + mMessagesManager.showInfoMessage(R.string.reported_users_for_spam, false); + final Intent intent = new Intent(BROADCAST_MULTI_BLOCKSTATE_CHANGED); + intent.putExtra(EXTRA_USER_IDS, user_ids); + intent.putExtra(EXTRA_ACCOUNT_ID, account_id); + mContext.sendBroadcast(intent); + } + super.onPostExecute(result); + } + + } + + class ReportSpamTask extends ManagedAsyncTask> { + + private final long account_id; + private final long user_id; + + public ReportSpamTask(final long account_id, final long user_id) { + super(mContext, mAsyncTaskManager); + this.account_id = account_id; + this.user_id = user_id; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + final Twitter twitter = getTwitterInstance(mContext, account_id, false); + if (twitter != null) { + try { + final User user = twitter.reportSpam(user_id); + return SingleResponse.getInstance(user, null); + } catch (final TwitterException e) { + return SingleResponse.getInstance(null, e); + } + } + return SingleResponse.getInstance(); + } + + @Override + protected void onPostExecute(final SingleResponse result) { + if (result.hasData() && result.getData().getId() > 0) { + for (final Uri uri : STATUSES_URIS) { + final String where = Statuses.ACCOUNT_ID + " = " + account_id + " AND " + Statuses.USER_ID + " = " + + user_id; + mResolver.delete(uri, where, null); + } + mMessagesManager.showInfoMessage(R.string.reported_user_for_spam, false); + final Intent intent = new Intent(BROADCAST_FRIENDSHIP_CHANGED); + intent.putExtra(EXTRA_USER_ID, user_id); + mContext.sendBroadcast(intent); + } else { + mMessagesManager.showErrorMessage(R.string.action_reporting_for_spam, result.getException(), true); + } + super.onPostExecute(result); + } + + } + + class RetweetStatusTask extends ManagedAsyncTask> { + + private final long account_id; + + private final long status_id; + + public RetweetStatusTask(final long account_id, final long status_id) { + super(mContext, mAsyncTaskManager); + this.account_id = account_id; + this.status_id = status_id; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + + if (account_id < 0) return SingleResponse.getInstance(); + + final Twitter twitter = getTwitterInstance(mContext, account_id, false); + if (twitter != null) { + try { + final twitter4j.Status status = twitter.retweetStatus(status_id); + return SingleResponse.getInstance(status, null); + } catch (final TwitterException e) { + return SingleResponse.getInstance(null, e); + } + } + return SingleResponse.getInstance(); + } + + @Override + protected void onPostExecute(final SingleResponse result) { + + if (result.hasData() && result.getData().getId() > 0) { + final ContentValues values = new ContentValues(); + values.put(Statuses.MY_RETWEET_ID, result.getData().getId()); + final String where = Statuses.STATUS_ID + " = " + status_id + " OR " + Statuses.RETWEET_ID + " = " + + status_id; + for (final Uri uri : STATUSES_URIS) { + mResolver.update(uri, values, where, null); + } + final Intent intent = new Intent(BROADCAST_RETWEET_CHANGED); + intent.putExtra(EXTRA_STATUS_ID, status_id); + intent.putExtra(EXTRA_RETWEETED, true); + mContext.sendBroadcast(intent); + mMessagesManager.showOkMessage(R.string.status_retweeted, false); + } else { + mMessagesManager.showErrorMessage(R.string.action_retweeting, result.getException(), true); + } + + super.onPostExecute(result); + } + + } + + abstract class StoreDirectMessagesTask extends ManagedAsyncTask> { + + private final List responses; + private final Uri uri; + private final boolean notify; + + public StoreDirectMessagesTask(final List result, final Uri uri, final boolean notify, + final String tag) { + super(mContext, mAsyncTaskManager, tag); + responses = result; + this.uri = uri; + this.notify = notify; + } + + @Override + protected SingleResponse doInBackground(final Void... args) { + + boolean succeed = false; + for (final TwitterListResponse response : responses) { + final long accountId = response.account_id; + final List messages = response.list; + if (messages != null) { + final ContentValues[] values_array = new ContentValues[messages.size()]; + final long[] messageIds = new long[messages.size()]; + + for (int i = 0, j = messages.size(); i < j; i++) { + final DirectMessage message = messages.get(i); + messageIds[i] = message.getId(); + values_array[i] = makeDirectMessageContentValues(message, accountId, isOutgoing()); + } + + // Delete all rows conflicting before new data inserted. + { + final Where deleteWhere = Where.and(Where.equals(DirectMessages.ACCOUNT_ID, accountId), + Where.in(new Column(DirectMessages.MESSAGE_ID), new RawItemArray(messageIds))); + final Uri deleteUri = appendQueryParameters(uri, new NameValuePairImpl(QUERY_PARAM_NOTIFY, + false)); + mResolver.delete(deleteUri, deleteWhere.getSQL(), null); + } + + // Insert previously fetched items. + final Uri insertUri = appendQueryParameters(uri, new NameValuePairImpl(QUERY_PARAM_NOTIFY, notify)); + bulkInsert(mResolver, insertUri, values_array); + + } + succeed = true; + } + return SingleResponse.getInstance(succeed); + } + + abstract boolean isOutgoing(); + + } + + class StoreHomeTimelineTask extends StoreStatusesTask { + + public StoreHomeTimelineTask(final List result, final boolean notify) { + super(result, Statuses.CONTENT_URI, notify, TASK_TAG_STORE_HOME_TIMELINE); + } + + @Override + protected void onPostExecute(final SingleResponse response) { + if (Boolean.TRUE.equals(response.getData())) { + mContext.sendBroadcast(new Intent(BROADCAST_HOME_TIMELINE_REFRESHED)); + } + super.onPostExecute(response); + } + + } + + class StoreLocalTrendsTask extends StoreTrendsTask { + + public StoreLocalTrendsTask(final ListResponse result) { + super(result, CachedTrends.Local.CONTENT_URI); + } + + } + + class StoreMentionsTask extends StoreStatusesTask { + + public StoreMentionsTask(final List result, final boolean notify) { + super(result, Mentions.CONTENT_URI, notify, TASK_TAG_STORE_MENTIONS); + } + + @Override + protected void onPostExecute(final SingleResponse response) { + if (Boolean.TRUE.equals(response.getData())) { + mContext.sendBroadcast(new Intent(BROADCAST_MENTIONS_REFRESHED)); + } + super.onPostExecute(response); + } + + } + + class StoreReceivedDirectMessagesTask extends StoreDirectMessagesTask { + + public StoreReceivedDirectMessagesTask(final List result, final boolean notify) { + super(result, DirectMessages.Inbox.CONTENT_URI, notify, TASK_TAG_STORE_RECEIVED_DIRECT_MESSAGES); + } + + @Override + boolean isOutgoing() { + return false; + } + + } + + class StoreSentDirectMessagesTask extends StoreDirectMessagesTask { + + public StoreSentDirectMessagesTask(final List result, final boolean notify) { + super(result, DirectMessages.Outbox.CONTENT_URI, notify, TASK_TAG_STORE_SENT_DIRECT_MESSAGES); + } + + @Override + boolean isOutgoing() { + return true; + } + + } + + abstract class StoreStatusesTask extends ManagedAsyncTask> { + + private final List responses; + private final Uri uri; + private final ArrayList all_statuses = new ArrayList<>(); + private final boolean notify; + + public StoreStatusesTask(final List result, final Uri uri, final boolean notify, + final String tag) { + super(mContext, mAsyncTaskManager, tag); + responses = result; + this.uri = uri; + this.notify = notify; + } + + @Override + protected SingleResponse doInBackground(final Void... args) { + boolean succeed = false; + for (final StatusListResponse response : responses) { + final long accountId = response.account_id; + final List statuses = response.list; + if (statuses == null || statuses.isEmpty()) { + continue; + } + final ArrayList ids_in_db = getStatusIdsInDatabase(mContext, uri, accountId); + final boolean noItemsBefore = ids_in_db.isEmpty(); + final ContentValues[] values = new ContentValues[statuses.size()]; + final long[] statusIds = new long[statuses.size()]; + for (int i = 0, j = statuses.size(); i < j; i++) { + final twitter4j.Status status = statuses.get(i); + values[i] = makeStatusContentValues(status, accountId); + statusIds[i] = status.getId(); + } + // Delete all rows conflicting before new data inserted. + final Where accountWhere = Where.equals(Statuses.ACCOUNT_ID, accountId); + final Where statusWhere = Where.in(new Column(Statuses.STATUS_ID), new RawItemArray(statusIds)); + final String deleteWhere = Where.and(accountWhere, statusWhere).getSQL(); + final Uri deleteUri = appendQueryParameters(uri, new NameValuePairImpl(QUERY_PARAM_NOTIFY, false)); + final int rowsDeleted = mResolver.delete(deleteUri, deleteWhere, null); + // UCD + ProfilingUtil.profile(mContext, accountId, + "Download tweets, " + ArrayUtils.toString(statusIds, ',', true)); + all_statuses.addAll(Arrays.asList(values)); + // Insert previously fetched items. + final Uri insertUri = appendQueryParameters(uri, new NameValuePairImpl(QUERY_PARAM_NOTIFY, notify)); + bulkInsert(mResolver, insertUri, values); + + // Insert a gap. + final long minId = statusIds.length != 0 ? ArrayUtils.min(statusIds) : -1; + final boolean deletedOldGap = rowsDeleted > 0 && ArrayUtils.contains(statusIds, response.max_id); + final boolean noRowsDeleted = rowsDeleted == 0; + final boolean insertGap = minId > 0 && (noRowsDeleted || deletedOldGap) && !response.truncated + && !noItemsBefore && statuses.size() > 1; + if (insertGap) { + final ContentValues gapValue = new ContentValues(); + gapValue.put(Statuses.IS_GAP, 1); + final Where where = Where.and(Where.equals(Statuses.ACCOUNT_ID, accountId), + Where.equals(Statuses.STATUS_ID, minId)); + final Uri updateUri = appendQueryParameters(uri, new NameValuePairImpl(QUERY_PARAM_NOTIFY, true)); + mResolver.update(updateUri, gapValue, where.getSQL(), null); + } + succeed = true; + } + return SingleResponse.getInstance(succeed, null); + } + + @Override + protected void onPreExecute() { + super.onPreExecute(); + final StatusListResponse[] array = new StatusListResponse[responses.size()]; + new CacheUsersStatusesTask(mContext, responses.toArray(array)).execute(); + } + + } + + class StoreTrendsTask extends ManagedAsyncTask> { + + private final ListResponse response; + private final Uri uri; + + public StoreTrendsTask(final ListResponse result, final Uri uri) { + super(mContext, mAsyncTaskManager, TASK_TAG_STORE_TRENDS); + response = result; + this.uri = uri; + } + + @Override + protected SingleResponse doInBackground(final Void... args) { + if (response == null) return SingleResponse.getInstance(false); + final List messages = response.list; + final ArrayList hashtags = new ArrayList<>(); + final ArrayList hashtagValues = new ArrayList<>(); + if (messages != null && messages.size() > 0) { + final ContentValues[] valuesArray = makeTrendsContentValues(messages); + for (final ContentValues values : valuesArray) { + final String hashtag = values.getAsString(CachedTrends.NAME).replaceFirst("#", ""); + if (hashtags.contains(hashtag)) { + continue; + } + hashtags.add(hashtag); + final ContentValues hashtagValue = new ContentValues(); + hashtagValue.put(CachedHashtags.NAME, hashtag); + hashtagValues.add(hashtagValue); + } + mResolver.delete(uri, null, null); + bulkInsert(mResolver, uri, valuesArray); + bulkDelete(mResolver, CachedHashtags.CONTENT_URI, CachedHashtags.NAME, hashtags, null, true); + bulkInsert(mResolver, CachedHashtags.CONTENT_URI, + hashtagValues.toArray(new ContentValues[hashtagValues.size()])); + } + return SingleResponse.getInstance(true); + } + + @Override + protected void onPostExecute(final SingleResponse response) { + // if (response != null && response.data != null && + // response.data.getBoolean(EXTRA_SUCCEED)) { + // final Intent intent = new Intent(BROADCAST_TRENDS_UPDATED); + // intent.putExtra(EXTRA_SUCCEED, true); + // mContext.sendBroadcast(intent); + // } + super.onPostExecute(response); + } + + } + + class UpdateUserListDetailsTask extends ManagedAsyncTask> { + + private final long accountId; + private final long listId; + private final boolean isPublic; + private final String name, description; + + public UpdateUserListDetailsTask(final long accountId, final long listId, final boolean isPublic, + final String name, final String description) { + super(mContext, mAsyncTaskManager); + this.accountId = accountId; + this.listId = listId; + this.name = name; + this.isPublic = isPublic; + this.description = description; + } + + @Override + protected SingleResponse doInBackground(final Void... params) { + + final Twitter twitter = getTwitterInstance(mContext, accountId, false); + if (twitter != null) { + try { + final UserList list = twitter.updateUserList(listId, name, isPublic, description); + return SingleResponse.getInstance(new ParcelableUserList(list, accountId)); + } catch (final TwitterException e) { + return SingleResponse.getInstance(e); + } + } + return SingleResponse.getInstance(); + } + + @Override + protected void onPostExecute(final SingleResponse result) { + if (result.hasData() && result.getData().id > 0) { + final String message = mContext.getString(R.string.updated_list_details, result.getData().name); + mMessagesManager.showOkMessage(message, false); + final Intent intent = new Intent(BROADCAST_USER_LIST_DETAILS_UPDATED); + intent.putExtra(EXTRA_LIST_ID, listId); + mContext.sendBroadcast(intent); + } else { + mMessagesManager.showErrorMessage(R.string.action_updating_details, result.getException(), true); + } + super.onPostExecute(result); + } + + } } diff --git a/twidere/src/main/java/org/mariotaku/twidere/util/ImagePreloader.java b/twidere/src/main/java/org/mariotaku/twidere/util/ImagePreloader.java index 2dbbbfed2..8030db50c 100644 --- a/twidere/src/main/java/org/mariotaku/twidere/util/ImagePreloader.java +++ b/twidere/src/main/java/org/mariotaku/twidere/util/ImagePreloader.java @@ -19,11 +19,8 @@ package org.mariotaku.twidere.util; -import static org.mariotaku.twidere.util.Utils.isOnWifi; - import android.content.Context; import android.content.SharedPreferences; -import android.os.Handler; import android.text.TextUtils; import com.nostra13.universalimageloader.cache.disc.DiskCache; @@ -33,49 +30,42 @@ import org.mariotaku.twidere.Constants; import java.io.File; +import static org.mariotaku.twidere.util.Utils.isOnWifi; + /** * @author mariotaku */ public class ImagePreloader implements Constants { - public static final String LOGTAG = "ImagePreloader"; + public static final String LOGTAG = "ImagePreloader"; - private final Context mContext; - private final SharedPreferences mPreferences; - private final Handler mHandler; - private final DiskCache mDiskCache; - private final ImageLoader mImageLoader; + private final Context mContext; + private final SharedPreferences mPreferences; + private final DiskCache mDiskCache; + private final ImageLoader mImageLoader; - public ImagePreloader(final Context context, final ImageLoader loader) { - mContext = context; - mPreferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); - mImageLoader = loader; - mDiskCache = loader.getDiskCache(); - mHandler = new Handler(); - } + public ImagePreloader(final Context context, final ImageLoader loader) { + mContext = context; + mPreferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); + mImageLoader = loader; + mDiskCache = loader.getDiskCache(); + } - public File getCachedImageFile(final String url) { - if (url == null) return null; - final File cache = mDiskCache.get(url); - if (ImageValidator.checkImageValidity(cache)) - return cache; - else { - preloadImage(url); - } - return null; - } + public File getCachedImageFile(final String url) { + if (url == null) return null; + final File cache = mDiskCache.get(url); + if (ImageValidator.checkImageValidity(cache)) + return cache; + else { + preloadImage(url); + } + return null; + } - public void preloadImage(final String url) { - if (TextUtils.isEmpty(url)) return; - if (!isOnWifi(mContext) && mPreferences.getBoolean(KEY_PRELOAD_WIFI_ONLY, true)) return; - mHandler.post(new Runnable() { - - @Override - public void run() { - mImageLoader.loadImage(url, null); - } - - }); - } + public void preloadImage(final String url) { + if (TextUtils.isEmpty(url)) return; + if (!isOnWifi(mContext) && mPreferences.getBoolean(KEY_PRELOAD_WIFI_ONLY, true)) return; + mImageLoader.loadImage(url, null); + } } diff --git a/twidere/src/main/java/org/mariotaku/twidere/util/ThemeUtils.java b/twidere/src/main/java/org/mariotaku/twidere/util/ThemeUtils.java index 12cb2602d..87ddb434d 100644 --- a/twidere/src/main/java/org/mariotaku/twidere/util/ThemeUtils.java +++ b/twidere/src/main/java/org/mariotaku/twidere/util/ThemeUtils.java @@ -50,7 +50,7 @@ import org.mariotaku.refreshnow.widget.RefreshNowProgressIndicator.IndicatorConf import org.mariotaku.twidere.Constants; import org.mariotaku.twidere.R; import org.mariotaku.twidere.activity.iface.IThemedActivity; -import org.mariotaku.twidere.util.menu.StatusMenuInfo; +import org.mariotaku.twidere.util.menu.TwidereMenuInfo; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; @@ -146,15 +146,15 @@ public class ThemeUtils implements Constants { if (info instanceof MenuBarMenuInfo) { final MenuBarMenuInfo mbInfo = (MenuBarMenuInfo) info; final boolean inPopup = mbInfo.isInPopup(); - if (mbInfo.getMenuInfo() instanceof StatusMenuInfo) { - final StatusMenuInfo sInfo = (StatusMenuInfo) mbInfo.getMenuInfo(); + if (mbInfo.getMenuInfo() instanceof TwidereMenuInfo) { + final TwidereMenuInfo sInfo = (TwidereMenuInfo) mbInfo.getMenuInfo(); icon.setColorFilter(sInfo.isHighlight() ? highlightColor : (inPopup ? popupColor : color), mode); } else { icon.setColorFilter(inPopup ? popupColor : color, mode); } - } else if (info instanceof StatusMenuInfo) { - final StatusMenuInfo sInfo = (StatusMenuInfo) info; + } else if (info instanceof TwidereMenuInfo) { + final TwidereMenuInfo sInfo = (TwidereMenuInfo) info; icon.setColorFilter(sInfo.isHighlight() ? highlightColor : color, mode); } else { icon.setColorFilter(color, mode); diff --git a/twidere/src/main/java/org/mariotaku/twidere/util/Utils.java b/twidere/src/main/java/org/mariotaku/twidere/util/Utils.java index 74b4824a4..d207c224c 100644 --- a/twidere/src/main/java/org/mariotaku/twidere/util/Utils.java +++ b/twidere/src/main/java/org/mariotaku/twidere/util/Utils.java @@ -163,6 +163,7 @@ import org.mariotaku.twidere.provider.TweetStore.DNS; import org.mariotaku.twidere.provider.TweetStore.DirectMessages; import org.mariotaku.twidere.provider.TweetStore.Drafts; import org.mariotaku.twidere.provider.TweetStore.Filters; +import org.mariotaku.twidere.provider.TweetStore.Filters.Users; import org.mariotaku.twidere.provider.TweetStore.Mentions; import org.mariotaku.twidere.provider.TweetStore.Notifications; import org.mariotaku.twidere.provider.TweetStore.Permissions; @@ -172,7 +173,7 @@ import org.mariotaku.twidere.provider.TweetStore.Tabs; import org.mariotaku.twidere.provider.TweetStore.UnreadCounts; import org.mariotaku.twidere.service.RefreshService; import org.mariotaku.twidere.util.content.ContentResolverUtils; -import org.mariotaku.twidere.util.menu.StatusMenuInfo; +import org.mariotaku.twidere.util.menu.TwidereMenuInfo; import org.mariotaku.twidere.util.net.TwidereHostResolverFactory; import org.mariotaku.twidere.util.net.TwidereHttpClientFactory; @@ -3436,16 +3437,16 @@ public final class Utils implements Constants, TwitterConstants { final MenuItem retweet = menu.findItem(MENU_RETWEET); if (retweet != null) { retweet.setVisible(!status.user_is_protected || isMyRetweet); - MenuUtils.setMenuInfo(retweet, new StatusMenuInfo(isMyRetweet)); + MenuUtils.setMenuInfo(retweet, new TwidereMenuInfo(isMyRetweet)); retweet.setTitle(isMyRetweet ? R.string.cancel_retweet : R.string.retweet); } final MenuItem retweetSubItem = menu.findItem(R.id.retweet_submenu); if (retweetSubItem != null) { - MenuUtils.setMenuInfo(retweetSubItem, new StatusMenuInfo(isMyRetweet)); + MenuUtils.setMenuInfo(retweetSubItem, new TwidereMenuInfo(isMyRetweet)); } final MenuItem favorite = menu.findItem(MENU_FAVORITE); if (favorite != null) { - MenuUtils.setMenuInfo(favorite, new StatusMenuInfo(status.is_favorite)); + MenuUtils.setMenuInfo(favorite, new TwidereMenuInfo(status.is_favorite)); favorite.setTitle(status.is_favorite ? R.string.unfavorite : R.string.favorite); } final MenuItem translate = menu.findItem(MENU_TRANSLATE); @@ -3585,16 +3586,16 @@ public final class Utils implements Constants, TwitterConstants { public static void showInfoMessage(final Context context, final CharSequence message, final boolean long_message) { if (context == null || isEmpty(message)) return; - if (context instanceof Activity) { - final Crouton crouton = Crouton.makeText((Activity) context, message, CroutonStyle.INFO); - final CroutonConfiguration.Builder cb = new CroutonConfiguration.Builder(); - cb.setDuration(long_message ? CroutonConfiguration.DURATION_LONG : CroutonConfiguration.DURATION_SHORT); - crouton.setConfiguration(cb.build()); - crouton.show(); - } else { - final Toast toast = Toast.makeText(context, message, long_message ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT); - toast.show(); - } +// if (context instanceof Activity) { +// final Crouton crouton = Crouton.makeText((Activity) context, message, CroutonStyle.INFO); +// final CroutonConfiguration.Builder cb = new CroutonConfiguration.Builder(); +// cb.setDuration(long_message ? CroutonConfiguration.DURATION_LONG : CroutonConfiguration.DURATION_SHORT); +// crouton.setConfiguration(cb.build()); +// crouton.show(); +// } else { + final Toast toast = Toast.makeText(context, message, long_message ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT); + toast.show(); +// } } public static void showInfoMessage(final Context context, final int resId, final boolean long_message) { @@ -3893,4 +3894,15 @@ public final class Utils implements Constants, TwitterConstants { } } } + + public static boolean isFilteringUser(Context context, long userId) { + final ContentResolver cr = context.getContentResolver(); + final Where where = Where.equals(Users.USER_ID, userId); + final Cursor c = cr.query(Users.CONTENT_URI, new String[0], where.getSQL(), null, null); + try { + return c.getCount() > 0; + } finally { + c.close(); + } + } } diff --git a/twidere/src/main/java/org/mariotaku/twidere/util/menu/StatusMenuInfo.java b/twidere/src/main/java/org/mariotaku/twidere/util/menu/TwidereMenuInfo.java similarity index 73% rename from twidere/src/main/java/org/mariotaku/twidere/util/menu/StatusMenuInfo.java rename to twidere/src/main/java/org/mariotaku/twidere/util/menu/TwidereMenuInfo.java index 4d7f2164c..5f8dd3f70 100644 --- a/twidere/src/main/java/org/mariotaku/twidere/util/menu/StatusMenuInfo.java +++ b/twidere/src/main/java/org/mariotaku/twidere/util/menu/TwidereMenuInfo.java @@ -5,10 +5,10 @@ import android.view.ContextMenu.ContextMenuInfo; /** * Created by mariotaku on 14/10/27. */ -public class StatusMenuInfo implements ContextMenuInfo { +public class TwidereMenuInfo implements ContextMenuInfo { private final boolean highlight; - public StatusMenuInfo(boolean highlight) { + public TwidereMenuInfo(boolean highlight) { this.highlight = highlight; } diff --git a/twidere/src/main/java/org/mariotaku/twidere/view/HomeActionButtonCompat.java b/twidere/src/main/java/org/mariotaku/twidere/view/HomeActionButtonCompat.java index 2ed5e205e..825e7f2d2 100644 --- a/twidere/src/main/java/org/mariotaku/twidere/view/HomeActionButtonCompat.java +++ b/twidere/src/main/java/org/mariotaku/twidere/view/HomeActionButtonCompat.java @@ -22,8 +22,8 @@ package org.mariotaku.twidere.view; import android.content.Context; import android.graphics.Bitmap; import android.graphics.PorterDuff.Mode; +import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; -import android.graphics.drawable.LayerDrawable; import android.util.AttributeSet; import android.view.View; import android.widget.FrameLayout; @@ -32,10 +32,12 @@ import android.widget.ProgressBar; import org.mariotaku.twidere.R; import org.mariotaku.twidere.util.ThemeUtils; +import org.mariotaku.twidere.util.accessor.ViewAccessor; import org.mariotaku.twidere.view.iface.IHomeActionButton; public class HomeActionButtonCompat extends FrameLayout implements IHomeActionButton { + private final ImageView mBackgroundView; private final ImageView mIconView; private final ProgressBar mProgressBar; @@ -49,19 +51,31 @@ public class HomeActionButtonCompat extends FrameLayout implements IHomeActionBu public HomeActionButtonCompat(final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); + ViewAccessor.setBackground(this, null); inflate(ThemeUtils.getActionBarContext(context), R.layout.action_item_home_actions_compat, this); + mBackgroundView = (ImageView) findViewById(R.id.background); mIconView = (ImageView) findViewById(android.R.id.icon); mProgressBar = (ProgressBar) findViewById(android.R.id.progress); } @Override public void setButtonColor(int color) { - final Drawable drawable = getBackground(); - if (drawable instanceof LayerDrawable) { - final Drawable layer = ((LayerDrawable) drawable).findDrawableByLayerId(R.id.color_layer); - if (layer != null) { - layer.setColorFilter(color, Mode.SRC_ATOP); - } + mBackgroundView.setImageDrawable(new MyColorDrawable(color)); + } + + private static class MyColorDrawable extends ColorDrawable { + public MyColorDrawable(int color) { + super(color); + } + + @Override + public int getIntrinsicHeight() { + return 16; + } + + @Override + public int getIntrinsicWidth() { + return 16; } } diff --git a/twidere/src/main/java/twitter4j/TwitterImpl.java b/twidere/src/main/java/twitter4j/TwitterImpl.java index 60f64b72e..ea5476b39 100644 --- a/twidere/src/main/java/twitter4j/TwitterImpl.java +++ b/twidere/src/main/java/twitter4j/TwitterImpl.java @@ -1609,9 +1609,9 @@ final class TwitterImpl extends TwitterBaseImpl implements Twitter { ensureAuthorizationEnabled(); final String url = conf.getRestBaseURL() + (status.isWithMedia() ? ENDPOINT_STATUSES_UPDATE_WITH_MEDIA : ENDPOINT_STATUSES_UPDATE); - final String sign_url = conf.getSigningRestBaseURL() + final String signUrl = conf.getSigningRestBaseURL() + (status.isWithMedia() ? ENDPOINT_STATUSES_UPDATE_WITH_MEDIA : ENDPOINT_STATUSES_UPDATE); - return factory.createStatus(post(url, sign_url, status.asHttpParameterArray(INCLUDE_ENTITIES))); + return factory.createStatus(post(url, signUrl, status.asHttpParameterArray(INCLUDE_ENTITIES))); } @Override diff --git a/twidere/src/main/res/layout-v21/layout_home_actions_button.xml b/twidere/src/main/res-unused/layout-v21/layout_home_actions_button.xml similarity index 100% rename from twidere/src/main/res/layout-v21/layout_home_actions_button.xml rename to twidere/src/main/res-unused/layout-v21/layout_home_actions_button.xml diff --git a/twidere/src/main/res/drawable-hdpi/ic_action_add_to_list.png b/twidere/src/main/res/drawable-hdpi/ic_action_add_to_list.png new file mode 100644 index 000000000..7f0db8484 Binary files /dev/null and b/twidere/src/main/res/drawable-hdpi/ic_action_add_to_list.png differ diff --git a/twidere/src/main/res/drawable-mdpi/ic_action_add_to_list.png b/twidere/src/main/res/drawable-mdpi/ic_action_add_to_list.png new file mode 100644 index 000000000..8f077d5ed Binary files /dev/null and b/twidere/src/main/res/drawable-mdpi/ic_action_add_to_list.png differ diff --git a/twidere/src/main/res/drawable-xhdpi/ic_action_add_to_list.png b/twidere/src/main/res/drawable-xhdpi/ic_action_add_to_list.png new file mode 100644 index 000000000..e23f70274 Binary files /dev/null and b/twidere/src/main/res/drawable-xhdpi/ic_action_add_to_list.png differ diff --git a/twidere/src/main/res/drawable-xxhdpi/ic_action_add_to_list.png b/twidere/src/main/res/drawable-xxhdpi/ic_action_add_to_list.png new file mode 100644 index 000000000..0be5e31e4 Binary files /dev/null and b/twidere/src/main/res/drawable-xxhdpi/ic_action_add_to_list.png differ diff --git a/twidere/src/main/res/drawable/bg_unread_indicator.xml b/twidere/src/main/res/drawable/bg_unread_indicator.xml new file mode 100644 index 000000000..1686d016c --- /dev/null +++ b/twidere/src/main/res/drawable/bg_unread_indicator.xml @@ -0,0 +1,8 @@ + + + + + \ No newline at end of file diff --git a/twidere/src/main/res/drawable/btn_home_actions_compat.xml b/twidere/src/main/res/drawable/btn_home_actions_compat.xml index c0493eb28..4f305d662 100644 --- a/twidere/src/main/res/drawable/btn_home_actions_compat.xml +++ b/twidere/src/main/res/drawable/btn_home_actions_compat.xml @@ -1,15 +1,13 @@ - + - - - + style="?android:actionButtonStyle"> \ No newline at end of file diff --git a/twidere/src/main/res/layout/action_item_compose_send.xml b/twidere/src/main/res/layout/action_item_compose_send.xml index ff870dc61..820d3c161 100644 --- a/twidere/src/main/res/layout/action_item_compose_send.xml +++ b/twidere/src/main/res/layout/action_item_compose_send.xml @@ -16,6 +16,7 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" + android:minWidth="@dimen/element_size_small" android:textAppearance="?android:textAppearanceSmall"/> - + - + - + android:visibility="gone"/> + + \ No newline at end of file diff --git a/twidere/src/main/res/layout/activity_compose_actionbar.xml b/twidere/src/main/res/layout/activity_compose_actionbar.xml index 42f2ca164..b163fac44 100644 --- a/twidere/src/main/res/layout/activity_compose_actionbar.xml +++ b/twidere/src/main/res/layout/activity_compose_actionbar.xml @@ -65,6 +65,4 @@ - - \ No newline at end of file diff --git a/twidere/src/main/res/layout/layout_home_actions_button.xml b/twidere/src/main/res/layout/layout_home_actions_button.xml index 866a4f019..4da90a210 100644 --- a/twidere/src/main/res/layout/layout_home_actions_button.xml +++ b/twidere/src/main/res/layout/layout_home_actions_button.xml @@ -7,5 +7,4 @@ android:layout_height="@dimen/float_action_button_size" android:layout_gravity="bottom|right" android:layout_margin="@dimen/element_spacing_large" - android:background="@drawable/btn_home_actions_compat" android:visibility="visible"/> \ No newline at end of file diff --git a/twidere/src/main/res/layout/tab_item_home.xml b/twidere/src/main/res/layout/tab_item_home.xml index dc04144b0..d42d18892 100644 --- a/twidere/src/main/res/layout/tab_item_home.xml +++ b/twidere/src/main/res/layout/tab_item_home.xml @@ -1,6 +1,7 @@ @@ -21,13 +22,16 @@ android:layout_centerInParent="true" android:scaleType="centerInside"/> - diff --git a/twidere/src/main/res/menu/menu_user_profile.xml b/twidere/src/main/res/menu/menu_user_profile.xml index 611660192..9d09043ca 100644 --- a/twidere/src/main/res/menu/menu_user_profile.xml +++ b/twidere/src/main/res/menu/menu_user_profile.xml @@ -25,7 +25,7 @@ android:visible="false"/> 72dp 32dp + 16dp \ No newline at end of file diff --git a/twidere/src/main/res/values/strings.xml b/twidere/src/main/res/values/strings.xml index a1b59e77c..c8b5b8841 100644 --- a/twidere/src/main/res/values/strings.xml +++ b/twidere/src/main/res/values/strings.xml @@ -166,6 +166,7 @@ Muted users Added this user to filter list. You will not see tweets from this user in your home timeline/mentions list. Added users to filter list. You will not see tweets from these users in your home timeline/mentions list. + Removed this user from filter list. Inbox Load images Other settings @@ -649,5 +650,15 @@ Inverse selection Edit medias Medias + Mute %s + Muted %s + Unmute %s + Unmuted %s + Mute + Unmute + muting + unmuting + Mute %s? You will no longer see tweets from this user while keep following this user. + Remove from filter \ No newline at end of file