8 Commits
Author SHA1 Message Date
Marcus Handte a829aa01df Release 1.0.24
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-05-23 15:52:17 +02:00
Marcus Handte 76315eedc3 Remove deployment to beta.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-05-23 15:18:34 +02:00
handte 108df0d614 Remove unused robolectric tests.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2022-05-23 15:00:34 +02:00
Marcus Handte 449e128373 Prepare android app for upgrade.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2022-05-23 14:47:37 +02:00
handte be53bc8cfa Upgrade Android libraries and Swagger generators.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2022-05-22 19:32:37 +02:00
handte 70f8c27341 Upgrade project and dependencies.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2022-05-22 13:26:49 +02:00
handte f27c43bf92 Add monitoring script for experiments.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-12-16 11:53:43 +01:00
handte 5a9e73b72f Update to 1.0.24-SNAPSHOT.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-12-14 11:36:12 +01:00
240 changed files with 1445 additions and 11857 deletions
Vendored
+4 -4
View File
@@ -49,15 +49,15 @@ node {
if (env.BRANCH_NAME == "master" && release) {
echo "Deploying to production server ..."
withCredentials([sshUserPrivateKey(credentialsId: "mowesta-server-key", keyFileVariable: "KEYFILE")]) {
// sh 'scp -i $KEYFILE site-ear/build/libs/site-ear-' + version + '.ear wildfly@apps-pro.nes.uni-due.de:/opt/wildfly-21-mowesta/standalone/deployments/mowesta.ear'
sh 'scp -i $KEYFILE site-ear/build/libs/site-ear-' + version + '.ear wildfly@apps-pro.nes.uni-due.de:/opt/wildfly-21-mowesta/standalone/deployments/mowesta.ear'
sh 'scp -i $KEYFILE android-app/build/outputs/apk/prod/release/*.apk wildfly@apps-pro.nes.uni-due.de:/opt/android/mowesta/'
sh 'scp -i $KEYFILE android-app/build/outputs/bundle/prodRelease/*.aab wildfly@apps-pro.nes.uni-due.de:/opt/android/mowesta/'
}
} else if (env.BRANCH_NAME == "master" || env.BRANCH_NAME == "feat/auth") {
echo "Deploying to beta server ..."
} else if (env.BRANCH_NAME == "master") {
/* echo "Deploying to beta server ..."
withCredentials([sshUserPrivateKey(credentialsId: "mowesta-server-key", keyFileVariable: "KEYFILE")]) {
sh 'scp -i $KEYFILE site-ear/build/libs/site-ear-' + version + '.ear wildfly@apps-dev.nes.uni-due.de:/opt/wildfly-21-beta/standalone/deployments/mowesta.ear'
}
} */
} else {
echo "Skipping deployment for non-master branch."
}
@@ -2,7 +2,7 @@ plugins {
id 'org.hidetake.swagger.generator' version '2.18.2'
}
description = "Mowesta Android Feign"
description = "MoWeSta Android Api"
// downgrade jackson for Android, since versions > 2.9
// will contain module-info.class files that will result
@@ -33,7 +33,7 @@ swaggerSources {
language = 'java'
configFile = file('config.json')
components = [ models: true, apis: 'Default']
rawOptions = [ '--import-mappings', 'Geometry=org.geojson.Geometry']
rawOptions = [ '--import-mappings', 'Geometry=org.geojson.Geometry']
}
}
+22 -23
View File
@@ -2,7 +2,7 @@ apply plugin: 'org.handte.gradle-android-eclipse'
apply plugin: 'com.android.application'
apply plugin: 'com.google.android.gms.oss-licenses-plugin'
description = "Mowesta Android App"
description = "MoWeSta Android App"
ext {
@@ -13,16 +13,17 @@ ext {
versionAndroidXRecycler = '1.2.1'
versionAndroidXPaging = '2.1.2'
versionAndroidXCard = '1.0.0'
versionAndroidXCoordinator = '1.1.0'
versionAndroidXConstraint = '2.1.2'
versionAndroidXCoordinator = '1.2.0'
versionAndroidXConstraint = '2.1.3'
versionAndroidXNavigation = '2.3.5'
versionAndroidXLifecycle = '2.4.0'
versionAndroidXLifecycle = '2.4.1'
versionAndroidXSecurity = '1.0.0'
versionAndroidXViewpager = '1.0.0'
versionGoogleMaterial = '1.4.0'
versionAndroidXWork = '2.7.1'
versionGoogleMaterial = '1.6.0'
versionAndroidXSwipeRefresh = '1.1.0'
versionAndroidXWebkit = '1.4.0'
versionExoPlayer = '2.16.1'
versionExoPlayer = '2.17.1'
versionApp = project.version
}
@@ -41,7 +42,7 @@ dependencies {
implementation "javax.xml.bind:jaxb-api:${versionJaxb}"
implementation "androidx.appcompat:appcompat:${versionAndroidXAppcompat}"
implementation "androidx.work:work-runtime:${versionAndroidXWork}"
implementation "com.google.android.material:material:${versionGoogleMaterial}"
implementation "androidx.preference:preference:${versionAndroidXPreference}"
implementation "androidx.cardview:cardview:${versionAndroidXCard}"
@@ -83,14 +84,13 @@ dependencies {
testImplementation "junit:junit:${versionJunit}"
testImplementation "androidx.test:core:${versionAndroidXTest}"
testImplementation "androidx.arch.core:core-testing:${versionAndroidXCoreTest}"
testImplementation "org.robolectric:robolectric:${versionRobolectric}"
}
configurations {
all {
exclude group: 'com.google.auto.service', module: 'auto-service'
}
all {
exclude group: 'com.google.auto.service', module: 'auto-service'
exclude group: 'androidx.lifecycle', module: 'lifecycle-viewmodel-ktx'
}
}
@@ -100,7 +100,7 @@ android {
applicationId "com.mowesta.android.app"
minSdkVersion 19
targetSdkVersion 30
versionCode 23
versionCode 24
versionName "${versionApp}"
buildConfigField "long", "BUILD_TIME", System.currentTimeMillis() + "L"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
@@ -143,7 +143,8 @@ android {
beta {
dimension "backend"
applicationIdSuffix ".beta"
resValue "string", "mowesta_url_default", "https://beta.mowesta.com/api"
resValue "string", "mowesta_url_default", "https://www.mowesta.com/api"
// resValue "string", "mowesta_url_default", "https://beta.mowesta.com/api"
resValue "string", "application_long", "B-MoWeSta"
}
prod {
@@ -161,19 +162,17 @@ android {
includeAndroidResources = true
}
}
lintOptions {
// FragmentTagUsage: replacing fragment with FragmentContainerView breaks Navigation library
// RelativeOverlayp: occurs in video frame which is what we want
// VectorPath: our map and logo representations are very long vectors (consider compressing)
disable 'RelativeOverlap', 'FragmentTagUsage', 'VectorPath'
abortOnError false
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
lint {
abortOnError false
disable 'RelativeOverlap', 'FragmentTagUsage', 'VectorPath'
}
namespace 'com.mowesta.android.app'
}
+3 -12
View File
@@ -1,7 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.mowesta.android.app">
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
@@ -11,6 +10,7 @@
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
@@ -31,8 +31,7 @@
android:launchMode="singleTask"
android:name=".MowestaActivity"
android:windowSoftInputMode="adjustResize"
android:exported="true"
android:label="@string/application_long">
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
@@ -80,13 +79,5 @@
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/widget_measure" />
</receiver>
<receiver
android:name=".widget.WidgetReceiver"
android:exported="true"/>
<service android:name=".MowestaService" />
<service
android:name=".widget.WidgetService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="true"/>
</application>
</manifest>
Binary file not shown.
Binary file not shown.
@@ -4,16 +4,18 @@ import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Handler;
import android.os.Looper;
import android.os.StrictMode;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager;
import com.google.android.exoplayer2.database.ExoDatabaseProvider;
import com.google.android.exoplayer2.database.StandaloneDatabaseProvider;
import com.google.android.exoplayer2.upstream.cache.Cache;
import com.google.android.exoplayer2.upstream.cache.LeastRecentlyUsedCacheEvictor;
import com.google.android.exoplayer2.upstream.cache.SimpleCache;
import com.mowesta.android.app.database.Widget;
import com.mowesta.android.app.repository.ClientFactory;
import com.mowesta.android.app.repository.DeviceRepository;
import com.mowesta.android.app.repository.FavoriteRepository;
@@ -22,7 +24,7 @@ import com.mowesta.android.app.repository.WidgetRepository;
import com.mowesta.android.app.widget.AbstractWidgetProvider;
import com.mowesta.android.app.widget.ForecastWidgetProvider;
import com.mowesta.android.app.widget.MeasureWidgetProvider;
import com.mowesta.android.app.widget.WidgetReceiver;
import com.mowesta.android.app.widget.PeriodicWidgetWorker;
import java.io.File;
@@ -34,6 +36,9 @@ import java.io.File;
*/
public class MowestaApp extends Application implements IApp {
/** The log tag. */
public static final String TAG = "MowestaApp";
/**
* The widget providers of the app.
*/
@@ -82,8 +87,8 @@ public class MowestaApp extends Application implements IApp {
favoriteRepository = new FavoriteRepository(this);
widgetRepository = new WidgetRepository(this);
MowestaService.startService(this);
WidgetReceiver.updateWidgets(this);
WidgetReceiver.scheduleUpdates(this);
PeriodicWidgetWorker.updateWidgets(this);
PeriodicWidgetWorker.scheduleUpdates(this);
//if(BuildConfig.DEBUG)
// StrictMode.enableDefaults();
}
@@ -91,8 +96,9 @@ public class MowestaApp extends Application implements IApp {
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.d(TAG, "Configuration change detected.");
for (int i = widgetProviders.length - 1; i >= 0; i--) {
widgetProviders[i].triggerUpdates(this, false);
widgetProviders[i].triggerUpdates(MowestaApp.this, false);
}
}
@@ -135,7 +141,7 @@ public class MowestaApp extends Application implements IApp {
if (mediaCache == null) {
mediaCache = new SimpleCache(new File(this.getCacheDir(), "videos"),
new LeastRecentlyUsedCacheEvictor(25 * 1000 * 1000),
new ExoDatabaseProvider(getContext()));
new StandaloneDatabaseProvider(getContext()));
}
return mediaCache;
}
@@ -61,7 +61,7 @@ public class AdvertiseDialogFragment extends BottomSheetDialogFragment {
model.getClose().observe(getViewLifecycleOwner(), (v) -> { if (v) this.dismiss(); } );
model.getOpen().observe(getViewLifecycleOwner(), (v) -> {
if (v) {
String url = "https://www.mowesta.com/2021/12/01/fair-experiment-bei-der-eiszeit-in-karlsruhe/";
String url = "https://www.mowesta.com/2022/05/23/fair-experiment-bei-das-fest-in-karlsruhe/";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
try {
@@ -78,7 +78,7 @@ public class AdvertiseDialogFragment extends BottomSheetDialogFragment {
public boolean shouldShow(Context context) {
long time = System.currentTimeMillis();
if (time > 1643500800000l) return false;
if (time > 1658700000000l) return false;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
long last = prefs.getLong(KEY_ADVERTISEMENT, 0);
return (time - last > 7 * 24* 60 * 60 * 1000);
@@ -4,9 +4,7 @@ import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.renderscript.ScriptGroup;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@@ -28,8 +26,7 @@ import com.mowesta.android.app.model.ColorViewModel;
import com.mowesta.android.app.model.ForecastWidgetViewModel;
import com.mowesta.android.app.task.DatabaseTask;
import com.mowesta.android.app.widget.ForecastWidgetProvider;
import com.mowesta.android.app.widget.WidgetReceiver;
import com.mowesta.android.app.widget.WidgetService;
import com.mowesta.android.app.widget.PeriodicWidgetWorker;
import com.mowesta.android.feign.model.City;
/**
@@ -150,7 +147,8 @@ public class ForecastWidgetFragment extends AbstractNetworkFragment {
activity.finish();
}
});
WidgetReceiver.scheduleUpdates(app);
PeriodicWidgetWorker.scheduleUpdates(app);
int id = getWidgetId();
task.execute(id, ((IApp)activity.getApplicationContext()).getWidgetRepository().getDatabase());
Intent resultValue = new Intent();
@@ -34,7 +34,7 @@ import com.mowesta.android.app.model.ColorViewModel;
import com.mowesta.android.app.model.MeasureWidgetViewModel;
import com.mowesta.android.app.task.DatabaseTask;
import com.mowesta.android.app.widget.MeasureWidgetProvider;
import com.mowesta.android.app.widget.WidgetReceiver;
import com.mowesta.android.app.widget.PeriodicWidgetWorker;
import com.mowesta.android.feign.model.Device;
import java.util.ArrayList;
@@ -223,7 +223,7 @@ public class MeasureWidgetFragment extends AbstractNetworkFragment {
activity.finish();
}
});
WidgetReceiver.scheduleUpdates(app);
PeriodicWidgetWorker.scheduleUpdates(app);
int id = getWidgetId();
task.execute(id, ((IApp)activity.getApplicationContext()).getWidgetRepository().getDatabase());
Intent resultValue = new Intent();
@@ -26,14 +26,13 @@ import androidx.preference.PreferenceManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.ui.StyledPlayerView;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource;
import com.google.android.exoplayer2.upstream.cache.CacheDataSource;
import com.google.android.exoplayer2.upstream.cache.SimpleCache;
import com.google.android.exoplayer2.util.Util;
import com.mowesta.android.app.IApp;
import com.mowesta.android.app.MowestaSettings;
@@ -187,7 +186,7 @@ public class VideoFragment extends AbstractNetworkFragment {
/**
* The player.
*/
private PlayerView player;
private StyledPlayerView player;
/**
* The weather video to compute the timings.
@@ -237,7 +236,7 @@ public class VideoFragment extends AbstractNetworkFragment {
model = new ViewModelProvider(this).get(ExoPlayerViewModel.class);
ImageButton zoomButton = view.findViewById(R.id.video_zoom);
player = view.findViewById(R.id.video_view);
player.setShowBuffering(PlayerView.SHOW_BUFFERING_ALWAYS);
player.setShowBuffering(StyledPlayerView.SHOW_BUFFERING_ALWAYS);
overlay = view.findViewById(R.id.video_time);
View frame = LayoutInflater.from(view.getContext()).inflate(R.layout.view_marker, player.getOverlayFrameLayout(), true);
marker = frame.findViewById(R.id.video_marker);
@@ -272,7 +271,7 @@ public class VideoFragment extends AbstractNetworkFragment {
timeUtils = new TimeUtils(System.currentTimeMillis(), timezone);
formatter = new DateFormatter(getContext());
if (model.exoPlayer == null) {
model.exoPlayer = new SimpleExoPlayer.Builder(getContext()).build();
model.exoPlayer = new ExoPlayer.Builder(getContext()).build();
model.scaler.setContent(video.getWidth(), video.getHeight());
IApp app = (IApp)getActivity().getApplication();
DefaultHttpDataSource.Factory hf = new DefaultHttpDataSource.Factory();
@@ -7,7 +7,6 @@ import androidx.lifecycle.MutableLiveData;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.upstream.AssetDataSource;
@@ -23,7 +22,7 @@ public class AdvertiseViewModel extends AndroidViewModel {
public AdvertiseViewModel(Application app) {
super(app);
SimpleExoPlayer.Builder builder = new SimpleExoPlayer.Builder(app);
ExoPlayer.Builder builder = new ExoPlayer.Builder(app);
exoPlayer = builder.build();
DataSource.Factory df = new DataSource.Factory() {
@Override
@@ -32,7 +31,7 @@ public class AdvertiseViewModel extends AndroidViewModel {
}
};
MediaSource videoSource = new ProgressiveMediaSource.Factory(df)
.createMediaSource(MediaItem.fromUri("android_assets:///eiszeit.mp4"));
.createMediaSource(MediaItem.fromUri("android_assets:///dasfest.mp4"));
exoPlayer.setRepeatMode(ExoPlayer.REPEAT_MODE_ALL);
exoPlayer.setMediaSource(videoSource);
exoPlayer.prepare();
@@ -57,7 +57,7 @@ public class DrawerViewModel extends AbstractNetworkViewModel {
* The task to perform the search.
*/
private ApiTask<RequestParameter<String>, LocationHierarchyPage> searchTask = new ApiTask<>((input, client) -> {
return client.searchLocations(getLanguage(), input.getValue(), 0, 10, null);
return client.searchLocations(getLanguage(), input.getValue(), null,0, 10);
}, (input, result) -> {
completeRequest(input, () -> {
results.setValue(result);
@@ -68,7 +68,7 @@ public class ForecastWidgetViewModel extends AbstractNetworkViewModel {
private ApiTask<RequestParameter<String>, CityPage> searchTask = new ApiTask<>(
(input, client) -> {
CityPage cities = client.searchCities(getApplication().getString(R.string.language_code), input.getValue(), 0, 20, null);
CityPage cities = client.searchCities(getApplication().getString(R.string.language_code), input.getValue(), null, 0, 20);
return cities;
},
(input, result) -> {
@@ -150,7 +150,7 @@ public class StationsViewModel extends AbstractNetworkViewModel {
@Override
public void loadInitial(@NonNull LoadInitialParams params, @NonNull LoadInitialCallback<WeatherStation> callback) {
ApiTask<Void, WeatherStationPage> task = new ApiTask<>((v, client) -> { return client.getStations(term,0, params.requestedLoadSize ); },
ApiTask<Void, WeatherStationPage> task = new ApiTask<>((v, client) -> { return client.getStations(0, params.requestedLoadSize, term); },
(v, page) -> { completeRequest(requestCode, () -> callback.onResult(page.getElements(), 0, page.getTotal())); },
(v, status) -> { finishRequest(requestCode, true); });
if (isCurrentRequest(requestCode)) {
@@ -161,7 +161,7 @@ public class StationsViewModel extends AbstractNetworkViewModel {
@Override
public void loadRange(@NonNull LoadRangeParams params, @NonNull LoadRangeCallback<WeatherStation> callback) {
ApiTask<Void, WeatherStationPage> task = new ApiTask<>((v, client) -> { return client.getStations(term, params.startPosition, params.loadSize); },
ApiTask<Void, WeatherStationPage> task = new ApiTask<>((v, client) -> { return client.getStations(params.startPosition, params.loadSize, term); },
(v, page) -> { completeRequest(requestCode, () -> callback.onResult(page.getElements())); },
(v, status) -> { finishRequest(requestCode, true);});
if (isCurrentRequest(requestCode)) {
@@ -133,7 +133,7 @@ public abstract class AbstractWidgetProvider extends AppWidgetProvider {
* @param id The id.
*/
public void triggerUpdate(Context context, int id, boolean schedule) {
if (schedule) WidgetService.scheduleUpdate(context, type, id);
if (schedule) OnetimeWidgetWorker.updateWidget(context, type, id);
Log.d(TAG, "Start database query for widget " + id + ".");
DatabaseTask<WidgetDatabase, Integer, Widget> task = new DatabaseTask<WidgetDatabase, Integer, Widget>((input, database)-> {
List<Widget> widgets = database.getAccessor().get(type, input);
@@ -157,6 +157,7 @@ public abstract class AbstractWidgetProvider extends AppWidgetProvider {
* @return An int array containing the width and height.
*/
protected int[] getWidgetDimensions(Context context, int id) {
Log.d(TAG, "Requesting app widget manager options.");
AppWidgetManager manager = AppWidgetManager.getInstance(context);
Bundle options = manager.getAppWidgetOptions(id);
if (options == null) return new int[] { 0, 0 };
@@ -74,6 +74,7 @@ public class ForecastWidgetProvider extends AbstractWidgetProvider {
@Override
public void updateWidget(Context context, Widget widget) {
Log.d(TAG, "Performing forecast widget update "+ widget.getReference() + ".");
City city = widget.getData(City.class);
if (city == null) {
Log.d(TAG, "Ignoring update without for widget " + widget.getReference() + " without city.");
@@ -92,6 +93,7 @@ public class ForecastWidgetProvider extends AbstractWidgetProvider {
}
days = a.getDays();
}
Log.d(TAG, "Building remote views.");
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_forecast);
// set color
@@ -118,6 +120,7 @@ public class ForecastWidgetProvider extends AbstractWidgetProvider {
}
}
float scale = context.getResources().getDisplayMetrics().scaledDensity / context.getResources().getDisplayMetrics().density;
Log.d(TAG, "Building remote views done.");
int[] widgetDimension = getWidgetDimensions(context, widget.getReference());
int width = widgetDimension[0];
int height = widgetDimension[1];
@@ -59,6 +59,7 @@ public class MeasureWidgetProvider extends AbstractWidgetProvider {
@Override
public void updateWidget(Context context, Widget widget) {
Log.d(TAG, "Performing measure widget update "+ widget.getReference() + ".");
Device device = widget.getData(Device.class);
if (device == null) {
Log.d(TAG, "Ignoring update without for widget " + widget.getReference() + " without device.");
@@ -2,14 +2,17 @@ package com.mowesta.android.app.widget;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.JobIntentService;
import androidx.work.Data;
import androidx.work.OneTimeWorkRequest;
import androidx.work.OutOfQuotaPolicy;
import androidx.work.WorkManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import com.mowesta.android.app.IApp;
import com.mowesta.android.app.database.Widget;
@@ -21,22 +24,32 @@ import com.mowesta.android.feign.model.Device;
import com.mowesta.android.feign.model.Measurement;
import com.mowesta.android.feign.model.MeasurementPage;
import com.mowesta.android.feign.model.WeatherForecast;
import com.mowesta.android.sdk.task.AbstractTask;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* The service that updates the forecast widgets.
*
* @author Marcus
* A worker that updates a widget. The widget reference
* is passed as a parameter to the job.
*/
public class WidgetService extends JobIntentService {
public class OnetimeWidgetWorker extends Worker {
/**
* The worker to update the widget.
*/
public static final String TAG = "OnetimeWidgetWorker";
/**
* The extra containing the reference.
*/
public static final String EXTRA_WIDGET_REFERENCE = "reference";
/**
* The extra containing the widget type.
*/
public static final String EXTRA_WIDGET_TYPE = "type";
/**
* The delay to update the data.
*/
@@ -45,85 +58,64 @@ public class WidgetService extends JobIntentService {
/**
* The delay to update the content.
*/
private static final int DELAY_CONTENT = 1 * 60 * 60 * 1000;
private static final int DELAY_CONTENT = 30 * 60 * 1000;
/** The widget type. */
private int type;
/** The widget reference. */
private int reference;
/** The handler. */
private Handler handler;
/** The app. */
private IApp app;
public OnetimeWidgetWorker(
@NonNull Context context,
@NonNull WorkerParameters params) {
super(context, params);
app = (IApp)context.getApplicationContext();
handler = new Handler(Looper.getMainLooper());
type = params.getInputData().getInt(EXTRA_WIDGET_TYPE, Widget.TYPE_INVALID);
reference = params.getInputData().getInt(EXTRA_WIDGET_REFERENCE, AppWidgetManager.INVALID_APPWIDGET_ID);
}
public static void updateWidget(Context context, int type, int reference) {
Log.d(TAG, "Scheduling update for widget " + type + " " + reference + ".");
WorkManager workManager = WorkManager.getInstance(context);
OneTimeWorkRequest.Builder builder = new OneTimeWorkRequest.Builder(OnetimeWidgetWorker.class);
builder.setInputData(OnetimeWidgetWorker.createData(type, reference));
builder.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST);
OneTimeWorkRequest request = builder.build();
workManager.beginWith(request).enqueue();
}
/**
* The extra containing the widget type.
*/
public static final String EXTRA_WIDGET_TYPE = "type";
/**
* The id for the service.
*/
private static final int SERVICE_ID = 1111;
/**
* The log tag.
*/
private static final String TAG = "WidgetService";
/**
* A handler to perform work on the ui thread.
*/
private Handler handler = new Handler(Looper.getMainLooper());
/**
* Schedules an update for a particular widget referenced by its type and its
* local id.
* Creates the data for scheduling the worker.
*
* @param context Tthe context.
* @param reference The widget reference.
* @param type The widget type.
* @param type The type.
* @param reference The reference.
* @return The data.
*/
public static void scheduleUpdate(Context context, int type, int reference) {
Log.d(TAG, "Schedule background update for widget " + reference + " type " + type + ".");
Intent intent = new Intent();
intent.setClass(context, JobIntentService.class);
intent.putExtra(EXTRA_WIDGET_TYPE, type);
intent.putExtra(EXTRA_WIDGET_REFERENCE, reference);
// schedule background execution with proper locks
enqueueWork(context, WidgetService.class, SERVICE_ID, intent);
// and also execute immediately, if we are on > o
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Handler handler = new Handler(Looper.getMainLooper());
IApp app = (IApp)context.getApplicationContext();
new AbstractTask<Void>(true) {
@Override
protected Void doInBackground() {
updateWidget(app, handler, type, reference);
return null;
}
}.execute();
}
public static Data createData(int type, int reference) {
Data.Builder b = new Data.Builder();
b.putInt(EXTRA_WIDGET_TYPE, type);
b.putInt(EXTRA_WIDGET_REFERENCE, reference);
return b.build();
}
@Override
protected void onHandleWork(@NonNull Intent intent) {
int type = intent.getIntExtra(EXTRA_WIDGET_TYPE, Widget.TYPE_INVALID);
int reference = intent.getIntExtra(EXTRA_WIDGET_REFERENCE, AppWidgetManager.INVALID_APPWIDGET_ID);
IApp app = (IApp)getApplicationContext();
updateWidget(app, handler, type, reference);
}
/**
* Updates the data contained in the widget and requests a ui update.
*
* @param app The app.
* @param handler A handler to trigger a refresh.
* @param type The type.
* @param reference The reference.
*/
public static void updateWidget(IApp app, Handler handler, int type, int reference) {
public Result doWork() {
Log.d(TAG, "Performing update for widget " + type + " " + reference + ".");
if (type == Widget.TYPE_INVALID || reference == AppWidgetManager.INVALID_APPWIDGET_ID) {
Log.d(TAG, "Received an invalid request for type " + type + " and reference " + reference + ".");
return;
return Result.success();
}
WidgetDatabase database = app.getWidgetRepository().getDatabase();
WidgetAccessor accessor = database.getAccessor();
List<Widget> widgets = accessor.get(type, reference);
if (widgets.isEmpty()) {
Log.d(TAG, "Received a request for removed widget with type " + type + " and reference " + reference + ".");
return;
return Result.success();
}
Widget widget = widgets.get(0);
if (type == Widget.TYPE_FORECAST) {
@@ -200,6 +192,7 @@ public class WidgetService extends JobIntentService {
});
}
}
// Indicate whether the work finished successfully with the Result
return Result.success();
}
}
@@ -0,0 +1,95 @@
package com.mowesta.android.app.widget;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.work.ExistingPeriodicWorkPolicy;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import com.mowesta.android.app.database.Widget;
import java.util.concurrent.TimeUnit;
/**
* A widget worker that is scheduled for periodic
* execution and triggers immediate one-time updates
* for all widgets.
*
* @author Marcus
*/
public class PeriodicWidgetWorker extends Worker {
public static final String TAG = "PeriodicWidgetWorker";
private static final String WORK_TAG = "widget_refresh";
public PeriodicWidgetWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
updateWidgets(getApplicationContext());
return Result.success();
}
/**
* Schedules periodic updates to all widgets.
*
* @param context The context.
*/
public static void scheduleUpdates(Context context) {
Log.d(TAG, "Scheduling periodic widget updates.");
PeriodicWorkRequest.Builder builder = new PeriodicWorkRequest.Builder(PeriodicWidgetWorker.class, 15, TimeUnit.MINUTES);
WorkManager.getInstance(context).enqueueUniquePeriodicWork(WORK_TAG, ExistingPeriodicWorkPolicy.KEEP, builder.build());
}
/**
* Updates all widgets one time.
*
* @param context The context.
*/
public static void updateWidgets(Context context) {
Log.d(TAG, "Received widget update request.");
boolean hasWidgets = updateWidgets(context, ForecastWidgetProvider.class, Widget.TYPE_FORECAST);
hasWidgets |= updateWidgets(context, MeasureWidgetProvider.class, Widget.TYPE_MEASURE);
if (!hasWidgets) cancelUpdates(context);
}
/**
* Updates all widgets of a particular provider and returns whether anything
* has been scheduled.
*
* @param context The context.
* @param provider The widget provider class.
* @param type The widget type.
* @return True if any update has been scheduled.
*/
private static boolean updateWidgets(Context context, Class<?> provider, int type) {
AppWidgetManager manager = AppWidgetManager.getInstance(context);
int[] ids = manager.getAppWidgetIds(new ComponentName(context, provider));
WorkManager workManager = WorkManager.getInstance(context);
for (int id: ids) {
OnetimeWidgetWorker.updateWidget(context, type, id);
}
return ids.length > 0;
}
/**
* Removes the scheduled periodic update.
*
* @param context The context.
*/
public static void cancelUpdates(Context context) {
WorkManager.getInstance(context).cancelUniqueWork(WORK_TAG);
}
}
@@ -1,113 +0,0 @@
package com.mowesta.android.app.widget;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.SystemClock;
import android.util.Log;
import com.mowesta.android.app.database.Widget;
/**
* The receiver that is called periodically by the alarm
* manager to perform widget updates every x minutes.
*
* @author Marcus
*/
public class WidgetReceiver extends BroadcastReceiver {
/**
* The log tag.
*/
private static final String TAG = "WidgetReceiver";
/**
* The request code.
*/
private static final int REQuEST_CODE = 2298;
/**
* The initial scheduling delay.
*/
private static final int DELAY_START = 60000;
/**
* The periodic update rate.
*/
private static final int DELAY_PERIOD = 15 * 60000;
@Override
public void onReceive(Context context, Intent intent) {
updateWidgets(context);
}
/**
* Updates all widgets.
*
* @param context The context.
*/
public static void updateWidgets(Context context) {
Log.d(TAG, "Received widget update request.");
boolean hasWidgets = updateWidgets(context, ForecastWidgetProvider.class, Widget.TYPE_FORECAST);
hasWidgets |= updateWidgets(context, MeasureWidgetProvider.class, Widget.TYPE_MEASURE);
if (!hasWidgets) cancelUpdates(context);
}
/**
* Updates all widgets of a particular provider and returns whether anything
* has been scheduled.
*
* @param context The context.
* @param provider The widget provider class.
* @param type The widget type.
* @return True if any update has been scheduled.
*/
private static boolean updateWidgets(Context context, Class<?> provider, int type) {
AppWidgetManager manager = AppWidgetManager.getInstance(context);
int[] ids = manager.getAppWidgetIds(new ComponentName(context, provider));
for (int id: ids) {
WidgetService.scheduleUpdate(context, type, id);
}
return ids.length > 0;
}
/**
* Schedules periodic widget updates.
*
* @param context The context.
*/
public static void scheduleUpdates(Context context) {
Log.d(TAG, "Scheduling periodic widget updates.");
AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + DELAY_START, DELAY_PERIOD, createIntent(context));
}
/**
* Creates a pending intent for the updates.
*
* @param context The context.
* @return The pending intent.
*/
private static PendingIntent createIntent(Context context) {
Intent intent = new Intent(context, WidgetReceiver.class);
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) flags = flags | PendingIntent.FLAG_IMMUTABLE;
return PendingIntent.getBroadcast(context, REQuEST_CODE, intent, flags);
}
/**
* Cancels the period widget updates.
*
* @param context The context.
*/
public static void cancelUpdates(Context context) {
Log.d(TAG, "Canceling periodic widget updates.");
AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(createIntent(context));
}
}
@@ -60,24 +60,25 @@
android:layout_width="match_parent"
android:layout_height="180dp">
<com.google.android.exoplayer2.ui.PlayerView
<com.google.android.exoplayer2.ui.StyledPlayerView
android:id="@+id/video_view"
android:layout_alignParentBottom="true"
app:use_controller="false"
app:resize_mode="zoom"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:text="@string/advertise_title"
android:id="@+id/ad_title"
android:textAppearance="?attr/textAppearanceHeadline3"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:padding="8dp"
android:gravity="center"
android:textColor="@color/black"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="center"
android:padding="8dp"
android:text="@string/advertise_title"
android:textAppearance="?attr/textAppearanceHeadline3"
android:textColor="@color/white" />
<TextView
android:text="@string/advertise_more"
@@ -94,17 +95,17 @@
android:layout_height="wrap_content"/>
<TextView
android:text="@string/advertise_description"
android:id="@+id/ad_text"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:textAppearance="?attr/textAppearanceBody2"
android:textStyle="bold"
android:layout_centerHorizontal="true"
android:gravity="center"
android:padding="8dp"
android:textColor="@color/black"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
android:text="@string/advertise_description"
android:textAppearance="?attr/textAppearanceBody2"
android:textColor="@color/white"
android:textStyle="bold" />
</RelativeLayout>
</LinearLayout>
@@ -8,7 +8,7 @@
android:layout_height="match_parent">
<com.google.android.exoplayer2.ui.PlayerView
<com.google.android.exoplayer2.ui.StyledPlayerView
android:id="@+id/video_view"
android:layout_centerInParent="true"
app:resize_mode="zoom"
@@ -321,9 +321,9 @@
<string name="color_dialog_green">Grün</string>
<string name="advertise_header">Veranstaltungshinweis</string>
<string name="advertise_description">Mach mit beim FAIR Experiment vom 25. November bis zum 30. Januar in Karlsruhe</string>
<string name="advertise_description">Mach mit beim FAIR Experiment bei DAS FEST vom 21. bis zum 24. Juli in Karlsruhe</string>
<string name="advertise_more">Mehr erfahren…</string>
<string name="advertise_title">EISZEIT</string>
<string name="advertise_title">DAS FEST</string>
</resources>
+2 -2
View File
@@ -326,7 +326,7 @@
<string name="color_dialog_green">Green</string>
<string name="advertise_header">Event note</string>
<string name="advertise_description">Join the FAIR Experiment from November 25th to January 30th in Karlsruhe</string>
<string name="advertise_description">Join the FAIR Experiment at DAS FEST from July 21th to 24th in Karlsruhe</string>
<string name="advertise_more">Read more…</string>
<string name="advertise_title">EISZEIT</string>
<string name="advertise_title">DAS FEST</string>
</resources>
@@ -1,41 +0,0 @@
package com.mowesta.android.app.test;
import androidx.test.core.app.ApplicationProvider;
import com.mowesta.android.app.R;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
/**
* Runs a simple roboelectric test.
*
* @author Marcus
*/
@RunWith(RobolectricTestRunner.class)
// you can use the @Config annotation here to configure
// various aspects of the test such as the SDK version,
// the resource type to be loaded (e.g. "en-port" for
// english resources in portrait mode, etc.
// @Config(qualifiers = "en-port", sdk = 18)
@Config(manifest = "AndroidManifest.xml")
public class MainActivityTest {
@Test
public void test() {
// if you do not have an activity or a context, you can get access
// to the application class through the "RuntimeEnvironment" object
String name = ApplicationProvider.getApplicationContext().getResources().getString(R.string.application_long);
System.out.println("The application name is: " + name);
// create an activity
// TODO: fix test failures caused by MainActivity
// Activity activity = Robolectric.setupActivity(MainActivity.class);
// String expectedTitle = activity.getResources().getString(R.string.application_short);
// Assert.assertEquals("Title should match resource.", expectedTitle, activity.getTitle());
// fumble around in the layout
// Assert.assertNotNull("MapView should be loaded.", activity.findViewById(R.id.map));
}
}
@@ -1,62 +0,0 @@
package com.mowesta.android.app.test;
import android.view.View;
import android.widget.Button;
import com.mowesta.android.app.R;
import com.mowesta.android.app.fragment.SplashFragment;
import com.mowesta.android.app.fragment.TermsFragment;
import com.mowesta.android.app.test.util.FragmentActivity;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.android.controller.ActivityController;
import org.robolectric.annotation.Config;
import static org.robolectric.Shadows.shadowOf;
/**
* Runs a simple roboelectric test for start activity.
*
* @author sarah
*/
@RunWith(RobolectricTestRunner.class)
// you can use the @Config annotation here to configure
// various aspects of the test such as the SDK version,
// the resource type to be loaded (e.g. "en-port" for
// english resources in portrait mode, etc.
// @Config(qualifiers = "en-port", sdk = 18)
@Config(manifest = "AndroidManifest.xml")
public class StartActivityTest {
@Test
public void test() {
/*
// create start activity and show logo
ActivityController<FragmentActivity> ac = Robolectric.buildActivity(FragmentActivity.class);
FragmentActivity activity = ac.create().start().visible().resume().get();
final SplashFragment logoFragment = new SplashFragment();
activity.showFragment(logoFragment);
// change to T&Cs
final TermsFragment termsFragment = new TermsFragment();
activity.showFragment(termsFragment);
Assert.assertNotNull("WebView should be present.", activity.findViewById(R.id.web_view));
Assert.assertNotNull("Accept & continue button should be present.", activity.findViewById(R.id.start_button_continue));
// continue to main activity
Button buttonContinue = (Button) activity.findViewById(R.id.start_button_continue);
final boolean[] clicked = new boolean[1];
termsFragment.setOnContinueListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clicked[0] = true;
}
});
buttonContinue.performClick();
Assert.assertTrue("Button click should call continue.", clicked[0]);
*/
}
}
@@ -1,48 +0,0 @@
package com.mowesta.android.app.test.util;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.FrameLayout;
/**
* An activity showing a single fragment. This
* is useful for standalone fragment testing.
*
* @author Marcus
*/
public class FragmentActivity extends AppCompatActivity {
/**
* The id of the view. Somewhat hacky.
*/
public static final int FRAME_ID = 1;
/**
* Creates the fragment with a single frame layout.
*
* @param savedInstanceState The instance state.
*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout view = new FrameLayout(this);
view.setId(FRAME_ID);
this.setContentView(view);
}
/**
* Replaces any fragment on the main view with the
* specified fragment.
*
* @param fragment The fragment.
*/
public void showFragment(Fragment fragment) {
getSupportFragmentManager().beginTransaction().replace(FRAME_ID, fragment).commit();
}
@Override
public void invalidateOptionsMenu() {
super.invalidateOptionsMenu();
}
}
@@ -1,151 +0,0 @@
package com.mowesta.android.app.test.util;
import com.mowesta.android.feign.api.DefaultApi;
import feign.QueryMap;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* A simple proxy generator that enables us to emulate the
* mowesta server locally while testing. If only one method
* is required, you can use the createApiProxy(String,Object)
* method to create a proxy that will return the specified
* object in response to a call to the specified method.
*
* @author Marcus
*/
public class ProxyGenerator {
/**
* An interface for a method filter.
*/
public interface IMethodFilter {
/**
* Returns true if the method is acceptable.
*
* @param m The method.
* @return True if accepted, false otherwise.
*/
boolean accept(Method m);
}
/**
* A method filter that filters out the generated
* methods of the feign library which contain a
* query param annotation (or app should not call
* these methods as it would become dependent on
* the feign library).
*/
public static final IMethodFilter QUERY_PARAM_FILTER = new IMethodFilter() {
@Override
public boolean accept(Method m) {
for (Annotation[] annos: m.getParameterAnnotations()) {
for (Annotation a: annos) {
if (a instanceof QueryMap) {
return false;
}
}
}
return true;
}
};
/**
* Creates a proxy for a in interface that will return the predefined
* values as result of every method call.
*
* @param type The type of the interface to implement.
* @param results The mapping between methods and results.
* @param <T> The interface type to implement.
* @return The proxy for the interface.
*/
@SuppressWarnings("unchecked")
public static <T> T createProxy(Class<T> type, final Map<Method, Object> results) {
return (T)Proxy.newProxyInstance(type.getClassLoader(), new Class[] { type }, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (results.containsKey(method)) {
return results.get(method);
} else {
throw new RuntimeException("Method not proxied (fix your test case).");
}
}
});
}
/**
* Finds a method in an interface type and returns the associated method object.
*
* @param type The interface type.
* @param name The name of the method.
* @param filters A set of filters to apply during search.
* @return The method.
* @throws RuntimeException Thrown if the type does not contain the method or
* if the type specifies multiple methods with the same name.
*/
public static Method findMethod(Class<?> type, String name, IMethodFilter[] filters) {
Set<Method> candidates = new HashSet<>();
method: for (Method m: type.getMethods()) {
if (m.getName().equals(name)) {
for (IMethodFilter f: filters) {
if (! f.accept(m)) continue method;
}
candidates.add(m);
}
}
if (candidates.size() == 0) {
throw new RuntimeException("Cannot find method " + name + " in " + type.getName() + ".");
} else if (candidates.size() > 1) {
throw new RuntimeException("Found " + candidates.size() + " methods for " + name + " in " + type.getName() + ".");
} else {
return candidates.iterator().next();
}
}
/**
* Finds an api method by name.
*
* @param name The name of the method.
* @return The method.
* @throws RuntimeException Thrown if the type does not contain the method or
* if the type specifies multiple methods with the same name.
*/
public static Method findApiMethod(String name) {
return findMethod(DefaultApi.class, name, new IMethodFilter[] { QUERY_PARAM_FILTER });
}
/**
* Creates an api proxy that implements the methods specified by
* the map with the specified result.
*
* @param results The results.
* @return The proxy.
*/
public static DefaultApi createApiProxy(Map<Method, Object> results) {
return createProxy(DefaultApi.class, results);
}
/**
* Creates a simple api proxy that implements the method with the specified name
* using the specified result.
*
* @param method The method.
* @param result The result.
* @return The proxy.
*/
public static DefaultApi createApiProxy(String method, Object result) {
Map<Method, Object> results = new HashMap<>();
results.put(findApiMethod(method), result);
return createApiProxy(results);
}
}
+7 -7
View File
@@ -1,6 +1,6 @@
apply plugin: 'com.android.library'
description = "Mowesta Android SDK"
description = "MoWeSta Android SDK"
// remove project version to workaround bugs in
// oss-license-plugin that detects local libraries
@@ -28,17 +28,17 @@ android {
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
lintOptions {
quiet true
}
lint {
quiet true
}
namespace 'com.mowesta.android.sdk'
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
api project(":android-feign")
api project(":android-api")
implementation "androidx.appcompat:appcompat:${versionAndroidXAppcompat}"
implementation "androidx.preference:preference:${versionAndroidXPreference}"
implementation "androidx.room:room-runtime:${versionAndroidXRoom}"
@@ -49,4 +49,4 @@ dependencies {
testImplementation "androidx.test:core:${versionAndroidXTest}"
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
}
+1 -2
View File
@@ -1,5 +1,4 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mowesta.android.sdk">
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- permission for wifi scanning (used for caching) -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
+12 -12
View File
@@ -5,10 +5,10 @@ apply plugin: 'maven-publish'
buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:7.0.4'
classpath 'com.google.android.gms:oss-licenses-plugin:0.10.4'
classpath 'org.handte.gradle:gradle-android-eclipse:1.0.0'
classpath "org.openbakery:xcode-plugin:0.19.1"
classpath 'com.android.tools.build:gradle:7.2.0'
classpath 'com.google.android.gms:oss-licenses-plugin:0.10.4'
classpath 'org.handte.gradle:gradle-android-eclipse:1.0.0'
classpath "gradle.plugin.org.openbakery:plugin:0.21.0"
}
repositories {
maven {
@@ -24,7 +24,7 @@ allprojects {
// set version for our project
group = 'com.mowesta'
version = '1.0.23'
version = '1.0.24'
// set versions for our libraries
ext {
@@ -44,7 +44,7 @@ allprojects {
// built-in infinispan dependency
versionInfinispan = '9.4.20.Final'
// testing dependencies
versionJunit = '4.13.1'
versionJunit = '4.13.2'
versionArquillianContainer = '2.2.0.Final'
versionArquillianJunit = '1.5.0.Final'
// thorntail dependencies
@@ -54,13 +54,13 @@ allprojects {
mapstructVersion = '1.3.1.Final'
// shared android dependencies
versionAndroidXTest = '1.4.0'
versionAndroidXAppcompat = '1.4.0'
versionAndroidXRoom = '2.3.0'
versionAndroidXPreference = '1.1.1'
versionAndroidXAppcompat = '1.4.1'
versionAndroidXRoom = '2.4.2'
versionAndroidXPreference = '1.2.0'
versionRobolectric = '4.5'
// locoslab libraries and code
versionGeometry = '1.1.4'
versionCarta = '1.1.4'
// locoslab libraries and code
versionGeometry = '1.1.4'
versionCarta = '1.1.4'
}
+2 -2
View File
@@ -1,8 +1,8 @@
plugins {
id 'com.benjaminsproule.swagger' version '1.0.6'
id 'com.benjaminsproule.swagger' version '1.0.14'
}
description = 'Mowesta Common Api'
description = 'MoWeSta Common Api'
dependencies {
api "javax.xml.bind:jaxb-api:${versionJaxb}"
@@ -1,14 +1,12 @@
package com.mowesta.api.location;
import javax.annotation.security.PermitAll;
import javax.enterprise.inject.Default;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.ws.rs.BeanParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
@@ -64,6 +62,7 @@ public interface ILocationService {
* Searches for a particular city by name.
*
* @param pageConfig The page configuration.
* @param context The search context.
* @param term The search term.
* @return The page of cities.
*/
+3 -3
View File
@@ -1,6 +1,6 @@
#Sat Nov 07 15:10:18 CET 2020
#Mon May 23 12:33:06 CEST 2022
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip
zipStoreBase=GRADLE_USER_HOME
-19
View File
@@ -1,19 +0,0 @@
// swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "MowestaApi",
products: [
.library(name: "MowestaApi", targets: ["MowestaApi"]),
],
dependencies: [
.package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.9.1")
],
targets: [
.target(
name: "MowestaApi",
dependencies: ["Alamofire"],
path: "./"
)
]
)
@@ -1,61 +0,0 @@
//
// LocationHierarchy.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
/** Represents a hierarchy of locations. */
public class LocationHierarchy: Codable {
public enum ModelType: String, Codable {
case country = "COUNTRY"
case state = "STATE"
case city = "CITY"
}
/** The unique identifier of the data. */
public var _id: Int64?
/** The time stamp when the data was created. */
public var creationTime: Int64?
/** The time stamp when the data was created. */
public var modificationTime: Int64?
/** A flag to indicate whether the data was deleted. */
public var deleted: Bool?
/** The coordinate of the location. */
public var coordinate: Coordinate
/** The type of the location. */
public var type: ModelType
/** The parent of the location (country for states, country or state for cities, null for countries). */
public var parent: LocationHierarchy?
/** The names of the location by language code. */
public var names: [String:String]
public init(_id: Int64?, creationTime: Int64?, modificationTime: Int64?, deleted: Bool?, coordinate: Coordinate, type: ModelType, parent: LocationHierarchy?, names: [String:String]) {
self._id = _id
self.creationTime = creationTime
self.modificationTime = modificationTime
self.deleted = deleted
self.coordinate = coordinate
self.type = type
self.parent = parent
self.names = names
}
public enum CodingKeys: String, CodingKey {
case _id = "id"
case creationTime
case modificationTime
case deleted
case coordinate
case type
case parent
case names
}
}
+17
View File
@@ -0,0 +1,17 @@
// swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "MoWeSta",
products: [
.library(name: "MoWeSta", targets: ["MoWeSta"]),
],
dependencies: [
],
targets: [
.target(
name: "MoWeSta",
path: "./"
)
]
)
@@ -1,11 +1,11 @@
plugins {
id 'org.hidetake.swagger.generator' version '2.18.2'
id 'org.hidetake.swagger.generator' version '2.19.2'
}
description = "Mowesta IOS Alamofire"
description = "MoWeSta iOS Api"
dependencies {
swaggerCodegen 'io.swagger:swagger-codegen-cli:2.4.11'
swaggerCodegen 'io.swagger.codegen.v3:swagger-codegen-cli:3.0.33'
}
swaggerSources {
@@ -14,7 +14,6 @@ swaggerSources {
code {
outputDir = file("${project.buildDir}/swagger")
language = 'swift5'
rawOptions = ['--import-mappings', 'LocationHierarchy=LocationHierarchy']
}
}
}
@@ -1,16 +0,0 @@
//
// CDDataDictionary+CoreDataClass.swift
// app
//
// Created by Sebastian Pobel on 08.02.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
//
import Foundation
import CoreData
@objc(CDDataDictionary)
public class CDDataDictionary: NSManagedObject {
}
@@ -1,39 +0,0 @@
//
// CDDataDictionary+CoreDataProperties.swift
// app
//
// Created by Sebastian Pobel on 08.02.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
//
import Foundation
import CoreData
extension CDDataDictionary {
@nonobjc public class func fetchRequest() -> NSFetchRequest<CDDataDictionary> {
return NSFetchRequest<CDDataDictionary>(entityName: "CDDataDictionary")
}
@NSManaged public var key: String?
@NSManaged public var value: String?
@NSManaged public var measurement: CDMeasurement?
}
enum MeasurementDataContext: String {
case BatteryCharging = "BATTERY_CHARGING"
case CpuFrequency = "CPU_FREQUENCY"
case ScreenEnabled = "SCREEN_ENABLED"
case BatteryTemperature = "BATTERY_TEMPERATURE"
case CpuTemperature = "CPU_TEMPERATURE"
case SensorTemperature = "SENSOR_TEMPERATURE"
case SensorPressure = "SENSOR_PRESSURE"
case SensorHumidity = "SENSOR_HUMIDITY"
case BatteryVoltage = "BATTERY_VOLTAGE"
case SolarVoltage = "SOLAR_VOLTAGE"
}
@@ -1,19 +0,0 @@
//
// CDPlacemarkLocation+CoreDataClass.swift
// app
//
// Created by Sebastian Pobel on 09.02.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
//
import Foundation
import CoreData
//The first decimal place is worth up to 11.1 km: it can distinguish the position of one large city from a neighboring large city.
//The second decimal place is worth up to 1.1 km: it can separate one village from the next.
//The third decimal place is worth up to 110 m: it can identify a large agricultural field or institutional campus.
@objc(CDPlacemarkLocation)
public class CDPlacemarkLocation: NSManagedObject {
}
@@ -1,33 +0,0 @@
//
// CDPlacemarkLocation+CoreDataProperties.swift
// app
//
// Created by Sebastian Pobel on 09.02.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
//
import Foundation
import CoreData
//The first decimal place is worth up to 11.1 km: it can distinguish the position of one large city from a neighboring large city.
//The second decimal place is worth up to 1.1 km: it can separate one village from the next.
//The third decimal place is worth up to 110 m: it can identify a large agricultural field or institutional campus.
extension CDPlacemarkLocation {
@nonobjc public class func fetchRequest() -> NSFetchRequest<CDPlacemarkLocation> {
return NSFetchRequest<CDPlacemarkLocation>(entityName: "CDPlacemarkLocation")
}
@nonobjc public class func fetchRequestFor(latitude: Int, longitude: Int) -> NSFetchRequest<CDPlacemarkLocation> {
let fetchRequest = NSFetchRequest<CDPlacemarkLocation>(entityName: "CDPlacemarkLocation")
fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \CDPlacemarkLocation.latitude, ascending: false)]
fetchRequest.predicate = NSPredicate(format: "latitude == %lld AND longitude == %lld", latitude, longitude)
return fetchRequest
}
@NSManaged public var name: String
@NSManaged public var longitude: Int64
@NSManaged public var latitude: Int64
}
-28
View File
@@ -1,28 +0,0 @@
//
// CDevice+CoreDataClass.swift
// app
//
// Created by Sebastian Pobel on 01.02.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
//
import Foundation
import CoreData
import MowestaApi
@objc(CDevice)
public class CDevice: NSManagedObject {
convenience init(context: NSManagedObjectContext, device: Device) {
self.init(context: context)
self.id = device._id!
self.creationTime = device.creationTime ?? -1000
self.device = device.device
self.manufacturer = device.manufacturer
self.markedDeleted = device.deleted ?? false
self.model = device.model
self.modificationTime = device.modificationTime ?? -1000
self.os = device.os.name
}
}
-81
View File
@@ -1,81 +0,0 @@
//
// CDevice+CoreDataProperties.swift
// app
//
// Created by Sebastian Pobel on 01.02.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
//
import Foundation
import CoreData
extension CDevice {
@nonobjc public class func fetchRequest() -> NSFetchRequest<CDevice> {
let fetchRequest = NSFetchRequest<CDevice>(entityName: "CDevice")
fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \CDevice.id, ascending: true)]
return fetchRequest
}
@nonobjc public class func fetchRequestWithout(id: Int64) -> NSFetchRequest<CDevice> {
let fetchRequest = NSFetchRequest<CDevice>(entityName: "CDevice")
fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \CDevice.id, ascending: true)]
fetchRequest.predicate = NSPredicate(format: "id != %lld", id)
return fetchRequest
}
@nonobjc public class func fetchRequestBy(id: Int64) -> NSFetchRequest<CDevice> {
let fetchRequest = NSFetchRequest<CDevice>(entityName: "CDevice")
fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \CDevice.id, ascending: true)]
fetchRequest.predicate = NSPredicate(format: "id == %lld", id)
return fetchRequest
}
@NSManaged public var creationTime: Int64
@NSManaged public var device: String?
@NSManaged public var id: Int64
@NSManaged public var manufacturer: String?
@NSManaged public var markedDeleted: Bool
@NSManaged public var model: String?
@NSManaged public var modificationTime: Int64
@NSManaged public var os: String?
@NSManaged public var measurements: NSOrderedSet?
}
// MARK: Generated accessors for measurements
extension CDevice {
@objc(insertObject:inMeasurementsAtIndex:)
@NSManaged public func insertIntoMeasurements(_ value: CDMeasurement, at idx: Int)
@objc(removeObjectFromMeasurementsAtIndex:)
@NSManaged public func removeFromMeasurements(at idx: Int)
@objc(insertMeasurements:atIndexes:)
@NSManaged public func insertIntoMeasurements(_ values: [CDMeasurement], at indexes: NSIndexSet)
@objc(removeMeasurementsAtIndexes:)
@NSManaged public func removeFromMeasurements(at indexes: NSIndexSet)
@objc(replaceObjectInMeasurementsAtIndex:withObject:)
@NSManaged public func replaceMeasurements(at idx: Int, with value: CDMeasurement)
@objc(replaceMeasurementsAtIndexes:withMeasurements:)
@NSManaged public func replaceMeasurements(at indexes: NSIndexSet, with values: [CDMeasurement])
@objc(addMeasurementsObject:)
@NSManaged public func addToMeasurements(_ value: CDMeasurement)
@objc(removeMeasurementsObject:)
@NSManaged public func removeFromMeasurements(_ value: CDMeasurement)
@objc(addMeasurements:)
@NSManaged public func addToMeasurements(_ values: NSOrderedSet)
@objc(removeMeasurements:)
@NSManaged public func removeFromMeasurements(_ values: NSOrderedSet)
}
File diff suppressed because it is too large Load Diff
@@ -1,98 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1130"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2C7846D02372F44300766694"
BuildableName = "MoWeSta.app"
BlueprintName = "app"
ReferencedContainer = "container:app.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2C7846E62372F44500766694"
BuildableName = "appTests.xctest"
BlueprintName = "appTests"
ReferencedContainer = "container:app.xcodeproj">
</BuildableReference>
</TestableReference>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2C7846F12372F44500766694"
BuildableName = "appUITests.xctest"
BlueprintName = "appUITests"
ReferencedContainer = "container:app.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2C7846D02372F44300766694"
BuildableName = "MoWeSta.app"
BlueprintName = "app"
ReferencedContainer = "container:app.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2C7846D02372F44300766694"
BuildableName = "MoWeSta.app"
BlueprintName = "app"
ReferencedContainer = "container:app.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>_XCCurrentVersionName</key>
<string>App.xcdatamodel</string>
</dict>
</plist>
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="1" systemVersion="11A491" minimumToolsVersion="Automatic" sourceLanguage="Swift" usedWithCloudKit="false" userDefinedModelVersionIdentifier="">
<entity name="Item" representedClassName="Item" syncable="YES" codeGenerationType="class">
<attribute name="timestamp" optional="YES" attributeType="Date" usesScalarValueType="NO"/>
</entity>
<elements>
<element name="Item" positionX="-63" positionY="-18" width="128" height="44"/>
</elements>
</model>
+20
View File
@@ -0,0 +1,20 @@
//
// AppApp.swift
// App
//
// Created by Marcus Handte on 22.05.22.
//
import SwiftUI
@main
struct AppApp: App {
let persistenceController = PersistenceController.shared
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
}
}
}
-96
View File
@@ -1,96 +0,0 @@
//
// AppDelegate.swift
// app
//
// Created by Marcus Handte on 06.11.19.
// Copyright © 2019 Marcus Handte. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
NSLog("didLaunchApplication")
BackgroundService.shared.registerMeasurementService()
WeatherForecastService.shared.registerWeatherforecastBackgroundService()
let userDefaults = UserDefaults.standard
if !userDefaults.bool(forKey: KeychainKeys.hasRunBefore) {
UserData.shared.reset()
DeviceData.shared.reset() {}
// Update the flag indicator
userDefaults.set(true, forKey: KeychainKeys.hasRunBefore)
}
//let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
//print(urls[urls.count-1] as URL)
return true
}
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
NSLog("new scene session created");
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
NSLog("user discards scene session");
}
func applicationDidEnterBackground(_ application: UIApplication) {
WeatherForecastService.shared.scheduleWeatherforecastBackgroundService()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Mowesta")
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
-29
View File
@@ -1,29 +0,0 @@
//
// AppRootView.swift
// app
//
// Created by Tobias Stottrop on 02.03.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
import SwiftUI
struct AppRootView: View {
@EnvironmentObject var user: UserData
var body: some View {
return Group {
if (user.agreedToS) {
MainTabView()
} else {
TermsRootView()
}
}
}
}
struct AppRootView_Previews: PreviewProvider {
static var previews: some View {
AppRootView()
}
}
@@ -0,0 +1,11 @@
{
"colors" : [
{
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -1,116 +1,93 @@
{
"images" : [
{
"size" : "20x20",
"idiom" : "iphone",
"filename" : "mowesta-20@2x.png",
"scale" : "2x"
"scale" : "2x",
"size" : "20x20"
},
{
"size" : "20x20",
"idiom" : "iphone",
"filename" : "mowesta-20@3x.png",
"scale" : "3x"
"scale" : "3x",
"size" : "20x20"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "mowesta-29@2x.png",
"scale" : "2x"
"scale" : "2x",
"size" : "29x29"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "mowesta-29@3x.png",
"scale" : "3x"
"scale" : "3x",
"size" : "29x29"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "mowesta-40@2x.png",
"scale" : "2x"
"scale" : "2x",
"size" : "40x40"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "mowesta-40@3x.png",
"scale" : "3x"
"scale" : "3x",
"size" : "40x40"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "mowesta-60@2x.png",
"scale" : "2x"
"scale" : "2x",
"size" : "60x60"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "mowesta-60@3x.png",
"scale" : "3x"
"scale" : "3x",
"size" : "60x60"
},
{
"size" : "20x20",
"idiom" : "ipad",
"filename" : "mowesta-20.png",
"scale" : "1x"
"scale" : "1x",
"size" : "20x20"
},
{
"size" : "20x20",
"idiom" : "ipad",
"filename" : "mowesta-20@2x.png",
"scale" : "2x"
"scale" : "2x",
"size" : "20x20"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "mowesta-29.png",
"scale" : "1x"
"scale" : "1x",
"size" : "29x29"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "mowesta-29@2x.png",
"scale" : "2x"
"scale" : "2x",
"size" : "29x29"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "mowesta-40.png",
"scale" : "1x"
"scale" : "1x",
"size" : "40x40"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "mowesta-40@2x.png",
"scale" : "2x"
"scale" : "2x",
"size" : "40x40"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "mowesta-76.png",
"scale" : "1x"
"scale" : "2x",
"size" : "76x76"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "mowesta-76@2x.png",
"scale" : "2x"
"scale" : "2x",
"size" : "83.5x83.5"
},
{
"size" : "83.5x83.5",
"idiom" : "ipad",
"filename" : "mowesta-83.5@2x.png",
"scale" : "2x"
},
{
"size" : "1024x1024",
"idiom" : "ios-marketing",
"filename" : "mowesta-1024.png",
"scale" : "1x"
"scale" : "1x",
"size" : "1024x1024"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
"author" : "xcode",
"version" : 1
}
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 186 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

+3 -3
View File
@@ -1,6 +1,6 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
"author" : "xcode",
"version" : 1
}
}
}
@@ -1,23 +0,0 @@
{
"images" : [
{
"idiom" : "universal",
"filename" : "frontpage.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "frontpage-1.png",
"scale" : "2x"
},
{
"idiom" : "universal",
"filename" : "frontpage-2.png",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 134 KiB

@@ -1,41 +0,0 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
},
"colors" : [
{
"idiom" : "universal",
"color" : {
"platform" : "ios",
"reference" : "systemBackgroundColor"
}
},
{
"idiom" : "universal",
"appearances" : [
{
"appearance" : "luminosity",
"value" : "light"
}
],
"color" : {
"platform" : "ios",
"reference" : "labelColor"
}
},
{
"idiom" : "universal",
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"color" : {
"platform" : "ios",
"reference" : "systemBackgroundColor"
}
}
]
}
@@ -1,51 +0,0 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
},
"colors" : [
{
"idiom" : "universal",
"color" : {
"color-space" : "srgb",
"components" : {
"red" : "1.000",
"alpha" : "1.000",
"blue" : "1.000",
"green" : "1.000"
}
}
},
{
"idiom" : "universal",
"appearances" : [
{
"appearance" : "luminosity",
"value" : "light"
}
],
"color" : {
"color-space" : "srgb",
"components" : {
"red" : "1.000",
"alpha" : "1.000",
"blue" : "1.000",
"green" : "1.000"
}
}
},
{
"idiom" : "universal",
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"color" : {
"platform" : "ios",
"reference" : "secondarySystemBackgroundColor"
}
}
]
}
@@ -1,56 +0,0 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
},
"colors" : [
{
"idiom" : "universal",
"color" : {
"color-space" : "srgb",
"components" : {
"red" : "40",
"alpha" : "1.000",
"blue" : "115",
"green" : "120"
}
}
},
{
"idiom" : "universal",
"appearances" : [
{
"appearance" : "luminosity",
"value" : "light"
}
],
"color" : {
"color-space" : "srgb",
"components" : {
"red" : "40",
"alpha" : "1.000",
"blue" : "115",
"green" : "120"
}
}
},
{
"idiom" : "universal",
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"color" : {
"color-space" : "srgb",
"components" : {
"red" : "0.078",
"alpha" : "1.000",
"blue" : "0.353",
"green" : "0.412"
}
}
}
]
}
@@ -1,59 +0,0 @@
{
"properties" : {
"localizable" : true
},
"info" : {
"version" : 1,
"author" : "xcode"
},
"colors" : [
{
"idiom" : "universal",
"color" : {
"color-space" : "srgb",
"components" : {
"red" : "0.842",
"alpha" : "1.000",
"blue" : "0.192",
"green" : "0.571"
}
}
},
{
"idiom" : "universal",
"appearances" : [
{
"appearance" : "luminosity",
"value" : "light"
}
],
"color" : {
"color-space" : "srgb",
"components" : {
"red" : "0.842",
"alpha" : "1.000",
"blue" : "0.192",
"green" : "0.571"
}
}
},
{
"idiom" : "universal",
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"color" : {
"color-space" : "srgb",
"components" : {
"red" : "1.000",
"alpha" : "1.000",
"blue" : "0.227",
"green" : "0.678"
}
}
}
]
}
@@ -1,56 +0,0 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
},
"colors" : [
{
"idiom" : "universal",
"color" : {
"color-space" : "srgb",
"components" : {
"red" : "0.936",
"alpha" : "1.000",
"blue" : "0.195",
"green" : "0.228"
}
}
},
{
"idiom" : "universal",
"appearances" : [
{
"appearance" : "luminosity",
"value" : "light"
}
],
"color" : {
"color-space" : "srgb",
"components" : {
"red" : "0.936",
"alpha" : "1.000",
"blue" : "0.195",
"green" : "0.228"
}
}
},
{
"idiom" : "universal",
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"color" : {
"color-space" : "srgb",
"components" : {
"red" : "0.936",
"alpha" : "1.000",
"blue" : "0.195",
"green" : "0.228"
}
}
}
]
}
@@ -1,56 +0,0 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
},
"colors" : [
{
"idiom" : "universal",
"color" : {
"color-space" : "srgb",
"components" : {
"red" : "0.500",
"alpha" : "0.300",
"blue" : "0.500",
"green" : "0.500"
}
}
},
{
"idiom" : "universal",
"appearances" : [
{
"appearance" : "luminosity",
"value" : "light"
}
],
"color" : {
"color-space" : "srgb",
"components" : {
"red" : "0.500",
"alpha" : "0.300",
"blue" : "0.500",
"green" : "0.500"
}
}
},
{
"idiom" : "universal",
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"color" : {
"color-space" : "srgb",
"components" : {
"red" : "0.800",
"alpha" : "0.500",
"blue" : "0.800",
"green" : "0.800"
}
}
}
]
}
@@ -1,38 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="15702" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="15704"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="MoWeSta" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="2Mg-n5-0wC">
<rect key="frame" x="170" y="437.5" width="74" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<constraints>
<constraint firstItem="2Mg-n5-0wC" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="centerY" id="MHQ-mn-8Ri"/>
<constraint firstItem="2Mg-n5-0wC" firstAttribute="centerX" secondItem="Ze5-6b-2t3" secondAttribute="centerX" id="VdM-hE-WeM"/>
</constraints>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
</document>
-18
View File
@@ -1,18 +0,0 @@
//
// AuthState.swift
// app
//
// Created by Tobias Stottrop on 04.03.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
import Foundation
enum AuthState {
case ToSScreen
case LoginScreen
case RegistrationScreen
case LocationScreen
case BackgroundScreen
case Finished
}
@@ -1,102 +0,0 @@
//
// DeviceData.swift
// app
//
// Created by Sebastian Pobel on 17.01.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
import os
import Foundation
import KeychainSwift
import MowestaApi
import UIKit
/*
This class provides device information like device token and device id.
This token and id are needed for uploading new measurements.
As this information must be kept secret, it is encrypted and secured in the keychain.
@author Sebastian.Pobel
*/
class DeviceData: ObservableObject {
static var shared = DeviceData()
static let deviceInfo = DeviceInfo(os: .ios, manufacturer: "Apple Inc.", device: UIDevice.current.modelName, model: UIDevice.current.model)
@Published var token: String = ""
@Published private var id: String = ""
var idInt64: Int64 { get { Int64(id) ?? -1 } }
var created : Bool { get { return id != "" && token != "" } }
@Published var bgMeasurement: Bool = false {
willSet {
BackgroundService.shared.activated = newValue
keyChain.set(newValue, forKey: KeychainKeys.device.bgMeasurement)
}
}
let keyChain = KeychainSwift()
private init(token: String? = nil, id: String? = nil, bgMeasurement: Bool? = nil) {
self.token = token ?? keyChain.get(KeychainKeys.device.token) ?? self.token
self.id = id ?? keyChain.get(KeychainKeys.device.id) ?? self.id
self.bgMeasurement = bgMeasurement ?? keyChain.getBool(KeychainKeys.device.bgMeasurement) ?? self.bgMeasurement
os_log("initial load with id: %@", log: .deviceData, type: .info, "\(self.id)")
}
func login() {
os_log("try login", log: .deviceData, type: .debug)
LoginService.shared.toggle()
DeviceAPI.getCurrentDevice(completion: { d, err in
if let device = d {
if (String(describing: device._id!) == self.id) {
os_log("login successful", log: .deviceData, type: .info)
} else {
os_log("token and id does not match", log: .deviceData, type: .error)
self.id = String(describing: device._id!)
os_log("updated id", log: .deviceData, type: .info)
}
} else {
os_log("login not successful", log: .deviceData, type: .info)
}
})
}
private func persist() {
keyChain.set(self.token, forKey: KeychainKeys.device.token)
keyChain.set(String(describing: self.id), forKey: KeychainKeys.device.id)
keyChain.set(self.bgMeasurement, forKey: KeychainKeys.device.bgMeasurement)
LoginService.shared.toggle()
os_log("persisted data", log: .deviceData, type: .debug)
}
func reset(completion: @escaping (() -> Void)) {
token = ""
id = ""
bgMeasurement = false
os_log("deleted data", log: .deviceData, type: .debug)
persist()
os_log("try create new", log: .deviceData, type: .debug)
DeviceAPI.createDevice(body: DeviceData.deviceInfo, completion: { dH, err in
if let deviceHandle = dH {
self.token = deviceHandle.token
self.id = String(describing: deviceHandle._id!)
self.persist()
os_log("create successful", log: .deviceData, type: .info)
completion()
} else {
if let error = err {
NSLog("\(error)")
}
}
})
}
}
#if DEBUG
extension DeviceData {
static let ownDeviceDataMock = DeviceData(token: "ABCDEF", id: "123456", bgMeasurement: true)
}
#endif
@@ -1,27 +0,0 @@
//
// PropertyKeys.swift
// app
//
// Created by Sebastian Pobel on 22.01.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
import Foundation
struct KeychainKeys {
static let hasRunBefore: String = "MoWeSta.hasRunBefore"
struct device {
static let token: String = "MoWeSta.device.token"
static let id: String = "MoWeSta.device.id"
static let bgMeasurement: String = "MoWeSta.device.bgMeasurement"
}
struct user {
static let loginName: String = "MoWeSta.user.loginName"
static let humanName: String = "MoWeSta.user.humanName"
static let password: String = "MoWeSta.user.password"
static let loggedIn: String = "MoWeSta.user.loggedIn"
static let agreedToS: String = "Nowesta.user.agreedToS"
}
}
@@ -1,49 +0,0 @@
//
// SwaggerAPIExtension.swift
// app
//
// Created by Sebastian Pobel on 17.01.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
import Foundation
import MowestaApi
/*
This class is an authorization helper for connection with Mowesta server.
Http Basic Auth is used for User authentication.
Http Bearer Auth is used for Device authentication.
In case of logging out, Http header has to be maniplated.
*/
class LoginService {
private static let authorizationHeader = "Authorization"
private static let basicHeader = "Basic "
private static let bearerHeader = "Bearer "
static let shared = LoginService()
private init() { }
/*
This func sets header of API calls.
As only user or device is logged in, auhtentication header has to be manipulated.
*/
func toggle() {
var auth = ""
if DeviceData.shared.created {
auth += LoginService.bearerHeader + DeviceData.shared.token
}
if UserData.shared.filledIn {
auth += (auth == "") ? "" : ", "
auth += LoginService.basicHeader + (UserData.shared.loginName + ":" + UserData.shared.password).toBase64()
}
if auth != "" {
SwaggerClientAPI.customHeaders[LoginService.authorizationHeader] = auth
} else {
SwaggerClientAPI.customHeaders.removeValue(forKey: LoginService.authorizationHeader)
}
}
}
@@ -1,164 +0,0 @@
//
// UserData.swift
// app
//
// Created by Sebastian Pobel on 16.12.19.
// Copyright © 2019 Marcus Handte. All rights reserved.
//
import os
import Foundation
import KeychainSwift
import UIKit
import MowestaApi
/*
This class provides user information like name and password.
This credentials are needed for accessing mowesta server.
As this information must be kept secret, it is encrypted and secured in the keychain.
@author Sebastian.Pobel
*/
class UserData: ObservableObject {
static var shared = UserData()
@Published var loginName: String = ""
@Published var humanName: String? = nil
@Published var password: String = ""
@Published var loggedIn: Bool = false
@Published var agreedToS: Bool = false
var filledIn : Bool { get { return loginName != "" && password != "" } }
let keyChain = KeychainSwift()
private init(loginName: String? = nil, password: String? = nil, humanName: String? = nil, loggedIn: Bool? = nil, agreedToS: Bool? = nil) {
self.loginName = loginName ?? keyChain.get(KeychainKeys.user.loginName) ?? self.loginName
self.humanName = humanName ?? keyChain.get(KeychainKeys.user.humanName) ?? self.humanName
self.password = password ?? keyChain.get(KeychainKeys.user.password) ?? self.password
self.loggedIn = loggedIn ?? keyChain.getBool(KeychainKeys.user.loggedIn) ?? self.loggedIn
self.agreedToS = agreedToS ?? keyChain.getBool(KeychainKeys.user.agreedToS) ?? self.agreedToS
os_log("initial load with name: %@", log: .userData, type: .info, "\(self.loginName)")
}
func login(onSuccess: @escaping () -> Void, onError: @escaping () -> Void, attempt: Int = 0) {
os_log("login attempt: %ld", log: .userData, type: .debug, attempt)
if attempt > 5 {
//TODO errorhandling
} else {
// no usercredentials?
if (!filledIn) {
os_log("credentials invalid", log: .userData, type: .info)
} else {
os_log("try login", log: .userData, type: .info)
LoginService.shared.toggle()
UserAPI.getCurrentUser(completion: {
self.didLogin(user: $0, error: $1)
if $1 != nil {
onError()
} else {
onSuccess()
}
})
}
}
}
func logout() {
os_log("try loggout", log: .userData, type: .debug)
DataManager.shared.deleteAllData()
reset()
}
func agreeToS() {
agreedToS = true
self.persist()
}
func disagreeToS() {
agreedToS = false
self.persist()
}
func pairDevice() {
if loggedIn {
if !DeviceData.shared.created {
resetDeviceForPairing()
} else {
let d = Device(_id: DeviceData.shared.idInt64, creationTime: 0, modificationTime: 0, deleted: false, user: nil, os: .ios, manufacturer: "Apple Inc.", device: UIDevice.current.modelName, model: UIDevice.current.model)
DeviceAPI.setCurrentDeviceUser(body: d, completion: { d, err in
if let error = err {
switch(error as! ErrorResponse) {
case .error(let statusCode, _, _):
if statusCode == 409 || statusCode == 403 {
self.resetDeviceForPairing()
}
}
} else {
DataManager.shared.loadDevicesFromServer()
}
})
}
}
}
private func resetDeviceForPairing() {
let measurementToggle = DeviceData.shared.bgMeasurement
DeviceData.shared.reset() {
DeviceData.shared.bgMeasurement = measurementToggle
DataManager.shared.loadDevicesFromServer()
}
}
func register(registration: UserRegistration, onSuccess: @escaping () -> Void, onError: @escaping () -> Void) {
UserAPI.registerUser(body: registration, completion: {
self.didLogin(user: $0, error: $1)
if $1 != nil {
onError()
} else {
onSuccess()
}
})
}
private func didLogin(user: User?, error: Error?) {
if let u = user {
self.humanName = u.name
self.loggedIn = true
self.persist()
os_log("login successful", log: .userData, type: .info)
} else {
os_log("login not successful", log: .userData, type: .info)
//TODO errorhandling
}
}
private func persist() {
keyChain.set(self.loginName, forKey: KeychainKeys.user.loginName)
keyChain.set(self.humanName!, forKey: KeychainKeys.user.humanName)
keyChain.set(self.password, forKey: KeychainKeys.user.password)
keyChain.set(self.loggedIn, forKey: KeychainKeys.user.loggedIn)
keyChain.set(self.agreedToS, forKey: KeychainKeys.user.agreedToS)
LoginService.shared.toggle()
os_log("persisted", log: .userData, type: .info)
}
func reset() {
loginName = ""
humanName = ""
password = ""
loggedIn = false
agreedToS = false
os_log("deleted", log: .userData, type: .info)
persist()
}
}
#if DEBUG
extension UserData {
static let mockLoggedOut = UserData(loggedIn: false)
static let mockLoggedIn = UserData(loggedIn: true)
static let mockEmpty = UserData()
static let adminUser = UserData(loginName: "admin", password: "admin", humanName: "Administrator", loggedIn: true)
}
#endif
@@ -1,30 +0,0 @@
//
// DailyPrediction.swift
// app
//
// Created by Tobias Stottrop on 04.03.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
import Foundation
struct DailyPrediction : Hashable {
static func == (lhs: DailyPrediction, rhs: DailyPrediction) -> Bool {
return lhs.day.id == rhs.day.id && lhs.day.date == rhs.day.date && lhs.rawConditions.count == rhs.rawConditions.count && lhs.minTemperature == rhs.minTemperature && lhs.maxTemperature == rhs.maxTemperature && lhs.symbol == rhs.symbol
}
init(min: Double, max: Double, symbol: String, day: Day, rawConditions: [CDWeatherCondition]) {
self.minTemperature = min
self.maxTemperature = max
self.symbol = symbol
self.day = day
self.rawConditions = rawConditions
}
var minTemperature: Double = -1
var maxTemperature: Double = -1
var symbol: String = "unknown"
var day: Day
var rawConditions: [CDWeatherCondition] = [CDWeatherCondition]()
}
@@ -1,82 +0,0 @@
//
// DataManager+CDLocationExtension.swift
// app
//
// Created by Tobias Stottrop on 18.02.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
import Foundation
import MowestaApi
import CoreData
import UIKit
extension DataManager {
typealias MowestaState = MowestaApi.State
struct Holder {
static var _processedLocation: CDLocation = CDLocation()
}
var processedLocation:CDLocation {
get {
return Holder._processedLocation
}
set(newValue) {
Holder._processedLocation = newValue
}
}
func updateLocation(for city: City) -> CDLocation? {
guard let managedContext = getContext() else { return nil}
let location = CDLocation(context: managedContext, city: city)
self.processedLocation = location
WeatherAPI.getCityForecast(_id: location.id, completion: {
self.updateWeatherForecast(forecast: $0, error: $1, completion: nil)
})
do {
try managedContext.save()
} catch let error as NSError {
print("Failed to update city! \(error): \(error.userInfo)")
return nil
}
return location
}
func deleteAllLocations() {
guard let managedContext = getContext() else { return }
let fetchRequest: NSFetchRequest<CDLocation> = CDLocation.fetchRequest()
do {
let items = try managedContext.fetch(fetchRequest)
for item in items {
managedContext.delete(item)
}
try managedContext.save()
} catch {
}
}
func updateLocation(for state: MowestaState) -> CDLocation? {
guard let managedContext = getContext() else { return nil}
let location = CDLocation(context: managedContext, state: state)
do {
try managedContext.save()
} catch let error as NSError {
print("Failed to update State! \(error): \(error.userInfo)")
return nil
}
return location
}
}
#if DEBUG
extension DataManager {
static var locationMock: CDLocation {
let moc = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let cdlocation = CDLocation(context: moc)
cdlocation.id = 48264
return cdlocation
}
}
#endif
@@ -1,43 +0,0 @@
//
// DataManager+CDWeatherforecastExtension.swift
// app
//
// Created by Tobias Stottrop on 18.02.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
import Foundation
import MowestaApi
import CoreData
extension DataManager {
func updateWeatherForecast(forecast: WeatherForecast?, error: Error?, completion: (() -> Void)?) {
if (error != nil) {
//maybe handle
}
if (forecast != nil) {
guard let managedContext = getContext() else { return}
if (self.processedLocation.forecast != nil) {
deleteForecast(self.processedLocation.forecast!)
}
let cdWeatherForecast = CDWeatherForecast(context: managedContext, forecast: forecast!)
cdWeatherForecast.location = self.processedLocation
do {
try managedContext.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
completion?()
}
public func deleteForecast(_ forecast: CDWeatherForecast) {
guard let managedContext = getContext() else { return}
managedContext.delete(forecast)
}
}
#if DEBUG
#endif
@@ -1,101 +0,0 @@
//
// DataManager+DeviceExtension.swift
// app
//
// Created by Sebastian Pobel on 01.02.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
import Foundation
import MowestaApi
import CoreData
import UIKit
extension DataManager {
func loadDevicesFromServer(pageOffset: Int = 0, pageSize: Int = 20) {
DeviceAPI.getCurrentUserDevices(pageOffset: 0, pageSize: 20, completion: { dP, err in
if let devicePage = dP {
if (devicePage.total > devicePage.offset + devicePage.size) {
self.loadDevicesFromServer(pageOffset: devicePage.offset + devicePage.size)
}
self.updateDevicePage(devicePage)
} else if let error = err {
NSLog("\(error)")
}
})
}
func updateDevicePage(_ devicePage: DevicePage) {
guard let managedContext = getContext() else { return }
let fetchRequest: NSFetchRequest<CDevice> = CDevice.fetchRequest()
fetchRequest.includesPropertyValues = false
do {
let cdDevices = try managedContext.fetch(fetchRequest)
// 1. delete devices which are not connected to account anymore
for cdDevice in cdDevices {
var toDelete = true
for device in devicePage.elements {
if cdDevice.id == device._id {
toDelete = false
}
}
if toDelete { managedContext.delete(cdDevice) }
}
// 2. inster new devices
for device in devicePage.elements {
let _ = CDevice(context: managedContext, device: device)
}
try managedContext.save()
} catch let error as NSError {
print("Failed to update new device! \(error): \(error.userInfo)")
}
}
func removeDeviceWith(id: Int64) {
guard let managedContext = getContext() else { return }
let fetchRequest: NSFetchRequest<CDevice> = CDevice.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "id == %lld", id)
do {
let items = try managedContext.fetch(fetchRequest)
for item in items {
managedContext.delete(item)
}
try managedContext.save()
} catch {
}
}
func deleteAllDevices() {
guard let managedContext = getContext() else { return }
let fetchRequest: NSFetchRequest<CDevice> = CDevice.fetchRequest()
fetchRequest.includesPropertyValues = false
do {
let items = try managedContext.fetch(fetchRequest)
for item in items {
managedContext.delete(item)
}
try managedContext.save()
} catch {
}
}
}
#if DEBUG
extension DataManager {
static var deviceMock: CDevice {
let moc = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let device = CDevice(context: moc)
device.id = 13
device.manufacturer = "Apple Inc."
device.model = "iPhone"
device.device = "iPhone"
device.os = "iOS"
return device
}
}
#endif
@@ -1,85 +0,0 @@
//
// DataManager+CDMeasurementExtension.swift
// app
//
// Created by Sebastian Pobel on 02.02.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
import Foundation
import UIKit
import CoreData
import MowestaApi
extension DataManager {
func loadMeasurementsFromServer(device: CDevice, daysBack: Int64, date: Int64) {
if daysBack < 0 { return }
let start = date - (Date.day * daysBack)
let duration = Date.day
loadMeasurementsFromServerForDate(device: device, date: start, duration: duration)
loadMeasurementsFromServer(device: device, daysBack: daysBack - 1, date: date)
}
func loadMeasurementsFromServerForDate(device: CDevice, pageOffset: Int = 0, pageSize: Int = 20, date: Int64 = Date().millisecondsSince1970, duration: Int64 = Date.day) {
DeviceAPI.getDeviceMeasurements(_id: device.id, start: date, duration: duration, pageOffset: pageOffset, pageSize: pageSize) { mP, err in
if let measurementPage = mP {
if (measurementPage.total > measurementPage.offset + measurementPage.size) {
self.loadMeasurementsFromServerForDate(device: device, pageOffset: measurementPage.offset + measurementPage.size, date: date, duration: duration)
}
if measurementPage.elements.count != 0 {
self.updateMeasurementPage(device: device, measurementPage)
}
} else if let error = err {
NSLog("\(error)")
}
}
}
func updateMeasurementPage(device: CDevice, _ measurementPage: MeasurementPage) {
guard let managedContext = getContext() else { return }
for measurement in measurementPage.elements {
let cdMeasurement = CDMeasurement(context: managedContext, measurement: measurement)
device.addToMeasurements(cdMeasurement)
}
do {
try managedContext.save()
} catch let error as NSError {
print("Failed to save new device! \(error): \(error.userInfo)")
}
}
func deleteAllMeasurements() {
guard let managedContext = getContext() else { return }
let fetchRequest: NSFetchRequest<CDMeasurement> = CDMeasurement.fetchRequest()
fetchRequest.includesPropertyValues = false
do {
let items = try managedContext.fetch(fetchRequest)
for item in items {
managedContext.delete(item)
}
try managedContext.save()
} catch {
}
}
}
#if DEBUG
extension DataManager {
static var measurementMock: CDMeasurement {
let moc = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let measurement = CDMeasurement(context: moc)
measurement.creationTime = Date().millisecondsSince1970 + 1000
measurement.humidity = 40
measurement.id = 12910
measurement.markedDeleted = false
measurement.pressure = 1003.94
measurement.temperature = 35
measurement.time = Date().millisecondsSince1970
measurement.version = 1
return measurement
}
}
#endif
@@ -1,50 +0,0 @@
//
// DataManager+CDPlacemarkLocationExtension.swift
// app
//
// Created by Sebastian Pobel on 09.02.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
import Foundation
import CoreData
import CoreLocation
extension DataManager {
//The first decimal place is worth up to 11.1 km: it can distinguish the position of one large city from a neighboring large city.
//The second decimal place is worth up to 1.1 km: it can separate one village from the next.
//The third decimal place is worth up to 110 m: it can identify a large agricultural field or institutional campus.
func addPlacemarkLocation(coordinate: CDCoordinate) {
guard let managedContext = getContext() else { return }
CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude), completionHandler: { placemarks, err in
if let country = placemarks?.first?.country, let city = placemarks?.first?.locality {
let placemarkLocation = CDPlacemarkLocation(context: managedContext)
placemarkLocation.name = "\(city), \(country)"
placemarkLocation.latitude = Int64(coordinate.latitude * 100)
placemarkLocation.longitude = Int64(coordinate.longitude * 100)
do {
try managedContext.save()
} catch let error as NSError {
print("Failed to save new placemark location! \(error): \(error.userInfo)")
}
} else if let error = err {
NSLog("\(error)")
}
})
}
func deleteAllPlacemarkLocations() {
guard let managedContext = getContext() else { return }
let fetchRequest: NSFetchRequest<CDPlacemarkLocation> = CDPlacemarkLocation.fetchRequest()
fetchRequest.includesPropertyValues = false
do {
let items = try managedContext.fetch(fetchRequest)
for item in items {
managedContext.delete(item)
}
try managedContext.save()
} catch {
}
}
}

Some files were not shown because too many files have changed in this diff Show More