Skip to content

Commit

Permalink
Merge pull request #186 from shankari/fix_id_and_upgrade
Browse files Browse the repository at this point in the history
Fix id and upgrade
  • Loading branch information
shankari authored Aug 1, 2020
2 parents b5f46de + 3db23d2 commit d0ccc2e
Show file tree
Hide file tree
Showing 14 changed files with 316 additions and 601 deletions.
117 changes: 56 additions & 61 deletions hooks/android/addResourcesClassImport.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,14 @@
* A hook to add resources class (R.java) import to Android classes which uses it.
*/

function getRegexGroupMatches(string, regex, index) {
index || (index = 1)

var matches = [];
var match;
if (regex.global) {
while (match = regex.exec(string)) {
matches.push(match[index]);
console.log('Match:', match);
}
}
else {
if (match = regex.exec(string)) {
matches.push(match[index]);
}
}
const fs = require('fs'),
path = require('path');

const PACKAGE_RE = /package ([^;]+);/;
const R_RE = /[^\.\w]R\./;
const BUILDCONFIG_RE = /[^\.\w]BuildConfig\./;
const MAINACT_RE = /[^\.\w]MainActivity\./;

return matches;
}

// Adapted from
// https://stackoverflow.com/a/5827895
Expand All @@ -31,10 +20,7 @@ function getRegexGroupMatches(string, regex, index) {
// javascript modules using plugin.xml, and this uses only standard modules

var walk = function(ctx, dir, done) {
var results = [];

var fs = ctx.requireCordovaModule('fs'),
path = ctx.requireCordovaModule('path');
let results = [];

fs.readdir(dir, function(err, list) {
if (err) return done(err);
Expand Down Expand Up @@ -62,15 +48,11 @@ module.exports = function (ctx) {
if (ctx.opts.cordova.platforms.indexOf('android') < 0)
return;

var fs = ctx.requireCordovaModule('fs'),
path = ctx.requireCordovaModule('path'),
Q = ctx.requireCordovaModule('q');

var platformSourcesRoot = path.join(ctx.opts.projectRoot, 'platforms/android/app/src/main/java/');
var pluginSourcesRoot = path.join(ctx.opts.plugin.dir, 'src/android');
const platformSourcesRoot = path.join(ctx.opts.projectRoot, 'platforms/android/app/src/main/java/');
const pluginSourcesRoot = path.join(ctx.opts.plugin.dir, 'src/android');

var androidPluginsData = JSON.parse(fs.readFileSync(path.join(ctx.opts.projectRoot, 'plugins', 'android.json'), 'utf8'));
var appPackage = androidPluginsData.installed_plugins[ctx.opts.plugin.id]['PACKAGE_NAME'];
const androidPluginsData = JSON.parse(fs.readFileSync(path.join(ctx.opts.projectRoot, 'plugins', 'android.json'), 'utf8'));
const appPackage = androidPluginsData.installed_plugins[ctx.opts.plugin.id]['PACKAGE_NAME'];

walk(ctx, pluginSourcesRoot, function (err, files) {
console.log("walk callback with files = "+files);
Expand All @@ -83,73 +65,86 @@ module.exports = function (ctx) {

files.filter(function (file) { return path.extname(file) === '.java'; })
.forEach(function (file) {
var deferral = Q.defer();

// console.log("Considering file "+file);
var filename = path.basename(file);
// console.log("basename "+filename);
// var file = path.join(pluginSourcesRoot, filename);
// console.log("newfile"+file);
fs.readFile(file, 'utf-8', function (err, contents) {
if (err) {
console.error('Error when reading file:', err)
deferral.reject();
return
}

if (contents.match(/[^\.\w]R\./) || contents.match(/[^\.\w]BuildConfig\./) || contents.match(/[^\.\w]MainActivity\./)) {
console.log('Trying to get packages from file:', filename);
var packages = getRegexGroupMatches(contents, /package ([^;]+);/);
for (var p = 0; p < packages.length; p++) {
try {
var package = packages[p];
console.log('Handling package:', package);
const cp = new Promise(function(resolve, reject) {
// console.log("Considering file "+file);
const filename = path.basename(file);
// console.log("basename "+filename);
// var file = path.join(pluginSourcesRoot, filename);
// console.log("newfile"+file);
fs.readFile(file, 'utf-8', function (err, contents) {
if (err) {
console.error('Error when reading file:', err)
reject();
}

var sourceFile = path.join(platformSourcesRoot, package.replace(/\./g, '/'), filename)
if (contents.match(R_RE) || contents.match(BUILDCONFIG_RE) || contents.match(MAINACT_RE)) {
console.log('file '+filename+' needs to be rewritten, checking package');
const packages = contents.match(PACKAGE_RE);
if (packages.length > 2) {
console.error('Java source files must have only one package, found ', packages.length);
reject();
}

const pkg = packages[1];
console.log('Handling package:', pkg);
try {
const sourceFile = path.join(platformSourcesRoot, pkg.replace(/\./g, '/'), filename)
console.log('sourceFile:', sourceFile);
if (!fs.existsSync(sourceFile))
throw 'Can\'t find file in installed platform directory: "' + sourceFile + '".';

var sourceFileContents = fs.readFileSync(sourceFile, 'utf8');
const sourceFileContents = fs.readFileSync(sourceFile, 'utf8');
if (!sourceFileContents)
throw 'Can\'t read file contents.';

var newContents = sourceFileContents;
let newContents = sourceFileContents;

if (contents.match(/[^\.\w]R\./)) {
if (contents.match(R_RE)) {
newContents = sourceFileContents
.replace(/(import ([^;]+).R;)/g, '')
.replace(/(package ([^;]+);)/g, '$1 \n// Auto fixed by post-plugin hook \nimport ' + appPackage + '.R;');
}

// replace BuildConfig as well
if (contents.match(/[^\.\w]BuildConfig\./)) {
if (contents.match(BUILDCONFIG_RE)) {
newContents = newContents
.replace(/(import ([^;]+).BuildConfig;)/g, '')
.replace(/(package ([^;]+);)/g, '$1 \n// Auto fixed by post-plugin hook \nimport ' + appPackage + '.BuildConfig;');
}

// replace MainActivity as well
if (contents.match(/[^\.\w]MainActivity\./)) {
if (contents.match(MAINACT_RE)) {
newContents = newContents
.replace(/(import ([^;]+).MainActivity;)/g, '')
.replace(/(package ([^;]+);)/g, '$1 \n// Auto fixed by post-plugin hook \nimport ' + appPackage + '.MainActivity;');
}

fs.writeFileSync(sourceFile, newContents, 'utf8');
break;
resolve();
}
catch (ex) {
console.log('Could not add import to "' + filename + '" using package "' + package + '". ' + ex);
reject();
}
// we should never really get here because we return
// from both the try and the catch blocks. But in case we do,
// let's reject so we can debug
reject();
} else {
// the file had no BuildConfig or R dependencies, no need
// to rewrite it. We can potentially get rid of this check
// since we re-check for the imports before re-writing them
// but it avoid unnecessary file rewrites, so we retain
// it for now
resolve();
}
}
});
});

deferrals.push(deferral.promise);
deferrals.push(cp);
});

Q.all(deferrals)
Promise.all(deferrals)
.then(function() {
console.log('Done with the hook!');
})
Expand Down
13 changes: 6 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
{
"name": "e-mission-data-collection",
"version": "1.3.3",
"name": "cordova-plugin-em-datacollection",
"version": "1.4.4",
"description": "The main tracking for the e-mission platform",
"license": "BSD-3-clause",
"cordova": {
"id": "e-mission-data-collection",
"id": "cordova-plugin-em-datacollection",
"platforms": [
"android",
"ios",
"windows"
"ios"
]
},
"repository": {
Expand All @@ -29,7 +29,7 @@
},
{
"name": "cordova-android",
"version": ">=6.0.0"
"version": ">=7.0.0"
},
{
"name": "android-sdk",
Expand All @@ -41,7 +41,6 @@
}
],
"author": "K. Shankari",
"license": "BSD 3-clause",
"bugs": {
"url": "https://github.com/e-mission/e-mission-data-collection/issues"
},
Expand Down
7 changes: 4 additions & 3 deletions plugin.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
id="edu.berkeley.eecs.emission.cordova.datacollection"
version="1.4.3">
id="cordova-plugin-em-datacollection"
version="1.4.4">

<name>DataCollection</name>
<description>Background data collection FTW! This is the part that I really
Expand Down Expand Up @@ -116,7 +116,7 @@

<framework src="com.google.code.gson:gson:2.8.5"/>
<framework src="com.google.android.gms:play-services-location:$LOCATION_VERSION"/>
<preference name="LOCATION_VERSION" default="11.0.1"/>
<preference name="LOCATION_VERSION" default="17.0.0"/>

<source-file src="src/android/DataCollectionPlugin.java" target-dir="src/edu/berkeley/eecs/emission/cordova/tracker"/>
<source-file src="src/android/BootReceiver.java" target-dir="src/edu/berkeley/eecs/emission/cordova/tracker"/>
Expand All @@ -141,6 +141,7 @@
<source-file src="src/android/sensors/PollSensorManager.java" target-dir="src/edu/berkeley/eecs/emission/cordova/tracker/sensors"/>
<source-file src="src/android/wrapper/Metadata.java" target-dir="src/edu/berkeley/eecs/emission/cordova/tracker/wrapper"/>
<source-file src="src/android/wrapper/SimpleLocation.java" target-dir="src/edu/berkeley/eecs/emission/cordova/tracker/wrapper"/>
<source-file src="src/android/wrapper/MotionActivity.java" target-dir="src/edu/berkeley/eecs/emission/cordova/tracker/wrapper"/>
<source-file src="src/android/wrapper/Transition.java" target-dir="src/edu/berkeley/eecs/emission/cordova/tracker/wrapper"/>
<source-file src="src/android/wrapper/LocationTrackingConfig.java" target-dir="src/edu/berkeley/eecs/emission/cordova/tracker/wrapper"/>
<source-file src="src/android/wrapper/Battery.java" target-dir="src/edu/berkeley/eecs/emission/cordova/tracker/wrapper"/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.google.android.gms.location.DetectedActivity;

import edu.berkeley.eecs.emission.cordova.tracker.ConfigManager;
import edu.berkeley.eecs.emission.cordova.tracker.wrapper.MotionActivity;
import edu.berkeley.eecs.emission.cordova.unifiedlogger.NotificationHelper;
import edu.berkeley.eecs.emission.R;

Expand Down Expand Up @@ -61,7 +62,8 @@ protected void onHandleIntent(Intent intent) {
// better.
// if (mostProbableActivity.getConfidence() > 90) {
UserCache userCache = UserCacheFactory.getUserCache(this);
userCache.putSensorData(R.string.key_usercache_activity, mostProbableActivity);
MotionActivity mpma = new MotionActivity(mostProbableActivity);
userCache.putSensorData(R.string.key_usercache_activity, mpma);
// }
/*
DetectedActivity currentActivity = DataUtils.getCurrentMode(this).getLastActivity();
Expand Down
24 changes: 18 additions & 6 deletions src/android/location/LocationChangeIntentService.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

// import com.google.android.gms.location.LocationClient;

Expand All @@ -26,6 +28,7 @@

import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationAvailability;
import com.google.android.gms.location.LocationResult;

public class LocationChangeIntentService extends IntentService {
private static final String TAG = "LocationChangeIntentService";
Expand Down Expand Up @@ -75,9 +78,9 @@ protected void onHandleIntent(Intent intent) {
*/
PollSensorManager.getAndSaveAllValues(this);

Location loc = (Location)intent.getExtras().get(FusedLocationProviderApi.KEY_LOCATION_CHANGED);
List<Location> locList = LocationResult.hasResult(intent)? LocationResult.extractResult(intent).getLocations() : null;
LocationAvailability locationAvailability = LocationAvailability.extractLocationAvailability(intent);
Log.d(this, TAG, "Read location "+loc+" from intent");
Log.d(this, TAG, "Read locations "+locList+" from intent");
if (locationAvailability != null) {
Log.d(this, TAG, "availability = "+locationAvailability.isLocationAvailable());
if (!locationAvailability.isLocationAvailable()) {
Expand All @@ -94,10 +97,12 @@ protected void onHandleIntent(Intent intent) {
see http://stackoverflow.com/questions/29960981/why-does-android-fusedlocationproviderapi-requestlocationupdates-send-updates-wi
*/

if (loc == null) return;
if (locList == null) return;

for (Location loc: locList) {
SimpleLocation simpleLoc = new SimpleLocation(loc);
uc.putSensorData(R.string.key_usercache_location, simpleLoc);
}

/*
* If we are going to read data continuously and never stop, then we don't need to read any
Expand Down Expand Up @@ -137,8 +142,12 @@ protected void onHandleIntent(Intent intent) {
SimpleLocation[] points5MinsAgo = uc.getSensorDataForInterval(R.string.key_usercache_filtered_location,
tq, SimpleLocation.class);

boolean validPoint = false;
List<Location> validLocList = new LinkedList<Location>();
List<SimpleLocation> validSimpleLocList = new ArrayList<SimpleLocation>();

for (Location loc: locList) {
boolean validPoint = false;
SimpleLocation simpleLoc = new SimpleLocation(loc);
if (loc.getAccuracy() < ACCURACY_THRESHOLD) {
if (last10Points.length == 0) {
// Insert at least one entry before we can start comparing for duplicates
Expand All @@ -159,6 +168,9 @@ protected void onHandleIntent(Intent intent) {

if (validPoint) {
uc.putSensorData(R.string.key_usercache_filtered_location, simpleLoc);
validLocList.add(loc);
validSimpleLocList.add(simpleLoc);
}
}

double lastTransitionTs = ((BuiltinUserCache)uc).getTsOfLastTransition();
Expand All @@ -167,11 +179,11 @@ protected void onHandleIntent(Intent intent) {

// We will check whether the trip ended only when the point is valid.
// Otherwise, we might end up with the duplicates triggering trip ends.
if (validPoint && isTripEnded(last10Points, points5MinsAgo, tripEndSecs)) {
if (validLocList.size() > 0 && isTripEnded(last10Points, points5MinsAgo, tripEndSecs)) {
// Stop listening to more updates
Intent stopMonitoringIntent = new Intent();
stopMonitoringIntent.setAction(getString(R.string.transition_stopped_moving));
stopMonitoringIntent.putExtra(FusedLocationProviderApi.KEY_LOCATION_CHANGED, loc);
// stopMonitoringIntent.putExtra(FusedLocationProviderApi.KEY_LOCATION_CHANGED, validLocList.get(0));
sendBroadcast(new ExplicitIntent(this, stopMonitoringIntent));
Log.d(this, TAG, "Finished broadcasting state change to receiver, ending trip now");
// DataUtils.endTrip(this);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import androidx.annotation.Nullable;

import edu.berkeley.eecs.emission.MainActivity;

Expand Down
16 changes: 1 addition & 15 deletions src/android/location/TripDiaryStateMachineReceiver.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,12 @@
package edu.berkeley.eecs.emission.cordova.tracker.location;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.os.Build;
import android.preference.PreferenceManager;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;

import org.apache.cordova.ConfigXmlParser;
import org.json.JSONException;
import org.json.JSONObject;

Expand Down Expand Up @@ -140,13 +132,7 @@ public static void performPeriodicActivity(Context ctxt) {
}

public static void checkLocationStillAvailable(Context ctxt) {
GoogleApiClient mApiClient = new GoogleApiClient.Builder(ctxt)
.addApi(LocationServices.API)
.build();
// This runs as part of the service thread and not the UI thread, so can block
// can switch to Tasks later anyway
mApiClient.blockingConnect();
TripDiaryStateMachineService.checkLocationSettingsAndPermissions(ctxt, mApiClient);
TripDiaryStateMachineService.checkLocationSettingsAndPermissions(ctxt);
}

public static void validateAndCleanupState(Context ctxt) {
Expand Down
Loading

0 comments on commit d0ccc2e

Please sign in to comment.