fixed cached user search user type

This commit is contained in:
Mariotaku Lee 2017-03-27 21:56:03 +08:00
parent 9040dca086
commit 08975a71e3
No known key found for this signature in database
GPG Key ID: 15C10F89D7C33535
41 changed files with 236 additions and 167 deletions

View File

@ -193,6 +193,10 @@ public class ParcelableUser implements Parcelable, Comparable<ParcelableUser> {
@CursorField(value = CachedUsers.SCORE, excludeWrite = true)
public int score;
@ParcelableThisPlease
@CursorField(value = CachedUsers.USER_TYPE)
public String user_type;
@ParcelableThisPlease
public int color;
@ParcelableThisPlease

View File

@ -32,7 +32,6 @@ import org.mariotaku.twidere.model.FiltersSubscriptionTableInfo;
import org.mariotaku.twidere.model.ParcelableActivityTableInfo;
import org.mariotaku.twidere.model.ParcelableMessageConversationTableInfo;
import org.mariotaku.twidere.model.ParcelableMessageTableInfo;
import org.mariotaku.twidere.model.ParcelableRelationship;
import org.mariotaku.twidere.model.ParcelableRelationshipTableInfo;
import org.mariotaku.twidere.model.ParcelableStatusTableInfo;
import org.mariotaku.twidere.model.ParcelableTrendTableInfo;
@ -272,6 +271,8 @@ public interface TwidereDataStore {
String SCORE = "score";
String USER_TYPE = "user_type";
String EXTRAS = "extras";
String[] COLUMNS = ParcelableUserTableInfo.COLUMNS;

View File

@ -24,12 +24,14 @@ class ParcelableStatusUtilsTest {
val context = InstrumentationRegistry.getContext()
val status_8754050 = context.resources.openRawResource(R.raw.status_8754050).use {
val status = LoganSquare.parse(it, Status::class.java)
return@use ParcelableStatusUtils.fromStatus(status, UserKey("1234567", "gnusocial.de"), false)
return@use ParcelableStatusUtils.fromStatus(status, UserKey("1234567", "gnusocial.de"),
"statusnet", false)
}
val status_9171447 = context.resources.openRawResource(R.raw.status_9171447).use {
val status = LoganSquare.parse(it, Status::class.java)
return@use ParcelableStatusUtils.fromStatus(status, UserKey("1234567", "gnusocial.de"), false)
return@use ParcelableStatusUtils.fromStatus(status, UserKey("1234567", "gnusocial.de"),
"statusnet", false)
}
Assert.assertEquals(status_8754050.text_unescaped, expectedStatusText)

View File

@ -106,7 +106,8 @@ class UserStreamDumperPlugin(val context: Context) : DumperPlugin {
override fun onActivityAboutMe(activity: Activity): Boolean {
if (!includeInteractions && includeTimeline) return true
val pActivity = ParcelableActivityUtils.fromActivity(activity, account.key)
val pActivity = ParcelableActivityUtils.fromActivity(activity, account.key,
account.type)
val message = ActivityTitleSummaryMessage.get(context, manager, pActivity, pActivity.sources, 0,
true, true)
if (message != null) {
@ -154,7 +155,8 @@ class UserStreamDumperPlugin(val context: Context) : DumperPlugin {
override fun onActivityAboutMe(activity: Activity): Boolean {
if (!includeInteractions && includeTimeline) return true
val pActivity = ParcelableActivityUtils.fromActivity(activity, account.key)
val pActivity = ParcelableActivityUtils.fromActivity(activity, account.key,
account.type)
val message = ActivityTitleSummaryMessage.get(context, manager, pActivity, pActivity.sources, 0,
true, true)
if (message != null) {

View File

@ -34,7 +34,7 @@ import static org.mariotaku.twidere.annotation.PreferenceType.STRING;
public interface Constants extends TwidereConstants {
String DATABASES_NAME = "twidere.sqlite";
int DATABASES_VERSION = 181;
int DATABASES_VERSION = 182;
int EXTRA_FEATURES_NOTICE_VERSION = 1;

View File

@ -98,11 +98,13 @@ public class ParcelableMediaUtils {
}
@Nullable
public static ParcelableMedia[] fromStatus(@NonNull final Status status, UserKey accountKey) {
public static ParcelableMedia[] fromStatus(@NonNull final Status status, UserKey accountKey,
String accountType) {
final ParcelableMedia[] fromEntities = fromEntities(status);
final ParcelableMedia[] fromAttachments = fromAttachments(status);
final ParcelableMedia[] fromCard = fromCard(status.getCard(), status.getUrlEntities(),
status.getMediaEntities(), status.getExtendedMediaEntities(), accountKey);
status.getMediaEntities(), status.getExtendedMediaEntities(), accountKey,
accountType);
final ParcelableMedia[] fromPhoto = fromPhoto(status);
final ParcelableMedia[] merged = new ParcelableMedia[fromCard.length +
fromAttachments.length + fromEntities.length + fromPhoto.length];
@ -157,16 +159,15 @@ public class ParcelableMediaUtils {
@NonNull
private static ParcelableMedia[] fromCard(@Nullable CardEntity card,
@Nullable UrlEntity[] urlEntities,
@Nullable MediaEntity[] mediaEntities,
@Nullable MediaEntity[] extendedMediaEntities,
UserKey accountKey) {
@Nullable UrlEntity[] urlEntities, @Nullable MediaEntity[] mediaEntities,
@Nullable MediaEntity[] extendedMediaEntities, UserKey accountKey, String accountType) {
if (card == null) return new ParcelableMedia[0];
final String name = card.getName();
if ("animated_gif".equals(name) || "player".equals(name)) {
final ParcelableMedia media = new ParcelableMedia();
final CardEntity.BindingValue playerStreamUrl = card.getBindingValue("player_stream_url");
media.card = ParcelableCardEntityUtils.INSTANCE.fromCardEntity(card, accountKey);
media.card = ParcelableCardEntityUtils.INSTANCE.fromCardEntity(card, accountKey,
accountType);
CardEntity.StringValue appUrlResolved = (CardEntity.StringValue) card.getBindingValue("app_url_resolved");
media.url = checkUrl(appUrlResolved) ? appUrlResolved.getValue() : card.getUrl();
if ("animated_gif".equals(name)) {
@ -203,7 +204,8 @@ public class ParcelableMediaUtils {
final ParcelableMedia media = new ParcelableMedia();
media.url = card.getUrl();
media.card = ParcelableCardEntityUtils.INSTANCE.fromCardEntity(card, accountKey);
media.card = ParcelableCardEntityUtils.INSTANCE.fromCardEntity(card, accountKey,
accountType);
media.type = ParcelableMedia.Type.IMAGE;
media.media_url = ((CardEntity.ImageValue) photoImageFullSize).getUrl();
media.width = ((CardEntity.ImageValue) photoImageFullSize).getWidth();

View File

@ -344,8 +344,8 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher, APIEditorDi
Toast.makeText(this, R.string.message_toast_already_logged_in, Toast.LENGTH_SHORT).show()
} else {
result.addAccount(am, preferences[randomizeAccountNameKey])
Analyzer.log(SignIn(true, accountType = result.accountType.first, credentialsType = apiConfig.credentialsType,
officialKey = result.accountType.second?.official ?: false))
Analyzer.log(SignIn(true, accountType = result.typeExtras.first, credentialsType = apiConfig.credentialsType,
officialKey = result.typeExtras.second?.official ?: false))
finishSignIn()
}
}
@ -611,10 +611,10 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher, APIEditorDi
accountType = apiConfig.type, cls = MicroBlog::class.java)
val apiUser = twitter.verifyCredentials()
var color = analyseUserProfileColor(apiUser)
val accountType = SignInActivity.detectAccountType(twitter, apiUser, apiConfig.type)
val typeExtras = SignInActivity.detectAccountType(twitter, apiUser, apiConfig.type)
val userId = apiUser.id!!
val accountKey = UserKey(userId, UserKeyUtils.getUserHost(apiUser))
val user = ParcelableUserUtils.fromUser(apiUser, accountKey,
val user = ParcelableUserUtils.fromUser(apiUser, accountKey, typeExtras.first,
profileImageSize = profileImageSize)
val am = AccountManager.get(context)
val account = AccountUtils.findByAccountKey(am, accountKey)
@ -633,7 +633,7 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher, APIEditorDi
credentials.access_token_secret = accessToken.oauthTokenSecret
return SignInResponse(account != null, Credentials.Type.OAUTH, credentials, user, color,
accountType)
typeExtras)
}
}
@ -763,19 +763,19 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher, APIEditorDi
val credentials: Credentials,
val user: ParcelableUser,
val color: Int = 0,
val accountType: Pair<String, AccountExtras?>
val typeExtras: Pair<String, AccountExtras?>
) {
private fun writeAccountInfo(action: (k: String, v: String?) -> Unit) {
action(ACCOUNT_USER_DATA_KEY, user.key.toString())
action(ACCOUNT_USER_DATA_TYPE, accountType.first)
action(ACCOUNT_USER_DATA_TYPE, typeExtras.first)
action(ACCOUNT_USER_DATA_CREDS_TYPE, credsType)
action(ACCOUNT_USER_DATA_ACTIVATED, true.toString())
action(ACCOUNT_USER_DATA_COLOR, toHexColor(color, format = HexColorFormat.RGB))
action(ACCOUNT_USER_DATA_USER, LoganSquare.serialize(user))
action(ACCOUNT_USER_DATA_EXTRAS, accountType.second?.let { LoganSquare.serialize(it) })
action(ACCOUNT_USER_DATA_EXTRAS, typeExtras.second?.let { LoganSquare.serialize(it) })
}
private fun writeAuthToken(am: AccountManager, account: Account) {
@ -901,9 +901,9 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher, APIEditorDi
val userId = apiUser.id!!
var color = analyseUserProfileColor(apiUser)
val accountType = SignInActivity.detectAccountType(twitter, apiUser, apiConfig.type)
val typeExtras = SignInActivity.detectAccountType(twitter, apiUser, apiConfig.type)
val accountKey = UserKey(userId, UserKeyUtils.getUserHost(apiUser))
val user = ParcelableUserUtils.fromUser(apiUser, accountKey,
val user = ParcelableUserUtils.fromUser(apiUser, accountKey, typeExtras.first,
profileImageSize = profileImageSize)
val am = AccountManager.get(activity)
val account = AccountUtils.findByAccountKey(am, accountKey)
@ -916,7 +916,7 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher, APIEditorDi
credentials.username = username
credentials.password = password
return SignInResponse(account != null, Credentials.Type.BASIC, credentials, user,
color, accountType)
color, typeExtras)
}
@ -932,9 +932,9 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher, APIEditorDi
val apiUser = twitter.verifyCredentials()
val userId = apiUser.id!!
var color = analyseUserProfileColor(apiUser)
val accountType = SignInActivity.detectAccountType(twitter, apiUser, apiConfig.type)
val typeExtras = SignInActivity.detectAccountType(twitter, apiUser, apiConfig.type)
val accountKey = UserKey(userId, UserKeyUtils.getUserHost(apiUser))
val user = ParcelableUserUtils.fromUser(apiUser, accountKey,
val user = ParcelableUserUtils.fromUser(apiUser, accountKey, typeExtras.first,
profileImageSize = profileImageSize)
val am = AccountManager.get(activity)
val account = AccountUtils.findByAccountKey(am, accountKey)
@ -946,7 +946,7 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher, APIEditorDi
credentials.no_version_suffix = apiConfig.isNoVersionSuffix
return SignInResponse(account != null, Credentials.Type.EMPTY, credentials, user, color,
accountType)
typeExtras)
}
@Throws(MicroBlogException::class)
@ -961,9 +961,9 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher, APIEditorDi
accountType = apiConfig.type, cls = MicroBlog::class.java)
val apiUser = twitter.verifyCredentials()
var color = analyseUserProfileColor(apiUser)
val accountType = SignInActivity.detectAccountType(twitter, apiUser, apiConfig.type)
val typeExtras = SignInActivity.detectAccountType(twitter, apiUser, apiConfig.type)
val accountKey = UserKey(userId, UserKeyUtils.getUserHost(apiUser))
val user = ParcelableUserUtils.fromUser(apiUser, accountKey,
val user = ParcelableUserUtils.fromUser(apiUser, accountKey, typeExtras.first,
profileImageSize = profileImageSize)
val am = AccountManager.get(activity)
val account = AccountUtils.findByAccountKey(am, accountKey)
@ -981,7 +981,7 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher, APIEditorDi
credentials.access_token = accessToken.oauthToken
credentials.access_token_secret = accessToken.oauthTokenSecret
return SignInResponse(account != null, authType, credentials, user, color, accountType)
return SignInResponse(account != null, authType, credentials, user, color, typeExtras)
}
internal class WrongBasicCredentialException : OAuthPasswordAuthenticator.AuthenticationException()

View File

@ -2102,7 +2102,7 @@ class StatusFragment : BaseFragment(), LoaderCallbacks<SingleResponse<Parcelable
val retweeters = ArrayList<ParcelableUser>()
try {
for (status in twitter.getRetweets(statusId, paging)) {
val user = ParcelableUserUtils.fromUser(status.user, accountKey)
val user = ParcelableUserUtils.fromUser(status.user, accountKey, details.type)
if (!DataStoreUtils.isFilteringUser(context, user.key.toString())) {
retweeters.add(user)
}
@ -2132,8 +2132,8 @@ class StatusFragment : BaseFragment(), LoaderCallbacks<SingleResponse<Parcelable
Expression.equalsArgs(Activities.STATUS_ID),
Expression.equalsArgs(Activities.STATUS_RETWEET_ID)))
val pStatus = ParcelableStatusUtils.fromStatus(status,
accountKey, false)
val pStatus = ParcelableStatusUtils.fromStatus(status, accountKey, details.type,
false)
cr.insert(CachedStatuses.CONTENT_URI, ObjectCursor.valuesCreatorFrom(ParcelableStatus::class.java).create(pStatus))
val activityCursor = cr.query(Activities.AboutMe.CONTENT_URI,

View File

@ -1401,22 +1401,31 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
val args = arguments
val tabArgs = Bundle()
val user = args.getParcelable<ParcelableUser>(EXTRA_USER)
val userKey: UserKey?
if (user != null) {
tabArgs.putParcelable(EXTRA_ACCOUNT_KEY, user.account_key)
userKey = user.account_key
tabArgs.putParcelable(EXTRA_ACCOUNT_KEY, userKey)
tabArgs.putParcelable(EXTRA_USER_KEY, user.key)
tabArgs.putString(EXTRA_SCREEN_NAME, user.screen_name)
} else {
tabArgs.putParcelable(EXTRA_ACCOUNT_KEY, args.getParcelable<Parcelable>(EXTRA_ACCOUNT_KEY))
userKey = args.getParcelable<UserKey>(EXTRA_ACCOUNT_KEY)
tabArgs.putParcelable(EXTRA_ACCOUNT_KEY, userKey)
tabArgs.putParcelable(EXTRA_USER_KEY, args.getParcelable<Parcelable>(EXTRA_USER_KEY))
tabArgs.putString(EXTRA_SCREEN_NAME, args.getString(EXTRA_SCREEN_NAME))
}
pagerAdapter.add(cls = UserTimelineFragment::class.java, args = Bundle(tabArgs).apply {
putBoolean(EXTRA_EXCLUDE_REPLIES, true)
}, name = getString(R.string.title_statuses), type = TAB_TYPE_STATUSES,
position = TAB_POSITION_STATUSES)
pagerAdapter.add(cls = UserTimelineFragment::class.java, args = tabArgs,
name = getString(R.string.title_statuses_and_replies), type = TAB_TYPE_STATUSES_WITH_REPLIES,
position = TAB_POSITION_STATUSES)
if (userKey?.host == USER_TYPE_TWITTER_COM) {
pagerAdapter.add(cls = UserTimelineFragment::class.java, args = Bundle(tabArgs).apply {
putBoolean(EXTRA_EXCLUDE_REPLIES, true)
}, name = getString(R.string.title_statuses), type = TAB_TYPE_STATUSES,
position = TAB_POSITION_STATUSES)
pagerAdapter.add(cls = UserTimelineFragment::class.java, args = tabArgs,
name = getString(R.string.title_statuses_and_replies), type = TAB_TYPE_STATUSES_WITH_REPLIES,
position = TAB_POSITION_STATUSES)
} else {
pagerAdapter.add(cls = UserTimelineFragment::class.java, args = tabArgs,
name = getString(R.string.title_statuses), type = TAB_TYPE_STATUSES,
position = TAB_POSITION_STATUSES)
}
pagerAdapter.add(cls = UserMediaTimelineFragment::class.java, args = tabArgs,
name = getString(R.string.media), type = TAB_TYPE_MEDIA,
position = TAB_POSITION_MEDIA)

View File

@ -363,9 +363,10 @@ class UserProfileEditorFragment : BaseFragment(), OnSizeChangedListener, TextWat
override fun doLongOperation(context: Context): SingleResponse<ParcelableUser> {
val details = AccountUtils.getAccountDetails(AccountManager.get(context), accountKey, true) ?: return SingleResponse.getInstance()
val microBlog = details.newMicroBlogInstance(context = context, cls = MicroBlog::class.java)
try {
val details = AccountUtils.getAccountDetails(AccountManager.get(context), accountKey,
true) ?: throw MicroBlogException("No account")
val microBlog = details.newMicroBlogInstance(context = context, cls = MicroBlog::class.java)
var user: User? = null
if (isProfileChanged) {
val profileUpdate = ProfileUpdate()
@ -379,15 +380,15 @@ class UserProfileEditorFragment : BaseFragment(), OnSizeChangedListener, TextWat
}
if (user == null) {
// User profile unchanged
return SingleResponse.Companion.getInstance<ParcelableUser>()
return SingleResponse()
}
val profileImageSize = context.getString(R.string.profile_image_size)
val response = SingleResponse(ParcelableUserUtils.fromUser(user, accountKey,
profileImageSize = profileImageSize))
details.type, profileImageSize = profileImageSize))
response.extras.putParcelable(EXTRA_ACCOUNT, details)
return response
} catch (e: MicroBlogException) {
return SingleResponse.Companion.getInstance<ParcelableUser>(e)
return SingleResponse(e)
}
}

View File

@ -1,5 +1,6 @@
package org.mariotaku.twidere.loader
import android.annotation.SuppressLint
import android.content.Context
import org.mariotaku.library.objectcursor.ObjectCursor
import org.mariotaku.microblog.library.MicroBlog
@ -37,14 +38,16 @@ class CacheUserSearchLoader(
return super.getUsers(twitter, details)
}
override fun processUsersData(list: MutableList<ParcelableUser>) {
override fun processUsersData(details: AccountDetails, list: MutableList<ParcelableUser>) {
if (query.isEmpty() || !fromCache) return
val queryEscaped = query.replace("_", "^_")
val nicknameKeys = Utils.getMatchedNicknameKeys(query, userColorNameManager)
val selection = Expression.or(Expression.likeRaw(Columns.Column(CachedUsers.SCREEN_NAME), "?||'%'", "^"),
Expression.likeRaw(Columns.Column(CachedUsers.NAME), "?||'%'", "^"),
Expression.inArgs(Columns.Column(CachedUsers.USER_KEY), nicknameKeys.size))
val selectionArgs = arrayOf(queryEscaped, queryEscaped, *nicknameKeys)
val selection = Expression.and(Expression.equalsArgs(Columns.Column(CachedUsers.USER_TYPE)),
Expression.or(Expression.likeRaw(Columns.Column(CachedUsers.SCREEN_NAME), "?||'%'", "^"),
Expression.likeRaw(Columns.Column(CachedUsers.NAME), "?||'%'", "^"),
Expression.inArgs(Columns.Column(CachedUsers.USER_KEY), nicknameKeys.size)))
val selectionArgs = arrayOf(details.type, queryEscaped, queryEscaped, *nicknameKeys)
@SuppressLint("Recycle")
val c = context.contentResolver.query(CachedUsers.CONTENT_URI, CachedUsers.BASIC_COLUMNS,
selection.sql, selectionArgs, null)!!
val i = ObjectCursor.indicesFrom(c, ParcelableUser::class.java)

View File

@ -90,6 +90,7 @@ abstract class MicroBlogAPIStatusesLoader(
val accountKey = accountKey ?: return ListResponse.getListInstance<ParcelableStatus>(MicroBlogException("No Account"))
val details = AccountUtils.getAccountDetails(AccountManager.get(context), accountKey, true) ?:
return ListResponse.getListInstance<ParcelableStatus>(MicroBlogException("No Account"))
val accountType = details.type
var data: MutableList<ParcelableStatus>? = data
if (data == null) {
@ -151,7 +152,8 @@ abstract class MicroBlogAPIStatusesLoader(
for (i in 0 until statuses.size) {
val status = statuses[i]
val isGap = insertGap && isGapEnabled && minIdx == i
val item = ParcelableStatusUtils.fromStatus(status, accountKey, isGap, profileImageSize)
val item = ParcelableStatusUtils.fromStatus(status, accountKey, accountType, isGap,
profileImageSize)
item.position_key = GetStatusesTask.getPositionKey(item.timestamp, item.sort_id, lastSortId,
sortDiff, i, statuses.size)
ParcelableStatusUtils.updateExtraInformation(item, details)

View File

@ -67,24 +67,24 @@ abstract class MicroBlogAPIUsersLoader(
if (hasId(user.id)) {
continue
}
val item = ParcelableUserUtils.fromUser(user, accountKey, pos.toLong(),
val item = ParcelableUserUtils.fromUser(user, accountKey, details.type, pos.toLong(),
profileImageSize = profileImageSize)
processUser(item)
processUser(details, item)
data.add(item)
pos++
}
processUsersData(data)
processUsersData(details, data)
return ListResponse.getListInstance(data)
}
protected open fun processUser(user: ParcelableUser) {
protected open fun processUser(details: AccountDetails, user: ParcelableUser) {
}
@Throws(MicroBlogException::class)
protected abstract fun getUsers(twitter: MicroBlog, details: AccountDetails): List<User>
protected open fun processUsersData(list: MutableList<ParcelableUser>) {
protected open fun processUsersData(details: AccountDetails, list: MutableList<ParcelableUser>) {
Collections.sort(data)
}
}

View File

@ -28,6 +28,7 @@ import org.mariotaku.microblog.library.twitter.model.User
import org.mariotaku.twidere.model.AccountDetails
import org.mariotaku.twidere.model.ParcelableUser
import org.mariotaku.twidere.model.UserKey
import org.mariotaku.twidere.model.util.AccountUtils
import org.mariotaku.twidere.util.DataStoreUtils
class MutesUsersLoader(
@ -49,7 +50,7 @@ class MutesUsersLoader(
return super.onLoadInBackground()
}
override fun processUser(user: ParcelableUser) {
override fun processUser(details: AccountDetails, user: ParcelableUser) {
user.is_filtered = filteredUsers?.contains(user.key) ?: false
}
}

View File

@ -156,9 +156,10 @@ class ParcelableUserLoader(
twitterUser = TwitterWrapper.tryShowUser(twitter, id, screenName, details.type)
}
}
val cachedUserValues = ContentValuesCreator.createCachedUser(twitterUser, profileImageSize)
val cachedUserValues = ContentValuesCreator.createCachedUser(twitterUser, details.type,
profileImageSize)
resolver.insert(CachedUsers.CONTENT_URI, cachedUserValues)
val user = ParcelableUserUtils.fromUser(twitterUser, accountKey,
val user = ParcelableUserUtils.fromUser(twitterUser, accountKey, details.type,
profileImageSize = profileImageSize)
ParcelableUserUtils.updateExtraInformation(user, details, userColorNameManager)
return SingleResponse(user).apply {

View File

@ -29,6 +29,7 @@ import org.mariotaku.twidere.annotation.AccountType
import org.mariotaku.twidere.model.AccountDetails
import org.mariotaku.twidere.model.ParcelableUser
import org.mariotaku.twidere.model.UserKey
import org.mariotaku.twidere.model.util.AccountUtils
import org.mariotaku.twidere.util.DataStoreUtils
class UserBlocksLoader(
@ -57,7 +58,7 @@ class UserBlocksLoader(
return super.onLoadInBackground()
}
override fun processUser(user: ParcelableUser) {
override fun processUser(details: AccountDetails, user: ParcelableUser) {
user.is_filtered = filteredUsers?.contains(user.key) ?: false
}
}

View File

@ -70,7 +70,7 @@ class UserTimelineLoader(
if (pinnedStatusIds != null) {
pinnedStatuses = try {
microBlog.lookupStatuses(pinnedStatusIds).mapIndexed { idx, status ->
val created = ParcelableStatusUtils.fromStatus(status, details.key,
val created = ParcelableStatusUtils.fromStatus(status, details.key, details.type,
profileImageSize = profileImageSize)
created.sort_id = idx.toLong()
return@mapIndexed created

View File

@ -57,8 +57,8 @@ object ParcelableActivityUtils {
return result
}
fun fromActivity(activity: Activity, accountKey: UserKey, isGap: Boolean = false,
profileImageSize: String = "normal"): ParcelableActivity {
fun fromActivity(activity: Activity, accountKey: UserKey, accountType: String,
isGap: Boolean = false, profileImageSize: String = "normal"): ParcelableActivity {
val result = ParcelableActivity()
result.account_key = accountKey
result.timestamp = activity.createdAt.time
@ -67,13 +67,20 @@ object ParcelableActivityUtils {
result.min_sort_position = activity.minSortPosition
result.max_position = activity.maxPosition
result.min_position = activity.minPosition
result.sources = ParcelableUserUtils.fromUsers(activity.sources, accountKey, profileImageSize)
result.target_users = ParcelableUserUtils.fromUsers(activity.targetUsers, accountKey, profileImageSize)
result.target_user_lists = ParcelableUserListUtils.fromUserLists(activity.targetUserLists, accountKey, profileImageSize)
result.target_statuses = ParcelableStatusUtils.fromStatuses(activity.targetStatuses, accountKey, profileImageSize)
result.target_object_statuses = ParcelableStatusUtils.fromStatuses(activity.targetObjectStatuses, accountKey, profileImageSize)
result.target_object_user_lists = ParcelableUserListUtils.fromUserLists(activity.targetObjectUserLists, accountKey, profileImageSize)
result.target_object_users = ParcelableUserUtils.fromUsers(activity.targetObjectUsers, accountKey, profileImageSize)
result.sources = ParcelableUserUtils.fromUsers(activity.sources, accountKey, accountType,
profileImageSize)
result.target_users = ParcelableUserUtils.fromUsers(activity.targetUsers, accountKey,
accountType, profileImageSize)
result.target_user_lists = ParcelableUserListUtils.fromUserLists(activity.targetUserLists,
accountKey, profileImageSize)
result.target_statuses = ParcelableStatusUtils.fromStatuses(activity.targetStatuses,
accountKey, accountType, profileImageSize)
result.target_object_statuses = ParcelableStatusUtils.fromStatuses(activity.targetObjectStatuses,
accountKey, accountType, profileImageSize)
result.target_object_user_lists = ParcelableUserListUtils.fromUserLists(activity.targetObjectUserLists,
accountKey, profileImageSize)
result.target_object_users = ParcelableUserUtils.fromUsers(activity.targetObjectUsers,
accountKey, accountType, profileImageSize)
result.has_following_source = activity.sources.fold(false) { folded, item ->
if (item.isFollowing == true) {
return@fold true

View File

@ -24,12 +24,12 @@ object ParcelableCardEntityUtils {
sISOFormat.timeZone = TimeZone.getTimeZone("UTC")
}
fun fromCardEntity(card: CardEntity?, accountKey: UserKey?): ParcelableCardEntity? {
fun fromCardEntity(card: CardEntity?, accountKey: UserKey?, accountType: String?): ParcelableCardEntity? {
if (card == null) return null
val obj = ParcelableCardEntity()
obj.name = card.name
obj.url = card.url
obj.users = ParcelableUserUtils.fromUsers(card.users, accountKey)
obj.users = ParcelableUserUtils.fromUsers(card.users, accountKey, accountType)
obj.account_key = accountKey
obj.values = from(card.bindingValues)
return obj

View File

@ -34,8 +34,8 @@ object ParcelableMessageUtils {
return result
}
fun fromEntry(accountKey: UserKey, entry: DMResponse.Entry, users: Map<String, User>,
profileImageSize: String = "normal"): ParcelableMessage? {
fun fromEntry(accountKey: UserKey, accountType: String, entry: DMResponse.Entry,
users: Map<String, User>, profileImageSize: String = "normal"): ParcelableMessage? {
when {
entry.message != null -> {
return ParcelableMessage().apply { applyMessage(accountKey, entry.message) }
@ -45,28 +45,28 @@ object ParcelableMessageUtils {
}
entry.joinConversation != null -> {
return ParcelableMessage().apply {
applyUsersEvent(accountKey, entry.joinConversation, users, MessageType.JOIN_CONVERSATION)
applyUsersEvent(accountKey, accountType, entry.joinConversation, users, MessageType.JOIN_CONVERSATION)
}
}
entry.participantsLeave != null -> {
return ParcelableMessage().apply {
applyUsersEvent(accountKey, entry.participantsLeave, users, MessageType.PARTICIPANTS_LEAVE)
applyUsersEvent(accountKey, accountType, entry.participantsLeave, users, MessageType.PARTICIPANTS_LEAVE)
}
}
entry.participantsJoin != null -> {
return ParcelableMessage().apply {
applyUsersEvent(accountKey, entry.participantsJoin, users, MessageType.PARTICIPANTS_JOIN)
applyUsersEvent(accountKey, accountType, entry.participantsJoin, users, MessageType.PARTICIPANTS_JOIN)
}
}
entry.conversationNameUpdate != null -> {
return ParcelableMessage().apply {
applyInfoUpdatedEvent(accountKey, entry.conversationNameUpdate, users,
applyInfoUpdatedEvent(accountKey, accountType, entry.conversationNameUpdate, users,
MessageType.CONVERSATION_NAME_UPDATE, profileImageSize)
}
}
entry.conversationAvatarUpdate != null -> {
return ParcelableMessage().apply {
applyInfoUpdatedEvent(accountKey, entry.conversationAvatarUpdate, users,
applyInfoUpdatedEvent(accountKey, accountType, entry.conversationAvatarUpdate, users,
MessageType.CONVERSATION_AVATAR_UPDATE, profileImageSize)
}
}
@ -101,28 +101,30 @@ object ParcelableMessageUtils {
this.is_outgoing = false
}
private fun ParcelableMessage.applyUsersEvent(accountKey: UserKey, message: Message,
users: Map<String, User>, @MessageType type: String) {
private fun ParcelableMessage.applyUsersEvent(accountKey: UserKey, accountType: String,
message: Message, users: Map<String, User>, @MessageType type: String) {
this.commonEntry(accountKey, message)
this.message_type = type
this.extras = UserArrayExtras().apply {
this.users = message.participants.mapNotNull {
val user = users[it.userId] ?: return@mapNotNull null
ParcelableUserUtils.fromUser(user, accountKey)
ParcelableUserUtils.fromUser(user, accountKey, accountType)
}.toTypedArray()
}
this.is_outgoing = false
}
private fun ParcelableMessage.applyInfoUpdatedEvent(accountKey: UserKey, message: Message,
users: Map<String, User>, @MessageType type: String, profileImageSize: String = "normal") {
private fun ParcelableMessage.applyInfoUpdatedEvent(accountKey: UserKey, accountType: String,
message: Message, users: Map<String, User>, @MessageType type: String,
profileImageSize: String = "normal") {
this.commonEntry(accountKey, message)
this.message_type = type
this.extras = ConversationInfoUpdatedExtras().apply {
this.name = message.conversationName
this.avatar = message.conversationAvatarImageHttps
this.user = users[message.byUserId]?.let {
ParcelableUserUtils.fromUser(it, accountKey, profileImageSize = profileImageSize)
ParcelableUserUtils.fromUser(it, accountKey, accountType,
profileImageSize = profileImageSize)
}
}
this.is_outgoing = false

View File

@ -26,7 +26,7 @@ object ParcelableStatusUtils {
status.retweet_id = null
}
fun fromStatus(orig: Status, accountKey: UserKey, isGap: Boolean = false,
fun fromStatus(orig: Status, accountKey: UserKey, accountType: String, isGap: Boolean = false,
profileImageSize: String = "normal"): ParcelableStatus {
val result = ParcelableStatus()
result.is_gap = isGap
@ -100,7 +100,7 @@ object ParcelableStatusUtils {
result.quoted_timestamp = quoted.createdAt.time
result.quoted_source = quoted.source
result.quoted_media = ParcelableMediaUtils.fromStatus(quoted, accountKey)
result.quoted_media = ParcelableMediaUtils.fromStatus(quoted, accountKey, accountType)
result.quoted_user_key = UserKeyUtils.fromUser(quotedUser)
result.quoted_user_name = quotedUser.name
@ -151,7 +151,7 @@ object ParcelableStatusUtils {
result.extras.display_text_range = textWithIndices.range
}
result.media = ParcelableMediaUtils.fromStatus(status, accountKey)
result.media = ParcelableMediaUtils.fromStatus(status, accountKey, accountType)
result.source = status.source
result.location = getLocation(status)
result.is_favorite = status.isFavorited
@ -163,7 +163,7 @@ object ParcelableStatusUtils {
result.is_possibly_sensitive = status.isPossiblySensitive
result.mentions = ParcelableUserMentionUtils.fromUserMentionEntities(user,
status.userMentionEntities)
result.card = ParcelableCardEntityUtils.fromCardEntity(status.card, accountKey)
result.card = ParcelableCardEntityUtils.fromCardEntity(status.card, accountKey, accountType)
result.place_full_name = getPlaceFullName(status)
result.card_name = if (result.card != null) result.card!!.name else null
result.lang = status.lang
@ -206,11 +206,11 @@ object ParcelableStatusUtils {
return UserKey(inReplyToUserId, accountKey.host)
}
fun fromStatuses(statuses: Array<Status>?, accountKey: UserKey,
profileImageSize: String = "normal"): Array<ParcelableStatus>? {
fun fromStatuses(statuses: Array<Status>?, accountKey: UserKey, accountType: String,
profileImageSize: String): Array<ParcelableStatus>? {
if (statuses == null) return null
return Array(statuses.size) { i ->
fromStatus(statuses[i], accountKey, false, profileImageSize)
fromStatus(statuses[i], accountKey, accountType, false, profileImageSize)
}
}

View File

@ -15,12 +15,11 @@ import org.mariotaku.twidere.util.UserColorNameManager
/**
* Processing ParcelableUser
*
*
* Created by mariotaku on 16/2/24.
*/
object ParcelableUserUtils {
fun fromUser(user: User, accountKey: UserKey?, position: Long = 0,
fun fromUser(user: User, accountKey: UserKey?, accountType: String?, position: Long = 0,
profileImageSize: String = "normal"): ParcelableUser {
val urlEntities = user.urlEntities
val obj = ParcelableUser()
@ -60,6 +59,7 @@ object ParcelableUserUtils {
obj.background_color = parseColor(user.profileBackgroundColor)
obj.link_color = parseColor(user.profileLinkColor)
obj.text_color = parseColor(user.profileTextColor)
obj.user_type = accountType
obj.is_cache = false
obj.is_basic = false
@ -78,8 +78,11 @@ object ParcelableUserUtils {
return obj
}
fun fromUsers(users: Array<User>?, accountKey: UserKey?, profileImageSize: String = "normal"): Array<ParcelableUser>? {
return users?.map { fromUser(it, accountKey, profileImageSize = profileImageSize) }?.toTypedArray()
fun fromUsers(users: Array<User>?, accountKey: UserKey?, accountType: String?,
profileImageSize: String = "normal"): Array<ParcelableUser>? {
return users?.map {
fromUser(it, accountKey, accountType, profileImageSize = profileImageSize)
}?.toTypedArray()
}
fun parseColor(colorString: String?): Int {
@ -99,7 +102,8 @@ object ParcelableUserUtils {
return null
}
fun updateExtraInformation(user: ParcelableUser, account: AccountDetails, manager: UserColorNameManager) {
fun updateExtraInformation(user: ParcelableUser, account: AccountDetails,
manager: UserColorNameManager) {
user.account_color = account.color
user.color = manager.getUserColor(user.key)
user.nickname = manager.getUserNickname(user.key)

View File

@ -270,7 +270,7 @@ class StreamingService : BaseService() {
return false
}
val parcelableStatus = ParcelableStatusUtils.fromStatus(status, account.key,
homeInsertGap, profileImageSize)
account.type, homeInsertGap, profileImageSize)
val currentTimeMillis = System.currentTimeMillis()
if (lastStatusTimestamps[0] >= parcelableStatus.timestamp) {
@ -312,7 +312,7 @@ class StreamingService : BaseService() {
insertGap = false
}
val curActivity = ParcelableActivityUtils.fromActivity(activity, account.key,
insertGap, profileImageSize)
account.type, insertGap, profileImageSize)
curActivity.position_key = curActivity.timestamp
var updateId = -1L
if (curActivity.action !in Activity.Action.MENTION_ACTIONS) {

View File

@ -54,7 +54,7 @@ abstract class AbsFriendshipOperationTask(
?: throw MicroBlogException("No account")
val twitter = details.newMicroBlogInstance(context, cls = MicroBlog::class.java)
val user = perform(twitter, details, params)
val parcelableUser = ParcelableUserUtils.fromUser(user, params.accountKey)
val parcelableUser = ParcelableUserUtils.fromUser(user, params.accountKey, details.type)
succeededWorker(twitter, details, params, parcelableUser)
return parcelableUser
}

View File

@ -58,11 +58,11 @@ class CreateFavoriteTask(
val result = when (details.type) {
AccountType.FANFOU -> {
ParcelableStatusUtils.fromStatus(microBlog.createFanfouFavorite(statusId), accountKey,
false)
details.type, false)
}
else -> {
ParcelableStatusUtils.fromStatus(microBlog.createFavorite(statusId), accountKey,
false)
details.type, false)
}
}
ParcelableStatusUtils.updateExtraInformation(result, details)

View File

@ -45,11 +45,11 @@ class DestroyFavoriteTask(
when (details.type) {
AccountType.FANFOU -> {
result = ParcelableStatusUtils.fromStatus(microBlog.destroyFanfouFavorite(statusId),
accountKey, false)
accountKey, details.type, false)
}
else -> {
result = ParcelableStatusUtils.fromStatus(microBlog.destroyFavorite(statusId),
accountKey, false)
accountKey, details.type, false)
}
}
val values = ContentValues()

View File

@ -36,7 +36,7 @@ class DestroyStatusTask(
var deleteStatus: Boolean = false
try {
status = ParcelableStatusUtils.fromStatus(microBlog.destroyStatus(statusId),
accountKey, false)
accountKey, details.type,false)
ParcelableStatusUtils.updateExtraInformation(status, details)
deleteStatus = true
return SingleResponse(status)

View File

@ -52,7 +52,7 @@ class RetweetStatusTask(
context, MicroBlog::class.java)
try {
val result = ParcelableStatusUtils.fromStatus(microBlog.retweetStatus(statusId),
accountKey, false)
accountKey, details.type, false)
ParcelableStatusUtils.updateExtraInformation(result, details)
Utils.setLastSeen(context, result.mentions, System.currentTimeMillis())
val values = ContentValues()

View File

@ -1,14 +1,18 @@
package org.mariotaku.twidere.task
import android.accounts.AccountManager
import android.content.Context
import android.net.Uri
import org.mariotaku.microblog.library.MicroBlog
import org.mariotaku.microblog.library.MicroBlogException
import org.mariotaku.twidere.R
import org.mariotaku.twidere.TwidereConstants.LOGTAG
import org.mariotaku.twidere.extension.model.newMicroBlogInstance
import org.mariotaku.twidere.model.ParcelableUser
import org.mariotaku.twidere.model.SingleResponse
import org.mariotaku.twidere.model.UserKey
import org.mariotaku.twidere.model.event.ProfileUpdatedEvent
import org.mariotaku.twidere.model.util.AccountUtils
import org.mariotaku.twidere.model.util.ParcelableUserUtils
import org.mariotaku.twidere.util.DebugLog
import org.mariotaku.twidere.util.MicroBlogAPIFactory
@ -40,8 +44,10 @@ open class UpdateProfileBackgroundImageTask<ResultHandler>(
override fun doLongOperation(params: Any?): SingleResponse<ParcelableUser> {
try {
val twitter = MicroBlogAPIFactory.getInstance(context, accountKey)!!
TwitterWrapper.updateProfileBackgroundImage(context, twitter, imageUri, tile,
val details = AccountUtils.getAccountDetails(AccountManager.get(context), accountKey,
true) ?: throw MicroBlogException("No account")
val microBlog = details.newMicroBlogInstance(context, MicroBlog::class.java)
TwitterWrapper.updateProfileBackgroundImage(context, microBlog, imageUri, tile,
deleteImage)
// Wait for 5 seconds, see
// https://dev.twitter.com/docs/api/1.1/post/account/update_profile_image
@ -50,8 +56,8 @@ open class UpdateProfileBackgroundImageTask<ResultHandler>(
} catch (e: InterruptedException) {
DebugLog.w(LOGTAG, tr = e)
}
val user = twitter.verifyCredentials()
return SingleResponse(ParcelableUserUtils.fromUser(user, accountKey))
val user = microBlog.verifyCredentials()
return SingleResponse(ParcelableUserUtils.fromUser(user, accountKey, details.type))
} catch (e: MicroBlogException) {
return SingleResponse(exception = e)
} catch (e: IOException) {

View File

@ -1,17 +1,20 @@
package org.mariotaku.twidere.task
import android.accounts.AccountManager
import android.content.Context
import android.net.Uri
import android.util.Log
import org.mariotaku.microblog.library.MicroBlog
import org.mariotaku.microblog.library.MicroBlogException
import org.mariotaku.twidere.R
import org.mariotaku.twidere.TwidereConstants.LOGTAG
import org.mariotaku.twidere.extension.model.newMicroBlogInstance
import org.mariotaku.twidere.model.ParcelableUser
import org.mariotaku.twidere.model.SingleResponse
import org.mariotaku.twidere.model.UserKey
import org.mariotaku.twidere.model.event.ProfileUpdatedEvent
import org.mariotaku.twidere.model.util.AccountUtils
import org.mariotaku.twidere.model.util.ParcelableUserUtils
import org.mariotaku.twidere.util.MicroBlogAPIFactory
import org.mariotaku.twidere.util.TwitterWrapper
import org.mariotaku.twidere.util.Utils
import java.io.IOException
@ -41,8 +44,10 @@ open class UpdateProfileBannerImageTask<ResultHandler>(
override fun doLongOperation(params: Any?): SingleResponse<ParcelableUser> {
try {
val twitter = MicroBlogAPIFactory.getInstance(context, accountKey)!!
TwitterWrapper.updateProfileBannerImage(context, twitter, imageUri, deleteImage)
val details = AccountUtils.getAccountDetails(AccountManager.get(context), accountKey,
true) ?: throw MicroBlogException("No account")
val microBlog = details.newMicroBlogInstance(context, MicroBlog::class.java)
TwitterWrapper.updateProfileBannerImage(context, microBlog, imageUri, deleteImage)
// Wait for 5 seconds, see
// https://dev.twitter.com/docs/api/1.1/post/account/update_profile_image
try {
@ -51,8 +56,8 @@ open class UpdateProfileBannerImageTask<ResultHandler>(
Log.w(LOGTAG, e)
}
val user = twitter.verifyCredentials()
return SingleResponse(ParcelableUserUtils.fromUser(user, accountKey,
val user = microBlog.verifyCredentials()
return SingleResponse(ParcelableUserUtils.fromUser(user, accountKey, details.type,
profileImageSize = profileImageSize))
} catch (e: MicroBlogException) {
return SingleResponse(exception = e)

View File

@ -1,17 +1,20 @@
package org.mariotaku.twidere.task
import android.accounts.AccountManager
import android.content.Context
import android.net.Uri
import android.util.Log
import org.mariotaku.microblog.library.MicroBlog
import org.mariotaku.microblog.library.MicroBlogException
import org.mariotaku.twidere.R
import org.mariotaku.twidere.TwidereConstants
import org.mariotaku.twidere.extension.model.newMicroBlogInstance
import org.mariotaku.twidere.model.ParcelableUser
import org.mariotaku.twidere.model.SingleResponse
import org.mariotaku.twidere.model.UserKey
import org.mariotaku.twidere.model.event.ProfileUpdatedEvent
import org.mariotaku.twidere.model.util.AccountUtils
import org.mariotaku.twidere.model.util.ParcelableUserUtils
import org.mariotaku.twidere.util.MicroBlogAPIFactory
import org.mariotaku.twidere.util.TwitterWrapper
import org.mariotaku.twidere.util.Utils
import java.io.IOException
@ -30,8 +33,9 @@ open class UpdateProfileImageTask<ResultHandler>(
override fun doLongOperation(params: Any?): SingleResponse<ParcelableUser> {
try {
val microBlog = MicroBlogAPIFactory.getInstance(context, accountKey)
?: throw MicroBlogException("No account")
val details = AccountUtils.getAccountDetails(AccountManager.get(context), accountKey,
true) ?: throw MicroBlogException("No account")
val microBlog = details.newMicroBlogInstance(context, MicroBlog::class.java)
TwitterWrapper.updateProfileImage(context, microBlog, imageUri, deleteImage)
// Wait for 5 seconds, see
// https://dev.twitter.com/rest/reference/post/account/update_profile_image
@ -42,7 +46,7 @@ open class UpdateProfileImageTask<ResultHandler>(
}
val user = microBlog.verifyCredentials()
return SingleResponse(ParcelableUserUtils.fromUser(user, accountKey,
return SingleResponse(ParcelableUserUtils.fromUser(user, accountKey, details.type,
profileImageSize = profileImageSize))
} catch (e: MicroBlogException) {
return SingleResponse(exception = e)

View File

@ -4,7 +4,6 @@ import android.annotation.SuppressLint
import android.content.ContentResolver
import android.content.Context
import android.support.v4.util.ArraySet
import org.mariotaku.abstask.library.AbstractTask
import org.mariotaku.ktextension.map
import org.mariotaku.ktextension.useCursor
import org.mariotaku.library.objectcursor.ObjectCursor
@ -16,24 +15,27 @@ import org.mariotaku.twidere.model.UserKey
import org.mariotaku.twidere.model.util.ParcelableRelationshipUtils
import org.mariotaku.twidere.model.util.ParcelableUserUtils
import org.mariotaku.twidere.model.util.UserKeyUtils
import org.mariotaku.twidere.provider.TwidereDataStore.CachedUsers
import org.mariotaku.twidere.provider.TwidereDataStore.CachedRelationships
import org.mariotaku.twidere.provider.TwidereDataStore.CachedUsers
import org.mariotaku.twidere.task.BaseAbstractTask
import org.mariotaku.twidere.util.content.ContentResolverUtils
/**
* Created by Mariotaku on 2017/3/17.
*/
class CacheUserRelationshipTask(
context: Context,
val accountKey: UserKey,
val accountType: String,
val users: Collection<User>
) : BaseAbstractTask<Any?, Unit, Any?>(context) {
class CacheUserRelationshipTask(context: Context, val accountKey: UserKey, val users: Collection<User>) : BaseAbstractTask<Any?, Unit, Any?>(context) {
override fun doLongOperation(param: Any?) {
cacheUserRelationships(context.contentResolver, accountKey, users)
cacheUserRelationships(context.contentResolver, accountKey, accountType, users)
}
companion object {
fun cacheUserRelationships(cr: ContentResolver, accountKey: UserKey, users: Collection<User>) {
fun cacheUserRelationships(cr: ContentResolver, accountKey: UserKey, accountType: String,
users: Collection<User>) {
val parcelableUsers = users.map { ParcelableUserUtils.fromUser(it, accountKey) }
val parcelableUsers = users.map { ParcelableUserUtils.fromUser(it, accountKey, accountType) }
val userValuesCreator = ObjectCursor.valuesCreatorFrom(ParcelableUser::class.java)
ContentResolverUtils.bulkInsert(cr, CachedUsers.CONTENT_URI, parcelableUsers.map(userValuesCreator::create))

View File

@ -28,16 +28,17 @@ import org.mariotaku.microblog.library.twitter.model.Status
import org.mariotaku.microblog.library.twitter.model.User
import org.mariotaku.twidere.R
import org.mariotaku.twidere.model.UserKey
import org.mariotaku.twidere.provider.TwidereDataStore.*
import org.mariotaku.twidere.provider.TwidereDataStore.CachedHashtags
import org.mariotaku.twidere.provider.TwidereDataStore.CachedStatuses
import org.mariotaku.twidere.util.ContentValuesCreator
import org.mariotaku.twidere.util.InternalTwitterContentUtils
import org.mariotaku.twidere.util.TwitterWrapper.TwitterListResponse
import org.mariotaku.twidere.util.content.ContentResolverUtils
import java.util.*
class CacheUsersStatusesTask(
private val context: Context,
private val accountKey: UserKey,
private val accountType: String,
private val statuses: List<Status>
) : AbstractTask<Any?, Unit?, Unit?>() {
@ -58,7 +59,8 @@ class CacheUsersStatusesTask(
val statusesValues = HashSet<ContentValues>()
val hashTagValues = HashSet<ContentValues>()
statusesValues.add(ContentValuesCreator.createStatus(status, accountKey, profileImageSize))
statusesValues.add(ContentValuesCreator.createStatus(status, accountKey, accountType,
profileImageSize))
val text = InternalTwitterContentUtils.unescapeTwitterStatusText(status.extendedText)
for (hashtag in extractor.extractHashtags(text)) {
val values = ContentValues()
@ -72,7 +74,8 @@ class CacheUsersStatusesTask(
ContentResolverUtils.bulkInsert(resolver, CachedStatuses.CONTENT_URI, statusesValues)
ContentResolverUtils.bulkInsert(resolver, CachedHashtags.CONTENT_URI, hashTagValues)
CacheUserRelationshipTask.cacheUserRelationships(resolver, accountKey, users)
CacheUserRelationshipTask.cacheUserRelationships(resolver, accountKey, accountType,
users)
idx++
}
bulkIdx += 100

View File

@ -130,8 +130,8 @@ abstract class GetActivitiesTask(
val sortDiff = firstSortId - lastSortId
for (i in activities.indices) {
val item = activities[i]
val activity = ParcelableActivityUtils.fromActivity(item, details.key, false,
profileImageSize)
val activity = ParcelableActivityUtils.fromActivity(item, details.key, details.type,
false, profileImageSize)
mediaPreloader.preloadActivity(activity)
activity.position_key = GetStatusesTask.getPositionKey(activity.timestamp,
activity.timestamp, lastSortId, sortDiff, i, activities.size)

View File

@ -109,7 +109,7 @@ abstract class GetStatusesTask(
val storeResult = storeStatus(accountKey, details, statuses, sinceId, maxId, sinceSortId,
maxSortId, loadItemLimit, false)
// TODO cache related data and preload
val cacheTask = CacheUsersStatusesTask(context, accountKey, statuses)
val cacheTask = CacheUsersStatusesTask(context, accountKey, details.type, statuses)
TaskStarter.execute(cacheTask)
errorInfoStore.remove(errorInfoKey, accountKey.id)
result.add(TwitterWrapper.StatusListResponse(accountKey, statuses))
@ -165,7 +165,8 @@ abstract class GetStatusesTask(
val creator = ObjectCursor.valuesCreatorFrom(ParcelableStatus::class.java)
for (i in 0 until statuses.size) {
val item = statuses[i]
val status = ParcelableStatusUtils.fromStatus(item, accountKey, false, profileImageSize)
val status = ParcelableStatusUtils.fromStatus(item, accountKey, details.type, false,
profileImageSize)
ParcelableStatusUtils.updateExtraInformation(status, details)
status.position_key = getPositionKey(status.timestamp, status.sort_id, lastSortId,
sortDiff, i, statuses.size)

View File

@ -301,7 +301,7 @@ class UpdateStatusTask(
}
}
result.statuses[i] = ParcelableStatusUtils.fromStatus(requestResult,
account.key, false)
account.key, account.type, false)
} catch (e: MicroBlogException) {
result.exceptions[i] = e
}

View File

@ -222,6 +222,7 @@ class GetMessagesTask(
private fun getFanfouConversations(microBlog: MicroBlog, details: AccountDetails,
param: RefreshMessagesTaskParam, index: Int): DatabaseUpdateData {
val accountKey = details.key
val accountType = details.type
val cursor = param.cursors?.get(index)
val page = cursor?.substringAfter("page:").toInt(-1)
val result = microBlog.getConversationList(Paging().apply {
@ -240,8 +241,8 @@ class GetMessagesTask(
// Sender is our self, treat as outgoing message
val message = ParcelableMessageUtils.fromMessage(accountKey, dm, dm.senderId == accountKey.id,
1.0 - (i.toDouble() / result.size))
val sender = ParcelableUserUtils.fromUser(dm.sender, accountKey)
val recipient = ParcelableUserUtils.fromUser(dm.recipient, accountKey)
val sender = ParcelableUserUtils.fromUser(dm.sender, accountKey, accountType)
val recipient = ParcelableUserUtils.fromUser(dm.recipient, accountKey, accountType)
val mc = conversations.addConversation(message.conversation_id, details, message,
setOf(sender, recipient))
mc?.request_cursor = "page:$page"
@ -392,8 +393,8 @@ class GetMessagesTask(
return@mapNotNullTo null
}
else -> {
return@mapNotNullTo ParcelableMessageUtils.fromEntry(accountKey, entry,
respUsers, profileImageSize)
return@mapNotNullTo ParcelableMessageUtils.fromEntry(accountKey, account.type,
entry, respUsers, profileImageSize)
}
}
}
@ -406,7 +407,10 @@ class GetMessagesTask(
val recentMessage = messagesMap[k]?.maxBy(ParcelableMessage::message_timestamp)
val participants = respUsers.filterKeys { userId ->
v.participants.any { it.userId == userId }
}.values.map { ParcelableUserUtils.fromUser(it, accountKey, profileImageSize = profileImageSize) }
}.values.map {
ParcelableUserUtils.fromUser(it, accountKey, account.type,
profileImageSize = profileImageSize)
}
val conversationType = when (v.type?.toUpperCase(Locale.US)) {
DMResponse.Conversation.Type.ONE_TO_ONE -> ConversationType.ONE_TO_ONE
DMResponse.Conversation.Type.GROUP_DM -> ConversationType.GROUP
@ -583,12 +587,13 @@ class GetMessagesTask(
details: AccountDetails, dm: DirectMessage, index: Int, size: Int,
outgoing: Boolean, profileImageSize: String = "normal", updateLastRead: Boolean) {
val accountKey = details.key
val accountType = details.type
val message = ParcelableMessageUtils.fromMessage(accountKey, dm, outgoing,
1.0 - (index.toDouble() / size))
messages.add(message)
val sender = ParcelableUserUtils.fromUser(dm.sender, accountKey,
val sender = ParcelableUserUtils.fromUser(dm.sender, accountKey, accountType,
profileImageSize = profileImageSize)
val recipient = ParcelableUserUtils.fromUser(dm.recipient, accountKey,
val recipient = ParcelableUserUtils.fromUser(dm.recipient, accountKey, accountType,
profileImageSize = profileImageSize)
val conversation = conversations.addConversation(message.conversation_id, details,
message, setOf(sender, recipient), updateLastRead = updateLastRead) ?: return

View File

@ -179,9 +179,9 @@ class SendMessageTask(
val conversations = hashMapOf<String, ParcelableMessageConversation>()
conversations.addLocalConversations(context, accountKey, conversationIds)
val message = ParcelableMessageUtils.fromMessage(accountKey, dm, true)
val sender = ParcelableUserUtils.fromUser(dm.sender, accountKey,
val sender = ParcelableUserUtils.fromUser(dm.sender, accountKey, details.type,
profileImageSize = profileImageSize)
val recipient = ParcelableUserUtils.fromUser(dm.recipient, accountKey,
val recipient = ParcelableUserUtils.fromUser(dm.recipient, accountKey, details.type,
profileImageSize = profileImageSize)
conversations.addConversation(message.conversation_id, details, message, setOf(sender, recipient), appendUsers = true)
return GetMessagesTask.DatabaseUpdateData(conversations.values, listOf(message))

View File

@ -33,9 +33,10 @@ import org.mariotaku.twidere.provider.TwidereDataStore.SavedSearches
object ContentValuesCreator {
fun createCachedUser(user: User, profileImageSize: String = "normal"): ContentValues {
fun createCachedUser(user: User, accountType: String, profileImageSize: String = "normal"): ContentValues {
return ObjectCursor.valuesCreatorFrom(ParcelableUser::class.java)
.create(ParcelableUserUtils.fromUser(user, null, profileImageSize = profileImageSize))
.create(ParcelableUserUtils.fromUser(user, null, accountType,
profileImageSize = profileImageSize))
}
fun createFilteredUser(status: ParcelableStatus): ContentValues {
@ -76,9 +77,11 @@ object ContentValuesCreator {
return savedSearches.map { createSavedSearch(it, accountKey) }.toTypedArray()
}
fun createStatus(orig: Status, accountKey: UserKey, profileImageSize: String): ContentValues {
fun createStatus(orig: Status, accountKey: UserKey, accountType: String,
profileImageSize: String): ContentValues {
return ObjectCursor.valuesCreatorFrom(ParcelableStatus::class.java)
.create(ParcelableStatusUtils.fromStatus(orig, accountKey, false, profileImageSize))
.create(ParcelableStatusUtils.fromStatus(orig, accountKey, accountType, false,
profileImageSize))
}
fun createActivity(activity: ParcelableActivity, details: AccountDetails): ContentValues {

View File

@ -35,6 +35,7 @@ import org.apache.commons.lang3.StringUtils
import org.mariotaku.kpreferences.get
import org.mariotaku.ktextension.useCursor
import org.mariotaku.library.objectcursor.ObjectCursor
import org.mariotaku.microblog.library.MicroBlog
import org.mariotaku.microblog.library.MicroBlogException
import org.mariotaku.microblog.library.twitter.model.Activity
import org.mariotaku.sqliteqb.library.*
@ -43,10 +44,7 @@ import org.mariotaku.sqliteqb.library.query.SQLSelectQuery
import org.mariotaku.twidere.TwidereConstants.*
import org.mariotaku.twidere.constant.IntentConstants
import org.mariotaku.twidere.constant.databaseItemLimitKey
import org.mariotaku.twidere.extension.model.getAccountKey
import org.mariotaku.twidere.extension.model.getAccountUser
import org.mariotaku.twidere.extension.model.getColor
import org.mariotaku.twidere.extension.model.isActivated
import org.mariotaku.twidere.extension.model.*
import org.mariotaku.twidere.extension.rawQuery
import org.mariotaku.twidere.model.*
import org.mariotaku.twidere.model.tab.extra.HomeTabExtras
@ -321,11 +319,8 @@ object DataStoreUtils {
return keys.toTypedArray()
}
fun getStatusesCount(context: Context,
preferences: SharedPreferences,
uri: Uri,
extraArgs: Bundle?, compare: Long,
compareColumn: String, greaterThan: Boolean,
fun getStatusesCount(context: Context, preferences: SharedPreferences, uri: Uri,
extraArgs: Bundle?, compare: Long, compareColumn: String, greaterThan: Boolean,
accountKeys: Array<UserKey>?): Int {
val keys = accountKeys ?: getActivatedAccountKeys(context)
@ -928,13 +923,15 @@ object DataStoreUtils {
fun findStatus(context: Context, accountKey: UserKey, statusId: String): ParcelableStatus {
val cached = findStatusInDatabases(context, accountKey, statusId)
if (cached != null) return cached
val twitter = MicroBlogAPIFactory.getInstance(context, accountKey) ?: throw MicroBlogException("Account does not exist")
val result = twitter.showStatus(statusId)
val details = AccountUtils.getAccountDetails(AccountManager.get(context), accountKey,
true) ?: throw MicroBlogException("No account")
val microBlog = details.newMicroBlogInstance(context, MicroBlog::class.java)
val result = microBlog.showStatus(statusId)
val where = Expression.and(Expression.equalsArgs(Statuses.ACCOUNT_KEY),
Expression.equalsArgs(Statuses.STATUS_ID)).sql
val whereArgs = arrayOf(accountKey.toString(), statusId)
val resolver = context.contentResolver
val status = ParcelableStatusUtils.fromStatus(result, accountKey, false)
val status = ParcelableStatusUtils.fromStatus(result, accountKey, details.type, false)
resolver.delete(CachedStatuses.CONTENT_URI, where, whereArgs)
resolver.insert(CachedStatuses.CONTENT_URI, ObjectCursor.valuesCreatorFrom(ParcelableStatus::class.java).create(status))
return status

View File

@ -104,7 +104,8 @@ class CardPollViewController : ContainerView.ViewController() {
if (cardResponse == null || cardResponse.name == null) {
throw IllegalStateException()
}
return@task ParcelableCardEntityUtils.fromCardEntity(cardResponse, details.key)
return@task ParcelableCardEntityUtils.fromCardEntity(cardResponse, details.key,
details.type)
}.successUi { data ->
weakThis.get()?.displayPoll(data, status)
}
@ -159,7 +160,7 @@ class CardPollViewController : ContainerView.ViewController() {
try {
val cardEntity = caps.sendPassThrough(cardDataMap).card
return ParcelableCardEntityUtils.fromCardEntity(cardEntity,
card.account_key)
card.account_key, details.type)
} catch (e: MicroBlogException) {
Log.w(LOGTAG, e)
}