diff --git a/README.md b/README.md
index c3e5e4b..dea8686 100644
--- a/README.md
+++ b/README.md
@@ -11,7 +11,6 @@ Human API Cordova Plugin for Android & IOS
cordova plugin add cordova-plugin-humanapi
-
Documentation
For a detailed documentation 📔, please have a look at the [Wiki](https://github.com/vikramezhil/cordova-plugin-humanapi/wiki).
@@ -28,24 +27,26 @@ For a detailed documentation 📔, please have a look at the [Wiki](https://gith
Usage
+Authentication
+
Cordova, Ionic 1
- window.plugin.humanapi.trigger("init", "CLIENT_ID", "CLIENT_SECRET", "USER_ID", "PUBLIC_TOKEN", "ACCESS_TOKEN", function(result) {
- alert("Result = " + JSON.stringify(result))
+ window.plugin.humanapi.auth("CLIENT_ID", "CLIENT_SECRET", "USER_ID", "PUBLIC_TOKEN", "ACCESS_TOKEN", function(result) {
+ alert("Result = " + result)
}, function(error) {
- alert("Error = " + JSON.stringify(error))
+ alert("Error = " + error)
})
Ionic 2+
var humanAPI: any = window
- humanAPI.plugin.humanapi.trigger("init", "CLIENT_ID", "CLIENT_SECRET", "USER_ID", "PUBLIC_TOKEN", "ACCESS_TOKEN", (result) => {
- alert("Result = " + JSON.stringify(result))
+ humanAPI.plugin.humanapi.auth("CLIENT_ID", "CLIENT_SECRET", "USER_ID", "PUBLIC_TOKEN", "ACCESS_TOKEN", (result) => {
+ alert("Result = " + result)
}, (error) => {
- alert("Error = " + JSON.stringify(error))
+ alert("Error = " + error)
})
-Plugin Data Format
+Authentication Data Format
{
clientID: "CLIENT_ID",
@@ -54,97 +55,31 @@ For a detailed documentation 📔, please have a look at the [Wiki](https://gith
humanID: "HUMAN_ID",
sessionToken: "SESSION_TOKEN",
publicToken: "PUBLIC_TOKEN",
- accessToken: "ACCESS_TOKEN"
- humanAPIData: "REFER BELOW",
+ accessToken: "ACCESS_TOKEN",
pluginMsg: "The plugin message if any"
}
-humanAPIData example data, more information can be found [here](https://reference.humanapi.co/v2.1/docs/data-overview)
+Wellness Data
- {
- "userId": "52e20cb2fff56aac62000001",
- "createdAt": "2014-01-24T06:48:18.361Z",
- "bloodGlucose": {
- "id": "52e20cb3fff56aac6200044a",
- "timestamp": "2014-01-23T22:48:19.858Z",
- "source": "glooko",
- "value": 90,
- "unit": "mg/dL"
- },
- "bloodOxygen": {
- "id": "54d1f018810a5ba429951b07",
- "timestamp": "2015-01-26T06:58:37.000Z",
- "source": "withings",
- "value": 99,
- "unit": "SpO2"
- },
- "bloodPressure": {
- "id": "550b8a8e834dd16f259683b1",
- "userId": "52e20cb2fff56aac62000001",
- "timestamp": "2015-03-19T22:48:26.000Z",
- "source": "ihealth",
- "systolic": 117,
- "diastolic": 76,
- "unit": "mmHg",
- "heartRate": 66
- },
- "bmi": {
- "id": "5702fed82add5c0900a6f95a",
- "timestamp": "2016-04-05T06:59:59.000Z",
- "source": "fitbit",
- "value": 23.98,
- "unit": "kg/m2"
- },
- "bodyFat": {
- "id": "562b08ef74a7be0700a0f88d",
- "timestamp": "2015-10-24T03:30:34.000Z",
- "source": "fitbit",
- "value": 21.4,
- "unit": "%"
- },
- "height": {
- "id": "57b531d4856bfe0a00d4cb25",
- "timestamp": "2016-08-18T03:56:04.156Z",
- "source": "fitbit",
- "value": 1730,
- "unit": "mm"
- },
- "heartRate": {
- "id": "550b8a8e834dd16f259683b2",
- "timestamp": "2015-03-19T22:48:26.000Z",
- "source": "ihealth",
- "value": 66,
- "unit": "bpm"
- },
- "weight": {
- "id": "5702fed8dfb2210c00af7405",
- "timestamp": "2016-04-05T06:59:59.000Z",
- "source": "fitbit",
- "value": 71.7,
- "unit": "kg"
- },
- "activitySummary": {
- "id": "5812b6e19e554b0800d8a1f6",
- "date": "2016-10-28",
- "duration": 0,
- "distance": 0,
- "sedentary": 954,
- "light": 0,
- "moderate": 0,
- "vigorous": 0,
- "total": 954,
- "steps": 0,
- "calories": 1113,
- "source": "fitbit"
- },
- "sleepSummary": {
- "id": "540e96b74247c3ea71d671b9",
- "userId": "52e20cb2fff56aac62000001",
- "date": "2014-09-09",
- "source": "fitbit",
- "timeAsleep": 456,
- "timeAwake": 0,
- "updatedAt": "2014-09-11T02:28:27.377Z"
- },
- "humanId": "5dc2527186aaf9de560e5841f1a44bd6"
- }
+Cordova, Ionic 1
+
+ window.plugin.humanapi.execute("WELLNESS_NAME", "ACCESS_TOKEN", function(result) {
+ alert("Result = " + result)
+ }, function(error) {
+ alert("Error = " + error)
+ })
+
+Ionic 2+
+
+ var humanAPI: any = window
+ humanAPI.plugin.humanapi.execute("WELLNESS_NAME", "ACCESS_TOKEN", (result) => {
+ alert("Result = " + result)
+ }, (error) => {
+ alert("Error = " + error)
+ })
+
+Wellness Supported API's & Data Format
+
+Currently the plugin supports 17 wellness API's (excluding Genetic Traits & Genotypes). Please refer for the list of wellness API's and data formats [here](https://reference.humanapi.co/v2.1/reference#wellness-api-introduction)
+
+For plugin examples, please refer [here](https://github.com/vikramezhil/cordova-plugin-humanapi/wiki/6.-API-calls)
diff --git a/package.json b/package.json
index 192b57c..e39a09e 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "cordova-plugin-humanapi",
- "version": "1.0.0",
+ "version": "1.0.1",
"description": "Human API Plugin for Android and IOS",
"cordova": {
"id": "cordova-plugin-humanapi",
@@ -18,13 +18,16 @@
"cordova-android",
"cordova-ios",
"cordova",
+ "cordova-plugin",
"ionic",
+ "ionic-plugin",
"android",
"ios",
"human",
"humanapi",
"human api",
- "human-api"
+ "human-api",
+ "humanapi-plugin"
],
"author": "Vikram Ezhil ",
"license": "Apache 2.0",
diff --git a/plugin.xml b/plugin.xml
index 69a5fdc..805a4dc 100644
--- a/plugin.xml
+++ b/plugin.xml
@@ -42,6 +42,9 @@
+
+
+
@@ -74,5 +77,7 @@
+
+
\ No newline at end of file
diff --git a/src/android/HumanAPIPlugin.java b/src/android/HumanAPIPlugin.java
index 0c83a10..8ff7a9d 100644
--- a/src/android/HumanAPIPlugin.java
+++ b/src/android/HumanAPIPlugin.java
@@ -14,7 +14,8 @@
import android.content.Intent;
import com.github.vikramezhil.cordova.human.HumanAPIActivity;
-import com.github.vikramezhil.cordova.human.HumanAPIActivity.HumanAPIListener;
+import com.github.vikramezhil.cordova.human.HumanAPIService;
+import com.github.vikramezhil.cordova.human.HumanAPIListener;
/**
* HumanAPIPlugin Android Controller Class
@@ -27,9 +28,14 @@ public class HumanAPIPlugin extends CordovaPlugin implements HumanAPIListener {
public static HumanAPIPlugin context;
+ private HumanAPIService humanAPIService;
+
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
context = this;
+
+ // Initializing the human API service
+ humanAPIService = new HumanAPIService(cordova.getActivity().getApplicationContext(), this);
}
@Override
@@ -44,7 +50,7 @@ public void onDestroy() {
//*************************************************************************************
- // Active8mePlugins
+ // Plugin Executions
//*************************************************************************************
@@ -52,8 +58,14 @@ public void onDestroy() {
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
Log.wtf(TAG, "Native Action = " + action);
- if (action.equals("trigger")) {
- this.trigger(callbackContext, args.getString(0), args.getString(1), args.getString(2), args.getString(3), args.getString(4), args.getString(5));
+ if (action == null || action.isEmpty()) {
+ return false;
+ } else if (action.equals("auth")) {
+ this.auth(callbackContext, args.getString(0), args.getString(1), args.getString(2), args.getString(3), args.getString(4));
+
+ return true;
+ } else if (action.equals("execute")) {
+ this.humanAPIService.execute(callbackContext, args.getString(0), args.getString(1));
return true;
}
@@ -70,17 +82,15 @@ public boolean execute(String action, JSONArray args, CallbackContext callbackCo
private CallbackContext humanAPICallbackContext;
/**
- * Triggers Human API
+ * Triggers Human API Authentication
*
- * @param callbackContext The callback context
- * @param triggerType The human API trigger type
* @param clientID The human API client ID
* @param clientSecret The human API client secret
* @param userID The human API user ID
* @param publicToken The human API public token
* @param accessToken The human API access token
*/
- private void trigger(CallbackContext callbackContext, String triggerType, String clientID, String clientSecret, String userID, String publicToken, String accessToken) {
+ private void auth(CallbackContext callbackContext, String clientID, String clientSecret, String userID, String publicToken, String accessToken) {
final CordovaInterface cordova = this.cordova;
// Saving a reference of the human API callback context
@@ -106,11 +116,17 @@ public void run() {
// MARK: HumanAPIListener Methods
@Override
- public void onHumanAPIUpdate(Boolean success, String humanAPIData) {
+ public void onHumanAPIUpdate(CallbackContext callbackContext, Boolean success, String humanAPIData) {
+ PluginResult result = new PluginResult(success ? PluginResult.Status.OK : PluginResult.Status.ERROR, humanAPIData);
+ result.setKeepCallback(true);
+
if(humanAPICallbackContext != null) {
- PluginResult result = new PluginResult(success ? PluginResult.Status.OK : PluginResult.Status.ERROR, humanAPIData);
- result.setKeepCallback(true);
humanAPICallbackContext.sendPluginResult(result);
+ humanAPICallbackContext = null;
+ } else if(callbackContext != null) {
+ callbackContext.sendPluginResult(result);
+ } else {
+ Log.wtf(TAG, "Unable to send back data, callbackContext is null");
}
}
}
diff --git a/src/android/human/HumanAPIActivity.java b/src/android/human/HumanAPIActivity.java
index 863918d..ebd035d 100644
--- a/src/android/human/HumanAPIActivity.java
+++ b/src/android/human/HumanAPIActivity.java
@@ -12,7 +12,6 @@
import org.json.JSONObject;
-import org.apache.cordova.PluginResult;
import org.apache.cordova.CallbackContext;
import com.github.vikramezhil.cordova.HumanAPIPlugin;
@@ -35,16 +34,6 @@ public class HumanAPIActivity extends Activity {
private HumanAPIListener humanAPIListener;
- public interface HumanAPIListener {
- /**
- * Sends an update with the human API data
- *
- * @param success The success status
- * @param humanAPIData The human API response data
- */
- void onHumanAPIUpdate(Boolean success, String humanAPIData);
- }
-
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
@@ -73,12 +62,12 @@ protected void onCreate(Bundle savedInstanceState) {
service = new Service(this, new ServiceListener() {
@Override
- public void onServiceRunning(String passBackKey, Boolean serviceRunning) {
+ public void onServiceRunning(CallbackContext callbackContext, String passBackKey, Boolean serviceRunning) {
Log.wtf(TAG, "Service running status for " + passBackKey + " = " + serviceRunning);
}
@Override
- public void onServiceResponse(String passBackKey, JSONObject serviceResponse) {
+ public void onServiceResponse(CallbackContext callbackContext, String passBackKey, String serviceResponse) {
if(passBackKey.equals(HumanAPIModel.humanAPITokenPassBackKey)) {
// Setting the tokens in the model data
humanAPIModel.setTokens(serviceResponse);
@@ -91,30 +80,22 @@ public void onServiceResponse(String passBackKey, JSONObject serviceResponse) {
Log.wtf(TAG, "publicToken = " + humanAPIModel.getPublicToken());
Log.wtf(TAG, "accessToken = " + humanAPIModel.getAccessToken());
+ // Sending back the human API data update
if(humanAPIModel.getAccessToken() == null) {
- humanAPIListener.onHumanAPIUpdate(false, humanAPIModel.getHumanAPIHybridData("Access token is null, unable to proceed"));
-
- finish();
- } else {
- // Getting the user human connected health data
- service.get(HumanAPIModel.humanAPIDataPassBackKey, humanAPIModel.getDataURL(), humanAPIModel.getDataHeader());
+ humanAPIListener.onHumanAPIUpdate(callbackContext, false, humanAPIModel.getHumanAPIHybridTokensData("Access token is null"));
+ } else {
+ humanAPIListener.onHumanAPIUpdate(callbackContext, true, humanAPIModel.getHumanAPIHybridTokensData("Human API tokens got"));
}
- } else if(passBackKey.equals(HumanAPIModel.humanAPIDataPassBackKey)) {
- // Setting the human data in the model
- humanAPIModel.setHumanData(serviceResponse);
-
- // Sending back the human API data update
- humanAPIListener.onHumanAPIUpdate(true, humanAPIModel.getHumanAPIHybridData("Human API data got"));
-
- finish();
}
+
+ finish();
}
@Override
- public void onServiceError(String passBackKey, String errorMessage) {
+ public void onServiceError(CallbackContext callbackContext, String passBackKey, String errorMessage) {
Log.wtf(TAG, "Service error for " + passBackKey + " = " + errorMessage);
- humanAPIListener.onHumanAPIUpdate(false, humanAPIModel.getHumanAPIHybridData(errorMessage));
+ humanAPIListener.onHumanAPIUpdate(callbackContext, false, humanAPIModel.getHumanAPIHybridTokensData(errorMessage));
finish();
}
@@ -134,11 +115,11 @@ public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request
humanAPIModel.setHumanAPIResponse(request.getUrl().toString());
// Getting the human API public token for the user
- service.post(HumanAPIModel.humanAPITokenPassBackKey, humanAPIModel.getTokenURL(), null, humanAPIModel.getTokenRequestBody());
+ service.post(null, HumanAPIModel.humanAPITokenPassBackKey, humanAPIModel.getTokenURL(), null, humanAPIModel.getTokenRequestBody());
return true;
} else if(request.getUrl().toString().startsWith(humanAPIModel.getCloseURL())) {
- humanAPIListener.onHumanAPIUpdate(true, humanAPIModel.getHumanAPIHybridData("Human API page closed by user"));
+ humanAPIListener.onHumanAPIUpdate(null, true, humanAPIModel.getHumanAPIHybridTokensData("Human API page closed by user"));
finish();
diff --git a/src/android/human/HumanAPIListener.java b/src/android/human/HumanAPIListener.java
new file mode 100644
index 0000000..846232c
--- /dev/null
+++ b/src/android/human/HumanAPIListener.java
@@ -0,0 +1,14 @@
+package com.github.vikramezhil.cordova.human;
+
+import org.apache.cordova.CallbackContext;
+
+public interface HumanAPIListener {
+ /**
+ * Sends an update with the human API data
+ *
+ * @param callbackContext The callback context
+ * @param success The success status
+ * @param humanAPIData The human API response data
+ */
+ void onHumanAPIUpdate(CallbackContext callbackContext, Boolean success, String humanAPIData);
+}
\ No newline at end of file
diff --git a/src/android/human/HumanAPIModel.java b/src/android/human/HumanAPIModel.java
index de61427..70eaeae 100644
--- a/src/android/human/HumanAPIModel.java
+++ b/src/android/human/HumanAPIModel.java
@@ -10,6 +10,8 @@
import com.google.gson.Gson;
+import com.github.vikramezhil.cordova.human.HumanAPIProperties;
+
/**
* HumanAPI Model
*
@@ -79,16 +81,18 @@ public void setPublicToken(String publicToken) {
*
* @param tokenResponse The token service response
*/
- public void setTokens(JSONObject tokenResponse) {
+ public void setTokens(String tokenResponse) {
try {
- if(tokenResponse.has("accessToken")) {
- this.accessToken = tokenResponse.getString("accessToken");
+ JSONObject parseTokenResponse = new JSONObject(tokenResponse);
+
+ if(parseTokenResponse.has("accessToken")) {
+ this.accessToken = parseTokenResponse.getString("accessToken");
} else {
this.accessToken = null;
}
- if(tokenResponse.has("publicToken")) {
- this.publicToken = tokenResponse.getString("publicToken");
+ if(parseTokenResponse.has("publicToken")) {
+ this.publicToken = parseTokenResponse.getString("publicToken");
} else {
this.publicToken = null;
}
@@ -281,17 +285,51 @@ public JSONObject getTokenRequestBody() {
//*************************************************************************************
- static final String humanAPIDataPassBackKey = "humanAPIDataPassBackKey";
- private static final String dataURL = "https://api.humanapi.co/v1/human";
- private JSONObject humanData;
-
/**
- * Gets the data url
+ * Gets the wellness data url based on key
+ *
+ * @param key The wellness data key
*
- * @return The data url
+ * @return The wellness data url based on key
*/
- public String getDataURL() {
- return dataURL;
+ public String getDataURL(String key) {
+ if(key.equals("activities")) {
+ return HumanAPIProperties.ACTIVITIES_URL;
+ } else if(key.equals("activitiesSummaries")) {
+ return HumanAPIProperties.ACTIVITIES_SUMMARIES_URL;
+ } else if(key.equals("bloodGlucose")) {
+ return HumanAPIProperties.BLOOD_GLUCOSE_URL;
+ } else if(key.equals("bloodOxygen")) {
+ return HumanAPIProperties.BLOOD_OXYGEN_URL;
+ } else if(key.equals("bloodPressure")) {
+ return HumanAPIProperties.BLOOD_PRESSURE_URL;
+ } else if(key.equals("bodyMassIndex")) {
+ return HumanAPIProperties.BMI_URL;
+ } else if(key.equals("bodyFat")) {
+ return HumanAPIProperties.BODY_FAT_URL;
+ } else if(key.equals("heartRate")) {
+ return HumanAPIProperties.HEART_RATE_URL;
+ } else if(key.equals("heartRateSummaries")) {
+ return HumanAPIProperties.HEART_RATE_SUMMARIES_URL;
+ } else if(key.equals("height")) {
+ return HumanAPIProperties.HEIGHT_URL;
+ } else if(key.equals("weight")) {
+ return HumanAPIProperties.WEIGHT_URL;
+ } else if(key.equals("locations")) {
+ return HumanAPIProperties.LOCATIONS_URL;
+ } else if(key.equals("meals")) {
+ return HumanAPIProperties.MEALS_URL;
+ } else if(key.equals("sleeps")) {
+ return HumanAPIProperties.SLEEPS_URL;
+ } else if(key.equals("sleepSummaries")) {
+ return HumanAPIProperties.SLEEP_SUMMARIES_URL;
+ } else if(key.equals("humanSummary")) {
+ return HumanAPIProperties.HUMAN_SUMMARY_URL;
+ } else if(key.equals("profile")) {
+ return HumanAPIProperties.HUMAN_PROFILE_URL;
+ } else {
+ return null;
+ }
}
/**
@@ -307,50 +345,62 @@ public Map getDataHeader() {
return header;
}
- /**
- * Sets the human data
- *
- * @param humanData The human data
- */
- public void setHumanData(JSONObject humanData) {
- this.humanData = humanData;
- }
+ //*************************************************************************************
+
+ // PARSE JSON FORMAT FOR HYBRID
+
+ //*************************************************************************************
/**
- * Gets the human data
+ * Converts HUMAN API tokens data to JSON string for hybrid
+ *
+ * @param pluginMsg The plugin msg if any
*
- * @return The human data
+ * @return The converted HUMAN API tokens data JSON String
*/
- private JSONObject getHumanData() {
- return this.humanData;
- }
-
- //*************************************************************************************
+ public String getHumanAPIHybridTokensData(String pluginMsg) {
+ HashMap dataMap = new HashMap();
- // PARSE JSON FORMAT FOR HYBRID
+ try {
+ dataMap.put("clientID", getClientId());
+ dataMap.put("clientSecret", getClientSecret());
+ dataMap.put("userID", getUserId());
+ dataMap.put("humanID", getHumanId());
+ dataMap.put("sessionToken", getSessionToken());
+ dataMap.put("publicToken", getPublicToken());
+ dataMap.put("accessToken", getAccessToken());
+ dataMap.put("pluginMsg", pluginMsg);
+
+ return new Gson().toJson(dataMap);
+ } catch(Exception e) {
+ e.printStackTrace();
- //*************************************************************************************
+ return "Data conversion error";
+ }
+ }
/**
* Converts HUMAN API data to JSON string for hybrid
*
+ * @param humanAPIData The human API data
+ * @param key The data key
* @param pluginMsg The plugin msg if any
*
* @return The converted HUMAN API data JSON String
*/
- public String getHumanAPIHybridData(String pluginMsg) {
+ public String getHumanAPIHybridData(String humanAPIData, String key, String pluginMsg) {
HashMap dataMap = new HashMap();
- dataMap.put("clientID", getClientId());
- dataMap.put("clientSecret", getClientSecret());
- dataMap.put("userID", getUserId());
- dataMap.put("humanID", getHumanId());
- dataMap.put("sessionToken", getSessionToken());
- dataMap.put("publicToken", getPublicToken());
- dataMap.put("accessToken", getAccessToken());
- dataMap.put("humanAPIData", getHumanData() == null ? "" : getHumanData().toString());
- dataMap.put("pluginMsg", pluginMsg);
-
- return new Gson().toJson(dataMap);
+ try {
+ dataMap.put("humanAPIData", humanAPIData);
+ dataMap.put("key", key);
+ dataMap.put("pluginMsg", pluginMsg);
+
+ return new Gson().toJson(dataMap);
+ } catch(Exception e) {
+ e.printStackTrace();
+
+ return "Data conversion error";
+ }
}
}
\ No newline at end of file
diff --git a/src/android/human/HumanAPIProperties.java b/src/android/human/HumanAPIProperties.java
new file mode 100644
index 0000000..5c49c82
--- /dev/null
+++ b/src/android/human/HumanAPIProperties.java
@@ -0,0 +1,60 @@
+package com.github.vikramezhil.cordova.human;
+
+/**
+ * HumanAPI Properties
+ *
+ * @author Vikram Ezhil
+ */
+
+public class HumanAPIProperties {
+ // https://reference.humanapi.co/v2.1/reference#activities
+ public static final String ACTIVITIES_URL = "https://api.humanapi.co/v1/human/activities";
+
+ // https://reference.humanapi.co/v2.1/reference#activity-summaries
+ public static final String ACTIVITIES_SUMMARIES_URL = "https://api.humanapi.co/v1/human/activities/summaries";
+
+ // https://reference.humanapi.co/v2.1/reference#blood-glucose
+ public static final String BLOOD_GLUCOSE_URL = "https://api.humanapi.co/v1/human/blood_glucose";
+
+ // https://reference.humanapi.co/v2.1/reference#blood-oxygen
+ public static final String BLOOD_OXYGEN_URL = "https://api.humanapi.co/v1/human/blood_oxygen";
+
+ // https://reference.humanapi.co/v2.1/reference#blood-pressure
+ public static final String BLOOD_PRESSURE_URL = "https://api.humanapi.co/v1/human/blood_pressure";
+
+ // https://reference.humanapi.co/v2.1/reference#body-mass-index-bmi
+ public static final String BMI_URL = "https://api.humanapi.co/v1/human/bmi";
+
+ // https://reference.humanapi.co/v2.1/reference#body-fat
+ public static final String BODY_FAT_URL = "https://api.humanapi.co/v1/human/body_fat";
+
+ // https://reference.humanapi.co/v2.1/reference#heart-rate
+ public static final String HEART_RATE_URL = "https://api.humanapi.co/v1/human/heart_rate";
+
+ // https://reference.humanapi.co/v2.1/reference#heart-rate-summaries
+ public static final String HEART_RATE_SUMMARIES_URL = "https://api.humanapi.co/v1/human/heart_rate/summaries";
+
+ // https://reference.humanapi.co/v2.1/reference#height
+ public static final String HEIGHT_URL = "https://api.humanapi.co/v1/human/height";
+
+ // https://reference.humanapi.co/v2.1/reference#weight
+ public static final String WEIGHT_URL = "https://api.humanapi.co/v1/human/weight";
+
+ // https://reference.humanapi.co/v2.1/reference#locations
+ public static final String LOCATIONS_URL = "https://api.humanapi.co/v1/human/locations";
+
+ // https://reference.humanapi.co/v2.1/reference#meals
+ public static final String MEALS_URL = "https://api.humanapi.co/v1/human/food/meals";
+
+ // https://reference.humanapi.co/v2.1/reference#sleeps
+ public static final String SLEEPS_URL = "https://api.humanapi.co/v1/human/sleeps";
+
+ // https://reference.humanapi.co/v2.1/reference#sleep-summaries
+ public static final String SLEEP_SUMMARIES_URL = "https://api.humanapi.co/v1/human/sleeps/summaries";
+
+ // https://reference.humanapi.co/v2.1/reference#human-summary
+ public static final String HUMAN_SUMMARY_URL = "https://api.humanapi.co/v1/human";
+
+ // https://reference.humanapi.co/v2.1/reference#profile-1
+ public static final String HUMAN_PROFILE_URL = "https://api.humanapi.co/v1/human/profile";
+}
\ No newline at end of file
diff --git a/src/android/human/HumanAPIService.java b/src/android/human/HumanAPIService.java
new file mode 100644
index 0000000..f787c81
--- /dev/null
+++ b/src/android/human/HumanAPIService.java
@@ -0,0 +1,82 @@
+package com.github.vikramezhil.cordova.human;
+
+import android.content.Context;
+import android.util.Log;
+
+import org.apache.cordova.CallbackContext;
+
+import org.json.JSONObject;
+
+import com.github.vikramezhil.cordova.service.Service;
+import com.github.vikramezhil.cordova.service.Service.ServiceListener;
+
+/**
+ * HumanAPI Service
+ *
+ * @author Vikram Ezhil
+ */
+
+public class HumanAPIService {
+ private final String TAG = "HumanAPIService";
+
+ private HumanAPIModel humanAPIModel = new HumanAPIModel();
+ private Service service;
+
+ private HumanAPIListener humanAPIListener;
+
+ /**
+ * Human API Service constructor
+ *
+ * @param context The application context
+ * @param humanAPIListener The class instance to initiate the listener
+ */
+ public HumanAPIService(Context context, HumanAPIListener humanAPIListener) {
+ this.humanAPIListener = humanAPIListener;
+
+ service = new Service(context, new ServiceListener() {
+ @Override
+ public void onServiceRunning(CallbackContext callbackContext, String passBackKey, Boolean serviceRunning) {
+ Log.wtf(TAG, "Service running status for " + passBackKey + " = " + serviceRunning);
+ }
+
+ @Override
+ public void onServiceResponse(CallbackContext callbackContext, String passBackKey, String serviceResponse) {
+ Log.wtf(TAG, "Service response for " + passBackKey + " = " + serviceResponse);
+
+ humanAPIListener.onHumanAPIUpdate(callbackContext, true, humanAPIModel.getHumanAPIHybridData(serviceResponse, passBackKey, "Human API Wellness data got"));
+ }
+
+ @Override
+ public void onServiceError(CallbackContext callbackContext, String passBackKey, String errorMessage) {
+ Log.wtf(TAG, "Service error for " + passBackKey + " = " + errorMessage);
+
+ humanAPIListener.onHumanAPIUpdate(callbackContext, false, humanAPIModel.getHumanAPIHybridData("", passBackKey, errorMessage));
+ }
+ });
+ }
+
+ /**
+ * Executes the human API wellness services based on key
+ *
+ * @param callbackContext The callback context
+ * @param key The human api service key
+ * @param accessToken The access token
+ */
+ public void execute(CallbackContext callbackContext, String key, String accessToken) {
+ if(accessToken == null || accessToken.isEmpty()) {
+ humanAPIListener.onHumanAPIUpdate(callbackContext, false, humanAPIModel.getHumanAPIHybridData("", key, "Access token is empty"));
+ } else {
+ // Getting the data url
+ String url = this.humanAPIModel.getDataURL(key);
+
+ if(url == null || url.isEmpty()) {
+ humanAPIListener.onHumanAPIUpdate(callbackContext, false, humanAPIModel.getHumanAPIHybridData("", key, "Unknown data key, unable to generate url"));
+ } else {
+ // Saving the access token in the human api model
+ this.humanAPIModel.setAccessToken(accessToken);
+
+ service.get(callbackContext, key, url, humanAPIModel.getDataHeader());
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/android/service/Service.java b/src/android/service/Service.java
index 553d7ec..ad352f5 100644
--- a/src/android/service/Service.java
+++ b/src/android/service/Service.java
@@ -14,11 +14,12 @@
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
+import org.apache.cordova.CallbackContext;
+
import org.json.JSONObject;
import java.util.Map;
-
/**
* Service class
*
@@ -35,26 +36,29 @@ public interface ServiceListener {
/**
* Updates with the service running status
*
+ * @param callbackContext The callback context
* @param passBackKey The pass back key
* @param serviceRunning The service running status
*/
- void onServiceRunning(String passBackKey, Boolean serviceRunning);
+ void onServiceRunning(CallbackContext callbackContext, String passBackKey, Boolean serviceRunning);
/**
* Updates with the service response
*
+ * @param callbackContext The callback context
* @param passBackKey The pass back key
* @param serviceResponse The service response
*/
- void onServiceResponse(String passBackKey, JSONObject serviceResponse);
+ void onServiceResponse(CallbackContext callbackContext, String passBackKey, String serviceResponse);
/**
* Updates with the service error
*
+ * @param callbackContext The callback context
* @param passBackKey The pass back key
* @param errorMessage The error message
*/
- void onServiceError(String passBackKey, String errorMessage);
+ void onServiceError(CallbackContext callbackContext, String passBackKey, String errorMessage);
}
/**
@@ -71,6 +75,7 @@ public Service(Context context, ServiceListener serviceListener) {
/**
* Sends a POST request
*
+ * @param callbackContext The callback context
* @param passBackKey The pass back key
* @param requestLink The request link
* @param customHeaders The custom headers if any
@@ -78,7 +83,7 @@ public Service(Context context, ServiceListener serviceListener) {
*
* Listener Interface => ServiceListener
*/
- public void post(final String passBackKey, final String requestLink, final Map customHeaders, final JSONObject requestBody) {
+ public void post(final CallbackContext callbackContext, final String passBackKey, final String requestLink, final Map customHeaders, final JSONObject requestBody) {
try {
Log.wtf(TAG, "Request type = POST");
Log.wtf(TAG, "Pass back key = " + passBackKey);
@@ -88,7 +93,7 @@ public void post(final String passBackKey, final String requestLink, final Map parseNetworkResponse(NetworkResponse response) {
} catch (Exception e) {
e.printStackTrace();
- serviceListener.onServiceRunning(passBackKey, false);
+ serviceListener.onServiceRunning(callbackContext, passBackKey, false);
}
}
-
/**
* Sends a GET request
*
+ * @param callbackContext The callback context
* @param passBackKey The pass back key
* @param requestLink The request link
* @param customHeaders The custom headers if any
*
* Listener Interface => ServiceListener
*/
- public void get(final String passBackKey, final String requestLink, final Map customHeaders) {
+ public void get(final CallbackContext callbackContext, final String passBackKey, final String requestLink, final Map customHeaders) {
try {
Log.wtf(TAG, "Request type = GET");
Log.wtf(TAG, "Pass back key = " + passBackKey);
@@ -189,7 +186,7 @@ public void get(final String passBackKey, final String requestLink, final Map parseNetworkResponse(NetworkResponse response) {
} catch (Exception e) {
e.printStackTrace();
- serviceListener.onServiceRunning(passBackKey, false);
+ serviceListener.onServiceRunning(callbackContext, passBackKey, false);
}
}
}
diff --git a/src/ios/HumanAPIPlugin.swift b/src/ios/HumanAPIPlugin.swift
index a4f432c..5f56623 100644
--- a/src/ios/HumanAPIPlugin.swift
+++ b/src/ios/HumanAPIPlugin.swift
@@ -9,15 +9,22 @@ import Foundation
import UIKit
@objc(HumanAPIPlugin) class HumanAPIPlugin: CDVPlugin, HumanAPIVCDelegate {
+ private let TAG: String = "HumanAPIPlugin"
+
var command: CDVInvokedUrlCommand?
var storyboard: UIStoryboard?
+ private var humanAPIService: HumanAPIService?
+
override func pluginInitialize() {
super.pluginInitialize()
// Initializing the storyboard
storyboard = UIStoryboard(name: "Human", bundle: nil)
+
+ humanAPIService = HumanAPIService()
+ humanAPIService?.humanAPIServiceDelegate = self
}
//*************************************************************************************
@@ -30,17 +37,18 @@ import UIKit
private var humanCDVContext: CDVInvokedUrlCommand?
///
- /// Triggers Human API
+ /// Triggers Human API Authentication
///
/// :param: command The cdv url command instance
///
- @objc(trigger:)
- func trigger(command: CDVInvokedUrlCommand) {
+ @objc(auth:)
+ func auth(command: CDVInvokedUrlCommand) {
// Saving a reference of the human API command invoke context
humanCDVContext = command
- if let _ = command.arguments[0] as? String, let clientID = command.arguments[1] as? String, let clientSecret = command.arguments[2] as? String,
- let userID = command.arguments[3] as? String, let publicToken = command.arguments[4] as? String, let accessToken = command.arguments[5] as? String {
+ if let clientID = command.arguments[0] as? String, let clientSecret = command.arguments[1] as? String,
+ let userID = command.arguments[2] as? String, let publicToken = command.arguments[3] as? String,
+ let accessToken = command.arguments[4] as? String {
humanAPIVC = storyboard?.instantiateViewController(withIdentifier: "humanAPIVC") as? HumanAPIVC
humanAPIVC?.humanAPIVCDelegate = self
humanAPIVC?.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
@@ -57,14 +65,31 @@ import UIKit
}
}
+ ///
+ /// Executes the human API wellness services
+ ///
+ /// :param: command The cdv url command instance
+ ///
+ @objc(execute:)
+ func execute(command: CDVInvokedUrlCommand) {
+ if let wellnessKey = command.arguments[0] as? String, let token = command.arguments[1] as? String {
+ humanAPIService?.execute(command: command, key: wellnessKey, accessToken: token)
+ }
+ }
+
// @Override HumanAPIVCDelegate Methods
- func onHumanAPIUpdate(success: Bool, humanAPIData: String) {
+ func onHumanAPIUpdate(command: CDVInvokedUrlCommand?, success: Bool, humanAPIData: String) {
let result = CDVPluginResult(status: success ? CDVCommandStatus_OK : CDVCommandStatus_ERROR, messageAs: humanAPIData)
result?.setKeepCallbackAs(true)
- if let cdvUrl = humanCDVContext {
+ if let humanCDVUrl = humanCDVContext {
+ self.commandDelegate!.send(result, callbackId: humanCDVUrl.callbackId)
+ humanCDVContext = nil
+ } else if let cdvUrl = command {
self.commandDelegate!.send(result, callbackId: cdvUrl.callbackId)
+ } else {
+ print(TAG, "Unable to send back data, callback ID is nil")
}
}
}
\ No newline at end of file
diff --git a/src/ios/human/HumanAPIModel.swift b/src/ios/human/HumanAPIModel.swift
index d6ef2f2..5e8a480 100644
--- a/src/ios/human/HumanAPIModel.swift
+++ b/src/ios/human/HumanAPIModel.swift
@@ -178,21 +178,28 @@ class HumanAPIModel: NSObject {
}
}
- var tokens: [String: Any] {
+ var tokens: String {
get {
- return [:]
+ return ""
}
set(tokens) {
- if let aToken = tokens["accessToken"] {
- self.aToken = aToken as! String
+ let parseTokens = tokens.convertToDictionary()
+
+ if let unwrappedTokens = parseTokens {
+ if let aToken = unwrappedTokens["accessToken"] {
+ self.aToken = aToken as! String
+ } else {
+ self.aToken = ""
+ }
+
+ if let pToken = unwrappedTokens["publicToken"] {
+ self.pToken = pToken as! String
+ } else {
+ self.pToken = ""
+ }
} else {
self.aToken = ""
- }
-
- if let pToken = tokens["publicToken"] {
- self.pToken = pToken as! String
- } else {
self.pToken = ""
}
}
@@ -268,13 +275,50 @@ class HumanAPIModel: NSObject {
//*************************************************************************************
- static let humanAPIDataPassBackKey: String = "humanAPIDataPassBackKey"
- private let dataURL: String = "https://api.humanapi.co/v1/human"
- private var humanDataSet: [String: Any] = [:]
-
- var dataUrl: String {
- get {
- return self.dataURL
+ ///
+ /// Gets the wellness data url based on key
+ ///
+ /// :param: dataKey The wellness data key
+ ///
+ /// :return: The wellness data url based on key
+ ///
+ func getDataURL(dataKey: String) -> String? {
+ if(dataKey == "activities") {
+ return HumanAPIProperties.ACTIVITIES_URL
+ } else if(dataKey == "activitiesSummaries") {
+ return HumanAPIProperties.ACTIVITIES_SUMMARIES_URL
+ } else if(dataKey == "bloodGlucose") {
+ return HumanAPIProperties.BLOOD_GLUCOSE_URL
+ } else if(dataKey == "bloodOxygen") {
+ return HumanAPIProperties.BLOOD_OXYGEN_URL
+ } else if(dataKey == "bloodPressure") {
+ return HumanAPIProperties.BLOOD_PRESSURE_URL
+ } else if(dataKey == "bodyMassIndex") {
+ return HumanAPIProperties.BMI_URL
+ } else if(dataKey == "bodyFat") {
+ return HumanAPIProperties.BODY_FAT_URL
+ } else if(dataKey == "heartRate") {
+ return HumanAPIProperties.HEART_RATE_URL
+ } else if(dataKey == "heartRateSummaries") {
+ return HumanAPIProperties.HEART_RATE_SUMMARIES_URL
+ } else if(dataKey == "height") {
+ return HumanAPIProperties.HEIGHT_URL
+ } else if(dataKey == "weight") {
+ return HumanAPIProperties.WEIGHT_URL
+ } else if(dataKey == "locations") {
+ return HumanAPIProperties.LOCATIONS_URL
+ } else if(dataKey == "meals") {
+ return HumanAPIProperties.MEALS_URL
+ } else if(dataKey == "sleeps") {
+ return HumanAPIProperties.SLEEPS_URL
+ } else if(dataKey == "sleepSummaries") {
+ return HumanAPIProperties.SLEEP_SUMMARIES_URL
+ } else if(dataKey == "humanSummary") {
+ return HumanAPIProperties.HUMAN_SUMMARY_URL
+ } else if(dataKey == "profile") {
+ return HumanAPIProperties.HUMAN_PROFILE_URL
+ } else {
+ return nil
}
}
@@ -287,16 +331,6 @@ class HumanAPIModel: NSObject {
}
}
- var humanData: [String: Any] {
- get {
- return self.humanDataSet
- }
-
- set(humanDataSet) {
- self.humanDataSet = humanDataSet
- }
- }
-
//*************************************************************************************
// PARSE JSON FORMAT FOR HYBRID
@@ -304,14 +338,15 @@ class HumanAPIModel: NSObject {
//*************************************************************************************
///
- /// Converts HUMAN API data to JSON string for hybrid
+ /// Converts HUMAN API tokens data to JSON string for hybrid
///
/// :param: pluginMsg The plugin msg if any
///
/// :return: The converted HUMAN API data JSON String
///
- public func getHumanAPIHybridData(pluginMsg: String) -> String {
+ public func getHumanAPIHybridTokensData(pluginMsg: String) -> String {
var dataMap: [String : String] = [:]
+
dataMap["clientId"] = clientId
dataMap["clientSecret"] = clientSecret
dataMap["userID"] = userId
@@ -319,7 +354,25 @@ class HumanAPIModel: NSObject {
dataMap["sessionToken"] = sessionToken
dataMap["publicToken"] = publicToken
dataMap["accessToken"] = accessToken
- dataMap["humanAPIData"] = humanData.toJSONString()
+ dataMap["pluginMsg"] = pluginMsg
+
+ return dataMap.toJSONString()
+ }
+
+ ///
+ /// Converts HUMAN API data to JSON string for hybrid
+ ///
+ /// :param: humanAPIData The human API data
+ /// :param: key The data key
+ /// :param: pluginMsg The plugin msg if any
+ ///
+ /// :return: The converted HUMAN API data JSON String
+ ///
+ public func getHumanAPIHybridData(humanAPIData: String, key: String, pluginMsg: String) -> String {
+ var dataMap: [String : String] = [:]
+
+ dataMap["humanAPIData"] = humanAPIData
+ dataMap["key"] = key
dataMap["pluginMsg"] = pluginMsg
return dataMap.toJSONString()
diff --git a/src/ios/human/HumanAPIProperties.swift b/src/ios/human/HumanAPIProperties.swift
new file mode 100644
index 0000000..359fc95
--- /dev/null
+++ b/src/ios/human/HumanAPIProperties.swift
@@ -0,0 +1,71 @@
+//
+// HumanAPIProperties.swift
+//
+// Created by Vikram Ezhil on 23/11/18.
+//
+
+import Foundation
+
+protocol HumanAPIVCDelegate: class {
+ ///
+ /// Sends an update with the human API data
+ ///
+ /// :param: command The callback context
+ /// :param: success The success status
+ /// :param: humanAPIData The human API response data
+ ///
+ func onHumanAPIUpdate(command: CDVInvokedUrlCommand?, success: Bool, humanAPIData: String)
+}
+
+struct HumanAPIProperties {
+ // https://reference.humanapi.co/v2.1/reference#activities
+ static let ACTIVITIES_URL = "https://api.humanapi.co/v1/human/activities"
+
+ // https://reference.humanapi.co/v2.1/reference#activity-summaries
+ static let ACTIVITIES_SUMMARIES_URL = "https://api.humanapi.co/v1/human/activities/summaries"
+
+ // https://reference.humanapi.co/v2.1/reference#blood-glucose
+ static let BLOOD_GLUCOSE_URL = "https://api.humanapi.co/v1/human/blood_glucose"
+
+ // https://reference.humanapi.co/v2.1/reference#blood-oxygen
+ static let BLOOD_OXYGEN_URL = "https://api.humanapi.co/v1/human/blood_oxygen"
+
+ // https://reference.humanapi.co/v2.1/reference#blood-pressure
+ static let BLOOD_PRESSURE_URL = "https://api.humanapi.co/v1/human/blood_pressure"
+
+ // https://reference.humanapi.co/v2.1/reference#body-mass-index-bmi
+ static let BMI_URL = "https://api.humanapi.co/v1/human/bmi"
+
+ // https://reference.humanapi.co/v2.1/reference#body-fat
+ static let BODY_FAT_URL = "https://api.humanapi.co/v1/human/body_fat"
+
+ // https://reference.humanapi.co/v2.1/reference#heart-rate
+ static let HEART_RATE_URL = "https://api.humanapi.co/v1/human/heart_rate"
+
+ // https://reference.humanapi.co/v2.1/reference#heart-rate-summaries
+ static let HEART_RATE_SUMMARIES_URL = "https://api.humanapi.co/v1/human/heart_rate/summaries"
+
+ // https://reference.humanapi.co/v2.1/reference#height
+ static let HEIGHT_URL = "https://api.humanapi.co/v1/human/height"
+
+ // https://reference.humanapi.co/v2.1/reference#weight
+ static let WEIGHT_URL = "https://api.humanapi.co/v1/human/weight"
+
+ // https://reference.humanapi.co/v2.1/reference#locations
+ static let LOCATIONS_URL = "https://api.humanapi.co/v1/human/locations"
+
+ // https://reference.humanapi.co/v2.1/reference#meals
+ static let MEALS_URL = "https://api.humanapi.co/v1/human/food/meals"
+
+ // https://reference.humanapi.co/v2.1/reference#sleeps
+ static let SLEEPS_URL = "https://api.humanapi.co/v1/human/sleeps"
+
+ // https://reference.humanapi.co/v2.1/reference#sleep-summaries
+ static let SLEEP_SUMMARIES_URL = "https://api.humanapi.co/v1/human/sleeps/summaries"
+
+ // https://reference.humanapi.co/v2.1/reference#human-summary
+ static let HUMAN_SUMMARY_URL = "https://api.humanapi.co/v1/human"
+
+ // https://reference.humanapi.co/v2.1/reference#profile-1
+ static let HUMAN_PROFILE_URL = "https://api.humanapi.co/v1/human/profile"
+}
\ No newline at end of file
diff --git a/src/ios/human/HumanAPIService.swift b/src/ios/human/HumanAPIService.swift
new file mode 100644
index 0000000..3cb0b42
--- /dev/null
+++ b/src/ios/human/HumanAPIService.swift
@@ -0,0 +1,65 @@
+//
+// HumanAPIService.swift
+//
+// Created by Vikram Ezhil on 23/11/18.
+//
+
+import Foundation
+
+class HumanAPIService: NSObject, ServiceDelegate {
+ private let TAG: String = "HumanAPIService"
+
+ private var service: Service = Service()
+ private var humanAPIModel: HumanAPIModel = HumanAPIModel()
+
+ weak var humanAPIServiceDelegate: HumanAPIVCDelegate?
+
+ ///
+ /// Initializer
+ ///
+ override init() {
+ super.init()
+
+ service.serviceDelegate = self
+ }
+
+ ///
+ /// Executes the human API wellness services based on key
+ ///
+ /// :param: command The callback context
+ /// :param: key The human api service key
+ /// :param: accessToken The access token
+ ///
+ func execute(command: CDVInvokedUrlCommand, key: String, accessToken: String) {
+ if(accessToken.count == 0) {
+ humanAPIServiceDelegate?.onHumanAPIUpdate(command: command, success: false, humanAPIData: humanAPIModel.getHumanAPIHybridData(humanAPIData: "", key: key, pluginMsg: "Access token is empty"))
+ } else {
+ if let url = humanAPIModel.getDataURL(dataKey: key) {
+ // Saving the access token in the human api model
+ humanAPIModel.accessToken = accessToken
+
+ service.get(command: command, passbackKey: key, requestLink: url, customHeaders: humanAPIModel.dataHeader)
+ } else {
+ humanAPIServiceDelegate?.onHumanAPIUpdate(command: command, success: false, humanAPIData: humanAPIModel.getHumanAPIHybridData(humanAPIData: "", key: key, pluginMsg: "Unknown data key, unable to generate url"))
+ }
+ }
+ }
+
+ // @Override ServiceDelegate Methods
+
+ func onServiceRunning(command: CDVInvokedUrlCommand?, passBackKey: String, serviceRunning: Bool) {
+ print(TAG, "Service running status for \(passBackKey) = \(serviceRunning)")
+ }
+
+ func onServiceResponse(command: CDVInvokedUrlCommand?, passBackKey: String, serviceResponse: String) {
+ print(TAG, "Service success for \(passBackKey) = \(serviceResponse)")
+
+ humanAPIServiceDelegate?.onHumanAPIUpdate(command: command, success: true, humanAPIData: humanAPIModel.getHumanAPIHybridData(humanAPIData: serviceResponse, key: passBackKey, pluginMsg: "Human API Wellness data got"))
+ }
+
+ func onServiceError(command: CDVInvokedUrlCommand?, passBackKey: String, errorMessage: String) {
+ print(TAG, "Service error for \(passBackKey) = \(errorMessage)")
+
+ humanAPIServiceDelegate?.onHumanAPIUpdate(command: command, success: false, humanAPIData: humanAPIModel.getHumanAPIHybridData(humanAPIData: "", key: passBackKey, pluginMsg: errorMessage))
+ }
+}
\ No newline at end of file
diff --git a/src/ios/human/HumanAPIVC.swift b/src/ios/human/HumanAPIVC.swift
index 0515929..f51fae4 100644
--- a/src/ios/human/HumanAPIVC.swift
+++ b/src/ios/human/HumanAPIVC.swift
@@ -7,16 +7,6 @@
import UIKit
import WebKit
-protocol HumanAPIVCDelegate: class {
- ///
- /// Sends an update with the human API data
- ///
- /// :param: success The success status
- /// :param: humanAPIData The human API response data
- ///
- func onHumanAPIUpdate(success: Bool, humanAPIData: String)
-}
-
class HumanAPIVC: UIViewController, WKUIDelegate, WKNavigationDelegate, ServiceDelegate {
private let TAG: String = "HumanAPIVC"
@@ -119,9 +109,9 @@ class HumanAPIVC: UIViewController, WKUIDelegate, WKNavigationDelegate, ServiceD
humanAPIModel.setHumanAPIResponse(response: requestUrl)
// Getting the human API public token for the user
- service.post(passbackKey: HumanAPIModel.humanAPITokenPassBackKey, requestLink: humanAPIModel.tokenUrl, customHeaders: [:], requestBody: humanAPIModel.getTokenRequestBody())
+ service.post(command: nil, passbackKey: HumanAPIModel.humanAPITokenPassBackKey, requestLink: humanAPIModel.tokenUrl, customHeaders: [:], requestBody: humanAPIModel.getTokenRequestBody())
} else if(newUrl.hasPrefix(humanAPIModel.closeUrl)) {
- humanAPIVCDelegate?.onHumanAPIUpdate(success: true, humanAPIData: humanAPIModel.getHumanAPIHybridData(pluginMsg: "Human API page closed by user"))
+ humanAPIVCDelegate?.onHumanAPIUpdate(command: nil, success: true, humanAPIData: humanAPIModel.getHumanAPIHybridTokensData(pluginMsg: "Human API page closed by user"))
decisionHandler(.cancel)
@@ -162,18 +152,18 @@ class HumanAPIVC: UIViewController, WKUIDelegate, WKNavigationDelegate, ServiceD
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
- humanAPIVCDelegate?.onHumanAPIUpdate(success: false, humanAPIData: humanAPIModel.getHumanAPIHybridData(pluginMsg: "Web API load error = \(error.localizedDescription)"))
+ humanAPIVCDelegate?.onHumanAPIUpdate(command: nil, success: false, humanAPIData: humanAPIModel.getHumanAPIHybridTokensData(pluginMsg: "Web API load error = \(error.localizedDescription)"))
self.dismiss(animated: true, completion: nil)
}
// @Override ServiceDelegate Methods
- func onServiceRunning(passBackKey: String, serviceRunning: Bool) {
+ func onServiceRunning(command: CDVInvokedUrlCommand?, passBackKey: String, serviceRunning: Bool) {
print(TAG, "Service running status for \(passBackKey) = \(serviceRunning)")
}
- func onServiceResponse(passBackKey: String, serviceResponse: [String: Any]) {
+ func onServiceResponse(command: CDVInvokedUrlCommand?, passBackKey: String, serviceResponse: String) {
print(TAG, "Service success for \(passBackKey) = \(serviceResponse)")
switch passBackKey {
@@ -191,25 +181,13 @@ class HumanAPIVC: UIViewController, WKUIDelegate, WKNavigationDelegate, ServiceD
print(TAG, "accessToken = \(humanAPIModel.accessToken)");
if(humanAPIModel.accessToken.count == 0) {
- humanAPIVCDelegate?.onHumanAPIUpdate(success: false, humanAPIData: humanAPIModel.getHumanAPIHybridData(pluginMsg: "Access token is empty, unable to proceed"))
-
- self.dismiss(animated: true, completion: nil)
+ humanAPIVCDelegate?.onHumanAPIUpdate(command: command, success: false, humanAPIData: humanAPIModel.getHumanAPIHybridTokensData(pluginMsg: "Access token is empty"))
} else {
- // Getting the user human connected health data
- service.get(passbackKey: HumanAPIModel.humanAPIDataPassBackKey, requestLink: humanAPIModel.dataUrl, customHeaders: humanAPIModel.dataHeader)
+ humanAPIVCDelegate?.onHumanAPIUpdate(command: command, success: true, humanAPIData: humanAPIModel.getHumanAPIHybridTokensData(pluginMsg: "Human API tokens got"))
}
- break
-
- case HumanAPIModel.humanAPIDataPassBackKey:
-
- // Setting the human data in the model
- humanAPIModel.humanData = serviceResponse
-
- humanAPIVCDelegate?.onHumanAPIUpdate(success: true, humanAPIData: humanAPIModel.getHumanAPIHybridData(pluginMsg: "Human API data got"))
-
self.dismiss(animated: true, completion: nil)
-
+
break
default:
@@ -217,10 +195,10 @@ class HumanAPIVC: UIViewController, WKUIDelegate, WKNavigationDelegate, ServiceD
}
}
- func onServiceError(passBackKey: String, errorMessage: String) {
+ func onServiceError(command: CDVInvokedUrlCommand?, passBackKey: String, errorMessage: String) {
print(TAG, "Service error for \(passBackKey) = \(errorMessage)")
- humanAPIVCDelegate?.onHumanAPIUpdate(success: false, humanAPIData: humanAPIModel.getHumanAPIHybridData(pluginMsg: errorMessage))
+ humanAPIVCDelegate?.onHumanAPIUpdate(command: command, success: false, humanAPIData: humanAPIModel.getHumanAPIHybridTokensData(pluginMsg: errorMessage))
self.dismiss(animated: true, completion: nil)
}
diff --git a/src/ios/service/Service.swift b/src/ios/service/Service.swift
index fd67e95..63902a0 100644
--- a/src/ios/service/Service.swift
+++ b/src/ios/service/Service.swift
@@ -10,30 +10,32 @@ protocol ServiceDelegate: class {
//
// Updates with the service running status
//
+ // :param: command The callback context
// :param: passBackKey The pass back key
// :param: serviceRunning The service running status
//
- func onServiceRunning(passBackKey: String, serviceRunning: Bool)
+ func onServiceRunning(command: CDVInvokedUrlCommand?, passBackKey: String, serviceRunning: Bool)
//
// Updates with the service response
//
+ // :param: command The callback context
// :param: passBackKey The pass back key
// :param: serviceResponse The service response
//
- func onServiceResponse(passBackKey: String, serviceResponse: [String: Any])
+ func onServiceResponse(command: CDVInvokedUrlCommand?, passBackKey: String, serviceResponse: String)
//
// Updates with the service error
//
+ // :param: command The callback context
// :param: passBackKey The pass back key
// :param: errorMessage The error message
//
- func onServiceError(passBackKey: String, errorMessage: String)
+ func onServiceError(command: CDVInvokedUrlCommand?, passBackKey: String, errorMessage: String)
}
class Service: NSObject {
-
private let TAG: String = "Service"
weak var serviceDelegate: ServiceDelegate?
@@ -48,6 +50,7 @@ class Service: NSObject {
///
/// Sends a POST request
///
+ /// :param: command The callback context
/// :param: passBackKey The pass back key
/// :param: requestLink The request link
/// :param: customHeaders The custom headers if any
@@ -55,7 +58,7 @@ class Service: NSObject {
///
/// :callbacks: ServiceDelegate onServiceRunning, onServiceResponse, onServiceError
///
- public func post(passbackKey: String, requestLink: String, customHeaders: [String: String], requestBody: [String: Any]) {
+ public func post(command: CDVInvokedUrlCommand?, passbackKey: String, requestLink: String, customHeaders: [String: String], requestBody: [String: Any]) {
print(TAG, "Request type = POST");
print(TAG, "Pass back key = \(passbackKey)");
print(TAG, "Request link = \(requestLink)");
@@ -76,29 +79,29 @@ class Service: NSObject {
request.httpBody = jsonData
// Sending back the service running status
- serviceDelegate?.onServiceRunning(passBackKey: passbackKey, serviceRunning: true)
+ serviceDelegate?.onServiceRunning(command: command, passBackKey: passbackKey, serviceRunning: true)
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
// Sending back the service running status
- self.serviceDelegate?.onServiceRunning(passBackKey: passbackKey, serviceRunning: false)
+ self.serviceDelegate?.onServiceRunning(command: command, passBackKey: passbackKey, serviceRunning: false)
if(error == nil) {
if let httpResponse = response as? HTTPURLResponse {
if(httpResponse.statusCode == 200) {
- if let responseData = data, let responseString = responseData.toString(), let responseDict = responseString.convertToDictionary() {
- self.serviceDelegate?.onServiceResponse(passBackKey: passbackKey, serviceResponse: responseDict)
+ if let responseData = data, let responseString = responseData.toString() {
+ self.serviceDelegate?.onServiceResponse(command: command, passBackKey: passbackKey, serviceResponse: responseString)
} else {
- self.serviceDelegate?.onServiceError(passBackKey: passbackKey, errorMessage: "Data conversion error = \(String(describing: data))")
+ self.serviceDelegate?.onServiceError(command: command, passBackKey: passbackKey, errorMessage: "Data conversion error = \(String(describing: data))")
}
} else {
- self.serviceDelegate?.onServiceError(passBackKey: passbackKey, errorMessage: "Service error, status code = \(httpResponse.statusCode)")
+ self.serviceDelegate?.onServiceError(command: command, passBackKey: passbackKey, errorMessage: "Service error, status code = \(httpResponse.statusCode)")
}
} else {
- self.serviceDelegate?.onServiceError(passBackKey: passbackKey, errorMessage: "Service error, status code unavailable")
+ self.serviceDelegate?.onServiceError(command: command, passBackKey: passbackKey, errorMessage: "Service error, status code unavailable")
}
} else {
- self.serviceDelegate?.onServiceError(passBackKey: passbackKey, errorMessage: error.debugDescription)
+ self.serviceDelegate?.onServiceError(command: command, passBackKey: passbackKey, errorMessage: error.debugDescription)
}
})
@@ -109,13 +112,14 @@ class Service: NSObject {
///
/// Sends a GET request
///
+ /// :param: command The callback context
/// :param: passBackKey The pass back key
/// :param: requestLink The request link
/// :param: customHeaders The custom headers if any
///
/// :callbacks: ServiceDelegate onServiceRunning, onServiceResponse, onServiceError
///
- public func get(passbackKey: String, requestLink: String, customHeaders: [String: String]) {
+ public func get(command: CDVInvokedUrlCommand?, passbackKey: String, requestLink: String, customHeaders: [String: String]) {
print(TAG, "Request type = GET");
print(TAG, "Pass back key = \(passbackKey)");
print(TAG, "Request link = \(requestLink)");
@@ -131,29 +135,29 @@ class Service: NSObject {
}
// Sending back the service running status
- serviceDelegate?.onServiceRunning(passBackKey: passbackKey, serviceRunning: true)
+ serviceDelegate?.onServiceRunning(command: command, passBackKey: passbackKey, serviceRunning: true)
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
// Sending back the service running status
- self.serviceDelegate?.onServiceRunning(passBackKey: passbackKey, serviceRunning: false)
+ self.serviceDelegate?.onServiceRunning(command: command, passBackKey: passbackKey, serviceRunning: false)
if(error == nil) {
if let httpResponse = response as? HTTPURLResponse {
if(httpResponse.statusCode == 200) {
- if let responseData = data, let responseString = responseData.toString(), let responseDict = responseString.convertToDictionary() {
- self.serviceDelegate?.onServiceResponse(passBackKey: passbackKey, serviceResponse: responseDict)
+ if let responseData = data, let responseString = responseData.toString() {
+ self.serviceDelegate?.onServiceResponse(command: command, passBackKey: passbackKey, serviceResponse: responseString)
} else {
- self.serviceDelegate?.onServiceError(passBackKey: passbackKey, errorMessage: "Data conversion error = \(String(describing: data))")
+ self.serviceDelegate?.onServiceError(command: command, passBackKey: passbackKey, errorMessage: "Data conversion error = \(String(describing: data))")
}
} else {
- self.serviceDelegate?.onServiceError(passBackKey: passbackKey, errorMessage: "Service error, status code = \(httpResponse.statusCode)")
+ self.serviceDelegate?.onServiceError(command: command, passBackKey: passbackKey, errorMessage: "Service error, status code = \(httpResponse.statusCode)")
}
} else {
- self.serviceDelegate?.onServiceError(passBackKey: passbackKey, errorMessage: "Service error, status code unavailable")
+ self.serviceDelegate?.onServiceError(command: command, passBackKey: passbackKey, errorMessage: "Service error, status code unavailable")
}
} else {
- self.serviceDelegate?.onServiceError(passBackKey: passbackKey, errorMessage: error.debugDescription)
+ self.serviceDelegate?.onServiceError(command: command, passBackKey: passbackKey, errorMessage: error.debugDescription)
}
})
diff --git a/www/humanapi.js b/www/humanapi.js
index 419179a..fe4457c 100644
--- a/www/humanapi.js
+++ b/www/humanapi.js
@@ -6,8 +6,12 @@ var pluginName = "HumanAPIPlugin";
*/
function HumanAPIPlugin() {}
-HumanAPIPlugin.prototype.trigger = function (triggerType, clientID, clientSecret, userID, publicToken, accessToken, success, error) {
- exec(success, error, pluginName, 'trigger', [triggerType, clientID, clientSecret, userID, publicToken, accessToken]);
+HumanAPIPlugin.prototype.auth = function (clientID, clientSecret, userID, publicToken, accessToken, success, error) {
+ exec(success, error, pluginName, 'auth', [clientID, clientSecret, userID, publicToken, accessToken]);
+};
+
+HumanAPIPlugin.prototype.execute = function (type, accessToken, success, error) {
+ exec(success, error, pluginName, 'execute', [type, accessToken]);
};
// Installation constructor that binds HumanAPIPlugin to window