diff --git a/build.gradle b/build.gradle
index 9bf5a8c..a7f57f4 100644
--- a/build.gradle
+++ b/build.gradle
@@ -32,13 +32,16 @@ dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.squareup.okhttp:okhttp:2.0.0'
- compile 'com.squareup.retrofit:retrofit:1.9.0'
+ compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.google.code.gson:gson:2.4'
- compile 'com.google.android.gms:play-services-gcm:8.4.0'
+ compile 'com.google.firebase:firebase-messaging:9.8.0'
+ compile 'com.google.android.gms:play-services:9.8.0'
compile 'com.github.fge:json-patch:1.9'
compile 'com.snappydb:snappydb-lib:0.5.0'
compile 'com.esotericsoftware.kryo:kryo:2.24.0'
compile 'com.github.nkzawa:socket.io-client:0.5.0'
+ compile 'com.squareup.retrofit2:converter-gson:2.1.0'
+ compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'
}
if(file("..//upload_archives_task.gradle").exists()) {
@@ -52,3 +55,4 @@ if(file("..//upload_archives_task.gradle").exists()) {
apply plugin: 'signing'
apply from: "..//upload_archives_task.gradle"
}
+
diff --git a/src/main/java/io/telepat/sdk/Telepat.java b/src/main/java/io/telepat/sdk/Telepat.java
index c5ae030..3f7ab0f 100644
--- a/src/main/java/io/telepat/sdk/Telepat.java
+++ b/src/main/java/io/telepat/sdk/Telepat.java
@@ -2,12 +2,12 @@
import android.content.Context;
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.GoogleApiAvailability;
+import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
@@ -15,12 +15,12 @@
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
-import io.telepat.BuildConfig;
import io.telepat.sdk.data.TelepatInternalDB;
import io.telepat.sdk.data.TelepatSnappyDb;
import io.telepat.sdk.models.Channel;
import io.telepat.sdk.models.ContextUpdateListener;
import io.telepat.sdk.models.OnChannelEventListener;
+import io.telepat.sdk.models.TelepatCallback;
import io.telepat.sdk.models.TelepatContext;
import io.telepat.sdk.models.TelepatProxyRequest;
import io.telepat.sdk.models.TelepatProxyResponse;
@@ -34,673 +34,711 @@
import io.telepat.sdk.networking.requests.RegisterDeviceRequest;
import io.telepat.sdk.networking.requests.RegisterFacebookUserRequest;
import io.telepat.sdk.networking.requests.RegisterTwitterUserRequest;
+import io.telepat.sdk.networking.responses.ApiError;
import io.telepat.sdk.networking.responses.ContextsApiResponse;
import io.telepat.sdk.networking.responses.GenericApiResponse;
import io.telepat.sdk.networking.responses.TelepatCountCallback;
-import io.telepat.sdk.networking.transports.gcm.GcmRegistrar;
import io.telepat.sdk.utilities.TelepatConstants;
import io.telepat.sdk.utilities.TelepatLogger;
-import retrofit.Callback;
-import retrofit.RestAdapter;
-import retrofit.RetrofitError;
-import retrofit.android.AndroidLog;
-import retrofit.client.Response;
+import okhttp3.OkHttpClient;
+import okhttp3.logging.HttpLoggingInterceptor;
+import retrofit2.Call;
+import retrofit2.Callback;
+import retrofit2.Response;
+import retrofit2.Retrofit;
+import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by Andrei Marinescu, catalinivan on 10/03/15.
- *
+ *
* Telepat Main Orchestrator
*/
-public final class Telepat
-{
- /**
- * Telepat singleton instance
- */
- private static Telepat mInstance;
- /**
- * Reference to the application context
- */
- private Context mContext;
- /**
- * References to the currently available Telepat contexts
- */
- private HashMap mServerContexts;
- /**
- * Reference to a Telepat Sync API client
- */
- private OctopusApi apiClient;
- /**
- * Retrofit RequestInterceptor implementation for injecting the proper authentication headers
- */
- private OctopusRequestInterceptor requestInterceptor;
- /**
- * Internal storage reference
- */
- private TelepatInternalDB internalDB;
- /**
- * Locally registered Channel instances
- */
- private HashMap subscriptions = new HashMap<>();
- /**
- * Context update listener array
- */
- private CopyOnWriteArrayList contextUpdateListeners = new CopyOnWriteArrayList<>();
- /**
- * Unique device identifier
- */
- private String localUdid;
-
- /**
- * Configured Telepat Application ID
- */
- private String appId;
-
- private Telepat() { }
-
- /**
- *
- * @return Returns a reference to the singleton instance
- */
- public static Telepat getInstance()
- {
- if (mInstance == null) {
- mInstance = new Telepat();
- }
-
- return mInstance;
- }
-
- /**
- * Get access to an instance controlling the internal storage DB
- * @return An instance of a class implementing TelepatInternalDB
- */
- public TelepatInternalDB getDBInstance() {
- return internalDB;
- }
+public final class Telepat {
+
+ public static boolean isDebugMode = false;
+
+ /**
+ * Telepat singleton instance
+ */
+ private static Telepat mInstance;
+ /**
+ * Reference to the application context
+ */
+ private Context mContext;
+ /**
+ * References to the currently available Telepat contexts
+ */
+ private HashMap mServerContexts;
+ /**
+ * Reference to a Telepat Sync API client
+ */
+ private OctopusApi apiClient;
+ /**
+ * Retrofit RequestInterceptor implementation for injecting the proper authentication headers
+ */
+ private OctopusRequestInterceptor requestInterceptor;
+ /**
+ * Internal storage reference
+ */
+ private TelepatInternalDB internalDB;
+ /**
+ * Locally registered Channel instances
+ */
+ private HashMap subscriptions = new HashMap<>();
+ /**
+ * Context update listener array
+ */
+ private CopyOnWriteArrayList contextUpdateListeners = new CopyOnWriteArrayList<>();
+ /**
+ * Unique device identifier
+ */
+ private String localUdid;
+
+ /**
+ * Configured Telepat Application ID
+ */
+ private String appId;
+ public Retrofit retrofit;
+
+ private Telepat() {
+ }
+
+ /**
+ * @return Returns a reference to the singleton instance
+ */
+ public static Telepat getInstance() {
+ if (mInstance == null) {
+ mInstance = new Telepat();
+ }
+
+ return mInstance;
+ }
+
+ /**
+ * Get access to an instance controlling the internal storage DB
+ *
+ * @return An instance of a class implementing TelepatInternalDB
+ */
+ public TelepatInternalDB getDBInstance() {
+ return internalDB;
+ }
/**
* Get access to an Retrofit instance that is able to communicate with the Telepat Sync API
+ *
* @return An OctopusApi
instance
*/
- public OctopusApi getAPIInstance() { return apiClient; }
-
- @SuppressWarnings("unused")
- public void emptyDB(Context ctx) {
- if(internalDB == null) {
- internalDB = new TelepatSnappyDb(ctx);
- }
- internalDB.empty();
- }
-
- public void initialize(Context context,
- final String telepatEndpoint,
- final String clientApiKey,
- final String clientAppId,
- String senderId) {
- mContext = context.getApplicationContext();
- internalDB = new TelepatSnappyDb(context);
- appId = clientAppId;
- TelepatConstants.GCM_SENDER_ID = senderId;
- initHTTPClient(telepatEndpoint, clientApiKey, clientAppId);
- new GcmRegistrar(mContext).initGcmRegistration();
-
- String JWTtoken = (String) internalDB.getOperationsData(TelepatConstants.JWT_KEY, null, String.class);
- if(JWTtoken != null) {
- requestInterceptor.setAuthorizationToken(JWTtoken);
- refreshToken(null);
- }
-
- requestContexts();
-// String registrationId = (String) Telepat.getInstance()
-// .getDBInstance()
-// .getOperationsData(GcmRegistrar.PROPERTY_REG_ID, "", String.class);
- TelepatLogger.log("Initialized Telepat Android SDK version " + BuildConfig.VERSION_NAME);
- }
+ public OctopusApi getAPIInstance() {
+ return apiClient;
+ }
+ @SuppressWarnings("unused")
+ public void emptyDB(Context ctx) {
+ if (internalDB == null) {
+ internalDB = new TelepatSnappyDb(ctx);
+ }
+ internalDB.empty();
+ }
+
+ public void initialize(Context context,
+ final String telepatEndpoint,
+ final String clientApiKey,
+ final String clientAppId,
+ String senderId) {
+
+ try {
+ if (isGooglePlayServicesAvailable(context)) {
+ mContext = context.getApplicationContext();
+ internalDB = new TelepatSnappyDb(context);
+ appId = clientAppId;
+ TelepatConstants.GCM_SENDER_ID = senderId;
+ initHTTPClient(telepatEndpoint, clientApiKey, clientAppId);
+ // new GcmRegistrar(mContext).initGcmRegistration();
+
+ String JWTtoken = (String) internalDB.getOperationsData(TelepatConstants.JWT_KEY, null, String.class);
+ if (JWTtoken != null) {
+ requestInterceptor.setAuthorizationToken(JWTtoken);
+ refreshToken(null);
+ }
+
+ requestContexts();
+ // String registrationId = (String) Telepat.getInstance()
+ // .getDBInstance()
+ // .getOperationsData(GcmRegistrar.PROPERTY_REG_ID, "", String.class);
+ // TelepatLogger.log("Initialized Telepat Android SDK version " + BuildConfig.VERSION_NAME);
+ }
+ } catch (GooglePlayServicesNotAvailableException e) {
+ e.printStackTrace();
+ }
+ }
+
+
+ public boolean isGooglePlayServicesAvailable(Context context) throws GooglePlayServicesNotAvailableException {
+ GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
+ int status = googleApiAvailability.isGooglePlayServicesAvailable(context);
+ if (status != ConnectionResult.SUCCESS) {
+ throw new GooglePlayServicesNotAvailableException(status);
+ }
+ return true;
+ }
/**
* Close the current Telepat instance. You should reinitialize the Telepat SDK before doing
* additional work.
*/
- @SuppressWarnings("unused")
- public void destroy() {
- internalDB.close();
- }
+ @SuppressWarnings("unused")
+ public void destroy() {
+ internalDB.close();
+ }
/**
* Configures the OctopusApi instance with relevant credentials
+ *
* @param clientApiKey A string containing a Telepat client API key
- * @param clientAppId A string containing the corresponding Telepat application ID
+ * @param clientAppId A string containing the corresponding Telepat application ID
*/
- private void initHTTPClient(String telepatEndpoint, String clientApiKey, final String clientAppId) {
- requestInterceptor = new OctopusRequestInterceptor(clientApiKey, clientAppId);
+ private void initHTTPClient(String telepatEndpoint, String clientApiKey, final String clientAppId) {
+ requestInterceptor = new OctopusRequestInterceptor(clientApiKey, clientAppId);
- RestAdapter.Builder rBuilder = new RestAdapter.Builder()
- .setEndpoint(telepatEndpoint)
- .setRequestInterceptor(requestInterceptor);
- if(TelepatConstants.RETROFIT_DEBUG_ENABLED)
- rBuilder.setLogLevel(RestAdapter.LogLevel.FULL)
- .setLog(new AndroidLog(TelepatConstants.TAG));
+ HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
+ loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
- RestAdapter restAdapter = rBuilder.build();
- apiClient = restAdapter.create(OctopusApi.class);
- }
+ OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
+ okHttpClient.interceptors().add(requestInterceptor);
+ okHttpClient.interceptors().add(loggingInterceptor);
+
+ retrofit = new Retrofit.Builder()
+ .client(okHttpClient.build())
+ .addConverterFactory(GsonConverterFactory.create())
+ .baseUrl(telepatEndpoint).build();
+ apiClient = retrofit.create(OctopusApi.class);
+ }
/**
* Send the Telepat Sync API a device registration request
- * @param regId A GCM token for the current device
+ *
+ * @param regId A GCM token for the current device
* @param shouldUpdateBackend If true, an update should be sent to the Telepat cloud instance
* regardless of the state of the token (new/already sent)
*/
- public void registerDevice(String regId, boolean shouldUpdateBackend)
- {
- String udid = (String) internalDB.getOperationsData(TelepatConstants.UDID_KEY,
- "",
- String.class);
- if(!udid.isEmpty()) {
- for (ContextUpdateListener listener : Telepat.this.contextUpdateListeners) {
- listener.deviceRegisterSuccess();
- }
- return;
- }
-
- if(udid.isEmpty() || shouldUpdateBackend) {
- RegisterDeviceRequest request = new RegisterDeviceRequest(regId);
- apiClient.registerDevice(request.getParams(), new Callback() {
- @Override
- public void success(GenericApiResponse octopusResponse,
- retrofit.client.Response response) {
- TelepatLogger.log("Register device success");
- if (octopusResponse.status == 200 && octopusResponse.content.get("identifier") != null) {
- requestInterceptor.setUdid((String)octopusResponse.content.get("identifier"));
- internalDB.setOperationsData(TelepatConstants.UDID_KEY,
- octopusResponse.content.get("identifier"));
- for (ContextUpdateListener listener : Telepat.this.contextUpdateListeners) {
- listener.deviceRegisterSuccess();
- }
- TelepatLogger.log("Received Telepat UDID: " + octopusResponse.content.get("identifier"));
- }
- }
-
- @Override
- public void failure(RetrofitError error) {
- TelepatLogger.log("Register device failure.");
-
- }
- });
- } //else {
- //TODO send update
- //}
- }
+ public void registerDevice(final String regId, boolean shouldUpdateBackend) {
+ String udid = (String) internalDB.getOperationsData(TelepatConstants.UDID_KEY,
+ "",
+ String.class);
+ if (!udid.isEmpty()) {
+ for (ContextUpdateListener listener : Telepat.this.contextUpdateListeners) {
+ listener.deviceRegisterSuccess();
+ }
+ return;
+ }
+
+ if (udid.isEmpty() || shouldUpdateBackend) {
+ RegisterDeviceRequest request = new RegisterDeviceRequest(regId);
+ Call call = apiClient.registerDevice(request.getParams());
+ call.enqueue(new TelepatCallback() {
+ @Override
+ public void success(GenericApiResponse apiResponse) {
+ TelepatLogger.log("Register device success");
+ if (apiResponse.status == 200 && apiResponse.getContent().get("identifier") != null) {
+ requestInterceptor.setUdid((String) apiResponse.getContent().get("identifier"));
+ internalDB.setOperationsData(TelepatConstants.UDID_KEY,
+ apiResponse.getContent().get("identifier"));
+ for (ContextUpdateListener listener : Telepat.this.contextUpdateListeners) {
+ listener.deviceRegisterSuccess();
+ }
+ TelepatLogger.log("Received Telepat UDID: " + apiResponse.getContent().get("identifier"));
+ }
+ }
+
+ @Override
+ public void failure(ApiError error) {
+ TelepatLogger.log("Register device failure. " + error.message());
+ }
+
+ });
+ } //else {
+ //TODO send update
+ //}
+ }
/**
* Retrieve the currently active contexts for the current Telepat application
*/
- private void requestContexts()
- {
- apiClient.updateContexts(new Callback() {
- @Override
- public void success(ContextsApiResponse contextMap,
- retrofit.client.Response response) {
- updateContexts(contextMap);
- }
-
- @Override
- public void failure(RetrofitError error) {
- //TODO: bubble errors to the User level
- if (error != null && error.getResponse() != null) {
- if (error.getResponse().getStatus() == 404) {
- apiClient.updateContextsCompat(new Callback() {
- @Override
- public void success(ContextsApiResponse contextsApiResponse, Response response) {
- updateContexts(contextsApiResponse);
- }
-
- @Override
- public void failure(RetrofitError error) {
- TelepatLogger.log("Failed to get contexts" + error.getMessage());
- }
- });
- } else {
- TelepatLogger.log("Failed to get contexts" + error.getMessage());
- }
- } else {
- TelepatLogger.log("Failed to get contexts");
- }
- }
- });
- }
-
- private void updateContexts(ContextsApiResponse contextMap) {
- if (contextMap == null) return;
- if (mServerContexts == null) mServerContexts = new HashMap<>();
- for (TelepatContext ctx : contextMap.content)
- mServerContexts.put(ctx.getId(), ctx);
- for (ContextUpdateListener listener : Telepat.this.contextUpdateListeners) {
- listener.contextInitializeSuccess();
- }
- TelepatLogger.log("Retrieved " + contextMap.content.size() + " contexts");
- }
-
- /**
- * Send a Telepat Sync API call for registering a user with the Facebook auth provider
- * @param fbToken A Facebook OAUTH token
- */
- @Deprecated
- @SuppressWarnings("unused")
- public void register(final String fbToken, final TelepatRequestListener loginListener) {
- registerFacebookUser(fbToken, loginListener);
- }
-
- /**
- * Send a Telepat Sync API call for registering a user with the Facebook auth provider
- * @param fbToken A Facebook OAUTH token
- */
- @SuppressWarnings("unused")
- public void registerFacebookUser(final String fbToken, final TelepatRequestListener loginListener)
- {
- internalDB.setOperationsData(TelepatConstants.FB_TOKEN_KEY, fbToken);
- apiClient.registerUserFacebook(new RegisterFacebookUserRequest(fbToken).getParams(), new Callback