From 4c41cc1af10308e1aba605ebff1d3c65b8da52bf Mon Sep 17 00:00:00 2001 From: Mariotaku Lee Date: Sun, 22 Mar 2015 12:03:46 +0800 Subject: [PATCH] improved account switching animation fixed MIUI connectivity issue --- .../java/twitter4j/http/HttpClientImpl.java | 290 +----------------- .../support/AccountsDashboardFragment.java | 32 +- .../org/mariotaku/twidere/util/Utils.java | 176 +++++------ .../twidere/util/net/OkHttpClientFactory.java | 3 - .../util/net/TwidereHostAddressResolver.java | 10 +- 5 files changed, 104 insertions(+), 407 deletions(-) diff --git a/twidere.component.twitter4j/src/main/java/twitter4j/http/HttpClientImpl.java b/twidere.component.twitter4j/src/main/java/twitter4j/http/HttpClientImpl.java index f9e850f06..7c5f2dce2 100644 --- a/twidere.component.twitter4j/src/main/java/twitter4j/http/HttpClientImpl.java +++ b/twidere.component.twitter4j/src/main/java/twitter4j/http/HttpClientImpl.java @@ -19,70 +19,19 @@ package twitter4j.http; -import java.io.BufferedInputStream; -import java.io.DataOutputStream; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.net.Authenticator; -import java.net.HttpURLConnection; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.PasswordAuthentication; -import java.net.Proxy; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLEncoder; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.security.cert.X509Certificate; import java.util.HashMap; -import java.util.List; import java.util.Map; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; - import twitter4j.TwitterException; import twitter4j.conf.ConfigurationContext; -import twitter4j.internal.logging.Logger; -import twitter4j.internal.util.InternalStringUtil; - -import static twitter4j.http.RequestMethod.POST; /** * @author Yusuke Yamamoto - yusuke at mac.com * @since Twitter4J 2.1.2 */ public class HttpClientImpl extends HttpClientBase implements HttpClient, HttpResponseCode { - private static final Logger logger = Logger.getLogger(HttpClientImpl.class); - private static final TrustManager[] TRUST_ALL_CERTS = new TrustManager[]{new TrustAllX509TrustManager()}; - - private static final SSLSocketFactory IGNORE_ERROR_SSL_FACTORY; - - static { - System.setProperty("http.keepAlive", "false"); - SSLSocketFactory factory = null; - try { - final SSLContext sc = SSLContext.getInstance("TLS"); - sc.init(null, TRUST_ALL_CERTS, new SecureRandom()); - factory = sc.getSocketFactory(); - } catch (final KeyManagementException | NoSuchAlgorithmException e) { - } - IGNORE_ERROR_SSL_FACTORY = factory; - } - - private static final HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER = new AllowAllHostnameVerifier(); - - private static final Map instanceMap = new HashMap( + private static final Map instanceMap = new HashMap<>( 1); public HttpClientImpl() { @@ -104,221 +53,7 @@ public class HttpClientImpl extends HttpClientBase implements HttpClient, HttpRe @Override public HttpResponse request(final HttpRequest req) throws TwitterException { - int retriedCount; - final int retry = CONF.getHttpRetryCount() + 1; - HttpResponse res = null; - for (retriedCount = 0; retriedCount < retry; retriedCount++) { - int responseCode = -1; - try { - HttpURLConnection con; - OutputStream os = null; - try { - con = getConnection(req.getURL()); - con.setDoInput(true); - setHeaders(req, con); - con.setRequestMethod(req.getMethod().name()); - final HttpParameter[] params = req.getParameters(); - if (req.getMethod() == POST) { - if (HttpParameter.containsFile(params)) { - String boundary = "----Twitter4J-upload" + System.currentTimeMillis(); - con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); - boundary = "--" + boundary; - con.setDoOutput(true); - os = con.getOutputStream(); - final DataOutputStream out = new DataOutputStream(os); - for (final HttpParameter param : params) { - if (param.isFile()) { - write(out, boundary + "\r\n"); - write(out, "Content-Disposition: form-data; name=\"" + param.getName() - + "\"; filename=\"" + param.getFileName() + "\"\r\n"); - write(out, "Content-Type: " + param.getContentType() + "\r\n\r\n"); - final BufferedInputStream in = new BufferedInputStream( - param.hasFileBody() ? param.getFileBody() : new FileInputStream( - param.getFile())); - int buff; - while ((buff = in.read()) != -1) { - out.write(buff); - } - write(out, "\r\n"); - in.close(); - } else { - write(out, boundary + "\r\n"); - write(out, "Content-Disposition: form-data; name=\"" + param.getName() + "\"\r\n"); - write(out, "Content-Type: text/plain; charset=UTF-8\r\n\r\n"); - logger.debug(param.getValue()); - out.write(param.getValue().getBytes("UTF-8")); - write(out, "\r\n"); - } - } - write(out, boundary + "--\r\n"); - write(out, "\r\n"); - - } else { - con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); - final String postParam = HttpParameter.encodeParameters(req.getParameters()); - logger.debug("Post Params: ", postParam); - final byte[] bytes = postParam.getBytes("UTF-8"); - con.setRequestProperty("Content-Length", Integer.toString(bytes.length)); - con.setDoOutput(true); - os = con.getOutputStream(); - os.write(bytes); - } - os.flush(); - os.close(); - } - res = new HttpResponseImpl(con, CONF); - responseCode = con.getResponseCode(); - if (logger.isDebugEnabled()) { - logger.debug("Response: "); - final Map> responseHeaders = con.getHeaderFields(); - for (final String key : responseHeaders.keySet()) { - final List values = responseHeaders.get(key); - for (final String value : values) { - if (key != null) { - logger.debug(key + ": " + value); - } else { - logger.debug(value); - } - } - } - } - if (responseCode < OK || responseCode > ACCEPTED) { - if (responseCode == ENHANCE_YOUR_CLAIM || responseCode == BAD_REQUEST - || responseCode < INTERNAL_SERVER_ERROR || retriedCount == CONF.getHttpRetryCount()) - throw new TwitterException(res.asString(), req, res); - } else { - break; - } - } finally { - try { - if (os != null) { - os.close(); - } - } catch (final IOException ignore) { - } - } - } catch (final IOException ioe) { - // connection timeout or read timeout - if (retriedCount == CONF.getHttpRetryCount()) - // throw new TwitterException(ioe.getMessage(), ioe, - // responseCode); - throw new TwitterException(ioe.getMessage(), req, res); - } catch (final NullPointerException e) { - // This exception will be thown when URL is invalid. - e.printStackTrace(); - throw new TwitterException("The URL requested is invalid.", e); - } catch (final OutOfMemoryError e) { - throw new TwitterException(e.getMessage(), e); - } - try { - if (logger.isDebugEnabled() && res != null) { - res.asString(); - } - logger.debug("Sleeping " + CONF.getHttpRetryIntervalSeconds() + " seconds until the next retry."); - Thread.sleep(CONF.getHttpRetryIntervalSeconds() * 1000); - } catch (final InterruptedException ignore) { - // nothing to do - } - } - return res; - } - - private HttpURLConnection getConnection(final String url_string) throws IOException { - - final HttpURLConnection con; - final Proxy proxy; - if (isProxyConfigured()) { - if (CONF.getHttpProxyUser() != null && !CONF.getHttpProxyUser().equals("")) { - if (logger.isDebugEnabled()) { - logger.debug("Proxy AuthUser: " + CONF.getHttpProxyUser()); - logger.debug("Proxy AuthPassword: " + InternalStringUtil.maskString(CONF.getHttpProxyPassword())); - } - Authenticator.setDefault(new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - // respond only to proxy auth requests - if (getRequestorType().equals(RequestorType.PROXY)) - return new PasswordAuthentication(CONF.getHttpProxyUser(), CONF.getHttpProxyPassword() - .toCharArray()); - else - return null; - } - }); - } - proxy = new Proxy(Proxy.Type.HTTP, InetSocketAddress.createUnresolved(CONF.getHttpProxyHost(), - CONF.getHttpProxyPort())); - if (logger.isDebugEnabled()) { - logger.debug("Opening proxied connection(" + CONF.getHttpProxyHost() + ":" + CONF.getHttpProxyPort() - + ")"); - } - } else { - proxy = Proxy.NO_PROXY; - } - final HostAddressResolver resolver = FactoryUtils.getHostAddressResolver(CONF); - final URI url_orig; - try { - url_orig = new URI(url_string); - } catch (final URISyntaxException e) { - throw new IOException("Invalid URI " + url_string); - } - final String host = url_orig.getHost(), authority = url_orig.getAuthority(); - final InetAddress[] resolved_host = resolver != null ? resolver.resolve(host) : InetAddress.getAllByName(host); - con = (HttpURLConnection) new URL(resolved_host.length > 0 ? url_string.replace("://" + host, "://" - + resolved_host[0].getHostAddress()) : url_string).openConnection(proxy); -// if (resolved_host != null && !host.equals(resolved_host)) { -// con.setRequestProperty("Host", authority); -// } - if (CONF.getHttpConnectionTimeout() > 0) { - con.setConnectTimeout(CONF.getHttpConnectionTimeout()); - } - if (CONF.getHttpReadTimeout() > 0) { - con.setReadTimeout(CONF.getHttpReadTimeout()); - } - con.setInstanceFollowRedirects(false); - if (con instanceof HttpsURLConnection && CONF.isSSLErrorIgnored()) { - ((HttpsURLConnection) con).setHostnameVerifier(ALLOW_ALL_HOSTNAME_VERIFIER); - if (IGNORE_ERROR_SSL_FACTORY != null) { - ((HttpsURLConnection) con).setSSLSocketFactory(IGNORE_ERROR_SSL_FACTORY); - } - } - return con; - } - - /** - * sets HTTP headers - * - * @param req The request - * @param connection HttpURLConnection - */ - private void setHeaders(final HttpRequest req, final HttpURLConnection connection) { - if (logger.isDebugEnabled()) { - logger.debug("Request: "); - logger.debug(req.getMethod().name() + " ", req.getURL()); - } - - String authorizationHeader; - if (req.getAuthorization() != null - && (authorizationHeader = req.getAuthorization().getAuthorizationHeader(req)) != null) { - if (logger.isDebugEnabled()) { - logger.debug("Authorization: ", InternalStringUtil.maskString(authorizationHeader)); - } - connection.addRequestProperty("Authorization", authorizationHeader); - } - final Map req_headers = req.getRequestHeaders(); - if (req_headers != null) { - for (final String key : req_headers.keySet()) { - connection.addRequestProperty(key, req.getRequestHeaders().get(key)); - logger.debug(key + ": " + req.getRequestHeaders().get(key)); - } - } - } - - public static String encode(final String str) { - try { - return URLEncoder.encode(str, "UTF-8"); - } catch (final java.io.UnsupportedEncodingException neverHappen) { - throw new AssertionError("will never happen"); - } + throw new UnsupportedOperationException(); } public static HttpClient getInstance(final HttpClientConfiguration conf) { @@ -330,25 +65,4 @@ public class HttpClientImpl extends HttpClientBase implements HttpClient, HttpRe return client; } - static class AllowAllHostnameVerifier implements HostnameVerifier { - @Override - public boolean verify(final String hostname, final SSLSession session) { - return true; - } - } - - final static class TrustAllX509TrustManager implements X509TrustManager { - @Override - public void checkClientTrusted(final X509Certificate[] chain, final String authType) { - } - - @Override - public void checkServerTrusted(final X509Certificate[] chain, final String authType) { - } - - @Override - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[]{}; - } - } } diff --git a/twidere/src/main/java/org/mariotaku/twidere/fragment/support/AccountsDashboardFragment.java b/twidere/src/main/java/org/mariotaku/twidere/fragment/support/AccountsDashboardFragment.java index 84e458240..ce6e3875a 100644 --- a/twidere/src/main/java/org/mariotaku/twidere/fragment/support/AccountsDashboardFragment.java +++ b/twidere/src/main/java/org/mariotaku/twidere/fragment/support/AccountsDashboardFragment.java @@ -419,17 +419,29 @@ public class AccountsDashboardFragment extends BaseSupportListFragment implement return mThemedContext = new ContextThemeWrapper(context, themeResource); } + private void getLocationOnScreen(View view, RectF rectF) { + final int[] location = new int[2]; + view.getLocationOnScreen(location); + rectF.set(location[0], location[1], location[0] + view.getWidth(), location[1] + view.getHeight()); + } + private void onAccountSelected(AccountProfileImageViewHolder holder, final ParcelableAccount account) { if (mSwitchAccountAnimationPlaying) return; final ImageView snapshotView = mFloatingProfileImageSnapshotView; final ShapedImageView profileImageView = mAccountProfileImageView; final ShapedImageView clickedImageView = holder.getIconView(); + + // Reset snapshot view position + snapshotView.setPivotX(0); + snapshotView.setPivotY(0); + snapshotView.setTranslationX(0); + snapshotView.setTranslationY(0); + final Matrix matrix = new Matrix(); - final Rect tempRect = new Rect(); - clickedImageView.getGlobalVisibleRect(tempRect); - final RectF sourceBounds = new RectF(tempRect); - profileImageView.getGlobalVisibleRect(tempRect); - final RectF destBounds = new RectF(tempRect); + final RectF sourceBounds = new RectF(), destBounds = new RectF(), snapshotBounds = new RectF(); + getLocationOnScreen(clickedImageView, sourceBounds); + getLocationOnScreen(profileImageView, destBounds); + getLocationOnScreen(snapshotView, snapshotBounds); final float finalScale = destBounds.width() / sourceBounds.width(); final Bitmap snapshotBitmap = TransitionUtils.createViewBitmap(clickedImageView, matrix, new RectF(0, 0, sourceBounds.width(), sourceBounds.height())); @@ -439,12 +451,10 @@ public class AccountsDashboardFragment extends BaseSupportListFragment implement snapshotView.setLayoutParams(lp); // Copied from MaterialNavigationDrawer: https://github.com/madcyph3r/AdvancedMaterialDrawer/ AnimatorSet set = new AnimatorSet(); - snapshotView.setPivotX(0); - snapshotView.setPivotY(0); - snapshotView.setX(sourceBounds.left); - snapshotView.setY(sourceBounds.top); - set.play(ObjectAnimator.ofFloat(snapshotView, View.X, sourceBounds.left, destBounds.left)) - .with(ObjectAnimator.ofFloat(snapshotView, View.Y, sourceBounds.top, destBounds.top)) + set.play(ObjectAnimator.ofFloat(snapshotView, View.TRANSLATION_X, + sourceBounds.left - snapshotBounds.left, destBounds.left - snapshotBounds.left)) + .with(ObjectAnimator.ofFloat(snapshotView, View.TRANSLATION_Y, + sourceBounds.top - snapshotBounds.top, destBounds.top - snapshotBounds.top)) .with(ObjectAnimator.ofFloat(snapshotView, View.SCALE_X, 1, finalScale)) .with(ObjectAnimator.ofFloat(snapshotView, View.SCALE_Y, 1, finalScale)) .with(ObjectAnimator.ofFloat(profileImageView, View.ALPHA, 1, 0)) 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 8bd3453cb..82c312861 100644 --- a/twidere/src/main/java/org/mariotaku/twidere/util/Utils.java +++ b/twidere/src/main/java/org/mariotaku/twidere/util/Utils.java @@ -1748,21 +1748,15 @@ public final class Utils implements Constants, TwitterConstants { return context.getResources().getInteger(R.integer.default_text_size); } - public static Twitter getDefaultTwitterInstance(final Context context, final boolean include_entities) { + public static Twitter getDefaultTwitterInstance(final Context context, final boolean includeEntities) { if (context == null) return null; - return getDefaultTwitterInstance(context, include_entities, true, true); + return getDefaultTwitterInstance(context, includeEntities, true); } public static Twitter getDefaultTwitterInstance(final Context context, final boolean includeEntities, final boolean includeRetweets) { if (context == null) return null; - return getDefaultTwitterInstance(context, includeEntities, includeRetweets, !MIUIUtils.isMIUI()); - } - - public static Twitter getDefaultTwitterInstance(final Context context, final boolean includeEntities, - final boolean includeRetweets, final boolean apacheHttp) { - if (context == null) return null; - return getTwitterInstance(context, getDefaultAccountId(context), includeEntities, includeRetweets, apacheHttp); + return getTwitterInstance(context, getDefaultAccountId(context), includeEntities, includeRetweets); } public static String getErrorMessage(final Context context, final CharSequence message) { @@ -2510,19 +2504,14 @@ public final class Utils implements Constants, TwitterConstants { public static Twitter getTwitterInstance(final Context context, final long accountId, final boolean includeEntities) { - return getTwitterInstance(context, accountId, includeEntities, true, !MIUIUtils.isMIUI()); + return getTwitterInstance(context, accountId, includeEntities, true); } - @Nullable - public static Twitter getTwitterInstance(final Context context, final long accountId, - final boolean includeEntities, final boolean includeRetweets) { - return getTwitterInstance(context, accountId, includeEntities, includeRetweets, !MIUIUtils.isMIUI()); - } @Nullable public static Twitter getTwitterInstance(final Context context, final long accountId, final boolean includeEntities, - final boolean includeRetweets, final boolean apacheHttp) { + final boolean includeRetweets) { if (context == null) return null; final TwidereApplication app = TwidereApplication.getInstance(context); final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); @@ -2532,94 +2521,85 @@ public final class Utils implements Constants, TwitterConstants { final boolean enableProxy = prefs.getBoolean(KEY_ENABLE_PROXY, false); // Here I use old consumer key/secret because it's default key for older // versions - final String where = Expression.equals(new Column(Accounts.ACCOUNT_ID), accountId).getSQL(); - final Cursor c = ContentResolverUtils.query(context.getContentResolver(), Accounts.CONTENT_URI, - Accounts.COLUMNS, where, null, null); - if (c == null) return null; - try { - if (!c.moveToFirst()) return null; - final ConfigurationBuilder cb = new ConfigurationBuilder(); - cb.setHostAddressResolverFactory(new TwidereHostResolverFactory(app)); - if (apacheHttp) { - cb.setHttpClientFactory(new OkHttpClientFactory(context)); - } - cb.setHttpConnectionTimeout(connection_timeout); - cb.setGZIPEnabled(enableGzip); - cb.setIgnoreSSLError(ignoreSslError); - cb.setIncludeCards(true); - cb.setCardsPlatform("Android-12"); + final ParcelableCredentials credentials = ParcelableCredentials.getCredentials(context, accountId); + if (credentials == null) return null; + final ConfigurationBuilder cb = new ConfigurationBuilder(); + cb.setHostAddressResolverFactory(new TwidereHostResolverFactory(app)); + cb.setHttpClientFactory(new OkHttpClientFactory(context)); + cb.setHttpConnectionTimeout(connection_timeout); + cb.setGZIPEnabled(enableGzip); + cb.setIgnoreSSLError(ignoreSslError); + cb.setIncludeCards(true); + cb.setCardsPlatform("Android-12"); // cb.setModelVersion(7); - if (enableProxy) { - final String proxy_host = prefs.getString(KEY_PROXY_HOST, null); - final int proxy_port = ParseUtils.parseInt(prefs.getString(KEY_PROXY_PORT, "-1")); - if (!isEmpty(proxy_host) && proxy_port > 0) { - cb.setHttpProxyHost(proxy_host); - cb.setHttpProxyPort(proxy_port); - } + if (enableProxy) { + final String proxy_host = prefs.getString(KEY_PROXY_HOST, null); + final int proxy_port = ParseUtils.parseInt(prefs.getString(KEY_PROXY_PORT, "-1")); + if (!isEmpty(proxy_host) && proxy_port > 0) { + cb.setHttpProxyHost(proxy_host); + cb.setHttpProxyPort(proxy_port); } - final String prefConsumerKey = prefs.getString(KEY_CONSUMER_KEY, TWITTER_CONSUMER_KEY); - final String prefConsumerSecret = prefs.getString(KEY_CONSUMER_SECRET, TWITTER_CONSUMER_SECRET); - final String apiUrlFormat = c.getString(c.getColumnIndex(Accounts.API_URL_FORMAT)); - final String consumerKey = trim(c.getString(c.getColumnIndex(Accounts.CONSUMER_KEY))); - final String consumerSecret = trim(c.getString(c.getColumnIndex(Accounts.CONSUMER_SECRET))); - final boolean sameOAuthSigningUrl = c.getInt(c.getColumnIndex(Accounts.SAME_OAUTH_SIGNING_URL)) == 1; - final boolean noVersionSuffix = c.getInt(c.getColumnIndex(Accounts.NO_VERSION_SUFFIX)) == 1; - if (!isEmpty(apiUrlFormat)) { - final String versionSuffix = noVersionSuffix ? null : "/1.1/"; - cb.setRestBaseURL(getApiUrl(apiUrlFormat, "api", versionSuffix)); - cb.setOAuthBaseURL(getApiUrl(apiUrlFormat, "api", "/oauth/")); - cb.setUploadBaseURL(getApiUrl(apiUrlFormat, "upload", versionSuffix)); - if (!sameOAuthSigningUrl) { - cb.setSigningRestBaseURL(DEFAULT_SIGNING_REST_BASE_URL); - cb.setSigningOAuthBaseURL(DEFAULT_SIGNING_OAUTH_BASE_URL); - cb.setSigningUploadBaseURL(DEFAULT_SIGNING_UPLOAD_BASE_URL); - } - } - if (TwitterContentUtils.isOfficialKey(context, consumerKey, consumerSecret)) { - setMockOfficialUserAgent(context, cb); - } else { - setUserAgent(context, cb); + } + final String prefConsumerKey = prefs.getString(KEY_CONSUMER_KEY, TWITTER_CONSUMER_KEY); + final String prefConsumerSecret = prefs.getString(KEY_CONSUMER_SECRET, TWITTER_CONSUMER_SECRET); + final String apiUrlFormat = credentials.api_url_format; + final String consumerKey = trim(credentials.consumer_key); + final String consumerSecret = trim(credentials.consumer_secret); + final boolean sameOAuthSigningUrl = credentials.same_oauth_signing_url; + final boolean noVersionSuffix = credentials.no_version_suffix; + if (!isEmpty(apiUrlFormat)) { + final String versionSuffix = noVersionSuffix ? null : "/1.1/"; + cb.setRestBaseURL(getApiUrl(apiUrlFormat, "api", versionSuffix)); + cb.setOAuthBaseURL(getApiUrl(apiUrlFormat, "api", "/oauth/")); + cb.setUploadBaseURL(getApiUrl(apiUrlFormat, "upload", versionSuffix)); + if (!sameOAuthSigningUrl) { + cb.setSigningRestBaseURL(DEFAULT_SIGNING_REST_BASE_URL); + cb.setSigningOAuthBaseURL(DEFAULT_SIGNING_OAUTH_BASE_URL); + cb.setSigningUploadBaseURL(DEFAULT_SIGNING_UPLOAD_BASE_URL); } + } + if (TwitterContentUtils.isOfficialKey(context, consumerKey, consumerSecret)) { + setMockOfficialUserAgent(context, cb); + } else { + setUserAgent(context, cb); + } - cb.setIncludeEntitiesEnabled(includeEntities); - cb.setIncludeRTsEnabled(includeRetweets); - cb.setIncludeReplyCountEnabled(true); - cb.setIncludeDescendentReplyCountEnabled(true); - switch (c.getInt(c.getColumnIndexOrThrow(Accounts.AUTH_TYPE))) { - case Accounts.AUTH_TYPE_OAUTH: - case Accounts.AUTH_TYPE_XAUTH: { - if (!isEmpty(consumerKey) && !isEmpty(consumerSecret)) { - cb.setOAuthConsumerKey(consumerKey); - cb.setOAuthConsumerSecret(consumerSecret); - } else if (!isEmpty(prefConsumerKey) && !isEmpty(prefConsumerSecret)) { - cb.setOAuthConsumerKey(prefConsumerKey); - cb.setOAuthConsumerSecret(prefConsumerSecret); - } else { - cb.setOAuthConsumerKey(TWITTER_CONSUMER_KEY); - cb.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET); - } - final String token = c.getString(c.getColumnIndexOrThrow(Accounts.OAUTH_TOKEN)); - final String tokenSecret = c.getString(c.getColumnIndexOrThrow(Accounts.OAUTH_TOKEN_SECRET)); - if (isEmpty(token) || isEmpty(tokenSecret)) return null; - return new TwitterFactory(cb.build()).getInstance(new AccessToken(token, tokenSecret)); - } - case Accounts.AUTH_TYPE_BASIC: { - final String screenName = c.getString(c.getColumnIndexOrThrow(Accounts.SCREEN_NAME)); - final String username = c.getString(c.getColumnIndexOrThrow(Accounts.BASIC_AUTH_USERNAME)); - final String loginName = username != null ? username : screenName; - final String password = c.getString(c.getColumnIndexOrThrow(Accounts.BASIC_AUTH_PASSWORD)); - if (isEmpty(loginName) || isEmpty(password)) return null; - return new TwitterFactory(cb.build()).getInstance(new BasicAuthorization(loginName, password)); - } - case Accounts.AUTH_TYPE_TWIP_O_MODE: { - return new TwitterFactory(cb.build()).getInstance(new TwipOModeAuthorization()); - } - default: { - return null; + cb.setIncludeEntitiesEnabled(includeEntities); + cb.setIncludeRTsEnabled(includeRetweets); + cb.setIncludeReplyCountEnabled(true); + cb.setIncludeDescendentReplyCountEnabled(true); + switch (credentials.auth_type) { + case Accounts.AUTH_TYPE_OAUTH: + case Accounts.AUTH_TYPE_XAUTH: { + if (!isEmpty(consumerKey) && !isEmpty(consumerSecret)) { + cb.setOAuthConsumerKey(consumerKey); + cb.setOAuthConsumerSecret(consumerSecret); + } else if (!isEmpty(prefConsumerKey) && !isEmpty(prefConsumerSecret)) { + cb.setOAuthConsumerKey(prefConsumerKey); + cb.setOAuthConsumerSecret(prefConsumerSecret); + } else { + cb.setOAuthConsumerKey(TWITTER_CONSUMER_KEY); + cb.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET); } + final String token = credentials.oauth_token; + final String tokenSecret = credentials.oauth_token_secret; + if (isEmpty(token) || isEmpty(tokenSecret)) return null; + return new TwitterFactory(cb.build()).getInstance(new AccessToken(token, tokenSecret)); + } + case Accounts.AUTH_TYPE_BASIC: { + final String screenName = credentials.screen_name; + final String username = credentials.basic_auth_username; + final String loginName = username != null ? username : screenName; + final String password = credentials.basic_auth_password; + if (isEmpty(loginName) || isEmpty(password)) return null; + return new TwitterFactory(cb.build()).getInstance(new BasicAuthorization(loginName, password)); + } + case Accounts.AUTH_TYPE_TWIP_O_MODE: { + return new TwitterFactory(cb.build()).getInstance(new TwipOModeAuthorization()); + } + default: { + return null; } - } finally { - c.close(); } } diff --git a/twidere/src/main/java/org/mariotaku/twidere/util/net/OkHttpClientFactory.java b/twidere/src/main/java/org/mariotaku/twidere/util/net/OkHttpClientFactory.java index bff9a0ded..ff7d2156b 100644 --- a/twidere/src/main/java/org/mariotaku/twidere/util/net/OkHttpClientFactory.java +++ b/twidere/src/main/java/org/mariotaku/twidere/util/net/OkHttpClientFactory.java @@ -21,9 +21,6 @@ package org.mariotaku.twidere.util.net; import android.content.Context; -import org.mariotaku.twidere.app.TwidereApplication; -import org.mariotaku.twidere.util.net.OkHttpClientImpl; - import twitter4j.http.HttpClient; import twitter4j.http.HttpClientConfiguration; import twitter4j.http.HttpClientFactory; diff --git a/twidere/src/main/java/org/mariotaku/twidere/util/net/TwidereHostAddressResolver.java b/twidere/src/main/java/org/mariotaku/twidere/util/net/TwidereHostAddressResolver.java index 1fdb830cd..5d5739182 100644 --- a/twidere/src/main/java/org/mariotaku/twidere/util/net/TwidereHostAddressResolver.java +++ b/twidere/src/main/java/org/mariotaku/twidere/util/net/TwidereHostAddressResolver.java @@ -150,15 +150,9 @@ public class TwidereHostAddressResolver implements Constants, HostAddressResolve if (record instanceof ARecord) { final InetAddress ipv4Addr = ((ARecord) record).getAddress(); resolvedAddresses.add(InetAddress.getByAddress(originalHost, ipv4Addr.getAddress())); -// if (ipv4Addr.isReachable(300)) { -// hostAddr = ipv4Addr.getHostAddress(); -// } } else if (record instanceof AAAARecord) { final InetAddress ipv6Addr = ((AAAARecord) record).getAddress(); resolvedAddresses.add(InetAddress.getByAddress(originalHost, ipv6Addr.getAddress())); -// if (ipv6Addr.isReachable(300)) { -// hostAddr = ipv6Addr.getHostAddress(); -// } } } if (!resolvedAddresses.isEmpty()) { @@ -179,7 +173,9 @@ public class TwidereHostAddressResolver implements Constants, HostAddressResolve if (Utils.isDebugBuild()) { Log.w(RESOLVER_LOGTAG, "Resolve address " + host + " failed, using original host"); } - return InetAddress.getAllByName(host); + final InetAddress[] defaultAddresses = InetAddress.getAllByName(host); + mHostCache.put(host, defaultAddresses); + return defaultAddresses; } private InetAddress[] fromAddressString(String host, String address) throws UnknownHostException {