From e0db0cfee5ea1d92c861f291923960529a193148 Mon Sep 17 00:00:00 2001 From: Vavassor Date: Tue, 16 May 2017 22:19:34 -0400 Subject: [PATCH 1/9] Initial client working for MQTT push notifications. --- app/build.gradle | 4 + app/src/main/AndroidManifest.xml | 4 + .../com/keylesspalace/tusky/BaseActivity.java | 43 +-- .../keylesspalace/tusky/ComposeActivity.java | 4 +- .../tusky/fragment/NotificationsFragment.java | 3 + .../service/PushNotificationService.java | 257 ++++++++++++++++++ .../tusky/util/PushNotificationClient.java | 256 +++++++++++++++++ app/src/main/res/values/donottranslate.xml | 1 + 8 files changed, 534 insertions(+), 38 deletions(-) create mode 100644 app/src/main/java/com/keylesspalace/tusky/service/PushNotificationService.java create mode 100644 app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java diff --git a/app/build.gradle b/app/build.gradle index cf42c979..5ef9205d 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -63,6 +63,10 @@ dependencies { googleCompile 'com.google.firebase:firebase-crash:10.2.4' testCompile 'junit:junit:4.12' annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1' + compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0' + compile('org.eclipse.paho:org.eclipse.paho.android.service:1.1.1') { + exclude module: 'support-v4' + } } apply plugin: 'com.google.gms.google-services' diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 058d165b..1fd924b5 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -7,6 +7,9 @@ + + + + () { - @Override - public void onResponse(Call call, retrofit2.Response response) { - Log.d(TAG, "Enable push notifications response: " + response.message()); - } - - @Override - public void onFailure(Call call, Throwable t) { - Log.d(TAG, "Enable push notifications failed: " + t.getMessage()); - } - }); + pushNotificationClient.subscribeToTopic(); } else { // Start up the MessagingService on a repeating interval for "pull" notifications. long checkInterval = 60 * 1000 * 5; @@ -231,17 +210,7 @@ public class BaseActivity extends AppCompatActivity { protected void disablePushNotifications() { if (BuildConfig.USES_PUSH_NOTIFICATIONS) { - tuskyAPI.unregister(getBaseUrl(), getAccessToken()).enqueue(new Callback() { - @Override - public void onResponse(Call call, retrofit2.Response response) { - Log.d(TAG, "Disable push notifications response: " + response.message()); - } - - @Override - public void onFailure(Call call, Throwable t) { - Log.d(TAG, "Disable push notifications failed: " + t.getMessage()); - } - }); + pushNotificationClient.unsubscribeToTopic(); } else if (serviceAlarmIntent != null) { // Cancel the repeating call for "pull" notifications. AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); diff --git a/app/src/main/java/com/keylesspalace/tusky/ComposeActivity.java b/app/src/main/java/com/keylesspalace/tusky/ComposeActivity.java index f0089fd2..319257b4 100644 --- a/app/src/main/java/com/keylesspalace/tusky/ComposeActivity.java +++ b/app/src/main/java/com/keylesspalace/tusky/ComposeActivity.java @@ -307,7 +307,9 @@ public class ComposeActivity extends BaseActivity implements ComposeOptionsFrag if (replyVisibility != null && startingVisibility != null) { // Lowest possible visibility setting in response - if (startingVisibility.equals("private") || replyVisibility.equals("private")) { + if (startingVisibility.equals("direct") || replyVisibility.equals("direct")) { + startingVisibility = "direct"; + } else if (startingVisibility.equals("private") || replyVisibility.equals("private")) { startingVisibility = "private"; } else if (startingVisibility.equals("unlisted") || replyVisibility.equals("unlisted")) { startingVisibility = "unlisted"; diff --git a/app/src/main/java/com/keylesspalace/tusky/fragment/NotificationsFragment.java b/app/src/main/java/com/keylesspalace/tusky/fragment/NotificationsFragment.java index bef04290..234ece7f 100644 --- a/app/src/main/java/com/keylesspalace/tusky/fragment/NotificationsFragment.java +++ b/app/src/main/java/com/keylesspalace/tusky/fragment/NotificationsFragment.java @@ -233,6 +233,9 @@ public class NotificationsFragment extends SFragment implements } else { adapter.update(notifications); } + for (Notification notification : notifications) { + Log.d(TAG, "id: " + notification.id); + } if (notifications.size() == 0 && adapter.getItemCount() == 1) { adapter.setFooterState(NotificationsAdapter.FooterState.EMPTY); } else if (fromId != null) { diff --git a/app/src/main/java/com/keylesspalace/tusky/service/PushNotificationService.java b/app/src/main/java/com/keylesspalace/tusky/service/PushNotificationService.java new file mode 100644 index 00000000..7db3e124 --- /dev/null +++ b/app/src/main/java/com/keylesspalace/tusky/service/PushNotificationService.java @@ -0,0 +1,257 @@ +package com.keylesspalace.tusky.service; + +import android.app.Service; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Binder; +import android.os.IBinder; +import android.preference.PreferenceManager; +import android.support.annotation.Nullable; +import android.text.Spanned; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.keylesspalace.tusky.R; +import com.keylesspalace.tusky.entity.Notification; +import com.keylesspalace.tusky.json.SpannedTypeAdapter; +import com.keylesspalace.tusky.json.StringWithEmoji; +import com.keylesspalace.tusky.json.StringWithEmojiTypeAdapter; +import com.keylesspalace.tusky.network.MastodonAPI; +import com.keylesspalace.tusky.util.Log; +import com.keylesspalace.tusky.util.NotificationMaker; +import com.keylesspalace.tusky.util.OkHttpUtils; + +import org.eclipse.paho.android.service.MqttAndroidClient; +import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions; +import org.eclipse.paho.client.mqttv3.IMqttActionListener; +import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; +import org.eclipse.paho.client.mqttv3.IMqttToken; +import org.eclipse.paho.client.mqttv3.MqttCallbackExtended; +import org.eclipse.paho.client.mqttv3.MqttConnectOptions; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.client.mqttv3.MqttMessage; + +import java.io.IOException; +import java.util.Locale; +import java.util.UUID; + +import okhttp3.Interceptor; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class PushNotificationService extends Service { + private class LocalBinder extends Binder { + PushNotificationService getService() { + return PushNotificationService.this; + } + } + + private static final String TAG = "PushNotificationService"; + private static final String CLIENT_NAME = "TuskyMastodonClient"; + private static final String TOPIC = "tusky/notification"; + private static final int NOTIFY_ID = 666; + + private final IBinder binder = new LocalBinder(); + private MqttAndroidClient mqttAndroidClient; + private MastodonAPI mastodonApi; + + @Override + public void onCreate() { + super.onCreate(); + + // Create the MQTT client. + String clientId = String.format(Locale.getDefault(), "%s/%s/%s", CLIENT_NAME, + System.currentTimeMillis(), UUID.randomUUID().toString()); + String serverUri = getString(R.string.tusky_api_url); + mqttAndroidClient = new MqttAndroidClient(this, serverUri, clientId); + mqttAndroidClient.setCallback(new MqttCallbackExtended() { + @Override + public void connectComplete(boolean reconnect, String serverURI) { + if (reconnect) { + subscribeToTopic(); + } + } + + @Override + public void connectionLost(Throwable cause) { + onConnectionLost(); + } + + @Override + public void messageArrived(String topic, MqttMessage message) throws Exception { + onMessageReceived(new String(message.getPayload())); + } + + @Override + public void deliveryComplete(IMqttDeliveryToken token) { + // This client is read-only, so this is unused. + } + }); + + // Open the MQTT connection. + MqttConnectOptions options = new MqttConnectOptions(); + options.setAutomaticReconnect(true); + options.setCleanSession(false); + try { + mqttAndroidClient.connect(options, null, new IMqttActionListener() { + @Override + public void onSuccess(IMqttToken asyncActionToken) { + DisconnectedBufferOptions options = new DisconnectedBufferOptions(); + options.setBufferEnabled(true); + options.setBufferSize(100); + options.setPersistBuffer(false); + options.setDeleteOldestMessages(false); + mqttAndroidClient.setBufferOpts(options); + onConnectionSuccess(); + subscribeToTopic(); + } + + @Override + public void onFailure(IMqttToken asyncActionToken, Throwable exception) { + onConnectionFailure(); + } + }); + } catch (MqttException e) { + Log.e(TAG, "An exception occurred while connecting. " + e.getMessage()); + onConnectionFailure(); + } + } + + @Override + public void onDestroy() { + super.onDestroy(); + disconnect(); + } + + @Nullable + @Override + public IBinder onBind(Intent intent) { + return binder; + } + + /** Subscribe to the push notification topic. */ + public void subscribeToTopic() { + try { + mqttAndroidClient.subscribe(TOPIC, 0, null, new IMqttActionListener() { + @Override + public void onSuccess(IMqttToken asyncActionToken) { + onConnectionSuccess(); + } + + @Override + public void onFailure(IMqttToken asyncActionToken, Throwable exception) { + onConnectionFailure(); + } + }); + } catch (MqttException e) { + Log.e(TAG, "An exception occurred while subscribing." + e.getMessage()); + onConnectionFailure(); + } + } + + /** Unsubscribe from the push notification topic. */ + public void unsubscribeToTopic() { + try { + mqttAndroidClient.unsubscribe(TOPIC); + } catch (MqttException e) { + Log.e(TAG, "An exception occurred while unsubscribing." + e.getMessage()); + onConnectionFailure(); + } + } + + private void onConnectionSuccess() { + + } + + private void onConnectionFailure() { + + } + + private void onConnectionLost() { + + } + + private void onMessageReceived(String message) { + String notificationId = message; // TODO: finalize the form the messages will be received + + Log.d(TAG, "Notification received: " + notificationId); + + SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences( + getApplicationContext()); + boolean enabled = preferences.getBoolean("notificationsEnabled", true); + if (!enabled) { + return; + } + + createMastodonAPI(); + + mastodonApi.notification(notificationId).enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + if (response.isSuccessful()) { + NotificationMaker.make(PushNotificationService.this, NOTIFY_ID, + response.body()); + } + } + + @Override + public void onFailure(Call call, Throwable t) {} + }); + } + + /** Disconnect from the MQTT broker. */ + public void disconnect() { + try { + mqttAndroidClient.disconnect(); + } catch (MqttException ex) { + Log.e(TAG, "An exception occurred while disconnecting."); + onDisconnectFailed(); + } + } + + private void onDisconnectFailed() { + + } + + private void createMastodonAPI() { + SharedPreferences preferences = getSharedPreferences( + getString(R.string.preferences_file_key), Context.MODE_PRIVATE); + final String domain = preferences.getString("domain", null); + final String accessToken = preferences.getString("accessToken", null); + + OkHttpClient okHttpClient = OkHttpUtils.getCompatibleClientBuilder() + .addInterceptor(new Interceptor() { + @Override + public okhttp3.Response intercept(Chain chain) throws IOException { + Request originalRequest = chain.request(); + + Request.Builder builder = originalRequest.newBuilder() + .header("Authorization", String.format("Bearer %s", accessToken)); + + Request newRequest = builder.build(); + + return chain.proceed(newRequest); + } + }) + .build(); + + Gson gson = new GsonBuilder() + .registerTypeAdapter(Spanned.class, new SpannedTypeAdapter()) + .registerTypeAdapter(StringWithEmoji.class, new StringWithEmojiTypeAdapter()) + .create(); + + Retrofit retrofit = new Retrofit.Builder() + .baseUrl("https://" + domain) + .client(okHttpClient) + .addConverterFactory(GsonConverterFactory.create(gson)) + .build(); + + mastodonApi = retrofit.create(MastodonAPI.class); + } +} diff --git a/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java b/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java new file mode 100644 index 00000000..ba8f3450 --- /dev/null +++ b/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java @@ -0,0 +1,256 @@ +package com.keylesspalace.tusky.util; + +import android.content.Context; +import android.content.SharedPreferences; +import android.support.annotation.NonNull; +import android.text.Spanned; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.keylesspalace.tusky.R; +import com.keylesspalace.tusky.entity.Notification; +import com.keylesspalace.tusky.json.SpannedTypeAdapter; +import com.keylesspalace.tusky.json.StringWithEmoji; +import com.keylesspalace.tusky.json.StringWithEmojiTypeAdapter; +import com.keylesspalace.tusky.network.MastodonAPI; + +import org.eclipse.paho.android.service.MqttAndroidClient; +import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions; +import org.eclipse.paho.client.mqttv3.IMqttActionListener; +import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; +import org.eclipse.paho.client.mqttv3.IMqttToken; +import org.eclipse.paho.client.mqttv3.MqttCallbackExtended; +import org.eclipse.paho.client.mqttv3.MqttClient; +import org.eclipse.paho.client.mqttv3.MqttConnectOptions; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.client.mqttv3.MqttMessage; + +import java.io.IOException; +import java.util.ArrayDeque; + +import okhttp3.Interceptor; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; + +public class PushNotificationClient { + private static final String TAG = "PushNotificationClient"; + private static final String TOPIC = "tusky/notification"; + private static final int NOTIFY_ID = 666; + + private enum QueuedAction { + SUBSCRIBE, + UNSUBSCRIBE, + DISCONNECT, + } + + private MqttAndroidClient mqttAndroidClient; + private MastodonAPI mastodonApi; + private boolean connected; + private ArrayDeque queuedActions; + + public PushNotificationClient(final @NonNull Context context, @NonNull String serverUri) { + queuedActions = new ArrayDeque<>(); + + // Create the MQTT client. + String clientId = MqttClient.generateClientId(); + mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId); + mqttAndroidClient.setCallback(new MqttCallbackExtended() { + @Override + public void connectComplete(boolean reconnect, String serverURI) { + if (reconnect) { + flushQueuedActions(); + } + } + + @Override + public void connectionLost(Throwable cause) { + onConnectionLost(); + } + + @Override + public void messageArrived(String topic, MqttMessage message) throws Exception { + onMessageReceived(context, new String(message.getPayload())); + } + + @Override + public void deliveryComplete(IMqttDeliveryToken token) { + // This client is read-only, so this is unused. + } + }); + + // Open the MQTT connection. + MqttConnectOptions options = new MqttConnectOptions(); + options.setAutomaticReconnect(true); + options.setCleanSession(false); + try { + /* TLS connection stuffs + InputStream input = context.getResources().openRawResource(R.raw.keystore_tusky_api); + String password = context.getString(R.string.tusky_api_keystore_password); + options.setSocketFactory(mqttAndroidClient.getSSLSocketFactory(input, password)); + */ + mqttAndroidClient.connect(options).setActionCallback(new IMqttActionListener() { + @Override + public void onSuccess(IMqttToken asyncActionToken) { + DisconnectedBufferOptions options = new DisconnectedBufferOptions(); + options.setBufferEnabled(true); + options.setBufferSize(100); + options.setPersistBuffer(false); + options.setDeleteOldestMessages(false); + mqttAndroidClient.setBufferOpts(options); + onConnectionSuccess(); + connected = true; + flushQueuedActions(); + } + + @Override + public void onFailure(IMqttToken asyncActionToken, Throwable exception) { + Log.e(TAG, "An exception occurred while connecting. " + exception.getMessage()); + onConnectionFailure(); + } + }); + } catch (MqttException e) { + Log.e(TAG, "An exception occurred while connecting. " + e.getMessage()); + onConnectionFailure(); + } + } + + private void flushQueuedActions() { + for (QueuedAction action : queuedActions) { + switch (action) { + case SUBSCRIBE: subscribeToTopic(); break; + case UNSUBSCRIBE: unsubscribeToTopic(); break; + case DISCONNECT: disconnect(); break; + } + } + } + + /** Disconnect from the MQTT broker. */ + public void disconnect() { + if (!connected) { + queuedActions.add(QueuedAction.DISCONNECT); + return; + } + try { + mqttAndroidClient.disconnect(); + } catch (MqttException ex) { + Log.e(TAG, "An exception occurred while disconnecting."); + onDisconnectFailed(); + } + } + + private void onDisconnectFailed() { + Log.v(TAG, "Failed while disconnecting from the broker."); + } + + /** Subscribe to the push notification topic. */ + public void subscribeToTopic() { + if (!connected) { + queuedActions.add(QueuedAction.SUBSCRIBE); + return; + } + try { + mqttAndroidClient.subscribe(TOPIC, 0, null, new IMqttActionListener() { + @Override + public void onSuccess(IMqttToken asyncActionToken) { + onConnectionSuccess(); + } + + @Override + public void onFailure(IMqttToken asyncActionToken, Throwable exception) { + Log.e(TAG, "An exception occurred while subscribing." + exception.getMessage()); + onConnectionFailure(); + } + }); + } catch (MqttException e) { + Log.e(TAG, "An exception occurred while subscribing." + e.getMessage()); + onConnectionFailure(); + } + } + + /** Unsubscribe from the push notification topic. */ + public void unsubscribeToTopic() { + if (!connected) { + queuedActions.add(QueuedAction.UNSUBSCRIBE); + return; + } + try { + mqttAndroidClient.unsubscribe(TOPIC); + } catch (MqttException e) { + Log.e(TAG, "An exception occurred while unsubscribing." + e.getMessage()); + onConnectionFailure(); + } + } + + private void onConnectionSuccess() { + Log.v(TAG, "The connection succeeded."); + } + + private void onConnectionFailure() { + Log.v(TAG, "The connection failed."); + } + + private void onConnectionLost() { + Log.v(TAG, "The connection was lost."); + } + + private void onMessageReceived(final Context context, String message) { + String notificationId = message; // TODO: finalize the form the messages will be received + + Log.v(TAG, "Notification received: " + notificationId); + + createMastodonAPI(context); + + mastodonApi.notification(notificationId).enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + if (response.isSuccessful()) { + NotificationMaker.make(context, NOTIFY_ID, response.body()); + } + } + + @Override + public void onFailure(Call call, Throwable t) {} + }); + } + + private void createMastodonAPI(Context context) { + SharedPreferences preferences = context.getSharedPreferences( + context.getString(R.string.preferences_file_key), Context.MODE_PRIVATE); + final String domain = preferences.getString("domain", null); + final String accessToken = preferences.getString("accessToken", null); + + OkHttpClient okHttpClient = OkHttpUtils.getCompatibleClientBuilder() + .addInterceptor(new Interceptor() { + @Override + public okhttp3.Response intercept(Chain chain) throws IOException { + Request originalRequest = chain.request(); + + Request.Builder builder = originalRequest.newBuilder() + .header("Authorization", String.format("Bearer %s", accessToken)); + + Request newRequest = builder.build(); + + return chain.proceed(newRequest); + } + }) + .build(); + + Gson gson = new GsonBuilder() + .registerTypeAdapter(Spanned.class, new SpannedTypeAdapter()) + .registerTypeAdapter(StringWithEmoji.class, new StringWithEmojiTypeAdapter()) + .create(); + + Retrofit retrofit = new Retrofit.Builder() + .baseUrl("https://" + domain) + .client(okHttpClient) + .addConverterFactory(GsonConverterFactory.create(gson)) + .build(); + + mastodonApi = retrofit.create(MastodonAPI.class); + } +} diff --git a/app/src/main/res/values/donottranslate.xml b/app/src/main/res/values/donottranslate.xml index b2a8e3b6..73a4b542 100644 --- a/app/src/main/res/values/donottranslate.xml +++ b/app/src/main/res/values/donottranslate.xml @@ -3,6 +3,7 @@ Tusky https://tusky.keylesspalace.com https://tuskynotifier.keylesspalace.com + your_password_here oauth2redirect com.keylesspalace.tusky From 54327f6e2be87cb738eb8cc4bef3ad68d2c7cf12 Mon Sep 17 00:00:00 2001 From: Vavassor Date: Thu, 18 May 2017 18:10:46 -0400 Subject: [PATCH 2/9] Removes the product flavor split. --- app/.gitignore | 1 + app/build.gradle | 16 +- app/google-services.json | 55 ------- app/src/fdroid/AndroidManifest.xml | 12 -- .../keylesspalace/tusky/MessagingService.java | 142 ------------------ app/src/google/AndroidManifest.xml | 18 --- .../keylesspalace/tusky/MessagingService.java | 133 ---------------- .../tusky/MyFirebaseInstanceIdService.java | 86 ----------- .../com/keylesspalace/tusky/BaseActivity.java | 32 +--- .../com/keylesspalace/tusky/MainActivity.java | 3 +- .../tusky/util/PushNotificationClient.java | 27 ++-- app/src/main/res/values/donottranslate.xml | 2 +- build.gradle | 1 - 13 files changed, 27 insertions(+), 501 deletions(-) delete mode 100644 app/google-services.json delete mode 100644 app/src/fdroid/AndroidManifest.xml delete mode 100644 app/src/fdroid/java/com/keylesspalace/tusky/MessagingService.java delete mode 100644 app/src/google/AndroidManifest.xml delete mode 100644 app/src/google/java/com/keylesspalace/tusky/MessagingService.java delete mode 100644 app/src/google/java/com/keylesspalace/tusky/MyFirebaseInstanceIdService.java diff --git a/app/.gitignore b/app/.gitignore index 61e52b44..d4026ab8 100644 --- a/app/.gitignore +++ b/app/.gitignore @@ -1,3 +1,4 @@ /build app-release.apk app-google-release.apk +src/main/res/raw/keystore_tusky_api.bks diff --git a/app/build.gradle b/app/build.gradle index 5ef9205d..cb33758a 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -12,14 +12,6 @@ android { testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" vectorDrawables.useSupportLibrary true } - productFlavors { - google { - buildConfigField "boolean", "USES_PUSH_NOTIFICATIONS", "true" - } - fdroid { - buildConfigField "boolean", "USES_PUSH_NOTIFICATIONS", "false" - } - } buildTypes { release { minifyEnabled true @@ -59,14 +51,10 @@ dependencies { compile 'com.github.arimorty:floatingsearchview:2.0.4' compile 'com.theartofdev.edmodo:android-image-cropper:2.4.3' compile 'com.jakewharton:butterknife:8.5.1' - googleCompile 'com.google.firebase:firebase-messaging:10.2.4' - googleCompile 'com.google.firebase:firebase-crash:10.2.4' - testCompile 'junit:junit:4.12' - annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1' compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0' compile('org.eclipse.paho:org.eclipse.paho.android.service:1.1.1') { exclude module: 'support-v4' } + testCompile 'junit:junit:4.12' + annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1' } - -apply plugin: 'com.google.gms.google-services' diff --git a/app/google-services.json b/app/google-services.json deleted file mode 100644 index bfd19f88..00000000 --- a/app/google-services.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "project_info": { - "project_number": "268851337880", - "firebase_url": "https://tusky-62772.firebaseio.com", - "project_id": "tusky-62772", - "storage_bucket": "tusky-62772.appspot.com" - }, - "client": [ - { - "client_info": { - "mobilesdk_app_id": "1:268851337880:android:fc4111b1d145a00e", - "android_client_info": { - "package_name": "com.keylesspalace.tusky" - } - }, - "oauth_client": [ - { - "client_id": "268851337880-eie2ssto2d21bfihn9d1qupcrke8oebf.apps.googleusercontent.com", - "client_type": 1, - "android_info": { - "package_name": "com.keylesspalace.tusky", - "certificate_hash": "18d196307d6e928e99c2e0bb9818c01c38aff2f9" - } - }, - { - "client_id": "268851337880-n19d05m282nirs1fc9kdd5n4of6je4fk.apps.googleusercontent.com", - "client_type": 3 - } - ], - "api_key": [ - { - "current_key": "AIzaSyCbJtSjuk4I3Jy8PdUaO3TaQOXubcOUElo" - } - ], - "services": { - "analytics_service": { - "status": 1 - }, - "appinvite_service": { - "status": 2, - "other_platform_oauth_client": [ - { - "client_id": "268851337880-n19d05m282nirs1fc9kdd5n4of6je4fk.apps.googleusercontent.com", - "client_type": 3 - } - ] - }, - "ads_service": { - "status": 2 - } - } - } - ], - "configuration_version": "1" -} \ No newline at end of file diff --git a/app/src/fdroid/AndroidManifest.xml b/app/src/fdroid/AndroidManifest.xml deleted file mode 100644 index b7060e6e..00000000 --- a/app/src/fdroid/AndroidManifest.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/app/src/fdroid/java/com/keylesspalace/tusky/MessagingService.java b/app/src/fdroid/java/com/keylesspalace/tusky/MessagingService.java deleted file mode 100644 index eaa1b1b5..00000000 --- a/app/src/fdroid/java/com/keylesspalace/tusky/MessagingService.java +++ /dev/null @@ -1,142 +0,0 @@ -/* Copyright 2017 Andrew Dawson - * - * This file is a part of Tusky. - * - * This program is free software; you can redistribute it and/or modify it under the terms of the - * GNU General Public License as published by the Free Software Foundation; either version 3 of the - * License, or (at your option) any later version. - * - * Tusky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even - * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General - * Public License for more details. - * - * You should have received a copy of the GNU General Public License along with Tusky; if not, - * see . */ - -package com.keylesspalace.tusky; - -import android.app.IntentService; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.preference.PreferenceManager; -import android.text.Spanned; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import com.keylesspalace.tusky.entity.Notification; -import com.keylesspalace.tusky.json.SpannedTypeAdapter; -import com.keylesspalace.tusky.json.StringWithEmoji; -import com.keylesspalace.tusky.json.StringWithEmojiTypeAdapter; -import com.keylesspalace.tusky.network.MastodonAPI; -import com.keylesspalace.tusky.util.NotificationMaker; -import com.keylesspalace.tusky.util.OkHttpUtils; - -import java.util.HashSet; -import java.util.List; - -import java.io.IOException; -import java.util.Set; - -import okhttp3.Interceptor; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import retrofit2.Call; -import retrofit2.Callback; -import retrofit2.Response; -import retrofit2.Retrofit; -import retrofit2.converter.gson.GsonConverterFactory; - -public class MessagingService extends IntentService { - public static final int NOTIFY_ID = 6; // This is an arbitrary number. - - private MastodonAPI mastodonAPI; - - public MessagingService() { - super("Tusky Pull Notification Service"); - } - - @Override - protected void onHandleIntent(Intent intent) { - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences( - getApplicationContext()); - boolean enabled = preferences.getBoolean("notificationsEnabled", true); - if (!enabled) { - return; - } - - createMastodonApi(); - - mastodonAPI.notifications(null, null, null).enqueue(new Callback>() { - @Override - public void onResponse(Call> call, - Response> response) { - if (response.isSuccessful()) { - onNotificationsReceived(response.body()); - } - } - - @Override - public void onFailure(Call> call, Throwable t) {} - }); - } - - private void createMastodonApi() { - SharedPreferences preferences = getSharedPreferences( - getString(R.string.preferences_file_key), Context.MODE_PRIVATE); - final String domain = preferences.getString("domain", null); - final String accessToken = preferences.getString("accessToken", null); - - OkHttpClient okHttpClient = OkHttpUtils.getCompatibleClientBuilder() - .addInterceptor(new Interceptor() { - @Override - public okhttp3.Response intercept(Chain chain) throws IOException { - Request originalRequest = chain.request(); - - Request.Builder builder = originalRequest.newBuilder() - .header("Authorization", String.format("Bearer %s", accessToken)); - - Request newRequest = builder.build(); - - return chain.proceed(newRequest); - } - }) - .build(); - - Gson gson = new GsonBuilder() - .registerTypeAdapter(Spanned.class, new SpannedTypeAdapter()) - .registerTypeAdapter(StringWithEmoji.class, new StringWithEmojiTypeAdapter()) - .create(); - - Retrofit retrofit = new Retrofit.Builder() - .baseUrl("https://" + domain) - .client(okHttpClient) - .addConverterFactory(GsonConverterFactory.create(gson)) - .build(); - - mastodonAPI = retrofit.create(MastodonAPI.class); - } - - private void onNotificationsReceived(List notificationList) { - SharedPreferences notificationsPreferences = getSharedPreferences( - "Notifications", Context.MODE_PRIVATE); - Set currentIds = notificationsPreferences.getStringSet( - "current_ids", new HashSet()); - for (Notification notification : notificationList) { - String id = notification.id; - if (!currentIds.contains(id)) { - currentIds.add(id); - NotificationMaker.make(this, NOTIFY_ID, notification); - } - } - notificationsPreferences.edit() - .putStringSet("current_ids", currentIds) - .apply(); - } - - public static String getInstanceToken() { - // This is only used for the "google" build flavor, so this version is just a stub method. - return null; - } -} diff --git a/app/src/google/AndroidManifest.xml b/app/src/google/AndroidManifest.xml deleted file mode 100644 index 20ecbe94..00000000 --- a/app/src/google/AndroidManifest.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/app/src/google/java/com/keylesspalace/tusky/MessagingService.java b/app/src/google/java/com/keylesspalace/tusky/MessagingService.java deleted file mode 100644 index 4a2a55da..00000000 --- a/app/src/google/java/com/keylesspalace/tusky/MessagingService.java +++ /dev/null @@ -1,133 +0,0 @@ -/* Copyright 2017 Andrew Dawson - * - * This file is a part of Tusky. - * - * This program is free software; you can redistribute it and/or modify it under the terms of the - * GNU General Public License as published by the Free Software Foundation; either version 3 of the - * License, or (at your option) any later version. - * - * Tusky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even - * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General - * Public License for more details. - * - * You should have received a copy of the GNU General Public License along with Tusky; if not, - * see . - * - * If you modify this Program, or any covered work, by linking or combining it with Firebase Cloud - * Messaging and Firebase Crash Reporting (or a modified version of those libraries), containing - * parts covered by the Google APIs Terms of Service, the licensors of this Program grant you - * additional permission to convey the resulting work. */ - -package com.keylesspalace.tusky; - -import android.content.Context; -import android.content.SharedPreferences; -import android.preference.PreferenceManager; -import android.text.Spanned; - -import com.google.firebase.iid.FirebaseInstanceId; -import com.google.firebase.messaging.FirebaseMessagingService; -import com.google.firebase.messaging.RemoteMessage; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import com.keylesspalace.tusky.entity.Notification; -import com.keylesspalace.tusky.json.SpannedTypeAdapter; -import com.keylesspalace.tusky.json.StringWithEmoji; -import com.keylesspalace.tusky.json.StringWithEmojiTypeAdapter; -import com.keylesspalace.tusky.network.MastodonAPI; -import com.keylesspalace.tusky.util.Log; -import com.keylesspalace.tusky.util.NotificationMaker; -import com.keylesspalace.tusky.util.OkHttpUtils; - -import java.io.IOException; - -import okhttp3.Interceptor; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import retrofit2.Call; -import retrofit2.Callback; -import retrofit2.Response; -import retrofit2.Retrofit; -import retrofit2.converter.gson.GsonConverterFactory; - -public class MessagingService extends FirebaseMessagingService { - private MastodonAPI mastodonAPI; - private static final String TAG = "MessagingService"; - public static final int NOTIFY_ID = 666; - - @Override - public void onMessageReceived(RemoteMessage remoteMessage) { - Log.d(TAG, remoteMessage.getFrom()); - Log.d(TAG, remoteMessage.toString()); - - String notificationId = remoteMessage.getData().get("notification_id"); - - if (notificationId == null) { - Log.e(TAG, "No notification ID in payload!!"); - return; - } - - Log.d(TAG, notificationId); - - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences( - getApplicationContext()); - boolean enabled = preferences.getBoolean("notificationsEnabled", true); - if (!enabled) { - return; - } - - createMastodonAPI(); - - mastodonAPI.notification(notificationId).enqueue(new Callback() { - @Override - public void onResponse(Call call, Response response) { - if (response.isSuccessful()) { - NotificationMaker.make(MessagingService.this, NOTIFY_ID, response.body()); - } - } - - @Override - public void onFailure(Call call, Throwable t) {} - }); - } - - private void createMastodonAPI() { - SharedPreferences preferences = getSharedPreferences(getString(R.string.preferences_file_key), Context.MODE_PRIVATE); - final String domain = preferences.getString("domain", null); - final String accessToken = preferences.getString("accessToken", null); - - OkHttpClient okHttpClient = OkHttpUtils.getCompatibleClientBuilder() - .addInterceptor(new Interceptor() { - @Override - public okhttp3.Response intercept(Chain chain) throws IOException { - Request originalRequest = chain.request(); - - Request.Builder builder = originalRequest.newBuilder() - .header("Authorization", String.format("Bearer %s", accessToken)); - - Request newRequest = builder.build(); - - return chain.proceed(newRequest); - } - }) - .build(); - - Gson gson = new GsonBuilder() - .registerTypeAdapter(Spanned.class, new SpannedTypeAdapter()) - .registerTypeAdapter(StringWithEmoji.class, new StringWithEmojiTypeAdapter()) - .create(); - - Retrofit retrofit = new Retrofit.Builder() - .baseUrl("https://" + domain) - .client(okHttpClient) - .addConverterFactory(GsonConverterFactory.create(gson)) - .build(); - - mastodonAPI = retrofit.create(MastodonAPI.class); - } - - public static String getInstanceToken() { - return FirebaseInstanceId.getInstance().getToken(); - } -} diff --git a/app/src/google/java/com/keylesspalace/tusky/MyFirebaseInstanceIdService.java b/app/src/google/java/com/keylesspalace/tusky/MyFirebaseInstanceIdService.java deleted file mode 100644 index 14d640d5..00000000 --- a/app/src/google/java/com/keylesspalace/tusky/MyFirebaseInstanceIdService.java +++ /dev/null @@ -1,86 +0,0 @@ -/* Copyright 2017 Andrew Dawson - * - * This file is a part of Tusky. - * - * This program is free software; you can redistribute it and/or modify it under the terms of the - * GNU General Public License as published by the Free Software Foundation; either version 3 of the - * License, or (at your option) any later version. - * - * Tusky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even - * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General - * Public License for more details. - * - * You should have received a copy of the GNU General Public License along with Tusky; if not, - * see . - * - * If you modify this Program, or any covered work, by linking or combining it with Firebase Cloud - * Messaging and Firebase Crash Reporting (or a modified version of those libraries), containing - * parts covered by the Google APIs Terms of Service, the licensors of this Program grant you - * additional permission to convey the resulting work. */ - -package com.keylesspalace.tusky; - -import android.content.Context; -import android.content.SharedPreferences; - -import com.google.firebase.iid.FirebaseInstanceId; -import com.google.firebase.iid.FirebaseInstanceIdService; -import com.keylesspalace.tusky.network.TuskyAPI; -import com.keylesspalace.tusky.util.Log; -import com.keylesspalace.tusky.util.OkHttpUtils; - -import okhttp3.ResponseBody; -import retrofit2.Call; -import retrofit2.Callback; -import retrofit2.Response; -import retrofit2.Retrofit; - -public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService { - private static final String TAG = "com.keylesspalace.tusky.MyFirebaseInstanceIdService"; - - private TuskyAPI tuskyAPI; - - protected void createTuskyAPI() { - Retrofit retrofit = new Retrofit.Builder() - .baseUrl(getString(R.string.tusky_api_url)) - .client(OkHttpUtils.getCompatibleClient()) - .build(); - - tuskyAPI = retrofit.create(TuskyAPI.class); - } - - @Override - public void onTokenRefresh() { - createTuskyAPI(); - - String refreshedToken = FirebaseInstanceId.getInstance().getToken(); - SharedPreferences preferences = getSharedPreferences(getString(R.string.preferences_file_key), Context.MODE_PRIVATE); - String accessToken = preferences.getString("accessToken", null); - String domain = preferences.getString("domain", null); - - if (accessToken != null && domain != null) { - tuskyAPI.unregister("https://" + domain, accessToken).enqueue(new Callback() { - @Override - public void onResponse(Call call, Response response) { - Log.d(TAG, response.message()); - } - - @Override - public void onFailure(Call call, Throwable t) { - Log.d(TAG, t.getMessage()); - } - }); - tuskyAPI.register("https://" + domain, accessToken, refreshedToken).enqueue(new Callback() { - @Override - public void onResponse(Call call, Response response) { - Log.d(TAG, response.message()); - } - - @Override - public void onFailure(Call call, Throwable t) { - Log.d(TAG, t.getMessage()); - } - }); - } - } -} diff --git a/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java b/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java index 4ba4c0b8..e88cd1cb 100644 --- a/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java +++ b/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java @@ -15,8 +15,6 @@ package com.keylesspalace.tusky; -import android.app.AlarmManager; -import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; @@ -24,7 +22,6 @@ import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.os.Bundle; -import android.os.SystemClock; import android.preference.PreferenceManager; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; @@ -55,7 +52,6 @@ public class BaseActivity extends AppCompatActivity { public MastodonAPI mastodonAPI; protected PushNotificationClient pushNotificationClient; protected Dispatcher mastodonApiDispatcher; - protected PendingIntent serviceAlarmIntent; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { @@ -156,10 +152,8 @@ public class BaseActivity extends AppCompatActivity { } protected void createTuskyAPI() { - if (BuildConfig.USES_PUSH_NOTIFICATIONS) { - // TODO: Remove this test broker address. - pushNotificationClient = new PushNotificationClient(this, "tcp://104.236.116.199:1883"); - } + pushNotificationClient = new PushNotificationClient(this, + getString(R.string.tusky_api_url)); } protected void redirectIfNotLoggedIn() { @@ -193,28 +187,10 @@ public class BaseActivity extends AppCompatActivity { } protected void enablePushNotifications() { - if (BuildConfig.USES_PUSH_NOTIFICATIONS) { - pushNotificationClient.subscribeToTopic(); - } else { - // Start up the MessagingService on a repeating interval for "pull" notifications. - long checkInterval = 60 * 1000 * 5; - AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); - Intent intent = new Intent(this, MessagingService.class); - final int SERVICE_REQUEST_CODE = 8574603; // This number is arbitrary. - serviceAlarmIntent = PendingIntent.getService(this, SERVICE_REQUEST_CODE, intent, - PendingIntent.FLAG_UPDATE_CURRENT); - alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, - SystemClock.elapsedRealtime(), checkInterval, serviceAlarmIntent); - } + pushNotificationClient.subscribeToTopic(); } protected void disablePushNotifications() { - if (BuildConfig.USES_PUSH_NOTIFICATIONS) { - pushNotificationClient.unsubscribeToTopic(); - } else if (serviceAlarmIntent != null) { - // Cancel the repeating call for "pull" notifications. - AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); - alarmManager.cancel(serviceAlarmIntent); - } + pushNotificationClient.unsubscribeToTopic(); } } diff --git a/app/src/main/java/com/keylesspalace/tusky/MainActivity.java b/app/src/main/java/com/keylesspalace/tusky/MainActivity.java index 3d39b81a..4c4c2db5 100644 --- a/app/src/main/java/com/keylesspalace/tusky/MainActivity.java +++ b/app/src/main/java/com/keylesspalace/tusky/MainActivity.java @@ -215,8 +215,7 @@ public class MainActivity extends BaseActivity implements SFragment.OnUserRemove .putString("current", "[]") .apply(); - ((NotificationManager) (getSystemService(NOTIFICATION_SERVICE))) - .cancel(MessagingService.NOTIFY_ID); + pushNotificationClient.clearNotifications(); /* After editing a profile, the profile header in the navigation drawer needs to be * refreshed */ diff --git a/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java b/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java index ba8f3450..6c944f75 100644 --- a/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java +++ b/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java @@ -26,6 +26,7 @@ import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import java.io.IOException; +import java.io.InputStream; import java.util.ArrayDeque; import okhttp3.Interceptor; @@ -88,20 +89,24 @@ public class PushNotificationClient { options.setAutomaticReconnect(true); options.setCleanSession(false); try { - /* TLS connection stuffs - InputStream input = context.getResources().openRawResource(R.raw.keystore_tusky_api); + /* String password = context.getString(R.string.tusky_api_keystore_password); - options.setSocketFactory(mqttAndroidClient.getSSLSocketFactory(input, password)); + InputStream keystore = context.getResources().openRawResource(R.raw.keystore_tusky_api); + try { + options.setSocketFactory(mqttAndroidClient.getSSLSocketFactory(keystore, password)); + } finally { + IOUtils.closeQuietly(keystore); + } */ mqttAndroidClient.connect(options).setActionCallback(new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { - DisconnectedBufferOptions options = new DisconnectedBufferOptions(); - options.setBufferEnabled(true); - options.setBufferSize(100); - options.setPersistBuffer(false); - options.setDeleteOldestMessages(false); - mqttAndroidClient.setBufferOpts(options); + DisconnectedBufferOptions bufferOptions = new DisconnectedBufferOptions(); + bufferOptions.setBufferEnabled(true); + bufferOptions.setBufferSize(100); + bufferOptions.setPersistBuffer(false); + bufferOptions.setDeleteOldestMessages(false); + mqttAndroidClient.setBufferOpts(bufferOptions); onConnectionSuccess(); connected = true; flushQueuedActions(); @@ -253,4 +258,8 @@ public class PushNotificationClient { mastodonApi = retrofit.create(MastodonAPI.class); } + + public void clearNotifications() { + // TODO: make it happen + } } diff --git a/app/src/main/res/values/donottranslate.xml b/app/src/main/res/values/donottranslate.xml index 73a4b542..212d54db 100644 --- a/app/src/main/res/values/donottranslate.xml +++ b/app/src/main/res/values/donottranslate.xml @@ -2,7 +2,7 @@ Tusky https://tusky.keylesspalace.com - https://tuskynotifier.keylesspalace.com + tcp://tuskyapi.keylesspalace.com your_password_here oauth2redirect diff --git a/build.gradle b/build.gradle index 80e6fd50..bfed5920 100644 --- a/build.gradle +++ b/build.gradle @@ -9,7 +9,6 @@ buildscript { // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files - classpath 'com.google.gms:google-services:3.0.0' } } From 6208b848b749cffafc9e002b6399c7b4bb41e243 Mon Sep 17 00:00:00 2001 From: Vavassor Date: Fri, 19 May 2017 20:00:57 -0400 Subject: [PATCH 3/9] Adds notification clearing and makes the client a little more stable. --- app/src/main/AndroidManifest.xml | 12 +++---- .../com/keylesspalace/tusky/BaseActivity.java | 2 +- .../com/keylesspalace/tusky/MainActivity.java | 3 +- .../tusky/util/PushNotificationClient.java | 31 ++++++++++++------- 4 files changed, 28 insertions(+), 20 deletions(-) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 1fd924b5..cbe15faa 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -6,18 +6,18 @@ - - - - + + + + + android:theme="@style/AppTheme"> queuedActions; + private boolean subscribed; - public PushNotificationClient(final @NonNull Context context, @NonNull String serverUri) { + public PushNotificationClient(final @NonNull Context applicationContext, + @NonNull String serverUri) { queuedActions = new ArrayDeque<>(); // Create the MQTT client. String clientId = MqttClient.generateClientId(); - mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId); + mqttAndroidClient = new MqttAndroidClient(applicationContext, serverUri, clientId); mqttAndroidClient.setCallback(new MqttCallbackExtended() { @Override public void connectComplete(boolean reconnect, String serverURI) { if (reconnect) { flushQueuedActions(); + if (subscribed) { + subscribeToTopic(); + } } } @@ -75,7 +82,7 @@ public class PushNotificationClient { @Override public void messageArrived(String topic, MqttMessage message) throws Exception { - onMessageReceived(context, new String(message.getPayload())); + onMessageReceived(applicationContext, new String(message.getPayload())); } @Override @@ -108,7 +115,6 @@ public class PushNotificationClient { bufferOptions.setDeleteOldestMessages(false); mqttAndroidClient.setBufferOpts(bufferOptions); onConnectionSuccess(); - connected = true; flushQueuedActions(); } @@ -125,7 +131,8 @@ public class PushNotificationClient { } private void flushQueuedActions() { - for (QueuedAction action : queuedActions) { + while (!queuedActions.isEmpty()) { + QueuedAction action = queuedActions.pop(); switch (action) { case SUBSCRIBE: subscribeToTopic(); break; case UNSUBSCRIBE: unsubscribeToTopic(); break; @@ -136,7 +143,7 @@ public class PushNotificationClient { /** Disconnect from the MQTT broker. */ public void disconnect() { - if (!connected) { + if (!mqttAndroidClient.isConnected()) { queuedActions.add(QueuedAction.DISCONNECT); return; } @@ -154,7 +161,7 @@ public class PushNotificationClient { /** Subscribe to the push notification topic. */ public void subscribeToTopic() { - if (!connected) { + if (!mqttAndroidClient.isConnected()) { queuedActions.add(QueuedAction.SUBSCRIBE); return; } @@ -162,6 +169,7 @@ public class PushNotificationClient { mqttAndroidClient.subscribe(TOPIC, 0, null, new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { + subscribed = true; onConnectionSuccess(); } @@ -179,12 +187,13 @@ public class PushNotificationClient { /** Unsubscribe from the push notification topic. */ public void unsubscribeToTopic() { - if (!connected) { + if (!mqttAndroidClient.isConnected()) { queuedActions.add(QueuedAction.UNSUBSCRIBE); return; } try { mqttAndroidClient.unsubscribe(TOPIC); + subscribed = false; } catch (MqttException e) { Log.e(TAG, "An exception occurred while unsubscribing." + e.getMessage()); onConnectionFailure(); @@ -259,7 +268,7 @@ public class PushNotificationClient { mastodonApi = retrofit.create(MastodonAPI.class); } - public void clearNotifications() { - // TODO: make it happen + public void clearNotifications(Context context) { + ((NotificationManager) (context.getSystemService(NOTIFICATION_SERVICE))).cancel(NOTIFY_ID); } } From 3744bb1a60f03651607950af22ec8c5d941979c8 Mon Sep 17 00:00:00 2001 From: Vavassor Date: Fri, 19 May 2017 21:28:12 -0400 Subject: [PATCH 4/9] Setup client-side for integration with the wryk/tusky-api prototype. --- .../com/keylesspalace/tusky/BaseActivity.java | 76 +++++++++++++++++-- .../network/{TuskyAPI.java => TuskyApi.java} | 7 +- .../tusky/util/PushNotificationClient.java | 61 ++++++++++----- app/src/main/res/values/donottranslate.xml | 2 +- 4 files changed, 115 insertions(+), 31 deletions(-) rename app/src/main/java/com/keylesspalace/tusky/network/{TuskyAPI.java => TuskyApi.java} (73%) diff --git a/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java b/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java index 0bb76039..d01eb28f 100644 --- a/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java +++ b/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java @@ -35,6 +35,8 @@ import com.keylesspalace.tusky.json.SpannedTypeAdapter; import com.keylesspalace.tusky.json.StringWithEmoji; import com.keylesspalace.tusky.json.StringWithEmojiTypeAdapter; import com.keylesspalace.tusky.network.MastodonAPI; +import com.keylesspalace.tusky.network.TuskyApi; +import com.keylesspalace.tusky.util.Log; import com.keylesspalace.tusky.util.OkHttpUtils; import com.keylesspalace.tusky.util.PushNotificationClient; @@ -45,11 +47,17 @@ import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Callback; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class BaseActivity extends AppCompatActivity { + private static final String TAG = "BaseActivity"; // logging tag + public MastodonAPI mastodonAPI; + public TuskyApi tuskyApi; protected PushNotificationClient pushNotificationClient; protected Dispatcher mastodonApiDispatcher; @@ -59,7 +67,8 @@ public class BaseActivity extends AppCompatActivity { redirectIfNotLoggedIn(); createMastodonAPI(); - createTuskyAPI(); + createTuskyApi(); + createPushNotificationClient(); /* There isn't presently a way to globally change the theme of a whole application at * runtime, just individual activities. So, each activity has to set its theme before any @@ -151,9 +160,19 @@ public class BaseActivity extends AppCompatActivity { mastodonAPI = retrofit.create(MastodonAPI.class); } - protected void createTuskyAPI() { + protected void createTuskyApi() { + Retrofit retrofit = new Retrofit.Builder() + .baseUrl("https://" + getString(R.string.tusky_api_domain)) + .client(OkHttpUtils.getCompatibleClient()) + .build(); + + tuskyApi = retrofit.create(TuskyApi.class); + } + + protected void createPushNotificationClient() { + // TODO: Switch to ssl:// when TLS support is added. pushNotificationClient = new PushNotificationClient(getApplicationContext(), - getString(R.string.tusky_api_url)); + "tcp://" + getString(R.string.tusky_api_domain)); } protected void redirectIfNotLoggedIn() { @@ -187,10 +206,57 @@ public class BaseActivity extends AppCompatActivity { } protected void enablePushNotifications() { - pushNotificationClient.subscribeToTopic(); + Callback callback = new Callback() { + @Override + public void onResponse(Call call, + retrofit2.Response response) { + if (response.isSuccessful()) { + pushNotificationClient.subscribeToTopic(getPushNotificationTopic()); + } else { + onEnablePushNotificationsFailure(); + } + } + + @Override + public void onFailure(Call call, Throwable t) { + onEnablePushNotificationsFailure(); + } + }; + tuskyApi.register(getBaseUrl(), getAccessToken(), pushNotificationClient.getDeviceToken()) + .enqueue(callback); + } + + private void onEnablePushNotificationsFailure() { + Log.e(TAG, "Enabling push notifications failed."); } protected void disablePushNotifications() { - pushNotificationClient.unsubscribeToTopic(); + Callback callback = new Callback() { + @Override + public void onResponse(Call call, + retrofit2.Response response) { + if (response.isSuccessful()) { + pushNotificationClient.unsubscribeToTopic(getPushNotificationTopic()); + } else { + onDisablePushNotificationsFailure(); + } + } + + @Override + public void onFailure(Call call, Throwable t) { + onDisablePushNotificationsFailure(); + } + }; + tuskyApi.unregister(getBaseUrl(), getAccessToken(), pushNotificationClient.getDeviceToken()) + .enqueue(callback); + } + + private void onDisablePushNotificationsFailure() { + Log.e(TAG, "Disabling push notifications failed."); + } + + private String getPushNotificationTopic() { + return String.format("%s/%s/%s", getBaseUrl(), getAccessToken(), + pushNotificationClient.getDeviceToken()); } } diff --git a/app/src/main/java/com/keylesspalace/tusky/network/TuskyAPI.java b/app/src/main/java/com/keylesspalace/tusky/network/TuskyApi.java similarity index 73% rename from app/src/main/java/com/keylesspalace/tusky/network/TuskyAPI.java rename to app/src/main/java/com/keylesspalace/tusky/network/TuskyApi.java index 700de83c..393decb9 100644 --- a/app/src/main/java/com/keylesspalace/tusky/network/TuskyAPI.java +++ b/app/src/main/java/com/keylesspalace/tusky/network/TuskyApi.java @@ -17,15 +17,14 @@ package com.keylesspalace.tusky.network; import okhttp3.ResponseBody; import retrofit2.Call; -import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; -public interface TuskyAPI { +public interface TuskyApi { @FormUrlEncoded @POST("/register") - Call register(@Field("instance_url") String instanceUrl, @Field("access_token") String accessToken, @Field("device_token") String deviceToken); + Call register(String instanceUrl, String accessToken, String deviceToken); @FormUrlEncoded @POST("/unregister") - Call unregister(@Field("instance_url") String instanceUrl, @Field("access_token") String accessToken); + Call unregister(String instanceUrl, String accessToken, String deviceToken); } diff --git a/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java b/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java index f75e318e..40150bb2 100644 --- a/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java +++ b/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java @@ -29,6 +29,7 @@ import org.eclipse.paho.client.mqttv3.MqttMessage; import java.io.IOException; import java.io.InputStream; import java.util.ArrayDeque; +import java.util.ArrayList; import okhttp3.Interceptor; import okhttp3.OkHttpClient; @@ -43,23 +44,37 @@ import static android.content.Context.NOTIFICATION_SERVICE; public class PushNotificationClient { private static final String TAG = "PushNotificationClient"; - private static final String TOPIC = "tusky/notification"; private static final int NOTIFY_ID = 666; - private enum QueuedAction { - SUBSCRIBE, - UNSUBSCRIBE, - DISCONNECT, + private static class QueuedAction { + enum Type { + SUBSCRIBE, + UNSUBSCRIBE, + DISCONNECT, + } + + Type type; + String topic; + + QueuedAction(Type type) { + this.type = type; + } + + QueuedAction(Type type, String topic) { + this.type = type; + this.topic = topic; + } } private MqttAndroidClient mqttAndroidClient; private MastodonAPI mastodonApi; private ArrayDeque queuedActions; - private boolean subscribed; + private ArrayList subscribedTopics; public PushNotificationClient(final @NonNull Context applicationContext, @NonNull String serverUri) { queuedActions = new ArrayDeque<>(); + subscribedTopics = new ArrayList<>(); // Create the MQTT client. String clientId = MqttClient.generateClientId(); @@ -69,8 +84,8 @@ public class PushNotificationClient { public void connectComplete(boolean reconnect, String serverURI) { if (reconnect) { flushQueuedActions(); - if (subscribed) { - subscribeToTopic(); + for (String topic : subscribedTopics) { + subscribeToTopic(topic); } } } @@ -133,10 +148,10 @@ public class PushNotificationClient { private void flushQueuedActions() { while (!queuedActions.isEmpty()) { QueuedAction action = queuedActions.pop(); - switch (action) { - case SUBSCRIBE: subscribeToTopic(); break; - case UNSUBSCRIBE: unsubscribeToTopic(); break; - case DISCONNECT: disconnect(); break; + switch (action.type) { + case SUBSCRIBE: subscribeToTopic(action.topic); break; + case UNSUBSCRIBE: unsubscribeToTopic(action.topic); break; + case DISCONNECT: disconnect(); break; } } } @@ -144,7 +159,7 @@ public class PushNotificationClient { /** Disconnect from the MQTT broker. */ public void disconnect() { if (!mqttAndroidClient.isConnected()) { - queuedActions.add(QueuedAction.DISCONNECT); + queuedActions.add(new QueuedAction(QueuedAction.Type.DISCONNECT)); return; } try { @@ -160,16 +175,16 @@ public class PushNotificationClient { } /** Subscribe to the push notification topic. */ - public void subscribeToTopic() { + public void subscribeToTopic(final String topic) { if (!mqttAndroidClient.isConnected()) { - queuedActions.add(QueuedAction.SUBSCRIBE); + queuedActions.add(new QueuedAction(QueuedAction.Type.SUBSCRIBE, topic)); return; } try { - mqttAndroidClient.subscribe(TOPIC, 0, null, new IMqttActionListener() { + mqttAndroidClient.subscribe(topic, 0, null, new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { - subscribed = true; + subscribedTopics.add(topic); onConnectionSuccess(); } @@ -186,14 +201,14 @@ public class PushNotificationClient { } /** Unsubscribe from the push notification topic. */ - public void unsubscribeToTopic() { + public void unsubscribeToTopic(String topic) { if (!mqttAndroidClient.isConnected()) { - queuedActions.add(QueuedAction.UNSUBSCRIBE); + queuedActions.add(new QueuedAction(QueuedAction.Type.UNSUBSCRIBE, topic)); return; } try { - mqttAndroidClient.unsubscribe(TOPIC); - subscribed = false; + mqttAndroidClient.unsubscribe(topic); + subscribedTopics.remove(topic); } catch (MqttException e) { Log.e(TAG, "An exception occurred while unsubscribing." + e.getMessage()); onConnectionFailure(); @@ -271,4 +286,8 @@ public class PushNotificationClient { public void clearNotifications(Context context) { ((NotificationManager) (context.getSystemService(NOTIFICATION_SERVICE))).cancel(NOTIFY_ID); } + + public String getDeviceToken() { + return mqttAndroidClient.getClientId(); + } } diff --git a/app/src/main/res/values/donottranslate.xml b/app/src/main/res/values/donottranslate.xml index 212d54db..e6982534 100644 --- a/app/src/main/res/values/donottranslate.xml +++ b/app/src/main/res/values/donottranslate.xml @@ -2,7 +2,7 @@ Tusky https://tusky.keylesspalace.com - tcp://tuskyapi.keylesspalace.com + tuskyapi.keylesspalace.com your_password_here oauth2redirect From 623af5fd9b2c1f235bbbb4e97ff45bc8d396c2dd Mon Sep 17 00:00:00 2001 From: Vavassor Date: Sat, 20 May 2017 02:39:29 -0400 Subject: [PATCH 5/9] Integrates with wryk/tusky-api, but only partially working. Registers to the web-service fine but loses connection when subscribing with the broker. --- .../com/keylesspalace/tusky/BaseActivity.java | 23 +- .../keylesspalace/tusky/entity/Session.java | 28 ++ .../keylesspalace/tusky/network/TuskyApi.java | 10 +- .../service/PushNotificationService.java | 257 ------------------ .../tusky/util/PushNotificationClient.java | 48 ++-- 5 files changed, 75 insertions(+), 291 deletions(-) create mode 100644 app/src/main/java/com/keylesspalace/tusky/entity/Session.java delete mode 100644 app/src/main/java/com/keylesspalace/tusky/service/PushNotificationService.java diff --git a/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java b/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java index d01eb28f..da1656fc 100644 --- a/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java +++ b/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java @@ -31,6 +31,7 @@ import android.view.Menu; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.keylesspalace.tusky.entity.Session; import com.keylesspalace.tusky.json.SpannedTypeAdapter; import com.keylesspalace.tusky.json.StringWithEmoji; import com.keylesspalace.tusky.json.StringWithEmojiTypeAdapter; @@ -162,8 +163,9 @@ public class BaseActivity extends AppCompatActivity { protected void createTuskyApi() { Retrofit retrofit = new Retrofit.Builder() - .baseUrl("https://" + getString(R.string.tusky_api_domain)) + .baseUrl("http://" + getString(R.string.tusky_api_domain) + ":8080") .client(OkHttpUtils.getCompatibleClient()) + .addConverterFactory(GsonConverterFactory.create()) .build(); tuskyApi = retrofit.create(TuskyApi.class); @@ -172,7 +174,7 @@ public class BaseActivity extends AppCompatActivity { protected void createPushNotificationClient() { // TODO: Switch to ssl:// when TLS support is added. pushNotificationClient = new PushNotificationClient(getApplicationContext(), - "tcp://" + getString(R.string.tusky_api_domain)); + "tcp://" + getString(R.string.tusky_api_domain) + ":8000"); } protected void redirectIfNotLoggedIn() { @@ -212,6 +214,7 @@ public class BaseActivity extends AppCompatActivity { retrofit2.Response response) { if (response.isSuccessful()) { pushNotificationClient.subscribeToTopic(getPushNotificationTopic()); + pushNotificationClient.connect(); } else { onEnablePushNotificationsFailure(); } @@ -222,7 +225,9 @@ public class BaseActivity extends AppCompatActivity { onEnablePushNotificationsFailure(); } }; - tuskyApi.register(getBaseUrl(), getAccessToken(), pushNotificationClient.getDeviceToken()) + String deviceToken = pushNotificationClient.getDeviceToken(); + Session session = new Session(getDomain(), getAccessToken(), deviceToken); + tuskyApi.register(session) .enqueue(callback); } @@ -247,7 +252,9 @@ public class BaseActivity extends AppCompatActivity { onDisablePushNotificationsFailure(); } }; - tuskyApi.unregister(getBaseUrl(), getAccessToken(), pushNotificationClient.getDeviceToken()) + String deviceToken = pushNotificationClient.getDeviceToken(); + Session session = new Session(getDomain(), getAccessToken(), deviceToken); + tuskyApi.unregister(session) .enqueue(callback); } @@ -256,7 +263,11 @@ public class BaseActivity extends AppCompatActivity { } private String getPushNotificationTopic() { - return String.format("%s/%s/%s", getBaseUrl(), getAccessToken(), - pushNotificationClient.getDeviceToken()); + return String.format("%s/%s/#", getDomain(), getAccessToken()); + } + + private String getDomain() { + return getPrivatePreferences() + .getString("domain", null); } } diff --git a/app/src/main/java/com/keylesspalace/tusky/entity/Session.java b/app/src/main/java/com/keylesspalace/tusky/entity/Session.java new file mode 100644 index 00000000..8a3c5d0b --- /dev/null +++ b/app/src/main/java/com/keylesspalace/tusky/entity/Session.java @@ -0,0 +1,28 @@ +/* Copyright 2017 Andrew Dawson + * + * This file is a part of Tusky. + * + * This program is free software; you can redistribute it and/or modify it under the terms of the + * GNU General Public License as published by the Free Software Foundation; either version 3 of the + * License, or (at your option) any later version. + * + * Tusky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even + * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General + * Public License for more details. + * + * You should have received a copy of the GNU General Public License along with Tusky; if not, + * see . */ + +package com.keylesspalace.tusky.entity; + +public class Session { + public String instanceUrl; + public String accessToken; + public String deviceToken; + + public Session(String instanceUrl, String accessToken, String deviceToken) { + this.instanceUrl = instanceUrl; + this.accessToken = accessToken; + this.deviceToken = deviceToken; + } +} diff --git a/app/src/main/java/com/keylesspalace/tusky/network/TuskyApi.java b/app/src/main/java/com/keylesspalace/tusky/network/TuskyApi.java index 393decb9..24384dcf 100644 --- a/app/src/main/java/com/keylesspalace/tusky/network/TuskyApi.java +++ b/app/src/main/java/com/keylesspalace/tusky/network/TuskyApi.java @@ -15,16 +15,16 @@ package com.keylesspalace.tusky.network; +import com.keylesspalace.tusky.entity.Session; + import okhttp3.ResponseBody; import retrofit2.Call; -import retrofit2.http.FormUrlEncoded; +import retrofit2.http.Body; import retrofit2.http.POST; public interface TuskyApi { - @FormUrlEncoded @POST("/register") - Call register(String instanceUrl, String accessToken, String deviceToken); - @FormUrlEncoded + Call register(@Body Session session); @POST("/unregister") - Call unregister(String instanceUrl, String accessToken, String deviceToken); + Call unregister(@Body Session session); } diff --git a/app/src/main/java/com/keylesspalace/tusky/service/PushNotificationService.java b/app/src/main/java/com/keylesspalace/tusky/service/PushNotificationService.java deleted file mode 100644 index 7db3e124..00000000 --- a/app/src/main/java/com/keylesspalace/tusky/service/PushNotificationService.java +++ /dev/null @@ -1,257 +0,0 @@ -package com.keylesspalace.tusky.service; - -import android.app.Service; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.os.Binder; -import android.os.IBinder; -import android.preference.PreferenceManager; -import android.support.annotation.Nullable; -import android.text.Spanned; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.keylesspalace.tusky.R; -import com.keylesspalace.tusky.entity.Notification; -import com.keylesspalace.tusky.json.SpannedTypeAdapter; -import com.keylesspalace.tusky.json.StringWithEmoji; -import com.keylesspalace.tusky.json.StringWithEmojiTypeAdapter; -import com.keylesspalace.tusky.network.MastodonAPI; -import com.keylesspalace.tusky.util.Log; -import com.keylesspalace.tusky.util.NotificationMaker; -import com.keylesspalace.tusky.util.OkHttpUtils; - -import org.eclipse.paho.android.service.MqttAndroidClient; -import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions; -import org.eclipse.paho.client.mqttv3.IMqttActionListener; -import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; -import org.eclipse.paho.client.mqttv3.IMqttToken; -import org.eclipse.paho.client.mqttv3.MqttCallbackExtended; -import org.eclipse.paho.client.mqttv3.MqttConnectOptions; -import org.eclipse.paho.client.mqttv3.MqttException; -import org.eclipse.paho.client.mqttv3.MqttMessage; - -import java.io.IOException; -import java.util.Locale; -import java.util.UUID; - -import okhttp3.Interceptor; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import retrofit2.Call; -import retrofit2.Callback; -import retrofit2.Response; -import retrofit2.Retrofit; -import retrofit2.converter.gson.GsonConverterFactory; - -public class PushNotificationService extends Service { - private class LocalBinder extends Binder { - PushNotificationService getService() { - return PushNotificationService.this; - } - } - - private static final String TAG = "PushNotificationService"; - private static final String CLIENT_NAME = "TuskyMastodonClient"; - private static final String TOPIC = "tusky/notification"; - private static final int NOTIFY_ID = 666; - - private final IBinder binder = new LocalBinder(); - private MqttAndroidClient mqttAndroidClient; - private MastodonAPI mastodonApi; - - @Override - public void onCreate() { - super.onCreate(); - - // Create the MQTT client. - String clientId = String.format(Locale.getDefault(), "%s/%s/%s", CLIENT_NAME, - System.currentTimeMillis(), UUID.randomUUID().toString()); - String serverUri = getString(R.string.tusky_api_url); - mqttAndroidClient = new MqttAndroidClient(this, serverUri, clientId); - mqttAndroidClient.setCallback(new MqttCallbackExtended() { - @Override - public void connectComplete(boolean reconnect, String serverURI) { - if (reconnect) { - subscribeToTopic(); - } - } - - @Override - public void connectionLost(Throwable cause) { - onConnectionLost(); - } - - @Override - public void messageArrived(String topic, MqttMessage message) throws Exception { - onMessageReceived(new String(message.getPayload())); - } - - @Override - public void deliveryComplete(IMqttDeliveryToken token) { - // This client is read-only, so this is unused. - } - }); - - // Open the MQTT connection. - MqttConnectOptions options = new MqttConnectOptions(); - options.setAutomaticReconnect(true); - options.setCleanSession(false); - try { - mqttAndroidClient.connect(options, null, new IMqttActionListener() { - @Override - public void onSuccess(IMqttToken asyncActionToken) { - DisconnectedBufferOptions options = new DisconnectedBufferOptions(); - options.setBufferEnabled(true); - options.setBufferSize(100); - options.setPersistBuffer(false); - options.setDeleteOldestMessages(false); - mqttAndroidClient.setBufferOpts(options); - onConnectionSuccess(); - subscribeToTopic(); - } - - @Override - public void onFailure(IMqttToken asyncActionToken, Throwable exception) { - onConnectionFailure(); - } - }); - } catch (MqttException e) { - Log.e(TAG, "An exception occurred while connecting. " + e.getMessage()); - onConnectionFailure(); - } - } - - @Override - public void onDestroy() { - super.onDestroy(); - disconnect(); - } - - @Nullable - @Override - public IBinder onBind(Intent intent) { - return binder; - } - - /** Subscribe to the push notification topic. */ - public void subscribeToTopic() { - try { - mqttAndroidClient.subscribe(TOPIC, 0, null, new IMqttActionListener() { - @Override - public void onSuccess(IMqttToken asyncActionToken) { - onConnectionSuccess(); - } - - @Override - public void onFailure(IMqttToken asyncActionToken, Throwable exception) { - onConnectionFailure(); - } - }); - } catch (MqttException e) { - Log.e(TAG, "An exception occurred while subscribing." + e.getMessage()); - onConnectionFailure(); - } - } - - /** Unsubscribe from the push notification topic. */ - public void unsubscribeToTopic() { - try { - mqttAndroidClient.unsubscribe(TOPIC); - } catch (MqttException e) { - Log.e(TAG, "An exception occurred while unsubscribing." + e.getMessage()); - onConnectionFailure(); - } - } - - private void onConnectionSuccess() { - - } - - private void onConnectionFailure() { - - } - - private void onConnectionLost() { - - } - - private void onMessageReceived(String message) { - String notificationId = message; // TODO: finalize the form the messages will be received - - Log.d(TAG, "Notification received: " + notificationId); - - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences( - getApplicationContext()); - boolean enabled = preferences.getBoolean("notificationsEnabled", true); - if (!enabled) { - return; - } - - createMastodonAPI(); - - mastodonApi.notification(notificationId).enqueue(new Callback() { - @Override - public void onResponse(Call call, Response response) { - if (response.isSuccessful()) { - NotificationMaker.make(PushNotificationService.this, NOTIFY_ID, - response.body()); - } - } - - @Override - public void onFailure(Call call, Throwable t) {} - }); - } - - /** Disconnect from the MQTT broker. */ - public void disconnect() { - try { - mqttAndroidClient.disconnect(); - } catch (MqttException ex) { - Log.e(TAG, "An exception occurred while disconnecting."); - onDisconnectFailed(); - } - } - - private void onDisconnectFailed() { - - } - - private void createMastodonAPI() { - SharedPreferences preferences = getSharedPreferences( - getString(R.string.preferences_file_key), Context.MODE_PRIVATE); - final String domain = preferences.getString("domain", null); - final String accessToken = preferences.getString("accessToken", null); - - OkHttpClient okHttpClient = OkHttpUtils.getCompatibleClientBuilder() - .addInterceptor(new Interceptor() { - @Override - public okhttp3.Response intercept(Chain chain) throws IOException { - Request originalRequest = chain.request(); - - Request.Builder builder = originalRequest.newBuilder() - .header("Authorization", String.format("Bearer %s", accessToken)); - - Request newRequest = builder.build(); - - return chain.proceed(newRequest); - } - }) - .build(); - - Gson gson = new GsonBuilder() - .registerTypeAdapter(Spanned.class, new SpannedTypeAdapter()) - .registerTypeAdapter(StringWithEmoji.class, new StringWithEmojiTypeAdapter()) - .create(); - - Retrofit retrofit = new Retrofit.Builder() - .baseUrl("https://" + domain) - .client(okHttpClient) - .addConverterFactory(GsonConverterFactory.create(gson)) - .build(); - - mastodonApi = retrofit.create(MastodonAPI.class); - } -} diff --git a/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java b/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java index 40150bb2..259704f8 100644 --- a/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java +++ b/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java @@ -105,8 +105,21 @@ public class PushNotificationClient { // This client is read-only, so this is unused. } }); + } + + private void flushQueuedActions() { + while (!queuedActions.isEmpty()) { + QueuedAction action = queuedActions.pop(); + switch (action.type) { + case SUBSCRIBE: subscribeToTopic(action.topic); break; + case UNSUBSCRIBE: unsubscribeToTopic(action.topic); break; + case DISCONNECT: disconnect(); break; + } + } + } - // Open the MQTT connection. + /** Connect to the MQTT broker. */ + public void connect() { MqttConnectOptions options = new MqttConnectOptions(); options.setAutomaticReconnect(true); options.setCleanSession(false); @@ -140,20 +153,21 @@ public class PushNotificationClient { } }); } catch (MqttException e) { - Log.e(TAG, "An exception occurred while connecting. " + e.getMessage()); + Log.e(TAG, "An exception occurred while connecpting. " + e.getMessage()); onConnectionFailure(); } } - private void flushQueuedActions() { - while (!queuedActions.isEmpty()) { - QueuedAction action = queuedActions.pop(); - switch (action.type) { - case SUBSCRIBE: subscribeToTopic(action.topic); break; - case UNSUBSCRIBE: unsubscribeToTopic(action.topic); break; - case DISCONNECT: disconnect(); break; - } - } + private void onConnectionSuccess() { + Log.v(TAG, "The connection succeeded."); + } + + private void onConnectionFailure() { + Log.v(TAG, "The connection failed."); + } + + private void onConnectionLost() { + Log.v(TAG, "The connection was lost."); } /** Disconnect from the MQTT broker. */ @@ -215,18 +229,6 @@ public class PushNotificationClient { } } - private void onConnectionSuccess() { - Log.v(TAG, "The connection succeeded."); - } - - private void onConnectionFailure() { - Log.v(TAG, "The connection failed."); - } - - private void onConnectionLost() { - Log.v(TAG, "The connection was lost."); - } - private void onMessageReceived(final Context context, String message) { String notificationId = message; // TODO: finalize the form the messages will be received From 5487e8ce7ce8f2712fc17dd8c78682d501cfba00 Mon Sep 17 00:00:00 2001 From: Vavassor Date: Sun, 21 May 2017 22:21:23 -0400 Subject: [PATCH 6/9] First notification received successfully from the wryk/tusky-api prototype! --- .../com/keylesspalace/tusky/BaseActivity.java | 2 +- .../tusky/fragment/NotificationsFragment.java | 3 - .../tusky/util/PushNotificationClient.java | 68 ++----------------- 3 files changed, 6 insertions(+), 67 deletions(-) diff --git a/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java b/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java index da1656fc..97bbebec 100644 --- a/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java +++ b/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java @@ -174,7 +174,7 @@ public class BaseActivity extends AppCompatActivity { protected void createPushNotificationClient() { // TODO: Switch to ssl:// when TLS support is added. pushNotificationClient = new PushNotificationClient(getApplicationContext(), - "tcp://" + getString(R.string.tusky_api_domain) + ":8000"); + "tcp://" + getString(R.string.tusky_api_domain) + ":1883"); } protected void redirectIfNotLoggedIn() { diff --git a/app/src/main/java/com/keylesspalace/tusky/fragment/NotificationsFragment.java b/app/src/main/java/com/keylesspalace/tusky/fragment/NotificationsFragment.java index 234ece7f..bef04290 100644 --- a/app/src/main/java/com/keylesspalace/tusky/fragment/NotificationsFragment.java +++ b/app/src/main/java/com/keylesspalace/tusky/fragment/NotificationsFragment.java @@ -233,9 +233,6 @@ public class NotificationsFragment extends SFragment implements } else { adapter.update(notifications); } - for (Notification notification : notifications) { - Log.d(TAG, "id: " + notification.id); - } if (notifications.size() == 0 && adapter.getItemCount() == 1) { adapter.setFooterState(NotificationsAdapter.FooterState.EMPTY); } else if (fromId != null) { diff --git a/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java b/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java index 259704f8..1d7741a3 100644 --- a/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java +++ b/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java @@ -2,18 +2,15 @@ package com.keylesspalace.tusky.util; import android.app.NotificationManager; import android.content.Context; -import android.content.SharedPreferences; import android.support.annotation.NonNull; import android.text.Spanned; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import com.keylesspalace.tusky.R; import com.keylesspalace.tusky.entity.Notification; import com.keylesspalace.tusky.json.SpannedTypeAdapter; import com.keylesspalace.tusky.json.StringWithEmoji; import com.keylesspalace.tusky.json.StringWithEmojiTypeAdapter; -import com.keylesspalace.tusky.network.MastodonAPI; import org.eclipse.paho.android.service.MqttAndroidClient; import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions; @@ -26,20 +23,9 @@ import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; -import java.io.IOException; -import java.io.InputStream; import java.util.ArrayDeque; import java.util.ArrayList; -import okhttp3.Interceptor; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import retrofit2.Call; -import retrofit2.Callback; -import retrofit2.Response; -import retrofit2.Retrofit; -import retrofit2.converter.gson.GsonConverterFactory; - import static android.content.Context.NOTIFICATION_SERVICE; public class PushNotificationClient { @@ -67,7 +53,6 @@ public class PushNotificationClient { } private MqttAndroidClient mqttAndroidClient; - private MastodonAPI mastodonApi; private ArrayDeque queuedActions; private ArrayList subscribedTopics; @@ -148,7 +133,8 @@ public class PushNotificationClient { @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { - Log.e(TAG, "An exception occurred while connecting. " + exception.getMessage()); + Log.e(TAG, "An exception occurred while connecting. " + exception.getMessage() + + " " + exception.getCause()); onConnectionFailure(); } }); @@ -230,59 +216,15 @@ public class PushNotificationClient { } private void onMessageReceived(final Context context, String message) { - String notificationId = message; // TODO: finalize the form the messages will be received - - Log.v(TAG, "Notification received: " + notificationId); - - createMastodonAPI(context); - - mastodonApi.notification(notificationId).enqueue(new Callback() { - @Override - public void onResponse(Call call, Response response) { - if (response.isSuccessful()) { - NotificationMaker.make(context, NOTIFY_ID, response.body()); - } - } - - @Override - public void onFailure(Call call, Throwable t) {} - }); - } - - private void createMastodonAPI(Context context) { - SharedPreferences preferences = context.getSharedPreferences( - context.getString(R.string.preferences_file_key), Context.MODE_PRIVATE); - final String domain = preferences.getString("domain", null); - final String accessToken = preferences.getString("accessToken", null); - - OkHttpClient okHttpClient = OkHttpUtils.getCompatibleClientBuilder() - .addInterceptor(new Interceptor() { - @Override - public okhttp3.Response intercept(Chain chain) throws IOException { - Request originalRequest = chain.request(); - - Request.Builder builder = originalRequest.newBuilder() - .header("Authorization", String.format("Bearer %s", accessToken)); - - Request newRequest = builder.build(); - - return chain.proceed(newRequest); - } - }) - .build(); + Log.v(TAG, "Notification received: " + message); Gson gson = new GsonBuilder() .registerTypeAdapter(Spanned.class, new SpannedTypeAdapter()) .registerTypeAdapter(StringWithEmoji.class, new StringWithEmojiTypeAdapter()) .create(); + Notification notification = gson.fromJson(message, Notification.class); - Retrofit retrofit = new Retrofit.Builder() - .baseUrl("https://" + domain) - .client(okHttpClient) - .addConverterFactory(GsonConverterFactory.create(gson)) - .build(); - - mastodonApi = retrofit.create(MastodonAPI.class); + NotificationMaker.make(context, NOTIFY_ID, notification); } public void clearNotifications(Context context) { From efaf0f50b5ec96ac29cf43cc8c858f6d8ab7b9a1 Mon Sep 17 00:00:00 2001 From: Vavassor Date: Mon, 22 May 2017 02:05:37 -0400 Subject: [PATCH 7/9] Adds TLS to the push notification client (keystore_tusky_api is omitted). --- .../com/keylesspalace/tusky/BaseActivity.java | 15 +++++++-------- .../tusky/util/PushNotificationClient.java | 6 +++--- app/src/main/res/values/donottranslate.xml | 2 +- 3 files changed, 11 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java b/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java index 97bbebec..c6d27244 100644 --- a/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java +++ b/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java @@ -163,7 +163,7 @@ public class BaseActivity extends AppCompatActivity { protected void createTuskyApi() { Retrofit retrofit = new Retrofit.Builder() - .baseUrl("http://" + getString(R.string.tusky_api_domain) + ":8080") + .baseUrl("https://" + getString(R.string.tusky_api_domain) + ":8080") .client(OkHttpUtils.getCompatibleClient()) .addConverterFactory(GsonConverterFactory.create()) .build(); @@ -172,9 +172,8 @@ public class BaseActivity extends AppCompatActivity { } protected void createPushNotificationClient() { - // TODO: Switch to ssl:// when TLS support is added. pushNotificationClient = new PushNotificationClient(getApplicationContext(), - "tcp://" + getString(R.string.tusky_api_domain) + ":1883"); + "ssl://" + getString(R.string.tusky_api_domain) + ":8883"); } protected void redirectIfNotLoggedIn() { @@ -214,15 +213,15 @@ public class BaseActivity extends AppCompatActivity { retrofit2.Response response) { if (response.isSuccessful()) { pushNotificationClient.subscribeToTopic(getPushNotificationTopic()); - pushNotificationClient.connect(); + pushNotificationClient.connect(BaseActivity.this); } else { - onEnablePushNotificationsFailure(); + onEnablePushNotificationsFailure(response.message()); } } @Override public void onFailure(Call call, Throwable t) { - onEnablePushNotificationsFailure(); + onEnablePushNotificationsFailure(t.getMessage()); } }; String deviceToken = pushNotificationClient.getDeviceToken(); @@ -231,8 +230,8 @@ public class BaseActivity extends AppCompatActivity { .enqueue(callback); } - private void onEnablePushNotificationsFailure() { - Log.e(TAG, "Enabling push notifications failed."); + private void onEnablePushNotificationsFailure(String message) { + Log.e(TAG, "Enabling push notifications failed. " + message); } protected void disablePushNotifications() { diff --git a/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java b/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java index 1d7741a3..f3df738f 100644 --- a/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java +++ b/app/src/main/java/com/keylesspalace/tusky/util/PushNotificationClient.java @@ -7,6 +7,7 @@ import android.text.Spanned; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.keylesspalace.tusky.R; import com.keylesspalace.tusky.entity.Notification; import com.keylesspalace.tusky.json.SpannedTypeAdapter; import com.keylesspalace.tusky.json.StringWithEmoji; @@ -23,6 +24,7 @@ import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; +import java.io.InputStream; import java.util.ArrayDeque; import java.util.ArrayList; @@ -104,12 +106,11 @@ public class PushNotificationClient { } /** Connect to the MQTT broker. */ - public void connect() { + public void connect(Context context) { MqttConnectOptions options = new MqttConnectOptions(); options.setAutomaticReconnect(true); options.setCleanSession(false); try { - /* String password = context.getString(R.string.tusky_api_keystore_password); InputStream keystore = context.getResources().openRawResource(R.raw.keystore_tusky_api); try { @@ -117,7 +118,6 @@ public class PushNotificationClient { } finally { IOUtils.closeQuietly(keystore); } - */ mqttAndroidClient.connect(options).setActionCallback(new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { diff --git a/app/src/main/res/values/donottranslate.xml b/app/src/main/res/values/donottranslate.xml index e6982534..6d61f3f3 100644 --- a/app/src/main/res/values/donottranslate.xml +++ b/app/src/main/res/values/donottranslate.xml @@ -2,7 +2,7 @@ Tusky https://tusky.keylesspalace.com - tuskyapi.keylesspalace.com + apitusky.keylesspalace.com your_password_here oauth2redirect From dfe9cae90b25d175dbb0ca6b949c7490a6eab833 Mon Sep 17 00:00:00 2001 From: Vavassor Date: Tue, 23 May 2017 19:48:54 -0400 Subject: [PATCH 8/9] pretty much finishes the prototype --- app/src/main/java/com/keylesspalace/tusky/BaseActivity.java | 4 ++-- app/src/main/res/values/donottranslate.xml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java b/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java index c6d27244..fa569fa8 100644 --- a/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java +++ b/app/src/main/java/com/keylesspalace/tusky/BaseActivity.java @@ -163,7 +163,7 @@ public class BaseActivity extends AppCompatActivity { protected void createTuskyApi() { Retrofit retrofit = new Retrofit.Builder() - .baseUrl("https://" + getString(R.string.tusky_api_domain) + ":8080") + .baseUrl("https://" + getString(R.string.tusky_api_url)) .client(OkHttpUtils.getCompatibleClient()) .addConverterFactory(GsonConverterFactory.create()) .build(); @@ -173,7 +173,7 @@ public class BaseActivity extends AppCompatActivity { protected void createPushNotificationClient() { pushNotificationClient = new PushNotificationClient(getApplicationContext(), - "ssl://" + getString(R.string.tusky_api_domain) + ":8883"); + "ssl://" + getString(R.string.tusky_api_url) + ":8883"); } protected void redirectIfNotLoggedIn() { diff --git a/app/src/main/res/values/donottranslate.xml b/app/src/main/res/values/donottranslate.xml index 6d61f3f3..ad2d3b37 100644 --- a/app/src/main/res/values/donottranslate.xml +++ b/app/src/main/res/values/donottranslate.xml @@ -2,7 +2,7 @@ Tusky https://tusky.keylesspalace.com - apitusky.keylesspalace.com + apitusky.keylesspalace.com your_password_here oauth2redirect From b4e8fe9a78cd54a74ed73c0f26cf817c3e55d2f6 Mon Sep 17 00:00:00 2001 From: Vavassor Date: Tue, 23 May 2017 20:13:49 -0400 Subject: [PATCH 9/9] release 1.1.4-beta.1 --- app/build.gradle | 4 ++-- app/src/main/AndroidManifest.xml | 1 - 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index cb33758a..6453f7c5 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -7,8 +7,8 @@ android { applicationId "com.keylesspalace.tusky" minSdkVersion 15 targetSdkVersion 25 - versionCode 16 - versionName "1.1.3" + versionCode 17 + versionName "1.1.4-beta.1" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" vectorDrawables.useSupportLibrary true } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index cbe15faa..c30a26ca 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -9,7 +9,6 @@ -