39 Commits

Author SHA1 Message Date
Sebastian Seedorf
c4f849072f Untested 2020-12-06 19:49:16 +01:00
Sebastian Seedorf
e9e169ff49 Bug fixed and sync performance improvements 2019-10-31 23:31:36 +01:00
Sebastian Seedorf
58c727b527 Version 43 (1.6.4) 2019-10-28 23:35:05 +01:00
Joshua Priebsch
6ade7b1561 Merge remote-tracking branch 'origin/master' 2019-10-28 23:20:16 +01:00
Joshua Priebsch
0bd9a70415 editing the share textes 2019-10-28 23:18:43 +01:00
Sebastian Seedorf
98d04cb810 Resource Download Android 10 Compatibility 2019-10-28 22:20:44 +01:00
Sebastian Seedorf
22b42ff3f4 Implemented calendar integration 2019-10-28 18:56:12 +01:00
Sebastian Seedorf
e5d7d1faae Better offline access with bad network connection 2019-10-27 22:11:58 +01:00
Sebastian Seedorf
61cf9d6d48 Preference optimizations 2019-10-27 21:47:11 +01:00
Sebastian Seedorf
8abad827a7 Renamed variable 2019-10-24 15:35:02 +02:00
Sebastian Seedorf
ed57ada8ad Version 42 (1.6.3) 2019-10-24 13:27:14 +02:00
Sebastian Seedorf
dae05bda49 Collected Course Types 2019-10-24 13:24:23 +02:00
Sebastian Seedorf
b20f48cf56 Schedule Event Color 2019-10-24 12:11:39 +02:00
Sebastian Seedorf
a0fe303d4b Toolbar Color Fix 2019-10-24 11:23:51 +02:00
Sebastian Seedorf
034b558eeb Schedule Color Fix 2019-10-24 10:45:22 +02:00
Sebastian Seedorf
c641e24a43 Gradebook NullPointerException Fix 2019-10-24 10:41:14 +02:00
Sebastian Seedorf
234e7ebc11 Network and Sync Stabilization 2019-10-24 10:36:04 +02:00
Sebastian Seedorf
8a969a5cfe Version 41 (1.6.2) 2019-10-22 02:29:51 +02:00
Sebastian Seedorf
da03253172 Gradebook Design Update 2019-10-22 02:12:52 +02:00
Sebastian Seedorf
5077898031 Night mode color fix in Gradebook 2019-10-21 22:04:04 +02:00
Sebastian Seedorf
45704c4f35 Added night mode 2019-10-21 18:21:46 +02:00
Sebastian Seedorf
c18f4093e4 Fixed expand card view duration 2019-10-21 12:53:12 +02:00
Sebastian Seedorf
6ddeca6c48 Version 40 (1.6.1) 2019-10-21 01:27:51 +02:00
Sebastian Seedorf
7c54b4c407 Added News 2019-10-21 01:21:44 +02:00
Sebastian Seedorf
451114f254 Added canteen adding dialog 2019-10-21 01:02:33 +02:00
Sebastian Seedorf
633a095dab Fixed expandable card view arrow 2019-10-20 16:23:23 +02:00
Sebastian Seedorf
d8f60635fb Fixed canteen legend icons 2019-10-20 15:31:27 +02:00
Sebastian Seedorf
ab6d81ec8b News Manager silent error fix 2019-10-20 15:17:06 +02:00
Sebastian Seedorf
26742cd704 Vegetarian/Vegan filter 2019-10-20 15:16:45 +02:00
Sebastian Seedorf
59155923a1 Vegetarian/Vegan filter 2019-10-20 15:16:24 +02:00
Sebastian Seedorf
69a0fcb3a3 Tiny News fix up 2019-10-18 18:05:13 +02:00
Sebastian Seedorf
46851a4627 Changed Minimum Android API Level to 21 (Android 5) and Code clean up 2019-10-18 17:44:01 +02:00
Sebastian Seedorf
4925943957 Delete Canteens and Restore Canteen List to Default 2019-10-18 01:49:10 +02:00
Sebastian Seedorf
f358bc1fe1 Canteens only for API 21 upwards, show canteen legend, added Rate button, made share button black 2019-10-17 22:08:05 +02:00
Sebastian Seedorf
c8dac5d2fc Added Rate Button 2019-10-17 15:12:03 +02:00
Sebastian Seedorf
88f885202f Merge remote-tracking branch 'origin/kvv_rename'
# Conflicts:
#	app/build.gradle
#	app/src/main/java/de/sebse/fuplanner/services/kvv/ModulesAnnouncements.java
#	app/src/main/java/de/sebse/fuplanner/services/kvv/ModulesAssignments.java
#	app/src/main/java/de/sebse/fuplanner/services/kvv/ModulesEvents.java
#	app/src/main/java/de/sebse/fuplanner/services/kvv/ModulesGradebook.java
#	app/src/main/java/de/sebse/fuplanner/services/kvv/ModulesList.java
#	app/src/main/java/de/sebse/fuplanner/services/kvv/ModulesResources.java
#	app/src/main/java/de/sebse/fuplanner/services/kvv/sync/KVVLogin.java
2019-10-15 14:42:23 +02:00
Sebastian Seedorf
f3c055ae57 Added iml to git 2019-10-15 14:22:28 +02:00
Sebastian Seedorf
23e061c5f4 Version 39 (1.6) 2019-10-15 12:23:41 +02:00
Sebastian Seedorf
cfaba7a7f5 A lot of changes 2019-10-15 12:12:04 +02:00
144 changed files with 3220 additions and 1404 deletions

1
.gitignore vendored
View File

@@ -1,4 +1,3 @@
*.iml
.gradle
/local.properties
/.idea/*

141
app/app.iml Normal file
View File

@@ -0,0 +1,141 @@
<?xml version="1.0" encoding="UTF-8"?>
<module external.linked.project.id=":app" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="android-gradle" name="Android-Gradle">
<configuration>
<option name="GRADLE_PROJECT_PATH" value=":app" />
<option name="LAST_SUCCESSFUL_SYNC_AGP_VERSION" value="3.5.1" />
<option name="LAST_KNOWN_AGP_VERSION" value="3.5.1" />
</configuration>
</facet>
<facet type="android" name="Android">
<configuration>
<option name="SELECTED_BUILD_VARIANT" value="debug" />
<option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
<option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
<afterSyncTasks>
<task>generateDebugSources</task>
</afterSyncTasks>
<option name="ALLOW_USER_CONFIGURATION" value="false" />
<option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
<option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
<option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res;file://$MODULE_DIR$/build/generated/res/resValues/debug" />
<option name="TEST_RES_FOLDERS_RELATIVE_PATH" value="" />
<option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/build/intermediates/javac/debug/classes" />
<output-test url="file://$MODULE_DIR$/build/intermediates/javac/debugUnitTest/classes" />
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/build/generated/ap_generated_sources/debug/out" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/aidl_source_output_dir/debug/compileDebugAidl/out" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/renderscript_source_output_dir/debug/compileDebugRenderscript/out" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/debug" type="java-resource" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/ap_generated_sources/debugAndroidTest/out" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/aidl_source_output_dir/debugAndroidTest/compileDebugAndroidTestAidl/out" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/renderscript_source_output_dir/debugAndroidTest/compileDebugAndroidTestRenderscript/out" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/androidTest/debug" type="java-test-resource" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/ap_generated_sources/debugUnitTest/out" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/shaders" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/res" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/resources" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/assets" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/aidl" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/rs" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/shaders" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/res" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/resources" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/assets" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/aidl" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/rs" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/shaders" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/shaders" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/shaders" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/res" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/assets" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/aidl" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/rs" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/shaders" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/build" />
</content>
<orderEntry type="jdk" jdkName="Android API 29 Platform" jdkType="Android SDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Gradle: __local_aars__:/media/sebastian/Daten/nextcloud/Documents/Programmierung/Java - Android Studio/fuplanner/app/libs/jericho-html-3.4.jar:unspecified@jar" level="project" />
<orderEntry type="library" name="Gradle: androidx.collection:collection:1.1.0@jar" level="project" />
<orderEntry type="library" name="Gradle: androidx.lifecycle:lifecycle-common:2.1.0@jar" level="project" />
<orderEntry type="library" name="Gradle: androidx.arch.core:core-common:2.1.0@jar" level="project" />
<orderEntry type="library" name="Gradle: androidx.annotation:annotation:1.1.0@jar" level="project" />
<orderEntry type="library" name="Gradle: androidx.constraintlayout:constraintlayout-solver:2.0.0-beta3@jar" level="project" />
<orderEntry type="library" name="Gradle: org.jetbrains:annotations-java5:15.0@jar" level="project" />
<orderEntry type="library" name="Gradle: androidx.preference:preference:1.1.0@aar" level="project" />
<orderEntry type="library" name="Gradle: com.google.android.material:material:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.recyclerview:recyclerview:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.constraintlayout:constraintlayout:2.0.0-beta3@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.appcompat:appcompat:1.1.0@aar" level="project" />
<orderEntry type="library" name="Gradle: com.ms-square:expandableTextView:0.1.4@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.legacy:legacy-support-core-ui:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: com.google.android.gms:play-services-base:17.1.0@aar" level="project" />
<orderEntry type="library" name="Gradle: com.google.android.gms:play-services-tasks:17.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: com.google.android.gms:play-services-basement:17.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.fragment:fragment:1.1.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.appcompat:appcompat-resources:1.1.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.drawerlayout:drawerlayout:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.legacy:legacy-support-core-utils:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.transition:transition:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.viewpager:viewpager:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.coordinatorlayout:coordinatorlayout:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.slidingpanelayout:slidingpanelayout:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.customview:customview:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.swiperefreshlayout:swiperefreshlayout:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.asynclayoutinflater:asynclayoutinflater:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.loader:loader:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.activity:activity:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.vectordrawable:vectordrawable-animated:1.1.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.vectordrawable:vectordrawable:1.1.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.core:core:1.1.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.versionedparcelable:versionedparcelable:1.1.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.cursoradapter:cursoradapter:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.cardview:cardview:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.interpolator:interpolator:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.lifecycle:lifecycle-viewmodel:2.1.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.documentfile:documentfile:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.localbroadcastmanager:localbroadcastmanager:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.print:print:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.lifecycle:lifecycle-runtime:2.1.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.savedstate:savedstate:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.lifecycle:lifecycle-livedata:2.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.lifecycle:lifecycle-livedata-core:2.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.arch.core:core-runtime:2.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: com.android.volley:volley:1.1.1@aar" level="project" />
<orderEntry type="library" name="Gradle: com.github.Cutta:TagView:1.3@aar" level="project" />
</component>
</module>

View File

@@ -1,14 +1,14 @@
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
compileSdkVersion 29
buildToolsVersion '28.0.3'
defaultConfig {
applicationId "de.sebse.fuplanner"
minSdkVersion 15
targetSdkVersion 28
versionCode 39
versionName "1.5.16_2"
minSdkVersion 21
targetSdkVersion 29
versionCode 43
versionName "1.6.4"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
@@ -29,12 +29,13 @@ android {
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'androidx.preference:preference:1.0.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.0-alpha3'
implementation 'com.android.volley:volley:1.1.0'
implementation 'androidx.preference:preference:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.0-beta3'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.android.volley:volley:1.1.1'
implementation 'com.github.Cutta:TagView:1.3'
implementation 'com.google.android.material:material:1.0.0'
implementation 'com.google.android.gms:play-services-base:16.1.0'
implementation 'com.google.android.gms:play-services-base:17.1.0'
implementation 'com.ms-square:expandableTextView:0.1.4'
implementation 'org.jetbrains:annotations-java5:15.0'
//implementation 'com.github.quivr:android-week-view:2.0.2' //com.github.alamkanak:android-week-view:1.2.6

View File

@@ -1,5 +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="de.sebse.fuplanner">
<uses-permission
@@ -21,6 +22,10 @@
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<!-- Calendar integration -->
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
<application
android:allowBackup="true"
android:fullBackupContent="@xml/backup_descriptor"
@@ -58,11 +63,12 @@
android:syncable="true">
</provider>
<activity
android:name=".services.fulogin.FUAuthenticatorActivity"
android:label="@string/title_activity_fuauthenticator" />
<service android:name=".services.fulogin.FUAuthenticatorService">
<service
android:name=".services.fulogin.FUAuthenticatorService"
android:permission="de.sebse.fuplanner.Account">
<intent-filter>
<action android:name="android.accounts.AccountAuthenticator" />
</intent-filter>

View File

@@ -2,11 +2,13 @@ package de.sebse.fuplanner;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
@@ -29,6 +31,7 @@ import java.util.Locale;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.arch.core.util.Function;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
@@ -44,6 +47,7 @@ import de.sebse.fuplanner.fragments.NewsFragment;
import de.sebse.fuplanner.fragments.PrefsFragment;
import de.sebse.fuplanner.fragments.ScheduleFragment;
import de.sebse.fuplanner.fragments.StartupFragment;
import de.sebse.fuplanner.fragments.canteen.CanteensAddFragment;
import de.sebse.fuplanner.fragments.canteen.DaySwitcherFragment;
import de.sebse.fuplanner.fragments.moddetails.ModDetailFragment;
import de.sebse.fuplanner.services.canteen.CanteenBrowser;
@@ -81,6 +85,7 @@ public class MainActivity extends AppCompatActivity
public static final int FRAGMENT_SCHEDULE = 4;
public static final int FRAGMENT_CANTEENS = 5;
public static final int FRAGMENT_CANTEENS_DETAILS = 6;
public static final int FRAGMENT_CANTEENS_ADD = 9;
public static final int FRAGMENT_PREFERENCES = 7;
public static final int FRAGMENT_NEWS = 8;
@@ -169,6 +174,13 @@ public class MainActivity extends AppCompatActivity
toggle.syncState();
}
String nightMode = Preferences.getStringArray(getApplicationContext(), R.array.pref_night_mode);
switch (nightMode) {
case "night": AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); break;
case "day": AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); break;
default: AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM); break;
}
mNavigationView = findViewById(R.id.nav_view);
mNavigationView.setNavigationItemSelectedListener(this);
mFragmentManager = getSupportFragmentManager();
@@ -177,7 +189,7 @@ public class MainActivity extends AppCompatActivity
if (!mAccountManager.hasAccounts(AccountGeneral.ACCOUNT_TYPE)) {
desiredPage = getDefaultFragmentAfterLogout();
desiredData = "";
mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD, null, null);
goToLoginScreen();
updateNavigation();
changeFragment(desiredPage, desiredData);
} else {
@@ -198,16 +210,10 @@ public class MainActivity extends AppCompatActivity
if (!mAlreadyCreated) {
Intent serviceIntent = new Intent(this, KVV.class);
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
getApplicationContext().bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
}
mAlreadyCreated = true;
if (!Preferences.getBoolean(this, R.string.pref_set_auto_sync_on_startup)) {
registerSync(true);
Preferences.setBoolean(this, R.string.pref_set_auto_sync_on_startup, true);
} else {
registerSync(false);
}
CustomNotificationManager.createNotificationChannel(this);
/*getKVV(kvv -> {
kvv.modules().list().recv(list -> {
@@ -217,12 +223,17 @@ public class MainActivity extends AppCompatActivity
});*/
}
private void goToLoginScreen() {
Preferences.setBoolean(this, R.string.pref_set_auto_sync_on_startup, false);
mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD, null, null);
}
@Override
protected void onStart() {
super.onStart();
if (!mAlreadyCreated) {
Intent serviceIntent = new Intent(this, KVV.class);
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
getApplicationContext().bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
}
mAlreadyCreated = true;
}
@@ -233,7 +244,7 @@ public class MainActivity extends AppCompatActivity
if (mKVV != null)
mKVV.removeListener("mainactivity");
if (mBound)
unbindService(mConnection);
getApplicationContext().unbindService(mConnection);
mKVV = null;
mBound = false;
mAlreadyCreated = false;
@@ -267,11 +278,19 @@ public class MainActivity extends AppCompatActivity
updateNavigation();
if (restoreResult == Login.RESTORE_STATUS_SUCCESS && !isLoggedInBeforePause) {
changeFragment(getDefaultFragmentAfterLogin());
registerSync(true);
} else if (restoreResult == Login.RESTORE_STATUS_INVALID_PASSWORD && isLoggedInBeforePause) {
kvv.account().logout(false);
changeFragment(getDefaultFragmentAfterLogout());
}
if (restoreResult == Login.RESTORE_STATUS_SUCCESS || restoreResult == Login.RELOGIN) {
if (!Preferences.getBoolean(this, R.string.pref_set_auto_sync_on_startup) && mAccountManager.hasAccounts(AccountGeneral.ACCOUNT_TYPE)) {
registerSync(true);
Preferences.setBoolean(this, R.string.pref_set_auto_sync_on_startup, true);
} else {
registerSync();
}
}
});
kvv.modules().list().reloadIfOutdated();
});
@@ -305,6 +324,8 @@ public class MainActivity extends AppCompatActivity
} else {
changeFragment(FRAGMENT_CANTEENS);
}
} else if (mFragmentPage == FRAGMENT_CANTEENS_ADD) {
changeFragment(FRAGMENT_CANTEENS);
} else if (kvv.account().isLoggedIn() && mFragmentPage != getDefaultFragmentAfterLogin()) {
changeFragment(getDefaultFragmentAfterLogin());
} else {
@@ -322,6 +343,9 @@ public class MainActivity extends AppCompatActivity
if (mFragmentPage == FRAGMENT_SCHEDULE) {
getMenuInflater().inflate(R.menu.options_schedule, menu);
return true;
} else if (mFragmentPage == FRAGMENT_CANTEENS) {
getMenuInflater().inflate(R.menu.options_canteens, menu);
return true;
}
return false;
}
@@ -333,19 +357,39 @@ public class MainActivity extends AppCompatActivity
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.refresh) {
ScheduleFragment fragment = (ScheduleFragment) mFragmentManager.findFragmentByTag(String.valueOf(FRAGMENT_SCHEDULE));
if (fragment != null && fragment.isVisible()) {
fragment.invalidate(true);
if (mFragmentPage == FRAGMENT_SCHEDULE) {
if (id == R.id.refresh) {
ScheduleFragment fragment = (ScheduleFragment) mFragmentManager.findFragmentByTag(String.valueOf(FRAGMENT_SCHEDULE));
if (fragment != null && fragment.isVisible()) {
fragment.invalidate(true);
}
return true;
} else if (id == R.id.go_to_today) {
ScheduleFragment fragment = (ScheduleFragment) mFragmentManager.findFragmentByTag(String.valueOf(FRAGMENT_SCHEDULE));
if (fragment != null && fragment.isVisible()) {
fragment.goToToday();
}
return true;
}
return true;
} else if (id == R.id.go_to_today) {
ScheduleFragment fragment = (ScheduleFragment) mFragmentManager.findFragmentByTag(String.valueOf(FRAGMENT_SCHEDULE));
if (fragment != null && fragment.isVisible()) {
fragment.goToToday();
} else if (mFragmentPage == FRAGMENT_CANTEENS) {
if (id == R.id.restore) {
CanteensFragment fragment = (CanteensFragment) mFragmentManager.findFragmentByTag(String.valueOf(FRAGMENT_CANTEENS));
if (fragment != null && fragment.isVisible()) {
fragment.restoreDefaults();
}
return true;
}
if (id == R.id.delete) {
CanteensFragment fragment = (CanteensFragment) mFragmentManager.findFragmentByTag(String.valueOf(FRAGMENT_CANTEENS));
if (fragment != null && fragment.isVisible()) {
fragment.startDelete();
}
return true;
}
if (id == R.id.add) {
changeFragment(FRAGMENT_CANTEENS_ADD);
return true;
}
return true;
}
return super.onOptionsItemSelected(item);
@@ -378,6 +422,18 @@ public class MainActivity extends AppCompatActivity
sendIntent.setType("text/plain");
startActivity(sendIntent);
break;
case R.id.nav_rate:
Uri uri = Uri.parse("market://details?id=" + getApplicationContext().getPackageName());
Intent viewIntent = new Intent(Intent.ACTION_VIEW, uri);
viewIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_NEW_DOCUMENT | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(viewIntent);
} catch (ActivityNotFoundException e) {
uri = Uri.parse("http://play.google.com/store/apps/details?id=" + getApplicationContext().getPackageName());
viewIntent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(viewIntent);
}
break;
case R.id.nav_logout:
getKVV(kvv -> {
kvv.account().logout(true);
@@ -401,7 +457,7 @@ public class MainActivity extends AppCompatActivity
}
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
protected void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
if (mFragmentPage != FRAGMENT_STARTUP && mFragmentPage != FRAGMENT_NONE) {
Fragment fragment = mFragmentManager.findFragmentByTag(String.valueOf(mFragmentPage));
savedInstanceState.putInt(ARG_FRAGMENT_PAGE, mFragmentPage);
@@ -474,16 +530,30 @@ public class MainActivity extends AppCompatActivity
changeFragment(newFragment);
}
private void registerSync(boolean onLogin) {
private void registerSync() {
registerSync(false);
}
private void registerSync(boolean isLogin) {
Account accountByType = mAccountManager.getAccountByType(AccountGeneral.ACCOUNT_TYPE);
if (accountByType != null) {
if (onLogin)
if (isLogin || (ContentResolver.getMasterSyncAutomatically() && ContentResolver.getSyncAutomatically(accountByType, KVVContentProvider.PROVIDER_NAME))) {
ContentResolver.setSyncAutomatically(accountByType, KVVContentProvider.PROVIDER_NAME, true);
}
ContentResolver.addPeriodicSync(
accountByType,
KVVContentProvider.PROVIDER_NAME,
Bundle.EMPTY,
Long.parseLong(Preferences.getStringArray(this, R.array.pref_sync_frequency))*60*60);
accountByType,
KVVContentProvider.PROVIDER_NAME,
Bundle.EMPTY,
Long.parseLong(Preferences.getStringArray(this, R.array.pref_sync_frequency)) * 60 * 60
);
forceSync();
}
}
public void forceSync() {
Account accountByType = mAccountManager.getAccountByType(AccountGeneral.ACCOUNT_TYPE);
if (accountByType != null && ContentResolver.getMasterSyncAutomatically() && ContentResolver.getSyncAutomatically(accountByType, KVVContentProvider.PROVIDER_NAME)) {
ContentResolver.requestSync(accountByType, KVVContentProvider.PROVIDER_NAME, Bundle.EMPTY);
}
}
@@ -514,6 +584,9 @@ public class MainActivity extends AppCompatActivity
case FRAGMENT_CANTEENS_DETAILS:
fragment = DaySwitcherFragment.newInstance(newData);
break;
case FRAGMENT_CANTEENS_ADD:
fragment = CanteensAddFragment.newInstance();
break;
case FRAGMENT_CANTEENS:
fragment = CanteensFragment.newInstance();
break;
@@ -589,7 +662,6 @@ public class MainActivity extends AppCompatActivity
int size = mNavigationView.getMenu().size();
try {
Canteen canteen = success.getCanteen(Integer.parseInt(mFragmentData));
//noinspection ConstantConditions
String title = canteen == null ? null : canteen.getName();
for (int k = 0; k < size; k++) {
MenuItem menuItem = mNavigationView.getMenu().getItem(k);
@@ -604,6 +676,7 @@ public class MainActivity extends AppCompatActivity
}, log::e);
return;
case FRAGMENT_CANTEENS:
case FRAGMENT_CANTEENS_ADD:
item = mNavigationView.getMenu().findItem(R.id.nav_canteens);
break;
case FRAGMENT_NEWS:
@@ -634,7 +707,7 @@ public class MainActivity extends AppCompatActivity
if (drawer.isDrawerOpen(GravityCompat.START) && !isDrawerFixed) {
drawer.closeDrawer(GravityCompat.START);
}
mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD, null, null);
goToLoginScreen();
});
}
@@ -666,7 +739,7 @@ public class MainActivity extends AppCompatActivity
for (Canteen canteen: success) {
MenuItem menuItem = mNavigationView.getMenu().add(Menu.NONE, Menu.NONE, 201 + i, canteen.getName());
menuItem.setOnMenuItemClickListener(item -> {
onCanteensFragmentInteraction(canteen.getId());
this.onCanteensFragmentInteraction(canteen.getId());
return false;
});
i++;
@@ -755,6 +828,8 @@ public class MainActivity extends AppCompatActivity
@Override
public void onCanteenRefreshCompleted(boolean isFailed) {
if (!isFailed)
updateNavigation();
setRefreshFailedBanner(isFailed);
}
@@ -818,6 +893,8 @@ public class MainActivity extends AppCompatActivity
@Override
public void onKVVNetworkResponse(NetworkResponse error) {
if (error != null)
updateNavigation();
setRefreshFailedBanner(error != null);
}

View File

@@ -6,20 +6,30 @@ import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.fragments.CanteensFragment.OnCanteensFragmentInteractionListener;
import de.sebse.fuplanner.services.canteen.types.Canteen;
import de.sebse.fuplanner.services.canteen.types.Canteens;
import de.sebse.fuplanner.tools.ui.ItemViewHolder;
import de.sebse.fuplanner.tools.ui.CanteensViewHolder;
import de.sebse.fuplanner.tools.ui.CustomViewHolder;
import de.sebse.fuplanner.tools.ui.StringViewHolder;
/**
* {@link RecyclerView.Adapter} that can display a {@link Canteen} and makes a call to the
* specified {@link OnCanteensFragmentInteractionListener}.
*/
class CanteensAdapter extends RecyclerView.Adapter<ItemViewHolder> {
class CanteensAdapter extends RecyclerView.Adapter<CustomViewHolder> {
private static final int TYPE_DELETE_BUTTON = 1;
private static final int TYPE_ENTRY = 2;
private Canteens mValues;
private final OnCanteensFragmentInteractionListener mListener;
private boolean mIsShowDeletion = false;
private ArrayList<Integer> mDeleteCanteenIds = new ArrayList<>();
private DeletionListener mDeletionListener;
CanteensAdapter(OnCanteensFragmentInteractionListener listener) {
mValues = null;
@@ -33,35 +43,95 @@ class CanteensAdapter extends RecyclerView.Adapter<ItemViewHolder> {
@NonNull
@Override
public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if (viewType == TYPE_DELETE_BUTTON) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_canteens_btn_delete, parent, false);
return new StringViewHolder(view);
}
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_all_items, parent, false);
return new ItemViewHolder(view);
.inflate(R.layout.list_canteens_items, parent, false);
return new CanteensViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {
if (mValues == null)
return;
Canteen canteen = mValues.get(holder.getAdapterPosition());
holder.mTitle.setText(canteen.getName());
holder.mSubLeft.setText(canteen.getAddress());
holder.mSubRight.setText(canteen.getCity());
holder.mView.setOnClickListener(v -> {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onCanteensFragmentInteraction(canteen.getId());
public void onBindViewHolder(@NonNull CustomViewHolder holder, int position) {
int viewType = getItemViewType(position);
if (viewType == TYPE_DELETE_BUTTON) {
((StringViewHolder) holder).mString.setOnClickListener(v -> endDeletion());
} else {
if (mIsShowDeletion) {
position--;
}
});
if (mValues == null)
return;
Canteen canteen = mValues.get(position);
((CanteensViewHolder) holder).mTitle.setText(canteen.getName());
((CanteensViewHolder) holder).mSubLeft.setText(canteen.getAddress());
((CanteensViewHolder) holder).mSubRight.setText(canteen.getCity());
((CanteensViewHolder) holder).mActionIcon.setVisibility(mIsShowDeletion ? View.VISIBLE : View.GONE);
if (mDeleteCanteenIds.contains(canteen.getId())) {
((CanteensViewHolder) holder).mActionIcon.setImageDrawable(holder.mView.getResources().getDrawable(R.drawable.ic_remove_circle));
} else {
((CanteensViewHolder) holder).mActionIcon.setImageDrawable(holder.mView.getResources().getDrawable(R.drawable.ic_remove_circle_outline));
}
((CanteensViewHolder) holder).mActionIcon.setOnClickListener(v -> {
if (mDeleteCanteenIds.contains(canteen.getId())) {
// Prevent calling remove with index
//noinspection SuspiciousMethodCalls
mDeleteCanteenIds.remove((Object) canteen.getId());
} else {
mDeleteCanteenIds.add(canteen.getId());
}
notifyDataSetChanged();
});
holder.mView.setOnClickListener(v -> {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onCanteensFragmentInteraction(canteen.getId());
}
});
}
}
@Override
public int getItemCount() {
if (mValues != null) {
return mValues.size();
return mIsShowDeletion ? mValues.size() + 1 : mValues.size();
}
return 0;
}
@Override
public int getItemViewType(int position) {
return mIsShowDeletion && position == 0 ? TYPE_DELETE_BUTTON : TYPE_ENTRY;
}
public void startDeletion(DeletionListener listener) {
mDeletionListener = listener;
if (mValues.size() > 0) {
mDeleteCanteenIds.clear();
mIsShowDeletion = true;
notifyDataSetChanged();
}
}
public void endDeletion() {
int[] canteenIds = new int[mDeleteCanteenIds.size()];
for (int i = 0; i < mDeleteCanteenIds.size(); i++) {
canteenIds[i] = mDeleteCanteenIds.get(i);
}
mDeletionListener.onDeletionFinished(canteenIds);
mDeleteCanteenIds.clear();
mIsShowDeletion = false;
notifyDataSetChanged();
}
public interface DeletionListener {
void onDeletionFinished(int[] canteenIds);
}
}

View File

@@ -11,10 +11,14 @@ import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import java.util.ArrayList;
import de.sebse.fuplanner.MainActivity;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.services.canteen.CanteenBrowser;
import de.sebse.fuplanner.tools.MainActivityListener;
import de.sebse.fuplanner.tools.Preferences;
import de.sebse.fuplanner.tools.logging.Logger;
/**
@@ -82,7 +86,7 @@ public class CanteensFragment extends Fragment {
@Override
public void onAttach(Context context) {
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof OnCanteensFragmentInteractionListener) {
mListener = (OnCanteensFragmentInteractionListener) context;
@@ -104,6 +108,37 @@ public class CanteensFragment extends Fragment {
mMainActivityListener = null;
}
public void restoreDefaults() {
Preferences.setArrayInt(requireContext(), R.string.pref_canteen_selection, null);
this.refresh(true);
}
public void startDelete() {
adapter.startDeletion(items -> {
int[] canteens = Preferences.getArrayInt(requireContext(), R.string.pref_canteen_selection);
if (canteens != null) {
ArrayList<Integer> newList = new ArrayList<>();
for (int canteen : canteens) {
boolean found = false;
for (int item : items) {
if (item == canteen) {
found = true;
break;
}
}
if (!found) {
newList.add(canteen);
}
}
int[] newCants = new int[newList.size()];
for (int i = 0; i < newList.size(); i++)
newCants[i] = newList.get(i);
Preferences.setArrayInt(requireContext(), R.string.pref_canteen_selection, newCants);
}
this.refresh(true);
});
}
public interface OnCanteensFragmentInteractionListener {
void onCanteensFragmentInteraction(int id);
}

View File

@@ -98,6 +98,8 @@ class ModulesAdapter extends RecyclerView.Adapter<CustomViewHolder> {
lecturers.append(lecturer.getNameShort());
}
iHolder.mSubLeft.setText(lecturers);
// {'G', 'V-Ue', 'P', 'S', 'V', 'Ue', 'L'}
// {'Vorlesung', 'Übung', 'Praktikum', 'Zentralübung', 'Seminaristische Übung', 'Integrierte Veranstaltung', 'Seminar am PC', 'Praxisseminar', 'Seminar', 'Projektseminar', 'Projekt'}
iHolder.mSubRight.setText(module.type);
iHolder.mView.setOnClickListener(v -> {

View File

@@ -82,7 +82,7 @@ public class ModulesFragment extends Fragment {
@Override
public void onAttach(Context context) {
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof OnModulesFragmentInteractionListener) {
mListener = (OnModulesFragmentInteractionListener) context;

View File

@@ -27,11 +27,6 @@ public class NewsFragment extends Fragment {
private Logger log = new Logger(this);
private MainActivityListener mListener;
private NewsAdapter mAdapter;
private NewsList dates = new NewsList();
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
// TODO: Rename and change types of parameters
public NewsFragment() {
@@ -53,7 +48,7 @@ public class NewsFragment extends Fragment {
}
@Override
public void onAttach(Context context) {
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof MainActivityListener) {
mListener = (MainActivityListener) context;

View File

@@ -1,22 +1,40 @@
package de.sebse.fuplanner.fragments;
import android.Manifest;
import android.accounts.Account;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.preference.ListPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import java.util.Arrays;
import de.sebse.fuplanner.MainActivity;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.services.fulogin.AccountGeneral;
import de.sebse.fuplanner.services.kvv.sync.KVVContentProvider;
import de.sebse.fuplanner.services.kvv.ui.Download;
import de.sebse.fuplanner.tools.CustomAccountManager;
import de.sebse.fuplanner.tools.MainActivityListener;
import de.sebse.fuplanner.tools.Preferences;
import de.sebse.fuplanner.tools.RequestPermissionsResultListener;
import de.sebse.fuplanner.tools.logging.Logger;
public class PrefsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener {
private MainActivityListener mMainActivityListener;
private Logger log = new Logger(this);
public static PrefsFragment newInstance() {
PrefsFragment fragment = new PrefsFragment();
Bundle args = new Bundle();
@@ -29,7 +47,7 @@ public class PrefsFragment extends PreferenceFragmentCompat implements SharedPre
// Load the preferences from an XML resource
setPreferencesFromResource(R.xml.preferences, rootKey);
for (String s : getPreferenceScreen().getSharedPreferences().getAll().keySet()) {
onSharedPreferenceChanged(getPreferenceScreen().getSharedPreferences(), s);
updateListPreferenceSummary(s);
}
}
@@ -47,23 +65,87 @@ public class PrefsFragment extends PreferenceFragmentCompat implements SharedPre
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
Preference preference = getPreferenceScreen().findPreference(s);
if (preference instanceof ListPreference)
preference.setSummary(((ListPreference) preference).getEntry());
updateListPreferenceSummary(s);
if (getActivity() != null && getActivity() instanceof MainActivity) {
CustomAccountManager accountManager = ((MainActivity) getActivity()).getAccountManager();
if (accountManager != null) {
Account accountByType = accountManager.getAccountByType(AccountGeneral.ACCOUNT_TYPE);
if (accountByType != null) {
ContentResolver.setSyncAutomatically(accountByType, KVVContentProvider.PROVIDER_NAME, true);
ContentResolver.addPeriodicSync(
accountByType,
KVVContentProvider.PROVIDER_NAME,
Bundle.EMPTY,
Long.parseLong(Preferences.getStringArray(getActivity(), R.array.pref_sync_frequency)));
if (s.equals(requireContext().getString(R.string.pref_sync_frequency))) {
if (getActivity() != null && getActivity() instanceof MainActivity) {
CustomAccountManager accountManager = ((MainActivity) getActivity()).getAccountManager();
if (accountManager != null) {
Account accountByType = accountManager.getAccountByType(AccountGeneral.ACCOUNT_TYPE);
if (accountByType != null) {
ContentResolver.setSyncAutomatically(accountByType, KVVContentProvider.PROVIDER_NAME, true);
ContentResolver.addPeriodicSync(
accountByType,
KVVContentProvider.PROVIDER_NAME,
Bundle.EMPTY,
Long.parseLong(Preferences.getStringArray(getActivity(), R.array.pref_sync_frequency)));
}
}
}
}
if (s.equals(requireContext().getString(R.string.pref_night_mode))) {
String nightMode = Preferences.getStringArray(requireContext(), R.array.pref_night_mode);
switch (nightMode) {
case "night":
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
break;
case "day":
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
break;
default:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
break;
}
}
if (s.equals(requireContext().getString(R.string.pref_add_calendar))
&& getActivity() != null
&& Preferences.getBoolean(getActivity(), R.string.pref_add_calendar)) {
if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_CALENDAR, Manifest.permission.READ_CALENDAR}, 1);
}
}
if (s.equals(requireContext().getString(R.string.pref_add_calendar)) && mMainActivityListener != null) {
log.d("Force sync...");
mMainActivityListener.forceSync();
}
}
private void updateListPreferenceSummary(String s) {
Preference preference = getPreferenceScreen().findPreference(s);
if (preference instanceof ListPreference)
preference.setSummary(((ListPreference) preference).getEntry());
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof MainActivityListener) {
mMainActivityListener = (MainActivityListener) context;
mMainActivityListener.onTitleTextChange(R.string.settings);
mMainActivityListener.addRequestPermissionsResultListener(getRequestPermissionsResultListener(), "PrefFragment");
} else
throw new RuntimeException(context.toString() + " must implement MainActivityListener");
}
@Override
public void onDetach() {
super.onDetach();
mMainActivityListener.removeRequestPermissionsResultListener("PrefFragment");
mMainActivityListener = null;
}
private RequestPermissionsResultListener getRequestPermissionsResultListener() {
return (requestCode, permissions, grantResults) -> {
if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
Preferences.setBoolean(requireContext(), R.string.pref_add_calendar, false);
setPreferenceScreen(null);
setPreferencesFromResource(R.xml.preferences, null);
}
};
}
}

View File

@@ -103,7 +103,7 @@ public class ScheduleFragment extends Fragment implements
@Override
public void onAttach(Context context) {
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof MainActivityListener) {
mListener = (MainActivityListener) context;
@@ -140,7 +140,7 @@ public class ScheduleFragment extends Fragment implements
start.setTimeInMillis(e.getStartDate());
WeekViewEvent weekViewEvent = new WeekViewEvent(e.getModuleId()+"/"+e.getId(), e.getTitle(), e.getLocation(), start, end);
weekViewEvent.setColor(e.getColor());
weekViewEvent.setColor(e.getColor(getContext()));
events.add(weekViewEvent);
}
}

View File

@@ -0,0 +1,108 @@
package de.sebse.fuplanner.fragments.canteen;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import java.util.Arrays;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.services.canteen.types.Canteen;
import de.sebse.fuplanner.services.canteen.types.Canteens;
import de.sebse.fuplanner.tools.Preferences;
import de.sebse.fuplanner.tools.logging.Logger;
import de.sebse.fuplanner.tools.ui.CanteensViewHolder;
class CanteensAddAdapter extends RecyclerView.Adapter<CanteensViewHolder> {
private int[] mElements;
private Canteens mCanteens = null;
@Nullable
private CanteenAddedInterface mCanteenAddedInterface;
private Canteens mValues = null;
private String mFilter = "";
private final Context mContext;
Logger log = new Logger(this);
public CanteensAddAdapter(Context context, @Nullable CanteenAddedInterface canteenAddedInterface) {
mCanteenAddedInterface = canteenAddedInterface;
mContext = context;
mElements = Preferences.getArrayInt(mContext, R.string.pref_canteen_selection);
}
public void setFilterString(String filter) {
mFilter = filter;
this.update();
}
public void setCanteens(Canteens canteens) {
mCanteens = canteens;
this.update();
}
public void update() {
if (mCanteens == null || mFilter == null) {
mValues = null;
} else {
mValues = new Canteens();
for (Canteen canteen : mCanteens) {
boolean found = false;
for (int element : mElements) {
if (element == canteen.getId()) {
found = true;
break;
}
}
if (!found && canteen.contains(mFilter)) {
mValues.addCanteen(canteen);
}
}
}
this.notifyDataSetChanged();
}
@NonNull
@Override
public CanteensViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_canteens_items, parent, false);
return new CanteensViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull CanteensViewHolder holder, int position) {
if (mValues == null)
return;
Canteen canteen = mValues.get(position);
holder.mTitle.setText(canteen.getName());
holder.mSubLeft.setText(canteen.getAddress());
holder.mSubRight.setText(canteen.getCity());
holder.mActionIcon.setVisibility(View.VISIBLE);
holder.mActionIcon.setImageDrawable(holder.mView.getResources().getDrawable(R.drawable.ic_add_circle_outline));
holder.mActionIcon.setOnClickListener(v -> {
mElements = Arrays.copyOf(mElements, mElements.length + 1);
mElements[mElements.length - 1] = canteen.getId();
Preferences.setArrayInt(mContext, R.string.pref_canteen_selection, mElements);
if (mCanteenAddedInterface != null)
mCanteenAddedInterface.onCanteenAdded(canteen.getId());
update();
});
}
@Override
public int getItemCount() {
if (mValues != null) {
return mValues.size();
}
return 0;
}
interface CanteenAddedInterface {
void onCanteenAdded(int canteenId);
}
}

View File

@@ -0,0 +1,129 @@
package de.sebse.fuplanner.fragments.canteen;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import de.sebse.fuplanner.MainActivity;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.services.canteen.CanteenBrowser;
import de.sebse.fuplanner.tools.MainActivityListener;
import de.sebse.fuplanner.tools.logging.Logger;
/**
* A simple {@link Fragment} subclass.
*/
public class CanteensAddFragment extends Fragment implements CanteensAddAdapter.CanteenAddedInterface {
private CanteensAddAdapter adapter;
private SwipeRefreshLayout swipeLayout;
private MainActivityListener mMainActivityListener;
private final Logger log = new Logger(this);
public CanteensAddFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment CanteensAddFragment.
*/
// TODO: Rename and change types and number of parameters
public static CanteensAddFragment newInstance() {
CanteensAddFragment fragment = new CanteensAddFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_canteens_add, container, false);
// Set the adapter
Context context = view.getContext();
RecyclerView recyclerView = view.findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
adapter = new CanteensAddAdapter(context, this);
recyclerView.setAdapter(adapter);
// Getting SwipeContainerLayout
swipeLayout = view.findViewById(R.id.swipe_container);
// Adding Listener
swipeLayout.setOnRefreshListener(() -> refresh(true));
refresh(false);
EditText searchBox = view.findViewById(R.id.search_box);
searchBox.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
adapter.setFilterString(charSequence.toString());
}
@Override
public void afterTextChanged(Editable editable) {
}
});
return view;
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof MainActivityListener) {
mMainActivityListener = (MainActivityListener) context;
mMainActivityListener.onTitleTextChange(R.string.canteens);
} else
throw new RuntimeException(context.toString() + " must implement MainActivityListener");
}
@Override
public void onDetach() {
super.onDetach();
mMainActivityListener = null;
}
private void refresh(boolean forceRefresh) {
if (getActivity() != null) {
CanteenBrowser browser = ((MainActivity) getActivity()).getCanteenBrowser();
browser.getAvailableCanteens(success -> {
adapter.setCanteens(success);
swipeLayout.setRefreshing(false);
}, error -> {
log.e(error.toString());
swipeLayout.setRefreshing(false);
}, forceRefresh);
}
}
@Override
public void onCanteenAdded(int canteenId) {
if (getActivity() != null) {
CanteenBrowser browser = ((MainActivity) getActivity()).getCanteenBrowser();
browser.getCanteens(success -> {}, error -> {}, true);
}
}
}

View File

@@ -1,5 +1,6 @@
package de.sebse.fuplanner.fragments.canteen;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
@@ -11,15 +12,15 @@ class DaySwitcherAdapter extends FragmentStatePagerAdapter {
private Canteen mCanteen = null;
DaySwitcherAdapter(FragmentManager fm) {
super(fm);
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
public void setModule(Canteen canteen) {
public void setCanteen(Canteen canteen) {
mCanteen = canteen;
this.setModule();
this.setCanteen();
}
public void setModule() {
public void setCanteen() {
this.notifyDataSetChanged();
}
@@ -31,6 +32,7 @@ class DaySwitcherAdapter extends FragmentStatePagerAdapter {
}
// Returns the fragment to display for that page
@NonNull
@Override
public Fragment getItem(int position) {
return MealFragment.newInstance(mCanteen.getId(), position);

View File

@@ -101,7 +101,7 @@ public class DaySwitcherFragment extends Fragment implements DaySwitcherListener
}
@Override
public void onAttach(Context context) {
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof MainActivityListener) {
mListener = (MainActivityListener) context;
@@ -127,10 +127,10 @@ public class DaySwitcherFragment extends Fragment implements DaySwitcherListener
browser.getCanteens(canteens -> {
Canteen canteen = canteens.getCanteen(mCanteenId);
canteen.cleanUpDays();
adapterViewPager.setModule(canteen);
adapterViewPager.setCanteen(canteen);
applyPageRequest();
browser.getCanteen(canteen, success -> {
adapterViewPager.setModule();
adapterViewPager.setCanteen();
applyPageRequest();
if (callback != null)
callback.onResponse(success);

View File

@@ -27,6 +27,10 @@ class MealAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final int CATEGORY_OTHER = R.string.others;
private final ArrayList<Object> matches = new ArrayList<>();
private static final int TYPE_MEAL = 0;
private static final int TYPE_HEADER = 1;
private static final int TYPE_LEGEND = 2;
private Day mDay = null;
private final Context mContext;
@@ -37,20 +41,24 @@ class MealAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
if (viewType == 0) {
if (viewType == TYPE_MEAL) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.list_canteen_items, viewGroup, false);
return new MealViewHolder(view);
} else {
} else if (viewType == TYPE_HEADER) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.list_all_caption, viewGroup, false);
return new StringViewHolder(view);
} else {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.list_canteen_legend, viewGroup, false);
return new StringViewHolder(view);
}
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if (holder.getItemViewType() == 0) {
if (holder.getItemViewType() == TYPE_MEAL) {
MealViewHolder viewHolder = ((MealViewHolder) holder);
viewHolder.reset();
Meal meal = getMeal(position);
@@ -107,7 +115,7 @@ class MealAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
viewHolder.mIconVegetarian.setVisibility(meal.getVegan() == Meal.VEGAN_VEGETARIAN ? View.VISIBLE : View.GONE);
viewHolder.mIconBio.setVisibility((meal.getCertificates() & Meal.CERT_BIO) != 0 ? View.VISIBLE : View.GONE);
viewHolder.mIconMsc.setVisibility((meal.getCertificates() & Meal.CERT_MSC) != 0 ? View.VISIBLE : View.GONE);
} else {
} else if (holder.getItemViewType() == TYPE_HEADER) {
StringViewHolder viewHolder = ((StringViewHolder) holder);
viewHolder.mString.setText(getHeading(position));
}
@@ -115,23 +123,25 @@ class MealAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
@Override
public int getItemCount() {
return matches.size();
return matches.size() + 1;
}
@Override
public int getItemViewType(int position) {
return matches.get(position) instanceof String ? 1 : 0;
if (position == 0)
return TYPE_LEGEND;
return matches.get(position - 1) instanceof String ? TYPE_HEADER : TYPE_MEAL;
}
private Meal getMeal(int position) {
if (this.mDay != null)
return this.mDay.get((Integer) matches.get(position));
return this.mDay.get((Integer) matches.get(position - 1));
else
return null;
}
private String getHeading(int position) {
return (String) matches.get(position);
return (String) matches.get(position - 1);
}
public void setDay(Day day) {
@@ -141,8 +151,13 @@ class MealAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public void setDay() {
HashMap<String, ArrayList<Integer>> map = new HashMap<>();
String foodLevel = Preferences.getStringArray(mContext, R.array.pref_food_level);
for (int i = 0; i < this.mDay.size(); i++) {
String category = this.mDay.get(i).getCategory();
Meal meal = this.mDay.get(i);
if (!(meal.getVegan() == Meal.VEGAN_VEGAN || ("vegetarian".equals(foodLevel) && meal.getVegan() == Meal.VEGAN_VEGETARIAN) || "all".equals(foodLevel))) {
continue;
}
String category = meal.getCategory();
boolean found = false;
for (String category_key : CATEGORY_KEYS) {
if (category_key.equals(category)) {

View File

@@ -85,7 +85,7 @@ public class MealFragment extends Fragment {
}
@Override
public void onAttach(Context context) {
public void onAttach(@NonNull Context context) {
super.onAttach(context);
Fragment parentFragment = getParentFragment();
if (parentFragment != null) {
@@ -104,6 +104,10 @@ public class MealFragment extends Fragment {
browser.getCanteens(canteens -> {
Canteen canteen = canteens.getCanteen(mCanteenId);
browser.getCanteen(canteen, success -> {
if (success.size() <= mDayPosition) {
swipeLayout.setRefreshing(false);
return;
}
Day day = success.get(mDayPosition);
adapter.setDay(day);
browser.getDay(day, success1 -> {

View File

@@ -1,6 +1,8 @@
package de.sebse.fuplanner.fragments.moddetails;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
@@ -12,7 +14,7 @@ class ModDetailAdapter extends FragmentStatePagerAdapter {
private final Context mContext;
ModDetailAdapter(FragmentManager fm, String itemPosition, Context context) {
super(fm);
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
this.mContext = context;
this.mItemPos = itemPosition;
}
@@ -25,6 +27,7 @@ class ModDetailAdapter extends FragmentStatePagerAdapter {
}
// Returns the fragment to display for that page
@NonNull
@Override
public Fragment getItem(int position) {
switch (ModulePart.getPartByPage(position)) {

View File

@@ -93,10 +93,7 @@ class ModDetailAnnounceAdapter extends RecyclerView.Adapter<CustomViewHolder> {
try {
return URLDecoder.decode(Regex.regex("/([^/]*)$", url), "UTF-8");
} catch (NoSuchFieldException e) {
e.printStackTrace();
return res.getString(R.string.attachment_nr, index);
} catch (UnsupportedEncodingException e) {
} catch (NoSuchFieldException | UnsupportedEncodingException e) {
e.printStackTrace();
return res.getString(R.string.attachment_nr, index);
}

View File

@@ -2,6 +2,7 @@ package de.sebse.fuplanner.fragments.moddetails;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
@@ -102,15 +103,27 @@ public class ModDetailAnnounceFragment extends Fragment implements Download.OnDo
return;
mListener.getKVV(kvv -> {
kvv.modules().list().find(mItemPos, (Modules.Module module) -> {
String folderName = "FU-"+module.title.replaceAll("[:*<>|/\"\\\\]", "-");
folderName += "/Announcement";
String folderName;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (module.semester != null) {
folderName = module.semester.toString();
} else {
folderName = "PROJ";
}
folderName += "-" + module.title.replaceAll("[:*<>|/\"\\\\]", "-");
folderName += "/Announcements";
} else {
folderName = "FU-"+module.title.replaceAll("[:*<>|/\"\\\\]", "-");
folderName += "/Announcement";
}
getDownload().openDownloadDialog(title, url, folderName);
}, log::e);
});
}
@Override
public void onAttach(Context context) {
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof MainActivityListener) {
this.mListener = ((MainActivityListener) context);

View File

@@ -72,7 +72,7 @@ class ModDetailAssignmentAdapter extends RecyclerView.Adapter<CustomViewHolder>
String name = urlToName(notes.get(i), i, holder.mView.getResources());
Tag tag = new Tag(name);
tag.id = i;
tag.layoutColor = ContextCompat.getColor(holder.mView.getContext(), R.color.colorFUBlue);
tag.layoutColor = ContextCompat.getColor(holder.mView.getContext(), R.color.fuAccent);
holder.mTagGroup.addTag(tag);
}
holder.mTagGroup.setOnTagClickListener((tag, i) -> {
@@ -93,10 +93,7 @@ class ModDetailAssignmentAdapter extends RecyclerView.Adapter<CustomViewHolder>
try {
return URLDecoder.decode(Regex.regex("/([^/]*)$", url), "UTF-8");
} catch (NoSuchFieldException e) {
e.printStackTrace();
return res.getString(R.string.attachment_nr, index);
} catch (UnsupportedEncodingException e) {
} catch (NoSuchFieldException | UnsupportedEncodingException e) {
e.printStackTrace();
return res.getString(R.string.attachment_nr, index);
}

View File

@@ -2,6 +2,7 @@ package de.sebse.fuplanner.fragments.moddetails;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
@@ -102,15 +103,27 @@ public class ModDetailAssignmentFragment extends Fragment implements Download.On
return;
mListener.getKVV(kvv -> {
kvv.modules().list().find(mItemPos, (Modules.Module module) -> {
String folderName = "FU-"+module.title.replaceAll("[:*<>|/\"\\\\]", "-");
folderName += "/Announcement";
String folderName;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (module.semester != null) {
folderName = module.semester.toString();
} else {
folderName = "PROJ";
}
folderName += "-" + module.title.replaceAll("[:*<>|/\"\\\\]", "-");
folderName += "/Assignments";
} else {
folderName = "FU-"+module.title.replaceAll("[:*<>|/\"\\\\]", "-");
folderName += "/Assignment";
}
getDownload().openDownloadDialog(title, url, folderName);
}, log::e);
});
}
@Override
public void onAttach(Context context) {
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof MainActivityListener) {
this.mListener = ((MainActivityListener) context);

View File

@@ -96,7 +96,7 @@ public class ModDetailEventFragment extends Fragment {
}
@Override
public void onAttach(Context context) {
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof MainActivityListener) {
this.mListener = ((MainActivityListener) context);

View File

@@ -97,7 +97,7 @@ public class ModDetailFragment extends Fragment implements ModDetailListener {
}
@Override
public void onAttach(Context context) {
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof MainActivityListener) {
mListener = (MainActivityListener) context;

View File

@@ -13,6 +13,7 @@ import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.services.kvv.types.Grade;
import de.sebse.fuplanner.services.kvv.types.Gradebook;
import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.tools.ui.StringViewHolder;
@@ -20,9 +21,12 @@ class ModDetailGradebookAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
private static final int TYPE_TOTAL = 0;
private static final int TYPE_GRADE = 1;
private static final int SECTION_GRADE = 0;
private static final int SECTION_EXAM = 0;
private static final int SECTION_ASSIGNMENT = 1;
private static final int SECTION_OTHER = 2;
private Modules.Module mValue;
private Gradebook.CategorizedGrades mGrades;
private final ArrayList<Pair<Integer, Integer>> mPositionalData;
ModDetailGradebookAdapter() {
@@ -38,9 +42,32 @@ class ModDetailGradebookAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
private void setModule() {
mPositionalData.clear();
mPositionalData.add(new Pair<>(TYPE_TOTAL, SECTION_GRADE));
for (int i = 0; i < getGradesCount(); i++) {
mPositionalData.add(new Pair<>(TYPE_GRADE, SECTION_GRADE +1024*i));
if (mValue != null && mValue.gradebook != null) {
mGrades = mValue.gradebook.getAutoCategorizedGrades();
int size;
size = mGrades.getExams().grades.size();
if (size > 0) {
mPositionalData.add(new Pair<>(setViewType(TYPE_TOTAL, SECTION_EXAM), 0));
for (int i = 0; i < size; i++) {
mPositionalData.add(new Pair<>(setViewType(TYPE_GRADE, SECTION_EXAM), i));
}
}
size = mGrades.getAssignments().grades.size();
if (size > 0) {
mPositionalData.add(new Pair<>(setViewType(TYPE_TOTAL, SECTION_ASSIGNMENT), 0));
for (int i = 0; i < size; i++) {
mPositionalData.add(new Pair<>(setViewType(TYPE_GRADE, SECTION_ASSIGNMENT), i));
}
}
size = mGrades.getOthers().grades.size();
if (size > 0) {
mPositionalData.add(new Pair<>(setViewType(TYPE_TOTAL, SECTION_OTHER), 0));
for (int i = 0; i < size; i++) {
mPositionalData.add(new Pair<>(setViewType(TYPE_GRADE, SECTION_OTHER), i));
}
}
} else {
mGrades = null;
}
this.notifyDataSetChanged();
@@ -53,8 +80,8 @@ class ModDetailGradebookAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
switch (viewType) {
case TYPE_TOTAL:
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_all_caption, parent, false);
return new StringViewHolder(view);
.inflate(R.layout.list_moddetails_gradebook_title, parent, false);
return new GradeTitleViewHolder(view);
case TYPE_GRADE:
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_moddetails_gradebook, parent, false);
@@ -69,7 +96,7 @@ class ModDetailGradebookAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
public int getItemViewType(int position) {
// Note that unlike in ListView adapters, types don't have to be contiguous
if (position < mPositionalData.size())
return mPositionalData.get(position).first;
return getViewType(mPositionalData.get(position).first);
else return -1;
}
@@ -79,19 +106,45 @@ class ModDetailGradebookAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
if (mValue == null || position > mPositionalData.size())
return;
Pair<Integer, Integer> data = mPositionalData.get(position);
switch (data.first) {
int viewType = getViewType(data.first);
int viewSection = getViewSection(data.first);
Gradebook.GradebookOutput gradebook = getViewSectionGradebook(viewSection);
switch (viewType) {
case TYPE_TOTAL:
StringViewHolder h = (StringViewHolder) holder;
h.mString.setText(h.mView.getResources().getString(R.string.current_percentage, mValue.getGradebookPercent()*100));
break;
case TYPE_GRADE:
int index = data.second / 1024;
GradeViewHolder i = (GradeViewHolder) holder;
Grade gradebook = mValue.gradebook.get(index);
GradeTitleViewHolder h = (GradeTitleViewHolder) holder;
i.mTitle.setText(gradebook.getItemName());
i.mGrade.setText(String.valueOf(gradebook.getPoints()));
i.mGradeMax.setText(String.valueOf(gradebook.getMaxPoints()));
if (gradebook != null) {
String title = "";
switch (viewSection) {
case SECTION_EXAM: title = h.mView.getResources().getString(R.string.exam); break;
case SECTION_ASSIGNMENT: title = h.mView.getResources().getString(R.string.assignments); break;
case SECTION_OTHER: title = h.mView.getResources().getString(R.string.others); break;
}
h.mTitle.setText(title);
Grade bestGrade = gradebook.getBestGrade();
h.mString.setText(h.mView.getResources().getString(
R.string.current_percentage,
gradebook.getUserPointSum(),
gradebook.getMaxPointSum(),
gradebook.getPercentage() * 100,
bestGrade == null ? 0 : bestGrade.getPoints(),
bestGrade == null ? 0 : bestGrade.getMaxPoints(),
bestGrade == null ? 0 : bestGrade.getPoints() / bestGrade.getMaxPoints() * 100,
bestGrade == null ? "" : bestGrade.getItemName()
));
}
break;
case TYPE_GRADE:
int index = data.second;
GradeViewHolder i = (GradeViewHolder) holder;
if (gradebook != null) {
Grade grade = gradebook.grades.get(index);
i.mTitle.setText(grade.getItemName());
i.mGrade.setText(String.valueOf(grade.getPoints()));
i.mGradeMax.setText(String.valueOf(grade.getMaxPoints()));
}
break;
}
}
@@ -101,10 +154,27 @@ class ModDetailGradebookAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
return mPositionalData.size();
}
private int getGradesCount() {
if (mValue.gradebook != null)
return mValue.gradebook.size();
return 0;
private int setViewType(int type, int section) {
return type * 1024 + section;
}
private int getViewType(int combinedViewType) {
return combinedViewType / 1024;
}
private int getViewSection(int combinedViewType) {
return combinedViewType - getViewType(combinedViewType) * 1024;
}
private Gradebook.GradebookOutput getViewSectionGradebook(int viewSection) {
if (mGrades != null) {
switch (viewSection) {
case SECTION_EXAM: return mGrades.getExams();
case SECTION_ASSIGNMENT: return mGrades.getAssignments();
case SECTION_OTHER: return mGrades.getOthers();
}
}
return null;
}
@@ -133,4 +203,19 @@ class ModDetailGradebookAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
return super.toString() + " '" + mTitle.getText() + " '" + mGrade.getText() + " '" + mGradeMax.getText() + "'";
}
}
private class GradeTitleViewHolder extends StringViewHolder {
private final TextView mTitle;
GradeTitleViewHolder(View view) {
super(view);
mTitle = view.findViewById(R.id.title);
}
@NonNull
@Override
public String toString() {
return super.toString() + " '" + mTitle.getText();
}
}
}

View File

@@ -96,7 +96,7 @@ public class ModDetailGradebookFragment extends Fragment {
}
@Override
public void onAttach(Context context) {
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof MainActivityListener) {
this.mListener = ((MainActivityListener) context);

View File

@@ -100,7 +100,7 @@ public class ModDetailOverviewFragment extends Fragment {
}
@Override
public void onAttach(Context context) {
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof MainActivityListener) {
this.mListener = ((MainActivityListener) context);

View File

@@ -2,6 +2,7 @@ package de.sebse.fuplanner.fragments.moddetails;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
@@ -92,7 +93,18 @@ public class ModDetailResourceFragment extends Fragment implements Download.OnDo
} else if (node.getContent() instanceof Resource.File && ModDetailResourceFragment.this.mListener != null) { // if leaf is file
ModDetailResourceFragment.this.mListener.getKVV(kvv -> {
kvv.modules().resources().recv(mItemPos, (Modules.Module module) -> {
String folderName = "FU-"+module.title.replaceAll("[:*<>|/\"\\\\]", "-");
String folderName;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (module.semester != null) {
folderName = module.semester.toString();
} else {
folderName = "PROJ";
}
folderName += "-" + module.title.replaceAll("[:*<>|/\"\\\\]", "-");
folderName += "/Resources";
} else {
folderName = "FU-"+module.title.replaceAll("[:*<>|/\"\\\\]", "-");
}
Resource.File file = (Resource.File) node.getContent();
getDownload().openDownloadDialog(file, folderName);
}, log::e);
@@ -135,7 +147,7 @@ public class ModDetailResourceFragment extends Fragment implements Download.OnDo
}
@Override
public void onAttach(Context context) {
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof MainActivityListener) {
this.mListener = ((MainActivityListener) context);

View File

@@ -1,19 +1,22 @@
package de.sebse.fuplanner.services.canteen;
import android.content.Context;
import android.os.Build;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.services.canteen.types.Canteen;
import de.sebse.fuplanner.services.canteen.types.CanteenListener;
import de.sebse.fuplanner.services.canteen.types.Canteens;
import de.sebse.fuplanner.services.canteen.types.Day;
import de.sebse.fuplanner.tools.AsyncQueue;
import de.sebse.fuplanner.tools.Preferences;
import de.sebse.fuplanner.tools.network.HTTPService;
import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkError;
@@ -21,9 +24,11 @@ import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
public class CanteenBrowser extends HTTPService {
private Canteens canteens;
private Canteens availableCanteens;
private final AsyncQueue queue = new AsyncQueue();
private final Context context;
private CanteenListener mListener;
private final double[][] canteenRoots = {{52.5508,13.4014}, {52.4438,13.2771}, {52.3926,13.0611}, {52.4781,13.5286}};
public CanteenBrowser(Context context) {
super(context);
@@ -34,9 +39,7 @@ public class CanteenBrowser extends HTTPService {
throw new RuntimeException(context.toString() + " must implement CanteenListener");
try {
this.canteens = Canteens.load(context);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
@@ -46,12 +49,11 @@ public class CanteenBrowser extends HTTPService {
}
public void getCanteens(final NetworkCallback<Canteens> callback, final NetworkErrorCallback errorCallback, boolean forceRefresh) {
if (this.canteens != null && !forceRefresh) {
callback.onResponse(this.canteens);
return;
}
queue.add("list", () -> {
if (this.canteens != null && !forceRefresh) {
callback.onResponse(this.canteens);
queue.next("list");
return;
}
this.upgradeCanteens(success -> {
if (this.canteens == null)
this.canteens = success;
@@ -65,12 +67,22 @@ public class CanteenBrowser extends HTTPService {
}
private void upgradeCanteens(final NetworkCallback<Canteens> callback, final NetworkErrorCallback errorCallback) {
// TSL 1.2 not supported (https://github.com/google/volley/issues/77)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
int[] visibleCanteens = Preferences.getArrayInt(context, R.string.pref_canteen_selection);
if (visibleCanteens == null) {
Preferences.setArrayInt(context, R.string.pref_canteen_selection, Canteens.availableCanteens);
visibleCanteens = Preferences.getArrayInt(context, R.string.pref_canteen_selection);
}
if (visibleCanteens == null || visibleCanteens.length == 0) {
callback.onResponse(new Canteens());
return;
}
get("https://openmensa.org/api/v2/canteens?near[lat]=52.449743&near[lng]=13.282245&near[dist]=7", null, response -> {
StringBuilder ids = new StringBuilder();
ids.append(visibleCanteens[0]);
for (int i = 1; i < visibleCanteens.length; i++) ids.append(",").append(visibleCanteens[i]);
// "https://openmensa.org/api/v2/canteens?near[lat]=52.449743&near[lng]=13.282245&near[dist]=7"
get("https://openmensa.org/api/v2/canteens?ids=" + ids.toString(), null, response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(201101, 403, "No canteen list retrieved!"));
@@ -78,28 +90,7 @@ public class CanteenBrowser extends HTTPService {
}
Canteens canteens = new Canteens();
try {
JSONArray json = new JSONArray(body);
for (int i = 0; i < json.length(); i++) {
JSONObject canteen = json.getJSONObject(i);
int id = canteen.getInt("id");
String name = canteen.getString("name");
String city = canteen.getString("city");
String address = canteen.getString("address");
JSONArray coords = canteen.getJSONArray("coordinates");
double lat = 0;
double lng = 0;
if (coords != null) {
lat = coords.getDouble(0);
lng = coords.getDouble(1);
}
for (int cant : Canteens.availableCanteens) {
if (cant == id) {
canteens.addCanteen(id, name, city, address, lat, lng);
break;
}
}
}
parseCanteens(body, canteens);
} catch (JSONException e) {
e.printStackTrace();
errorCallback.onError(new NetworkError(201102, 403, "Cannot parse canteen list!"));
@@ -109,18 +100,95 @@ public class CanteenBrowser extends HTTPService {
}, error -> errorCallback.onError(new NetworkError(201103, error.networkResponse.statusCode, "Cannot get canteen list!")));
}
public void getAvailableCanteens(final NetworkCallback<Canteens> callback, final NetworkErrorCallback errorCallback) {
getAvailableCanteens(callback, errorCallback, false);
}
public void getAvailableCanteens(final NetworkCallback<Canteens> callback, final NetworkErrorCallback errorCallback, boolean forceRefresh) {
if (this.availableCanteens != null && !forceRefresh) {
callback.onResponse(this.availableCanteens);
return;
}
queue.add("available", () -> {
this.upgradeAvailableCanteens(success -> {
if (this.availableCanteens == null)
this.availableCanteens = success;
else
this.availableCanteens.update(success);
callback.onResponse(success);
queue.next("available");
}, queue.check("available", errorCallback));
});
}
private void upgradeAvailableCanteens(final NetworkCallback<Canteens> callback, final NetworkErrorCallback errorCallback) {
AtomicInteger finishedCount = new AtomicInteger();
Canteens canteens = new Canteens();
// "https://openmensa.org/api/v2/canteens?near[lat]=52.449743&near[lng]=13.282245&near[dist]=50"
for (double[] root : canteenRoots) {
get(String.format("https://openmensa.org/api/v2/canteens?near[lat]=%s&near[lng]=%s&near[dist]=50", root[0], root[1]), null, response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(201401, 403, "No canteen list retrieved!"));
return;
}
try {
parseCanteens(body, canteens);
} catch (JSONException e) {
e.printStackTrace();
errorCallback.onError(new NetworkError(201402, 403, "Cannot parse canteen list!"));
return;
}
finishedCount.getAndIncrement();
if (finishedCount.get() == this.canteenRoots.length) {
callback.onResponse(canteens);
}
}, error -> errorCallback.onError(new NetworkError(201403, error.networkResponse.statusCode, "Cannot get canteen list!")));
}
}
private void parseCanteens(@NotNull String body, @NotNull Canteens canteens) throws JSONException {
JSONArray json = new JSONArray(body);
for (int i = 0; i < json.length(); i++) {
JSONObject canteen = json.getJSONObject(i);
int id = canteen.getInt("id");
String name = canteen.getString("name");
String city = canteen.getString("city");
String address = canteen.getString("address");
double lat = 0;
double lng = 0;
if (canteen.has("coordinates")) {
JSONArray coords = canteen.getJSONArray("coordinates");
lat = coords.getDouble(0);
lng = coords.getDouble(1);
}
canteens.addCanteen(id, name, city, address, lat, lng);
}
}
public void getCanteen(Canteen canteen, final NetworkCallback<Canteen> callback, final NetworkErrorCallback errorCallback) {
getCanteen(canteen, callback, errorCallback, false);
}
public void getCanteen(Canteen canteen, final NetworkCallback<Canteen> callback, final NetworkErrorCallback errorCallback, boolean forceRefresh) {
String hash = "canteen" + canteen.getId();
if (canteen.size() > 0 && !forceRefresh) {
callback.onResponse(canteen);
return;
}
queue.add(hash, () -> {
if (canteen.size() > 0 && !forceRefresh) {
callback.onResponse(canteen);
queue.next(hash);
return;
}
this.upgradeCanteen(canteen, success -> {
canteen.update(success);
this.save();
@@ -131,11 +199,6 @@ public class CanteenBrowser extends HTTPService {
}
private void upgradeCanteen(Canteen canteen, final NetworkCallback<Canteen> callback, final NetworkErrorCallback errorCallback) {
// TSL 1.2 not supported (https://github.com/google/volley/issues/77)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
callback.onResponse(canteen);
return;
}
get(String.format("https://openmensa.org/api/v2/canteens/%s/days", canteen.getId()), null, response -> {
String body = response.getParsed();
if (body == null) {
@@ -167,12 +230,11 @@ public class CanteenBrowser extends HTTPService {
public void getDay(Day day, final NetworkCallback<Day> callback, final NetworkErrorCallback errorCallback, boolean forceRefresh) {
String hash = "day" + day.getCanteenId() + "@@@" + Canteen.calendarToKey(day.getCalendar());
if (day.size() > 0 && !forceRefresh) {
callback.onResponse(day);
return;
}
queue.add(hash, () -> {
if (day.size() > 0 && !forceRefresh) {
callback.onResponse(day);
queue.next(hash);
return;
}
this.upgradeDay(day, success -> {
day.update(success);
this.save();
@@ -183,11 +245,6 @@ public class CanteenBrowser extends HTTPService {
}
private void upgradeDay(Day day, final NetworkCallback<Day> callback, final NetworkErrorCallback errorCallback) {
// TSL 1.2 not supported (https://github.com/google/volley/issues/77)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
callback.onResponse(day);
return;
}
get(String.format("https://openmensa.org/api/v2/canteens/%s/days/%s/meals/", day.getCanteenId(), Canteen.calendarToKey(day.getCalendar())), null, response -> {
String body = response.getParsed();
if (body == null) {

View File

@@ -126,4 +126,12 @@ public class Canteen implements Serializable, Iterable<Day> {
public String toString() {
return id+": "+name+"\n"+list.toString()+"\n";
}
public boolean contains(String searchString) {
return containsIgnoreCase(getName(), searchString) || containsIgnoreCase(getAddress(), searchString) || containsIgnoreCase(getCity(), searchString);
}
private static boolean containsIgnoreCase(String str, String subString) {
return str.toLowerCase().contains(subString.toLowerCase());
}
}

View File

@@ -4,6 +4,7 @@ import android.content.Context;
import androidx.annotation.NonNull;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
@@ -25,7 +26,7 @@ public class Canteens implements Serializable, Iterable<Canteen> {
addCanteen(canteen);
}
private void addCanteen(Canteen canteen) {
public void addCanteen(Canteen canteen) {
if (this.list.contains(canteen)) return;
this.list.add(canteen);
}
@@ -74,7 +75,12 @@ public class Canteens implements Serializable, Iterable<Canteen> {
}
public static Canteens load(Context context) throws IOException, ClassNotFoundException {
FileInputStream fis = context.openFileInput(FILE_NAME);
FileInputStream fis;
try {
fis = context.openFileInput(FILE_NAME);
} catch (FileNotFoundException e) {
return null;
}
ObjectInputStream is = new ObjectInputStream(fis);
Canteens modules = (Canteens) is.readObject();
is.close();

View File

@@ -73,9 +73,7 @@ public class FUAuthenticator extends AbstractAccountAuthenticator {
throw new NetworkErrorException(authToken);
else authToken = null;
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}

View File

@@ -171,7 +171,7 @@ public class FUAuthenticatorActivity extends AccountAuthenticatorActivity {
final Account account = new Account(accountName, intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE));
final AccountManager mAccountManager = AccountManager.get(this);
if (getIntent().getBooleanExtra(ARG_IS_ADDING_NEW_ACCOUNT, false)) {
if (mIsAddingNewAccount) {
String authtoken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN);
String authtokenType = mAuthTokenType;

View File

@@ -0,0 +1,4 @@
package de.sebse.fuplanner.services.fulogin;
public class UserLoginResult {
}

View File

@@ -5,7 +5,6 @@ import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import org.jetbrains.annotations.NotNull;
@@ -67,7 +66,7 @@ public class UserLoginTask extends AsyncTask<Void, Void, String> {
AtomicReference<String> login = new AtomicReference<>();
NetworkErrorCallback errorFunc = error -> {
log.e(error);
login.set("Error: "+String.valueOf(error.getCode()));
login.set("Error: "+ error.getCode());
latch.countDown();
};
switch (mTokenType) {
@@ -123,7 +122,7 @@ public class UserLoginTask extends AsyncTask<Void, Void, String> {
protected void onPostExecute(final String success) {
if (mActivity == null || mActivity.isFinishing())
return;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mActivity.isDestroyed())
if (mActivity.isDestroyed())
return;
mActivity.mAuthTask = null;
mActivity.showProgress(false);
@@ -149,7 +148,7 @@ public class UserLoginTask extends AsyncTask<Void, Void, String> {
protected void onCancelled() {
if (mActivity == null || mActivity.isFinishing())
return;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mActivity.isDestroyed())
if (mActivity.isDestroyed())
return;
mActivity.mAuthTask = null;
mActivity.showProgress(false);

View File

@@ -1,5 +1,6 @@
package de.sebse.fuplanner.services.kvv;
public class Constants {
public static final String KVV_SERVER_URL = "https://mycampus.imp.fu-berlin.de/";
public static final String WB_SERVER_URL = "https://mycampus.imp.fu-berlin.de/";
public static final String BB_SERVER_URL = "https://lms.fu-berlin.de/";
}

View File

@@ -13,7 +13,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import de.sebse.fuplanner.services.kvv.types.LoginTokenBB;
import de.sebse.fuplanner.services.kvv.types.LoginTokenKVV;
import de.sebse.fuplanner.services.kvv.types.LoginTokenWB;
import de.sebse.fuplanner.tools.CustomAccountManager;
public class KVV extends Service {
@@ -36,7 +36,7 @@ public class KVV extends Service {
}
@Override
public void onLogin(LoginTokenKVV tokenKVV, LoginTokenBB tokenBB, boolean isOnlyRefresh) {
public void onLogin(LoginTokenWB tokenKVV, LoginTokenBB tokenBB, boolean isOnlyRefresh) {
for (KVVListener listener : mListeners.values())
listener.onLogin(tokenKVV, tokenBB, isOnlyRefresh);
}

View File

@@ -3,12 +3,12 @@ package de.sebse.fuplanner.services.kvv;
import com.android.volley.NetworkResponse;
import de.sebse.fuplanner.services.kvv.types.LoginTokenBB;
import de.sebse.fuplanner.services.kvv.types.LoginTokenKVV;
import de.sebse.fuplanner.services.kvv.types.LoginTokenWB;
import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.tools.CustomAccountManager;
public interface KVVListener {
default void onLogin(LoginTokenKVV tokenKVV, LoginTokenBB tokenBB, boolean isOnlyRefresh) {}
default void onLogin(LoginTokenWB tokenKVV, LoginTokenBB tokenBB, boolean isOnlyRefresh) {}
default void onLogout() {}

View File

@@ -10,18 +10,17 @@ import de.sebse.fuplanner.R;
import de.sebse.fuplanner.services.fulogin.AccountGeneral;
import de.sebse.fuplanner.services.kvv.sync.BBLogin;
import de.sebse.fuplanner.services.kvv.sync.FULogin;
import de.sebse.fuplanner.services.kvv.sync.KVVLogin;
import de.sebse.fuplanner.services.kvv.sync.WBLogin;
import de.sebse.fuplanner.services.kvv.types.LoginTokenBB;
import de.sebse.fuplanner.services.kvv.types.LoginTokenKVV;
import de.sebse.fuplanner.services.kvv.types.LoginTokenWB;
import de.sebse.fuplanner.tools.CustomAccountManager;
import de.sebse.fuplanner.tools.NetworkCallbackCollector;
import de.sebse.fuplanner.tools.Preferences;
import de.sebse.fuplanner.tools.network.HTTPService;
import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkError;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
public class Login extends HTTPService {
public class Login {
public static final int RESTORE_STATUS_SUCCESS = 1;
public static final int RESTORE_STATUS_ERROR = 2;
public static final int RESTORE_STATUS_INVALID_PASSWORD = 3;
@@ -31,15 +30,21 @@ public class Login extends HTTPService {
public static final int RELOGIN = 0;
private final KVVListener mListener;
@Nullable private LoginTokenKVV mTokenKVV;
private Context context;
@Nullable private LoginTokenWB mTokenKVV;
@Nullable private LoginTokenBB mTokenBB;
private boolean mLoginPending = false;
private final NetworkCallbackCollector<Pair<LoginTokenKVV, LoginTokenBB>> mRefreshCallbacks = new NetworkCallbackCollector<>();
private final NetworkCallbackCollector<Pair<LoginTokenWB, LoginTokenBB>> mRefreshCallbacks = new NetworkCallbackCollector<>();
private final NetworkCallbackCollector<Integer> mRestoreCallbacks = new NetworkCallbackCollector<>();
Login(KVVListener listener, Context context) {
super(context);
super();
this.mListener = listener;
this.context = context;
}
private Context getContext() {
return this.context;
}
public void restoreOnlineLogin(IntegerInterface callback) {
@@ -48,7 +53,7 @@ public class Login extends HTTPService {
return;
}
mLoginPending = true;
LoginTokenKVV.load(mListener.getAccountManager(), tokenKVV -> {
LoginTokenWB.load(mListener.getAccountManager(), tokenKVV -> {
LoginTokenBB.load(mListener.getAccountManager(), tokenBB -> {
boolean result = setToken(tokenKVV, tokenBB);
mLoginPending = false;
@@ -64,7 +69,7 @@ public class Login extends HTTPService {
}
public void isOfflineStoredAvailable(BooleanInterface callback) {
LoginTokenKVV.load(mListener.getAccountManager(), tokenKVV -> {
LoginTokenWB.load(mListener.getAccountManager(), tokenKVV -> {
LoginTokenBB.load(mListener.getAccountManager(), tokenBB -> {
callback.run(tokenKVV != null && tokenBB != null);
}, e -> callback.run(false));
@@ -98,7 +103,7 @@ public class Login extends HTTPService {
return isLoggedIn();
}
void testLoginToken(@NotNull NetworkCallback<Pair<LoginTokenKVV, LoginTokenBB>> callback, @NotNull NetworkErrorCallback errorCallback) {
void testLoginToken(@NotNull NetworkCallback<Pair<LoginTokenWB, LoginTokenBB>> callback, @NotNull NetworkErrorCallback errorCallback) {
if (mTokenKVV == null) {
errorCallback.onError(new NetworkError(100173, -1, "Not logged in!"));
return;
@@ -110,16 +115,16 @@ public class Login extends HTTPService {
testLoginToken(mTokenKVV, mTokenBB, callback, errorCallback);
}
private void testLoginToken(@NotNull LoginTokenKVV tokenKVV, @NotNull LoginTokenBB tokenBB, @NotNull NetworkCallback<Pair<LoginTokenKVV, LoginTokenBB>> callback, @NotNull NetworkErrorCallback errorCallback) {
private void testLoginToken(@NotNull LoginTokenWB tokenKVV, @NotNull LoginTokenBB tokenBB, @NotNull NetworkCallback<Pair<LoginTokenWB, LoginTokenBB>> callback, @NotNull NetworkErrorCallback errorCallback) {
FULogin mFULogin = new FULogin(getContext());
new KVVLogin(getContext(), mFULogin).testLoginToken(tokenKVV, tokenKVV1 -> {
new WBLogin(getContext(), mFULogin).testLoginToken(tokenKVV, tokenKVV1 -> {
new BBLogin(getContext(), mFULogin).testLoginToken(tokenBB, tokenBB1 -> {
callback.onResponse(new Pair<>(tokenKVV1, tokenBB1));
}, errorCallback);
}, errorCallback);
}
@Nullable public LoginTokenKVV getLoginTokenKVV() {
@Nullable public LoginTokenWB getLoginTokenKVV() {
return mTokenKVV;
}
@@ -127,7 +132,7 @@ public class Login extends HTTPService {
return mTokenBB;
}
void refreshLogin(NetworkCallback<Pair<LoginTokenKVV, LoginTokenBB>> success, NetworkErrorCallback error, int flags) {
void refreshLogin(NetworkCallback<Pair<LoginTokenWB, LoginTokenBB>> success, NetworkErrorCallback error, int flags) {
boolean isFirst = mRefreshCallbacks.isEmpty();
mRefreshCallbacks.add(success, error);
if (!isFirst)
@@ -135,10 +140,10 @@ public class Login extends HTTPService {
refreshLoginRunner(success, error, flags);
}
private void refreshLoginRunner(NetworkCallback<Pair<LoginTokenKVV, LoginTokenBB>> success, NetworkErrorCallback error, int flags) {
private void refreshLoginRunner(NetworkCallback<Pair<LoginTokenWB, LoginTokenBB>> success, NetworkErrorCallback error, int flags) {
CustomAccountManager manager = mListener.getAccountManager();
if ((flags & LOGOUT_KVV) == LOGOUT_KVV) {
manager.doInvalidateToken(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV, ignored -> {
manager.doInvalidateToken(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_WB, ignored -> {
refreshLoginRunner(success, error, flags & ~LOGOUT_KVV);
});
} else if ((flags & LOGOUT_BB) == LOGOUT_BB) {
@@ -173,7 +178,7 @@ public class Login extends HTTPService {
}
}
private boolean setToken(@Nullable LoginTokenKVV tokenKVV, @Nullable LoginTokenBB tokenBB) {
private boolean setToken(@Nullable LoginTokenWB tokenKVV, @Nullable LoginTokenBB tokenBB) {
if (tokenKVV == null || tokenBB == null)
return false;
boolean isOnlyRefresh = mTokenKVV != null;

View File

@@ -39,7 +39,7 @@ public class ModulesAnnouncements extends PartModules<ArrayList<Announcement>> {
errorCallback.onError(new NetworkError(101204, 500, "Currently running in offline mode!"));
return;
}
super.get(String.format(Constants.KVV_SERVER_URL+"direct/announcement/site/%s.json?n=999999&d=999999999&_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
super.get(String.format(Constants.WB_SERVER_URL +"direct/announcement/site/%s.json?n=999999&d=999999999&_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(101201, 403, "No announcements retrieved!"));

View File

@@ -39,7 +39,7 @@ public class ModulesAssignments extends PartModules<AssignmentList> {
errorCallback.onError(new NetworkError(101304, 500, "Currently running in offline mode!"));
return;
}
get(String.format(Constants.KVV_SERVER_URL+"direct/assignment/site/%s.json?_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
get(String.format(Constants.WB_SERVER_URL +"direct/assignment/site/%s.json?_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(101301, 403, "No assignments retrieved!"));

View File

@@ -1,7 +1,6 @@
package de.sebse.fuplanner.services.kvv;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import org.json.JSONArray;
@@ -47,7 +46,7 @@ public class ModulesEvents extends PartModules<EventList> {
errorCallback.onError(new NetworkError(101404, 500, "Currently running in offline mode!"));
return;
}
get(String.format(Constants.KVV_SERVER_URL+"direct/calendar/site/%s.json?detailed=true&_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
get(String.format(Constants.WB_SERVER_URL +"direct/calendar/site/%s.json?detailed=true&_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(101401, 403, "No events retrieved!"));
@@ -89,11 +88,6 @@ public class ModulesEvents extends PartModules<EventList> {
@Override
protected void upgradeBB(String ID, NetworkCallback<EventList> callback, NetworkErrorCallback errorCallback) {
// TSL 1.2 not supported (https://github.com/google/volley/issues/77)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
callback.onResponse(new EventList());
return;
}
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenBB() == null || !mLogin.getLoginTokenBB().isAvailable()) {
errorCallback.onError(new NetworkError(101414, 500, "Currently running in offline mode!"));
return;
@@ -129,7 +123,6 @@ public class ModulesEvents extends PartModules<EventList> {
//String[] tests = {"462854", "465661", "462126", "463782", "437050", "433843", "471614", "464205"};
//String[] tests = {"461459", "424564", "459494", "429737", "463765", "476477", "464082", "459577", "459743", "464318", "449358", "454327", "461784", "468081", "485919"};
//vvNumber = tests[new Random().nextInt(tests.length)];
//log.d("LAAAAAAST", vvNumber);
//vvNumber = "462126";
super.get(String.format("https://www.fu-berlin.de/vv/de/lv/%s", vvNumber), null, response1 -> {
String body = response1.getParsed();

View File

@@ -2,17 +2,9 @@ package de.sebse.fuplanner.services.kvv;
import android.content.Context;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import de.sebse.fuplanner.services.kvv.types.CacheBBEventNumber;
import de.sebse.fuplanner.services.kvv.types.CacheLecturer;
import de.sebse.fuplanner.services.kvv.types.Lecturer;
import de.sebse.fuplanner.tools.Regex;
import de.sebse.fuplanner.tools.network.HTTPService;
import de.sebse.fuplanner.tools.network.NetworkCallback;
@@ -27,9 +19,7 @@ class ModulesEventsNumber extends HTTPService {
CacheBBEventNumber storage = null;
try {
storage = CacheBBEventNumber.load(context);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
if (storage == null) {

View File

@@ -6,45 +6,44 @@ import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import de.sebse.fuplanner.services.kvv.types.Grade;
import de.sebse.fuplanner.services.kvv.types.Gradebook;
import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkError;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
public class ModulesGradebook extends PartModules<ArrayList<Grade>> {
public class ModulesGradebook extends PartModules<Gradebook> {
ModulesGradebook(Login login, ModulesList list, Context context) {
super(login, list, context);
}
@Override
protected ArrayList<Grade> getPart(Modules.Module module) {
protected Gradebook getPart(Modules.Module module) {
return module.gradebook;
}
@Override
protected boolean setPart(Modules.Module module, ArrayList<Grade> part) {
protected boolean setPart(Modules.Module module, Gradebook part) {
boolean changed = module.gradebook == null || module.gradebook.hashCode() != part.hashCode();
module.gradebook = part;
return changed;
}
@Override
protected void upgradeKVV(final String ID, final NetworkCallback<ArrayList<Grade>> callback, final NetworkErrorCallback errorCallback) {
protected void upgradeKVV(final String ID, final NetworkCallback<Gradebook> callback, final NetworkErrorCallback errorCallback) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenKVV() == null || !mLogin.getLoginTokenKVV().isAvailable()) {
errorCallback.onError(new NetworkError(101504, 500, "Currently running in offline mode!"));
return;
}
super.get(String.format(Constants.KVV_SERVER_URL+"direct/gradebook/site/%s.json", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
super.get(String.format(Constants.WB_SERVER_URL +"direct/gradebook/site/%s.json", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(101501, 403, "No gradebook retrieved!"));
return;
}
ArrayList<Grade> gradebook = new ArrayList<>();
Gradebook gradebook = new Gradebook();
JSONArray sites;
try {
JSONObject json = new JSONObject(body);
@@ -62,7 +61,7 @@ public class ModulesGradebook extends PartModules<ArrayList<Grade>> {
String itemName = site.optString("itemName", null);
double maxPoints = site.optDouble("points", -1);
gradebook.add(0, new Grade(itemName, grade, maxPoints));
gradebook.addGrade(new Grade(itemName, grade, maxPoints));
} catch (JSONException e) {
log.e(new NetworkError(101505, 403, "Cannot parse gradebook!"));
log.e("ID:", i, "JSON:", sites);
@@ -73,14 +72,14 @@ public class ModulesGradebook extends PartModules<ArrayList<Grade>> {
callback.onResponse(gradebook);
}, error -> {
if (error.networkResponse.statusCode == 400)
callback.onResponse(new ArrayList<>());
callback.onResponse(new Gradebook());
else
errorCallback.onError(new NetworkError(101503, error.networkResponse.statusCode, "Cannot get gradebook!"));
});
}
@Override
protected void upgradeBB(String ID, NetworkCallback<ArrayList<Grade>> callback, NetworkErrorCallback errorCallback) {
protected void upgradeBB(String ID, NetworkCallback<Gradebook> callback, NetworkErrorCallback errorCallback) {
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenBB() == null || !mLogin.getLoginTokenBB().isAvailable()) {
errorCallback.onError(new NetworkError(101510, 500, "Currently running in offline mode!"));
return;
@@ -117,7 +116,7 @@ public class ModulesGradebook extends PartModules<ArrayList<Grade>> {
return;
}
ArrayList<Grade> result = new ArrayList<>();
Gradebook result = new Gradebook();
for (int i = 0; i < grades.length(); i++) {
for (int j = 0; j < gradeColumns.length(); j++) {
try {
@@ -133,7 +132,7 @@ public class ModulesGradebook extends PartModules<ArrayList<Grade>> {
JSONObject score = column.optJSONObject("score");
double maxPoints = score != null ? score.optDouble("possible", 0) : 0;
result.add(new Grade(name, points, maxPoints));
result.addGrade(new Grade(name, points, maxPoints));
} catch (JSONException e) {
log.e(new NetworkError(101515, 400, "Cannot parse grades!"));
log.e("ID:", i, "JSON-grades:", grades);
@@ -147,7 +146,7 @@ public class ModulesGradebook extends PartModules<ArrayList<Grade>> {
}, error -> errorCallback.onError(new NetworkError(101516, error.networkResponse.statusCode, "Cannot get gradebook columns!")));
}, error -> {
if (error.networkResponse.statusCode == 403)
callback.onResponse(new ArrayList<>());
callback.onResponse(new Gradebook());
else
errorCallback.onError(new NetworkError(101517, error.networkResponse.statusCode, "Cannot get gradebook entries!"));
});

View File

@@ -27,7 +27,7 @@ import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkError;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
import static de.sebse.fuplanner.services.kvv.PartModules.RETRY_COUNT;
import static de.sebse.fuplanner.services.kvv.Part.RETRY_COUNT;
public class ModulesList extends HTTPService {
private final Login mLogin;
@@ -102,13 +102,12 @@ public class ModulesList extends HTTPService {
try {
this.mModules = Modules.load(getContext());
} catch (FileNotFoundException ignored) {
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
delete();
}
if (this.mModules == null) {
recv(success -> {}, log::e);
recv(success -> {}, log::e, true);
}
}
@@ -133,6 +132,10 @@ public class ModulesList extends HTTPService {
mLogin.getLoginTokenBB() != null && mLogin.getLoginTokenBB().isOtherUser(mModules.getUsername())
)
delete();
if (this.mModules != null && !forceRefresh) {
callback.onResponse(this.mModules);
return;
}
mQueue.add(() -> {
if (mLogin.isLoginPending()) {
mLogin.restoreOnlineLogin(resCode -> {
@@ -143,11 +146,6 @@ public class ModulesList extends HTTPService {
}
});
mQueue.add(() -> {
if (this.mModules != null && !forceRefresh) {
callback.onResponse(this.mModules);
mQueue.next();
return;
}
Function<Integer, NetworkErrorCallback> errorFunc = ((Integer errorCode) -> (error -> {
if (retries > 0 && (error.getHttpStatus() == 401 || error.getHttpStatus() == 403)) {
mLogin.refreshLogin(success -> {
@@ -196,7 +194,7 @@ public class ModulesList extends HTTPService {
callback.onResponse(modules);
return;
}
get(Constants.KVV_SERVER_URL+"direct/membership.json?_validateSession=", mLogin.getLoginTokenKVV().getCookies(), response -> {
get(Constants.WB_SERVER_URL +"direct/membership.json?_validateSession=", mLogin.getLoginTokenKVV().getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(101111, 403, "No membership list retrieved!"));
@@ -228,7 +226,7 @@ public class ModulesList extends HTTPService {
if (--latch[0] == 0) successCallback.onResponse(modules);
continue;
}
get(String.format(Constants.KVV_SERVER_URL+"direct/site/%s.json?_validateSession=", courseId), mLogin.getLoginTokenKVV().getCookies(), response1 -> {
get(String.format(Constants.WB_SERVER_URL +"direct/site/%s.json?_validateSession=", courseId), mLogin.getLoginTokenKVV().getCookies(), response1 -> {
String body1 = response1.getParsed();
if (body1 == null) {
errorCallback.onError(new NetworkError(101113, 403, "No site retrieved!"));
@@ -429,9 +427,7 @@ public class ModulesList extends HTTPService {
if (mBBCache == null) {
try {
mBBCache = CacheBBCourse.load(getContext());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
@@ -444,9 +440,7 @@ public class ModulesList extends HTTPService {
if (mKVVCache == null) {
try {
mKVVCache = CacheKVVCourse.load(getContext());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}

View File

@@ -27,9 +27,7 @@ class ModulesListLecturer extends HTTPService {
CacheLecturer storage = null;
try {
storage = CacheLecturer.load(context);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
if (storage == null) {

View File

@@ -47,7 +47,7 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
errorCallback.onError(new NetworkError(101604, 500, "Currently running in offline mode!"));
return;
}
get(String.format(Constants.KVV_SERVER_URL+"direct/content/site/%s.json?_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
get(String.format(Constants.WB_SERVER_URL +"direct/content/site/%s.json?_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(101601, 403, "No resources retrieved!"));
@@ -101,9 +101,7 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
for (Resource res2: resources) {
try {
String utf8Name;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
utf8Name = StandardCharsets.UTF_8.name();
else utf8Name = "UTF-8";
utf8Name = StandardCharsets.UTF_8.name();
if (URLDecoder.decode(res2.getUrl(), utf8Name).endsWith(res.getContainer()) && res2 instanceof Resource.Folder) {
// Append File/Folder to list
((Resource.Folder) res2).add(res);
@@ -370,8 +368,15 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
}
private String saveFileInDownloads(String filename, byte[] data, String moduleName) {
// Saves file in folder: DOWNLOADS/moduleName
File folder = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), moduleName);
File folder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
folder = new File(getContext().getExternalFilesDir(
Environment.DIRECTORY_DOWNLOADS), moduleName);
} else {
folder = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), moduleName);
}
if (!folder.mkdirs()) {
log.w( "Directory not created");
}

View File

@@ -19,6 +19,10 @@ abstract class PartModules<T> extends Part<Modules.Module> {
@Override
protected void recv(final Modules.Module module, final NetworkCallback<Modules.Module> callback, final NetworkErrorCallback errorCallback, final boolean forceRefresh, final int retries) {
if (getPart(module) != null && !forceRefresh) {
callback.onResponse(module);
return;
}
mQueue.add(() -> {
if (mLogin.isLoginPending()) {
mLogin.restoreOnlineLogin(resCode -> {
@@ -29,11 +33,6 @@ abstract class PartModules<T> extends Part<Modules.Module> {
}
});
mQueue.add(() -> {
if (getPart(module) != null && !forceRefresh) {
callback.onResponse(module);
mQueue.next();
return;
}
upgrade(module.getModuleType(), module.getID(), success -> {
if (setPart(module, success)) {
this.mList.store();

View File

@@ -1,6 +1,7 @@
package de.sebse.fuplanner.services.kvv.sync;
import android.content.Context;
import android.os.Bundle;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
@@ -16,147 +17,133 @@ import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkError;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
public class BBLogin extends HTTPService {
private final FULogin mFULogin;
private long lastHash;
private long lastSync;
private static final long MAX_CACHE_TIME = 1000 * 60; // 1 minute
import static de.sebse.fuplanner.services.kvv.Constants.BB_SERVER_URL;
public class BBLogin extends LoginRoutine<LoginTokenBB> {
private FULogin fuLogin;
public BBLogin(Context context, FULogin fuLogin) {
super(context);
this.mFULogin = fuLogin;
this.fuLogin = fuLogin;
}
public void testLoginToken(@NotNull LoginTokenBB token, @NotNull NetworkCallback<LoginTokenBB> callback, @NotNull NetworkErrorCallback errorCallback) {
if (token.hashCode() == lastHash && lastSync + MAX_CACHE_TIME > System.currentTimeMillis() && token.getStudentId() != null) {
callback.onResponse(token);
return;
}
get(String.format("https://lms.fu-berlin.de/learn/api/public/v1/users/?userName=%s", token.getUsername()), token.getCookies(), response -> {
@Override
public void doesAccountExists(@NotNull String username, @NotNull NetworkCallback<Boolean> callback, @NotNull NetworkErrorCallback error) {
callback.onResponse(true);
}
@Override
protected LoginTokenBB createUnavailableToken() {
return new LoginTokenBB();
}
@Override
protected void checkToken(@NotNull LoginTokenBB token, @NotNull NetworkCallback<Bundle> bundleCallback, @NotNull NetworkErrorCallback error) {
get(String.format(BB_SERVER_URL + "learn/api/public/v1/users/?userName=%s", token.getUsername()), token.getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(100272, 403, "Testing login failed!"));
error.onError(new NetworkError(100272, 403, "Testing BB login failed!"));
return;
}
try {
JSONObject json = new JSONObject(body);
json = json.getJSONArray("results").getJSONObject(0);
String id = json.getString("id");
String studentId = json.getString("studentId");
token.setAdditionals(id, studentId);
lastSync = System.currentTimeMillis();
lastHash = token.hashCode();
callback.onResponse(token);
Bundle bundle = new Bundle();
bundle.putString("id", json.getString("id"));
bundle.putString("studentId", json.getString("studentId"));
bundleCallback.onResponse(bundle);
} catch (JSONException e) {
errorCallback.onError(new NetworkError(100271, 403, "Cannot parse profile!"));
error.onError(new NetworkError(100271, 403, "Cannot parse BB profile!"));
}
}, error -> errorCallback.onError(new NetworkError(100270, error.networkResponse.statusCode, "Testing login failed!")));
}, err -> error.onError(new NetworkError(100270, err.networkResponse.statusCode, "Testing BB login failed!")));
}
public void doLogin(String username, String password, NetworkCallback<LoginTokenBB> callback, NetworkErrorCallback error) {
step1(success1 -> {
String samlLocation = success1.get("Location");
mFULogin.fulogin(samlLocation, username, password, samlResponse -> {
step5(samlResponse, success5 -> {
String shibsessionKey = success5.get("shibsessionKey");
String shibsessionName = success5.get("shibsessionName");
step6(shibsessionKey, shibsessionName, success6 -> {
String s_session_id = success6.get("s_session_id");
String session_id = success6.get("session_id");
LoginTokenBB token = new LoginTokenBB(username, s_session_id, session_id);
callback.onResponse(token);
@Override
public void createLoginToken(@NotNull String username, @NotNull String password, @NotNull NetworkCallback<LoginTokenBB> callback, @NotNull NetworkErrorCallback error) {
getSAMLLocation(samlLocation -> {
fuLogin.fulogin(samlLocation, username, password, samlResponse -> {
startShibSession(samlResponse, shibSessionKey -> {
String shibsessionKey = shibSessionKey.getString("shibsessionKey");
String shibsessionName = shibSessionKey.getString("shibsessionName");
startSession(shibsessionKey, shibsessionName, sessionCookies -> {
Bundle bundle = new Bundle();
bundle.putString("username", username);
bundle.putAll(sessionCookies);
LoginTokenBB tokenBB = new LoginTokenBB(bundle);
testToken(tokenBB, callback, error);
}, error);
}, error);
}, error);
}, error);
}
/*
1= GET https://lms.fu-berlin.de/lms-apps/login/sso/index.php
-> Location-Header: https://identity.fu-berlin.de/idp-fub/profile/SAML2/Redirect/SSO?SAMLResponse=[SAMLResponse]&RelayState=[RelayState]
*/
private void step1(final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
get("https://lms.fu-berlin.de/lms-apps/login/sso/index.php", null, response -> {
private void getSAMLLocation(final NetworkCallback<String> callback, final NetworkErrorCallback errorCallback) {
get(BB_SERVER_URL + "lms-apps/login/sso/index.php", null, response -> {
String location = response.getHeaders().get("Location");
if (location==null) {
errorCallback.onError(new NetworkError(100211, -1, "Error on getting SAML request!"));
if (location == null) {
errorCallback.onError(new NetworkError(100211, -1, "Error on getting BB SAML request!"));
return;
}
HashMap<String, String> object = new HashMap<>();
object.put("Location", location);
callback.onResponse(object);
}, error -> errorCallback.onError(new NetworkError(100210, error.networkResponse.statusCode, "Error on getting SAML request!")));
callback.onResponse(location);
}, error -> errorCallback.onError(new NetworkError(100210, error.networkResponse.statusCode, "Error on getting BB SAML request!")));
}
/*
5= POST https://lms.fu-berlin.de/Shibboleth.sso/SAML2/POST
+ Body: SAMLResponse=[SAML-RESPONSE]
+ Header: Content-Type: application/x-www-form-urlencoded
-> Set-Cookie: _shibsession_[SESS-NR]: [SESS-VALUE]
*/
private void step5(String SAMLResponse, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
private void startShibSession(String samlResponse, final NetworkCallback<Bundle> callback, final NetworkErrorCallback errorCallback) {
HashMap<String, String> body = new HashMap<>();
body.put("SAMLResponse", SAMLResponse);
post("https://lms.fu-berlin.de/Shibboleth.sso/SAML2/POST", null, body, response -> {
body.put("SAMLResponse", samlResponse);
post(BB_SERVER_URL + "Shibboleth.sso/SAML2/POST", null, body, response -> {
String cookies = response.getHeaders().get("Set-Cookie");
if (cookies ==null) {
errorCallback.onError(new NetworkError(100251, -1, "Error on starting KVV session!"));
errorCallback.onError(new NetworkError(100251, -1, "Error on starting BB session!"));
return;
}
HashMap<String, String> object = new HashMap<>();
Pattern pattern = Pattern.compile("(_shibsession_[0-9a-f]+)=([^;]+);");
Matcher matcher = pattern.matcher(cookies);
if (!matcher.find()) {
errorCallback.onError(new NetworkError(100252, -1, "Error on starting KVV session!"));
errorCallback.onError(new NetworkError(100252, -1, "Error on starting BB session!"));
}
object.put("shibsessionKey", matcher.group(1));
object.put("shibsessionName", matcher.group(2));
callback.onResponse(object);
}, error -> errorCallback.onError(new NetworkError(100250, error.networkResponse.statusCode, "Error on starting KVV session!")));
Bundle bundle = new Bundle();
bundle.putString("shibsessionKey", matcher.group(1));
bundle.putString("shibsessionName", matcher.group(2));
callback.onResponse(bundle);
}, error -> errorCallback.onError(new NetworkError(100250, error.networkResponse.statusCode, "Error on starting BB session!")));
}
/*
6= https://lms.fu-berlin.de/webapps/bb-auth-provider-shibboleth-bb_bb60/execute/shibbolethLogin?returnUrl=https://lms.fu-berlin.de/webapps/portal/execute/defaultTab&authProviderId=_3_1
+ Cookie: _shibsession_[SESS-NR]: [SESS-VALUE]
-> Set-Cookie: JSESSIONID: [JSESSION-KVV]
*/
private void step6(String shibsessionKey, String shibsessionName, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
private void startSession(String shibsessionKey, String shibsessionName, final NetworkCallback<Bundle> callback, final NetworkErrorCallback errorCallback) {
HashMap<String, String> cookies = new HashMap<>();
cookies.put(shibsessionKey, shibsessionName);
get("https://lms.fu-berlin.de/webapps/bb-auth-provider-shibboleth-bb_bb60/execute/shibbolethLogin?returnUrl=https://lms.fu-berlin.de/webapps/portal/execute/defaultTab&authProviderId=_3_1", cookies, response -> {
String cookies1 = response.getHeaders().get("Set-Cookie");
if (cookies1 ==null) {
errorCallback.onError(new NetworkError(100261, -1, "Cannot finish login process!"));
get(BB_SERVER_URL + "webapps/bb-auth-provider-shibboleth-bb_bb60/execute/shibbolethLogin?returnUrl=https://lms.fu-berlin.de/webapps/portal/execute/defaultTab&authProviderId=_3_1", cookies, response -> {
String cookiesSet = response.getHeaders().get("Set-Cookie");
if (cookiesSet == null) {
errorCallback.onError(new NetworkError(100261, -1, "Cannot finish BB login process!"));
return;
}
HashMap<String, String> object;
try {
object = getCookie(cookies1, new String[]{"session_id", "s_session_id"});
Bundle bundle = getCookie(cookiesSet, new String[]{"session_id", "s_session_id"});
callback.onResponse(bundle);
} catch (NoSuchFieldException e) {
errorCallback.onError(new NetworkError(100262, -1, "Cannot finish login process!"));
return;
errorCallback.onError(new NetworkError(100262, -1, "Cannot finish BB login process!"));
}
callback.onResponse(object);
}, error -> errorCallback.onError(new NetworkError(100260, error.networkResponse.statusCode, "Cannot finish login process!")));
}, error -> errorCallback.onError(new NetworkError(100260, error.networkResponse.statusCode, "Cannot finish BB login process!")));
}
}

View File

@@ -1,12 +1,16 @@
package de.sebse.fuplanner.services.kvv.sync;
import android.content.Context;
import android.os.Bundle;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import androidx.annotation.Nullable;
import org.jetbrains.annotations.NotNull;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.tools.Preferences;
import de.sebse.fuplanner.tools.network.HTTPService;
@@ -19,20 +23,20 @@ public class FULogin extends HTTPService {
super(context);
}
public void fulogin(String requestURI, String username, String password, final NetworkCallback<String> callback, final NetworkErrorCallback errorCallback) {
public void fulogin(String samlRequestUri, String username, String password, final NetworkCallback<String> callback, final NetworkErrorCallback errorCallback) {
String old_shib_idp_session = Preferences.getString(getContext(), R.string.pref_shib_idp_session);
step2(requestURI, old_shib_idp_session, success2 -> {
String samlResp = success2.get("SAMLResponse");
if (samlResp != null) {
callback.onResponse(samlResp);
startSamlRequest(samlRequestUri, old_shib_idp_session, samlRequest -> {
if (samlRequest.containsKey("SAMLResponse")) {
callback.onResponse(samlRequest.getString("SAMLResponse", ""));
return;
}
String fuJSESSIONID = success2.get("JSESSIONID");
step3(fuJSESSIONID, success3 -> {
step4(username, password, fuJSESSIONID, success4 -> {
String shib_idp_session = success4.get("shib_idp_session");
String JSESSIONID = samlRequest.getString("JSESSIONID");
openLoginForm(JSESSIONID, success -> {
finishLogin(username, password, JSESSIONID, samlResp -> {
String shib_idp_session = samlResp.getString("shib_idp_session");
Preferences.setString(getContext(), R.string.pref_shib_idp_session, shib_idp_session);
String samlResponse = success4.get("SAMLResponse");
String samlResponse = samlResp.getString("SAMLResponse");
if (samlResponse != null)
callback.onResponse(samlResponse);
else
@@ -47,24 +51,24 @@ public class FULogin extends HTTPService {
-> Set-Cookie: JSESSIONID=[JSESSION-FU]
-> Location: /idp-fub/profile/SAML2/Redirect/SSO?execution=e1s1
*/
private void step2(String url, @Nullable String shib_idp_session, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
private void startSamlRequest(String samlRequestUri, @Nullable String shib_idp_session, final NetworkCallback<Bundle> callback, final NetworkErrorCallback errorCallback) {
HashMap<String, String> cookiesReq = null;
if (shib_idp_session != null) {
cookiesReq = new HashMap<>();
cookiesReq.put("shib_idp_session", shib_idp_session);
}
get(url, cookiesReq, response -> {
get(samlRequestUri, cookiesReq, response -> {
String body = response.getParsed();
if (body != null) {
Pattern pattern = Pattern.compile("name=\"SAMLResponse\" value=\"([0-9a-zA-Z+]+=*)");
Matcher matcher = pattern.matcher(body);
if (!matcher.find()) {
errorCallback.onError(new NetworkError(100344, -1, "Error on getting SAML response!"));
errorCallback.onError(new NetworkError(100344, -1, "Error on getting FU SAML response!"));
return;
}
HashMap<String, String> object = new HashMap<>();
object.put("SAMLResponse", matcher.group(1));
callback.onResponse(object);
Bundle bundle = new Bundle();
bundle.putString("SAMLResponse", matcher.group(1));
callback.onResponse(bundle);
return;
}
String cookies = response.getHeaders().get("Set-Cookie");
@@ -72,14 +76,12 @@ public class FULogin extends HTTPService {
errorCallback.onError(new NetworkError(100321, -1, "Error on starting FU session!"));
return;
}
HashMap<String, String> object;
try {
object = getCookie(cookies, new String[]{"JSESSIONID"});
Bundle bundle = getCookie(cookies, new String[]{"JSESSIONID"});
callback.onResponse(bundle);
} catch (NoSuchFieldException e) {
errorCallback.onError(new NetworkError(100322, -1, "Error on starting FU session!"));
return;
}
callback.onResponse(object);
}, error -> errorCallback.onError(new NetworkError(100320, error.networkResponse.statusCode, "Error on starting FU session!")));
}
@@ -87,12 +89,12 @@ public class FULogin extends HTTPService {
3= GET [Location-Header 2]
+ Cookie: JSESSIONID=[JSESSION-FU]
*/
private void step3(String JSESSIONID_FU, final NetworkCallback<Boolean> callback, final NetworkErrorCallback errorCallback) {
private void openLoginForm(String JSESSIONID_FU, final NetworkCallback<Boolean> callback, final NetworkErrorCallback errorCallback) {
HashMap<String, String> cookies = new HashMap<>();
cookies.put("JSESSIONID", JSESSIONID_FU);
head("https://identity.fu-berlin.de/idp-fub/profile/SAML2/Redirect/SSO?execution=e1s1", cookies, response -> {
callback.onResponse(true);
}, error -> errorCallback.onError(new NetworkError(100330, error.networkResponse.statusCode, "Error starting login page!")));
}, error -> errorCallback.onError(new NetworkError(100330, error.networkResponse.statusCode, "Error starting FU login page!")));
}
/*
@@ -104,28 +106,28 @@ public class FULogin extends HTTPService {
-> Set-Cookie: shib_idp_session=[SHIB-IDP-SESSION]
-> Body SAMLResponse-Input-value
*/
private void step4(String username, String password, String JSESSIONID_FU, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
HashMap<String, String> cookies = new HashMap<>();
cookies.put("JSESSIONID", JSESSIONID_FU);
private void finishLogin(String username, String password, String JSESSIONID_FU, final NetworkCallback<Bundle> callback, final NetworkErrorCallback errorCallback) {
HashMap<String, String> cookiesReq = new HashMap<>();
cookiesReq.put("JSESSIONID", JSESSIONID_FU);
HashMap<String, String> body = new HashMap<>();
body.put("j_username", username);
body.put("j_password", password);
body.put("_eventId_proceed", "");
post("https://identity.fu-berlin.de/idp-fub/profile/SAML2/Redirect/SSO?execution=e1s1", cookies, body, response -> {
post("https://identity.fu-berlin.de/idp-fub/profile/SAML2/Redirect/SSO?execution=e1s1", cookiesReq, body, response -> {
String content = response.getParsed();
if (content == null) {
errorCallback.onError(new NetworkError(100343, -1, "Error on getting SAML response!"));
errorCallback.onError(new NetworkError(100343, -1, "Error on getting FU SAML response!"));
return;
}
String cookies1 = response.getHeaders().get("Set-Cookie");
if (cookies1 ==null) {
String cookies = response.getHeaders().get("Set-Cookie");
if (cookies == null) {
errorCallback.onError(new NetworkError(100341, -1, "Error on logging in to FU Identity Server!"));
return;
}
HashMap<String, String> object;
Bundle bundle;
try {
object = getCookie(cookies1, new String[]{"shib_idp_session"});
bundle = getCookie(cookies, new String[]{"shib_idp_session"});
} catch (NoSuchFieldException e) {
errorCallback.onError(new NetworkError(100342, -1, "Error on logging in to FU Identity Server!"));
return;
@@ -136,8 +138,8 @@ public class FULogin extends HTTPService {
errorCallback.onError(new NetworkError(100344, -1, "Error on getting SAML response!"));
return;
}
object.put("SAMLResponse", matcher.group(1));
callback.onResponse(object);
bundle.putString("SAMLResponse", matcher.group(1));
callback.onResponse(bundle);
}, error -> errorCallback.onError(new NetworkError(100345, error.networkResponse.statusCode, "Error on logging in to FU Identity Server!")));
}
}

View File

@@ -1,176 +0,0 @@
package de.sebse.fuplanner.services.kvv.sync;
import android.content.Context;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import de.sebse.fuplanner.services.kvv.Constants;
import de.sebse.fuplanner.services.kvv.types.LoginTokenKVV;
import de.sebse.fuplanner.tools.network.HTTPService;
import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkError;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
public class KVVLogin extends HTTPService {
private final FULogin mFULogin;
private long lastHash;
private long lastSync;
private static final long MAX_CACHE_TIME = 1000 * 60; // 1 minute
public static final String KVV_SERVER_URL = Constants.KVV_SERVER_URL;
public KVVLogin(Context context, FULogin fuLogin) {
super(context);
this.mFULogin = fuLogin;
}
public void testLoginToken(@NotNull LoginTokenKVV token, @NotNull NetworkCallback<LoginTokenKVV> callback, @NotNull NetworkErrorCallback errorCallback) {
if (token.hashCode() == lastHash && lastSync + MAX_CACHE_TIME > System.currentTimeMillis() && token.getFullName() != null) {
callback.onResponse(token);
return;
}
get(String.format(KVV_SERVER_URL+"direct/profile/%s.json", token.getUsername()), token.getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
errorCallback.onError(new NetworkError(100172, 403, "Testing login failed!"));
return;
}
try {
JSONObject json = new JSONObject(body);
String displayName = json.getString("displayName");
String email = json.getString("email");
token.setAdditionals(displayName, email);
lastSync = System.currentTimeMillis();
lastHash = token.hashCode();
callback.onResponse(token);
} catch (JSONException e) {
errorCallback.onError(new NetworkError(100171, 403, "Cannot parse profile!"));
}
}, error -> errorCallback.onError(new NetworkError(100170, error.networkResponse.statusCode, "Testing login failed!")));
}
public void doLogin(String username, String password, NetworkCallback<LoginTokenKVV> callback, NetworkErrorCallback error) {
step0(username, success -> {
step1(success1 -> {
String samlLocation = success1.get("Location");
mFULogin.fulogin(samlLocation, username, password, samlResponse -> {
step5(samlResponse, success5 -> {
String shibsessionKey = success5.get("shibsessionKey");
String shibsessionName = success5.get("shibsessionName");
step6(shibsessionKey, shibsessionName, success6 -> {
String kvvJSESSIONID = success6.get("JSESSIONID");
LoginTokenKVV token = new LoginTokenKVV(username, kvvJSESSIONID);
callback.onResponse(token);
}, error);
}, error);
}, error);
}, error);
}, error);
}
private void step0(String username, final NetworkCallback<Boolean> callback, final NetworkErrorCallback errorCallback) {
get(String.format(KVV_SERVER_URL+"direct/profile/%s", username), null, result -> {
callback.onResponse(true);
}, error -> {
if (error.networkResponse.statusCode == 500) {
errorCallback.onError(new NetworkError(100101, error.networkResponse.statusCode, "KVV not available!"));
} else {
callback.onResponse(true);
}
});
}
/*
1= GET https://kvv.imp.fu-berlin.de/Shibboleth.sso/Login?entityID=https://identity.fu-berlin.de/idp-fub
-> Location-Header: https://identity.fu-berlin.de/idp-fub/profile/SAML2/Redirect/SSO?SAMLResponse=[SAMLResponse]&RelayState=[RelayState]
*/
private void step1(final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
get(KVV_SERVER_URL+"Shibboleth.sso/Login?entityID=https://identity.fu-berlin.de/idp-fub", null, response -> {
String location = response.getHeaders().get("Location");
if (location==null) {
errorCallback.onError(new NetworkError(100111, -1, "Error on getting SAML request!"));
return;
}
HashMap<String, String> object = new HashMap<>();
object.put("Location", location);
callback.onResponse(object);
}, error -> errorCallback.onError(new NetworkError(100110, error.networkResponse.statusCode, "Error on getting SAML request!")));
}
/*
5= POST https://kvv.imp.fu-berlin.de/Shibboleth.sso/SAML2/POST
+ Body: SAMLResponse=[SAML-RESPONSE]
+ Header: Content-Type: application/x-www-form-urlencoded
-> Set-Cookie: _shibsession_[SESS-NR]: [SESS-VALUE]
*/
private void step5(String SAMLResponse, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
HashMap<String, String> body = new HashMap<>();
body.put("SAMLResponse", SAMLResponse);
post(KVV_SERVER_URL+"Shibboleth.sso/SAML2/POST", null, body, response -> {
String cookies = response.getHeaders().get("Set-Cookie");
if (cookies ==null) {
errorCallback.onError(new NetworkError(100151, -1, "Error on starting KVV session!"));
return;
}
HashMap<String, String> object = new HashMap<>();
Pattern pattern = Pattern.compile("(_shibsession_[0-9a-f]+)=([^;]+);");
Matcher matcher = pattern.matcher(cookies);
if (!matcher.find()) {
errorCallback.onError(new NetworkError(100152, -1, "Error on starting KVV session!"));
}
object.put("shibsessionKey", matcher.group(1));
object.put("shibsessionName", matcher.group(2));
callback.onResponse(object);
}, error -> errorCallback.onError(new NetworkError(100150, error.networkResponse.statusCode, "Error on starting KVV session!")));
}
/*
6= https://kvv.imp.fu-berlin.de/sakai-login-tool/container
+ Cookie: _shibsession_[SESS-NR]: [SESS-VALUE]
-> Set-Cookie: JSESSIONID: [JSESSION-KVV]
*/
private void step6(String shibsessionKey, String shibsessionName, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
HashMap<String, String> cookies = new HashMap<>();
cookies.put(shibsessionKey, shibsessionName);
get(KVV_SERVER_URL+"sakai-login-tool/container", cookies, response -> {
String cookies1 = response.getHeaders().get("Set-Cookie");
if (cookies1 ==null) {
errorCallback.onError(new NetworkError(100161, -1, "Cannot finish login process!"));
return;
}
HashMap<String, String> object;
try {
object = getCookie(cookies1, new String[]{"JSESSIONID"});
} catch (NoSuchFieldException e) {
errorCallback.onError(new NetworkError(100162, -1, "Cannot finish login process!"));
return;
}
callback.onResponse(object);
}, error -> errorCallback.onError(new NetworkError(100160, error.networkResponse.statusCode, "Cannot finish login process!")));
}
}

View File

@@ -1,204 +0,0 @@
package de.sebse.fuplanner.services.kvv.sync;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ComponentName;
import android.content.ContentProviderClient;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SyncResult;
import android.os.Bundle;
import android.os.IBinder;
import java.util.ArrayList;
import java.util.Iterator;
import androidx.annotation.StringRes;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.fragments.moddetails.ModulePart;
import de.sebse.fuplanner.services.kvv.KVV;
import de.sebse.fuplanner.services.kvv.KVVListener;
import de.sebse.fuplanner.services.kvv.types.Announcement;
import de.sebse.fuplanner.services.kvv.types.Assignment;
import de.sebse.fuplanner.services.kvv.types.AssignmentList;
import de.sebse.fuplanner.services.kvv.types.EventList;
import de.sebse.fuplanner.services.kvv.types.Grade;
import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.services.kvv.types.Resource;
import de.sebse.fuplanner.tools.CustomAccountManager;
import de.sebse.fuplanner.tools.CustomNotificationManager;
import de.sebse.fuplanner.tools.NewAsyncQueue;
import de.sebse.fuplanner.tools.UtilsDate;
import de.sebse.fuplanner.tools.logging.Logger;
import static de.sebse.fuplanner.MainActivity.FRAGMENT_MODULES_DETAILS;
public class KVVSyncAdapter extends AbstractThreadedSyncAdapter {
private KVV mKVV;
private Logger log = new Logger(this);
private NewAsyncQueue mQueue = new NewAsyncQueue();
private boolean mBound = false;
private boolean mWaitForBound = false;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
KVV.LocalBinder binder = (KVV.LocalBinder) service;
mKVV = binder.getService();
mBound = true;
if (mWaitForBound) {
mWaitForBound = false;
mQueue.next();
}
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
mKVV = null;
}
};
/**
* Set up the sync adapter
*/
KVVSyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
init(context);
}
/**
* Set up the sync adapter. This form of the
* constructor maintains compatibility with Android 3.0
* and later platform versions
*/
public KVVSyncAdapter(
Context context,
boolean autoInitialize,
boolean allowParallelSyncs) {
super(context, autoInitialize, allowParallelSyncs);
init(context);
}
private void init(Context context) {
// Bind to LocalService
}
/*
* Specify the code you want to run in the sync adapter. The entire
* sync adapter runs in a background thread, so you don't have to set
* up your own background processing.
*/
@Override
public void onPerformSync(
Account account,
Bundle extras,
String authority,
ContentProviderClient provider,
SyncResult syncResult) {
if (!mBound) {
Intent intent = new Intent(getContext(), KVV.class);
mWaitForBound = true;
mQueue.add(() -> {});
}
mQueue.add(() -> {
mKVV.account().restoreOnlineLogin(bool -> {
mQueue.next();
});
});
mQueue.add(() -> {
if (!mKVV.account().isLoggedIn()) {
log.w("Not logged in!");
return;
}
mKVV.modules().list().reloadIfOutdated();
mKVV.modules().list().recv(success -> {
final int[] latch = {0};
Iterator<Modules.Module> iterator = success.latestSemesterIterator();
while (iterator.hasNext()) {
latch[0] += 1;
iterator.next();
}
iterator = success.latestSemesterIterator();
while (iterator.hasNext()) {
Modules.Module module = iterator.next();
final ArrayList<Announcement> announcements = module.announcements;
final AssignmentList assignments = module.assignments;
final EventList events = module.events;
final ArrayList<Grade> gradebook = module.gradebook;
final ArrayList<Resource> resources = module.resources;
mKVV.modules().details().recv(module, success1 -> {
if (success1.second) {
sendNotifications(announcements, module.announcements, module.title, Announcement::getTitle, Announcement::getId,
module.getID(), ModulePart.ANNOUNCEMENT,
R.string.announcement_updated, R.string.announcement_added, R.string.announcement_removed);
sendNotifications(assignments, module.assignments, module.title, Assignment::getTitle, Assignment::getId,
module.getID(), ModulePart.ASSIGNMENT,
R.string.assignment_updated, R.string.assignment_added, R.string.assignment_removed);
sendNotifications(events, module.events, module.title, evt -> evt.getTitle()+" - "+UtilsDate.getModifiedDate(evt.getStartDate()), event -> String.valueOf(event.getStartDate())+event.getType()+event.getTitle(),
module.getID(), ModulePart.EVENT,
R.string.event_updated, R.string.event_added, R.string.event_removed);
sendNotifications(gradebook, module.gradebook, module.title, Grade::getItemName, Grade::getItemName,
module.getID(), ModulePart.GRADEBOOK,
R.string.gradebook_updated, R.string.gradebook_added, R.string.gradebook_removed);
sendNotifications(resources, module.resources, module.title, Resource::getTitle, Resource::getUrl,
module.getID(), ModulePart.RESOURCES,
R.string.resource_updated, R.string.resource_added, R.string.resource_removed);
if (--latch[0] == 0) mQueue.next();
}
}, error -> {
log.e(error);
if (--latch[0] == 0) mQueue.next();
}, true);
}
}, msg -> {
log.e(msg);
mQueue.next();
}, true);
});
mQueue.add(() -> {
mBound = false;
mKVV = null;
getContext().unbindService(mConnection);
});
}
private <T> void sendNotifications(Iterable<T> oldList, Iterable<T> newList, String title, StringInterface<T> titleInterface, StringInterface<T> idInterface, String moduleId, int modulePart, @StringRes int updateRes, @StringRes int addRes, @StringRes int removeRes) {
if (oldList == null || newList == null) {
return;
}
ArrayList<T> obsoletes = new ArrayList<>();
for (T old: oldList) {
obsoletes.add(old);
}
String targetData = moduleId+"."+ModulePart.getPageByPart(modulePart);
for (T newEntry: newList) {
boolean found = false;
for (T oldEntry: oldList) {
if (idInterface.get(newEntry).equals(idInterface.get(oldEntry))) {
found = true;
if (newEntry.hashCode() != oldEntry.hashCode()) {
CustomNotificationManager.sendNotification(getContext(), getContext().getString(updateRes, title), titleInterface.get(newEntry), FRAGMENT_MODULES_DETAILS, targetData);
}
obsoletes.remove(oldEntry);
break;
}
}
if (!found) {
CustomNotificationManager.sendNotification(getContext(), getContext().getString(addRes, title), titleInterface.get(newEntry), FRAGMENT_MODULES_DETAILS, targetData);
}
}
for (T oldEntry: obsoletes) {
CustomNotificationManager.sendNotification(getContext(), getContext().getString(removeRes, title), titleInterface.get(oldEntry), FRAGMENT_MODULES_DETAILS, targetData);
}
}
@FunctionalInterface
interface StringInterface<T> {
String get(T element);
}
}

View File

@@ -0,0 +1,55 @@
package de.sebse.fuplanner.services.kvv.sync;
import android.content.Context;
import android.os.Bundle;
import org.jetbrains.annotations.NotNull;
import de.sebse.fuplanner.services.kvv.types.LoginToken;
import de.sebse.fuplanner.tools.network.HTTPService;
import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
public abstract class LoginRoutine<T extends LoginToken> extends HTTPService {
private long lastHash;
private long lastSync;
private static final long MAX_CACHE_TIME = 1000 * 60; // 1 minute
public LoginRoutine(Context context) {
super(context);
}
public final void testToken(@NotNull T token, @NotNull NetworkCallback<T> callback, @NotNull NetworkErrorCallback error) {
if (token.hashCode() == lastHash && lastSync + MAX_CACHE_TIME > System.currentTimeMillis() && token.hasAdditionals()) {
callback.onResponse(token);
return;
}
checkToken(token, (bundle) -> {
token.setAdditionals(bundle);
lastSync = System.currentTimeMillis();
lastHash = token.hashCode();
callback.onResponse(token);
}, error);
}
public abstract void doesAccountExists(@NotNull String username, @NotNull NetworkCallback<Boolean> callback, @NotNull NetworkErrorCallback error);
protected abstract void checkToken(@NotNull T token, @NotNull NetworkCallback<Bundle> bundleCallback, @NotNull NetworkErrorCallback error);
public final void login(@NotNull String username, @NotNull String password, @NotNull NetworkCallback<T> callback, @NotNull NetworkErrorCallback error) {
doesAccountExists(username, success -> {
if (success) {
createLoginToken(username, password, callback, error);
return;
} else {
callback.onResponse(createUnavailableToken());
return;
}
}, error);
}
protected abstract void createLoginToken(@NotNull String username, @NotNull String password, @NotNull NetworkCallback<T> callback, @NotNull NetworkErrorCallback error);
protected abstract T createUnavailableToken();
}

View File

@@ -0,0 +1,373 @@
package de.sebse.fuplanner.services.kvv.sync;
import android.Manifest;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ComponentName;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SyncResult;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.CalendarContract.Calendars;
import android.provider.CalendarContract.Events;
import android.util.Pair;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import androidx.annotation.StringRes;
import androidx.core.content.ContextCompat;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.fragments.moddetails.ModulePart;
import de.sebse.fuplanner.services.kvv.KVV;
import de.sebse.fuplanner.services.kvv.types.Announcement;
import de.sebse.fuplanner.services.kvv.types.Assignment;
import de.sebse.fuplanner.services.kvv.types.AssignmentList;
import de.sebse.fuplanner.services.kvv.types.Event;
import de.sebse.fuplanner.services.kvv.types.EventList;
import de.sebse.fuplanner.services.kvv.types.Grade;
import de.sebse.fuplanner.services.kvv.types.Gradebook;
import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.services.kvv.types.Resource;
import de.sebse.fuplanner.tools.CustomNotificationManager;
import de.sebse.fuplanner.tools.NewAsyncQueue;
import de.sebse.fuplanner.tools.Preferences;
import de.sebse.fuplanner.tools.UtilsDate;
import de.sebse.fuplanner.tools.logging.Logger;
import static android.provider.CalendarContract.CALLER_IS_SYNCADAPTER;
import static de.sebse.fuplanner.MainActivity.FRAGMENT_MODULES_DETAILS;
public class KVVSyncAdapter extends AbstractThreadedSyncAdapter {
private KVV mKVV;
private Logger log = new Logger(this);
private NewAsyncQueue mQueue = new NewAsyncQueue();
private boolean mBound = false;
private boolean mWaitForBound = false;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
KVV.LocalBinder binder = (KVV.LocalBinder) service;
mKVV = binder.getService();
mBound = true;
if (mWaitForBound) {
mWaitForBound = false;
mQueue.next();
}
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
mKVV = null;
}
};
/**
* Set up the sync adapter
*/
KVVSyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
init(context);
}
/**
* Set up the sync adapter. This form of the
* constructor maintains compatibility with Android 3.0
* and later platform versions
*/
public KVVSyncAdapter(
Context context,
boolean autoInitialize,
boolean allowParallelSyncs) {
super(context, autoInitialize, allowParallelSyncs);
init(context);
}
private void init(Context context) {
// Bind to LocalService
}
/*
* Specify the code you want to run in the sync adapter. The entire
* sync adapter runs in a background thread, so you don't have to set
* up your own background processing.
*/
@Override
public void onPerformSync(
Account account,
Bundle extras,
String authority,
ContentProviderClient provider,
SyncResult syncResult) {
if (!mBound && !mWaitForBound) {
Intent intent = new Intent(getContext(), KVV.class);
getContext().bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
mWaitForBound = true;
mQueue.add(() -> {});
}
mQueue.add(() -> {
mKVV.account().restoreOnlineLogin(bool -> {
mQueue.next();
});
});
mQueue.add(() -> {
if (!mKVV.account().isLoggedIn()) {
log.w("Not logged in!");
mQueue.next();
return;
}
mKVV.modules().list().reloadIfOutdated();
mKVV.modules().list().recv(success -> {
final int[] latch = {0};
Iterator<Modules.Module> iterator = success.latestSemesterIterator();
while (iterator.hasNext()) {
latch[0] += 1;
iterator.next();
}
boolean doAddToCalendar = createCalendar(account);
log.d("sync calendar", doAddToCalendar);
iterator = success.latestSemesterIterator();
while (iterator.hasNext()) {
Modules.Module module = iterator.next();
final ArrayList<Announcement> announcements = module.announcements;
final AssignmentList assignments = module.assignments;
final EventList events = module.events;
final Gradebook gradebook = module.gradebook;
final ArrayList<Resource> resources = module.resources;
mKVV.modules().details().recv(module, success1 -> {
if (success1.second) {
sendNotifications(announcements, module.announcements, module.title, Announcement::getTitle, Announcement::getId,
module.getID(), ModulePart.ANNOUNCEMENT,
R.string.announcement_updated, R.string.announcement_added, R.string.announcement_removed);
sendNotifications(assignments, module.assignments, module.title, Assignment::getTitle, Assignment::getId,
module.getID(), ModulePart.ASSIGNMENT,
R.string.assignment_updated, R.string.assignment_added, R.string.assignment_removed);
//ArrayList<Event> differencesAdd = new ArrayList<>();
//ArrayList<Pair<Event, Event>> differencesUpd = new ArrayList<>();
//ArrayList<Event> differencesDel = new ArrayList<>();
sendNotifications(events, module.events, module.title, evt -> evt.getTitle()+" - "+UtilsDate.getModifiedDate(evt.getStartDate()), event -> event.getStartDate() +event.getType()+event.getTitle(),
module.getID(), ModulePart.EVENT,
R.string.event_updated, R.string.event_added, R.string.event_removed/*,
differencesAdd, differencesUpd, differencesDel*/);
sendNotifications(gradebook, module.gradebook, module.title, Grade::getItemName, Grade::getItemName,
module.getID(), ModulePart.GRADEBOOK,
R.string.gradebook_updated, R.string.gradebook_added, R.string.gradebook_removed);
sendNotifications(resources, module.resources, module.title, Resource::getTitle, Resource::getUrl,
module.getID(), ModulePart.RESOURCES,
R.string.resource_updated, R.string.resource_added, R.string.resource_removed);
if (doAddToCalendar) {
addToCalendar(module.events, account);
}
if (--latch[0] == 0) {
forceSync();
mQueue.next();
}
}
}, error -> {
log.e(error);
if (--latch[0] == 0) {
forceSync();
mQueue.next();
}
}, true);
}
}, error -> {
log.e(error);
mQueue.next();
}, true);
});
mQueue.add(() -> {
if (mBound) {
getContext().unbindService(mConnection);
}
mBound = false;
mKVV = null;
mQueue.next();
});
}
static Uri asSyncAdapter(Uri uri, String account, String accountType) {
return uri.buildUpon()
.appendQueryParameter(CALLER_IS_SYNCADAPTER, "true")
.appendQueryParameter(Calendars.ACCOUNT_NAME, account)
.appendQueryParameter(Calendars.ACCOUNT_TYPE, accountType).build();
}
private static Uri createCalendarWithName(Context ctx, Account account, String calendarName) {
String accountName = account.name;
String accountType = account.type;
Uri target = asSyncAdapter(Calendars.CONTENT_URI, accountName, accountType);
ContentValues values = new ContentValues();
values.put(Calendars._ID, calendarName.hashCode());
values.put(Calendars.ACCOUNT_NAME, accountName);
values.put(Calendars.ACCOUNT_TYPE, accountType);
values.put(Calendars.NAME, calendarName);
values.put(Calendars.CALENDAR_DISPLAY_NAME, calendarName);
values.put(Calendars.CALENDAR_COLOR, 0x00FF00);
values.put(Calendars.CALENDAR_ACCESS_LEVEL, Calendars.CAL_ACCESS_READ);
values.put(Calendars.OWNER_ACCOUNT, accountName);
values.put(Calendars.VISIBLE, 1);
values.put(Calendars.SYNC_EVENTS, 1);
values.put(Calendars.CALENDAR_TIME_ZONE, "Europe/Berlin");
values.put(Calendars.CAN_PARTIALLY_UPDATE, 1);
values.put(Calendars.CAL_SYNC1, System.currentTimeMillis());
return ctx.getContentResolver().insert(target, values);
}
private int createEvents(Context ctx, Account account, String calendarName, EventList events) {
String accountName = account.name;
String accountType = account.type;
Uri target = asSyncAdapter(Events.CONTENT_URI, accountName, accountType);
ContentValues[] contentValues = new ContentValues[events.size()];
for (int i = 0; i < contentValues.length; i++) {
Event event = events.get(i);
ContentValues values = new ContentValues();
//values.put(Events._ID, event.hashCode());
values.put(Events.TITLE, event.getTitle());
values.put(Events.DTSTART, event.getStartDate());
values.put(Events.DTEND, event.getEndDate());
values.put(Events.CALENDAR_ID, calendarName.hashCode());
contentValues[i] = values;
//ctx.getContentResolver().insert(target, values);
}
log.d(contentValues.length);
return ctx.getContentResolver().bulkInsert(target, contentValues);
}
private static Cursor getCalendars(Context ctx, Account account) {
Uri target = asSyncAdapter(Calendars.CONTENT_URI, account.name, account.type);
return ctx.getContentResolver().query(target, new String[]{Calendars.CALENDAR_DISPLAY_NAME, Calendars.ACCOUNT_NAME}, null, null, null);
}
private static Cursor getEvents(Context ctx, Account account) {
Uri target = asSyncAdapter(Events.CONTENT_URI, account.name, account.type);
return ctx.getContentResolver().query(target, new String[]{Events.TITLE, Events.DTSTART}, null, null, null);
}
private static int deleteCalendars(Context ctx, Account account) {
String accountName = account.name;
String accountType = account.type;
Uri target = asSyncAdapter(Calendars.CONTENT_URI, account.name, account.type);
ContentValues values = new ContentValues();
values.put(Calendars.ACCOUNT_NAME, accountName);
values.put(Calendars.ACCOUNT_TYPE, accountType);
return ctx.getContentResolver().delete(target, null, null);
}
private void addToCalendar(EventList events, Account account) {
if (events == null) {
return;
}
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_CALENDAR) == PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_CALENDAR) == PackageManager.PERMISSION_GRANTED) {
boolean integrationEnabled = Preferences.getBoolean(getContext(), R.string.pref_add_calendar);
if (integrationEnabled) {
createEvents(getContext(), account, getContext().getString(R.string.app_name), events);
}
}
}
private boolean createCalendar(Account account) {
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_CALENDAR) == PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_CALENDAR) == PackageManager.PERMISSION_GRANTED) {
boolean integrationEnabled = Preferences.getBoolean(getContext(), R.string.pref_add_calendar);
if (integrationEnabled) {
//log.w("No calendar found! Add calendar...");
deleteCalendars(getContext(), account);
createCalendarWithName(getContext(), account, getContext().getString(R.string.app_name));
return true;
} else {
log.w("Calendar found and integration disabled! Delete calendar...");
deleteCalendars(getContext(), account);
return false;
}
} else {
log.w("Permission calendar not granted!");
return false;
}
}
private void forceSync() {
// Force a sync
Bundle extras = new Bundle();
extras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
AccountManager am = AccountManager.get(getContext());
Account[] acc = am.getAccountsByType("com.google");
Account account = null;
if (acc.length>0) {
account = acc[0];
ContentResolver.requestSync(account, "com.android.calendar", extras);
}
}
private <T> void sendNotifications(Iterable<T> oldList, Iterable<T> newList, String title, StringInterface<T> titleInterface, StringInterface<T> idInterface, String moduleId, int modulePart, @StringRes int updateRes, @StringRes int addRes, @StringRes int removeRes) {
sendNotifications(oldList, newList, title, titleInterface, idInterface, moduleId, modulePart, updateRes, addRes, removeRes, null, null, null);
}
private <T> void sendNotifications(Iterable<T> oldList, Iterable<T> newList, String title, StringInterface<T> titleInterface, StringInterface<T> idInterface, String moduleId, int modulePart, @StringRes int updateRes, @StringRes int addRes, @StringRes int removeRes, ArrayList<T> changesAdd, ArrayList<Pair<T, T>> changesUpd, ArrayList<T> changesDel) {
if (oldList == null || newList == null) {
return;
}
ArrayList<T> obsoletes = new ArrayList<>();
for (T old: oldList) {
obsoletes.add(old);
}
String targetData = moduleId+"."+ModulePart.getPageByPart(modulePart);
for (T newEntry: newList) {
boolean found = false;
for (T oldEntry: oldList) {
if (idInterface.get(newEntry).equals(idInterface.get(oldEntry))) {
found = true;
if (newEntry.hashCode() != oldEntry.hashCode()) {
CustomNotificationManager.sendNotification(getContext(), getContext().getString(updateRes, title), titleInterface.get(newEntry), FRAGMENT_MODULES_DETAILS, targetData);
if (changesUpd != null) {
changesUpd.add(new Pair<>(oldEntry, newEntry));
}
}
obsoletes.remove(oldEntry);
break;
}
}
if (!found) {
CustomNotificationManager.sendNotification(getContext(), getContext().getString(addRes, title), titleInterface.get(newEntry), FRAGMENT_MODULES_DETAILS, targetData);
if (changesAdd != null) {
changesAdd.add(newEntry);
}
}
}
for (T oldEntry: obsoletes) {
CustomNotificationManager.sendNotification(getContext(), getContext().getString(removeRes, title), titleInterface.get(oldEntry), FRAGMENT_MODULES_DETAILS, targetData);
if (changesDel != null) {
changesDel.add(oldEntry);
}
}
}
@FunctionalInterface
interface StringInterface<T> {
String get(T element);
}
}

View File

@@ -0,0 +1,158 @@
package de.sebse.fuplanner.services.kvv.sync;
import android.content.Context;
import android.os.Bundle;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import de.sebse.fuplanner.services.kvv.types.LoginTokenWB;
import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkError;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
import static de.sebse.fuplanner.services.kvv.Constants.WB_SERVER_URL;
public class WBLogin extends LoginRoutine<LoginTokenWB> {
private final FULogin fuLogin;
public WBLogin(Context context, FULogin fuLogin) {
super(context);
this.fuLogin = fuLogin;
}
@Override
public void doesAccountExists(@NotNull String username, @NotNull NetworkCallback<Boolean> callback, @NotNull NetworkErrorCallback error) {
callback.onResponse(true);
get(String.format(WB_SERVER_URL + "direct/profile/%s.json", username), null, response -> {
callback.onResponse(true);
}, err -> {
if (err.networkResponse.statusCode == 403) {
callback.onResponse(true);
} else {
callback.onResponse(false);
}
});
}
@Override
protected LoginTokenWB createUnavailableToken() {
return new LoginTokenWB();
}
@Override
protected void checkToken(@NotNull LoginTokenWB token, @NotNull NetworkCallback<Bundle> bundleCallback, @NotNull NetworkErrorCallback error) {
get(String.format(WB_SERVER_URL + "direct/profile/%s.json", token.getUsername()), token.getCookies(), response -> {
String body = response.getParsed();
if (body == null) {
error.onError(new NetworkError(100172, 403, "Testing WB login failed!"));
return;
}
try {
JSONObject json = new JSONObject(body);
Bundle bundle = new Bundle();
bundle.putString("fullName", json.getString("displayName"));
bundle.putString("email", json.getString("email"));
bundleCallback.onResponse(bundle);
} catch (JSONException e) {
error.onError(new NetworkError(100171, 403, "Cannot parse WB profile!"));
}
}, err -> error.onError(new NetworkError(100170, err.networkResponse.statusCode, "Testing WB login failed!")));
}
@Override
public void createLoginToken(@NotNull String username, @NotNull String password, @NotNull NetworkCallback<LoginTokenWB> callback, @NotNull NetworkErrorCallback error) {
getSAMLLocation(samlLocation -> {
fuLogin.fulogin(samlLocation, username, password, samlResponse -> {
startShibSession(samlResponse, shibSessionKey -> {
String shibsessionKey = shibSessionKey.getString("shibsessionKey");
String shibsessionName = shibSessionKey.getString("shibsessionName");
startSession(shibsessionKey, shibsessionName, sessionCookies -> {
Bundle bundle = new Bundle();
bundle.putString("username", username);
bundle.putAll(sessionCookies);
LoginTokenWB tokenWB = new LoginTokenWB(bundle);
testToken(tokenWB, callback, error);
}, error);
}, error);
}, error);
}, error);
}
/*
1= GET https://mycampus.imp.fu-berlin.de/Shibboleth.sso/Login?entityID=https://identity.fu-berlin.de/idp-fub
-> Location-Header: https://identity.fu-berlin.de/idp-fub/profile/SAML2/Redirect/SSO?SAMLResponse=[SAMLResponse]&RelayState=[RelayState]
*/
private void getSAMLLocation(final NetworkCallback<String> callback, final NetworkErrorCallback errorCallback) {
get(WB_SERVER_URL + "Shibboleth.sso/Login?entityID=https://identity.fu-berlin.de/idp-fub", null, response -> {
String location = response.getHeaders().get("Location");
if (location == null) {
errorCallback.onError(new NetworkError(100111, -1, "Error on getting WB SAML request!"));
return;
}
callback.onResponse(location);
}, error -> errorCallback.onError(new NetworkError(100110, error.networkResponse.statusCode, "Error on getting WB SAML request!")));
}
/*
5= POST https://mycampus.imp.fu-berlin.de/Shibboleth.sso/SAML2/POST
+ Body: SAMLResponse=[SAML-RESPONSE]
+ Header: Content-Type: application/x-www-form-urlencoded
-> Set-Cookie: _shibsession_[SESS-NR]: [SESS-VALUE]
*/
private void startShibSession(String samlResponse, final NetworkCallback<Bundle> callback, final NetworkErrorCallback errorCallback) {
HashMap<String, String> body = new HashMap<>();
body.put("SAMLResponse", samlResponse);
post(WB_SERVER_URL + "Shibboleth.sso/SAML2/POST", null, body, response -> {
String cookies = response.getHeaders().get("Set-Cookie");
if (cookies ==null) {
errorCallback.onError(new NetworkError(100151, -1, "Error on starting WB session!"));
return;
}
Pattern pattern = Pattern.compile("(_shibsession_[0-9a-f]+)=([^;]+);");
Matcher matcher = pattern.matcher(cookies);
if (!matcher.find()) {
errorCallback.onError(new NetworkError(100152, -1, "Error on starting WB session!"));
}
Bundle bundle = new Bundle();
bundle.putString("shibsessionKey", matcher.group(1));
bundle.putString("shibsessionName", matcher.group(2));
callback.onResponse(bundle);
}, error -> errorCallback.onError(new NetworkError(100150, error.networkResponse.statusCode, "Error on starting WB session!")));
}
/*
6= https://mycampus.imp.fu-berlin.de/sakai-login-tool/container
+ Cookie: _shibsession_[SESS-NR]: [SESS-VALUE]
-> Set-Cookie: JSESSIONID: [JSESSION-KVV]
*/
private void startSession(String shibsessionKey, String shibsessionName, final NetworkCallback<Bundle> callback, final NetworkErrorCallback errorCallback) {
HashMap<String, String> cookies = new HashMap<>();
cookies.put(shibsessionKey, shibsessionName);
get(WB_SERVER_URL + "sakai-login-tool/container", cookies, response -> {
String cookies1 = response.getHeaders().get("Set-Cookie");
if (cookies1 ==null) {
errorCallback.onError(new NetworkError(100161, -1, "Cannot finish WB login process!"));
return;
}
try {
Bundle bundle = getCookie(cookies1, new String[]{"JSESSIONID"});
callback.onResponse(bundle);
} catch (NoSuchFieldException e) {
errorCallback.onError(new NetworkError(100162, -1, "Cannot finish WB login process!"));
}
}, error -> errorCallback.onError(new NetworkError(100160, error.networkResponse.statusCode, "Cannot finish WB login process!")));
}
}

View File

@@ -3,6 +3,7 @@ package de.sebse.fuplanner.services.kvv.types;
import android.content.Context;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
@@ -23,7 +24,12 @@ public class CacheBBCourse implements Serializable {
private HashMap<String, Long> mBBCourseListRefresh = new HashMap<>();
public static CacheBBCourse load(Context context) throws IOException, ClassNotFoundException {
FileInputStream fis = context.openFileInput(FILE_NAME);
FileInputStream fis;
try {
fis = context.openFileInput(FILE_NAME);
} catch (FileNotFoundException e) {
return null;
}
ObjectInputStream is = new ObjectInputStream(fis);
Object readObject = is.readObject();
if (!(readObject instanceof CacheBBCourse))
@@ -76,8 +82,8 @@ public class CacheBBCourse implements Serializable {
return mKVVCourseList.contains(courseID);
}
public void setBBCourse(String courseID, Modules.Module lecturer) {
mBBCourseList.put(courseID, lecturer);
public void setBBCourse(String courseID, Modules.Module module) {
mBBCourseList.put(courseID, module);
mBBCourseListRefresh.put(courseID, System.currentTimeMillis());
}

View File

@@ -3,13 +3,13 @@ package de.sebse.fuplanner.services.kvv.types;
import android.content.Context;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
public class CacheKVVCourse implements Serializable {
private transient static final long RESAVE_TIMER = 1000L * 60 * 60 * 24 * 30;
@@ -21,7 +21,12 @@ public class CacheKVVCourse implements Serializable {
private HashMap<String, Long> mKVVCourseListRefresh = new HashMap<>();
public static CacheKVVCourse load(Context context) throws IOException, ClassNotFoundException {
FileInputStream fis = context.openFileInput(FILE_NAME);
FileInputStream fis;
try {
fis = context.openFileInput(FILE_NAME);
} catch (FileNotFoundException e) {
return null;
}
ObjectInputStream is = new ObjectInputStream(fis);
Object readObject = is.readObject();
if (!(readObject instanceof CacheKVVCourse))
@@ -63,8 +68,8 @@ public class CacheKVVCourse implements Serializable {
fos.close();
}
public void setKVVCourse(String courseID, Modules.Module lecturer) {
mKVVCourseList.put(courseID, lecturer);
public void setKVVCourse(String courseID, Modules.Module module) {
mKVVCourseList.put(courseID, module);
mKVVCourseListRefresh.put(courseID, System.currentTimeMillis());
}

View File

@@ -3,6 +3,7 @@ package de.sebse.fuplanner.services.kvv.types;
import android.content.Context;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
@@ -23,7 +24,12 @@ public class CacheLecturer implements Serializable {
private HashMap<String, Long> mLecturersRefresh = new HashMap<>();
public static CacheLecturer load(Context context) throws IOException, ClassNotFoundException {
FileInputStream fis = context.openFileInput(FILE_NAME);
FileInputStream fis;
try {
fis = context.openFileInput(FILE_NAME);
} catch (FileNotFoundException e) {
return null;
}
ObjectInputStream is = new ObjectInputStream(fis);
Object readObject = is.readObject();
if (!(readObject instanceof CacheLecturer))

View File

@@ -1,5 +1,8 @@
package de.sebse.fuplanner.services.kvv.types;
import android.content.Context;
import android.content.res.Configuration;
import com.google.android.gms.common.internal.Objects;
import java.io.Serializable;
@@ -8,6 +11,9 @@ import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDelegate;
import de.sebse.fuplanner.tools.ColorRGB;
public class Event implements Serializable {
@@ -60,7 +66,7 @@ public class Event implements Serializable {
return siteId;
}
public ColorRGB getColor() {
public ColorRGB getColor(@Nullable Context context) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA-256");
@@ -69,11 +75,7 @@ public class Event implements Serializable {
return null;
}
byte[] encodedHash;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
encodedHash = digest.digest(siteId.getBytes(StandardCharsets.UTF_8));
} else {
encodedHash = digest.digest(siteId.getBytes());
}
encodedHash = digest.digest(siteId.getBytes(StandardCharsets.UTF_8));
int h = (0xff & encodedHash[0]) + (0xff & encodedHash[1]) * 255;
h = h * 360 / 0xffff;
//int s = 0xff & encodedHash[2];
@@ -83,8 +85,21 @@ public class Event implements Serializable {
// range for more beautiful colors
h = h / 30 * 30;
boolean nightMode = false;
if (context != null) {
int currentNightMode = context.getResources().getConfiguration().uiMode
& Configuration.UI_MODE_NIGHT_MASK;
if (currentNightMode == Configuration.UI_MODE_NIGHT_YES) {
nightMode = true;
}
}
int s = 100;
int v = 80;
if (nightMode) {
s = 60;
v = 100;
}
return hsvToRgb(h/360.0, s/100.0, v/100.0);
}

View File

@@ -0,0 +1,138 @@
package de.sebse.fuplanner.services.kvv.types;
import androidx.annotation.NonNull;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class Gradebook implements Serializable, Iterable<Grade> {
private ArrayList<Grade> gradebook = new ArrayList<>();
private final static String[] EXAM_KEYWORDS = new String[] {"exam", "klausur", "prüfung"};
private final static String[] ASSIGNMENT_KEYWORDS = new String[] {"übung", "assignment", "blatt", "sheet", "exercise"};
public void addGrade(Grade grade) {
gradebook.add(0, grade);
}
public CategorizedGrades getAutoCategorizedGrades() {
ArrayList<Grade> exams = new ArrayList<>();
ArrayList<Grade> assignments = new ArrayList<>();
ArrayList<Grade> others = new ArrayList<>();
for (Grade grade : gradebook) {
boolean found = false;
String name = grade.getItemName().toLowerCase();
for (String keyword : EXAM_KEYWORDS) {
if (name.contains(keyword)) {
exams.add(grade);
found = true;
break;
}
}
if (found) continue;
for (String keyword : ASSIGNMENT_KEYWORDS) {
if (name.contains(keyword)) {
assignments.add(grade);
found = true;
break;
}
}
if (found) continue;
others.add(grade);
}
return new CategorizedGrades(exams, assignments, others);
}
public GradebookOutput getUncategorizedGrades() {
return new GradebookOutput(gradebook);
}
@NonNull
@Override
public Iterator<Grade> iterator() {
return gradebook.iterator();
}
public class CategorizedGrades {
private GradebookOutput exams;
private GradebookOutput assignments;
private GradebookOutput others;
private CategorizedGrades(List<Grade> exams, List<Grade> assignments, List<Grade> others) {
this.exams = new GradebookOutput(exams);
this.assignments = new GradebookOutput(assignments);
this.others = new GradebookOutput(others);
}
public GradebookOutput getExams() {
return exams;
}
public GradebookOutput getAssignments() {
return assignments;
}
public GradebookOutput getOthers() {
return others;
}
}
public class GradebookOutput {
public List<Grade> grades;
private GradebookOutput(List<Grade> grades) {
this.grades = Collections.unmodifiableList(grades);
}
public float getPercentage() {
float maxPoints = 0;
float userPoints = 0;
if (grades != null) {
for (Grade g : grades){
maxPoints += g.getMaxPoints();
userPoints += g.getPoints();
}
}
if (maxPoints == 0)
return 0;
return userPoints / maxPoints;
}
public float getMaxPointSum() {
float maxPoints = 0;
if (grades != null) {
for (Grade g : grades){
maxPoints += g.getMaxPoints();
}
}
return maxPoints;
}
public float getUserPointSum() {
float userPoints = 0;
if (grades != null) {
for (Grade g : grades){
userPoints += g.getPoints();
}
}
return userPoints;
}
public Grade getBestGrade() {
Grade bestGrade = null;
double bestValue = -1;
if (grades != null) {
for (Grade g : grades){
double perc = g.getPoints() / g.getMaxPoints();
if (perc > bestValue) {
bestValue = perc;
bestGrade = g;
}
}
}
return bestGrade;
}
}
}

View File

@@ -0,0 +1,123 @@
package de.sebse.fuplanner.services.kvv.types;
import android.os.Bundle;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Objects;
import de.sebse.fuplanner.services.fulogin.AccountGeneral;
import de.sebse.fuplanner.tools.CustomAccountManager;
public abstract class LoginToken {
private boolean isExpanded = false;
private boolean isAvailable = false;
LoginToken(@NotNull CustomAccountManager manager, @NotNull LoginTokenInterface callback, @NotNull CustomAccountManager.ExceptionInterface errorCallback) {
if (!manager.hasAccounts(AccountGeneral.ACCOUNT_TYPE)) {
callback.run(null);
return;
}
manager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD, tokenString -> {
if (tokenString == null) {
callback.run(null);
return;
}
fromString(tokenString);
callback.run(this);
}, errorCallback);
}
LoginToken() {
super();
}
LoginToken(Bundle bundle) {
super();
init(bundle);
}
protected abstract String getAccountType();
protected void init(Bundle bundle) {
isAvailable = true;
}
public void setAdditionals(Bundle bundle) {
isExpanded = true;
isAvailable = true;
}
public final boolean hasAdditionals() {
return isExpanded;
}
public void setUnavailable() {
isExpanded = false;
isAvailable = false;
}
public final void unsetAdditionals() {
isExpanded = false;
}
public final void fromString(String jsonString) {
try {
JSONObject json = new JSONObject(jsonString);
this.isAvailable = json.getBoolean("isAvailable");
this.isExpanded = json.getBoolean("isExpanded");
jsonToObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
}
@NotNull
public final String toString() {
JSONObject json = null;
try {
json = objectToJson();
json.put("isAvailable", isAvailable);
json.put("isExpanded", isExpanded);
} catch (JSONException e) {
e.printStackTrace();
}
if (json != null) {
return json.toString();
}
return "";
}
protected abstract void jsonToObject(JSONObject json) throws JSONException;
protected abstract JSONObject objectToJson() throws JSONException;
public abstract HashMap<String, String> getCookies();
public final String getCookieString() {
StringBuilder result = new StringBuilder();
HashMap<String, String> cookies = this.getCookies();
for (String header: cookies.keySet()) {
result.append(header).append("=").append(cookies.get(header)).append(";");
}
return result.substring(0, result.length()-1);
}
public final boolean isExpanded() {
return isExpanded;
}
public final boolean isAvailable() {
return isAvailable;
}
public interface LoginTokenInterface {
void run(LoginToken token);
}
public abstract boolean isOtherUser(String user);
}

View File

@@ -1,7 +1,10 @@
package de.sebse.fuplanner.services.kvv.types;
import android.os.Bundle;
import com.google.android.gms.common.internal.Objects;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;
@@ -16,62 +19,59 @@ import de.sebse.fuplanner.tools.CustomAccountManager;
* Created by sebastian on 29.10.17.
*/
public class LoginTokenBB {
private final String s_session_id;
private final String session_id;
private final String username;
private boolean isAvailable = true;
public class LoginTokenBB extends LoginToken {
private String s_session_id;
private String session_id;
private String username;
@Nullable private String id;
@Nullable private String studentId;
public LoginTokenBB(String username, String s_session_id, String session_id) {
this.username = username;
this.s_session_id = s_session_id;
this.session_id = session_id;
public LoginTokenBB() {
super();
}
public static void load(CustomAccountManager manager, LoginTokenInterface callback, CustomAccountManager.ExceptionInterface errorCallback) {
if (!manager.hasAccounts(AccountGeneral.ACCOUNT_TYPE)) {
callback.run(null);
return;
}
manager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD, tokenString -> {
if (tokenString == null) {
callback.run(null);
return;
}
callback.run(LoginTokenBB.fromJsonString(tokenString));
}, errorCallback);
public LoginTokenBB(Bundle bundle) {
super(bundle);
}
public void delete(CustomAccountManager manager) {
manager.deleteAccount(AccountGeneral.ACCOUNT_TYPE);
@Override
protected void init(Bundle bundle) {
super.init(bundle);
this.username = bundle.getString("username");
this.s_session_id = bundle.getString("s_session_id");
this.session_id = bundle.getString("session_id");
}
public void setAdditionals(String id, String studentId) {
this.id = id;
this.studentId = studentId;
this.isAvailable = true;
@Override
protected String getAccountType() {
return AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD;
}
public void setNotAvailable() {
@Override
public void setAdditionals(Bundle bundle) {
super.setAdditionals(bundle);
this.id = bundle.getString("id");
this.studentId = bundle.getString("studentId");
}
@Override
public void setUnavailable() {
super.setUnavailable();
this.id = null;
this.studentId = null;
this.isAvailable = false;
}
public boolean isAvailable() {
return isAvailable;
}
@NotNull
public String getUsername() {
return username;
}
private String getSessionId() {
@NotNull
public String getSessionId() {
return session_id;
}
@NotNull
public String getSSessionId() {
return s_session_id;
}
@@ -86,6 +86,7 @@ public class LoginTokenBB {
return studentId;
}
@Override
public HashMap<String, String> getCookies() {
HashMap<String, String> cookies = new HashMap<>();
cookies.put("session_id", getSessionId());
@@ -93,55 +94,40 @@ public class LoginTokenBB {
return cookies;
}
@Override
public boolean isOtherUser(String username) {
return !this.getUsername().equals(username);
}
@NonNull
@Override
public String toString() {
StringBuilder result = new StringBuilder();
HashMap<String, String> cookies = this.getCookies();
for (String header: cookies.keySet()) {
result.append(header).append("=").append(cookies.get(header)).append(";");
}
return result.substring(0, result.length()-1);
}
public String toJsonString() {
protected JSONObject objectToJson() throws JSONException {
JSONObject json = new JSONObject();
try {
if (isAvailable()) {
json.put("s_session_id", s_session_id);
json.put("session_id", session_id);
json.put("username", username);
}
if (isExpanded()) {
json.put("id", id);
json.put("studentId", studentId);
json.put("isAvailable", isAvailable);
} catch (JSONException e) {
return null;
}
return json.toString();
return json;
}
private static LoginTokenBB fromJsonString(String tokenString) {
try {
JSONObject json = new JSONObject(tokenString);
LoginTokenBB token = new LoginTokenBB(
json.getString("username"),
json.getString("s_session_id"),
json.getString("session_id"));
if (!json.isNull("id"))
token.setAdditionals(
json.getString("id"),
json.getString("studentId")
);
if (!json.optBoolean("isAvailable", true)) {
token.setNotAvailable();
}
return token;
} catch (JSONException e) {
e.printStackTrace();
return null;
@Override
protected void jsonToObject(JSONObject json) throws JSONException {
if (isAvailable()) {
Bundle bundle = new Bundle();
bundle.putString("username", json.getString("username"));
bundle.putString("s_session_id", json.getString("s_session_id"));
bundle.putString("session_id", json.getString("session_id"));
init(bundle);
}
if (isExpanded()) {
Bundle bundle = new Bundle();
bundle.putString("id", json.getString("id"));
bundle.putString("studentId", json.getString("studentId"));
setAdditionals(bundle);
}
}
@@ -149,8 +135,4 @@ public class LoginTokenBB {
public int hashCode() {
return Objects.hashCode(s_session_id, session_id, username, id, studentId);
}
public interface LoginTokenInterface {
void run(LoginTokenBB token);
}
}

View File

@@ -1,148 +0,0 @@
package de.sebse.fuplanner.services.kvv.types;
import com.google.android.gms.common.internal.Objects;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import de.sebse.fuplanner.services.fulogin.AccountGeneral;
import de.sebse.fuplanner.tools.CustomAccountManager;
/**
* Created by sebastian on 29.10.17.
*/
public class LoginTokenKVV {
private final String username;
private final String JSESSIONID;
private boolean isAvailable = true;
@Nullable private String fullName;
@Nullable private String email;
public LoginTokenKVV(String username, String JSESSIONID) {
this.username = username;
this.JSESSIONID = JSESSIONID;
}
public static void load(CustomAccountManager manager, LoginTokenInterface callback, CustomAccountManager.ExceptionInterface errorCallback) {
if (!manager.hasAccounts(AccountGeneral.ACCOUNT_TYPE)) {
callback.run(null);
return;
}
manager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV, tokenString -> {
if (tokenString == null) {
callback.run(null);
return;
}
callback.run(LoginTokenKVV.fromJsonString(tokenString));
}, errorCallback);
}
public void delete(CustomAccountManager manager) {
manager.deleteAccount(AccountGeneral.ACCOUNT_TYPE);
}
public void setAdditionals(String fullName, String email) {
this.fullName = fullName;
this.email = email;
this.isAvailable = true;
}
public void setNotAvailable() {
this.fullName = null;
this.email = null;
this.isAvailable = false;
}
public boolean isAvailable() {
return isAvailable;
}
public String getUsername() {
return username;
}
private String getJSESSIONID() {
return JSESSIONID;
}
@Nullable
public String getFullName() {
return fullName;
}
@Nullable
public String getEmail() {
return email;
}
public HashMap<String, String> getCookies() {
HashMap<String, String> cookies = new HashMap<>();
cookies.put("JSESSIONID", getJSESSIONID());
cookies.put("pasystem_timezone_ok", "true");
return cookies;
}
public boolean isOtherUser(String username) {
return !this.getUsername().equals(username);
}
@NonNull
@Override
public String toString() {
StringBuilder result = new StringBuilder();
HashMap<String, String> cookies = this.getCookies();
for (String header: cookies.keySet()) {
result.append(header).append("=").append(cookies.get(header)).append(";");
}
return result.substring(0, result.length()-1);
}
public String toJsonString() {
JSONObject json = new JSONObject();
try {
json.put("username", username);
json.put("JSESSIONID", JSESSIONID);
json.put("fullName", fullName);
json.put("email", email);
json.put("isAvailable", isAvailable);
} catch (JSONException e) {
return null;
}
return json.toString();
}
private static LoginTokenKVV fromJsonString(String tokenString) {
try {
JSONObject json = new JSONObject(tokenString);
LoginTokenKVV token = new LoginTokenKVV(
json.getString("username"),
json.getString("JSESSIONID"));
if (!json.isNull("fullName"))
token.setAdditionals(
json.getString("fullName"),
json.getString("email")
);
if (!json.optBoolean("isAvailable", true)) {
token.setNotAvailable();
}
return token;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
@Override
public int hashCode() {
return Objects.hashCode(username, JSESSIONID, fullName, email);
}
public interface LoginTokenInterface {
void run(LoginTokenKVV token);
}
}

View File

@@ -0,0 +1,126 @@
package de.sebse.fuplanner.services.kvv.types;
import android.os.Bundle;
import com.google.android.gms.common.internal.Objects;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import de.sebse.fuplanner.services.fulogin.AccountGeneral;
import de.sebse.fuplanner.tools.CustomAccountManager;
/**
* Created by sebastian on 29.10.17.
*/
public class LoginTokenWB extends LoginToken {
private String username;
private String JSESSIONID;
@Nullable private String fullName;
@Nullable private String email;
public LoginTokenWB() {
super();
}
public LoginTokenWB(Bundle bundle) {
super(bundle);
}
@Override
protected void init(Bundle bundle) {
super.init(bundle);
this.username = bundle.getString("username");
this.JSESSIONID = bundle.getString("JSESSIONID");
}
@Override
protected String getAccountType() {
return AccountGeneral.AUTHTOKEN_TYPE_WB;
}
@Override
public void setAdditionals(Bundle bundle) {
super.setAdditionals(bundle);
this.fullName = bundle.getString("fullName");
this.email = bundle.getString("email");
}
@Override
public void setUnavailable() {
super.setUnavailable();
this.fullName = null;
this.email = null;
}
public String getUsername() {
return username;
}
private String getJSESSIONID() {
return JSESSIONID;
}
@Nullable
public String getFullName() {
return fullName;
}
@Nullable
public String getEmail() {
return email;
}
@Override
public HashMap<String, String> getCookies() {
HashMap<String, String> cookies = new HashMap<>();
cookies.put("JSESSIONID", getJSESSIONID());
cookies.put("pasystem_timezone_ok", "true");
return cookies;
}
@Override
public boolean isOtherUser(String username) {
return !this.getUsername().equals(username);
}
@Override
protected JSONObject objectToJson() throws JSONException {
JSONObject json = new JSONObject();
if (isAvailable()) {
json.put("username", username);
json.put("JSESSIONID", JSESSIONID);
}
if (isExpanded()) {
json.put("fullName", fullName);
json.put("email", email);
}
return json;
}
@Override
protected void jsonToObject(JSONObject json) throws JSONException {
if (isAvailable()) {
Bundle bundle = new Bundle();
bundle.putString("username", json.getString("username"));
bundle.putString("JSESSIONID", json.getString("JSESSIONID"));
init(bundle);
}
if (isExpanded()) {
Bundle bundle = new Bundle();
bundle.putString("fullName", json.getString("fullName"));
bundle.putString("email", json.getString("email"));
setAdditionals(bundle);
}
}
@Override
public int hashCode() {
return Objects.hashCode(username, JSESSIONID, fullName, email);
}
}

View File

@@ -174,28 +174,14 @@ public class Modules implements Iterable<Modules.Module>, Serializable {
@Nullable public final String type;
@Nullable public final String description;
@NotNull private final String ID;
@NotNull private final int moduleType;
private final int moduleType;
@Nullable public ArrayList<Announcement> announcements;
@Nullable public AssignmentList assignments;
@Nullable public EventList events;
@Nullable public ArrayList<Grade> gradebook;
@Nullable public Gradebook gradebook;
@Nullable public ArrayList<Resource> resources;
public float getGradebookPercent(){
float maxPoint = 0;
float userPoint = 0;
if (gradebook != null) {
for (Grade g : gradebook){
maxPoint += g.getMaxPoints();
userPoint += g.getPoints();
}
}
if (maxPoint == 0)
return 0;
return userPoint/maxPoint;
}
private Module(@Nullable Semester semester, @NotNull HashSet<String> lvNumber, @NotNull String title, @NotNull LinkedHashSet<Lecturer> lecturer, @Nullable String type, @Nullable String description, @NotNull String ID, @NotNull int moduleType) {
private Module(@Nullable Semester semester, @NotNull HashSet<String> lvNumber, @NotNull String title, @NotNull LinkedHashSet<Lecturer> lecturer, @Nullable String type, @Nullable String description, @NotNull String ID, int moduleType) {
title = title.replaceAll("(.*?) (S[0-9]{2}|W[0-9/]{5})", "$1");
@@ -238,6 +224,7 @@ public class Modules implements Iterable<Modules.Module>, Serializable {
return moduleType;
}
@NonNull
public Module clone() {
return new Module(semester, lvNumber, title, new LinkedHashSet<>(lecturer), type, description, ID, moduleType);
}

View File

@@ -2,6 +2,7 @@ package de.sebse.fuplanner.services.kvv.types;
import java.io.Serializable;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import de.sebse.fuplanner.tools.Regex;
@@ -52,4 +53,10 @@ public class Semester implements Serializable {
}
return false;
}
@NonNull
@Override
public String toString() {
return (type == SEM_SS ? "SS" : "WS") + year;
}
}

View File

@@ -2,15 +2,16 @@ package de.sebse.fuplanner.services.kvv.ui;
import android.Manifest;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import androidx.annotation.Nullable;
@@ -48,8 +49,14 @@ public class Download {
if (context == null)
return;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
File f = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS)+"/"+folderName+"/"+file.getTitle());
File f;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
f = new File(context.getExternalFilesDir(
Environment.DIRECTORY_DOWNLOADS) + "/" + folderName + "/" + file.getTitle());
} else {
f = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS) + "/" + folderName + "/" + file.getTitle());
}
Resources resources = context.getResources();
String message = "";
if (file.getAuthor() != null && !file.getAuthor().isEmpty())
@@ -148,11 +155,6 @@ public class Download {
showDownloadError();
return;
}
ArrayList<Integer> intList = new ArrayList<>();
for (int i : grantResults)
{
intList.add(i);
}
int pos = Arrays.asList(permissions).indexOf("android.permission.WRITE_EXTERNAL_STORAGE");
if (pos != -1) {
if (grantResults[pos] != -1) {
@@ -194,11 +196,7 @@ public class Download {
Uri uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".my.provider", url);
Intent intent;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
intent = new Intent(Intent.ACTION_VIEW);
} else {
intent = new Intent();
}
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// Check what kind of file you are trying to open, by comparing the url with extensions.
@@ -246,7 +244,12 @@ public class Download {
intent.setDataAndType(uri, "*/*");
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
log.e("No matching activity found!");
e.printStackTrace();
}
}

View File

@@ -8,6 +8,7 @@ import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import de.sebse.fuplanner.R;
@@ -15,6 +16,7 @@ import de.sebse.fuplanner.tools.UtilsDate;
import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkError;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
import de.sebse.fuplanner.tools.types.News;
import de.sebse.fuplanner.tools.types.NewsList;
public class NewsManager {
@@ -51,21 +53,28 @@ public class NewsManager {
for (int i = news.length() - 1; i >= 0; i--) {
try {
String title = news.getJSONObject(i).optString("title_" + language, null);
if (title == null)
String title;
if (news.getJSONObject(i).has("title_" + language)) {
title = news.getJSONObject(i).getString("title_" + language);
} else {
title = news.getJSONObject(i).getString("title");
}
String text;
if (news.getJSONObject(i).has("text_" + language)) {
text = news.getJSONObject(i).getString("text_" + language);
} else {
text = news.getJSONObject(i).getString("text");
}
String categoryString = news.getJSONObject(i).getString("category");
int category;
if (categoryString.equals("CATEGORY_TRICKS"))
category = de.sebse.fuplanner.tools.types.News.CATEGORY_TRICKS;
category = News.CATEGORY_TRICKS;
else
category = de.sebse.fuplanner.tools.types.News.CATEGORY_UPDATE;
category = News.CATEGORY_UPDATE;
String dateString = news.getJSONObject(i).getString("date");
long date = UtilsDate.stringToMillis(dateString, "dd.MM.yyyy");
String text = news.getJSONObject(i).optString("text_" + language, null);
if (text == null)
text = news.getJSONObject(i).getString("text");
de.sebse.fuplanner.tools.types.News event = new de.sebse.fuplanner.tools.types.News(title, category, date, text);
News event = new News(title, category, date, text);
dates.add(event);
} catch (JSONException e) {
e.printStackTrace();
@@ -82,7 +91,7 @@ public class NewsManager {
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer, "UTF-8");
return new String(buffer, StandardCharsets.UTF_8);
} catch (IOException ex) {
ex.printStackTrace();
return null;

View File

@@ -34,11 +34,7 @@ public class CustomAccountManager {
try {
String token = mAccountManager.blockingGetAuthToken(account, authTokenType, true);
mAccountManager.invalidateAuthToken(accountType, token);
} catch (AuthenticatorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (OperationCanceledException e) {
} catch (AuthenticatorException | OperationCanceledException | IOException e) {
e.printStackTrace();
}
}
@@ -53,11 +49,7 @@ public class CustomAccountManager {
if (callback != null)
callback.run(true);
return;
} catch (AuthenticatorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (OperationCanceledException e) {
} catch (AuthenticatorException | OperationCanceledException | IOException e) {
e.printStackTrace();
}
if (callback != null)
@@ -102,11 +94,7 @@ public class CustomAccountManager {
Account account = mAccountManager.getAccountsByType(accountType)[0];
try {
return mAccountManager.blockingGetAuthToken(account, authTokenType, true);
} catch (AuthenticatorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (OperationCanceledException e) {
} catch (AuthenticatorException | OperationCanceledException | IOException e) {
e.printStackTrace();
}
return null;

View File

@@ -4,8 +4,6 @@ import androidx.annotation.StringRes;
import de.sebse.fuplanner.MainActivity;
import de.sebse.fuplanner.services.canteen.CanteenBrowser;
import de.sebse.fuplanner.services.kvv.KVV;
import de.sebse.fuplanner.services.kvv.KVVListener;
import de.sebse.fuplanner.services.news.NewsManager;
public interface MainActivityListener {
@@ -26,4 +24,6 @@ public interface MainActivityListener {
void addRequestPermissionsResultListener(RequestPermissionsResultListener listener, String id);
void removeRequestPermissionsResultListener(String id);
void forceSync();
}

View File

@@ -2,7 +2,6 @@ package de.sebse.fuplanner.tools;
import java.util.LinkedList;
import de.sebse.fuplanner.tools.logging.Logger;
import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;

View File

@@ -1,6 +1,7 @@
package de.sebse.fuplanner.tools;
import android.content.Context;
import android.content.SharedPreferences;
import androidx.annotation.ArrayRes;
import androidx.annotation.StringRes;
@@ -39,4 +40,37 @@ public class Preferences {
String string = context.getResources().getString(key);
PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(string, value).apply();
}
public static int[] getArrayInt(Context context, @StringRes int key) {
String string = context.getResources().getString(key);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
if (!prefs.contains(string + "_size")) {
return null;
}
int size = prefs.getInt(string + "_size", 0);
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = prefs.getInt(string + "_" + i, 0);
return array;
}
public static void setArrayInt(Context context, @StringRes int key, int[] value) {
String string = context.getResources().getString(key);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
int oldSize = prefs.getInt(string + "_size", 0);
int newSize = 0;
if (value == null) {
editor.remove(string + "_size");
} else {
newSize = value.length;
editor.putInt(string +"_size", newSize);
}
for (int i = 0; i < newSize; i++)
editor.putInt(string + "_" + i, value[i]);
for (int i = newSize; i < oldSize; i++)
editor.remove(string + "_" + i);
editor.apply();
}
}

View File

@@ -49,11 +49,7 @@ public class UtilsDate {
skeleton = skeleton.replaceAll("h", "H");
if (context != null && !DateFormat.is24HourFormat(context))
skeleton = skeleton.replaceAll("H", "h");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
dateFormat = new SimpleDateFormat(getDateFormat(locale, skeleton));
} else {
dateFormat = new SimpleDateFormat(skeleton, locale);
}
dateFormat = new SimpleDateFormat(getDateFormat(locale, skeleton));
return dateFormat.format(new Date(modified));
}

View File

@@ -1,7 +1,6 @@
package de.sebse.fuplanner.tools.network;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
@@ -17,10 +16,9 @@ import com.android.volley.toolbox.Volley;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import androidx.annotation.Nullable;
import de.sebse.fuplanner.tools.EventListener;
@@ -147,11 +145,7 @@ public class HTTPNetwork extends Service {
}
}
String requestBody = sb.toString();
try {
return requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
return null;
}
return requestBody.getBytes(StandardCharsets.UTF_8);
}
@Override

View File

@@ -31,6 +31,6 @@ public class NetworkError {
@NonNull
public String toString() {
return String.valueOf(getCode()) + " - " + getHttpStatus() + " - " + getMessage();
return getCode() + " - " + getHttpStatus() + " - " + getMessage();
}
}

View File

@@ -1,5 +1,7 @@
package de.sebse.fuplanner.tools.types;
import androidx.annotation.NonNull;
public class News {
public static final int CATEGORY_TRICKS = 0;
public static final int CATEGORY_UPDATE = 1;
@@ -32,6 +34,7 @@ public class News {
return text;
}
@NonNull
@Override
public String toString() {
return "News{" +

View File

@@ -0,0 +1,15 @@
package de.sebse.fuplanner.tools.ui;
import android.view.View;
import android.widget.ImageView;
import de.sebse.fuplanner.R;
public class CanteensViewHolder extends ItemViewHolder {
public final ImageView mActionIcon;
public CanteensViewHolder(View view) {
super(view);
mActionIcon = view.findViewById(R.id.remove_icon);
}
}

View File

@@ -0,0 +1,84 @@
package de.sebse.fuplanner.tools.ui;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import androidx.appcompat.widget.AppCompatTextView;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.tools.logging.Logger;
public class TextViewDrawableSize extends AppCompatTextView {
private int mDrawableWidth;
private int mDrawableHeight;
public TextViewDrawableSize(Context context) {
super(context);
init(context, null, 0);
}
public TextViewDrawableSize(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public TextViewDrawableSize(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
private void init(Context context, AttributeSet attrs, int defStyleAttr) {
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.TextViewDrawableSize, defStyleAttr, 0);
try {
mDrawableWidth = array.getDimensionPixelSize(R.styleable.TextViewDrawableSize_compoundDrawableWidth, -1);
mDrawableHeight = array.getDimensionPixelSize(R.styleable.TextViewDrawableSize_compoundDrawableHeight, -1);
} finally {
array.recycle();
}
if (mDrawableWidth > 0 || mDrawableHeight > 0) {
initCompoundDrawableSize();
}
}
private void initCompoundDrawableSize() {
Drawable[] drawables = getCompoundDrawablesRelative();
for (Drawable drawable : drawables) {
if (drawable == null) {
continue;
}
Rect realBounds = drawable.getBounds();
float scaleFactor = realBounds.height() / (float) realBounds.width();
float drawableWidth = realBounds.width();
float drawableHeight = realBounds.height();
if (mDrawableWidth > 0) {
// save scale factor of image
if (drawableWidth > mDrawableWidth) {
drawableWidth = mDrawableWidth;
drawableHeight = drawableWidth * scaleFactor;
}
}
if (mDrawableHeight > 0) {
// save scale factor of image
if (drawableHeight > mDrawableHeight) {
drawableHeight = mDrawableHeight;
drawableWidth = drawableHeight / scaleFactor;
}
}
realBounds.right = realBounds.left + Math.round(drawableWidth);
realBounds.bottom = realBounds.top + Math.round(drawableHeight);
drawable.setBounds(realBounds);
}
setCompoundDrawablesRelative(drawables[0], drawables[1], drawables[2], drawables[3]);
}
}

View File

@@ -50,7 +50,7 @@ public class ExpandableCardView extends CardView {
private View outerView;
private ImageButton imageButton;
private static final int DEFAULT_ANIM_DURATION = 350;
private static final int DEFAULT_ANIM_DURATION = 300;
private long animDuration = DEFAULT_ANIM_DURATION;
private final static int COLLAPSING = 0;
@@ -103,11 +103,9 @@ public class ExpandableCardView extends CardView {
(int) UtilsUi.convertDpToPixels(getContext(), 10),
(int) UtilsUi.convertDpToPixels(getContext(), 10)
);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
imageButton.setBackgroundResource(outValue.resourceId);
}
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
imageButton.setBackgroundResource(outValue.resourceId);
isExpanded = startExpanded;
}
@@ -262,8 +260,29 @@ public class ExpandableCardView extends CardView {
new RotateAnimation(180,0,Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
arrowAnimation.setFillAfter(true);
arrowAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
imageButton.setRotationX(0);
imageButton.setRotationY(0);
}
@Override
public void onAnimationEnd(Animation animation) {
if (isExpanded) {
imageButton.setRotationX(180);
imageButton.setRotationY(180);
} else {
imageButton.setRotationX(0);
imageButton.setRotationY(0);
}
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
arrowAnimation.setDuration(animDuration);
expandAnimation.setDuration(animDuration);

View File

@@ -140,7 +140,8 @@ public class TreeNode<T extends LayoutItemType> implements Cloneable {
}
@SuppressWarnings({"CloneDoesntDeclareCloneNotSupportedException", "MethodDoesntCallSuperMethod"})
@NonNull
@SuppressWarnings({"CloneDoesntDeclareCloneNotSupportedException"})
@Override
protected TreeNode<T> clone() {
TreeNode<T> clone = new TreeNode<>(this.content);

View File

@@ -309,7 +309,7 @@ public class WeekView extends View {
mDoubleTapListener.onDoubleTapListener((Calendar) selectedTime.clone());
}
if (mDoubleTapLeftRightListener != null)
mDoubleTapLeftRightListener.onDoubleTapLeftRightListener(getWidth()/2 < e.getX());
mDoubleTapLeftRightListener.onDoubleTapLeftRightListener(getWidth() / 2.0 < e.getX());
return super.onDoubleTap(e);
}

View File

@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/colorFUBlue" android:state_checked="true" />
<item android:color="@color/colorFUBlack" android:state_checked="false"/>
<item android:color="@color/fuAccent" android:state_checked="true" />
<item android:color="@color/fuHeaderText1" android:state_checked="false"/>
</selector>

View File

@@ -0,0 +1,5 @@
<vector android:height="24dp" android:tint="@color/fuAccent"
android:viewportHeight="24.0" android:viewportWidth="24.0"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#FF000000" android:pathData="M13,7h-2v4L7,11v2h4v4h2v-4h4v-2h-4L13,7zM12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM12,20c-4.41,0 -8,-3.59 -8,-8s3.59,-8 8,-8 8,3.59 8,8 -3.59,8 -8,8z"/>
</vector>

View File

@@ -1,4 +1,4 @@
<vector android:height="24dp" android:tint="#003366"
<vector android:height="24dp" android:tint="@color/fuAccent"
android:viewportHeight="24.0" android:viewportWidth="24.0"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#FF000000" android:pathData="M10,4H4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2V8c0,-1.1 -0.9,-2 -2,-2h-8l-2,-2z"/>

View File

@@ -1,4 +1,4 @@
<vector android:height="24dp" android:tint="#003366"
<vector android:height="24dp" android:tint="@color/fuAccent"
android:viewportHeight="24.0" android:viewportWidth="24.0"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#FF000000" android:pathData="M6,2c-1.1,0 -1.99,0.9 -1.99,2L4,20c0,1.1 0.89,2 1.99,2L18,22c1.1,0 2,-0.9 2,-2L20,8l-6,-6L6,2zM13,9L13,3.5L18.5,9L13,9z"/>

View File

@@ -1,4 +1,5 @@
<vector android:height="18dp" android:viewportHeight="24.0"
android:viewportWidth="24.0" android:width="18dp" xmlns:android="http://schemas.android.com/apk/res/android">
android:viewportWidth="24.0" android:width="18dp" xmlns:android="http://schemas.android.com/apk/res/android"
android:tint="@color/fuIcon">
<path android:fillColor="#FF000000" android:pathData="M8.59,16.34l4.58,-4.59 -4.58,-4.59L10,5.75l6,6 -6,6z"/>
</vector>

View File

@@ -2,8 +2,9 @@
android:width="40dp"
android:height="40dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
android:viewportHeight="24.0"
android:tint="@color/fuAccent">
<path
android:fillColor="#003366"
android:fillColor="#FF000000"
android:pathData="M20,4L4,4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2L22,6c0,-1.1 -0.9,-2 -2,-2zM20,8l-8,5 -8,-5L4,6l8,5 8,-5v2z"/>
</vector>

View File

@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FF000000"
android:pathData="M20,2L4,2c-1.1,0 -1.99,0.9 -1.99,2L2,22l4,-4h14c1.1,0 2,-0.9 2,-2L22,4c0,-1.1 -0.9,-2 -2,-2zM6,14v-2.47l6.88,-6.88c0.2,-0.2 0.51,-0.2 0.71,0l1.77,1.77c0.2,0.2 0.2,0.51 0,0.71L8.47,14L6,14zM18,14h-7.5l2,-2L18,12v2z"/>
</vector>

View File

@@ -0,0 +1,5 @@
<vector android:height="24dp" android:tint="@color/fuIconWarn"
android:viewportHeight="24.0" android:viewportWidth="24.0"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#FF000000" android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM17,13L7,13v-2h10v2z"/>
</vector>

View File

@@ -0,0 +1,5 @@
<vector android:height="24dp" android:tint="@color/fuIconWarn"
android:viewportHeight="24.0" android:viewportWidth="24.0"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#FF000000" android:pathData="M7,11v2h10v-2L7,11zM12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM12,20c-4.41,0 -8,-3.59 -8,-8s3.59,-8 8,-8 8,3.59 8,8 -3.59,8 -8,8z"/>
</vector>

View File

@@ -1,9 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0">
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FF000000"
android:pathData="M18,16.08c-0.76,0 -1.44,0.3 -1.96,0.77L8.91,12.7c0.05,-0.23 0.09,-0.46 0.09,-0.7s-0.04,-0.47 -0.09,-0.7l7.05,-4.11c0.54,0.5 1.25,0.81 2.04,0.81 1.66,0 3,-1.34 3,-3s-1.34,-3 -3,-3 -3,1.34 -3,3c0,0.24 0.04,0.47 0.09,0.7L8.04,9.81C7.5,9.31 6.79,9 6,9c-1.66,0 -3,1.34 -3,3s1.34,3 3,3c0.79,0 1.5,-0.31 2.04,-0.81l7.12,4.16c-0.05,0.21 -0.08,0.43 -0.08,0.65 0,1.61 1.31,2.92 2.92,2.92 1.61,0 2.92,-1.31 2.92,-2.92s-1.31,-2.92 -2.92,-2.92z" />
android:pathData="M18,16.08c-0.76,0 -1.44,0.3 -1.96,0.77L8.91,12.7c0.05,-0.23 0.09,-0.46 0.09,-0.7s-0.04,-0.47 -0.09,-0.7l7.05,-4.11c0.54,0.5 1.25,0.81 2.04,0.81 1.66,0 3,-1.34 3,-3s-1.34,-3 -3,-3 -3,1.34 -3,3c0,0.24 0.04,0.47 0.09,0.7L8.04,9.81C7.5,9.31 6.79,9 6,9c-1.66,0 -3,1.34 -3,3s1.34,3 3,3c0.79,0 1.5,-0.31 2.04,-0.81l7.12,4.16c-0.05,0.21 -0.08,0.43 -0.08,0.65 0,1.61 1.31,2.92 2.92,2.92 1.61,0 2.92,-1.31 2.92,-2.92s-1.31,-2.92 -2.92,-2.92z"/>
</vector>

View File

@@ -3,10 +3,10 @@
android:shape="rectangle">
<stroke
android:width="4dp"
android:color="@color/colorFUBlue" />
android:color="@color/fuAccent" />
<solid
android:color="@color/colorFUBlue"
android:color="@color/fuAccent"
/>
<corners android:radius="360dp" />

View File

@@ -2,7 +2,7 @@
android:shape="rectangle">
<gradient
android:angle="135"
android:endColor="@color/colorFUGreenDark"
android:startColor="@color/colorFUGreen"
android:endColor="@color/fuSecondary"
android:startColor="@color/fuPrimary"
android:type="linear" />
</shape>

View File

@@ -17,8 +17,8 @@
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:itemTextColor="@color/menu_text_color"
app:itemIconTint="@color/menu_text_color"
app:itemTextColor="@color/fuHeaderText2"
app:itemIconTint="@color/fuHeaderText2"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />

View File

@@ -46,7 +46,7 @@
android:layout_height="wrap_content"
android:id="@+id/error_textview"
android:textAppearance="@style/TextAppearance.Design.Error"
android:textColor="@color/colorFURed"
android:textColor="@color/fuIconWarn"
tools:text="@string/hello_blank_fragment" />
<!-- Email Label -->

View File

@@ -20,8 +20,8 @@
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:itemTextColor="@color/menu_text_color"
app:itemIconTint="@color/menu_text_color"
app:itemTextColor="@color/fuHeaderText2"
app:itemIconTint="@color/fuHeaderText2"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />

View File

@@ -9,21 +9,22 @@
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
android:theme="@style/FUTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorFUGreen"
app:popupTheme="@style/AppTheme.PopupOverlay" />
android:background="@color/fuToolbarBackground"
app:popupTheme="@style/FUTheme.PopupOverlay"
android:theme="@style/FUTheme.Toolbar" />
<TextView
android:id="@+id/no_connection_msg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorFUOrange"
android:textColor="@color/colorFUWhite"
android:textColor="@color/colorFUBlack"
android:gravity="center"
android:textStyle="bold"
android:visibility="gone"

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