From 69829e3f6893141afd39d11031330ef25e357575 Mon Sep 17 00:00:00 2001 From: Alex Baker Date: Thu, 24 Oct 2013 18:01:09 -0500 Subject: [PATCH] Remove update message service --- .../andlib/service/HttpErrorException.java | 18 - .../andlib/service/HttpRestClient.java | 246 ----------- .../service/HttpUnavailableException.java | 30 -- .../todoroo/andlib/service/RestClient.java | 22 - .../astrid/sync/SyncProviderPreferences.java | 1 - astrid/build.gradle | 1 - .../service/UpdateMessageServiceTest.java | 330 --------------- .../service/AstridDependencyInjector.java | 2 - .../astrid/service/UpdateMessageService.java | 383 ------------------ .../layout/update_message_speech_bubble.xml | 47 --- .../main/res/layout/update_message_view.xml | 43 -- astrid/src/main/res/values-ca/strings.xml | 1 - astrid/src/main/res/values-cs/strings.xml | 1 - astrid/src/main/res/values-da/strings.xml | 1 - astrid/src/main/res/values-de/strings.xml | 1 - astrid/src/main/res/values-es/strings.xml | 1 - astrid/src/main/res/values-fr/strings.xml | 1 - astrid/src/main/res/values-it/strings.xml | 1 - astrid/src/main/res/values-iw/strings.xml | 1 - astrid/src/main/res/values-ja/strings.xml | 1 - astrid/src/main/res/values-ko/strings.xml | 1 - astrid/src/main/res/values-nb/strings.xml | 1 - astrid/src/main/res/values-nl/strings.xml | 1 - astrid/src/main/res/values-pl/strings.xml | 1 - astrid/src/main/res/values-pt-rBR/strings.xml | 1 - astrid/src/main/res/values-ru/strings.xml | 1 - astrid/src/main/res/values-sv/strings.xml | 1 - astrid/src/main/res/values-th/strings.xml | 1 - astrid/src/main/res/values-tr/strings.xml | 1 - astrid/src/main/res/values-uk/strings.xml | 1 - astrid/src/main/res/values-zh-rCN/strings.xml | 1 - astrid/src/main/res/values-zh-rTW/strings.xml | 1 - astrid/src/main/res/values/strings-core.xml | 3 - 33 files changed, 1147 deletions(-) delete mode 100644 api/src/main/java/com/todoroo/andlib/service/HttpErrorException.java delete mode 100644 api/src/main/java/com/todoroo/andlib/service/HttpRestClient.java delete mode 100644 api/src/main/java/com/todoroo/andlib/service/HttpUnavailableException.java delete mode 100644 api/src/main/java/com/todoroo/andlib/service/RestClient.java delete mode 100644 astrid/src/instrumentTest/java/com/todoroo/astrid/service/UpdateMessageServiceTest.java delete mode 100644 astrid/src/main/java/com/todoroo/astrid/service/UpdateMessageService.java delete mode 100644 astrid/src/main/res/layout/update_message_speech_bubble.xml delete mode 100644 astrid/src/main/res/layout/update_message_view.xml diff --git a/api/src/main/java/com/todoroo/andlib/service/HttpErrorException.java b/api/src/main/java/com/todoroo/andlib/service/HttpErrorException.java deleted file mode 100644 index 94eeb0288..000000000 --- a/api/src/main/java/com/todoroo/andlib/service/HttpErrorException.java +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Copyright (c) 2012 Todoroo Inc - * - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.andlib.service; - -import java.io.IOException; - -public class HttpErrorException extends IOException { - - private static final long serialVersionUID = 5373340422464657279L; - - public HttpErrorException(int code, String message) { - super(String.format("%d %s", code, message)); //$NON-NLS-1$ - } - -} diff --git a/api/src/main/java/com/todoroo/andlib/service/HttpRestClient.java b/api/src/main/java/com/todoroo/andlib/service/HttpRestClient.java deleted file mode 100644 index ca2b83ac0..000000000 --- a/api/src/main/java/com/todoroo/andlib/service/HttpRestClient.java +++ /dev/null @@ -1,246 +0,0 @@ -/** - * Copyright (c) 2012 Todoroo Inc - * - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.andlib.service; - -import android.util.Log; - -import com.todoroo.andlib.utility.AndroidUtilities; - -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.HttpEntity; -import org.apache.http.HttpException; -import org.apache.http.HttpRequest; -import org.apache.http.HttpRequestInterceptor; -import org.apache.http.HttpResponse; -import org.apache.http.HttpResponseInterceptor; -import org.apache.http.HttpVersion; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.conn.params.ConnManagerPNames; -import org.apache.http.conn.params.ConnPerRouteBean; -import org.apache.http.conn.scheme.PlainSocketFactory; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.entity.HttpEntityWrapper; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.HttpConnectionParams; -import org.apache.http.params.HttpParams; -import org.apache.http.params.HttpProtocolParams; -import org.apache.http.protocol.HttpContext; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.ref.WeakReference; -import java.util.zip.GZIPInputStream; - -/** - * RestClient allows Android to consume web requests. - * - * @author Tim Su - * - */ -public class HttpRestClient implements RestClient { - - private static final int HTTP_UNAVAILABLE_END = 599; - private static final int HTTP_UNAVAILABLE_START = 500; - private static final int HTTP_OK = 200; - - private static final int TIMEOUT_MILLIS = 60000; - - private WeakReference httpClient = null; - - protected boolean debug = false; - - private int timeout = TIMEOUT_MILLIS; - - public HttpRestClient() { - DependencyInjectionService.getInstance().inject(this); - - SchemeRegistry schemeRegistry = new SchemeRegistry(); - schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); - schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); - - params = new BasicHttpParams(); - HttpConnectionParams.setConnectionTimeout(params, timeout); - HttpConnectionParams.setSoTimeout(params, timeout); - params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30); - params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30)); - params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false); - HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); - - cm = new ThreadSafeClientConnManager(params, schemeRegistry); - } - - public HttpRestClient(int timeout) { - super(); - this.timeout = timeout; - - HttpConnectionParams.setConnectionTimeout(params, timeout); - HttpConnectionParams.setSoTimeout(params, timeout); - } - - private HttpParams params; - private ThreadSafeClientConnManager cm; - - private synchronized HttpClient getClient() { - if (httpClient == null || httpClient.get() == null) { - DefaultHttpClient client = new DefaultHttpClient(cm, params); - httpClient = new WeakReference(client); - actsAsGzippable(client); - return client; - } - return httpClient.get(); - } - - protected void actsAsGzippable(DefaultHttpClient client) { - client.addRequestInterceptor(new HttpRequestInterceptor() { - @Override - public void process( - final HttpRequest request, - final HttpContext context) throws HttpException, IOException { - if (!request.containsHeader("Accept-Encoding")) { - request.addHeader("Accept-Encoding", "gzip"); - } - } - - }); - - client.addResponseInterceptor(new HttpResponseInterceptor() { - @Override - public void process( - final HttpResponse response, - final HttpContext context) throws HttpException, IOException { - HttpEntity entity = response.getEntity(); - Header ceheader = entity.getContentEncoding(); - if (ceheader != null) { - HeaderElement[] codecs = ceheader.getElements(); - for (int i = 0; i < codecs.length; i++) { - if (codecs[i].getName().equalsIgnoreCase("gzip")) { - response.setEntity( - new GzipDecompressingEntity(response.getEntity())); - return; - } - } - } - } - }); - } - - private static class GzipDecompressingEntity extends HttpEntityWrapper { - - public GzipDecompressingEntity(final HttpEntity entity) { - super(entity); - } - - @Override - public InputStream getContent() - throws IOException, IllegalStateException { - - // the wrapped entity's getContent() decides about repeatability - InputStream wrappedin = wrappedEntity.getContent(); - - return new GZIPInputStream(wrappedin); - } - - @Override - public long getContentLength() { - // length of ungzipped content is not known - return -1; - } - - } - - private String processHttpResponse(HttpResponse response) throws IOException { - int statusCode = response.getStatusLine().getStatusCode(); - if(statusCode >= HTTP_UNAVAILABLE_START && statusCode <= HTTP_UNAVAILABLE_END) { - throw new HttpUnavailableException(); - } - - HttpEntity entity = response.getEntity(); - - String body = null; - if (entity != null) { - InputStream contentStream = entity.getContent(); - try { - body = AndroidUtilities.readInputStream(contentStream); - } finally { - contentStream.close(); - } - } - - if(statusCode != HTTP_OK) { - System.out.println(body); - throw new HttpErrorException(response.getStatusLine().getStatusCode(), - response.getStatusLine().getReasonPhrase()); - } - - return body; - } - - /** - * Issue an HTTP GET for the given URL, return the response - * - * @param url url with url-encoded params - * @return response, or null if there was no response - * @throws IOException - */ - @Override - public synchronized String get(String url) throws IOException { - if(debug) { - Log.d("http-rest-client-get", url); //$NON-NLS-1$ - } - - try { - HttpGet httpGet = new HttpGet(url); - HttpResponse response = getClient().execute(httpGet); - - return processHttpResponse(response); - } catch (IOException e) { - throw e; - } catch (Exception e) { - IOException ioException = new IOException(e.getMessage()); - ioException.initCause(e); - throw ioException; - } - } - - /** - * Issue an HTTP POST for the given URL, return the response - * - * @param data - * url-encoded data - * @throws IOException - */ - @Override - public synchronized String post(String url, HttpEntity data, Header... headers) throws IOException { - if(debug) { - Log.d("http-rest-client-post", url + " | " + data); //$NON-NLS-1$ //$NON-NLS-2$ - } - - try { - HttpPost httpPost = new HttpPost(url); - httpPost.setEntity(data); - for(Header header : headers) { - httpPost.addHeader(header); - } - HttpResponse response = getClient().execute(httpPost); - - return processHttpResponse(response); - } catch (IOException e) { - throw e; - } catch (Exception e) { - IOException ioException = new IOException(e.getMessage()); - ioException.initCause(e); - throw ioException; - } - } - -} diff --git a/api/src/main/java/com/todoroo/andlib/service/HttpUnavailableException.java b/api/src/main/java/com/todoroo/andlib/service/HttpUnavailableException.java deleted file mode 100644 index 6aea1cb4c..000000000 --- a/api/src/main/java/com/todoroo/andlib/service/HttpUnavailableException.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright (c) 2012 Todoroo Inc - * - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.andlib.service; - -import java.io.IOException; - -/** - * Exception displayed when a 500 error is received on an HTTP invocation - * - * @author Tim Su - * - */ -public class HttpUnavailableException extends IOException { - - private static final long serialVersionUID = 5373340422464657279L; - - public HttpUnavailableException() { - super(); - DependencyInjectionService.getInstance().inject(this); - } - - @Override - public String getMessage() { - return "Sorry, our servers are experiencing some issues. Please try again later!"; //$NON-NLS-1$ // FIXME - } - -} diff --git a/api/src/main/java/com/todoroo/andlib/service/RestClient.java b/api/src/main/java/com/todoroo/andlib/service/RestClient.java deleted file mode 100644 index 96a00138d..000000000 --- a/api/src/main/java/com/todoroo/andlib/service/RestClient.java +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Copyright (c) 2012 Todoroo Inc - * - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.andlib.service; - -import org.apache.http.Header; -import org.apache.http.HttpEntity; - -import java.io.IOException; - -/** - * RestClient stub invokes the HTML requests as desired - * - * @author Tim Su - * - */ -public interface RestClient { - public String get(String url) throws IOException; - public String post(String url, HttpEntity data, Header... headers) throws IOException; -} diff --git a/api/src/main/java/com/todoroo/astrid/sync/SyncProviderPreferences.java b/api/src/main/java/com/todoroo/astrid/sync/SyncProviderPreferences.java index 37a4cc569..58fd5b1c4 100644 --- a/api/src/main/java/com/todoroo/astrid/sync/SyncProviderPreferences.java +++ b/api/src/main/java/com/todoroo/astrid/sync/SyncProviderPreferences.java @@ -256,7 +256,6 @@ abstract public class SyncProviderPreferences extends TodorooPreferenceActivity exceptionsToDisplayMessages = new HashMap(); exceptionsToDisplayMessages.put("java.net.ConnectionException", R.string.sync_error_offline); exceptionsToDisplayMessages.put("java.net.UnknownHostException", R.string.sync_error_offline); - exceptionsToDisplayMessages.put("org.apache.http.conn.HttpHostConnectionException", R.string.sync_error_offline); } return exceptionsToDisplayMessages; } diff --git a/astrid/build.gradle b/astrid/build.gradle index 203206963..68973b177 100644 --- a/astrid/build.gradle +++ b/astrid/build.gradle @@ -71,7 +71,6 @@ dependencies { compile group: 'com.google.guava', name: 'guava', version: '11.0.1', transitive: false compile group: 'com.google.code.gson', name: 'gson', version: '1.7.1', transitive: false - compile group: 'org.apache.httpcomponents', name: 'httpmime', version: '4.1.1', transitive: false compile group: 'com.google.api-client', name: 'google-api-client', version: '1.6.0-beta', transitive: false compile group: 'com.google.api-client', name: 'google-api-client-extensions', version: '1.6.0-beta', transitive: false compile group: 'com.google.api-client', name: 'google-api-client-extensions-android2', version: '1.6.0-beta', transitive: false diff --git a/astrid/src/instrumentTest/java/com/todoroo/astrid/service/UpdateMessageServiceTest.java b/astrid/src/instrumentTest/java/com/todoroo/astrid/service/UpdateMessageServiceTest.java deleted file mode 100644 index 1c81f2841..000000000 --- a/astrid/src/instrumentTest/java/com/todoroo/astrid/service/UpdateMessageServiceTest.java +++ /dev/null @@ -1,330 +0,0 @@ -/** - * Copyright (c) 2012 Todoroo Inc - * - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.astrid.service; - -import com.todoroo.andlib.service.Autowired; -import com.todoroo.andlib.service.RestClient; -import com.todoroo.astrid.dao.StoreObjectDao; -import com.todoroo.astrid.dao.StoreObjectDao.StoreObjectCriteria; -import com.todoroo.astrid.gtasks.GtasksPreferenceService; -import com.todoroo.astrid.test.DatabaseTestCase; -import com.todoroo.astrid.utility.Constants; - -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.json.JSONArray; - -import java.io.IOException; - -public class UpdateMessageServiceTest extends DatabaseTestCase { - - @Autowired private StoreObjectDao storeObjectDao; - @Autowired private GtasksPreferenceService gtasksPreferenceService; - - public void testNoUpdates() { - clearLatestUpdates(); - - new TestUpdateMessageService() { - - @Override - void verifyMessage(MessageTuple message) { - fail("should not have displayed updates"); - } - - @Override - String getUpdates(String url) throws IOException { - assertTrue(url, url.contains("language=eng")); - assertTrue(url.contains("version=")); - return ""; - } - }.processUpdates(); - } - - public void testIOException() { - clearLatestUpdates(); - - new TestUpdateMessageService() { - - @Override - void verifyMessage(MessageTuple message) { - fail("should not have displayed updates"); - } - - @Override - String getUpdates(String url) throws IOException { - throw new IOException("yayaya"); - } - }.processUpdates(); - } - - public void testNewUpdate() { - clearLatestUpdates(); - - new TestUpdateMessageService() { - - @Override - void verifyMessage(MessageTuple message) { - assertTrue(message.message.toString().contains("yo")); - } - - @Override - String getUpdates(String url) throws IOException { - return "[{message:'yo'}]"; - } - }.processUpdates(); - } - - public void testMultipleUpdates() { - clearLatestUpdates(); - - new TestUpdateMessageService() { - - @Override - void verifyMessage(MessageTuple message) { - assertTrue(message.message.toString().contains("yo")); - assertFalse(message.message.toString().contains("cat")); // We only process the first update now - } - - @Override - String getUpdates(String url) throws IOException { - return "[{message:'yo'},{message:'cat'}]"; - } - }.processUpdates(); - } - - public void testExistingUpdate() { - clearLatestUpdates(); - - new TestUpdateMessageService() { - - @Override - void verifyMessage(MessageTuple message) { - assertTrue(message.message.toString().contains("yo")); - } - - @Override - String getUpdates(String url) throws IOException { - return "[{message:'yo'}]"; - } - }.processUpdates(); - - new TestUpdateMessageService() { - - @Override - void verifyMessage(MessageTuple message) { - fail("should have not displayed again"); - } - - @Override - protected void onEmptyMessage() { - // expected - } - - @Override - String getUpdates(String url) throws IOException { - return "[{message:'yo'}]"; - } - }.processUpdates(); - } - - public void testUpdateWithDate() { - clearLatestUpdates(); - - new TestUpdateMessageService() { - - @Override - void verifyMessage(MessageTuple message) { - assertTrue(message.message.toString().contains("yo")); - } - - @Override - String getUpdates(String url) throws IOException { - return "[{message:'yo',date:'date'}]"; - } - }.processUpdates(); - } - - public void testUpdateWithInternalPluginOn() { - clearLatestUpdates(); - gtasksPreferenceService.setToken("gtasks"); - - new TestUpdateMessageService() { - - @Override - void verifyMessage(MessageTuple message) { - assertTrue(message.message.toString().contains("gtasks man")); - } - - @Override - String getUpdates(String url) throws IOException { - return "[{message:'gtasks man',plugin:'gtasks'}]"; - } - }.processUpdates(); - gtasksPreferenceService.setToken(null); - } - - public void testUpdateWithInternalPluginOff() { - clearLatestUpdates(); - gtasksPreferenceService.setToken(null); - - new TestUpdateMessageService() { - - @Override - void verifyMessage(MessageTuple message) { - fail("displayed update"); - } - - @Override - protected void onEmptyMessage() { - // expected - } - - @Override - String getUpdates(String url) throws IOException { - return "[{message:'gtasks man',plugin:'gtasks'}]"; - } - }.processUpdates(); - } - - public void testUpdateWithExternalPluginOn() { - clearLatestUpdates(); - - new TestUpdateMessageService() { - - @Override - void verifyMessage(MessageTuple message) { - assertTrue(message.message.toString().contains("astrid man")); - } - - @Override - String getUpdates(String url) throws IOException { - return "[{message:'astrid man',plugin:'" + Constants.PACKAGE + "'}]"; - } - }.processUpdates(); - } - - public void testUpdateWithExternalPluginOff() { - clearLatestUpdates(); - - new TestUpdateMessageService() { - - @Override - void verifyMessage(MessageTuple message) { - fail("displayed update"); - } - - @Override - protected void onEmptyMessage() { - // expected - } - - @Override - String getUpdates(String url) throws IOException { - return "[{message:'astrid man',plugin:'com.bogus.package'}]"; - } - }.processUpdates(); - } - - public void testUpdateWithScreenFlow() { - clearLatestUpdates(); - - new TestUpdateMessageService() { - - @Override - void verifyMessage(MessageTuple message) { - assertTrue(message.linkText.size() > 0); - assertTrue(message.click.size() > 0); - } - - @Override - String getUpdates(String url) throws IOException { - return "[{type:'screen',screens:['com.todoroo.astrid.activity.TaskListActivity'],message:'Screens'}]"; - } - }; - } - - public void testUpdateWithPrefs() { - clearLatestUpdates(); - - new TestUpdateMessageService() { - - @Override - void verifyMessage(MessageTuple message) { - assertTrue(message.linkText.size() > 0); - assertTrue(message.click.size() > 0); - } - - @Override - String getUpdates(String url) throws IOException { - return "[{type:'pref',prefs:[{key:'key', type:'bool', title:'my pref'}],message:'Prefs'}]"; - } - }; - } - - public void testUpdateWithLinks() { - clearLatestUpdates(); - - new TestUpdateMessageService() { - @Override - void verifyMessage(MessageTuple message) { - assertEquals("Message", message.message); - assertEquals("link", message.linkText.get(0)); - assertNotNull(message.click.get(0)); - } - - @Override - String getUpdates(String url) throws IOException { - return "[{message:'Message', links:[{title:'link',url:'http://astrid.com'}]]"; - } - }; - } - - // --- - - private void clearLatestUpdates() { - storeObjectDao.deleteWhere(StoreObjectCriteria.byType(UpdateMessageService.UpdateMessage.TYPE)); - } - - /** helper test class */ - abstract public class TestUpdateMessageService extends UpdateMessageService { - - public TestUpdateMessageService() { - super(null); - restClient = new RestClient() { - - public String post(String url, HttpEntity data, Header... headers) throws IOException { - return null; - } - - public String get(String url) throws IOException { - return getUpdates(url); - } - }; - } - - abstract void verifyMessage(MessageTuple message); - - abstract String getUpdates(String url) throws IOException; - - protected void onEmptyMessage() { - fail("empty update message"); - } - - @Override - protected MessageTuple buildUpdateMessage(JSONArray updates) { - MessageTuple message = super.buildUpdateMessage(updates); - if(message == null || message.message.length() == 0) - onEmptyMessage(); - return message; - } - - @Override - protected void displayUpdateDialog(MessageTuple tuple) { - verifyMessage(tuple); - } - } - -} diff --git a/astrid/src/main/java/com/todoroo/astrid/service/AstridDependencyInjector.java b/astrid/src/main/java/com/todoroo/astrid/service/AstridDependencyInjector.java index aa938377c..f7cb12687 100644 --- a/astrid/src/main/java/com/todoroo/astrid/service/AstridDependencyInjector.java +++ b/astrid/src/main/java/com/todoroo/astrid/service/AstridDependencyInjector.java @@ -9,7 +9,6 @@ import com.todoroo.andlib.service.AbstractDependencyInjector; import com.todoroo.andlib.service.DependencyInjectionService; import com.todoroo.andlib.service.ExceptionService.AndroidLogReporter; import com.todoroo.andlib.service.ExceptionService.ErrorReporter; -import com.todoroo.andlib.service.HttpRestClient; import com.todoroo.astrid.dao.Database; import com.todoroo.astrid.dao.MetadataDao; import com.todoroo.astrid.dao.StoreObjectDao; @@ -56,7 +55,6 @@ public class AstridDependencyInjector extends AbstractDependencyInjector { // com.todoroo.android.service injectables.put("applicationName", "astrid"); - injectables.put("restClient", HttpRestClient.class); // com.todoroo.astrid.dao injectables.put("database", Database.class); diff --git a/astrid/src/main/java/com/todoroo/astrid/service/UpdateMessageService.java b/astrid/src/main/java/com/todoroo/astrid/service/UpdateMessageService.java deleted file mode 100644 index 24c843a8f..000000000 --- a/astrid/src/main/java/com/todoroo/astrid/service/UpdateMessageService.java +++ /dev/null @@ -1,383 +0,0 @@ -/** - * Copyright (c) 2012 Todoroo Inc - * - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.astrid.service; - -import android.app.Activity; -import android.app.Dialog; -import android.content.Intent; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.content.pm.PackageManager.NameNotFoundException; -import android.graphics.Color; -import android.net.Uri; -import android.text.TextUtils; -import android.util.DisplayMetrics; -import android.util.TypedValue; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.WindowManager.BadTokenException; -import android.webkit.WebView; -import android.widget.Button; -import android.widget.LinearLayout; -import android.widget.LinearLayout.LayoutParams; - -import com.todoroo.andlib.data.Property.StringProperty; -import com.todoroo.andlib.data.TodorooCursor; -import com.todoroo.andlib.service.Autowired; -import com.todoroo.andlib.service.ContextManager; -import com.todoroo.andlib.service.DependencyInjectionService; -import com.todoroo.andlib.service.RestClient; -import com.todoroo.andlib.sql.Query; -import com.todoroo.andlib.utility.AndroidUtilities; -import com.todoroo.astrid.dao.StoreObjectDao; -import com.todoroo.astrid.dao.StoreObjectDao.StoreObjectCriteria; -import com.todoroo.astrid.data.StoreObject; -import com.todoroo.astrid.gtasks.GtasksPreferenceService; -import com.todoroo.astrid.utility.Constants; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.tasks.R; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -/** - * Notifies users when there are server updates - * - * @author Tim Su - * - */ -public class UpdateMessageService { - - private static final String URL = "http://blog.astrid.com/updates"; - - private static final String PLUGIN_GTASKS = "gtasks"; - - @Autowired protected RestClient restClient; - @Autowired private GtasksPreferenceService gtasksPreferenceService; - @Autowired private AddOnService addOnService; - @Autowired private StoreObjectDao storeObjectDao; - - private final Activity activity; - - public UpdateMessageService(Activity activity) { - this.activity = activity; - DependencyInjectionService.getInstance().inject(this); - } - - public void processUpdates() { - JSONArray updates = checkForUpdates(); - - if(updates == null || updates.length() == 0) { - return; - } - - MessageTuple message = buildUpdateMessage(updates); - if(message == null || message.message.length() == 0) { - return; - } - - displayUpdateDialog(message); - } - - public static class MessageTuple { - public String message = null; - public List linkText = new ArrayList(); - public List click = new ArrayList(); - } - - private static interface DialogShower { - void showDialog(Activity activity); - } - - private void tryShowDialog(DialogShower ds) { - try { - ds.showDialog(activity); - } catch (BadTokenException bt) { - try { - Activity current = (Activity) ContextManager.getContext(); - ds.showDialog(current); - } catch (ClassCastException c) { - // Oh well, context wasn't an activity - } catch (BadTokenException bt2) { - // Oh well, activity isn't running - } - } - } - - protected void displayUpdateDialog(final MessageTuple message) { - if(activity == null) { - return; - } - - if (message.linkText.size() > 0) { - final DialogShower ds = new DialogShower() { - @Override - public void showDialog(Activity a) { - try { - final Dialog d = new Dialog(activity, R.style.ReminderDialog); - d.setContentView(R.layout.update_message_view); - - // TODO: Make HTML message - WebView messageView = (WebView) d.findViewById(R.id.reminder_message); - String html = "" + message.message + ""; - messageView.loadDataWithBaseURL("file:///android_asset/", html, "text/html", "utf-8", null); - messageView.setBackgroundColor(0); - d.findViewById(R.id.dismiss).setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - d.dismiss(); - } - }); - - - LinearLayout root = (LinearLayout) d.findViewById(R.id.reminder_root); - DisplayMetrics metrics = activity.getResources().getDisplayMetrics(); - TypedValue themeColor = new TypedValue(); - activity.getTheme().resolveAttribute(R.attr.asThemeTextColor, themeColor, false); - int color = activity.getResources().getColor(themeColor.data); - for (int i = 0; i < message.linkText.size(); i++) { - Button linkButton = new Button(activity); - linkButton.setText(message.linkText.get(i)); - final OnClickListener click = message.click.get(i); - linkButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - click.onClick(v); - d.dismiss(); - } - }); - LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, (int) (metrics.density * 35)); - params.leftMargin = params.rightMargin = (int) (metrics.density * 5); - params.bottomMargin = (int) (metrics.density * 10); - linkButton.setTextColor(Color.WHITE); - linkButton.setTextSize(20); - linkButton.setBackgroundColor(color); - linkButton.setLayoutParams(params); - linkButton.setPadding(0, 0, 0, 0); - - root.addView(linkButton); - } - - d.show(); - } catch (Exception e) { - // This should never ever crash - } - } - }; - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - tryShowDialog(ds); - } - }); - } - - } - - protected MessageTuple buildUpdateMessage(JSONArray updates) { - for(int i = 0; i < updates.length(); i++) { - JSONObject update; - try { - update = updates.getJSONObject(i); - } catch (JSONException e) { - continue; - } - - String date = update.optString("date", null); - String message = update.optString("message", null); - String plugin = update.optString("plugin", null); - String notPlugin = update.optString("notplugin", null); - - if(message == null) { - continue; - } - if(plugin != null) { - if(!pluginConditionMatches(plugin)) { - continue; - } - } - if(notPlugin != null) { - if(pluginConditionMatches(notPlugin)) { - continue; - } - } - - MessageTuple toReturn = new MessageTuple(); - toReturn.message = message; - String type = update.optString("type", null); - if ("screen".equals(type) || "pref".equals(type)) { - String linkText = update.optString("link"); - OnClickListener click = getClickListenerForUpdate(update, type); - if (click == null) { - continue; - } - toReturn.linkText.add(linkText); - toReturn.click.add(click); - } else { - JSONArray links = update.optJSONArray("links"); - if (links != null) { - for (int j = 0; j < links.length(); j++) { - JSONObject link = links.optJSONObject(j); - if (link == null) { - continue; - } - String linkText = link.optString("title"); - if (TextUtils.isEmpty(linkText)) { - continue; - } - - final String url = link.optString("url"); - OnClickListener click = new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); - activity.startActivity(intent); - } - }; - - toReturn.linkText.add(linkText); - toReturn.click.add(click); - } - } - } - - if(messageAlreadySeen(date, message)) { - continue; - } - return toReturn; - } - return null; - } - - private OnClickListener getClickListenerForUpdate(JSONObject update, String type) { - if ("pref".equals(type)) { - try { - if (!update.has("action_list")) { - return null; - } - JSONArray prefSpec = update.getJSONArray("action_list"); - if (prefSpec.length() == 0) { - return null; - } - final String prefArray = prefSpec.toString(); - return new View.OnClickListener() { - @Override - public void onClick(View b) { - Intent prefScreen = new Intent(activity, UpdateMessagePreference.class); - prefScreen.putExtra(UpdateMessagePreference.TOKEN_PREFS_ARRAY, prefArray); - activity.startActivityForResult(prefScreen, 0); - } - }; - } catch (JSONException e) { - return null; - } - } else if ("screen".equals(type)) { - try { - if (!update.has("action_list")) { - return null; - } - JSONArray screens = update.getJSONArray("action_list"); - if (screens.length() == 0) { - return null; - } - final ArrayList screenList = new ArrayList(); - for (int i = 0; i < screens.length(); i++) { - String screen = screens.getString(i).trim(); - if (!TextUtils.isEmpty(screen)) { - screenList.add(screen); - } - } - return new View.OnClickListener() { - @Override - public void onClick(View v) { - Intent screenFlow = new Intent(activity, UpdateScreenFlow.class); - screenFlow.putStringArrayListExtra(UpdateScreenFlow.TOKEN_SCREENS, screenList); - activity.startActivity(screenFlow); - } - }; - } catch (JSONException e) { - return null; - } - } - return null; - } - - private boolean pluginConditionMatches(String plugin) { - // handle internal plugin specially - if(PLUGIN_GTASKS.equals(plugin)) { - return gtasksPreferenceService.isLoggedIn(); - } else { - return addOnService.isInstalled(plugin); - } - } - - private boolean messageAlreadySeen(String date, String message) { - if(date != null) { - message = date + message; - } - String hash = AndroidUtilities.md5(message); - - TodorooCursor cursor = storeObjectDao.query(Query.select(StoreObject.ID). - where(StoreObjectCriteria.byTypeAndItem(UpdateMessage.TYPE, hash))); - try { - if(cursor.getCount() > 0) { - return true; - } - } finally { - cursor.close(); - } - - StoreObject newUpdateMessage = new StoreObject(); - newUpdateMessage.setValue(StoreObject.TYPE, UpdateMessage.TYPE); - newUpdateMessage.setValue(UpdateMessage.HASH, hash); - storeObjectDao.persist(newUpdateMessage); - return false; - } - - private JSONArray checkForUpdates() { - PackageManager pm = ContextManager.getContext().getPackageManager(); - try { - PackageInfo pi = pm.getPackageInfo(Constants.PACKAGE, PackageManager.GET_META_DATA); - int versionCode = pi.versionCode; - String url = URL + "?version=" + versionCode + "&" + - "language=" + Locale.getDefault().getISO3Language() + "&" + - "market=" + Constants.MARKET_STRATEGY.strategyId() + "&" + - "actfm=0" + "&" + - "premium=1"; - String result = restClient.get(url); //$NON-NLS-1$ - if(TextUtils.isEmpty(result)) { - return null; - } - - return new JSONArray(result); - } catch (IOException e) { - return null; - } catch (NameNotFoundException e) { - return null; - } catch (JSONException e) { - return null; - } - } - - /** store object for messages a user has seen */ - static class UpdateMessage { - - /** type*/ - public static final String TYPE = "update-message"; //$NON-NLS-1$ - - /** message contents */ - public static final StringProperty HASH = new StringProperty(StoreObject.TABLE, - StoreObject.ITEM.name); - - } - - -} diff --git a/astrid/src/main/res/layout/update_message_speech_bubble.xml b/astrid/src/main/res/layout/update_message_speech_bubble.xml deleted file mode 100644 index 6c465a5d6..000000000 --- a/astrid/src/main/res/layout/update_message_speech_bubble.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - - - - - - - diff --git a/astrid/src/main/res/layout/update_message_view.xml b/astrid/src/main/res/layout/update_message_view.xml deleted file mode 100644 index 1796aa86f..000000000 --- a/astrid/src/main/res/layout/update_message_view.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - diff --git a/astrid/src/main/res/values-ca/strings.xml b/astrid/src/main/res/values-ca/strings.xml index f7ccbc98e..c5a4ad28e 100644 --- a/astrid/src/main/res/values-ca/strings.xml +++ b/astrid/src/main/res/values-ca/strings.xml @@ -168,7 +168,6 @@ Retorna la trucada a %s Retorna la trucada a %s en... Què hi ha de nou en Tasks? - Novetats de l\'Tasks Tasks: Paràmetres desactivat Aparença diff --git a/astrid/src/main/res/values-cs/strings.xml b/astrid/src/main/res/values-cs/strings.xml index 1727d29e5..a2461a72c 100644 --- a/astrid/src/main/res/values-cs/strings.xml +++ b/astrid/src/main/res/values-cs/strings.xml @@ -162,7 +162,6 @@ Zavolat %s zpět Zavolat %s zpět... Co je nového v Tasks? - Poslední \"Tasks\" novinky Tasks: Vlastnosti Vzhled Velikost seznamu úkolů diff --git a/astrid/src/main/res/values-da/strings.xml b/astrid/src/main/res/values-da/strings.xml index 11768f4cb..aeecce123 100644 --- a/astrid/src/main/res/values-da/strings.xml +++ b/astrid/src/main/res/values-da/strings.xml @@ -98,7 +98,6 @@ Noter %1$s\ncalled at %2$s Hvad er nyt i Tasks - Seneste Tasks-nyheder Tasks: Opsætning Udseende Opgavelistestørrelse diff --git a/astrid/src/main/res/values-de/strings.xml b/astrid/src/main/res/values-de/strings.xml index 7a789fe09..8e1c73970 100644 --- a/astrid/src/main/res/values-de/strings.xml +++ b/astrid/src/main/res/values-de/strings.xml @@ -197,7 +197,6 @@ Liste erstellt Einzelaufgaben: %s Was ist neu bei Tasks? - Tasks Neuigkeiten Tasks: Einstellungen deaktiviert Erscheinungsbild diff --git a/astrid/src/main/res/values-es/strings.xml b/astrid/src/main/res/values-es/strings.xml index 7c3da9386..51484a869 100644 --- a/astrid/src/main/res/values-es/strings.xml +++ b/astrid/src/main/res/values-es/strings.xml @@ -205,7 +205,6 @@ Lista creada Acciones: %s ¿Que hay de nuevo en Tasks? - Últimas Noticias de Tasks Tasks: Preferencias desactivada Apariencia diff --git a/astrid/src/main/res/values-fr/strings.xml b/astrid/src/main/res/values-fr/strings.xml index bd0cb8b7b..db4efe593 100644 --- a/astrid/src/main/res/values-fr/strings.xml +++ b/astrid/src/main/res/values-fr/strings.xml @@ -202,7 +202,6 @@ Liste créée ! Choix d\'actions: %s Quoi de neuf dans Tasks ? - Dernières nouvelles d\'Tasks Tasks : Paramètres désactivé Apparence diff --git a/astrid/src/main/res/values-it/strings.xml b/astrid/src/main/res/values-it/strings.xml index 3a9330cd4..f93f9cbdc 100644 --- a/astrid/src/main/res/values-it/strings.xml +++ b/astrid/src/main/res/values-it/strings.xml @@ -190,7 +190,6 @@ Lista creata! Azioni: %s Novità in Tasks? - Ultime Novità di Tasks Tasks: Preferenze disattivato Aspetto diff --git a/astrid/src/main/res/values-iw/strings.xml b/astrid/src/main/res/values-iw/strings.xml index 82c8acaf9..4e23a8477 100644 --- a/astrid/src/main/res/values-iw/strings.xml +++ b/astrid/src/main/res/values-iw/strings.xml @@ -199,7 +199,6 @@ רשימה נוצרה! פריטי פעולה: %s מה חדש אצל אסטריד? - חדשות Tasks אחרונות הגדרות אסטריד מופסק חזות diff --git a/astrid/src/main/res/values-ja/strings.xml b/astrid/src/main/res/values-ja/strings.xml index 21bd4d6c3..85c603fd6 100644 --- a/astrid/src/main/res/values-ja/strings.xml +++ b/astrid/src/main/res/values-ja/strings.xml @@ -130,7 +130,6 @@ 無視する 無視する Tasks の変更点 - 最新のTasksニュース Tasks: 設定 外観 リストの文字サイズ diff --git a/astrid/src/main/res/values-ko/strings.xml b/astrid/src/main/res/values-ko/strings.xml index cb9b6cbf4..4c2a3ddaf 100644 --- a/astrid/src/main/res/values-ko/strings.xml +++ b/astrid/src/main/res/values-ko/strings.xml @@ -208,7 +208,6 @@ 목록을 만들었습니다! 활동 아이템: %s Tasks 의 새로운 기능 - 최신 아스트리드 뉴스 설정 비활성화됨 보기 설정 diff --git a/astrid/src/main/res/values-nb/strings.xml b/astrid/src/main/res/values-nb/strings.xml index ae2622b40..279cb4d6a 100644 --- a/astrid/src/main/res/values-nb/strings.xml +++ b/astrid/src/main/res/values-nb/strings.xml @@ -91,7 +91,6 @@ Notater %1$s\ncalled at %2$s Hva er nytt i Tasks? - Siste nytt om Tasks Tasks: Innstillinger Utseende Tekststørrelse for oppgavelista diff --git a/astrid/src/main/res/values-nl/strings.xml b/astrid/src/main/res/values-nl/strings.xml index a1a434dd7..d36e6737f 100644 --- a/astrid/src/main/res/values-nl/strings.xml +++ b/astrid/src/main/res/values-nl/strings.xml @@ -203,7 +203,6 @@ Lijst gemaakt! Actie-items: %s Nieuw in Tasks - Laatste Tasks nieuws Tasks: Instellingen uitgeschakeld Uiterlijk diff --git a/astrid/src/main/res/values-pl/strings.xml b/astrid/src/main/res/values-pl/strings.xml index 89f0f038c..f09b92dd7 100644 --- a/astrid/src/main/res/values-pl/strings.xml +++ b/astrid/src/main/res/values-pl/strings.xml @@ -197,7 +197,6 @@ Lista utworzona! Wydarzenia aktywne: %s Co nowego w Tasks? - Aktualności Tasks Tasks: Właściwości niekatywny Wygląd diff --git a/astrid/src/main/res/values-pt-rBR/strings.xml b/astrid/src/main/res/values-pt-rBR/strings.xml index a375e8c0b..b6b368911 100644 --- a/astrid/src/main/res/values-pt-rBR/strings.xml +++ b/astrid/src/main/res/values-pt-rBR/strings.xml @@ -201,7 +201,6 @@ Lista criada! Itens de ação: %s O que há de novo no Tasks? - Ultimas novidades no Tasks Tasks: Configurações desativado Aparência diff --git a/astrid/src/main/res/values-ru/strings.xml b/astrid/src/main/res/values-ru/strings.xml index 2b472648d..f56ed05a8 100644 --- a/astrid/src/main/res/values-ru/strings.xml +++ b/astrid/src/main/res/values-ru/strings.xml @@ -200,7 +200,6 @@ Список создан! Пункты события: %s Что нового в Tasks? - Последние новости Tasks Tasks: Настройки выключен Интерфейс diff --git a/astrid/src/main/res/values-sv/strings.xml b/astrid/src/main/res/values-sv/strings.xml index ab52e2d64..01fcaa2b1 100644 --- a/astrid/src/main/res/values-sv/strings.xml +++ b/astrid/src/main/res/values-sv/strings.xml @@ -193,7 +193,6 @@ Listan skapades! Saker att göra: %s Vad är nytt i Tasks? - Senaste Tasks nyheter Inställningar inaktiverad Utseende diff --git a/astrid/src/main/res/values-th/strings.xml b/astrid/src/main/res/values-th/strings.xml index c8b0f529e..1a9523fc7 100644 --- a/astrid/src/main/res/values-th/strings.xml +++ b/astrid/src/main/res/values-th/strings.xml @@ -72,7 +72,6 @@ บันทึกย่อ %1$s\ncalled at %2$s มีอะไรใหม่ใน Tasks? - ข่าวล่าสุดของ Tasks รูปโฉม ขนาดฟอนต์บนหน้ารายการหลัก บันทึกจะแสดงให้เห็นตลอดเวลา diff --git a/astrid/src/main/res/values-tr/strings.xml b/astrid/src/main/res/values-tr/strings.xml index 57fd7bfba..83bca9b40 100644 --- a/astrid/src/main/res/values-tr/strings.xml +++ b/astrid/src/main/res/values-tr/strings.xml @@ -187,7 +187,6 @@ Hayır teşekkürler Liste oluşturuldu! Tasks\'te Yenilikler Neler? - En Son Tasks Haberleri Tasks: Ayarlar devre dışı Görünüm diff --git a/astrid/src/main/res/values-uk/strings.xml b/astrid/src/main/res/values-uk/strings.xml index 22c64a3df..6edfacf1b 100644 --- a/astrid/src/main/res/values-uk/strings.xml +++ b/astrid/src/main/res/values-uk/strings.xml @@ -208,7 +208,6 @@ Список створений! Список дій: %s Що нового? - Останні новини Tasks Налаштування деактивовані Інтерфейс diff --git a/astrid/src/main/res/values-zh-rCN/strings.xml b/astrid/src/main/res/values-zh-rCN/strings.xml index 893027199..f24cdef4c 100644 --- a/astrid/src/main/res/values-zh-rCN/strings.xml +++ b/astrid/src/main/res/values-zh-rCN/strings.xml @@ -172,7 +172,6 @@ 也许以后 列表已存在 清单小助理有哪些最新功能? - 清单小助理最新消息 清单小助理:设置 禁用 外观 diff --git a/astrid/src/main/res/values-zh-rTW/strings.xml b/astrid/src/main/res/values-zh-rTW/strings.xml index f810589a4..416789294 100644 --- a/astrid/src/main/res/values-zh-rTW/strings.xml +++ b/astrid/src/main/res/values-zh-rTW/strings.xml @@ -191,7 +191,6 @@ 列表建立了! 行動事項:%s Tasks 有哪些最新消息? - Tasks 最新消息 Tasks: 偏好 禁用 外觀 diff --git a/astrid/src/main/res/values/strings-core.xml b/astrid/src/main/res/values/strings-core.xml index 8449b6883..9d29d0994 100644 --- a/astrid/src/main/res/values/strings-core.xml +++ b/astrid/src/main/res/values/strings-core.xml @@ -459,9 +459,6 @@ What\'s new? - - Latest Tasks News -