Compare commits
3 Commits
master
...
6325f312ea
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6325f312ea | ||
|
|
e0ed23dec5 | ||
|
|
bb85911324 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,3 +1,4 @@
|
||||
*.iml
|
||||
.gradle
|
||||
/local.properties
|
||||
/.idea/*
|
||||
|
||||
141
app/app.iml
141
app/app.iml
@@ -1,141 +0,0 @@
|
||||
<?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>
|
||||
@@ -1,14 +1,14 @@
|
||||
apply plugin: 'com.android.application'
|
||||
|
||||
android {
|
||||
compileSdkVersion 29
|
||||
compileSdkVersion 28
|
||||
buildToolsVersion '28.0.3'
|
||||
defaultConfig {
|
||||
applicationId "de.sebse.fuplanner"
|
||||
minSdkVersion 21
|
||||
targetSdkVersion 29
|
||||
versionCode 43
|
||||
versionName "1.6.4"
|
||||
minSdkVersion 15
|
||||
targetSdkVersion 28
|
||||
versionCode 16
|
||||
versionName "1.3.5"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
buildTypes {
|
||||
@@ -27,16 +27,28 @@ android {
|
||||
|
||||
|
||||
dependencies {
|
||||
implementation fileTree(include: ['*.jar'], dir: 'libs')
|
||||
implementation 'androidx.recyclerview:recyclerview:1.0.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 fileTree(include: ['*.jar'], dir: 'libs')
|
||||
androidTestImplementation('androidx.test.espresso:espresso-core:3.1.0-beta02', {
|
||||
exclude group: 'com.android.support', module: 'support-annotations'
|
||||
})
|
||||
implementation 'androidx.preference:preference:1.0.0'
|
||||
implementation 'com.google.android.material:material:1.0.0'
|
||||
implementation 'com.google.android.gms:play-services-base:17.1.0'
|
||||
implementation 'com.ms-square:expandableTextView:0.1.4'
|
||||
implementation 'androidx.constraintlayout:constraintlayout:2.0.0-alpha2'
|
||||
implementation 'com.android.volley:volley:1.1.0'
|
||||
//noinspection GradleDependency
|
||||
implementation 'com.google.android.gms:play-services-auth:15.0.0'
|
||||
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
|
||||
testImplementation 'junit:junit:4.12'
|
||||
implementation fileTree(include: ['*.jar'], dir: 'libs')
|
||||
implementation 'androidx.appcompat:appcompat:1.0.2'
|
||||
implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
|
||||
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
|
||||
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
|
||||
//implementation 'com.github.quivr:android-week-view:2.0.2'//com.github.alamkanak:android-week-view:1.2.6
|
||||
implementation 'com.ms-square:expandableTextView:0.1.4'
|
||||
// https://github.com/bignerdranch/expandable-recycler-view
|
||||
implementation 'com.bignerdranch.android:expandablerecyclerview:3.0.0-RC1'
|
||||
implementation 'com.github.Cutta:TagView:1.3'
|
||||
implementation files('libs/jericho-html-3.4.jar')
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package de.sebse.fuplanner;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import androidx.test.InstrumentationRegistry;
|
||||
import androidx.test.runner.AndroidJUnit4;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
* Instrumentation test, which will execute on an Android device.
|
||||
*
|
||||
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
|
||||
*/
|
||||
@RunWith(AndroidJUnit4.class)
|
||||
public class ExampleInstrumentedTest {
|
||||
@Test
|
||||
public void useAppContext() throws Exception {
|
||||
// Context of the app under test.
|
||||
Context appContext = InstrumentationRegistry.getTargetContext();
|
||||
|
||||
assertEquals("de.sebse.fuplanner", appContext.getPackageName());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
<?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
|
||||
@@ -19,13 +18,11 @@
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
|
||||
<!-- To auto-complete the email text field in the login form with the user's emails -->
|
||||
<uses-permission android:name="android.permission.READ_PROFILE" />
|
||||
<uses-permission android:name="android.permission.READ_CONTACTS" />
|
||||
<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"
|
||||
@@ -36,9 +33,7 @@
|
||||
android:theme="@style/FUTheme">
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:label="@string/app_name"
|
||||
android:clearTaskOnLaunch="true"
|
||||
android:launchMode="singleTop">
|
||||
android:label="@string/app_name">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
@@ -63,12 +58,11 @@
|
||||
android:syncable="true">
|
||||
|
||||
</provider>
|
||||
|
||||
<activity
|
||||
android:name=".services.fulogin.FUAuthenticatorActivity"
|
||||
android:label="@string/title_activity_fuauthenticator" />
|
||||
<service
|
||||
android:name=".services.fulogin.FUAuthenticatorService"
|
||||
android:permission="de.sebse.fuplanner.Account">
|
||||
<service android:name=".services.fulogin.FUAuthenticatorService">
|
||||
<intent-filter>
|
||||
<action android:name="android.accounts.AccountAuthenticator" />
|
||||
</intent-filter>
|
||||
@@ -86,20 +80,6 @@
|
||||
android:name="android.content.SyncAdapter"
|
||||
android:resource="@xml/syncadapter_kvv" />
|
||||
</service>
|
||||
<service
|
||||
android:name=".services.kvv.KVV"
|
||||
android:exported="false">
|
||||
<intent-filter>
|
||||
<action android:name="android.app.Service" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
<service
|
||||
android:name=".tools.network.HTTPNetwork"
|
||||
android:exported="false">
|
||||
<intent-filter>
|
||||
<action android:name="android.app.Service" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
|
||||
|
||||
</application>
|
||||
|
||||
@@ -1,17 +1,8 @@
|
||||
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;
|
||||
import android.view.Menu;
|
||||
import android.view.MenuItem;
|
||||
import android.view.View;
|
||||
@@ -23,16 +14,12 @@ import com.google.android.material.navigation.NavigationView;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
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;
|
||||
import androidx.appcompat.widget.Toolbar;
|
||||
@@ -47,23 +34,18 @@ 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;
|
||||
import de.sebse.fuplanner.services.canteen.types.Canteen;
|
||||
import de.sebse.fuplanner.services.canteen.types.CanteenListener;
|
||||
import de.sebse.fuplanner.services.fulogin.AccountGeneral;
|
||||
import de.sebse.fuplanner.services.kvv.KVV;
|
||||
import de.sebse.fuplanner.services.kvv.KVVListener;
|
||||
import de.sebse.fuplanner.services.kvv.Login;
|
||||
import de.sebse.fuplanner.services.kvv.sync.KVVContentProvider;
|
||||
import de.sebse.fuplanner.services.kvv.types.LoginTokenBB;
|
||||
import de.sebse.fuplanner.services.kvv.types.LoginTokenKVV;
|
||||
import de.sebse.fuplanner.services.kvv.types.LoginToken;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
import de.sebse.fuplanner.services.news.NewsManager;
|
||||
import de.sebse.fuplanner.services.fulogin.AccountGeneral;
|
||||
import de.sebse.fuplanner.tools.CustomAccountManager;
|
||||
import de.sebse.fuplanner.tools.CustomNotificationManager;
|
||||
import de.sebse.fuplanner.tools.MainActivityListener;
|
||||
import de.sebse.fuplanner.tools.NewAsyncQueue;
|
||||
import de.sebse.fuplanner.tools.Preferences;
|
||||
@@ -78,59 +60,27 @@ public class MainActivity extends AppCompatActivity
|
||||
ModulesFragment.OnModulesFragmentInteractionListener,
|
||||
CanteensFragment.OnCanteensFragmentInteractionListener {
|
||||
|
||||
public static final int FRAGMENT_NONE = -1;
|
||||
public static final int FRAGMENT_STARTUP = 0;
|
||||
public static final int FRAGMENT_MODULES = 1;
|
||||
public static final int FRAGMENT_MODULES_DETAILS = 2;
|
||||
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;
|
||||
private static final int FRAGMENT_NONE = -1;
|
||||
private static final int FRAGMENT_STARTUP = 0;
|
||||
private static final int FRAGMENT_MODULES = 1;
|
||||
private static final int FRAGMENT_MODULES_DETAILS = 2;
|
||||
private static final int FRAGMENT_SCHEDULE = 4;
|
||||
private static final int FRAGMENT_CANTEENS = 5;
|
||||
private static final int FRAGMENT_CANTEENS_DETAILS = 6;
|
||||
private static final int FRAGMENT_PREFERENCES = 7;
|
||||
private static final int FRAGMENT_NEWS = 8;
|
||||
|
||||
private static final String ARG_FRAGMENT_PAGE = "fragment_page";
|
||||
private static final String ARG_FRAGMENT_STATUS = "fragment_status";
|
||||
private static final int DOUBLE_CLICK_TO_EXIT_MILLIS = 2000;
|
||||
|
||||
private FragmentManager mFragmentManager;
|
||||
private KVV mKVV;
|
||||
private NewsManager mNewsManager;
|
||||
private CanteenBrowser mCanteenBrowser;
|
||||
private final Logger log = new Logger(this);
|
||||
private NavigationView mNavigationView;
|
||||
|
||||
private boolean mAlreadyCreated = false;
|
||||
|
||||
// KVV service
|
||||
private ArrayList<KVVCallback> mCallbacks = new ArrayList<>();
|
||||
@Nullable private KVV mKVV;
|
||||
boolean mBound = false;
|
||||
/** Defines callbacks for service binding, passed to bindService() */
|
||||
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();
|
||||
mKVV.addListener("mainactivity", MainActivity.this);
|
||||
for (KVVCallback callback : mCallbacks) {
|
||||
callback.get(mKVV);
|
||||
}
|
||||
mBound = true;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onServiceDisconnected(ComponentName arg0) {
|
||||
mKVV.removeListener("mainactivity");
|
||||
mBound = false;
|
||||
mKVV = null;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
private int mFragmentPage = FRAGMENT_NONE;
|
||||
@NotNull
|
||||
private String mFragmentData = "";
|
||||
@@ -140,24 +90,14 @@ public class MainActivity extends AppCompatActivity
|
||||
private CustomAccountManager mAccountManager;
|
||||
private boolean isPaused = false;
|
||||
private boolean isLoggedInBeforePause = false;
|
||||
private boolean isDrawerFixed = false;
|
||||
private Function<Modules, Void> mMolduleListUpdateFunction;
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
mAccountManager = new CustomAccountManager(AccountManager.get(this), () -> MainActivity.this);
|
||||
isDrawerFixed = getResources().getBoolean(R.bool.isDrawerFixed);
|
||||
int desiredPage = getDefaultFragmentAfterLogin();
|
||||
String desiredData = "";
|
||||
Intent intent = getIntent();
|
||||
if (intent != null && CustomNotificationManager.NOTIFICATION_TYPE_NAVIGATE.equals(intent.getStringExtra(CustomNotificationManager.NOTIFICATION_INTENT))) {
|
||||
int page = intent.getIntExtra(CustomNotificationManager.NOTIFICATION_PAGE, 0);
|
||||
if (page == FRAGMENT_STARTUP || page == FRAGMENT_NONE)
|
||||
page = getDefaultFragmentAfterLogin();
|
||||
desiredPage = page;
|
||||
desiredData = intent.getStringExtra(CustomNotificationManager.NOTIFICATION_DATA);
|
||||
} else if (savedInstanceState != null) {
|
||||
if (savedInstanceState != null) {
|
||||
desiredPage = savedInstanceState.getInt(ARG_FRAGMENT_PAGE, desiredPage);
|
||||
desiredData = savedInstanceState.getString(ARG_FRAGMENT_STATUS, desiredData);
|
||||
}
|
||||
@@ -166,20 +106,11 @@ public class MainActivity extends AppCompatActivity
|
||||
Toolbar toolbar = findViewById(R.id.toolbar);
|
||||
setSupportActionBar(toolbar);
|
||||
|
||||
if (!isDrawerFixed) {
|
||||
DrawerLayout drawer = findViewById(R.id.drawer_layout);
|
||||
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
|
||||
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
|
||||
drawer.addDrawerListener(toggle);
|
||||
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;
|
||||
}
|
||||
DrawerLayout drawer = findViewById(R.id.drawer_layout);
|
||||
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
|
||||
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
|
||||
drawer.addDrawerListener(toggle);
|
||||
toggle.syncState();
|
||||
|
||||
mNavigationView = findViewById(R.id.nav_view);
|
||||
mNavigationView.setNavigationItemSelectedListener(this);
|
||||
@@ -189,7 +120,7 @@ public class MainActivity extends AppCompatActivity
|
||||
if (!mAccountManager.hasAccounts(AccountGeneral.ACCOUNT_TYPE)) {
|
||||
desiredPage = getDefaultFragmentAfterLogout();
|
||||
desiredData = "";
|
||||
goToLoginScreen();
|
||||
mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV, null);
|
||||
updateNavigation();
|
||||
changeFragment(desiredPage, desiredData);
|
||||
} else {
|
||||
@@ -197,102 +128,35 @@ public class MainActivity extends AppCompatActivity
|
||||
changeFragment(FRAGMENT_STARTUP);
|
||||
int targetPage = desiredPage;
|
||||
String targetData = desiredData;
|
||||
getKVV(kvv -> {
|
||||
kvv.account().restoreOnlineLogin(restoreResult -> {
|
||||
updateNavigation();
|
||||
if (restoreResult != Login.RESTORE_STATUS_INVALID_PASSWORD)
|
||||
changeFragment(targetPage, targetData);
|
||||
else
|
||||
changeFragment(getDefaultFragmentAfterLogout());
|
||||
});
|
||||
getKVV().account().restoreOnlineLogin(isRestored -> {
|
||||
updateNavigation();
|
||||
if (isRestored)
|
||||
changeFragment(targetPage, targetData);
|
||||
else
|
||||
changeFragment(getDefaultFragmentAfterLogout());
|
||||
});
|
||||
}
|
||||
|
||||
if (!mAlreadyCreated) {
|
||||
Intent serviceIntent = new Intent(this, KVV.class);
|
||||
getApplicationContext().bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
|
||||
}
|
||||
mAlreadyCreated = true;
|
||||
|
||||
CustomNotificationManager.createNotificationChannel(this);
|
||||
/*getKVV(kvv -> {
|
||||
kvv.modules().list().recv(list -> {
|
||||
Modules.Module module = list.getByIndex(0);
|
||||
CustomNotificationManager.sendNotification(this, "Test", module.title, FRAGMENT_MODULES_DETAILS, module.getID()+"."+ ModulePart.getPageByPart(ModulePart.EVENT));
|
||||
}, log::e);
|
||||
});*/
|
||||
}
|
||||
|
||||
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);
|
||||
getApplicationContext().bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
|
||||
}
|
||||
mAlreadyCreated = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStop() {
|
||||
super.onStop();
|
||||
if (mKVV != null)
|
||||
mKVV.removeListener("mainactivity");
|
||||
if (mBound)
|
||||
getApplicationContext().unbindService(mConnection);
|
||||
mKVV = null;
|
||||
mBound = false;
|
||||
mAlreadyCreated = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onNewIntent(Intent intent) {
|
||||
super.onNewIntent(intent);
|
||||
if (CustomNotificationManager.NOTIFICATION_TYPE_NAVIGATE.equals(intent.getStringExtra(CustomNotificationManager.NOTIFICATION_INTENT))) {
|
||||
int page = intent.getIntExtra(CustomNotificationManager.NOTIFICATION_PAGE, 0);
|
||||
String data = intent.getStringExtra(CustomNotificationManager.NOTIFICATION_DATA);
|
||||
if (page == FRAGMENT_STARTUP || page == FRAGMENT_NONE)
|
||||
page = getDefaultFragmentAfterLogin();
|
||||
changeFragment(page, data);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPause() {
|
||||
super.onPause();
|
||||
isPaused = true;
|
||||
getKVV(kvv -> isLoggedInBeforePause = kvv.account().isLoggedIn());
|
||||
isLoggedInBeforePause = getKVV().account().isLoggedIn();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
if (isPaused) {
|
||||
getKVV(kvv -> {
|
||||
kvv.account().restoreOnlineLogin(restoreResult -> {
|
||||
updateNavigation();
|
||||
if (restoreResult == Login.RESTORE_STATUS_SUCCESS && !isLoggedInBeforePause) {
|
||||
changeFragment(getDefaultFragmentAfterLogin());
|
||||
} 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();
|
||||
getKVV().account().restoreOnlineLogin(isRestored -> {
|
||||
updateNavigation();
|
||||
if (isRestored && !isLoggedInBeforePause)
|
||||
changeFragment(getDefaultFragmentAfterLogin());
|
||||
else if (!isRestored && isLoggedInBeforePause) {
|
||||
getKVV().account().logout(false);
|
||||
changeFragment(getDefaultFragmentAfterLogout());
|
||||
}
|
||||
});
|
||||
}
|
||||
isPaused = false;
|
||||
@@ -306,34 +170,30 @@ public class MainActivity extends AppCompatActivity
|
||||
}
|
||||
|
||||
DrawerLayout drawer = findViewById(R.id.drawer_layout);
|
||||
if (drawer.isDrawerOpen(GravityCompat.START) && !isDrawerFixed) {
|
||||
if (drawer.isDrawerOpen(GravityCompat.START)) {
|
||||
drawer.closeDrawer(GravityCompat.START);
|
||||
} else {
|
||||
getKVV(kvv -> {
|
||||
if (mFragmentPage == FRAGMENT_MODULES_DETAILS) {
|
||||
ModDetailFragment fragment = (ModDetailFragment) mFragmentManager.findFragmentByTag(String.valueOf(FRAGMENT_MODULES_DETAILS));
|
||||
if (fragment != null && fragment.isVisible() && Regex.has("\\.[1-9][0-9]*", fragment.getData())) {
|
||||
fragment.gotoFragmentPart(0, -1);
|
||||
} else {
|
||||
changeFragment(FRAGMENT_MODULES);
|
||||
}
|
||||
} else if (mFragmentPage == FRAGMENT_CANTEENS_DETAILS) {
|
||||
DaySwitcherFragment fragment = (DaySwitcherFragment) mFragmentManager.findFragmentByTag(String.valueOf(FRAGMENT_CANTEENS_DETAILS));
|
||||
if (fragment != null && fragment.isVisible() && Regex.has("\\.[1-9][0-9]*", fragment.getData())) {
|
||||
fragment.gotoFragmentPart(0);
|
||||
} else {
|
||||
changeFragment(FRAGMENT_CANTEENS);
|
||||
}
|
||||
} else if (mFragmentPage == FRAGMENT_CANTEENS_ADD) {
|
||||
changeFragment(FRAGMENT_CANTEENS);
|
||||
} else if (kvv.account().isLoggedIn() && mFragmentPage != getDefaultFragmentAfterLogin()) {
|
||||
changeFragment(getDefaultFragmentAfterLogin());
|
||||
if (mFragmentPage == FRAGMENT_MODULES_DETAILS) {
|
||||
ModDetailFragment fragment = (ModDetailFragment) mFragmentManager.findFragmentByTag(String.valueOf(FRAGMENT_MODULES_DETAILS));
|
||||
if (fragment != null && fragment.isVisible() && Regex.has("\\.[1-9][0-9]*", fragment.getData())) {
|
||||
fragment.gotoFragmentPart(0, -1);
|
||||
} else {
|
||||
mDoubleBackToExitPressedOnce = System.currentTimeMillis();
|
||||
showToast(R.string.back_to_exit);
|
||||
//getTokenForAccountCreateIfNeeded(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD);
|
||||
changeFragment(FRAGMENT_MODULES);
|
||||
}
|
||||
});
|
||||
} else if (mFragmentPage == FRAGMENT_CANTEENS_DETAILS) {
|
||||
DaySwitcherFragment fragment = (DaySwitcherFragment) mFragmentManager.findFragmentByTag(String.valueOf(FRAGMENT_CANTEENS_DETAILS));
|
||||
if (fragment != null && fragment.isVisible() && Regex.has("\\.[1-9][0-9]*", fragment.getData())) {
|
||||
fragment.gotoFragmentPart(0);
|
||||
} else {
|
||||
changeFragment(FRAGMENT_CANTEENS);
|
||||
}
|
||||
} else if (getKVV().account().isLoggedIn() && mFragmentPage != getDefaultFragmentAfterLogin()) {
|
||||
changeFragment(getDefaultFragmentAfterLogin());
|
||||
} else {
|
||||
mDoubleBackToExitPressedOnce = System.currentTimeMillis();
|
||||
showToast(R.string.back_to_exit);
|
||||
//getTokenForAccountCreateIfNeeded(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -343,9 +203,6 @@ 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;
|
||||
}
|
||||
@@ -357,39 +214,19 @@ public class MainActivity extends AppCompatActivity
|
||||
// as you specify a parent activity in AndroidManifest.xml.
|
||||
int id = item.getItemId();
|
||||
|
||||
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;
|
||||
//noinspection SimplifiableIfStatement
|
||||
if (id == R.id.refresh) {
|
||||
ScheduleFragment fragment = (ScheduleFragment) mFragmentManager.findFragmentByTag(String.valueOf(FRAGMENT_SCHEDULE));
|
||||
if (fragment != null && fragment.isVisible()) {
|
||||
fragment.invalidate(true);
|
||||
}
|
||||
} 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;
|
||||
} 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 super.onOptionsItemSelected(item);
|
||||
@@ -422,30 +259,14 @@ 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);
|
||||
kvv.modules().list().delete();
|
||||
});
|
||||
getKVV().account().logout(true);
|
||||
getKVV().modules().list().delete();
|
||||
break;
|
||||
|
||||
}
|
||||
if (!isDrawerFixed) {
|
||||
DrawerLayout drawer = findViewById(R.id.drawer_layout);
|
||||
drawer.closeDrawer(GravityCompat.START);
|
||||
}
|
||||
DrawerLayout drawer = findViewById(R.id.drawer_layout);
|
||||
drawer.closeDrawer(GravityCompat.START);
|
||||
|
||||
int size = mNavigationView.getMenu().size();
|
||||
for (int k = 0; k < size; k++) {
|
||||
@@ -457,7 +278,7 @@ public class MainActivity extends AppCompatActivity
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
|
||||
protected void onSaveInstanceState(Bundle savedInstanceState) {
|
||||
if (mFragmentPage != FRAGMENT_STARTUP && mFragmentPage != FRAGMENT_NONE) {
|
||||
Fragment fragment = mFragmentManager.findFragmentByTag(String.valueOf(mFragmentPage));
|
||||
savedInstanceState.putInt(ARG_FRAGMENT_PAGE, mFragmentPage);
|
||||
@@ -490,12 +311,11 @@ public class MainActivity extends AppCompatActivity
|
||||
return this.mNewsManager;
|
||||
}
|
||||
|
||||
public void getKVV(KVVCallback callback) {
|
||||
public KVV getKVV() {
|
||||
if (this.mKVV == null) {
|
||||
mCallbacks.add(callback);
|
||||
} else {
|
||||
callback.get(this.mKVV);
|
||||
this.mKVV = new KVV(this, this);
|
||||
}
|
||||
return this.mKVV;
|
||||
}
|
||||
|
||||
public CanteenBrowser getCanteenBrowser() {
|
||||
@@ -517,7 +337,7 @@ public class MainActivity extends AppCompatActivity
|
||||
setRefreshFailedBanner(false);
|
||||
updateNavigation();
|
||||
changeFragment(getDefaultFragmentAfterLogout());
|
||||
//mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD, null, null);
|
||||
mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV, null);
|
||||
}
|
||||
|
||||
private void toLoginState(String fullName, String email, int newFragment) {
|
||||
@@ -530,33 +350,6 @@ public class MainActivity extends AppCompatActivity
|
||||
changeFragment(newFragment);
|
||||
}
|
||||
|
||||
private void registerSync() {
|
||||
registerSync(false);
|
||||
}
|
||||
|
||||
private void registerSync(boolean isLogin) {
|
||||
Account accountByType = mAccountManager.getAccountByType(AccountGeneral.ACCOUNT_TYPE);
|
||||
if (accountByType != null) {
|
||||
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
|
||||
);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
private void changeFragment(int newFragment) {
|
||||
changeFragment(newFragment, "");
|
||||
}
|
||||
@@ -578,15 +371,15 @@ public class MainActivity extends AppCompatActivity
|
||||
case FRAGMENT_MODULES:
|
||||
fragment = ModulesFragment.newInstance();
|
||||
break;
|
||||
/*case FRAGMENT_LOGIN:
|
||||
fragment = LoginFragment.newInstance();
|
||||
break;*/
|
||||
case FRAGMENT_SCHEDULE:
|
||||
fragment = ScheduleFragment.newInstance();
|
||||
break;
|
||||
case FRAGMENT_CANTEENS_DETAILS:
|
||||
fragment = DaySwitcherFragment.newInstance(newData);
|
||||
break;
|
||||
case FRAGMENT_CANTEENS_ADD:
|
||||
fragment = CanteensAddFragment.newInstance();
|
||||
break;
|
||||
case FRAGMENT_CANTEENS:
|
||||
fragment = CanteensFragment.newInstance();
|
||||
break;
|
||||
@@ -629,27 +422,20 @@ public class MainActivity extends AppCompatActivity
|
||||
|
||||
private void setNavigationSelection() {
|
||||
MenuItem item = null;
|
||||
int dotPos = mFragmentData.indexOf(".");
|
||||
String moduleId = mFragmentData;
|
||||
if (dotPos != -1)
|
||||
moduleId = moduleId.substring(0, dotPos);
|
||||
switch (mFragmentPage) {
|
||||
case FRAGMENT_MODULES_DETAILS:
|
||||
String finalModuleId = moduleId;
|
||||
getKVV(kvv -> {
|
||||
kvv.modules().list().find(finalModuleId, success -> {
|
||||
int size = mNavigationView.getMenu().size();
|
||||
//noinspection ConstantConditions
|
||||
String title = success == null ? null : success.title;
|
||||
for (int k = 0; k < size; k++) {
|
||||
MenuItem menuItem = mNavigationView.getMenu().getItem(k);
|
||||
if (menuItem.getTitle().equals(title)) {
|
||||
menuItem.setChecked(true);
|
||||
break;
|
||||
}
|
||||
getKVV().modules().list().find(mFragmentData, success -> {
|
||||
int size = mNavigationView.getMenu().size();
|
||||
//noinspection ConstantConditions
|
||||
String title = success == null ? null : success.title;
|
||||
for (int k = 0; k < size; k++) {
|
||||
MenuItem menuItem = mNavigationView.getMenu().getItem(k);
|
||||
if (menuItem.getTitle().equals(title)) {
|
||||
menuItem.setChecked(true);
|
||||
break;
|
||||
}
|
||||
}, log::e);
|
||||
});
|
||||
}
|
||||
}, log::e);
|
||||
return;
|
||||
case FRAGMENT_MODULES:
|
||||
item = mNavigationView.getMenu().findItem(R.id.nav_modules);
|
||||
@@ -660,23 +446,19 @@ public class MainActivity extends AppCompatActivity
|
||||
case FRAGMENT_CANTEENS_DETAILS:
|
||||
getCanteenBrowser().getCanteens(success -> {
|
||||
int size = mNavigationView.getMenu().size();
|
||||
try {
|
||||
Canteen canteen = success.getCanteen(Integer.parseInt(mFragmentData));
|
||||
String title = canteen == null ? null : canteen.getName();
|
||||
for (int k = 0; k < size; k++) {
|
||||
MenuItem menuItem = mNavigationView.getMenu().getItem(k);
|
||||
if (menuItem.getTitle().equals(title)) {
|
||||
menuItem.setChecked(true);
|
||||
break;
|
||||
}
|
||||
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);
|
||||
if (menuItem.getTitle().equals(title)) {
|
||||
menuItem.setChecked(true);
|
||||
break;
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}, log::e);
|
||||
return;
|
||||
case FRAGMENT_CANTEENS:
|
||||
case FRAGMENT_CANTEENS_ADD:
|
||||
item = mNavigationView.getMenu().findItem(R.id.nav_canteens);
|
||||
break;
|
||||
case FRAGMENT_NEWS:
|
||||
@@ -704,10 +486,10 @@ public class MainActivity extends AppCompatActivity
|
||||
if (!viewBtn.hasOnClickListeners())
|
||||
viewBtn.setOnClickListener(v -> {
|
||||
DrawerLayout drawer = findViewById(R.id.drawer_layout);
|
||||
if (drawer.isDrawerOpen(GravityCompat.START) && !isDrawerFixed) {
|
||||
if (drawer.isDrawerOpen(GravityCompat.START)) {
|
||||
drawer.closeDrawer(GravityCompat.START);
|
||||
}
|
||||
goToLoginScreen();
|
||||
mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV, null);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -715,23 +497,21 @@ public class MainActivity extends AppCompatActivity
|
||||
int MAX_COUNT = isLoggedIn ? 3 : 2;
|
||||
final int[] count = {0};
|
||||
if (isLoggedIn) {
|
||||
getKVV(kvv -> {
|
||||
kvv.modules().list().recv(success -> {
|
||||
int i = 0;
|
||||
for (Iterator<Modules.Module> it = success.latestSemesterIterator(); it.hasNext(); ) {
|
||||
Modules.Module module = it.next();
|
||||
MenuItem menuItem = mNavigationView.getMenu().add(Menu.NONE, Menu.NONE, 101 + i, module.title);
|
||||
menuItem.setOnMenuItemClickListener(item -> {
|
||||
onModulesFragmentInteraction(module.getID());
|
||||
return false;
|
||||
});
|
||||
i++;
|
||||
}
|
||||
if (++count[0] == MAX_COUNT) done.run();
|
||||
}, error -> {
|
||||
if (++count[0] == MAX_COUNT) done.run();
|
||||
log.e(error);
|
||||
});
|
||||
getKVV().modules().list().recv(success -> {
|
||||
int i = 0;
|
||||
for (Iterator<Modules.Module> it = success.latestSemesterIterator(); it.hasNext(); ) {
|
||||
Modules.Module module = it.next();
|
||||
MenuItem menuItem = mNavigationView.getMenu().add(Menu.NONE, Menu.NONE, 101 + i, module.title);
|
||||
menuItem.setOnMenuItemClickListener(item -> {
|
||||
onModulesFragmentInteraction(module.getID());
|
||||
return false;
|
||||
});
|
||||
i++;
|
||||
}
|
||||
if (++count[0] == MAX_COUNT) done.run();
|
||||
}, error -> {
|
||||
if (++count[0] == MAX_COUNT) done.run();
|
||||
log.e(error);
|
||||
});
|
||||
}
|
||||
getCanteenBrowser().getCanteens(success -> {
|
||||
@@ -739,7 +519,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 -> {
|
||||
this.onCanteensFragmentInteraction(canteen.getId());
|
||||
onCanteensFragmentInteraction(canteen.getId());
|
||||
return false;
|
||||
});
|
||||
i++;
|
||||
@@ -772,18 +552,16 @@ public class MainActivity extends AppCompatActivity
|
||||
|
||||
private void updateNavigation() {
|
||||
mQueue.add(() -> {
|
||||
getKVV(kvv -> {
|
||||
boolean isLoggedIn = kvv.account().isLoggedIn();
|
||||
setNavigationHeader(isLoggedIn);
|
||||
mNavigationView.getMenu().clear();
|
||||
if (isLoggedIn)
|
||||
mNavigationView.inflateMenu(R.menu.activity_main_drawer_login);
|
||||
else
|
||||
mNavigationView.inflateMenu(R.menu.activity_main_drawer);
|
||||
afterAnyMenuInflate(isLoggedIn, () -> {
|
||||
setNavigationSelection();
|
||||
mQueue.next();
|
||||
});
|
||||
boolean isLoggedIn = getKVV().account().isLoggedIn();
|
||||
setNavigationHeader(isLoggedIn);
|
||||
mNavigationView.getMenu().clear();
|
||||
if (isLoggedIn)
|
||||
mNavigationView.inflateMenu(R.menu.activity_main_drawer_login);
|
||||
else
|
||||
mNavigationView.inflateMenu(R.menu.activity_main_drawer);
|
||||
afterAnyMenuInflate(isLoggedIn, () -> {
|
||||
setNavigationSelection();
|
||||
mQueue.next();
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -805,11 +583,6 @@ public class MainActivity extends AppCompatActivity
|
||||
setNavigationSelection();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onModulesFragmentListUpdate(Function<Modules, Void> update) {
|
||||
this.mMolduleListUpdateFunction = update;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCanteensFragmentInteraction(final int itemID) {
|
||||
changeFragment(FRAGMENT_CANTEENS_DETAILS, String.valueOf(itemID));
|
||||
@@ -828,8 +601,6 @@ public class MainActivity extends AppCompatActivity
|
||||
|
||||
@Override
|
||||
public void onCanteenRefreshCompleted(boolean isFailed) {
|
||||
if (!isFailed)
|
||||
updateNavigation();
|
||||
setRefreshFailedBanner(isFailed);
|
||||
}
|
||||
|
||||
@@ -864,21 +635,8 @@ public class MainActivity extends AppCompatActivity
|
||||
|
||||
|
||||
@Override
|
||||
public void onLogin(LoginTokenKVV tokenKVV, LoginTokenBB tokenBB, boolean isOnlyRefresh) {
|
||||
String fullName = "";
|
||||
if (tokenKVV != null && !TextUtils.isEmpty(tokenKVV.getFullName())) {
|
||||
fullName = tokenKVV.getFullName();
|
||||
} else if (tokenBB != null && !TextUtils.isEmpty(tokenBB.getUsername())) {
|
||||
fullName = tokenBB.getUsername();
|
||||
}
|
||||
|
||||
String email = "";
|
||||
if (tokenKVV != null && !TextUtils.isEmpty(tokenKVV.getEmail()) && !"null".equals(tokenKVV.getEmail())) {
|
||||
email = tokenKVV.getEmail();
|
||||
} else if (tokenBB != null && !TextUtils.isEmpty(tokenBB.getUsername())) {
|
||||
email = tokenBB.getUsername() + "@zedat.fu-berlin.de";
|
||||
}
|
||||
toLoginState(fullName, email, getDefaultFragmentAfterLogin());
|
||||
public void onLogin(LoginToken token) {
|
||||
toLoginState(token.getFullName(), token.getEmail(), getDefaultFragmentAfterLogin());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -893,8 +651,6 @@ public class MainActivity extends AppCompatActivity
|
||||
|
||||
@Override
|
||||
public void onKVVNetworkResponse(NetworkResponse error) {
|
||||
if (error != null)
|
||||
updateNavigation();
|
||||
setRefreshFailedBanner(error != null);
|
||||
}
|
||||
|
||||
@@ -902,15 +658,4 @@ public class MainActivity extends AppCompatActivity
|
||||
public CustomAccountManager getAccountManager() {
|
||||
return mAccountManager;
|
||||
}
|
||||
|
||||
public interface KVVCallback {
|
||||
void get(KVV kvv);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onModuleListPartiallyUpdated(Modules modules) {
|
||||
if (mMolduleListUpdateFunction != null) {
|
||||
mMolduleListUpdateFunction.apply(modules);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,30 +6,20 @@ 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.CanteensViewHolder;
|
||||
import de.sebse.fuplanner.tools.ui.CustomViewHolder;
|
||||
import de.sebse.fuplanner.tools.ui.StringViewHolder;
|
||||
import de.sebse.fuplanner.tools.ui.ItemViewHolder;
|
||||
|
||||
/**
|
||||
* {@link RecyclerView.Adapter} that can display a {@link Canteen} and makes a call to the
|
||||
* specified {@link OnCanteensFragmentInteractionListener}.
|
||||
*/
|
||||
class CanteensAdapter extends RecyclerView.Adapter<CustomViewHolder> {
|
||||
class CanteensAdapter extends RecyclerView.Adapter<ItemViewHolder> {
|
||||
|
||||
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;
|
||||
@@ -43,95 +33,35 @@ class CanteensAdapter extends RecyclerView.Adapter<CustomViewHolder> {
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
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);
|
||||
}
|
||||
public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
|
||||
View view = LayoutInflater.from(parent.getContext())
|
||||
.inflate(R.layout.list_canteens_items, parent, false);
|
||||
return new CanteensViewHolder(view);
|
||||
.inflate(R.layout.list_all_items, parent, false);
|
||||
return new ItemViewHolder(view);
|
||||
}
|
||||
|
||||
@Override
|
||||
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--;
|
||||
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());
|
||||
}
|
||||
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 mIsShowDeletion ? mValues.size() + 1 : mValues.size();
|
||||
return 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,14 +11,10 @@ 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;
|
||||
|
||||
/**
|
||||
@@ -86,7 +82,7 @@ public class CanteensFragment extends Fragment {
|
||||
|
||||
|
||||
@Override
|
||||
public void onAttach(@NonNull Context context) {
|
||||
public void onAttach(Context context) {
|
||||
super.onAttach(context);
|
||||
if (context instanceof OnCanteensFragmentInteractionListener) {
|
||||
mListener = (OnCanteensFragmentInteractionListener) context;
|
||||
@@ -108,37 +104,6 @@ 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);
|
||||
}
|
||||
|
||||
@@ -40,10 +40,12 @@ class ModulesAdapter extends RecyclerView.Adapter<CustomViewHolder> {
|
||||
public void setModules(Modules modules) {
|
||||
mValues = modules;
|
||||
mPositionalData.clear();
|
||||
Semester lastSemester = new Semester(Semester.SEM_WS, 0);
|
||||
Semester lastSemester = null;
|
||||
for (Modules.Module module : mValues) {
|
||||
Semester semester = module.semester;
|
||||
if (semester != null && !semester.equals(lastSemester) || semester == null && lastSemester != null) {
|
||||
if (semester == null)
|
||||
continue;
|
||||
if (!semester.equals(lastSemester)) {
|
||||
mPositionalData.add(new Pair<>(TYPE_HEADER, semester));
|
||||
lastSemester = semester;
|
||||
}
|
||||
@@ -78,9 +80,7 @@ class ModulesAdapter extends RecyclerView.Adapter<CustomViewHolder> {
|
||||
StringViewHolder sHolder = (StringViewHolder) holder;
|
||||
String localizedSemester;
|
||||
Semester semester = (Semester) pair.second;
|
||||
if (semester == null)
|
||||
localizedSemester = holder.mView.getResources().getString(R.string.others);
|
||||
else if (semester.getType() == Semester.SEM_WS)
|
||||
if (semester.getType() == Semester.SEM_WS)
|
||||
localizedSemester = holder.mView.getResources().getString(R.string.winter_semester, semester.getYear(), semester.getYear()+1);
|
||||
else
|
||||
localizedSemester = holder.mView.getResources().getString(R.string.summer_semester, semester.getYear());
|
||||
@@ -98,8 +98,6 @@ 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 -> {
|
||||
|
||||
@@ -8,13 +8,11 @@ import android.view.ViewGroup;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.arch.core.util.Function;
|
||||
import androidx.fragment.app.Fragment;
|
||||
import androidx.recyclerview.widget.LinearLayoutManager;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
import de.sebse.fuplanner.tools.MainActivityListener;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
|
||||
@@ -68,28 +66,24 @@ public class ModulesFragment extends Fragment {
|
||||
|
||||
private void refresh(boolean forceRefresh) {
|
||||
if (mMainActivityListener != null) {
|
||||
mMainActivityListener.getKVV(kvv -> {
|
||||
kvv.modules().list().recv(success -> {
|
||||
adapter.setModules(success);
|
||||
swipeLayout.setRefreshing(false);
|
||||
}, error -> {
|
||||
log.e(error.toString());
|
||||
swipeLayout.setRefreshing(false);
|
||||
}, forceRefresh);
|
||||
});
|
||||
mMainActivityListener.getKVV().modules().list().recv(success -> {
|
||||
adapter.setModules(success);
|
||||
//if (mMainActivityListener != null)
|
||||
// mMainActivityListener.refreshNavigation();
|
||||
swipeLayout.setRefreshing(false);
|
||||
}, error -> {
|
||||
log.e(error.toString());
|
||||
swipeLayout.setRefreshing(false);
|
||||
}, forceRefresh);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void onAttach(@NonNull Context context) {
|
||||
public void onAttach(Context context) {
|
||||
super.onAttach(context);
|
||||
if (context instanceof OnModulesFragmentInteractionListener) {
|
||||
mListener = (OnModulesFragmentInteractionListener) context;
|
||||
mListener.onModulesFragmentListUpdate(modules -> {
|
||||
if (adapter != null) adapter.setModules(modules);
|
||||
return null;
|
||||
});
|
||||
} else {
|
||||
throw new RuntimeException(context.toString()
|
||||
+ " must implement OnModulesFragmentInteractionListener");
|
||||
@@ -111,6 +105,5 @@ public class ModulesFragment extends Fragment {
|
||||
|
||||
public interface OnModulesFragmentInteractionListener {
|
||||
void onModulesFragmentInteraction(String id);
|
||||
void onModulesFragmentListUpdate(Function<Modules, Void> update);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,11 @@ 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() {
|
||||
@@ -48,7 +53,7 @@ public class NewsFragment extends Fragment {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAttach(@NonNull Context context) {
|
||||
public void onAttach(Context context) {
|
||||
super.onAttach(context);
|
||||
if (context instanceof MainActivityListener) {
|
||||
mListener = (MainActivityListener) context;
|
||||
|
||||
@@ -1,38 +1,16 @@
|
||||
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() {
|
||||
@@ -47,7 +25,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()) {
|
||||
updateListPreferenceSummary(s);
|
||||
onSharedPreferenceChanged(getPreferenceScreen().getSharedPreferences(), s);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,87 +43,8 @@ public class PrefsFragment extends PreferenceFragmentCompat implements SharedPre
|
||||
|
||||
@Override
|
||||
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
|
||||
updateListPreferenceSummary(s);
|
||||
|
||||
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);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -18,9 +18,8 @@ import androidx.fragment.app.Fragment;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.services.kvv.types.Event;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
import de.sebse.fuplanner.services.kvv.types.Semester;
|
||||
import de.sebse.fuplanner.tools.MainActivityListener;
|
||||
import de.sebse.fuplanner.tools.UtilsDate;
|
||||
import de.sebse.fuplanner.tools.MainActivityListener;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
import de.sebse.fuplanner.tools.ui.weekview.MonthLoader;
|
||||
import de.sebse.fuplanner.tools.ui.weekview.WeekView;
|
||||
@@ -64,25 +63,21 @@ public class ScheduleFragment extends Fragment implements
|
||||
|
||||
public void invalidate(boolean forceRefresh) {
|
||||
if (mListener == null) return;
|
||||
mListener.getKVV(kvv -> {
|
||||
kvv.modules().list().recv(modules -> {
|
||||
mModules = modules;
|
||||
final int[] i = {0};
|
||||
Iterator<Modules.Module> iter = mModules.latestSemesterIterator();
|
||||
while (iter.hasNext()) {
|
||||
Modules.Module module = iter.next();
|
||||
kvv.modules().events().recv(module, success1 -> {
|
||||
i[0]++;
|
||||
if (i[0] >= mModules.size()) {
|
||||
if (mWeekView != null) {
|
||||
mWeekView.invalidate();
|
||||
mWeekView.notifyDatasetChanged();
|
||||
}
|
||||
mListener.getKVV().modules().list().recv(modules -> {
|
||||
mModules = modules;
|
||||
final int[] i = {0};
|
||||
for (Modules.Module module: mModules) {
|
||||
mListener.getKVV().modules().events().recv(module, success1 -> {
|
||||
i[0]++;
|
||||
if (i[0] >= mModules.size()) {
|
||||
if (mWeekView != null) {
|
||||
mWeekView.invalidate();
|
||||
mWeekView.notifyDatasetChanged();
|
||||
}
|
||||
}, log::e, forceRefresh);
|
||||
}
|
||||
}, log::e, forceRefresh);
|
||||
});
|
||||
}
|
||||
}, log::e, forceRefresh);
|
||||
}
|
||||
}, log::e, forceRefresh);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -103,7 +98,7 @@ public class ScheduleFragment extends Fragment implements
|
||||
|
||||
|
||||
@Override
|
||||
public void onAttach(@NonNull Context context) {
|
||||
public void onAttach(Context context) {
|
||||
super.onAttach(context);
|
||||
if (context instanceof MainActivityListener) {
|
||||
mListener = (MainActivityListener) context;
|
||||
@@ -124,11 +119,7 @@ public class ScheduleFragment extends Fragment implements
|
||||
public List<? extends WeekViewEvent> onMonthChange(int newYear, int newMonth) {
|
||||
ArrayList<WeekViewEvent> events = new ArrayList<>();
|
||||
if (mModules != null){
|
||||
Semester latestSemester = mModules.getLatestSemester();
|
||||
for (Modules.Module mod: mModules) {
|
||||
if (mod.getModuleType() == Modules.TYPE_BB && mod.semester != null && !mod.semester.equals(latestSemester)) {
|
||||
continue;
|
||||
}
|
||||
if (mod.events != null) {
|
||||
Iterator<Event> it_modEvents = mod.events.getEventsOfMonth(newYear, newMonth);
|
||||
while (it_modEvents.hasNext()) {
|
||||
@@ -140,7 +131,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(getContext()));
|
||||
weekViewEvent.setColor(e.getColor());
|
||||
events.add(weekViewEvent);
|
||||
}
|
||||
}
|
||||
@@ -189,22 +180,20 @@ public class ScheduleFragment extends Fragment implements
|
||||
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());
|
||||
|
||||
if (mListener == null) return;
|
||||
mListener.getKVV(kvv -> {
|
||||
kvv.modules().list().find(moduleId, module -> {
|
||||
String moduleName = module.title;
|
||||
alertDialogBuilder
|
||||
.setTitle(event.getName())
|
||||
.setMessage(
|
||||
getResources().getString(R.string.module_name, moduleName) + "\n" +
|
||||
getResources().getString(R.string.location_name, event.getLocation()) + "\n" +
|
||||
getResources().getString(R.string.date_scale, UtilsDate.getModifiedTime(getContext(), event.getStartTime().getTimeInMillis()), UtilsDate.getModifiedTime(getContext(), event.getEndTime().getTimeInMillis()+1))
|
||||
)
|
||||
.setCancelable(true)
|
||||
.setNeutralButton(R.string.close, (dialog, id) -> dialog.cancel());
|
||||
mListener.getKVV().modules().list().find(moduleId, module -> {
|
||||
String moduleName = module.title;
|
||||
alertDialogBuilder
|
||||
.setTitle(event.getName())
|
||||
.setMessage(
|
||||
getResources().getString(R.string.module_name, moduleName) + "\n" +
|
||||
getResources().getString(R.string.location_name, event.getLocation()) + "\n" +
|
||||
getResources().getString(R.string.date_scale, UtilsDate.getModifiedTime(getContext(), event.getStartTime().getTimeInMillis()), UtilsDate.getModifiedTime(getContext(), event.getEndTime().getTimeInMillis()+1))
|
||||
)
|
||||
.setCancelable(true)
|
||||
.setNeutralButton(R.string.close, (dialog, id) -> dialog.cancel());
|
||||
|
||||
AlertDialog alertDialog = alertDialogBuilder.create();
|
||||
alertDialog.show();
|
||||
}, log::e);
|
||||
});
|
||||
AlertDialog alertDialog = alertDialogBuilder.create();
|
||||
alertDialog.show();
|
||||
}, log::e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
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;
|
||||
@@ -12,15 +11,15 @@ class DaySwitcherAdapter extends FragmentStatePagerAdapter {
|
||||
private Canteen mCanteen = null;
|
||||
|
||||
DaySwitcherAdapter(FragmentManager fm) {
|
||||
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
|
||||
super(fm);
|
||||
}
|
||||
|
||||
public void setCanteen(Canteen canteen) {
|
||||
public void setModule(Canteen canteen) {
|
||||
mCanteen = canteen;
|
||||
this.setCanteen();
|
||||
this.setModule();
|
||||
}
|
||||
|
||||
public void setCanteen() {
|
||||
public void setModule() {
|
||||
this.notifyDataSetChanged();
|
||||
}
|
||||
|
||||
@@ -32,7 +31,6 @@ 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);
|
||||
|
||||
@@ -101,7 +101,7 @@ public class DaySwitcherFragment extends Fragment implements DaySwitcherListener
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAttach(@NonNull Context context) {
|
||||
public void onAttach(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.setCanteen(canteen);
|
||||
adapterViewPager.setModule(canteen);
|
||||
applyPageRequest();
|
||||
browser.getCanteen(canteen, success -> {
|
||||
adapterViewPager.setCanteen();
|
||||
adapterViewPager.setModule();
|
||||
applyPageRequest();
|
||||
if (callback != null)
|
||||
callback.onResponse(success);
|
||||
|
||||
@@ -27,10 +27,6 @@ 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;
|
||||
|
||||
@@ -41,30 +37,26 @@ class MealAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
|
||||
@NonNull
|
||||
@Override
|
||||
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
|
||||
if (viewType == TYPE_MEAL) {
|
||||
if (viewType == 0) {
|
||||
View view = LayoutInflater.from(viewGroup.getContext())
|
||||
.inflate(R.layout.list_canteen_items, viewGroup, false);
|
||||
return new MealViewHolder(view);
|
||||
} 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);
|
||||
.inflate(R.layout.list_all_caption, viewGroup, false);
|
||||
return new StringViewHolder(view);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
|
||||
if (holder.getItemViewType() == TYPE_MEAL) {
|
||||
if (holder.getItemViewType() == 0) {
|
||||
MealViewHolder viewHolder = ((MealViewHolder) holder);
|
||||
viewHolder.reset();
|
||||
Meal meal = getMeal(position);
|
||||
viewHolder.mTitle.setText(meal.getName());
|
||||
String value;
|
||||
switch (Preferences.getStringArray(mContext, R.array.pref_price_group)) {
|
||||
switch (Preferences.getString(mContext, R.array.pref_price_group)) {
|
||||
case "student":
|
||||
if (meal.getPriceStdnt() < 0)
|
||||
value = mContext.getResources().getString(R.string.no_price_available);
|
||||
@@ -115,7 +107,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 if (holder.getItemViewType() == TYPE_HEADER) {
|
||||
} else {
|
||||
StringViewHolder viewHolder = ((StringViewHolder) holder);
|
||||
viewHolder.mString.setText(getHeading(position));
|
||||
}
|
||||
@@ -123,25 +115,23 @@ class MealAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
|
||||
|
||||
@Override
|
||||
public int getItemCount() {
|
||||
return matches.size() + 1;
|
||||
return matches.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemViewType(int position) {
|
||||
if (position == 0)
|
||||
return TYPE_LEGEND;
|
||||
return matches.get(position - 1) instanceof String ? TYPE_HEADER : TYPE_MEAL;
|
||||
return matches.get(position) instanceof String ? 1 : 0;
|
||||
}
|
||||
|
||||
private Meal getMeal(int position) {
|
||||
if (this.mDay != null)
|
||||
return this.mDay.get((Integer) matches.get(position - 1));
|
||||
return this.mDay.get((Integer) matches.get(position));
|
||||
else
|
||||
return null;
|
||||
}
|
||||
|
||||
private String getHeading(int position) {
|
||||
return (String) matches.get(position - 1);
|
||||
return (String) matches.get(position);
|
||||
}
|
||||
|
||||
public void setDay(Day day) {
|
||||
@@ -151,13 +141,8 @@ 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++) {
|
||||
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();
|
||||
String category = this.mDay.get(i).getCategory();
|
||||
boolean found = false;
|
||||
for (String category_key : CATEGORY_KEYS) {
|
||||
if (category_key.equals(category)) {
|
||||
|
||||
@@ -85,7 +85,7 @@ public class MealFragment extends Fragment {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAttach(@NonNull Context context) {
|
||||
public void onAttach(Context context) {
|
||||
super.onAttach(context);
|
||||
Fragment parentFragment = getParentFragment();
|
||||
if (parentFragment != null) {
|
||||
@@ -104,10 +104,6 @@ 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 -> {
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
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;
|
||||
@@ -14,7 +12,7 @@ class ModDetailAdapter extends FragmentStatePagerAdapter {
|
||||
private final Context mContext;
|
||||
|
||||
ModDetailAdapter(FragmentManager fm, String itemPosition, Context context) {
|
||||
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
|
||||
super(fm);
|
||||
this.mContext = context;
|
||||
this.mItemPos = itemPosition;
|
||||
}
|
||||
@@ -27,7 +25,6 @@ class ModDetailAdapter extends FragmentStatePagerAdapter {
|
||||
}
|
||||
|
||||
// Returns the fragment to display for that page
|
||||
@NonNull
|
||||
@Override
|
||||
public Fragment getItem(int position) {
|
||||
switch (ModulePart.getPartByPage(position)) {
|
||||
|
||||
@@ -21,12 +21,14 @@ import de.sebse.fuplanner.services.kvv.types.Announcement;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
import de.sebse.fuplanner.tools.Regex;
|
||||
import de.sebse.fuplanner.tools.UtilsDate;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
import de.sebse.fuplanner.tools.ui.AnnouncementViewHolder;
|
||||
import de.sebse.fuplanner.tools.ui.CustomViewHolder;
|
||||
|
||||
class ModDetailAnnounceAdapter extends RecyclerView.Adapter<CustomViewHolder> {
|
||||
|
||||
@Nullable private Modules.Module mModule = null;
|
||||
private Logger log = new Logger(this);
|
||||
@NonNull private final Download.OnDownloadRequestInterface requestInterface;
|
||||
|
||||
ModDetailAnnounceAdapter(@NonNull Download.OnDownloadRequestInterface requestInterface) {
|
||||
@@ -93,7 +95,10 @@ class ModDetailAnnounceAdapter extends RecyclerView.Adapter<CustomViewHolder> {
|
||||
|
||||
try {
|
||||
return URLDecoder.decode(Regex.regex("/([^/]*)$", url), "UTF-8");
|
||||
} catch (NoSuchFieldException | UnsupportedEncodingException e) {
|
||||
} catch (NoSuchFieldException e) {
|
||||
e.printStackTrace();
|
||||
return res.getString(R.string.attachment_nr, index);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
return res.getString(R.string.attachment_nr, index);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ 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;
|
||||
@@ -83,47 +82,31 @@ public class ModDetailAnnounceFragment extends Fragment implements Download.OnDo
|
||||
}
|
||||
|
||||
private void refresh(boolean forceRefresh) {
|
||||
if (mListener != null) {
|
||||
mListener.getKVV(kvv -> {
|
||||
kvv.modules().details().recv(mItemPos, pair -> {
|
||||
adapter.setModule(pair.first);
|
||||
if (pair.second)
|
||||
swipeLayout.setRefreshing(false);
|
||||
}, error -> {
|
||||
swipeLayout.setRefreshing(false);
|
||||
log.e(error);
|
||||
}, forceRefresh);
|
||||
});
|
||||
}
|
||||
if (mListener == null)
|
||||
return;
|
||||
mListener.getKVV().modules().details().recv(mItemPos, pair -> {
|
||||
adapter.setModule(pair.first);
|
||||
if (pair.second)
|
||||
swipeLayout.setRefreshing(false);
|
||||
}, error -> {
|
||||
swipeLayout.setRefreshing(false);
|
||||
log.e(error);
|
||||
}, forceRefresh);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void request(String title, String url) {
|
||||
if (mListener == null)
|
||||
return;
|
||||
mListener.getKVV(kvv -> {
|
||||
kvv.modules().list().find(mItemPos, (Modules.Module module) -> {
|
||||
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);
|
||||
});
|
||||
mListener.getKVV().modules().list().find(mItemPos, (Modules.Module module) -> {
|
||||
String folderName = "FU-"+module.title.replaceAll("[:*<>|/\"\\\\]", "-");
|
||||
folderName += "/Announcement";
|
||||
getDownload().openDownloadDialog(title, url, folderName);
|
||||
}, log::e);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAttach(@NonNull Context context) {
|
||||
public void onAttach(Context context) {
|
||||
super.onAttach(context);
|
||||
if (context instanceof MainActivityListener) {
|
||||
this.mListener = ((MainActivityListener) context);
|
||||
|
||||
@@ -21,12 +21,14 @@ import de.sebse.fuplanner.services.kvv.types.Assignment;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
import de.sebse.fuplanner.tools.Regex;
|
||||
import de.sebse.fuplanner.tools.UtilsDate;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
import de.sebse.fuplanner.tools.ui.AnnouncementViewHolder;
|
||||
import de.sebse.fuplanner.tools.ui.CustomViewHolder;
|
||||
|
||||
class ModDetailAssignmentAdapter extends RecyclerView.Adapter<CustomViewHolder> {
|
||||
|
||||
@Nullable private Modules.Module mModule = null;
|
||||
private Logger log = new Logger(this);
|
||||
@NonNull private final Download.OnDownloadRequestInterface requestInterface;
|
||||
|
||||
ModDetailAssignmentAdapter(@NonNull Download.OnDownloadRequestInterface requestInterface) {
|
||||
@@ -72,7 +74,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.fuAccent);
|
||||
tag.layoutColor = ContextCompat.getColor(holder.mView.getContext(), R.color.colorFUBlue);
|
||||
holder.mTagGroup.addTag(tag);
|
||||
}
|
||||
holder.mTagGroup.setOnTagClickListener((tag, i) -> {
|
||||
@@ -93,7 +95,10 @@ class ModDetailAssignmentAdapter extends RecyclerView.Adapter<CustomViewHolder>
|
||||
|
||||
try {
|
||||
return URLDecoder.decode(Regex.regex("/([^/]*)$", url), "UTF-8");
|
||||
} catch (NoSuchFieldException | UnsupportedEncodingException e) {
|
||||
} catch (NoSuchFieldException e) {
|
||||
e.printStackTrace();
|
||||
return res.getString(R.string.attachment_nr, index);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
return res.getString(R.string.attachment_nr, index);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ 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;
|
||||
@@ -83,47 +82,31 @@ public class ModDetailAssignmentFragment extends Fragment implements Download.On
|
||||
}
|
||||
|
||||
private void refresh(boolean forceRefresh) {
|
||||
if (mListener != null) {
|
||||
mListener.getKVV(kvv -> {
|
||||
kvv.modules().details().recv(mItemPos, pair -> {
|
||||
adapter.setModule(pair.first);
|
||||
if (pair.second)
|
||||
swipeLayout.setRefreshing(false);
|
||||
}, error -> {
|
||||
swipeLayout.setRefreshing(false);
|
||||
log.e(error);
|
||||
}, forceRefresh);
|
||||
});
|
||||
}
|
||||
if (mListener == null)
|
||||
return;
|
||||
mListener.getKVV().modules().details().recv(mItemPos, pair -> {
|
||||
adapter.setModule(pair.first);
|
||||
if (pair.second)
|
||||
swipeLayout.setRefreshing(false);
|
||||
}, error -> {
|
||||
swipeLayout.setRefreshing(false);
|
||||
log.e(error);
|
||||
}, forceRefresh);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void request(String title, String url) {
|
||||
if (mListener == null)
|
||||
return;
|
||||
mListener.getKVV(kvv -> {
|
||||
kvv.modules().list().find(mItemPos, (Modules.Module module) -> {
|
||||
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);
|
||||
});
|
||||
mListener.getKVV().modules().list().find(mItemPos, (Modules.Module module) -> {
|
||||
String folderName = "FU-"+module.title.replaceAll("[:*<>|/\"\\\\]", "-");
|
||||
folderName += "/Assignment";
|
||||
getDownload().openDownloadDialog(title, url, folderName);
|
||||
}, log::e);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAttach(@NonNull Context context) {
|
||||
public void onAttach(Context context) {
|
||||
super.onAttach(context);
|
||||
if (context instanceof MainActivityListener) {
|
||||
this.mListener = ((MainActivityListener) context);
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
package de.sebse.fuplanner.fragments.moddetails;
|
||||
|
||||
import android.app.AlertDialog;
|
||||
import android.content.Context;
|
||||
import android.content.res.Resources;
|
||||
import android.text.TextUtils;
|
||||
import android.util.Pair;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
@@ -21,6 +19,7 @@ import de.sebse.fuplanner.services.kvv.types.EventList;
|
||||
import de.sebse.fuplanner.services.kvv.types.GroupedEvents;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
import de.sebse.fuplanner.tools.UtilsDate;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
import de.sebse.fuplanner.tools.ui.CustomViewHolder;
|
||||
import de.sebse.fuplanner.tools.ui.ItemViewHolder;
|
||||
import de.sebse.fuplanner.tools.ui.StringViewHolder;
|
||||
@@ -42,6 +41,8 @@ class ModDetailEventAdapter extends RecyclerView.Adapter<CustomViewHolder> {
|
||||
private Modules.Module mValue;
|
||||
private final ArrayList<Pair<Integer, Object>> mPositionalData;
|
||||
|
||||
private final Logger log = new Logger(this);
|
||||
|
||||
ModDetailEventAdapter() {
|
||||
mValue = null;
|
||||
mPositionalData = new ArrayList<>();
|
||||
@@ -80,20 +81,19 @@ class ModDetailEventAdapter extends RecyclerView.Adapter<CustomViewHolder> {
|
||||
for (Map.Entry<String, GroupedEvents> value: listsGrouped.entrySet()) {
|
||||
if (value.getValue().getGroups().size() > 0) {
|
||||
mPositionalData.add(new Pair<>(TYPE_HEADER, value.getKey()));
|
||||
ArrayList<GroupedEvents.Group> ungroupedGroups = new ArrayList<>();
|
||||
for (GroupedEvents.Group group: value.getValue().getGroups()) {
|
||||
boolean showAsGrouped = true;
|
||||
if (group.getSkippedDates().size() > 3 || group.size() < 3) {
|
||||
boolean showAsGrouped = true;
|
||||
for (GroupedEvents.Group group : value.getValue().getGroups()) {
|
||||
if (group.getSkippedDates().size() > 2) {
|
||||
showAsGrouped = false;
|
||||
}
|
||||
if (showAsGrouped) {
|
||||
mPositionalData.add(new Pair<>(TYPE_GROUPED, group));
|
||||
} else {
|
||||
ungroupedGroups.add(group);
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (GroupedEvents.Group ungroupedGroup : ungroupedGroups) {
|
||||
for (Event event: ungroupedGroup) {
|
||||
if (showAsGrouped) {
|
||||
for (GroupedEvents.Group group : value.getValue().getGroups()) {
|
||||
mPositionalData.add(new Pair<>(TYPE_GROUPED, group));
|
||||
}
|
||||
} else {
|
||||
for (Event event : value.getValue()) {
|
||||
mPositionalData.add(new Pair<>(TYPE_UNGROUPED, event));
|
||||
}
|
||||
}
|
||||
@@ -178,7 +178,7 @@ class ModDetailEventAdapter extends RecyclerView.Adapter<CustomViewHolder> {
|
||||
end = UtilsDate.getModifiedDate(lastDateTime);
|
||||
weekday = UtilsDate.getModifiedDate(context, firstDateTime, "E");
|
||||
startTime = UtilsDate.getModifiedTime(context, firstDateTime);
|
||||
endTime = UtilsDate.getModifiedTime(context, lastDateTime+1);
|
||||
endTime = UtilsDate.getModifiedTime(context, lastDateTime);
|
||||
for (long skippedDate : group.getSkippedDates()) {
|
||||
if (excepts == null) {
|
||||
excepts = new StringBuilder(UtilsDate.getModifiedDate(skippedDate));
|
||||
@@ -186,30 +186,9 @@ class ModDetailEventAdapter extends RecyclerView.Adapter<CustomViewHolder> {
|
||||
excepts.append(", ").append(UtilsDate.getModifiedDate(skippedDate));
|
||||
}
|
||||
}
|
||||
String groupTitle = context.getString(R.string.event_scale, weekday, startTime, endTime);
|
||||
if (!TextUtils.isEmpty(group.getTitle()) && !group.getTitle().equals(mValue.title))
|
||||
groupTitle += " ("+group.getTitle()+")";
|
||||
ig.mTitle.setText(groupTitle);
|
||||
ig.mTitle.setText(context.getString(R.string.event_scale, weekday, startTime, endTime));
|
||||
ig.mSubLeft.setText(context.getString(R.string.date_scale, start, end));
|
||||
ig.mSubRight.setText(excepts != null ? context.getString(R.string.except_list, excepts.toString()) : "");
|
||||
String moduleName = mValue.title;
|
||||
StringBuilder finalExcepts = excepts;
|
||||
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ig.mView.getContext());
|
||||
ig.mView.setOnClickListener(v -> {
|
||||
alertDialogBuilder
|
||||
.setTitle(R.string.events)
|
||||
.setMessage(
|
||||
ig.mView.getResources().getString(R.string.module_name, moduleName) + "\n" +
|
||||
ig.mView.getResources().getString(R.string.location_name, group.getLocation()) + "\n" +
|
||||
context.getString(R.string.event_scale, weekday, startTime, endTime) + "\n" +
|
||||
context.getString(R.string.date_scale, start, end) + "\n" +
|
||||
(finalExcepts != null ? context.getString(R.string.except_list, finalExcepts.toString()) : "")
|
||||
)
|
||||
.setCancelable(true)
|
||||
.setNeutralButton(R.string.close, (dialog, id) -> dialog.cancel());
|
||||
AlertDialog alertDialog = alertDialogBuilder.create();
|
||||
alertDialog.show();
|
||||
});
|
||||
return;
|
||||
case TYPE_UNGROUPED:
|
||||
ItemViewHolder iu = (ItemViewHolder) holder;
|
||||
@@ -220,29 +199,13 @@ class ModDetailEventAdapter extends RecyclerView.Adapter<CustomViewHolder> {
|
||||
else
|
||||
start = UtilsDate.getModifiedDateTime(context, event.getStartDate());
|
||||
if (UtilsDate.dateEquals(event.getStartDate(), event.getEndDate()))
|
||||
end = UtilsDate.getModifiedTime(context, event.getEndDate()+1);
|
||||
end = UtilsDate.getModifiedTime(context, event.getEndDate());
|
||||
else
|
||||
end = UtilsDate.getModifiedDateTime(context, event.getEndDate()+1);
|
||||
end = UtilsDate.getModifiedDateTime(context, event.getEndDate());
|
||||
date = context.getString(R.string.date_scale, start, end);
|
||||
iu.mTitle.setText(event.getTitle());
|
||||
iu.mSubLeft.setText(date);
|
||||
iu.mSubRight.setText(event.getLocation());
|
||||
String moduleName1 = mValue.title;
|
||||
AlertDialog.Builder alertDialogBuilder1 = new AlertDialog.Builder(iu.mView.getContext());
|
||||
iu.mView.setOnClickListener(v -> {
|
||||
alertDialogBuilder1
|
||||
.setTitle(moduleName1)
|
||||
.setMessage(
|
||||
iu.mView.getResources().getString(R.string.module_name, moduleName1) + "\n" +
|
||||
iu.mView.getResources().getString(R.string.location_name, event.getLocation()) + "\n" +
|
||||
date
|
||||
)
|
||||
.setCancelable(true)
|
||||
.setNeutralButton(R.string.close, (dialog, id) -> dialog.cancel());
|
||||
|
||||
AlertDialog alertDialog = alertDialogBuilder1.create();
|
||||
alertDialog.show();
|
||||
});
|
||||
iu.mSubRight.setText("");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -81,22 +81,20 @@ public class ModDetailEventFragment extends Fragment {
|
||||
}
|
||||
|
||||
private void refresh(boolean forceRefresh) {
|
||||
if (mListener != null) {
|
||||
mListener.getKVV(kvv -> {
|
||||
kvv.modules().details().recv(mItemPos, pair -> {
|
||||
adapter.setModule(pair.first);
|
||||
if (pair.second)
|
||||
swipeLayout.setRefreshing(false);
|
||||
}, error -> {
|
||||
swipeLayout.setRefreshing(false);
|
||||
log.e(error);
|
||||
}, forceRefresh);
|
||||
});
|
||||
}
|
||||
if (mListener == null)
|
||||
return;
|
||||
mListener.getKVV().modules().details().recv(mItemPos, pair -> {
|
||||
adapter.setModule(pair.first);
|
||||
if (pair.second)
|
||||
swipeLayout.setRefreshing(false);
|
||||
}, error -> {
|
||||
swipeLayout.setRefreshing(false);
|
||||
log.e(error);
|
||||
}, forceRefresh);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAttach(@NonNull Context context) {
|
||||
public void onAttach(Context context) {
|
||||
super.onAttach(context);
|
||||
if (context instanceof MainActivityListener) {
|
||||
this.mListener = ((MainActivityListener) context);
|
||||
|
||||
@@ -72,13 +72,11 @@ public class ModDetailFragment extends Fragment implements ModDetailListener {
|
||||
}
|
||||
if (mListener != null) {
|
||||
mListener.onTitleTextChange(R.string.courses);
|
||||
mListener.getKVV(kvv -> {
|
||||
kvv.modules().list().recv(success -> {
|
||||
Modules.Module module = success.get(mItemPos);
|
||||
if (mListener != null && module != null)
|
||||
mListener.onTitleTextChange(module.title);
|
||||
}, log::e);
|
||||
});
|
||||
mListener.getKVV().modules().list().recv(success -> {
|
||||
Modules.Module module = success.get(mItemPos);
|
||||
if (mListener != null && module != null)
|
||||
mListener.onTitleTextChange(module.title);
|
||||
}, log::e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,7 +95,7 @@ public class ModDetailFragment extends Fragment implements ModDetailListener {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAttach(@NonNull Context context) {
|
||||
public void onAttach(Context context) {
|
||||
super.onAttach(context);
|
||||
if (context instanceof MainActivityListener) {
|
||||
mListener = (MainActivityListener) context;
|
||||
|
||||
@@ -13,7 +13,6 @@ 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;
|
||||
|
||||
@@ -21,12 +20,9 @@ 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_EXAM = 0;
|
||||
private static final int SECTION_ASSIGNMENT = 1;
|
||||
private static final int SECTION_OTHER = 2;
|
||||
private static final int SECTION_GRADE = 0;
|
||||
|
||||
private Modules.Module mValue;
|
||||
private Gradebook.CategorizedGrades mGrades;
|
||||
private final ArrayList<Pair<Integer, Integer>> mPositionalData;
|
||||
|
||||
ModDetailGradebookAdapter() {
|
||||
@@ -42,32 +38,9 @@ class ModDetailGradebookAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
|
||||
|
||||
private void setModule() {
|
||||
mPositionalData.clear();
|
||||
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;
|
||||
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));
|
||||
}
|
||||
|
||||
this.notifyDataSetChanged();
|
||||
@@ -80,8 +53,8 @@ class ModDetailGradebookAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
|
||||
switch (viewType) {
|
||||
case TYPE_TOTAL:
|
||||
view = LayoutInflater.from(parent.getContext())
|
||||
.inflate(R.layout.list_moddetails_gradebook_title, parent, false);
|
||||
return new GradeTitleViewHolder(view);
|
||||
.inflate(R.layout.list_all_caption, parent, false);
|
||||
return new StringViewHolder(view);
|
||||
case TYPE_GRADE:
|
||||
view = LayoutInflater.from(parent.getContext())
|
||||
.inflate(R.layout.list_moddetails_gradebook, parent, false);
|
||||
@@ -96,7 +69,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 getViewType(mPositionalData.get(position).first);
|
||||
return mPositionalData.get(position).first;
|
||||
else return -1;
|
||||
}
|
||||
|
||||
@@ -106,45 +79,19 @@ class ModDetailGradebookAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
|
||||
if (mValue == null || position > mPositionalData.size())
|
||||
return;
|
||||
Pair<Integer, Integer> data = mPositionalData.get(position);
|
||||
int viewType = getViewType(data.first);
|
||||
int viewSection = getViewSection(data.first);
|
||||
Gradebook.GradebookOutput gradebook = getViewSectionGradebook(viewSection);
|
||||
switch (viewType) {
|
||||
switch (data.first) {
|
||||
case TYPE_TOTAL:
|
||||
GradeTitleViewHolder h = (GradeTitleViewHolder) holder;
|
||||
|
||||
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;
|
||||
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;
|
||||
int index = data.second / 1024;
|
||||
GradeViewHolder i = (GradeViewHolder) holder;
|
||||
Grade gradebook = mValue.gradebook.get(index);
|
||||
|
||||
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()));
|
||||
}
|
||||
i.mTitle.setText(gradebook.getItemName());
|
||||
i.mGrade.setText(String.valueOf(gradebook.getPoints()));
|
||||
i.mGradeMax.setText(String.valueOf(gradebook.getMaxPoints()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -154,27 +101,10 @@ class ModDetailGradebookAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
|
||||
return mPositionalData.size();
|
||||
}
|
||||
|
||||
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;
|
||||
private int getGradesCount() {
|
||||
if (mValue.gradebook != null)
|
||||
return mValue.gradebook.size();
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -203,19 +133,4 @@ 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,22 +81,20 @@ public class ModDetailGradebookFragment extends Fragment {
|
||||
}
|
||||
|
||||
private void refresh(boolean forceRefresh) {
|
||||
if (mListener != null) {
|
||||
mListener.getKVV(kvv -> {
|
||||
kvv.modules().details().recv(mItemPos, pair -> {
|
||||
adapter.setModule(pair.first);
|
||||
if (pair.second)
|
||||
swipeLayout.setRefreshing(false);
|
||||
}, error -> {
|
||||
swipeLayout.setRefreshing(false);
|
||||
log.e(error);
|
||||
}, forceRefresh);
|
||||
});
|
||||
}
|
||||
if (mListener == null)
|
||||
return;
|
||||
mListener.getKVV().modules().details().recv(mItemPos, pair -> {
|
||||
adapter.setModule(pair.first);
|
||||
if (pair.second)
|
||||
swipeLayout.setRefreshing(false);
|
||||
}, error -> {
|
||||
swipeLayout.setRefreshing(false);
|
||||
log.e(error);
|
||||
}, forceRefresh);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAttach(@NonNull Context context) {
|
||||
public void onAttach(Context context) {
|
||||
super.onAttach(context);
|
||||
if (context instanceof MainActivityListener) {
|
||||
this.mListener = ((MainActivityListener) context);
|
||||
|
||||
@@ -2,7 +2,6 @@ package de.sebse.fuplanner.fragments.moddetails;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.text.TextUtils;
|
||||
import android.util.Pair;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
@@ -22,6 +21,7 @@ import de.sebse.fuplanner.services.kvv.types.Event;
|
||||
import de.sebse.fuplanner.services.kvv.types.Lecturer;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
import de.sebse.fuplanner.tools.UtilsDate;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
import de.sebse.fuplanner.tools.ui.CustomViewHolder;
|
||||
import de.sebse.fuplanner.tools.ui.ItemViewHolder;
|
||||
import de.sebse.fuplanner.tools.ui.MailViewHolder;
|
||||
@@ -37,12 +37,12 @@ class ModDetailOverviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
|
||||
private static final int TYPE_SHOW_MORE = 3;
|
||||
private static final int TYPE_MAIL = 4;
|
||||
private static final int TYPE_SHORTCUTS = 5;
|
||||
private static final int TYPE_NO_ITEMS = 6;
|
||||
|
||||
@Nullable private final ModDetailListener mListener;
|
||||
|
||||
private Modules.Module mValue;
|
||||
private final ArrayList<Pair<Integer, Object>> mPositionalData;
|
||||
private Logger log = new Logger(this);
|
||||
|
||||
ModDetailOverviewAdapter(@Nullable final ModDetailListener listener) {
|
||||
mValue = null;
|
||||
@@ -57,10 +57,8 @@ class ModDetailOverviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
|
||||
|
||||
private void setModule() {
|
||||
mPositionalData.clear();
|
||||
if (!TextUtils.isEmpty(mValue.description)) {
|
||||
mPositionalData.add(new Pair<>(TYPE_HEADER, ModulePart.DESCRIPTION));
|
||||
mPositionalData.add(new Pair<>(TYPE_DESCRIPTION, null));
|
||||
}
|
||||
mPositionalData.add(new Pair<>(TYPE_HEADER, ModulePart.DESCRIPTION));
|
||||
mPositionalData.add(new Pair<>(TYPE_DESCRIPTION, null));
|
||||
mPositionalData.add(new Pair<>(TYPE_SHORTCUTS, null));
|
||||
mPositionalData.add(new Pair<>(TYPE_HEADER, ModulePart.LECTURERS));
|
||||
for (int i = 0; i < mValue.lecturer.size(); i++) {
|
||||
@@ -81,9 +79,6 @@ class ModDetailOverviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
|
||||
}
|
||||
if (count > MAX_ITEMS_PER_PREVIEW)
|
||||
mPositionalData.add(new Pair<>(TYPE_SHOW_MORE, category));
|
||||
if (count == 0) {
|
||||
mPositionalData.add(new Pair<>(TYPE_NO_ITEMS, category));
|
||||
}
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@@ -107,10 +102,6 @@ class ModDetailOverviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
|
||||
view = LayoutInflater.from(parent.getContext())
|
||||
.inflate(R.layout.list_all_show_more, parent, false);
|
||||
return new CustomViewHolder(view);
|
||||
case TYPE_NO_ITEMS:
|
||||
view = LayoutInflater.from(parent.getContext())
|
||||
.inflate(R.layout.list_all_no_items, parent, false);
|
||||
return new CustomViewHolder(view);
|
||||
case TYPE_MAIL:
|
||||
view = LayoutInflater.from(parent.getContext())
|
||||
.inflate(R.layout.list_all_mails, parent, false);
|
||||
@@ -202,9 +193,9 @@ class ModDetailOverviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
|
||||
else
|
||||
start = UtilsDate.getModifiedDateTime(i.mView.getContext(), event.getStartDate());
|
||||
if (UtilsDate.dateEquals(event.getStartDate(), event.getEndDate()))
|
||||
end = UtilsDate.getModifiedTime(i.mView.getContext(), event.getEndDate()+1);
|
||||
end = UtilsDate.getModifiedTime(i.mView.getContext(), event.getEndDate());
|
||||
else
|
||||
end = UtilsDate.getModifiedDateTime(i.mView.getContext(), event.getEndDate()+1);
|
||||
end = UtilsDate.getModifiedDateTime(i.mView.getContext(), event.getEndDate());
|
||||
i.mSubRight.setText(i.mView.getResources().getString(R.string.date_scale,
|
||||
start, end
|
||||
));
|
||||
@@ -245,7 +236,6 @@ class ModDetailOverviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
|
||||
});
|
||||
break;
|
||||
case TYPE_SHOW_MORE:
|
||||
case TYPE_NO_ITEMS:
|
||||
CustomViewHolder c = (CustomViewHolder) holder;
|
||||
c.mView.setOnClickListener(view -> {
|
||||
if (mListener != null) mListener.gotoFragmentPart((Integer) data.second, -1);
|
||||
|
||||
@@ -86,21 +86,19 @@ public class ModDetailOverviewFragment extends Fragment {
|
||||
|
||||
private void refresh(boolean forceRefresh) {
|
||||
if (mListener != null) {
|
||||
mListener.getKVV(kvv -> {
|
||||
kvv.modules().details().recv(mItemPos, pair -> {
|
||||
adapter.setModule(pair.first);
|
||||
if (pair.second)
|
||||
swipeLayout.setRefreshing(false);
|
||||
}, error -> {
|
||||
mListener.getKVV().modules().details().recv(mItemPos, pair -> {
|
||||
adapter.setModule(pair.first);
|
||||
if (pair.second)
|
||||
swipeLayout.setRefreshing(false);
|
||||
log.e(error);
|
||||
}, forceRefresh);
|
||||
});
|
||||
}, error -> {
|
||||
swipeLayout.setRefreshing(false);
|
||||
log.e(error);
|
||||
}, forceRefresh);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAttach(@NonNull Context context) {
|
||||
public void onAttach(Context context) {
|
||||
super.onAttach(context);
|
||||
if (context instanceof MainActivityListener) {
|
||||
this.mListener = ((MainActivityListener) context);
|
||||
|
||||
@@ -2,7 +2,6 @@ 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;
|
||||
@@ -25,7 +24,6 @@ import de.sebse.fuplanner.services.kvv.types.Resource;
|
||||
import de.sebse.fuplanner.tools.MainActivityListener;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
import de.sebse.fuplanner.tools.ui.treeview.DirectoryNodeBinder;
|
||||
import de.sebse.fuplanner.tools.ui.treeview.DocumentNodeBinder;
|
||||
import de.sebse.fuplanner.tools.ui.treeview.FileNodeBinder;
|
||||
import de.sebse.fuplanner.tools.ui.treeview.TreeNode;
|
||||
import de.sebse.fuplanner.tools.ui.treeview.TreeViewAdapter;
|
||||
@@ -35,7 +33,7 @@ import de.sebse.fuplanner.tools.ui.treeview.TreeViewAdapter;
|
||||
* Use the {@link ModDetailResourceFragment#newInstance} factory method to
|
||||
* create an instance of this fragment.
|
||||
*/
|
||||
public class ModDetailResourceFragment extends Fragment implements Download.OnDownloadRequestInterface {
|
||||
public class ModDetailResourceFragment extends Fragment {
|
||||
private static final String ARG_POSITION = "itemPosition";
|
||||
|
||||
private String mItemPos;
|
||||
@@ -83,7 +81,7 @@ public class ModDetailResourceFragment extends Fragment implements Download.OnDo
|
||||
RecyclerView recyclerView = view.findViewById(R.id.list);
|
||||
recyclerView.setLayoutManager(new LinearLayoutManager(context));
|
||||
|
||||
adapter = new ModDetailResourceAdapter(Arrays.asList(new FileNodeBinder(), new DirectoryNodeBinder(), new DocumentNodeBinder(this)));
|
||||
adapter = new ModDetailResourceAdapter(Arrays.asList(new FileNodeBinder(), new DirectoryNodeBinder()));
|
||||
adapter.setOnTreeNodeListener(new TreeViewAdapter.OnTreeNodeListener() {
|
||||
@Override
|
||||
public boolean onClick(TreeNode node, RecyclerView.ViewHolder holder) {
|
||||
@@ -91,24 +89,11 @@ public class ModDetailResourceFragment extends Fragment implements Download.OnDo
|
||||
// Update and toggle the node.
|
||||
onToggle(!node.isExpand(), holder);
|
||||
} 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;
|
||||
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);
|
||||
});
|
||||
ModDetailResourceFragment.this.mListener.getKVV().modules().resources().recv(mItemPos, (Modules.Module module) -> {
|
||||
String folderName = "FU-"+module.title.replaceAll("[:*<>|/\"\\\\]", "-");
|
||||
Resource.File file = (Resource.File) node.getContent();
|
||||
getDownload().openDownloadDialog(file, folderName);
|
||||
}, log::e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -134,20 +119,7 @@ public class ModDetailResourceFragment extends Fragment implements Download.OnDo
|
||||
}
|
||||
|
||||
@Override
|
||||
public void request(String title, String url) {
|
||||
if (mListener == null)
|
||||
return;
|
||||
mListener.getKVV(kvv -> {
|
||||
kvv.modules().list().find(mItemPos, (Modules.Module module) -> {
|
||||
String folderName = "FU-"+module.title.replaceAll("[:*<>|/\"\\\\]", "-");
|
||||
folderName += "/Announcement";
|
||||
getDownload().openDownloadDialog(title, url, folderName);
|
||||
}, log::e);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAttach(@NonNull Context context) {
|
||||
public void onAttach(Context context) {
|
||||
super.onAttach(context);
|
||||
if (context instanceof MainActivityListener) {
|
||||
this.mListener = ((MainActivityListener) context);
|
||||
@@ -166,18 +138,16 @@ public class ModDetailResourceFragment extends Fragment implements Download.OnDo
|
||||
}
|
||||
|
||||
private void refresh(boolean forceRefresh) {
|
||||
if (mListener != null) {
|
||||
mListener.getKVV(kvv -> {
|
||||
kvv.modules().details().recv(mItemPos, pair -> {
|
||||
adapter.setModule(pair.first);
|
||||
if (pair.second)
|
||||
swipeLayout.setRefreshing(false);
|
||||
}, error -> {
|
||||
swipeLayout.setRefreshing(false);
|
||||
log.e(error);
|
||||
}, forceRefresh);
|
||||
});
|
||||
}
|
||||
if (mListener == null)
|
||||
return;
|
||||
mListener.getKVV().modules().details().recv(mItemPos, pair -> {
|
||||
adapter.setModule(pair.first);
|
||||
if (pair.second)
|
||||
swipeLayout.setRefreshing(false);
|
||||
}, error -> {
|
||||
swipeLayout.setRefreshing(false);
|
||||
log.e(error);
|
||||
}, forceRefresh);
|
||||
}
|
||||
|
||||
private Download getDownload() {
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
package de.sebse.fuplanner.fragments.moddetails;
|
||||
|
||||
public class ModulePart {
|
||||
class ModulePart {
|
||||
static final int DESCRIPTION = 0;
|
||||
static final int OVERVIEW = 1;
|
||||
public static final int ANNOUNCEMENT = 2;
|
||||
public static final int ASSIGNMENT = 3;
|
||||
public static final int EVENT = 4;
|
||||
public static final int GRADEBOOK = 5;
|
||||
public static final int RESOURCES = 6;
|
||||
static final int ANNOUNCEMENT = 2;
|
||||
static final int ASSIGNMENT = 3;
|
||||
static final int EVENT = 4;
|
||||
static final int GRADEBOOK = 5;
|
||||
static final int RESOURCES = 6;
|
||||
static final int LECTURERS = 7;
|
||||
private static final int[] pages = new int[]{OVERVIEW, ANNOUNCEMENT, ASSIGNMENT, GRADEBOOK, RESOURCES, EVENT};
|
||||
|
||||
|
||||
@@ -2,21 +2,17 @@ package de.sebse.fuplanner.services.canteen;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
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;
|
||||
@@ -24,11 +20,9 @@ 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);
|
||||
@@ -39,7 +33,9 @@ public class CanteenBrowser extends HTTPService {
|
||||
throw new RuntimeException(context.toString() + " must implement CanteenListener");
|
||||
try {
|
||||
this.canteens = Canteens.load(context);
|
||||
} catch (IOException | ClassNotFoundException e) {
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} catch (ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
@@ -49,11 +45,12 @@ 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;
|
||||
@@ -67,22 +64,7 @@ public class CanteenBrowser extends HTTPService {
|
||||
}
|
||||
|
||||
private void upgradeCanteens(final NetworkCallback<Canteens> callback, final NetworkErrorCallback errorCallback) {
|
||||
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;
|
||||
}
|
||||
|
||||
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 -> {
|
||||
get("https://openmensa.org/api/v2/canteens?near[lat]=52.449743&near[lng]=13.282245&near[dist]=7", null, response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(201101, 403, "No canteen list retrieved!"));
|
||||
@@ -90,7 +72,28 @@ public class CanteenBrowser extends HTTPService {
|
||||
}
|
||||
Canteens canteens = new Canteens();
|
||||
try {
|
||||
parseCanteens(body, canteens);
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
errorCallback.onError(new NetworkError(201102, 403, "Cannot parse canteen list!"));
|
||||
@@ -100,95 +103,18 @@ 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();
|
||||
@@ -230,11 +156,12 @@ 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();
|
||||
|
||||
@@ -126,12 +126,4 @@ 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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ 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;
|
||||
@@ -26,7 +25,7 @@ public class Canteens implements Serializable, Iterable<Canteen> {
|
||||
addCanteen(canteen);
|
||||
}
|
||||
|
||||
public void addCanteen(Canteen canteen) {
|
||||
private void addCanteen(Canteen canteen) {
|
||||
if (this.list.contains(canteen)) return;
|
||||
this.list.add(canteen);
|
||||
}
|
||||
@@ -75,12 +74,7 @@ public class Canteens implements Serializable, Iterable<Canteen> {
|
||||
}
|
||||
|
||||
public static Canteens load(Context context) throws IOException, ClassNotFoundException {
|
||||
FileInputStream fis;
|
||||
try {
|
||||
fis = context.openFileInput(FILE_NAME);
|
||||
} catch (FileNotFoundException e) {
|
||||
return null;
|
||||
}
|
||||
FileInputStream fis = context.openFileInput(FILE_NAME);
|
||||
ObjectInputStream is = new ObjectInputStream(fis);
|
||||
Canteens modules = (Canteens) is.readObject();
|
||||
is.close();
|
||||
|
||||
@@ -28,14 +28,6 @@ public class FUAuthenticator extends AbstractAccountAuthenticator {
|
||||
|
||||
@Override
|
||||
public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException {
|
||||
final AccountManager am = AccountManager.get(mContext);
|
||||
if (am.getAccountsByType(accountType).length > 0) {
|
||||
final Bundle bundle = new Bundle();
|
||||
bundle.putInt(AccountManager.KEY_ERROR_CODE, AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION);
|
||||
bundle.putString(AccountManager.KEY_ERROR_MESSAGE, "Already an account added!");
|
||||
return bundle;
|
||||
}
|
||||
|
||||
final Intent intent = new Intent(mContext, FUAuthenticatorActivity.class);
|
||||
intent.putExtra(FUAuthenticatorActivity.ARG_ACCOUNT_TYPE, accountType);
|
||||
intent.putExtra(FUAuthenticatorActivity.ARG_AUTH_TYPE, authTokenType);
|
||||
@@ -66,14 +58,9 @@ public class FUAuthenticator extends AbstractAccountAuthenticator {
|
||||
if (password != null) {
|
||||
try {
|
||||
authToken = new UserLoginTask(account.name, password, authTokenType, mContext).execute((Void) null).get();
|
||||
// Login when auth/re-auth
|
||||
if (!TextUtils.isEmpty(authToken) && authToken.startsWith("Error: ")) {
|
||||
// if password is not wrong -> Networking error
|
||||
if (!authToken.contains("100343"))
|
||||
throw new NetworkErrorException(authToken);
|
||||
else authToken = null;
|
||||
}
|
||||
} catch (InterruptedException | ExecutionException e) {
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
} catch (ExecutionException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,19 +6,25 @@ import android.accounts.AccountManager;
|
||||
import android.animation.Animator;
|
||||
import android.animation.AnimatorListenerAdapter;
|
||||
import android.annotation.TargetApi;
|
||||
import android.app.LoaderManager.LoaderCallbacks;
|
||||
import android.content.Context;
|
||||
import android.content.CursorLoader;
|
||||
import android.content.Intent;
|
||||
import android.content.Loader;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.database.Cursor;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.provider.ContactsContract;
|
||||
import android.text.TextUtils;
|
||||
import android.view.View;
|
||||
import android.view.inputmethod.EditorInfo;
|
||||
import android.view.inputmethod.InputMethodManager;
|
||||
import android.widget.Button;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.google.android.material.textfield.TextInputEditText;
|
||||
import android.widget.EditText;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import de.sebse.fuplanner.R;
|
||||
|
||||
import static de.sebse.fuplanner.services.fulogin.UserLoginTask.PARAM_USER_PASS;
|
||||
@@ -26,16 +32,21 @@ import static de.sebse.fuplanner.services.fulogin.UserLoginTask.PARAM_USER_PASS;
|
||||
/**
|
||||
* A login screen that offers login via email/password.
|
||||
*/
|
||||
public class FUAuthenticatorActivity extends AccountAuthenticatorActivity {
|
||||
public class FUAuthenticatorActivity extends AccountAuthenticatorActivity implements LoaderCallbacks<Cursor> {
|
||||
|
||||
/**
|
||||
* Id to identity READ_CONTACTS permission request.
|
||||
*/
|
||||
private static final int REQUEST_READ_CONTACTS = 0;
|
||||
|
||||
/**
|
||||
* Keep track of the login task to ensure we can cancel it if requested.
|
||||
*/
|
||||
UserLoginTask mAuthTask = null;
|
||||
|
||||
// UI references.
|
||||
private TextInputEditText mEmailView;
|
||||
TextInputEditText mPasswordView;
|
||||
TextView mErrorView;
|
||||
private EditText mEmailView;
|
||||
EditText mPasswordView;
|
||||
private View mProgressView;
|
||||
private View mLoginFormView;
|
||||
|
||||
@@ -55,13 +66,12 @@ public class FUAuthenticatorActivity extends AccountAuthenticatorActivity {
|
||||
|
||||
mAccountType = getIntent().getStringExtra(ARG_ACCOUNT_TYPE);
|
||||
mAuthTokenType = getIntent().getStringExtra(ARG_AUTH_TYPE);
|
||||
mAuthTokenType = mAuthTokenType != null ? mAuthTokenType : AccountGeneral.AUTHTOKEN_TYPE_KVV;
|
||||
mIsAddingNewAccount = getIntent().getBooleanExtra(ARG_IS_ADDING_NEW_ACCOUNT, false);
|
||||
|
||||
setContentView(R.layout.activity_fu_authenticator);
|
||||
mErrorView = findViewById(R.id.error_textview);
|
||||
// Set up the login form.
|
||||
mEmailView = findViewById(R.id.input_username);
|
||||
populateAutoComplete();
|
||||
|
||||
mPasswordView = findViewById(R.id.input_password);
|
||||
mPasswordView.setOnEditorActionListener((textView, id, keyEvent) -> {
|
||||
@@ -79,6 +89,49 @@ public class FUAuthenticatorActivity extends AccountAuthenticatorActivity {
|
||||
mProgressView = findViewById(R.id.login_progress);
|
||||
}
|
||||
|
||||
private void populateAutoComplete() {
|
||||
if (!mayRequestContacts()) {
|
||||
return;
|
||||
}
|
||||
|
||||
getLoaderManager().initLoader(0, null, this);
|
||||
}
|
||||
|
||||
private boolean mayRequestContacts() {
|
||||
/*if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
|
||||
return true;
|
||||
}
|
||||
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
|
||||
return true;
|
||||
}
|
||||
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
|
||||
Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
|
||||
.setAction(android.R.string.ok, new View.OnClickListener() {
|
||||
@Override
|
||||
@TargetApi(Build.VERSION_CODES.M)
|
||||
public void onClick(View v) {
|
||||
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
|
||||
}*/
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback received when a permissions request has been completed.
|
||||
*/
|
||||
@Override
|
||||
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
|
||||
@NonNull int[] grantResults) {
|
||||
if (requestCode == REQUEST_READ_CONTACTS) {
|
||||
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
|
||||
populateAutoComplete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Attempts to sign in or register the account specified by the login form.
|
||||
@@ -165,13 +218,50 @@ public class FUAuthenticatorActivity extends AccountAuthenticatorActivity {
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
|
||||
return new CursorLoader(this,
|
||||
// Retrieve data rows for the device user's 'profile' contact.
|
||||
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
|
||||
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
|
||||
|
||||
// Select only email addresses.
|
||||
ContactsContract.Contacts.Data.MIMETYPE +
|
||||
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
|
||||
.CONTENT_ITEM_TYPE},
|
||||
|
||||
// Show primary email addresses first. Note that there won't be
|
||||
// a primary email address if the user hasn't specified one.
|
||||
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLoaderReset(Loader<Cursor> cursorLoader) {
|
||||
|
||||
}
|
||||
|
||||
|
||||
private interface ProfileQuery {
|
||||
String[] PROJECTION = {
|
||||
ContactsContract.CommonDataKinds.Email.ADDRESS,
|
||||
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
|
||||
};
|
||||
|
||||
int ADDRESS = 0;
|
||||
int IS_PRIMARY = 1;
|
||||
}
|
||||
|
||||
void finishLogin(Intent intent) {
|
||||
String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
|
||||
String accountPassword = intent.getStringExtra(PARAM_USER_PASS);
|
||||
final Account account = new Account(accountName, intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE));
|
||||
final AccountManager mAccountManager = AccountManager.get(this);
|
||||
|
||||
if (mIsAddingNewAccount) {
|
||||
if (getIntent().getBooleanExtra(ARG_IS_ADDING_NEW_ACCOUNT, false)) {
|
||||
String authtoken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN);
|
||||
String authtokenType = mAuthTokenType;
|
||||
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
package de.sebse.fuplanner.services.fulogin;
|
||||
|
||||
public class UserLoginResult {
|
||||
}
|
||||
@@ -5,6 +5,7 @@ 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;
|
||||
|
||||
@@ -13,13 +14,9 @@ import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import de.sebse.fuplanner.R;
|
||||
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.types.LoginTokenKVV;
|
||||
import de.sebse.fuplanner.services.kvv.types.LoginToken;
|
||||
import de.sebse.fuplanner.services.kvv.sync.Login;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
import de.sebse.fuplanner.tools.network.NetworkError;
|
||||
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
|
||||
|
||||
|
||||
/**
|
||||
@@ -37,23 +34,20 @@ public class UserLoginTask extends AsyncTask<Void, Void, String> {
|
||||
};*/
|
||||
static final String PARAM_USER_PASS = "PARAM_USER_PASS";
|
||||
|
||||
private final String mUsername;
|
||||
private final String mEmail;
|
||||
private final String mPassword;
|
||||
private final KVVLogin mKVVLogin;
|
||||
private final BBLogin mBBLogin;
|
||||
private final Login mVolleyLogin;
|
||||
private String mTokenType;
|
||||
private Logger log = new Logger(this);
|
||||
@SuppressLint("StaticFieldLeak")
|
||||
@Nullable
|
||||
private FUAuthenticatorActivity mActivity;
|
||||
|
||||
UserLoginTask(String username, String password, @NotNull String tokenType, @NotNull Context context) {
|
||||
mUsername = username;
|
||||
UserLoginTask(String email, String password, String tokenType, @NotNull Context context) {
|
||||
mEmail = email;
|
||||
mPassword = password;
|
||||
mTokenType = tokenType;
|
||||
FULogin mFULogin = new FULogin(context);
|
||||
mKVVLogin = new KVVLogin(context, mFULogin);
|
||||
mBBLogin = new BBLogin(context, mFULogin);
|
||||
mVolleyLogin = new Login(context);
|
||||
if (context instanceof FUAuthenticatorActivity)
|
||||
mActivity = (FUAuthenticatorActivity) context;
|
||||
}
|
||||
@@ -63,84 +57,58 @@ public class UserLoginTask extends AsyncTask<Void, Void, String> {
|
||||
// TODO: attempt authentication against a network service.
|
||||
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
AtomicReference<String> login = new AtomicReference<>();
|
||||
NetworkErrorCallback errorFunc = error -> {
|
||||
log.e(error);
|
||||
login.set("Error: "+ error.getCode());
|
||||
latch.countDown();
|
||||
};
|
||||
switch (mTokenType) {
|
||||
case AccountGeneral.AUTHTOKEN_TYPE_KVV:
|
||||
mKVVLogin.doLogin(mUsername, mPassword, success -> {
|
||||
mKVVLogin.testLoginToken(success, success1 -> {
|
||||
login.set(success1.toJsonString());
|
||||
latch.countDown();
|
||||
}, errorFunc);
|
||||
}, error -> {
|
||||
if (error.getCode() == 100101) {
|
||||
// KVV never used
|
||||
LoginTokenKVV loginTokenKVV = new LoginTokenKVV(mUsername, "");
|
||||
loginTokenKVV.setNotAvailable();
|
||||
login.set(loginTokenKVV.toJsonString());
|
||||
latch.countDown();
|
||||
} else {
|
||||
errorFunc.onError(error);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD:
|
||||
mBBLogin.doLogin(mUsername, mPassword, success -> {
|
||||
mBBLogin.testLoginToken(success, success1 -> {
|
||||
login.set(success1.toJsonString());
|
||||
latch.countDown();
|
||||
}, error -> {
|
||||
if (error.getCode() == 100270) {
|
||||
// Blackboard never used
|
||||
success.setNotAvailable();
|
||||
login.set(success.toJsonString());
|
||||
latch.countDown();
|
||||
} else {
|
||||
errorFunc.onError(error);
|
||||
}
|
||||
});
|
||||
}, errorFunc);
|
||||
break;
|
||||
default:
|
||||
errorFunc.onError(new NetworkError(104100, 400, "Invalid auth token type"));
|
||||
return null;
|
||||
}
|
||||
AtomicReference<LoginToken> login = new AtomicReference<>();
|
||||
mVolleyLogin.doLogin(mEmail, mPassword, success -> {
|
||||
mVolleyLogin.testLoginToken(success, success1 -> {
|
||||
login.set(success);
|
||||
latch.countDown();
|
||||
}, error -> latch.countDown());
|
||||
}, error -> latch.countDown());
|
||||
try {
|
||||
latch.await();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return login.get();
|
||||
log.d(login.get());
|
||||
|
||||
if (login.get() == null) {
|
||||
return null;
|
||||
} else {
|
||||
return login.get().toJsonString();
|
||||
}
|
||||
|
||||
/*for (String credential : DUMMY_CREDENTIALS) {
|
||||
String[] pieces = credential.split(":");
|
||||
if (pieces[0].equals(mEmail)) {
|
||||
// Account exists, return true if the password matches.
|
||||
return pieces[1].equals(mPassword) ? "auth token here" : null;
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: register the new account here.
|
||||
return null;*/
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPostExecute(final String success) {
|
||||
if (mActivity == null || mActivity.isFinishing())
|
||||
return;
|
||||
if (mActivity.isDestroyed())
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mActivity.isDestroyed())
|
||||
return;
|
||||
mActivity.mAuthTask = null;
|
||||
mActivity.showProgress(false);
|
||||
|
||||
if (success != null && !success.startsWith("Error: ")) {
|
||||
if (success != null) {
|
||||
final Intent res = new Intent();
|
||||
res.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
|
||||
res.putExtra(AccountManager.KEY_ACCOUNT_NAME, mEmail);
|
||||
res.putExtra(AccountManager.KEY_ACCOUNT_TYPE, AccountGeneral.ACCOUNT_TYPE);
|
||||
res.putExtra(AccountManager.KEY_AUTHTOKEN, success);
|
||||
res.putExtra(PARAM_USER_PASS, mPassword);
|
||||
mActivity.finishLogin(res);
|
||||
} else if (success != null && (success.contains("100343"))) {
|
||||
} else {
|
||||
mActivity.mPasswordView.setError(mActivity.getString(R.string.error_incorrect_password));
|
||||
mActivity.mPasswordView.requestFocus();
|
||||
} else if (success != null) {
|
||||
mActivity.mErrorView.setText(mActivity.getString(R.string.network_error_parameter, success.substring(7)));
|
||||
} else {
|
||||
mActivity.mErrorView.setText(R.string.network_error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,7 +116,7 @@ public class UserLoginTask extends AsyncTask<Void, Void, String> {
|
||||
protected void onCancelled() {
|
||||
if (mActivity == null || mActivity.isFinishing())
|
||||
return;
|
||||
if (mActivity.isDestroyed())
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mActivity.isDestroyed())
|
||||
return;
|
||||
mActivity.mAuthTask = null;
|
||||
mActivity.showProgress(false);
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
package de.sebse.fuplanner.services.kvv;
|
||||
|
||||
public class Constants {
|
||||
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/";
|
||||
}
|
||||
@@ -1,104 +1,31 @@
|
||||
package de.sebse.fuplanner.services.kvv;
|
||||
|
||||
import android.accounts.AccountManager;
|
||||
import android.app.Service;
|
||||
import android.content.Intent;
|
||||
import android.os.Binder;
|
||||
import android.os.IBinder;
|
||||
|
||||
import com.android.volley.NetworkResponse;
|
||||
import android.content.Context;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import de.sebse.fuplanner.services.kvv.types.LoginTokenBB;
|
||||
import de.sebse.fuplanner.services.kvv.types.LoginTokenWB;
|
||||
import de.sebse.fuplanner.tools.CustomAccountManager;
|
||||
|
||||
public class KVV extends Service {
|
||||
public class KVV {
|
||||
private final HashMap<String, Object> addons = new HashMap<>();
|
||||
private final HashMap<String, KVVListener> mListeners = new HashMap<>();
|
||||
private final KVVListener mListener = new KVVListener() {
|
||||
CustomAccountManager accountManager = null;
|
||||
private final KVVListener mListener;
|
||||
private final Context mContext;
|
||||
|
||||
@Override
|
||||
public CustomAccountManager getAccountManager() {
|
||||
if (accountManager == null)
|
||||
accountManager = new CustomAccountManager(AccountManager.get(KVV.this.getApplicationContext()), () -> null);
|
||||
return accountManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onKVVNetworkResponse(NetworkResponse error) {
|
||||
for (KVVListener listener : mListeners.values())
|
||||
listener.onKVVNetworkResponse(error);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLogin(LoginTokenWB tokenKVV, LoginTokenBB tokenBB, boolean isOnlyRefresh) {
|
||||
for (KVVListener listener : mListeners.values())
|
||||
listener.onLogin(tokenKVV, tokenBB, isOnlyRefresh);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLogout() {
|
||||
for (KVVListener listener : mListeners.values())
|
||||
listener.onLogout();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onModuleListChange() {
|
||||
for (KVVListener listener : mListeners.values())
|
||||
listener.onModuleListChange();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onModuleListPartiallyUpdated(de.sebse.fuplanner.services.kvv.types.Modules modules) {
|
||||
for (KVVListener listener : mListeners.values())
|
||||
listener.onModuleListPartiallyUpdated(modules);
|
||||
}
|
||||
};
|
||||
|
||||
// Binder given to clients
|
||||
private final IBinder mBinder = new LocalBinder();
|
||||
public KVV(KVVListener listener, Context context) {
|
||||
this.mListener = listener;
|
||||
this.mContext = context;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Login account() {
|
||||
return (Login) addAndGet("account", () -> new Login(mListener, getApplicationContext()));
|
||||
return (Login) addAndGet("account", () -> new Login(mListener, mContext));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Modules modules() {
|
||||
return (Modules) addAndGet("module", () -> new Modules(account(), mListener, getApplicationContext()));
|
||||
return (Modules) addAndGet("module", () -> new Modules(account(), mListener, mContext));
|
||||
}
|
||||
|
||||
public void addListener(String key, KVVListener listener) {
|
||||
mListeners.put(key, listener);
|
||||
}
|
||||
|
||||
public void removeListener(String key) {
|
||||
mListeners.remove(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return mBinder;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Class used for the client Binder. Because we know this service always
|
||||
* runs in the same process as its clients, we don't need to deal with IPC.
|
||||
*/
|
||||
public class LocalBinder extends Binder {
|
||||
public KVV getService() {
|
||||
// Return this instance of LocalService so clients can call public methods
|
||||
return KVV.this;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -2,20 +2,16 @@ 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.LoginTokenWB;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
import de.sebse.fuplanner.services.kvv.types.LoginToken;
|
||||
import de.sebse.fuplanner.tools.CustomAccountManager;
|
||||
|
||||
public interface KVVListener {
|
||||
default void onLogin(LoginTokenWB tokenKVV, LoginTokenBB tokenBB, boolean isOnlyRefresh) {}
|
||||
default void onLogin(LoginToken token) {}
|
||||
|
||||
default void onLogout() {}
|
||||
|
||||
default void onModuleListChange() {}
|
||||
|
||||
default void onModuleListPartiallyUpdated(Modules modules) {}
|
||||
|
||||
default void onKVVNetworkResponse(NetworkResponse error) {}
|
||||
|
||||
CustomAccountManager getAccountManager();
|
||||
|
||||
@@ -1,94 +1,59 @@
|
||||
package de.sebse.fuplanner.services.kvv;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.Pair;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.services.kvv.types.LoginToken;
|
||||
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.WBLogin;
|
||||
import de.sebse.fuplanner.services.kvv.types.LoginTokenBB;
|
||||
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 {
|
||||
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;
|
||||
|
||||
public static final int LOGOUT_KVV = 2;
|
||||
public static final int LOGOUT_BB = 1;
|
||||
public static final int RELOGIN = 0;
|
||||
|
||||
public class Login extends HTTPService {
|
||||
private final KVVListener mListener;
|
||||
private Context context;
|
||||
@Nullable private LoginTokenWB mTokenKVV;
|
||||
@Nullable private LoginTokenBB mTokenBB;
|
||||
@Nullable private LoginToken mToken;
|
||||
private boolean mLoginPending = false;
|
||||
private final NetworkCallbackCollector<Pair<LoginTokenWB, LoginTokenBB>> mRefreshCallbacks = new NetworkCallbackCollector<>();
|
||||
private final NetworkCallbackCollector<Integer> mRestoreCallbacks = new NetworkCallbackCollector<>();
|
||||
private final NetworkCallbackCollector<LoginToken> mRefreshCallbacks = new NetworkCallbackCollector<>();
|
||||
|
||||
Login(KVVListener listener, Context context) {
|
||||
super();
|
||||
super(context);
|
||||
this.mListener = listener;
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
private Context getContext() {
|
||||
return this.context;
|
||||
}
|
||||
|
||||
public void restoreOnlineLogin(IntegerInterface callback) {
|
||||
mRestoreCallbacks.add(new Pair<>(callback::run, null));
|
||||
public void restoreOnlineLogin(BooleanInterface callback) {
|
||||
if (mLoginPending) {
|
||||
callback.run(false);
|
||||
return;
|
||||
}
|
||||
mLoginPending = true;
|
||||
LoginTokenWB.load(mListener.getAccountManager(), tokenKVV -> {
|
||||
LoginTokenBB.load(mListener.getAccountManager(), tokenBB -> {
|
||||
boolean result = setToken(tokenKVV, tokenBB);
|
||||
mLoginPending = false;
|
||||
mRestoreCallbacks.responseResponse(result ? RESTORE_STATUS_SUCCESS : RESTORE_STATUS_INVALID_PASSWORD);
|
||||
}, e -> {
|
||||
mLoginPending = false;
|
||||
mRestoreCallbacks.responseResponse(RESTORE_STATUS_ERROR);
|
||||
});
|
||||
}, e -> {
|
||||
LoginToken.load(mListener.getAccountManager(), token -> {
|
||||
boolean result = setToken(token);
|
||||
mLoginPending = false;
|
||||
mRestoreCallbacks.responseResponse(RESTORE_STATUS_ERROR);
|
||||
log.d("loginToken", token != null ? token.toString() : null);
|
||||
callback.run(result);
|
||||
});
|
||||
}
|
||||
|
||||
public void isOfflineStoredAvailable(BooleanInterface callback) {
|
||||
LoginTokenWB.load(mListener.getAccountManager(), tokenKVV -> {
|
||||
LoginTokenBB.load(mListener.getAccountManager(), tokenBB -> {
|
||||
callback.run(tokenKVV != null && tokenBB != null);
|
||||
}, e -> callback.run(false));
|
||||
}, e -> callback.run(false));
|
||||
LoginToken.load(mListener.getAccountManager(), token -> {
|
||||
callback.run(token != null);
|
||||
});
|
||||
}
|
||||
|
||||
public boolean logout(boolean delete) {
|
||||
if (mLoginPending)
|
||||
return false;
|
||||
if (mTokenKVV == null || mTokenBB == null)
|
||||
if (mToken == null)
|
||||
return true;
|
||||
if (delete) {
|
||||
Preferences.setString(getContext(), R.string.pref_shib_idp_session, "");
|
||||
mTokenKVV.delete(mListener.getAccountManager());
|
||||
mTokenBB.delete(mListener.getAccountManager());
|
||||
}
|
||||
mTokenKVV = null;
|
||||
mTokenBB = null;
|
||||
return handleCallbacks(false);
|
||||
if (delete)
|
||||
mToken.delete(mListener.getAccountManager());
|
||||
mToken = null;
|
||||
return handleCallbacks();
|
||||
}
|
||||
|
||||
public boolean isLoginPending() {
|
||||
@@ -96,81 +61,52 @@ public class Login {
|
||||
}
|
||||
|
||||
public boolean isLoggedIn() {
|
||||
return mTokenKVV != null && mTokenBB != null;
|
||||
return mToken != null;
|
||||
}
|
||||
|
||||
public boolean isInOnlineMode() {
|
||||
return isLoggedIn();
|
||||
}
|
||||
|
||||
void testLoginToken(@NotNull NetworkCallback<Pair<LoginTokenWB, LoginTokenBB>> callback, @NotNull NetworkErrorCallback errorCallback) {
|
||||
if (mTokenKVV == null) {
|
||||
void testLoginToken(@NotNull NetworkCallback<LoginToken> callback, @NotNull NetworkErrorCallback errorCallback) {
|
||||
if (mToken == null) {
|
||||
errorCallback.onError(new NetworkError(100173, -1, "Not logged in!"));
|
||||
return;
|
||||
}
|
||||
if (mTokenBB == null) {
|
||||
errorCallback.onError(new NetworkError(100174, -1, "Not logged in!"));
|
||||
return;
|
||||
}
|
||||
testLoginToken(mTokenKVV, mTokenBB, callback, errorCallback);
|
||||
testLoginToken(mToken, callback, 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 WBLogin(getContext(), mFULogin).testLoginToken(tokenKVV, tokenKVV1 -> {
|
||||
new BBLogin(getContext(), mFULogin).testLoginToken(tokenBB, tokenBB1 -> {
|
||||
callback.onResponse(new Pair<>(tokenKVV1, tokenBB1));
|
||||
}, errorCallback);
|
||||
}, errorCallback);
|
||||
private void testLoginToken(@NotNull LoginToken token, @NotNull NetworkCallback<LoginToken> callback, @NotNull NetworkErrorCallback errorCallback) {
|
||||
new de.sebse.fuplanner.services.kvv.sync.Login(getContext()).testLoginToken(token, callback, errorCallback);
|
||||
}
|
||||
|
||||
@Nullable public LoginTokenWB getLoginTokenKVV() {
|
||||
return mTokenKVV;
|
||||
@Nullable public LoginToken getLoginToken() {
|
||||
return mToken;
|
||||
}
|
||||
|
||||
@Nullable public LoginTokenBB getLoginTokenBB() {
|
||||
return mTokenBB;
|
||||
}
|
||||
|
||||
void refreshLogin(NetworkCallback<Pair<LoginTokenWB, LoginTokenBB>> success, NetworkErrorCallback error, int flags) {
|
||||
void refreshLogin(NetworkCallback<LoginToken> success, NetworkErrorCallback error) {
|
||||
boolean isFirst = mRefreshCallbacks.isEmpty();
|
||||
mRefreshCallbacks.add(success, error);
|
||||
if (!isFirst)
|
||||
return;
|
||||
refreshLoginRunner(success, error, 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_WB, ignored -> {
|
||||
refreshLoginRunner(success, error, flags & ~LOGOUT_KVV);
|
||||
});
|
||||
} else if ((flags & LOGOUT_BB) == LOGOUT_BB) {
|
||||
manager.doInvalidateToken(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD, ignored -> {
|
||||
refreshLoginRunner(success, error, flags & ~LOGOUT_BB);
|
||||
});
|
||||
} else if (flags == RELOGIN) {
|
||||
restoreOnlineLogin(restoreResult -> {
|
||||
if (restoreResult == RESTORE_STATUS_SUCCESS)
|
||||
manager.doInvalidateToken(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV, ignored -> {
|
||||
restoreOnlineLogin(isRestored -> {
|
||||
if (isRestored)
|
||||
testLoginToken(mRefreshCallbacks::responseResponse, mRefreshCallbacks::responseError);
|
||||
else if (restoreResult == RESTORE_STATUS_INVALID_PASSWORD) {
|
||||
else {
|
||||
logout(true);
|
||||
mRefreshCallbacks.responseError(new NetworkError(100180, 403, "Re-login failed (password)!"));
|
||||
} else {
|
||||
mRefreshCallbacks.responseError(new NetworkError(100181, 403, "Re-login failed (error)!"));
|
||||
mRefreshCallbacks.responseError(new NetworkError(100180, 403, "Re-login failed!"));
|
||||
}
|
||||
});
|
||||
} else {
|
||||
throw new IllegalArgumentException("Invalid flag in refreshLoginRunner: "+flags);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
private boolean handleCallbacks(boolean isOnlyRefresh) {
|
||||
if (mTokenKVV != null || mTokenBB != null) {
|
||||
mListener.onLogin(mTokenKVV, mTokenBB, isOnlyRefresh);
|
||||
private boolean handleCallbacks() {
|
||||
if (mToken != null) {
|
||||
mListener.onLogin(mToken);
|
||||
return true;
|
||||
} else {
|
||||
mListener.onLogout();
|
||||
@@ -178,20 +114,15 @@ public class Login {
|
||||
}
|
||||
}
|
||||
|
||||
private boolean setToken(@Nullable LoginTokenWB tokenKVV, @Nullable LoginTokenBB tokenBB) {
|
||||
if (tokenKVV == null || tokenBB == null)
|
||||
private boolean setToken(@Nullable LoginToken token) {
|
||||
if (token == null)
|
||||
return false;
|
||||
boolean isOnlyRefresh = mTokenKVV != null;
|
||||
mTokenKVV = tokenKVV;
|
||||
mTokenBB = tokenBB;
|
||||
return isOnlyRefresh || handleCallbacks(isOnlyRefresh);
|
||||
boolean isOnlyRefresh = mToken != null;
|
||||
mToken = token;
|
||||
return isOnlyRefresh || handleCallbacks();
|
||||
}
|
||||
|
||||
public interface BooleanInterface {
|
||||
void run(boolean bool);
|
||||
}
|
||||
|
||||
public interface IntegerInterface {
|
||||
void run(int integer);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,6 @@ package de.sebse.fuplanner.services.kvv;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import com.android.volley.NetworkResponse;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.HashMap;
|
||||
@@ -58,13 +56,7 @@ public class Modules {
|
||||
public ModulesList list() {
|
||||
if (mList == null) {
|
||||
mList = new ModulesList(mLogin, mListener, context);
|
||||
mList.addErrorListener("Modules", error -> {
|
||||
NetworkResponse networkResponse = error.networkResponse;
|
||||
if ((networkResponse.statusCode == 400 || networkResponse.statusCode == 403) && networkResponse.headers.containsKey("X-Blackboard-product"))
|
||||
mListener.onKVVNetworkResponse(null);
|
||||
else
|
||||
mListener.onKVVNetworkResponse(networkResponse);
|
||||
});
|
||||
mList.addErrorListener("Modules", error -> mListener.onKVVNetworkResponse(error.networkResponse));
|
||||
mList.addSuccessListener("Modules", success -> mListener.onKVVNetworkResponse(null));
|
||||
}
|
||||
return mList;
|
||||
@@ -76,13 +68,7 @@ public class Modules {
|
||||
Part o = mAddons.get(addon);
|
||||
if (o == null) {
|
||||
o = creatorInterface.create();
|
||||
o.addErrorListener("Modules", error -> {
|
||||
NetworkResponse networkResponse = error.networkResponse;
|
||||
if ((networkResponse.statusCode == 400 || networkResponse.statusCode == 403) && networkResponse.headers.containsKey("X-Blackboard-product"))
|
||||
mListener.onKVVNetworkResponse(null);
|
||||
else
|
||||
mListener.onKVVNetworkResponse(networkResponse);
|
||||
});
|
||||
o.addErrorListener("Modules", error -> mListener.onKVVNetworkResponse(error.networkResponse));
|
||||
o.addSuccessListener("Modules", success -> mListener.onKVVNetworkResponse(null));
|
||||
mAddons.put(addon, o);
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ import java.util.ArrayList;
|
||||
|
||||
import de.sebse.fuplanner.services.kvv.types.Announcement;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
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;
|
||||
@@ -34,12 +33,12 @@ public class ModulesAnnouncements extends PartModules<ArrayList<Announcement>> {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void upgradeKVV(final String ID, final NetworkCallback<ArrayList<Announcement>> callback, final NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenKVV() == null || !mLogin.getLoginTokenKVV().isAvailable()) {
|
||||
protected void upgrade(final String ID, final NetworkCallback<ArrayList<Announcement>> callback, final NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
|
||||
errorCallback.onError(new NetworkError(101204, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
super.get(String.format(Constants.WB_SERVER_URL +"direct/announcement/site/%s.json?n=999999&d=999999999&_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
|
||||
super.get(String.format("https://kvv.imp.fu-berlin.de/direct/announcement/site/%s.json?n=999999&d=999999999", ID), mLogin.getLoginToken().getCookies(), response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(101201, 403, "No announcements retrieved!"));
|
||||
@@ -82,59 +81,11 @@ public class ModulesAnnouncements extends PartModules<ArrayList<Announcement>> {
|
||||
}
|
||||
}
|
||||
|
||||
callback.onResponse(announcements);
|
||||
// Empty announcements *may be* because token is invalid -> check
|
||||
if (announcements.size() == 0)
|
||||
mLogin.testLoginToken(token -> callback.onResponse(announcements), errorCallback);
|
||||
else
|
||||
callback.onResponse(announcements);
|
||||
}, error -> errorCallback.onError(new NetworkError(101203, error.networkResponse.statusCode, "Cannot get announcements!")));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void upgradeBB(String ID, NetworkCallback<ArrayList<Announcement>> callback, NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenBB() == null || !mLogin.getLoginTokenBB().isAvailable()) {
|
||||
errorCallback.onError(new NetworkError(101214, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
super.get(String.format("https://lms.fu-berlin.de/learn/api/v1/courses/%s/announcements?fields=id,title,body.rawText,startDateRestriction,creatorUserId", ID), mLogin.getLoginTokenBB().getCookies(), response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(101211, 403, "No announcements retrieved!"));
|
||||
return;
|
||||
}
|
||||
ArrayList<Announcement> announcements = new ArrayList<>();
|
||||
JSONArray sites;
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
sites = json.getJSONArray("results");
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
errorCallback.onError(new NetworkError(101212, 403, "Cannot parse announcements!"));
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < sites.length(); i++) {
|
||||
try {
|
||||
JSONObject site = sites.getJSONObject(i);
|
||||
String id = site.getString("id");
|
||||
String title = site.getString("title");
|
||||
String text = site.getJSONObject("body").getString("rawText");
|
||||
text = String.valueOf(fromHtml(text));
|
||||
String createdBy = "";//site.getStringArray("createdByDisplayName");
|
||||
long createdOn = UtilsDate.stringToMillis(site.getString("startDateRestriction"), "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
|
||||
ArrayList<String> urls = new ArrayList<>();
|
||||
|
||||
announcements.add(new Announcement(id, title, text, createdBy, createdOn, urls));
|
||||
} catch (JSONException e) {
|
||||
log.e(new NetworkError(101215, 403, "Cannot parse announcements!"));
|
||||
log.e("ID:", i, "JSON:", sites);
|
||||
e.printStackTrace();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
callback.onResponse(announcements);
|
||||
}, error -> {
|
||||
if (error.networkResponse.statusCode == 400)
|
||||
callback.onResponse(new ArrayList<>());
|
||||
else
|
||||
errorCallback.onError(new NetworkError(101213, error.networkResponse.statusCode, "Cannot get announcements!"));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,12 +34,12 @@ public class ModulesAssignments extends PartModules<AssignmentList> {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void upgradeKVV(final String ID, final NetworkCallback<AssignmentList> callback, final NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenKVV() == null || !mLogin.getLoginTokenKVV().isAvailable()) {
|
||||
protected void upgrade(final String ID, final NetworkCallback<AssignmentList> callback, final NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
|
||||
errorCallback.onError(new NetworkError(101304, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
get(String.format(Constants.WB_SERVER_URL +"direct/assignment/site/%s.json?_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
|
||||
get(String.format("https://kvv.imp.fu-berlin.de/direct/assignment/site/%s.json", ID), mLogin.getLoginToken().getCookies(), response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(101301, 403, "No assignments retrieved!"));
|
||||
@@ -80,12 +80,11 @@ public class ModulesAssignments extends PartModules<AssignmentList> {
|
||||
}
|
||||
}
|
||||
|
||||
callback.onResponse(assignments);
|
||||
// Empty assignments *may be* because token is invalid -> check
|
||||
if (assignments.size() == 0)
|
||||
mLogin.testLoginToken(token -> callback.onResponse(assignments), errorCallback);
|
||||
else
|
||||
callback.onResponse(assignments);
|
||||
}, error -> errorCallback.onError(new NetworkError(101303, error.networkResponse.statusCode, "Cannot get assignments!")));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void upgradeBB(String ID, NetworkCallback<AssignmentList> callback, NetworkErrorCallback errorCallback) {
|
||||
callback.onResponse(new AssignmentList());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,29 +1,20 @@
|
||||
package de.sebse.fuplanner.services.kvv;
|
||||
|
||||
import android.content.Context;
|
||||
import android.text.TextUtils;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.regex.MatchResult;
|
||||
|
||||
import de.sebse.fuplanner.services.kvv.types.Event;
|
||||
import de.sebse.fuplanner.services.kvv.types.EventList;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
import de.sebse.fuplanner.services.kvv.types.Semester;
|
||||
import de.sebse.fuplanner.tools.Regex;
|
||||
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;
|
||||
|
||||
public class ModulesEvents extends PartModules<EventList> {
|
||||
|
||||
private ModulesEventsNumber mEventNumbers;
|
||||
|
||||
ModulesEvents(Login login, ModulesList list, Context context) {
|
||||
super(login, list, context);
|
||||
}
|
||||
@@ -41,12 +32,12 @@ public class ModulesEvents extends PartModules<EventList> {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void upgradeKVV(final String ID, final NetworkCallback<EventList> callback, final NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenKVV() == null || !mLogin.getLoginTokenKVV().isAvailable()) {
|
||||
protected void upgrade(final String ID, final NetworkCallback<EventList> callback, final NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
|
||||
errorCallback.onError(new NetworkError(101404, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
get(String.format(Constants.WB_SERVER_URL +"direct/calendar/site/%s.json?detailed=true&_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
|
||||
get(String.format("https://kvv.imp.fu-berlin.de/direct/calendar/site/%s.json?detailed=true", ID), mLogin.getLoginToken().getCookies(), response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(101401, 403, "No events retrieved!"));
|
||||
@@ -82,100 +73,11 @@ public class ModulesEvents extends PartModules<EventList> {
|
||||
}
|
||||
}
|
||||
|
||||
callback.onResponse(events);
|
||||
// Empty events *may be* because token is invalid -> check
|
||||
if (events.size() == 0)
|
||||
mLogin.testLoginToken(token -> callback.onResponse(events), errorCallback);
|
||||
else
|
||||
callback.onResponse(events);
|
||||
}, error -> errorCallback.onError(new NetworkError(101403, error.networkResponse.statusCode, "Cannot get events!")));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void upgradeBB(String ID, NetworkCallback<EventList> callback, NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenBB() == null || !mLogin.getLoginTokenBB().isAvailable()) {
|
||||
errorCallback.onError(new NetworkError(101414, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
this.mList.recv(modules -> {
|
||||
Modules.Module module = modules.get(ID);
|
||||
if (module == null) {
|
||||
errorCallback.onError(new NetworkError(101416, 400, "Cannot get events!"));
|
||||
return;
|
||||
}
|
||||
Semester latestSemester = modules.getLatestSemester();
|
||||
if (module.semester != null && !module.semester.equals(latestSemester)) {
|
||||
if (module.events != null) {
|
||||
callback.onResponse(module.events);
|
||||
} else {
|
||||
callback.onResponse(new EventList());
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (module.lvNumber.size() == 0) {
|
||||
// Events not available
|
||||
callback.onResponse(new EventList());
|
||||
return;
|
||||
}
|
||||
eventNumbers().getVVNumber(module.lvNumber.iterator().next(), vvNumber -> {
|
||||
if (vvNumber.equals("")) {
|
||||
// Events not available
|
||||
callback.onResponse(new EventList());
|
||||
//errorCallback.onError(new NetworkError(101410, 403, "Cannot get events!"));
|
||||
return;
|
||||
}
|
||||
// 462854, 465661, 462126, 463782, 437050, 433843, 471614, 464205
|
||||
//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)];
|
||||
//vvNumber = "462126";
|
||||
super.get(String.format("https://www.fu-berlin.de/vv/de/lv/%s", vvNumber), null, response1 -> {
|
||||
String body = response1.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(101411, 400, "Cannot get events!"));
|
||||
return;
|
||||
}
|
||||
EventList events = new EventList();
|
||||
for (MatchResult match : Regex.allMatches("<span id=\"link_to_details_[^~]*?</span>", body)) {
|
||||
String entry = match.group(0);
|
||||
String date;
|
||||
String title = "";
|
||||
try {
|
||||
date = Regex.regex("[A-Z][a-z], [0-9]{2}\\.[0-9]{2}\\.[0-9]{4} [0-9]{2}:[0-9]{2} - [0-9]{2}:[0-9]{2}", entry, 0);
|
||||
} catch (NoSuchFieldException e) {
|
||||
log.e(new NetworkError(101412, 400, "Cannot get events!"));
|
||||
e.printStackTrace();
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
title = Regex.regex("<div class=\"course_title\">([^<]*?)</div>", entry, 1);
|
||||
} catch (NoSuchFieldException ignored) {}
|
||||
if (TextUtils.isEmpty(title))
|
||||
title = module.title;
|
||||
ArrayList<String> docents = new ArrayList<>();
|
||||
ArrayList<String> locations = new ArrayList<>();
|
||||
for (MatchResult match1 : Regex.allMatches("<div class=\"appointment_details_column\">[^~]*?</div>", entry)) {
|
||||
if (match1.group(0).contains("Dozenten:")) {
|
||||
for (MatchResult match2 : Regex.allMatches(">([^>]*?)<small class=\"phone_portal\">", match1.group(0))) {
|
||||
docents.add(match2.group(0).trim());
|
||||
}
|
||||
} else if (match1.group(0).contains("Räume:")) {
|
||||
for (MatchResult match2 : Regex.allMatches("</b>([^~]*?)</p>", match1.group(0))) {
|
||||
locations.add(match2.group(1).trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
long start = UtilsDate.stringToMillis(date.substring(4, 20), "dd.MM.yyyy HH:mm");
|
||||
long duration = (Integer.parseInt(date.substring(23, 25))-Integer.parseInt(date.substring(15, 17)))*60
|
||||
+ Integer.parseInt(date.substring(26, 28))-Integer.parseInt(date.substring(18, 20));
|
||||
duration = duration*60*1000-1;
|
||||
String locationString = TextUtils.join(", ", locations);
|
||||
events.add(new Event("", "Class section - Lecture", title, duration, start, ID, locationString));
|
||||
}
|
||||
callback.onResponse(events);
|
||||
}, error -> errorCallback.onError(new NetworkError(101415, error.networkResponse.statusCode, "Cannot get events!")));
|
||||
}, errorCallback);
|
||||
}, errorCallback);
|
||||
}
|
||||
|
||||
private ModulesEventsNumber eventNumbers() {
|
||||
if (mEventNumbers == null)
|
||||
mEventNumbers = new ModulesEventsNumber(getContext());
|
||||
return mEventNumbers;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
package de.sebse.fuplanner.services.kvv;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import de.sebse.fuplanner.services.kvv.types.CacheBBEventNumber;
|
||||
import de.sebse.fuplanner.tools.Regex;
|
||||
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;
|
||||
|
||||
class ModulesEventsNumber extends HTTPService {
|
||||
private final CacheBBEventNumber mStorage;
|
||||
|
||||
ModulesEventsNumber(Context context) {
|
||||
super(context);
|
||||
CacheBBEventNumber storage = null;
|
||||
try {
|
||||
storage = CacheBBEventNumber.load(context);
|
||||
} catch (IOException | ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
if (storage == null) {
|
||||
mStorage = new CacheBBEventNumber();
|
||||
} else {
|
||||
mStorage = storage;
|
||||
}
|
||||
}
|
||||
|
||||
void getVVNumber(String lvNumber, NetworkCallback<String> callback, NetworkErrorCallback errorCallback) {
|
||||
String vvNumber = mStorage.getVVNumber(lvNumber);
|
||||
if (vvNumber != null) {
|
||||
callback.onResponse(vvNumber);
|
||||
return;
|
||||
}
|
||||
|
||||
super.head(String.format("https://www.fu-berlin.de/vv/de/search?utf8=✓&query=%s", lvNumber), null, response -> {
|
||||
String location = response.getHeaders().get("Location");
|
||||
if (location == null) {
|
||||
// Events not available
|
||||
callback.onResponse("");
|
||||
//errorCallback.onError(new NetworkError(101410, 403, "Cannot get events!"));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
String group = Regex.regex("lv/([0-9]+)\\?", location);
|
||||
mStorage.setVVNumber(lvNumber, group);
|
||||
try {
|
||||
mStorage.save(getContext());
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
callback.onResponse(group);
|
||||
} catch (NoSuchFieldException e) {
|
||||
errorCallback.onError(new NetworkError(102201, 400, "Cannot get events!"));
|
||||
e.printStackTrace();
|
||||
}
|
||||
}, error -> errorCallback.onError(new NetworkError(102202, error.networkResponse.statusCode, "Error retrieving lecturer!")));
|
||||
}
|
||||
}
|
||||
@@ -6,44 +6,45 @@ 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<Gradebook> {
|
||||
public class ModulesGradebook extends PartModules<ArrayList<Grade>> {
|
||||
|
||||
ModulesGradebook(Login login, ModulesList list, Context context) {
|
||||
super(login, list, context);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Gradebook getPart(Modules.Module module) {
|
||||
protected ArrayList<Grade> getPart(Modules.Module module) {
|
||||
return module.gradebook;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean setPart(Modules.Module module, Gradebook part) {
|
||||
protected boolean setPart(Modules.Module module, ArrayList<Grade> 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<Gradebook> callback, final NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenKVV() == null || !mLogin.getLoginTokenKVV().isAvailable()) {
|
||||
protected void upgrade(final String ID, final NetworkCallback<ArrayList<Grade>> callback, final NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
|
||||
errorCallback.onError(new NetworkError(101504, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
super.get(String.format(Constants.WB_SERVER_URL +"direct/gradebook/site/%s.json", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
|
||||
super.get(String.format("https://kvv.imp.fu-berlin.de/direct/gradebook/site/%s.json", ID), mLogin.getLoginToken().getCookies(), response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(101501, 403, "No gradebook retrieved!"));
|
||||
return;
|
||||
}
|
||||
Gradebook gradebook = new Gradebook();
|
||||
ArrayList<Grade> gradebook = new ArrayList<>();
|
||||
JSONArray sites;
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
@@ -61,7 +62,7 @@ public class ModulesGradebook extends PartModules<Gradebook> {
|
||||
String itemName = site.optString("itemName", null);
|
||||
double maxPoints = site.optDouble("points", -1);
|
||||
|
||||
gradebook.addGrade(new Grade(itemName, grade, maxPoints));
|
||||
gradebook.add(0, new Grade(itemName, grade, maxPoints));
|
||||
} catch (JSONException e) {
|
||||
log.e(new NetworkError(101505, 403, "Cannot parse gradebook!"));
|
||||
log.e("ID:", i, "JSON:", sites);
|
||||
@@ -70,85 +71,6 @@ public class ModulesGradebook extends PartModules<Gradebook> {
|
||||
}
|
||||
}
|
||||
callback.onResponse(gradebook);
|
||||
}, error -> {
|
||||
if (error.networkResponse.statusCode == 400)
|
||||
callback.onResponse(new Gradebook());
|
||||
else
|
||||
errorCallback.onError(new NetworkError(101503, error.networkResponse.statusCode, "Cannot get gradebook!"));
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
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;
|
||||
}
|
||||
super.get(String.format("https://lms.fu-berlin.de/learn/api/public/v2/courses/%s/gradebook/columns", ID), mLogin.getLoginTokenBB().getCookies(), response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(101511, 400, "No gradebook columns retrieved!"));
|
||||
return;
|
||||
}
|
||||
JSONArray gradeColumns;
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
gradeColumns = json.getJSONArray("results");
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
errorCallback.onError(new NetworkError(101512, 400, "Cannot parse gradebook columns!"));
|
||||
return;
|
||||
}
|
||||
|
||||
get(String.format("https://lms.fu-berlin.de/learn/api/public/v2/courses/%s/gradebook/users/%s", ID, mLogin.getLoginTokenBB().getId()), mLogin.getLoginTokenBB().getCookies(), response1 -> {
|
||||
String body1 = response1.getParsed();
|
||||
if (body1 == null) {
|
||||
errorCallback.onError(new NetworkError(101513, 400, "No gradebook entries retrieved!"));
|
||||
return;
|
||||
}
|
||||
JSONArray grades;
|
||||
try {
|
||||
JSONObject json = new JSONObject(body1);
|
||||
grades = json.getJSONArray("results");
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
errorCallback.onError(new NetworkError(101514, 400, "Cannot parse gradebook entries!"));
|
||||
return;
|
||||
}
|
||||
|
||||
Gradebook result = new Gradebook();
|
||||
for (int i = 0; i < grades.length(); i++) {
|
||||
for (int j = 0; j < gradeColumns.length(); j++) {
|
||||
try {
|
||||
JSONObject grade = grades.getJSONObject(i);
|
||||
JSONObject column = gradeColumns.getJSONObject(j);
|
||||
String grade_id = grade.getString("columnId");
|
||||
String column_id = column.getString("id");
|
||||
if (!grade_id.equals(column_id))
|
||||
continue;
|
||||
String name = column.getString("name");
|
||||
JSONObject displayGrade = grade.optJSONObject("displayGrade");
|
||||
double points = displayGrade != null ? displayGrade.optDouble("score", 0) : 0;
|
||||
JSONObject score = column.optJSONObject("score");
|
||||
double maxPoints = score != null ? score.optDouble("possible", 0) : 0;
|
||||
|
||||
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);
|
||||
log.e("ID:", j, "JSON-gradeColumns:", gradeColumns);
|
||||
e.printStackTrace();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
callback.onResponse(result);
|
||||
}, error -> errorCallback.onError(new NetworkError(101516, error.networkResponse.statusCode, "Cannot get gradebook columns!")));
|
||||
}, error -> {
|
||||
if (error.networkResponse.statusCode == 403)
|
||||
callback.onResponse(new Gradebook());
|
||||
else
|
||||
errorCallback.onError(new NetworkError(101517, error.networkResponse.statusCode, "Cannot get gradebook entries!"));
|
||||
});
|
||||
}, error -> errorCallback.onError(new NetworkError(101503, error.networkResponse.statusCode, "Cannot get gradebook!")));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,11 +12,7 @@ import java.io.IOException;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.regex.MatchResult;
|
||||
import java.util.regex.Matcher;
|
||||
|
||||
import androidx.arch.core.util.Function;
|
||||
import de.sebse.fuplanner.services.kvv.types.CacheBBCourse;
|
||||
import de.sebse.fuplanner.services.kvv.types.CacheKVVCourse;
|
||||
import de.sebse.fuplanner.services.kvv.types.Lecturer;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
import de.sebse.fuplanner.services.kvv.types.Semester;
|
||||
@@ -27,16 +23,13 @@ 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.Part.RETRY_COUNT;
|
||||
import static de.sebse.fuplanner.services.kvv.PartModules.RETRY_COUNT;
|
||||
|
||||
public class ModulesList extends HTTPService {
|
||||
private final Login mLogin;
|
||||
private final KVVListener mListener;
|
||||
@Nullable private Modules mModules;
|
||||
private ModulesListLecturer mLecturer;
|
||||
private CacheBBCourse mBBCache;
|
||||
private final NewAsyncQueue mQueue = new NewAsyncQueue();
|
||||
private CacheKVVCourse mKVVCache;
|
||||
|
||||
ModulesList(Login login, KVVListener listener, Context context) {
|
||||
super(context);
|
||||
@@ -53,28 +46,14 @@ public class ModulesList extends HTTPService {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void reloadIfOutdated() {
|
||||
try {
|
||||
if (mModules != null && mModules.isNewerVersionInStorage(getContext())) {
|
||||
restore();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public void find(String moduleID, NetworkCallback<Modules.Module> moduleNetworkCallback, NetworkErrorCallback errorCallback) {
|
||||
find(moduleID, moduleNetworkCallback, errorCallback, RETRY_COUNT);
|
||||
}
|
||||
|
||||
private void find(String moduleID, NetworkCallback<Modules.Module> moduleNetworkCallback, NetworkErrorCallback errorCallback, int retries) {
|
||||
if (mModules != null &&
|
||||
mLogin.getLoginTokenKVV() != null && mLogin.getLoginTokenKVV().isOtherUser(mModules.getUsername()) &&
|
||||
mLogin.getLoginTokenBB() != null && mLogin.getLoginTokenBB().isOtherUser(mModules.getUsername())
|
||||
)
|
||||
if (mModules != null && mLogin.getLoginToken() != null && mLogin.getLoginToken().isOtherUser(mModules.getUsername()))
|
||||
delete();
|
||||
if (retries < 0) {
|
||||
log.t("Too many retires", retries);
|
||||
errorCallback.onError(new NetworkError(101107, -1, "Too many retries!"));
|
||||
return;
|
||||
}
|
||||
@@ -102,12 +81,10 @@ public class ModulesList extends HTTPService {
|
||||
try {
|
||||
this.mModules = Modules.load(getContext());
|
||||
} catch (FileNotFoundException ignored) {
|
||||
} catch (IOException | ClassNotFoundException e) {
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} catch (ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
delete();
|
||||
}
|
||||
if (this.mModules == null) {
|
||||
recv(success -> {}, log::e, true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,325 +104,101 @@ public class ModulesList extends HTTPService {
|
||||
}
|
||||
|
||||
private void recv(final NetworkCallback<Modules> callback, final NetworkErrorCallback errorCallback, boolean forceRefresh, final int retries) {
|
||||
if (mModules != null &&
|
||||
mLogin.getLoginTokenKVV() != null && mLogin.getLoginTokenKVV().isOtherUser(mModules.getUsername()) &&
|
||||
mLogin.getLoginTokenBB() != null && mLogin.getLoginTokenBB().isOtherUser(mModules.getUsername())
|
||||
)
|
||||
if (mModules != null && mLogin.getLoginToken() != null && mLogin.getLoginToken().isOtherUser(mModules.getUsername()))
|
||||
delete();
|
||||
if (this.mModules != null && !forceRefresh) {
|
||||
callback.onResponse(this.mModules);
|
||||
return;
|
||||
}
|
||||
mQueue.add(() -> {
|
||||
if (mLogin.isLoginPending()) {
|
||||
mLogin.restoreOnlineLogin(resCode -> {
|
||||
mQueue.next();
|
||||
});
|
||||
} else {
|
||||
if (this.mModules != null && !forceRefresh) {
|
||||
callback.onResponse(this.mModules);
|
||||
mQueue.next();
|
||||
return;
|
||||
}
|
||||
});
|
||||
mQueue.add(() -> {
|
||||
Function<Integer, NetworkErrorCallback> errorFunc = ((Integer errorCode) -> (error -> {
|
||||
this.upgrade(success -> {
|
||||
if (this.mModules == null)
|
||||
this.mModules = success;
|
||||
else if (this.mModules.updateList(success)) {
|
||||
mListener.onModuleListChange();
|
||||
store();
|
||||
}
|
||||
callback.onResponse(this.mModules);
|
||||
mQueue.next();
|
||||
}, error -> {
|
||||
if (retries > 0 && (error.getHttpStatus() == 401 || error.getHttpStatus() == 403)) {
|
||||
mLogin.refreshLogin(success -> {
|
||||
recv(callback, errorCallback, forceRefresh, retries - 1);
|
||||
recv(callback, errorCallback, forceRefresh, retries-1);
|
||||
mQueue.next();
|
||||
}, error1 -> {
|
||||
errorCallback.onError(error1);
|
||||
mQueue.next();
|
||||
}, errorCode);
|
||||
});
|
||||
return;
|
||||
}
|
||||
errorCallback.onError(error);
|
||||
mQueue.next();
|
||||
}));
|
||||
this.upgradeKVV(successKVV -> {
|
||||
this.upgradeBB(successKVV, success -> {
|
||||
if (this.mModules == null)
|
||||
this.mModules = success;
|
||||
else if (this.mModules.updateList(success)) {
|
||||
mListener.onModuleListChange();
|
||||
store();
|
||||
}
|
||||
callback.onResponse(this.mModules);
|
||||
mQueue.next();
|
||||
}, errorFunc.apply(Login.LOGOUT_BB));
|
||||
}, errorFunc.apply(Login.LOGOUT_KVV));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private void upgradeKVV(final NetworkCallback<Modules> callback, final NetworkErrorCallback errorCallback) {
|
||||
NetworkCallback<Modules> successCallback = (modules -> {
|
||||
try {
|
||||
cacheKVVCourse().save(getContext());
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
callback.onResponse(modules);
|
||||
});
|
||||
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenKVV() == null) {
|
||||
errorCallback.onError(new NetworkError(101110, 500, "Currently running in offline mode!"));
|
||||
private void upgrade(final NetworkCallback<Modules> callback, final NetworkErrorCallback errorCallback) {
|
||||
log.d(mLogin.isInOnlineMode(), mLogin.getLoginToken());
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
|
||||
errorCallback.onError(new NetworkError(101105, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
Modules modules = new Modules(mLogin.getLoginTokenKVV().getUsername());
|
||||
if (!mLogin.getLoginTokenKVV().isAvailable()) {
|
||||
callback.onResponse(modules);
|
||||
return;
|
||||
}
|
||||
get(Constants.WB_SERVER_URL +"direct/membership.json?_validateSession=", mLogin.getLoginTokenKVV().getCookies(), response -> {
|
||||
get("https://kvv.imp.fu-berlin.de/direct/site.json", mLogin.getLoginToken().getCookies(), response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(101111, 403, "No membership list retrieved!"));
|
||||
errorCallback.onError(new NetworkError(101101, 403, "No module list retrieved!"));
|
||||
return;
|
||||
}
|
||||
JSONArray memberships;
|
||||
Modules modules = new Modules(mLogin.getLoginToken().getUsername());
|
||||
JSONArray sites;
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
memberships = json.getJSONArray("membership_collection");
|
||||
sites = json.getJSONArray("site_collection");
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
errorCallback.onError(new NetworkError(101112, 403, "Cannot parse membership list!"));
|
||||
errorCallback.onError(new NetworkError(101102, 403, "Cannot parse module list!"));
|
||||
return;
|
||||
}
|
||||
final int[] latch = {memberships.length()};
|
||||
if (latch[0] == 0) {
|
||||
successCallback.onResponse(modules);
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < memberships.length(); i++) {
|
||||
for (int i = 0; i < sites.length(); i++) {
|
||||
try {
|
||||
JSONObject membership = memberships.getJSONObject(i);
|
||||
String locationReference = membership.getString("locationReference");
|
||||
String courseId = Regex.regex("/site/([^/]*)", locationReference);
|
||||
Modules.Module kvvCourse = cacheKVVCourse().getKVVCourse(courseId);
|
||||
if (kvvCourse != null) {
|
||||
kvvCourse = kvvCourse.clone();
|
||||
modules.addModule(kvvCourse);
|
||||
if (--latch[0] == 0) successCallback.onResponse(modules);
|
||||
JSONObject site = sites.getJSONObject(i);
|
||||
String semester_string = site.getJSONObject("props").optString("term_eid", null);
|
||||
if (semester_string == null)
|
||||
continue;
|
||||
Semester semester = new Semester(semester_string);
|
||||
HashSet<String> lvNumbers = new HashSet<>();
|
||||
String kvv_lvnumbers = site.getJSONObject("props").optString("kvv_lvnumbers", null);
|
||||
if (kvv_lvnumbers != null) for (MatchResult matchResult : Regex.allMatches("[0-9]+", kvv_lvnumbers)) {
|
||||
lvNumbers.add(matchResult.group());
|
||||
}
|
||||
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!"));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
JSONObject site = new JSONObject(body1);
|
||||
|
||||
String semester_string = site.getJSONObject("props").optString("term_eid", null);
|
||||
Semester semester;
|
||||
if (semester_string == null)
|
||||
semester = null;
|
||||
else
|
||||
semester = new Semester(semester_string);
|
||||
HashSet<String> lvNumbers = new HashSet<>();
|
||||
String kvv_lvnumbers = site.getJSONObject("props").optString("kvv_lvnumbers", null);
|
||||
if (kvv_lvnumbers != null)
|
||||
for (MatchResult matchResult : Regex.allMatches("[0-9]+", kvv_lvnumbers)) {
|
||||
lvNumbers.add(matchResult.group());
|
||||
}
|
||||
String title = site.getString("entityTitle");
|
||||
LinkedHashSet<Lecturer> lecturers = new LinkedHashSet<>();
|
||||
String kvv_lecturers = site.getJSONObject("props").optString("kvv_lecturers", null);
|
||||
if (kvv_lecturers != null) for (String lecturer : kvv_lecturers.split("#")) {
|
||||
if (lecturer.length() > 2)
|
||||
lecturers.add(new Lecturer(lecturer));
|
||||
}
|
||||
String type = site.getJSONObject("props").optString("kvv_coursetype", "Projekt");
|
||||
String description = site.optString("description", "");
|
||||
description = String.valueOf(PartModules.fromHtml(description));
|
||||
String id = site.getString("id");
|
||||
Modules.Module module = modules.addModule(semester, lvNumbers, title, lecturers, type, description, id, Modules.TYPE_KVV);
|
||||
cacheKVVCourse().setKVVCourse(courseId, module.clone());
|
||||
if (--latch[0] == 0) successCallback.onResponse(modules);
|
||||
} catch (JSONException e) {
|
||||
log.e(new NetworkError(101114, 403, "Cannot parse site!"));
|
||||
log.e("JSON:", body1);
|
||||
e.printStackTrace();
|
||||
} catch (NoSuchFieldException e) {
|
||||
log.e(new NetworkError(101115, 403, "Cannot parse site!"));
|
||||
e.printStackTrace();
|
||||
}
|
||||
}, error -> errorCallback.onError(new NetworkError(101116, error.networkResponse.statusCode, "Cannot get parse!")));
|
||||
String title = site.getString("entityTitle");
|
||||
LinkedHashSet<Lecturer> lecturers = new LinkedHashSet<>();
|
||||
String kvv_lecturers = site.getJSONObject("props").optString("kvv_lecturers", null);
|
||||
if (kvv_lecturers != null) for (String lecturer : kvv_lecturers.split("#")) {
|
||||
if (lecturer.length() > 2)
|
||||
lecturers.add(new Lecturer(lecturer));
|
||||
}
|
||||
String type = site.getJSONObject("props").optString("kvv_coursetype", null);
|
||||
String description = site.optString("description", "");
|
||||
description = String.valueOf(PartModules.fromHtml(description));
|
||||
String id = site.getString("id");
|
||||
modules.addModule(semester, lvNumbers, title, lecturers, type, description, id);
|
||||
} catch (JSONException e) {
|
||||
log.e("ID:", i, "JSON:", memberships);
|
||||
log.e(new NetworkError(101103, 403, "Cannot parse module list!"));
|
||||
log.e("ID:", i, "JSON:", sites);
|
||||
e.printStackTrace();
|
||||
errorCallback.onError(new NetworkError(101117, 403, "Cannot parse membership list!"));
|
||||
return;
|
||||
} catch (NoSuchFieldException e) {
|
||||
log.e("ID:", i, "JSON:", memberships);
|
||||
e.printStackTrace();
|
||||
errorCallback.onError(new NetworkError(101118, 403, "Cannot parse membership list!"));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}, error -> errorCallback.onError(new NetworkError(101119, error.networkResponse.statusCode, "Cannot get membership list!")));
|
||||
}
|
||||
|
||||
private void upgradeBB(final Modules modulesKVV, final NetworkCallback<Modules> callback, final NetworkErrorCallback errorCallback) {
|
||||
NetworkCallback<Modules> successCallback = (modules -> {
|
||||
try {
|
||||
cacheBBCourse().save(getContext());
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
callback.onResponse(modules);
|
||||
});
|
||||
NetworkCallback<Modules> fastCallback = (modules -> {
|
||||
mListener.onModuleListPartiallyUpdated(modules);
|
||||
try {
|
||||
cacheBBCourse().save(getContext());
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
mListener.onModuleListPartiallyUpdated(modules);
|
||||
});
|
||||
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenBB() == null) {
|
||||
errorCallback.onError(new NetworkError(101120, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
if (!mLogin.getLoginTokenBB().isAvailable()) {
|
||||
callback.onResponse(modulesKVV);
|
||||
return;
|
||||
}
|
||||
get(String.format("https://lms.fu-berlin.de/learn/api/public/v1/users/%s/courses?fields=courseId,dataSourceId", mLogin.getLoginTokenBB().getId()), mLogin.getLoginTokenBB().getCookies(), response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(101121, 403, "No module list retrieved!"));
|
||||
return;
|
||||
}
|
||||
final JSONArray[] sites = new JSONArray[1];
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
sites[0] = json.getJSONArray("results");
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
errorCallback.onError(new NetworkError(101122, 403, "Cannot parse module list!"));
|
||||
return;
|
||||
}
|
||||
final int[] latch = {sites[0].length()};
|
||||
// fetching lecturers takes a lot of time, send success twice: first without lecturers
|
||||
final int[] latchNoLecturers = {sites[0].length()};
|
||||
if (sites[0].length() == 0) {
|
||||
successCallback.onResponse(modulesKVV);
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < sites[0].length(); i++) {
|
||||
try {
|
||||
JSONObject site = sites[0].getJSONObject(i);
|
||||
String courseId = site.getString("courseId");
|
||||
if (cacheBBCourse().hasKVVCourseID(courseId)) {
|
||||
if (--latchNoLecturers[0] == 0) fastCallback.onResponse(modulesKVV);
|
||||
if (--latch[0] == 0) successCallback.onResponse(modulesKVV);
|
||||
continue;
|
||||
}
|
||||
Modules.Module bbCourse = cacheBBCourse().getBBCourse(courseId);
|
||||
if (bbCourse != null) {
|
||||
bbCourse = bbCourse.clone();
|
||||
modulesKVV.addModule(bbCourse);
|
||||
if (--latchNoLecturers[0] == 0) fastCallback.onResponse(modulesKVV);
|
||||
if (--latch[0] == 0) successCallback.onResponse(modulesKVV);
|
||||
continue;
|
||||
}
|
||||
get(String.format("https://lms.fu-berlin.de/learn/api/v1/courses/%s?fields=name,courseId,description", courseId), mLogin.getLoginTokenBB().getCookies(), response1 -> {
|
||||
String body1 = response1.getParsed();
|
||||
if (body1 == null) {
|
||||
errorCallback.onError(new NetworkError(101124, 403, "No course entry retrieved!"));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
JSONObject json = new JSONObject(body1);
|
||||
String name = json.getString("name");
|
||||
String description = json.optString("description", null);
|
||||
String type, lvNumber, semYear, semType;
|
||||
Semester semester = null;
|
||||
HashSet<String> lvNumberSet = new HashSet<>();
|
||||
boolean found = false;
|
||||
try {
|
||||
Matcher match = Regex.match("[A-Za-z0-9]*_([A-Za-z0-9]*)_([A-Za-z0-9]*)_([0-9]{2,})([WS]+)", json.getString("courseId"));
|
||||
type = match.group(1);
|
||||
lvNumber = match.group(2);
|
||||
semYear = match.group(3);
|
||||
semType = match.group(4);
|
||||
semester = new Semester(semType.equals("W") ? Semester.SEM_WS : Semester.SEM_SS, Integer.valueOf(semYear) % 100);
|
||||
lvNumberSet.add(lvNumber);
|
||||
for (Modules.Module module: modulesKVV) {
|
||||
if (module.lvNumber.contains(lvNumber)) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (NoSuchFieldException | NumberFormatException e) {
|
||||
log.e(e);
|
||||
type = "Projekt";
|
||||
}
|
||||
if (!found) {
|
||||
Modules.Module module = modulesKVV.addModule(semester, lvNumberSet, name, new LinkedHashSet<>(), type, description, courseId, Modules.TYPE_BB);
|
||||
lecturer().getBBLecturers(courseId, success -> {
|
||||
module.setLecturers(success);
|
||||
cacheBBCourse().setBBCourse(courseId, module.clone());
|
||||
if (--latch[0] == 0) successCallback.onResponse(modulesKVV);
|
||||
}, error -> {
|
||||
log.e(error);
|
||||
if (--latch[0] == 0) successCallback.onResponse(modulesKVV);
|
||||
});
|
||||
if (--latchNoLecturers[0] == 0) fastCallback.onResponse(modulesKVV);
|
||||
} else {
|
||||
cacheBBCourse().addKVVCourseID(courseId);
|
||||
if (--latchNoLecturers[0] == 0) fastCallback.onResponse(modulesKVV);
|
||||
if (--latch[0] == 0) successCallback.onResponse(modulesKVV);
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
log.e(new NetworkError(101125, 403, "Cannot parse course entry!"));
|
||||
if (--latchNoLecturers[0] == 0) fastCallback.onResponse(modulesKVV);
|
||||
if (--latch[0] == 0) successCallback.onResponse(modulesKVV);
|
||||
}
|
||||
}, error -> errorCallback.onError(new NetworkError(101126, error.networkResponse.statusCode, "Cannot get module list!")));
|
||||
} catch (JSONException e) {
|
||||
log.e(new NetworkError(101123, 403, "Cannot parse course entry"));
|
||||
log.e("ID:", i, "JSON:", sites[0]);
|
||||
log.e(new NetworkError(101106, 403, "Cannot parse module list!"));
|
||||
log.e("ID:", i, "JSON:", sites);
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}, error -> errorCallback.onError(new NetworkError(101125, error.networkResponse.statusCode, "Cannot get module list!")));
|
||||
}
|
||||
|
||||
|
||||
|
||||
private ModulesListLecturer lecturer() {
|
||||
if (mLecturer == null)
|
||||
mLecturer = new ModulesListLecturer(getContext(), mLogin);
|
||||
return mLecturer;
|
||||
}
|
||||
|
||||
private CacheBBCourse cacheBBCourse() {
|
||||
if (mBBCache == null) {
|
||||
try {
|
||||
mBBCache = CacheBBCourse.load(getContext());
|
||||
} catch (IOException | ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
if (mBBCache == null)
|
||||
mBBCache = new CacheBBCourse();
|
||||
return mBBCache;
|
||||
}
|
||||
|
||||
private CacheKVVCourse cacheKVVCourse() {
|
||||
if (mKVVCache == null) {
|
||||
try {
|
||||
mKVVCache = CacheKVVCourse.load(getContext());
|
||||
} catch (IOException | ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
if (mKVVCache == null)
|
||||
mKVVCache = new CacheKVVCourse();
|
||||
return mKVVCache;
|
||||
// Empty module *may be* because token is invalid -> check
|
||||
if (modules.size() == 0)
|
||||
mLogin.testLoginToken(token -> callback.onResponse(modules), errorCallback);
|
||||
else
|
||||
callback.onResponse(modules);
|
||||
}, error -> errorCallback.onError(new NetworkError(101104, error.networkResponse.statusCode, "Cannot get module list!")));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,155 +0,0 @@
|
||||
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.CacheLecturer;
|
||||
import de.sebse.fuplanner.services.kvv.types.Lecturer;
|
||||
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;
|
||||
|
||||
class ModulesListLecturer extends HTTPService {
|
||||
private final Login mLogin;
|
||||
private final CacheLecturer mStorage;
|
||||
|
||||
ModulesListLecturer(Context context, Login login) {
|
||||
super(context);
|
||||
this.mLogin = login;
|
||||
CacheLecturer storage = null;
|
||||
try {
|
||||
storage = CacheLecturer.load(context);
|
||||
} catch (IOException | ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
if (storage == null) {
|
||||
mStorage = new CacheLecturer();
|
||||
} else {
|
||||
mStorage = storage;
|
||||
}
|
||||
}
|
||||
|
||||
void getBBLecturers(String moduleID, NetworkCallback<LinkedHashSet<Lecturer>> callback, NetworkErrorCallback errorCallback) {
|
||||
ArrayList<String> lecturerString = mStorage.getLecturersPerCourse(moduleID);
|
||||
if (lecturerString != null) {
|
||||
final int[] latch = {lecturerString.size()};
|
||||
LinkedHashSet<Lecturer> lecturers = new LinkedHashSet<>();
|
||||
for (String userId : lecturerString) {
|
||||
getBBLecturer(userId, success -> {
|
||||
lecturers.add(success);
|
||||
if (--latch[0] == 0) callback.onResponse(lecturers);
|
||||
}, error -> {
|
||||
log.e(error);
|
||||
if (--latch[0] == 0) callback.onResponse(lecturers);
|
||||
});
|
||||
}
|
||||
if (lecturerString.size() == 0)
|
||||
callback.onResponse(lecturers);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenBB() == null || !mLogin.getLoginTokenBB().isAvailable()) {
|
||||
errorCallback.onError(new NetworkError(102100, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
|
||||
get(String.format("https://lms.fu-berlin.de/learn/api/public/v1/courses/%s/users?fields=userId,courseRoleId", moduleID), mLogin.getLoginTokenBB().getCookies(), response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(102101, 403, "No lecturers retrieved!"));
|
||||
return;
|
||||
}
|
||||
JSONArray sites;
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
sites = json.getJSONArray("results");
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
errorCallback.onError(new NetworkError(102102, 403, "Cannot parse lecturers!"));
|
||||
return;
|
||||
}
|
||||
|
||||
LinkedHashSet<Lecturer> lecturers = new LinkedHashSet<>();
|
||||
final int[] latch = {sites.length()};
|
||||
ArrayList<String> lecturerString2 = new ArrayList<>();
|
||||
NetworkCallback<LinkedHashSet<Lecturer>> successCallback = l -> {
|
||||
mStorage.setLecturersPerCourse(moduleID, lecturerString2);
|
||||
try {
|
||||
mStorage.save(getContext());
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
callback.onResponse(lecturers);
|
||||
};
|
||||
for (int i = 0; i < sites.length(); i++) {
|
||||
try {
|
||||
JSONObject lecturerJson = sites.getJSONObject(i);
|
||||
String userId = lecturerJson.getString("userId");
|
||||
String role = lecturerJson.getString("courseRoleId");
|
||||
if (!"Student".equals(role)) {
|
||||
lecturerString2.add(userId);
|
||||
getBBLecturer(userId, success -> {
|
||||
lecturers.add(success);
|
||||
if (--latch[0] == 0) successCallback.onResponse(lecturers);
|
||||
}, error -> {
|
||||
log.e(error);
|
||||
if (--latch[0] == 0) successCallback.onResponse(lecturers);
|
||||
});
|
||||
} else {
|
||||
if (--latch[0] == 0) successCallback.onResponse(lecturers);
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
log.e(new NetworkError(102103, 403, "Cannot parse lecturers!"));
|
||||
log.e("ID:", i, "JSON:", sites);
|
||||
e.printStackTrace();
|
||||
if (--latch[0] == 0) successCallback.onResponse(lecturers);
|
||||
}
|
||||
}
|
||||
}, error -> errorCallback.onError(new NetworkError(102104, error.networkResponse.statusCode, "Error retrieving lecturers!")));
|
||||
}
|
||||
|
||||
private void getBBLecturer(String lecturerID, NetworkCallback<Lecturer> callback, NetworkErrorCallback errorCallback) {
|
||||
Lecturer lecturerStore = mStorage.getLecturer(lecturerID);
|
||||
if (lecturerStore != null) {
|
||||
callback.onResponse(lecturerStore);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenBB() == null || !mLogin.getLoginTokenBB().isAvailable()) {
|
||||
errorCallback.onError(new NetworkError(102110, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
get(String.format("https://lms.fu-berlin.de/learn/api/public/v1/users/%s?fields=userName,name", lecturerID), mLogin.getLoginTokenBB().getCookies(), response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(102111, 403, "No lecturer retrieved!"));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
String userName = json.getString("userName");
|
||||
String givenName = json.getJSONObject("name").getString("given");
|
||||
String familyName = json.getJSONObject("name").getString("family");
|
||||
Lecturer lecturer = new Lecturer(givenName, familyName, userName + "@zedat.fu-berlin.de", true);
|
||||
mStorage.setLecturer(lecturerID, lecturer);
|
||||
try {
|
||||
mStorage.save(getContext());
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
callback.onResponse(lecturer);
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
errorCallback.onError(new NetworkError(102112, 403, "Cannot parse lecturer!"));
|
||||
}
|
||||
}, error -> errorCallback.onError(new NetworkError(102113, error.networkResponse.statusCode, "Error retrieving lecturer!")));
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package de.sebse.fuplanner.services.kvv;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Build;
|
||||
import android.os.Environment;
|
||||
|
||||
import org.json.JSONArray;
|
||||
@@ -10,9 +9,6 @@ import org.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
@@ -42,12 +38,12 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void upgradeKVV(final String ID, final NetworkCallback<ArrayList<Resource>> callback, final NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenKVV() == null || !mLogin.getLoginTokenKVV().isAvailable()) {
|
||||
protected void upgrade(final String ID, final NetworkCallback<ArrayList<Resource>> callback, final NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
|
||||
errorCallback.onError(new NetworkError(101604, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
get(String.format(Constants.WB_SERVER_URL +"direct/content/site/%s.json?_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
|
||||
get(String.format("https://kvv.imp.fu-berlin.de/direct/content/site/%s.json", ID), mLogin.getLoginToken().getCookies(), response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(101601, 403, "No resources retrieved!"));
|
||||
@@ -99,139 +95,23 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
|
||||
} else {
|
||||
// in sub folder
|
||||
for (Resource res2: resources) {
|
||||
try {
|
||||
String utf8Name;
|
||||
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);
|
||||
}
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
if (res2.getUrl().endsWith(res.getContainer()) && res2 instanceof Resource.Folder) {
|
||||
// Append File/Folder to list
|
||||
((Resource.Folder) res2).add(res);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
callback.onResponse(root);
|
||||
// Empty resources *may be* because token is invalid -> check
|
||||
if (resources.size() == 0)
|
||||
mLogin.testLoginToken(token -> callback.onResponse(root), errorCallback);
|
||||
else
|
||||
callback.onResponse(root);
|
||||
}, error -> errorCallback.onError(new NetworkError(101603, error.networkResponse.statusCode, "Cannot get resources!")));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void upgradeBB(String ID, NetworkCallback<ArrayList<Resource>> callback, NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenBB() == null || !mLogin.getLoginTokenBB().isAvailable()) {
|
||||
errorCallback.onError(new NetworkError(101614, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
getRescourceFolder(String.format("https://lms.fu-berlin.de/learn/api/public/v1/courses/%s/contents/", ID), ID, false, callback, errorCallback);
|
||||
//callback.onResponse(new ArrayList<>());
|
||||
}
|
||||
|
||||
private void getRescourceFolder(String url, String ID, boolean subRequest, NetworkCallback<ArrayList<Resource>> callback, NetworkErrorCallback errorCallback) {
|
||||
if (mLogin.getLoginTokenBB() == null) {
|
||||
errorCallback.onError(new NetworkError(101610, 500, "Cannot get resources!"));
|
||||
return;
|
||||
}
|
||||
get(url, mLogin.getLoginTokenBB().getCookies(), response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(101611, 403, "No resources retrieved!"));
|
||||
return;
|
||||
}
|
||||
ArrayList<Resource> resources = new ArrayList<>();
|
||||
JSONArray sites;
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
sites = json.getJSONArray("results");
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
errorCallback.onError(new NetworkError(101612, 400, "Cannot parse resources!"));
|
||||
return;
|
||||
}
|
||||
|
||||
final int[] latch = {sites.length()};
|
||||
for (int i = 0; i < sites.length(); i++) {
|
||||
try {
|
||||
JSONObject resource = sites.getJSONObject(i);
|
||||
String resid = resource.getString("id");
|
||||
String title = resource.getString("title");
|
||||
String created = resource.getString("created");
|
||||
String content = resource.getJSONObject("contentHandler").getString("id");
|
||||
long createdDate = UtilsDate.stringToMillis(created, "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
|
||||
if (content.equals("resource/x-bb-folder")) {
|
||||
String url2 = String.format("https://lms.fu-berlin.de/learn/api/public/v1/courses/%s/contents/%s", ID, resid);
|
||||
Resource.Folder folder = new Resource.Folder("", title, createdDate, url2, true, "");
|
||||
resources.add(folder);
|
||||
getRescourceFolder(String.format("https://lms.fu-berlin.de/learn/api/public/v1/courses/%s/contents/%s/children", ID, resid), ID, true, response1 -> {
|
||||
for (Resource resource1 : response1) {
|
||||
folder.add(resource1);
|
||||
}
|
||||
if (--latch[0] == 0) callback.onResponse(resources);
|
||||
}, error -> {
|
||||
if (error.getHttpStatus() == 403) {
|
||||
if (--latch[0] == 0) callback.onResponse(resources);
|
||||
} else {
|
||||
errorCallback.onError(error);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
String bodyText = resource.optString("body", "");
|
||||
bodyText = String.valueOf(PartModules.fromHtml(bodyText));
|
||||
String url2 = String.format("https://lms.fu-berlin.de/learn/api/public/v1/courses/%s/contents/%s", ID, resid);
|
||||
Resource.Document document = new Resource.Document("", title, createdDate, url2, true, "", bodyText);
|
||||
resources.add(document);
|
||||
get(String.format("https://lms.fu-berlin.de/learn/api/public/v1/courses/%s/contents/%s/attachments", ID, resid), mLogin.getLoginTokenBB().getCookies(), response1 -> {
|
||||
|
||||
String body1 = response1.getParsed();
|
||||
if (body1 == null) {
|
||||
errorCallback.onError(new NetworkError(101617, 403, "No resource attachments retrieved!"));
|
||||
return;
|
||||
}
|
||||
JSONArray attachments;
|
||||
try {
|
||||
JSONObject json = new JSONObject(body1);
|
||||
attachments = json.getJSONArray("results");
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
errorCallback.onError(new NetworkError(101618, 400, "Cannot parse resource attachments!"));
|
||||
return;
|
||||
}
|
||||
for (int j = 0; j < attachments.length(); j++) {
|
||||
try {
|
||||
JSONObject attachment = attachments.getJSONObject(j);
|
||||
String attachid = attachment.getString("id");
|
||||
String attachname = attachment.getString("fileName");
|
||||
document.addUrl(String.format("https://lms.fu-berlin.de/learn/api/public/v1/courses/%s/contents/%s/attachments/%s/download", ID, resid, attachid), attachname);
|
||||
} catch (JSONException e) {
|
||||
log.e(new NetworkError(101619, 400, "Cannot parse resource attachments!"));
|
||||
e.printStackTrace();
|
||||
log.e("ID:", j, "JSON:", attachments);
|
||||
}
|
||||
}
|
||||
if (--latch[0] == 0) callback.onResponse(resources);
|
||||
}, error -> errorCallback.onError(new NetworkError(101616, error.networkResponse.statusCode, "Cannot get resource attachments!")));
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
log.e(new NetworkError(101615, 400, "Cannot parse resources!"));
|
||||
e.printStackTrace();
|
||||
log.e("ID:", i, "JSON:", sites);
|
||||
}
|
||||
}
|
||||
}, error -> {
|
||||
if (error.networkResponse.statusCode != 403) {
|
||||
errorCallback.onError(new NetworkError(101613, error.networkResponse.statusCode, "Cannot get resources!"));
|
||||
} else {
|
||||
callback.onResponse(new ArrayList<>());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -256,11 +136,11 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
|
||||
return;
|
||||
}
|
||||
}
|
||||
fileUpgrade(filename, url, modulename, callback, error -> {
|
||||
fileUpgrade(filename, url , modulename, callback, error -> {
|
||||
if (retries >= 0 && (error.getHttpStatus() == 401 || error.getHttpStatus() == 403)) {
|
||||
mLogin.refreshLogin(success -> {
|
||||
file(filename, url, modulename, callback, errorCallback, forceRefresh, retries-1);
|
||||
}, errorCallback, url.contains("lms.fu-berlin.de") ? Login.LOGOUT_BB : Login.LOGOUT_KVV);
|
||||
}, errorCallback);
|
||||
return;
|
||||
}
|
||||
errorCallback.onError(error);
|
||||
@@ -268,19 +148,11 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
|
||||
}
|
||||
|
||||
private void fileUpgrade(String filename, String url, String modulename, final NetworkCallback<String> callback, final NetworkErrorCallback errorCallback) {
|
||||
if (url.contains("lms.fu-berlin.de")) {
|
||||
fileUpgradeBB(filename, url, modulename, callback, errorCallback);
|
||||
} else {
|
||||
fileUpgradeKVV(filename, url, modulename, callback, errorCallback);
|
||||
}
|
||||
}
|
||||
|
||||
private void fileUpgradeKVV(String filename, String url, String modulename, final NetworkCallback<String> callback, final NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenKVV() == null || !mLogin.getLoginTokenKVV().isAvailable()) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
|
||||
errorCallback.onError(new NetworkError(101604, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
get(url, mLogin.getLoginTokenKVV().getCookies(), response -> {
|
||||
get(url, mLogin.getLoginToken().getCookies(), response -> {
|
||||
if (Regex.has("\\.[Uu][Rr][Ll]$", url)){
|
||||
// Return redirected URL
|
||||
String path = response.getHeaders().get("Location");
|
||||
@@ -294,50 +166,11 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
|
||||
String path = saveFileInDownloads(filename, response.getBytes(), modulename);
|
||||
callback.onResponse(path);
|
||||
} else {
|
||||
errorCallback.onError(new NetworkError(101704, 400, "External storage not writable!"));
|
||||
errorCallback.onError(new NetworkError(101704, 403, "External storage not writable!"));
|
||||
}
|
||||
}, error -> errorCallback.onError(new NetworkError(101702, error.networkResponse.statusCode, "Cannot get file!")));
|
||||
}
|
||||
|
||||
private void fileUpgradeBB(String filename, String url, String modulename, final NetworkCallback<String> callback, final NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenBB() == null || !mLogin.getLoginTokenBB().isAvailable()) {
|
||||
errorCallback.onError(new NetworkError(101615, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
get(url, mLogin.getLoginTokenBB().getCookies(), response -> {
|
||||
if (response.getHeaders().containsKey("Location")) {
|
||||
// Return redirected URL
|
||||
String redirectUrl = response.getHeaders().get("Location");
|
||||
if (redirectUrl == null){
|
||||
redirectUrl = "";
|
||||
}
|
||||
get(redirectUrl, mLogin.getLoginTokenBB().getCookies(), response1 -> {
|
||||
if (response1.getHeaders().containsKey("Location")) {
|
||||
// Return redirected URL
|
||||
String redirectUrl2 = response1.getHeaders().get("Location");
|
||||
if (redirectUrl2 == null) {
|
||||
redirectUrl2 = "";
|
||||
} else {
|
||||
redirectUrl2 = "https://lms.fu-berlin.de" + redirectUrl2;
|
||||
}
|
||||
get(redirectUrl2, mLogin.getLoginTokenBB().getCookies(), response2 -> {
|
||||
if (response2.getBytes() == null) {
|
||||
errorCallback.onError(new NetworkError(101714, 400, "Cannot get file!"));
|
||||
} else if (isExternalStorageWritable()) {
|
||||
String path = saveFileInDownloads(filename, response2.getBytes(), modulename);
|
||||
callback.onResponse(path);
|
||||
} else {
|
||||
errorCallback.onError(new NetworkError(101713, 400, "External storage not writable!"));
|
||||
}
|
||||
}, error -> errorCallback.onError(new NetworkError(101717, error.networkResponse.statusCode, "Cannot get file!")));
|
||||
} else {
|
||||
errorCallback.onError(new NetworkError(101716, 400, "External storage not writable!"));
|
||||
}
|
||||
}, error -> errorCallback.onError(new NetworkError(101712, error.networkResponse.statusCode, "Cannot get file!")));
|
||||
} else {
|
||||
errorCallback.onError(new NetworkError(101711, 400, "External storage not writable!"));
|
||||
}
|
||||
}, error -> errorCallback.onError(new NetworkError(101710, error.networkResponse.statusCode, "Cannot get file!")));
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -368,16 +201,9 @@ public class ModulesResources extends PartModules<ArrayList<Resource>> {
|
||||
}
|
||||
private String saveFileInDownloads(String filename, byte[] data, String moduleName) {
|
||||
// Saves file in folder: 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()) {
|
||||
File folder = new File(Environment.getExternalStoragePublicDirectory(
|
||||
Environment.DIRECTORY_DOWNLOADS), moduleName);
|
||||
if (!folder.mkdir()) {
|
||||
log.w( "Directory not created");
|
||||
}
|
||||
String path = "";
|
||||
|
||||
@@ -19,21 +19,13 @@ 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 -> {
|
||||
mQueue.next();
|
||||
});
|
||||
} else {
|
||||
if (getPart(module) != null && !forceRefresh) {
|
||||
callback.onResponse(module);
|
||||
mQueue.next();
|
||||
return;
|
||||
}
|
||||
});
|
||||
mQueue.add(() -> {
|
||||
upgrade(module.getModuleType(), module.getID(), success -> {
|
||||
upgrade(module.getID(), success -> {
|
||||
if (setPart(module, success)) {
|
||||
this.mList.store();
|
||||
}
|
||||
@@ -47,7 +39,7 @@ abstract class PartModules<T> extends Part<Modules.Module> {
|
||||
}, error1 -> {
|
||||
errorCallback.onError(error1);
|
||||
mQueue.next();
|
||||
}, module.getModuleType() == Modules.TYPE_BB ? Login.LOGOUT_BB : Login.LOGOUT_KVV);
|
||||
});
|
||||
return;
|
||||
}
|
||||
errorCallback.onError(error);
|
||||
@@ -69,18 +61,5 @@ abstract class PartModules<T> extends Part<Modules.Module> {
|
||||
|
||||
protected abstract boolean setPart(Modules.Module module, T part);
|
||||
|
||||
protected void upgrade(final int moduleType, final String ID, final NetworkCallback<T> callback, final NetworkErrorCallback errorCallback) {
|
||||
switch (moduleType) {
|
||||
case Modules.TYPE_KVV:
|
||||
upgradeKVV(ID, callback, errorCallback);
|
||||
break;
|
||||
case Modules.TYPE_BB:
|
||||
upgradeBB(ID, callback, errorCallback);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract void upgradeKVV(final String ID, final NetworkCallback<T> callback, final NetworkErrorCallback errorCallback);
|
||||
|
||||
protected abstract void upgradeBB(final String ID, final NetworkCallback<T> callback, final NetworkErrorCallback errorCallback);
|
||||
protected abstract void upgrade(final String ID, final NetworkCallback<T> callback, final NetworkErrorCallback errorCallback);
|
||||
}
|
||||
|
||||
@@ -1,149 +0,0 @@
|
||||
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.LoginTokenBB;
|
||||
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;
|
||||
|
||||
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.fuLogin = fuLogin;
|
||||
}
|
||||
|
||||
@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) {
|
||||
error.onError(new NetworkError(100272, 403, "Testing BB login failed!"));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
json = json.getJSONArray("results").getJSONObject(0);
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("id", json.getString("id"));
|
||||
bundle.putString("studentId", json.getString("studentId"));
|
||||
bundleCallback.onResponse(bundle);
|
||||
} catch (JSONException e) {
|
||||
error.onError(new NetworkError(100271, 403, "Cannot parse BB profile!"));
|
||||
}
|
||||
}, err -> error.onError(new NetworkError(100270, err.networkResponse.statusCode, "Testing BB login failed!")));
|
||||
}
|
||||
|
||||
@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 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 BB SAML request!"));
|
||||
return;
|
||||
}
|
||||
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 startShibSession(String samlResponse, final NetworkCallback<Bundle> callback, final NetworkErrorCallback errorCallback) {
|
||||
HashMap<String, String> body = new HashMap<>();
|
||||
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 BB session!"));
|
||||
return;
|
||||
}
|
||||
|
||||
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 BB 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 startSession(String shibsessionKey, String shibsessionName, final NetworkCallback<Bundle> callback, final NetworkErrorCallback errorCallback) {
|
||||
HashMap<String, String> cookies = new HashMap<>();
|
||||
cookies.put(shibsessionKey, shibsessionName);
|
||||
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;
|
||||
}
|
||||
try {
|
||||
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 BB login process!"));
|
||||
}
|
||||
}, error -> errorCallback.onError(new NetworkError(100260, error.networkResponse.statusCode, "Cannot finish BB login process!")));
|
||||
}
|
||||
}
|
||||
@@ -1,145 +0,0 @@
|
||||
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;
|
||||
import de.sebse.fuplanner.tools.network.NetworkCallback;
|
||||
import de.sebse.fuplanner.tools.network.NetworkError;
|
||||
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
|
||||
|
||||
public class FULogin extends HTTPService {
|
||||
public FULogin(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
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);
|
||||
startSamlRequest(samlRequestUri, old_shib_idp_session, samlRequest -> {
|
||||
if (samlRequest.containsKey("SAMLResponse")) {
|
||||
callback.onResponse(samlRequest.getString("SAMLResponse", ""));
|
||||
return;
|
||||
}
|
||||
|
||||
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 = samlResp.getString("SAMLResponse");
|
||||
if (samlResponse != null)
|
||||
callback.onResponse(samlResponse);
|
||||
else
|
||||
errorCallback.onError(new NetworkError(100300, -1, "Cannot get SAML Response!"));
|
||||
}, errorCallback);
|
||||
}, errorCallback);
|
||||
}, errorCallback);
|
||||
}
|
||||
|
||||
/*
|
||||
2= GET [Location-Header 1]
|
||||
-> Set-Cookie: JSESSIONID=[JSESSION-FU]
|
||||
-> Location: /idp-fub/profile/SAML2/Redirect/SSO?execution=e1s1
|
||||
*/
|
||||
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(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 FU SAML response!"));
|
||||
return;
|
||||
}
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("SAMLResponse", matcher.group(1));
|
||||
callback.onResponse(bundle);
|
||||
return;
|
||||
}
|
||||
String cookies = response.getHeaders().get("Set-Cookie");
|
||||
if (cookies == null) {
|
||||
errorCallback.onError(new NetworkError(100321, -1, "Error on starting FU session!"));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Bundle bundle = getCookie(cookies, new String[]{"JSESSIONID"});
|
||||
callback.onResponse(bundle);
|
||||
} catch (NoSuchFieldException e) {
|
||||
errorCallback.onError(new NetworkError(100322, -1, "Error on starting FU session!"));
|
||||
}
|
||||
}, error -> errorCallback.onError(new NetworkError(100320, error.networkResponse.statusCode, "Error on starting FU session!")));
|
||||
}
|
||||
|
||||
/*
|
||||
3= GET [Location-Header 2]
|
||||
+ Cookie: JSESSIONID=[JSESSION-FU]
|
||||
*/
|
||||
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 FU login page!")));
|
||||
}
|
||||
|
||||
/*
|
||||
4= POST [Location-Header 2]
|
||||
+ Body: j_username=[USERNAME]&j_password=[PASSWORD]&_eventId_proceed=
|
||||
+ Header: Content-Type: application/x-www-form-urlencoded
|
||||
+ Header: Referer: [Location-Header 2]
|
||||
+ Cookie: JSESSIONID=[JSESSION-FU]
|
||||
-> Set-Cookie: shib_idp_session=[SHIB-IDP-SESSION]
|
||||
-> Body SAMLResponse-Input-value
|
||||
*/
|
||||
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", cookiesReq, body, response -> {
|
||||
String content = response.getParsed();
|
||||
if (content == null) {
|
||||
errorCallback.onError(new NetworkError(100343, -1, "Error on getting FU SAML response!"));
|
||||
return;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
Bundle bundle;
|
||||
try {
|
||||
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;
|
||||
}
|
||||
Pattern pattern = Pattern.compile("name=\"SAMLResponse\" value=\"([0-9a-zA-Z+]+=*)");
|
||||
Matcher matcher = pattern.matcher(content);
|
||||
if (!matcher.find()) {
|
||||
errorCallback.onError(new NetworkError(100344, -1, "Error on getting SAML response!"));
|
||||
return;
|
||||
}
|
||||
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!")));
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import androidx.annotation.Nullable;
|
||||
|
||||
public class KVVContentProvider extends ContentProvider {
|
||||
|
||||
public static final String PROVIDER_NAME = "de.sebse.fuplanner.contentprovider.kvv.modules";
|
||||
private static final String PROVIDER_NAME = "de.sebse.fuplanner.contentprovider.kvv.modules";
|
||||
private static final Uri CONTENT_URI = Uri.parse("content://" + PROVIDER_NAME + "/modules");
|
||||
private static final int MODULE = 1;
|
||||
private static final int MODULE_ID = 2;
|
||||
@@ -0,0 +1,87 @@
|
||||
package de.sebse.fuplanner.services.kvv.sync;
|
||||
|
||||
import android.accounts.Account;
|
||||
import android.accounts.AccountManager;
|
||||
import android.content.AbstractThreadedSyncAdapter;
|
||||
import android.content.ContentProviderClient;
|
||||
import android.content.Context;
|
||||
import android.content.SyncResult;
|
||||
import android.os.Bundle;
|
||||
|
||||
import com.android.volley.NetworkResponse;
|
||||
|
||||
import java.util.Iterator;
|
||||
|
||||
import de.sebse.fuplanner.services.kvv.KVV;
|
||||
import de.sebse.fuplanner.services.kvv.KVVListener;
|
||||
import de.sebse.fuplanner.services.kvv.types.LoginToken;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
import de.sebse.fuplanner.tools.CustomAccountManager;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
|
||||
public class KVVSyncAdapter extends AbstractThreadedSyncAdapter {
|
||||
private KVV mKVV;
|
||||
private Logger log = new Logger(this);
|
||||
|
||||
/**
|
||||
* Set up the sync adapter
|
||||
*/
|
||||
public 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) {
|
||||
mKVV = new KVV(new KVVListener() {
|
||||
CustomAccountManager accountManager = null;
|
||||
@Override
|
||||
public CustomAccountManager getAccountManager() {
|
||||
if (accountManager == null)
|
||||
accountManager = new CustomAccountManager(AccountManager.get(context), () -> null);
|
||||
return accountManager;
|
||||
}
|
||||
}, context);
|
||||
mKVV.account().restoreOnlineLogin(bool -> {});
|
||||
}
|
||||
|
||||
/*
|
||||
* 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) {
|
||||
log.d("start syncing");
|
||||
/*
|
||||
* Put the data transfer code here.
|
||||
*/
|
||||
mKVV.modules().list().recv(success -> {
|
||||
Iterator<Modules.Module> iterator = success.latestSemesterIterator();
|
||||
while (iterator.hasNext()) {
|
||||
Modules.Module module = iterator.next();
|
||||
log.d("sync module", module.title);
|
||||
mKVV.modules().details().recv(module, success1 -> {
|
||||
if (success1.second)
|
||||
log.d("Sync Successful for Module '"+module.title+"'!");
|
||||
}, log::e, true);
|
||||
}
|
||||
}, log::e, true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
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.types.LoginToken;
|
||||
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 Login(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
|
||||
public void testLoginToken(@NotNull LoginToken token, @NotNull NetworkCallback<LoginToken> callback, @NotNull NetworkErrorCallback errorCallback) {
|
||||
get(String.format("https://kvv.imp.fu-berlin.de/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);
|
||||
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<LoginToken> callback, NetworkErrorCallback error) {
|
||||
startKVVSession(success -> {
|
||||
String kvvJSESSIONID = success.get("JSESSIONID");
|
||||
getSAMLRequest(kvvJSESSIONID, success1 -> startIdentSession(success1.get("Location"), success11 -> {
|
||||
String identJSESSIONID = success11.get("JSESSIONID");
|
||||
String ident_idp_authn_lc_key = success11.get("_idp_authn_lc_key");
|
||||
String identROUTEID = success11.get("ROUTEID");
|
||||
loginIdent(true, username, password, identJSESSIONID, ident_idp_authn_lc_key, identROUTEID, success111 -> loginIdent(false, username, password, identJSESSIONID, ident_idp_authn_lc_key, identROUTEID, success11112 -> {
|
||||
String ident_idp_session = success11112.get("_idp_session");
|
||||
getSAMLResponse(identJSESSIONID, ident_idp_authn_lc_key, identROUTEID, ident_idp_session, success1111 -> loginKVV(success1111.get("RelayState"), success1111.get("SAMLResponse"), kvvJSESSIONID, success111112 -> {
|
||||
LoginToken token = new LoginToken(username, success111112.get("shibsessionKey"), success111112.get("shibsessionName"), kvvJSESSIONID);
|
||||
finishKVVlogin(token, success11111 -> callback.onResponse(token), error);
|
||||
}, error), error);
|
||||
}, error), error);
|
||||
}, error), error);
|
||||
}, error);
|
||||
}
|
||||
|
||||
/*
|
||||
GET https://kvv.imp.fu-berlin.de/portal/login
|
||||
-> JSESSIONID 5c10406f-588c-4c16-96e9-c80d115417de.tomcat1
|
||||
*/
|
||||
private void startKVVSession(final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
|
||||
get("https://kvv.imp.fu-berlin.de/portal/login", null, response -> {
|
||||
String cookies = response.getHeaders().get("Set-Cookie");
|
||||
if (cookies==null) {
|
||||
errorCallback.onError(new NetworkError(100101, -1, "Error on starting KVV session!"));
|
||||
return;
|
||||
}
|
||||
HashMap<String, String> object;
|
||||
try {
|
||||
object = getCookie(cookies, new String[]{"JSESSIONID"});
|
||||
} catch (NoSuchFieldException e) {
|
||||
errorCallback.onError(new NetworkError(100102, -1, "Error on starting KVV session!"));
|
||||
return;
|
||||
}
|
||||
callback.onResponse(object);
|
||||
}, error -> errorCallback.onError(new NetworkError(100100, error.networkResponse.statusCode, "Error on starting KVV session!")));
|
||||
}
|
||||
|
||||
/*
|
||||
GET https://kvv.imp.fu-berlin.de/sakai-login-tool/container
|
||||
<- JSESSIONID
|
||||
-> (Location-Header) https://identity.fu-berlin.de/idp-fub/profile/SAML2/Redirect/SSO
|
||||
?SAMLRequest=fZLLb.....Q8yre3X1IHwkJKE0Mnpy/V9TH4A
|
||||
&RelayState=ss:mem:7ea01e29157b8bd906f7002176.....0d1a505f2c8bf
|
||||
*/
|
||||
private void getSAMLRequest(String JSESSIONID, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
|
||||
HashMap<String, String> cookies = new HashMap<>();
|
||||
cookies.put("JSESSIONID", JSESSIONID);
|
||||
get("https://kvv.imp.fu-berlin.de/sakai-login-tool/container", cookies, 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!")));
|
||||
}
|
||||
|
||||
/*
|
||||
GET https://identity.fu-berlin.de/idp-fub/profile/SAML2/Redirect/SSO
|
||||
?SAMLRequest=fZLLbsIwEEV/JfI+cWJAUIsgpbAoEi2IpF10UznxUKw6dupxaPn7hkdb2LD29bkzRzNGUeuGZ63fmjV8toA++K61QX58SEnrDLcCFXIjakDuK55njwvOopg3znpbWU2CDBGcV9ZMrcG2BpeD26kKnteLlGy9b5BT+rHbRapuok0bluC0MpEEmm9VWVoNfhshWnpgM7pa5gUJZt0wyogD9h+iJBiv/P6aomQTbtqSdhNtlIYzZg1SOag8zfMlCeazlLyNqpHsy1gO2V1fVsNBMuqJoUyAJaxXDUaiiyG2MDfohfEpYXEyDJM4ZKxgCe/FPI5fSbA6L36vjFTm/bal8hRC/lAUq/C02gs4PK7VBchkfHDNj8Xuwv5trPhVTiY3BeOf4DG96DmVNvypA89nK6tVtQ8yre3X1IHwkJKE0Mnpy/V9TH4A
|
||||
&RelayState=ss:mem:7ea01e29157b8bd906f7002176213b6db5e1f45ebb88716a9820d1a505f2c8bf
|
||||
-> JSESSIONID C4B6A428BA1F50746235D03F5D107A57
|
||||
-> _idp_authn_lc_key 57a6ae26067f374cc3d0ccfc47e27b04b47752d2a3d4eb2782af0d3994535395
|
||||
-> ROUTEID .1
|
||||
*/
|
||||
private void startIdentSession(String url, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
|
||||
get(url, null, response -> {
|
||||
String cookies = response.getHeaders().get("Set-Cookie");
|
||||
if (cookies==null) {
|
||||
errorCallback.onError(new NetworkError(100121, -1, "Error on starting Ident session!"));
|
||||
return;
|
||||
}
|
||||
HashMap<String, String> object;
|
||||
try {
|
||||
object = getCookie(cookies, new String[]{"JSESSIONID", "_idp_authn_lc_key", "ROUTEID"});
|
||||
} catch (NoSuchFieldException e) {
|
||||
errorCallback.onError(new NetworkError(100122, -1, "Error on starting Ident session!"));
|
||||
return;
|
||||
}
|
||||
callback.onResponse(object);
|
||||
}, error -> errorCallback.onError(new NetworkError(100120, error.networkResponse.statusCode, "Error on starting Ident session!")));
|
||||
}
|
||||
|
||||
/*
|
||||
POST https://identity.fu-berlin.de/idp-fub/Authn/UserPassword
|
||||
<- j_username seedorf96
|
||||
<- j_password neinhieristpatrick
|
||||
<- (Header-"Content-Type") application/x-www-form-urlencoded
|
||||
<- JSESSIONID
|
||||
<- _idp_authn_lc_key
|
||||
<- ROUTEID
|
||||
-> _idp_session OTMuMTkzLjg1LjMz|LQ==|OGYxOWI4MjA2NTQ4YWUwYzJkOWM4Mjk4YzcwZDMwZmJiZjBmMTdmMzkyZGU2OWIwY2JkNmZlNjlmNTRmNzBlMQ==|wLlzQal7VqyntmG2vLNn06wt8wQ=
|
||||
*/
|
||||
private void loginIdent(final boolean first, String username, String password, String JSESSIONID, String _idp_authn_lc_key, String ROUTEID, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
|
||||
HashMap<String, String> cookies = new HashMap<>();
|
||||
cookies.put("JSESSIONID", JSESSIONID);
|
||||
cookies.put("_idp_authn_lc_key", _idp_authn_lc_key);
|
||||
cookies.put("ROUTEID", ROUTEID);
|
||||
HashMap<String, String> body = new HashMap<>();
|
||||
body.put("j_username", username);
|
||||
body.put("j_password", password);
|
||||
post("https://identity.fu-berlin.de/idp-fub/Authn/UserPassword", cookies, body, response -> {
|
||||
if (first) {
|
||||
callback.onResponse(new HashMap<>());
|
||||
return;
|
||||
}
|
||||
|
||||
String cookies1 = response.getHeaders().get("Set-Cookie");
|
||||
if (cookies1 ==null) {
|
||||
errorCallback.onError(new NetworkError(100131, -1, "Error on logging in to Identity Server!"));
|
||||
return;
|
||||
}
|
||||
HashMap<String, String> object;
|
||||
try {
|
||||
object = getCookie(cookies1, new String[]{"_idp_session"});
|
||||
} catch (NoSuchFieldException e) {
|
||||
errorCallback.onError(new NetworkError(100132, -1, "Error on logging in to Identity Server!"));
|
||||
return;
|
||||
}
|
||||
callback.onResponse(object);
|
||||
}, error -> errorCallback.onError(new NetworkError(100130, error.networkResponse.statusCode, "Error on logging in to Identity Server!")));
|
||||
}
|
||||
|
||||
/*
|
||||
GET https://identity.fu-berlin.de/idp-fub/profile/SAML2/Redirect/SSO
|
||||
<- JSESSIONID
|
||||
<- _idp_authn_lc_key
|
||||
<- ROUTEID
|
||||
<- _idp_session
|
||||
-> (BODY) RelayState 7ea01e29157b8bd906f7002176213b6db5e1f45ebb88716a9820d1a505f2c8bf
|
||||
-> (BODY) SAMLResponse PD94bWwgdmVyc2lvbj0...........wvc2FtbDJwOlJlc3BvbnNlPg==
|
||||
*/
|
||||
private void getSAMLResponse(String JSESSIONID, String _idp_authn_lc_key, String ROUTEID, String _idp_session, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
|
||||
HashMap<String, String> cookies = new HashMap<>();
|
||||
cookies.put("JSESSIONID", JSESSIONID);
|
||||
cookies.put("_idp_authn_lc_key", _idp_authn_lc_key);
|
||||
cookies.put("ROUTEID", ROUTEID);
|
||||
cookies.put("_idp_session", _idp_session);
|
||||
get("https://identity.fu-berlin.de/idp-fub/profile/SAML2/Redirect/SSO", cookies, response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(100143, -1, "Error on getting SAML response!"));
|
||||
return;
|
||||
}
|
||||
|
||||
HashMap<String, String> object = new HashMap<>();
|
||||
|
||||
Pattern pattern = Pattern.compile("ss:mem:([0-9a-f]+)");
|
||||
Matcher matcher = pattern.matcher(body);
|
||||
if (!matcher.find()) {
|
||||
errorCallback.onError(new NetworkError(100142, -1, "Error on getting SAML response!"));
|
||||
return;
|
||||
}
|
||||
object.put("RelayState", "ss:mem:"+matcher.group(1));
|
||||
|
||||
pattern = Pattern.compile("name=\"SAMLResponse\" value=\"([0-9a-zA-Z+]+=*)");
|
||||
matcher = pattern.matcher(body);
|
||||
if (!matcher.find()) {
|
||||
errorCallback.onError(new NetworkError(100141, -1, "Error on getting SAML response!"));
|
||||
return;
|
||||
}
|
||||
object.put("SAMLResponse", matcher.group(1));
|
||||
|
||||
callback.onResponse(object);
|
||||
}, error -> errorCallback.onError(new NetworkError(100140, error.networkResponse.statusCode, "Error on getting SAML response!")));
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
POST https://kvv.imp.fu-berlin.de/Shibboleth.sso/SAML2/POST
|
||||
<- RelayState 7ea01e29157b8bd906f7002176213b6db5e1f45ebb88716a9820d1a505f2c8bf
|
||||
<- SAMLResponse PD94bWwgdmVyc2lvbj0...........wvc2FtbDJwOlJlc3BvbnNlPg==
|
||||
<- JSESSIONID
|
||||
-> _shibsession_64656661756c7468747470733a2f2f6b76762e696d702e66752d6265726c696e2e64652f73686962626f6c657468
|
||||
_b1912c5a03d733a80bd3fee772bf68d4
|
||||
*/
|
||||
private void loginKVV(String RelayState, String SAMLResponse, String JSESSIONID, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
|
||||
HashMap<String, String> cookies = new HashMap<>();
|
||||
cookies.put("JSESSIONID", JSESSIONID);
|
||||
HashMap<String, String> body = new HashMap<>();
|
||||
body.put("RelayState", RelayState);
|
||||
body.put("SAMLResponse", SAMLResponse);
|
||||
post("https://kvv.imp.fu-berlin.de/Shibboleth.sso/SAML2/POST", cookies, body, response -> {
|
||||
String cookies1 = response.getHeaders().get("Set-Cookie");
|
||||
if (cookies1 ==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(cookies1);
|
||||
if (!matcher.find()) {
|
||||
errorCallback.onError(new NetworkError(100152, -1, "Error on starting Ident 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 Ident session!")));
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
GET https://kvv.imp.fu-berlin.de/sakai-login-tool/container
|
||||
<- JSESSIONID
|
||||
<- _shibsession_64656661756c7468747470733a2f2f6b76762e696d702e66752d6265726c696e2e64652f73686962626f6c657468
|
||||
_b1912c5a03d733a80bd3fee772bf68d4
|
||||
*/
|
||||
private void finishKVVlogin(LoginToken loginToken, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
|
||||
get("https://kvv.imp.fu-berlin.de/sakai-login-tool/container", loginToken.getCookies(), response -> callback.onResponse(new HashMap<>()), error -> errorCallback.onError(new NetworkError(100160, error.networkResponse.statusCode, "Cannot finish login process!")));
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
private String getCookie(String cookies, String name) throws NoSuchFieldException {
|
||||
Pattern pattern = Pattern.compile(name+"=([^;]+);");
|
||||
Matcher matcher = pattern.matcher(cookies);
|
||||
if (!matcher.find()) {
|
||||
log.e("GETcookie failed", name);
|
||||
log.e("GETcookie failed", cookies);
|
||||
throw new NoSuchFieldException();
|
||||
}
|
||||
return matcher.group(1);
|
||||
}
|
||||
|
||||
private HashMap<String, String> getCookie(String cookies, String[] names) throws NoSuchFieldException {
|
||||
HashMap<String, String> result = new HashMap<>();
|
||||
for (String name: names) {
|
||||
result.put(name,this.getCookie(cookies, name));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
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();
|
||||
}
|
||||
@@ -1,373 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
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!")));
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,16 @@ package de.sebse.fuplanner.services.kvv.types;
|
||||
|
||||
import com.google.android.gms.common.internal.Objects;
|
||||
|
||||
import java.io.Serializable;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import de.sebse.fuplanner.tools.UtilsJson;
|
||||
|
||||
public class Announcement implements Serializable {
|
||||
public class Announcement implements UtilsJson.JsonConvertible {
|
||||
private final String id;
|
||||
private final String title;
|
||||
private final String body;
|
||||
@@ -24,11 +28,24 @@ public class Announcement implements Serializable {
|
||||
this.urls = urls;
|
||||
}
|
||||
|
||||
public Announcement(JSONObject json) throws JSONException {
|
||||
this.id = json.getString("id");
|
||||
this.title = json.getString("title");
|
||||
this.body = json.getString("body");
|
||||
this.createdBy = json.getString("createdBy");
|
||||
this.createdOn = json.getLong("createdOn");
|
||||
ArrayList<String> urls = new ArrayList<>();
|
||||
for (String url: UtilsJson.jsonArrayToIterableString(json.getJSONArray("urls"))) {
|
||||
urls.add(url);
|
||||
}
|
||||
this.urls = urls;
|
||||
}
|
||||
|
||||
public ArrayList<String> getUrls() {
|
||||
return urls;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
private String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@@ -63,4 +80,16 @@ public class Announcement implements Serializable {
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(getId(), getBody(), getCreatedBy(), getCreatedOn(), getTitle(), getUrls());
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject toJSONObject() throws JSONException {
|
||||
JSONObject json = new JSONObject();
|
||||
json.put("id", id);
|
||||
json.put("title", title);
|
||||
json.put("body", body);
|
||||
json.put("createdBy", createdBy);
|
||||
json.put("createdOn", createdOn);
|
||||
json.put("urls", UtilsJson.collectionToJson(urls));
|
||||
return json;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,12 +2,15 @@ package de.sebse.fuplanner.services.kvv.types;
|
||||
|
||||
import com.google.android.gms.common.internal.Objects;
|
||||
|
||||
import java.io.Serializable;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import de.sebse.fuplanner.tools.UtilsJson;
|
||||
|
||||
public class Assignment implements Serializable {
|
||||
public class Assignment implements UtilsJson.JsonConvertible {
|
||||
private final String id;
|
||||
private final String title;
|
||||
private final long dueTime;
|
||||
@@ -22,7 +25,7 @@ public class Assignment implements Serializable {
|
||||
this.instructions = instructions;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
private String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@@ -59,4 +62,15 @@ public class Assignment implements Serializable {
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(getId(), getDueDate(), getInstructions(), getTitle(), getUrls());
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject toJSONObject() throws JSONException {
|
||||
JSONObject json = new JSONObject();
|
||||
json.put("id", id);
|
||||
json.put("title", title);
|
||||
json.put("dueTime", dueTime);
|
||||
json.put("createdBy", UtilsJson.collectionToJson(urls));
|
||||
json.put("instructions", instructions);
|
||||
return json;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
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 CacheBBCourse implements Serializable {
|
||||
private transient static final long RESAVE_TIMER = 1000L * 60 * 60 * 24 * 30;
|
||||
private static final String FILE_NAME = "BBCourseStorageSaving";
|
||||
private static final String FILE_NAME_TIMESTAMP = "BBCourseStorageSavingTimestamp";
|
||||
private transient long mLastTimestamp = 0;
|
||||
|
||||
private HashSet<String> mKVVCourseList = new HashSet<>();
|
||||
private long mKVVCourseListRefresh = 0;
|
||||
private HashMap<String, Modules.Module> mBBCourseList = new HashMap<>();
|
||||
private HashMap<String, Long> mBBCourseListRefresh = new HashMap<>();
|
||||
|
||||
public static CacheBBCourse load(Context context) throws IOException, ClassNotFoundException {
|
||||
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))
|
||||
return null;
|
||||
CacheBBCourse storage = (CacheBBCourse) readObject;
|
||||
is.close();
|
||||
fis.close();
|
||||
|
||||
fis = context.openFileInput(FILE_NAME_TIMESTAMP);
|
||||
is = new ObjectInputStream(fis);
|
||||
storage.mLastTimestamp = is.readLong();
|
||||
is.close();
|
||||
fis.close();
|
||||
|
||||
return storage;
|
||||
}
|
||||
|
||||
public boolean isNewerVersionInStorage(Context context) throws IOException {
|
||||
FileInputStream fis = context.openFileInput(FILE_NAME_TIMESTAMP);
|
||||
ObjectInputStream is = new ObjectInputStream(fis);
|
||||
boolean result = this.mLastTimestamp < is.readLong();
|
||||
is.close();
|
||||
fis.close();
|
||||
return result;
|
||||
}
|
||||
|
||||
public void save(Context context) throws IOException {
|
||||
FileOutputStream fos = context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
|
||||
ObjectOutputStream os = new ObjectOutputStream(fos);
|
||||
os.writeObject(this);
|
||||
os.close();
|
||||
fos.close();
|
||||
|
||||
fos = context.openFileOutput(FILE_NAME_TIMESTAMP, Context.MODE_PRIVATE);
|
||||
os = new ObjectOutputStream(fos);
|
||||
this.mLastTimestamp = System.currentTimeMillis();
|
||||
os.writeLong(this.mLastTimestamp);
|
||||
os.close();
|
||||
fos.close();
|
||||
}
|
||||
|
||||
public void addKVVCourseID(String courseID) {
|
||||
mKVVCourseList.add(courseID);
|
||||
mKVVCourseListRefresh = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public boolean hasKVVCourseID(String courseID) {
|
||||
if (mKVVCourseListRefresh + RESAVE_TIMER < System.currentTimeMillis())
|
||||
return false;
|
||||
return mKVVCourseList.contains(courseID);
|
||||
}
|
||||
|
||||
public void setBBCourse(String courseID, Modules.Module module) {
|
||||
mBBCourseList.put(courseID, module);
|
||||
mBBCourseListRefresh.put(courseID, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public Modules.Module getBBCourse(String courseID) {
|
||||
if (!mBBCourseListRefresh.containsKey(courseID))
|
||||
return null;
|
||||
//noinspection ConstantConditions
|
||||
if (mBBCourseListRefresh.get(courseID) + RESAVE_TIMER < System.currentTimeMillis())
|
||||
return null;
|
||||
return mBBCourseList.get(courseID);
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
package de.sebse.fuplanner.services.kvv.types;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.Serializable;
|
||||
import java.util.HashMap;
|
||||
|
||||
public class CacheBBEventNumber implements Serializable {
|
||||
private transient static final long RESAVE_TIMER = 1000L * 60 * 60 * 24 * 30;
|
||||
private static final String FILE_NAME = "BBEventNumberStorageSaving";
|
||||
private static final String FILE_NAME_TIMESTAMP = "BBEventNumberStorageSavingTimestamp";
|
||||
private transient long mLastTimestamp = 0;
|
||||
|
||||
private HashMap<String, String> mBBEventNumbers = new HashMap<>();
|
||||
private HashMap<String, Long> mBBEventNumbersRefresh = new HashMap<>();
|
||||
|
||||
public static CacheBBEventNumber load(Context context) throws IOException, ClassNotFoundException {
|
||||
FileInputStream fis = context.openFileInput(FILE_NAME);
|
||||
ObjectInputStream is = new ObjectInputStream(fis);
|
||||
Object readObject = is.readObject();
|
||||
if (!(readObject instanceof CacheBBEventNumber))
|
||||
return null;
|
||||
CacheBBEventNumber storage = (CacheBBEventNumber) readObject;
|
||||
is.close();
|
||||
fis.close();
|
||||
|
||||
fis = context.openFileInput(FILE_NAME_TIMESTAMP);
|
||||
is = new ObjectInputStream(fis);
|
||||
storage.mLastTimestamp = is.readLong();
|
||||
is.close();
|
||||
fis.close();
|
||||
|
||||
return storage;
|
||||
}
|
||||
|
||||
public boolean isNewerVersionInStorage(Context context) throws IOException {
|
||||
FileInputStream fis = context.openFileInput(FILE_NAME_TIMESTAMP);
|
||||
ObjectInputStream is = new ObjectInputStream(fis);
|
||||
boolean result = this.mLastTimestamp < is.readLong();
|
||||
is.close();
|
||||
fis.close();
|
||||
return result;
|
||||
}
|
||||
|
||||
public void save(Context context) throws IOException {
|
||||
FileOutputStream fos = context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
|
||||
ObjectOutputStream os = new ObjectOutputStream(fos);
|
||||
os.writeObject(this);
|
||||
os.close();
|
||||
fos.close();
|
||||
|
||||
fos = context.openFileOutput(FILE_NAME_TIMESTAMP, Context.MODE_PRIVATE);
|
||||
os = new ObjectOutputStream(fos);
|
||||
this.mLastTimestamp = System.currentTimeMillis();
|
||||
os.writeLong(this.mLastTimestamp);
|
||||
os.close();
|
||||
fos.close();
|
||||
}
|
||||
|
||||
public void setVVNumber(String lvNumber, String vvNumber) {
|
||||
mBBEventNumbers.put(lvNumber, vvNumber);
|
||||
mBBEventNumbersRefresh.put(lvNumber, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public String getVVNumber(String lvNumber) {
|
||||
if (!mBBEventNumbersRefresh.containsKey(lvNumber))
|
||||
return null;
|
||||
//noinspection ConstantConditions
|
||||
if (mBBEventNumbersRefresh.get(lvNumber) + RESAVE_TIMER < System.currentTimeMillis())
|
||||
return null;
|
||||
return mBBEventNumbers.get(lvNumber);
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
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;
|
||||
|
||||
public class CacheKVVCourse implements Serializable {
|
||||
private transient static final long RESAVE_TIMER = 1000L * 60 * 60 * 24 * 30;
|
||||
private static final String FILE_NAME = "KVVCourseStorageSaving";
|
||||
private static final String FILE_NAME_TIMESTAMP = "KVVCourseStorageSavingTimestamp";
|
||||
private transient long mLastTimestamp = 0;
|
||||
|
||||
private HashMap<String, Modules.Module> mKVVCourseList = new HashMap<>();
|
||||
private HashMap<String, Long> mKVVCourseListRefresh = new HashMap<>();
|
||||
|
||||
public static CacheKVVCourse load(Context context) throws IOException, ClassNotFoundException {
|
||||
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))
|
||||
return null;
|
||||
CacheKVVCourse storage = (CacheKVVCourse) readObject;
|
||||
is.close();
|
||||
fis.close();
|
||||
|
||||
fis = context.openFileInput(FILE_NAME_TIMESTAMP);
|
||||
is = new ObjectInputStream(fis);
|
||||
storage.mLastTimestamp = is.readLong();
|
||||
is.close();
|
||||
fis.close();
|
||||
|
||||
return storage;
|
||||
}
|
||||
|
||||
public boolean isNewerVersionInStorage(Context context) throws IOException {
|
||||
FileInputStream fis = context.openFileInput(FILE_NAME_TIMESTAMP);
|
||||
ObjectInputStream is = new ObjectInputStream(fis);
|
||||
boolean result = this.mLastTimestamp < is.readLong();
|
||||
is.close();
|
||||
fis.close();
|
||||
return result;
|
||||
}
|
||||
|
||||
public void save(Context context) throws IOException {
|
||||
FileOutputStream fos = context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
|
||||
ObjectOutputStream os = new ObjectOutputStream(fos);
|
||||
os.writeObject(this);
|
||||
os.close();
|
||||
fos.close();
|
||||
|
||||
fos = context.openFileOutput(FILE_NAME_TIMESTAMP, Context.MODE_PRIVATE);
|
||||
os = new ObjectOutputStream(fos);
|
||||
this.mLastTimestamp = System.currentTimeMillis();
|
||||
os.writeLong(this.mLastTimestamp);
|
||||
os.close();
|
||||
fos.close();
|
||||
}
|
||||
|
||||
public void setKVVCourse(String courseID, Modules.Module module) {
|
||||
mKVVCourseList.put(courseID, module);
|
||||
mKVVCourseListRefresh.put(courseID, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public Modules.Module getKVVCourse(String courseID) {
|
||||
if (!mKVVCourseListRefresh.containsKey(courseID))
|
||||
return null;
|
||||
//noinspection ConstantConditions
|
||||
if (mKVVCourseListRefresh.get(courseID) + RESAVE_TIMER < System.currentTimeMillis())
|
||||
return null;
|
||||
return mKVVCourseList.get(courseID);
|
||||
}
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
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.ArrayList;
|
||||
import java.util.HashMap;
|
||||
|
||||
public class CacheLecturer implements Serializable {
|
||||
private transient static final long RESAVE_TIMER = 1000L * 60 * 60 * 24 * 30;
|
||||
private static final String FILE_NAME = "LecturerStorageSaving";
|
||||
private static final String FILE_NAME_TIMESTAMP = "LecturerStorageSavingTimestamp";
|
||||
private transient long mLastTimestamp = 0;
|
||||
|
||||
private HashMap<String, ArrayList<String>> mLecturersPerCourse = new HashMap<>();
|
||||
private HashMap<String, Long> mLecturersPerCourseRefresh = new HashMap<>();
|
||||
private HashMap<String, Lecturer> mLecturers = new HashMap<>();
|
||||
private HashMap<String, Long> mLecturersRefresh = new HashMap<>();
|
||||
|
||||
public static CacheLecturer load(Context context) throws IOException, ClassNotFoundException {
|
||||
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))
|
||||
return null;
|
||||
CacheLecturer storage = (CacheLecturer) readObject;
|
||||
is.close();
|
||||
fis.close();
|
||||
|
||||
fis = context.openFileInput(FILE_NAME_TIMESTAMP);
|
||||
is = new ObjectInputStream(fis);
|
||||
storage.mLastTimestamp = is.readLong();
|
||||
is.close();
|
||||
fis.close();
|
||||
|
||||
return storage;
|
||||
}
|
||||
|
||||
public boolean isNewerVersionInStorage(Context context) throws IOException {
|
||||
FileInputStream fis = context.openFileInput(FILE_NAME_TIMESTAMP);
|
||||
ObjectInputStream is = new ObjectInputStream(fis);
|
||||
boolean result = this.mLastTimestamp < is.readLong();
|
||||
is.close();
|
||||
fis.close();
|
||||
return result;
|
||||
}
|
||||
|
||||
public void save(Context context) throws IOException {
|
||||
FileOutputStream fos = context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
|
||||
ObjectOutputStream os = new ObjectOutputStream(fos);
|
||||
os.writeObject(this);
|
||||
os.close();
|
||||
fos.close();
|
||||
|
||||
fos = context.openFileOutput(FILE_NAME_TIMESTAMP, Context.MODE_PRIVATE);
|
||||
os = new ObjectOutputStream(fos);
|
||||
this.mLastTimestamp = System.currentTimeMillis();
|
||||
os.writeLong(this.mLastTimestamp);
|
||||
os.close();
|
||||
fos.close();
|
||||
}
|
||||
|
||||
public void setLecturersPerCourse(String courseID, ArrayList<String> lecturers) {
|
||||
mLecturersPerCourse.put(courseID, lecturers);
|
||||
mLecturersPerCourseRefresh.put(courseID, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public void setLecturer(String lecturerID, Lecturer lecturer) {
|
||||
mLecturers.put(lecturerID, lecturer);
|
||||
mLecturersRefresh.put(lecturerID, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public ArrayList<String> getLecturersPerCourse(String courseID) {
|
||||
if (!mLecturersPerCourseRefresh.containsKey(courseID))
|
||||
return null;
|
||||
//noinspection ConstantConditions
|
||||
if (mLecturersPerCourseRefresh.get(courseID) + RESAVE_TIMER < System.currentTimeMillis())
|
||||
return null;
|
||||
return mLecturersPerCourse.get(courseID);
|
||||
}
|
||||
|
||||
public Lecturer getLecturer(String lecturerID) {
|
||||
if (!mLecturersRefresh.containsKey(lecturerID))
|
||||
return null;
|
||||
//noinspection ConstantConditions
|
||||
if (mLecturersRefresh.get(lecturerID) + RESAVE_TIMER < System.currentTimeMillis())
|
||||
return null;
|
||||
return mLecturers.get(lecturerID);
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,19 @@
|
||||
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;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
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;
|
||||
import de.sebse.fuplanner.tools.UtilsJson;
|
||||
|
||||
public class Event implements Serializable {
|
||||
public class Event implements UtilsJson.JsonConvertible {
|
||||
private final String siteId;
|
||||
private final String id;
|
||||
private final String type;
|
||||
@@ -66,7 +63,7 @@ public class Event implements Serializable {
|
||||
return siteId;
|
||||
}
|
||||
|
||||
public ColorRGB getColor(@Nullable Context context) {
|
||||
public ColorRGB getColor() {
|
||||
MessageDigest digest;
|
||||
try {
|
||||
digest = MessageDigest.getInstance("SHA-256");
|
||||
@@ -75,7 +72,11 @@ public class Event implements Serializable {
|
||||
return null;
|
||||
}
|
||||
byte[] encodedHash;
|
||||
encodedHash = digest.digest(siteId.getBytes(StandardCharsets.UTF_8));
|
||||
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());
|
||||
}
|
||||
int h = (0xff & encodedHash[0]) + (0xff & encodedHash[1]) * 255;
|
||||
h = h * 360 / 0xffff;
|
||||
//int s = 0xff & encodedHash[2];
|
||||
@@ -85,21 +86,8 @@ 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);
|
||||
}
|
||||
@@ -133,6 +121,19 @@ public class Event implements Serializable {
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(getType(), getStartDate(), getEndDate(), getTitle(), getLocation());
|
||||
return Objects.hashCode(getId(), getType(), getStartDate(), getEndDate(), getTitle(), getLocation());
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject toJSONObject() throws JSONException {
|
||||
JSONObject json = new JSONObject();
|
||||
json.put("siteId", siteId);
|
||||
json.put("id", id);
|
||||
json.put("type", type);
|
||||
json.put("title", title);
|
||||
json.put("duration", duration);
|
||||
json.put("firstTime", firstTime);
|
||||
json.put("location", location);
|
||||
return json;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,11 +2,13 @@ package de.sebse.fuplanner.services.kvv.types;
|
||||
|
||||
import com.google.android.gms.common.internal.Objects;
|
||||
|
||||
import java.io.Serializable;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import de.sebse.fuplanner.tools.UtilsJson;
|
||||
|
||||
public class Grade implements Serializable {
|
||||
public class Grade implements UtilsJson.JsonConvertible {
|
||||
private final String itemName;
|
||||
private final double grade;
|
||||
private final double maxPoints;
|
||||
@@ -41,4 +43,13 @@ public class Grade implements Serializable {
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(getItemName(), getPoints(), getMaxPoints());
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject toJSONObject() throws JSONException {
|
||||
JSONObject json = new JSONObject();
|
||||
json.put("itemName", itemName);
|
||||
json.put("grade", grade);
|
||||
json.put("maxPoints", maxPoints);
|
||||
return json;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,138 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import android.annotation.SuppressLint;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
@@ -37,17 +36,14 @@ public class GroupedEvents extends EventList {
|
||||
return skippedDayCount;
|
||||
}
|
||||
|
||||
public class Group implements Iterable<Event> {
|
||||
public class Group {
|
||||
private long firstDate;
|
||||
private long lastDate;
|
||||
private final ArrayList<Long> skippedDates;
|
||||
private final ArrayList<Event> allEvents = new ArrayList<>();
|
||||
|
||||
private final int dayOfWeek;
|
||||
private final long startTime;
|
||||
private final long duration;
|
||||
private final String location;
|
||||
private final String title;
|
||||
|
||||
private Group(Event event) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
@@ -55,8 +51,6 @@ public class GroupedEvents extends EventList {
|
||||
dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
|
||||
startTime = calendar.get(Calendar.HOUR_OF_DAY)*3600000+calendar.get(Calendar.MINUTE)*60000+calendar.get(Calendar.SECOND)*1000+calendar.get(Calendar.MILLISECOND);
|
||||
duration = event.getEndDate()-event.getStartDate();
|
||||
location = event.getLocation();
|
||||
title = event.getTitle();
|
||||
|
||||
skippedDates = new ArrayList<>();
|
||||
calendar.set(Calendar.HOUR_OF_DAY, 0);
|
||||
@@ -65,7 +59,6 @@ public class GroupedEvents extends EventList {
|
||||
calendar.set(Calendar.MILLISECOND, 0);
|
||||
firstDate = calendar.getTimeInMillis();
|
||||
lastDate = firstDate;
|
||||
allEvents.add(event);
|
||||
}
|
||||
|
||||
private boolean add(Event event) {
|
||||
@@ -74,8 +67,7 @@ public class GroupedEvents extends EventList {
|
||||
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
|
||||
int startTime = calendar.get(Calendar.HOUR_OF_DAY)*3600000+calendar.get(Calendar.MINUTE)*60000+calendar.get(Calendar.SECOND)*1000+calendar.get(Calendar.MILLISECOND);
|
||||
long length = event.getEndDate()-event.getStartDate();
|
||||
String location = event.getLocation();
|
||||
if (this.dayOfWeek != dayOfWeek || this.startTime != startTime || this.duration != length || !this.location.equals(location))
|
||||
if (this.dayOfWeek != dayOfWeek || this.startTime != startTime || this.duration != length)
|
||||
return false;
|
||||
calendar.set(Calendar.HOUR_OF_DAY, 0);
|
||||
calendar.set(Calendar.MINUTE, 0);
|
||||
@@ -100,7 +92,6 @@ public class GroupedEvents extends EventList {
|
||||
skippedDates.remove(date);
|
||||
skippedDayCount -= 1;
|
||||
}
|
||||
allEvents.add(event);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -135,29 +126,11 @@ public class GroupedEvents extends EventList {
|
||||
return duration;
|
||||
}
|
||||
|
||||
public String getLocation() {
|
||||
return location;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
@SuppressLint("DefaultLocale")
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("%d - %d - %d - %s", dayOfWeek, startTime, duration, skippedDates);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public Iterator<Event> iterator() {
|
||||
return Collections.unmodifiableList(allEvents).iterator();
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return allEvents.size();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +1,22 @@
|
||||
package de.sebse.fuplanner.services.kvv.types;
|
||||
|
||||
import java.io.Serializable;
|
||||
import com.google.android.gms.common.internal.Objects;
|
||||
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import de.sebse.fuplanner.tools.UtilsJson;
|
||||
|
||||
public class Lecturer implements Serializable {
|
||||
public class Lecturer implements UtilsJson.JsonConvertible {
|
||||
private final String firstName;
|
||||
private final String surname;
|
||||
private final String mail;
|
||||
private final boolean isResponsible;
|
||||
|
||||
public Lecturer(String firstName, String surname, String mail, boolean isResponsible) {
|
||||
this.firstName = firstName;
|
||||
this.surname = surname;
|
||||
this.mail = mail;
|
||||
this.isResponsible = isResponsible;
|
||||
}
|
||||
|
||||
public Lecturer(String parsableString) throws NoSuchFieldException {
|
||||
Pattern pattern = Pattern.compile("([^|]*)\\|([^|]*)\\|([^|]*)\\|\\|([^|]*)", Pattern.DOTALL);
|
||||
Matcher matcher = pattern.matcher(parsableString);
|
||||
@@ -31,6 +29,13 @@ public class Lecturer implements Serializable {
|
||||
this.isResponsible = matcher.group(4).equals("true");
|
||||
}
|
||||
|
||||
public Lecturer(JSONObject json) throws JSONException {
|
||||
this.firstName = json.getString("firstName");
|
||||
this.surname = json.getString("surname");
|
||||
this.mail = json.getString("mail");
|
||||
this.isResponsible = json.getBoolean("isResponsible");
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
@@ -62,4 +67,19 @@ public class Lecturer implements Serializable {
|
||||
"\nSurname: "+getSurname()+
|
||||
"\nMail: "+getMail();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(getFirstName(), getSurname(), getMail(), isResponsible());
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject toJSONObject() throws JSONException {
|
||||
JSONObject json = new JSONObject();
|
||||
json.put("firstName", firstName);
|
||||
json.put("surname", surname);
|
||||
json.put("mail", mail);
|
||||
json.put("isResponsible", isResponsible);
|
||||
return json;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,104 +1,104 @@
|
||||
package de.sebse.fuplanner.services.kvv.types;
|
||||
|
||||
import android.os.Bundle;
|
||||
import android.content.Context;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Serializable;
|
||||
import java.util.HashMap;
|
||||
import java.util.Objects;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import de.sebse.fuplanner.services.fulogin.AccountGeneral;
|
||||
import de.sebse.fuplanner.tools.CustomAccountManager;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
|
||||
public abstract class LoginToken {
|
||||
private boolean isExpanded = false;
|
||||
private boolean isAvailable = false;
|
||||
/**
|
||||
* Created by sebastian on 29.10.17.
|
||||
*/
|
||||
|
||||
LoginToken(@NotNull CustomAccountManager manager, @NotNull LoginTokenInterface callback, @NotNull CustomAccountManager.ExceptionInterface errorCallback) {
|
||||
public class LoginToken {
|
||||
private final String username;
|
||||
private final String shibsessionKey;
|
||||
private final String shibsessionName;
|
||||
private final String JSESSIONID;
|
||||
@Nullable private String fullName;
|
||||
@Nullable private String email;
|
||||
|
||||
public LoginToken(String username, String shibsessionKey, String shibsessionName, String JSESSIONID) {
|
||||
this.username = username;
|
||||
this.shibsessionKey = shibsessionKey;
|
||||
this.shibsessionName = shibsessionName;
|
||||
this.JSESSIONID = JSESSIONID;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static void load(CustomAccountManager manager, LoginTokenInterface callback) {
|
||||
if (!manager.hasAccounts(AccountGeneral.ACCOUNT_TYPE)) {
|
||||
callback.run(null);
|
||||
return;
|
||||
}
|
||||
manager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD, tokenString -> {
|
||||
manager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV, tokenString -> {
|
||||
if (tokenString == null) {
|
||||
callback.run(null);
|
||||
return;
|
||||
}
|
||||
fromString(tokenString);
|
||||
callback.run(this);
|
||||
}, errorCallback);
|
||||
callback.run(LoginToken.fromJsonString(tokenString));
|
||||
});
|
||||
}
|
||||
|
||||
LoginToken() {
|
||||
super();
|
||||
public void delete(CustomAccountManager manager) {
|
||||
manager.deleteAccount(AccountGeneral.ACCOUNT_TYPE);
|
||||
}
|
||||
|
||||
LoginToken(Bundle bundle) {
|
||||
super();
|
||||
init(bundle);
|
||||
public void setAdditionals(String fullName, String email) {
|
||||
this.fullName = fullName;
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
protected abstract String getAccountType();
|
||||
|
||||
protected void init(Bundle bundle) {
|
||||
isAvailable = true;
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setAdditionals(Bundle bundle) {
|
||||
isExpanded = true;
|
||||
isAvailable = true;
|
||||
private String getShibsessionKey() {
|
||||
return shibsessionKey;
|
||||
}
|
||||
|
||||
public final boolean hasAdditionals() {
|
||||
return isExpanded;
|
||||
private String getShibsessionName() {
|
||||
return shibsessionName;
|
||||
}
|
||||
|
||||
public void setUnavailable() {
|
||||
isExpanded = false;
|
||||
isAvailable = false;
|
||||
private String getJSESSIONID() {
|
||||
return JSESSIONID;
|
||||
}
|
||||
|
||||
public final void unsetAdditionals() {
|
||||
isExpanded = false;
|
||||
@Nullable
|
||||
public String getFullName() {
|
||||
return fullName;
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
@Nullable
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
@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 "";
|
||||
public HashMap<String, String> getCookies() {
|
||||
HashMap<String, String> cookies = new HashMap<>();
|
||||
cookies.put("JSESSIONID", getJSESSIONID());
|
||||
cookies.put(getShibsessionKey(), getShibsessionName());
|
||||
cookies.put("pasystem_timezone_ok", "true");
|
||||
return cookies;
|
||||
}
|
||||
|
||||
protected abstract void jsonToObject(JSONObject json) throws JSONException;
|
||||
public boolean isOtherUser(String username) {
|
||||
return !this.getUsername().equals(username);
|
||||
}
|
||||
|
||||
protected abstract JSONObject objectToJson() throws JSONException;
|
||||
|
||||
public abstract HashMap<String, String> getCookies();
|
||||
|
||||
public final String getCookieString() {
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
HashMap<String, String> cookies = this.getCookies();
|
||||
for (String header: cookies.keySet()) {
|
||||
@@ -107,17 +107,42 @@ public abstract class LoginToken {
|
||||
return result.substring(0, result.length()-1);
|
||||
}
|
||||
|
||||
public final boolean isExpanded() {
|
||||
return isExpanded;
|
||||
public String toJsonString() {
|
||||
JSONObject json = new JSONObject();
|
||||
try {
|
||||
json.put("username", username);
|
||||
json.put("shibsessionKey", shibsessionKey);
|
||||
json.put("shibsessionName", shibsessionName);
|
||||
json.put("JSESSIONID", JSESSIONID);
|
||||
json.put("fullName", fullName);
|
||||
json.put("email", email);
|
||||
} catch (JSONException e) {
|
||||
return null;
|
||||
}
|
||||
return json.toString();
|
||||
}
|
||||
|
||||
public final boolean isAvailable() {
|
||||
return isAvailable;
|
||||
public static LoginToken fromJsonString(String tokenString) {
|
||||
try {
|
||||
JSONObject json = new JSONObject(tokenString);
|
||||
LoginToken token = new LoginToken(
|
||||
json.getString("username"),
|
||||
json.getString("shibsessionName"),
|
||||
json.getString("shibsessionName"),
|
||||
json.getString("JSESSIONID"));
|
||||
if (!json.isNull("fullName"))
|
||||
token.setAdditionals(
|
||||
json.getString("fullName"),
|
||||
json.getString("email")
|
||||
);
|
||||
return token;
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public interface LoginTokenInterface {
|
||||
void run(LoginToken token);
|
||||
}
|
||||
|
||||
public abstract boolean isOtherUser(String user);
|
||||
}
|
||||
|
||||
@@ -1,138 +0,0 @@
|
||||
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;
|
||||
|
||||
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 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() {
|
||||
super();
|
||||
}
|
||||
|
||||
public LoginTokenBB(Bundle bundle) {
|
||||
super(bundle);
|
||||
}
|
||||
|
||||
@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");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getAccountType() {
|
||||
return AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD;
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getSessionId() {
|
||||
return session_id;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getSSessionId() {
|
||||
return s_session_id;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getStudentId() {
|
||||
return studentId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HashMap<String, String> getCookies() {
|
||||
HashMap<String, String> cookies = new HashMap<>();
|
||||
cookies.put("session_id", getSessionId());
|
||||
cookies.put("s_session_id", getSSessionId());
|
||||
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("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);
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(s_session_id, session_id, username, id, studentId);
|
||||
}
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -5,13 +5,20 @@ import android.content.Context;
|
||||
import com.google.android.gms.common.internal.Objects;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.Serializable;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.lang.reflect.Array;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
@@ -19,18 +26,20 @@ import java.util.LinkedHashSet;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import de.sebse.fuplanner.tools.UtilsJson;
|
||||
|
||||
import static de.sebse.fuplanner.tools.UtilsJson.collectionToJson;
|
||||
import static de.sebse.fuplanner.tools.UtilsJson.jsonArrayToIterableObject;
|
||||
|
||||
/**
|
||||
* Created by sebastian on 29.10.17.
|
||||
*/
|
||||
|
||||
public class Modules implements Iterable<Modules.Module>, Serializable {
|
||||
public static final int TYPE_KVV = 1;
|
||||
public static final int TYPE_BB = 2;
|
||||
|
||||
public class Modules implements Iterable<Modules.Module> {
|
||||
private SortedListModule list;
|
||||
private final String mUsername;
|
||||
private transient long mLastTimestamp = 0;
|
||||
private long mLoadTime;
|
||||
//private transient Logger log = new Logger(this);
|
||||
private static final String FILE_NAME = "ModuleListSaving";
|
||||
private static final String FILE_NAME_TIMESTAMP = "ModuleListSavingTimestamp";
|
||||
|
||||
@@ -39,14 +48,9 @@ public class Modules implements Iterable<Modules.Module>, Serializable {
|
||||
this.list = new SortedListModule();
|
||||
}
|
||||
|
||||
public Module addModule(@Nullable Semester semester, HashSet<String> lvNumber, String title, LinkedHashSet<Lecturer> lecturer, String type, String description, String ID, int moduleType) {
|
||||
Module m = new Module(semester, lvNumber, title, lecturer, type, description, ID, moduleType);
|
||||
public void addModule(@Nullable Semester semester, HashSet<String> lvNumber, String title, LinkedHashSet<Lecturer> lecturer, String type, String description, String ID) {
|
||||
Module m = new Module(semester, lvNumber, title, lecturer, type, description, ID);
|
||||
this.list.add(m);
|
||||
return m;
|
||||
}
|
||||
|
||||
public void addModule(Module module) {
|
||||
this.list.add(module);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@@ -65,10 +69,6 @@ public class Modules implements Iterable<Modules.Module>, Serializable {
|
||||
return this.list.filteredIterator(this.list.getLatestSemester());
|
||||
}
|
||||
|
||||
public Semester getLatestSemester() {
|
||||
return this.list.getLatestSemester();
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return this.list.size();
|
||||
}
|
||||
@@ -81,47 +81,54 @@ public class Modules implements Iterable<Modules.Module>, Serializable {
|
||||
return this.list.get(index);
|
||||
}
|
||||
|
||||
public static Modules load(Context context) throws IOException, ClassNotFoundException {
|
||||
FileInputStream fis = context.openFileInput(FILE_NAME);
|
||||
ObjectInputStream is = new ObjectInputStream(fis);
|
||||
Object readObject = is.readObject();
|
||||
if (!(readObject instanceof Modules))
|
||||
return null;
|
||||
Modules modules = (Modules) readObject;
|
||||
is.close();
|
||||
fis.close();
|
||||
public static Modules load(Context context) throws IOException {
|
||||
String ret = "";
|
||||
InputStream inputStream = context.openFileInput(FILE_NAME);
|
||||
if (inputStream != null) {
|
||||
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
|
||||
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
|
||||
String receiveString;
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
while ((receiveString = bufferedReader.readLine()) != null) {
|
||||
stringBuilder.append(receiveString);
|
||||
}
|
||||
inputStream.close();
|
||||
ret = stringBuilder.toString();
|
||||
}
|
||||
|
||||
fis = context.openFileInput(FILE_NAME_TIMESTAMP);
|
||||
is = new ObjectInputStream(fis);
|
||||
modules.mLastTimestamp = is.readLong();
|
||||
is.close();
|
||||
fis.close();
|
||||
|
||||
return modules;
|
||||
}
|
||||
|
||||
public boolean isNewerVersionInStorage(Context context) throws IOException {
|
||||
FileInputStream fis = context.openFileInput(FILE_NAME_TIMESTAMP);
|
||||
ObjectInputStream is = new ObjectInputStream(fis);
|
||||
boolean result = this.mLastTimestamp < is.readLong();
|
||||
is.close();
|
||||
fis.close();
|
||||
return result;
|
||||
try {
|
||||
JSONObject json = new JSONObject(ret);
|
||||
Modules mod = new Modules(json.getString("username"));
|
||||
JSONArray arr = json.getJSONArray("modules");
|
||||
for (JSONObject jsonObject: jsonArrayToIterableObject(arr)) {
|
||||
mod.list.add(new Module(jsonObject));
|
||||
}
|
||||
FileInputStream ofi = context.openFileInput(FILE_NAME_TIMESTAMP);
|
||||
ObjectInputStream inputStream1 = new ObjectInputStream(ofi);
|
||||
mod.mLoadTime = inputStream1.readLong();
|
||||
return mod;
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void save(Context context) throws IOException {
|
||||
FileOutputStream fos = context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
|
||||
ObjectOutputStream os = new ObjectOutputStream(fos);
|
||||
os.writeObject(this);
|
||||
os.close();
|
||||
fos.close();
|
||||
JSONObject json = new JSONObject();
|
||||
try {
|
||||
json.put("username", mUsername);
|
||||
json.put("modules", UtilsJson.collectionToJson(list));
|
||||
OutputStreamWriter osw = new OutputStreamWriter(context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE));
|
||||
osw.write(json.toString());
|
||||
osw.close();
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
fos = context.openFileOutput(FILE_NAME_TIMESTAMP, Context.MODE_PRIVATE);
|
||||
os = new ObjectOutputStream(fos);
|
||||
this.mLastTimestamp = System.currentTimeMillis();
|
||||
os.writeLong(this.mLastTimestamp);
|
||||
os.close();
|
||||
fos.close();
|
||||
mLoadTime = System.currentTimeMillis();
|
||||
FileOutputStream ofo = context.openFileOutput(FILE_NAME_TIMESTAMP, Context.MODE_PRIVATE);
|
||||
ObjectOutputStream outputStream = new ObjectOutputStream(ofo);
|
||||
outputStream.writeLong(mLoadTime);
|
||||
}
|
||||
|
||||
public void delete(Context context) {
|
||||
@@ -150,8 +157,6 @@ public class Modules implements Iterable<Modules.Module>, Serializable {
|
||||
isChanged = true;
|
||||
}
|
||||
}
|
||||
if (this.list.size() != old.size())
|
||||
isChanged = true;
|
||||
return isChanged;
|
||||
}
|
||||
|
||||
@@ -164,24 +169,58 @@ public class Modules implements Iterable<Modules.Module>, Serializable {
|
||||
return o1.hashCode() == o2.hashCode();
|
||||
}
|
||||
|
||||
public class Module implements Serializable {
|
||||
|
||||
public static class Module implements UtilsJson.JsonConvertible {
|
||||
@Nullable public final Semester semester;
|
||||
@NotNull public final HashSet<String> lvNumber;
|
||||
@NotNull final HashSet<String> lvNumber;
|
||||
@NotNull public final String title;
|
||||
@NotNull
|
||||
public ArrayList<Lecturer> lecturer;
|
||||
@NotNull public final ArrayList<Lecturer> lecturer;
|
||||
@Nullable public final String type;
|
||||
@Nullable public final String description;
|
||||
@NotNull private final String ID;
|
||||
private final int moduleType;
|
||||
@Nullable public ArrayList<Announcement> announcements;
|
||||
@Nullable public AssignmentList assignments;
|
||||
@Nullable public EventList events;
|
||||
@Nullable public Gradebook gradebook;
|
||||
@Nullable public ArrayList<Grade> gradebook;
|
||||
@Nullable public ArrayList<Resource> resources;
|
||||
|
||||
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) {
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(semester, lvNumber, title, lecturer, type, description, ID);
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject toJSONObject() throws JSONException {
|
||||
JSONObject json = new JSONObject();
|
||||
json.put("semester", semester != null ? semester.toJSONObject() : null);
|
||||
json.put("lvNumber", collectionToJson(lvNumber));
|
||||
json.put("title", title);
|
||||
json.put("lecturer", collectionToJson(lecturer));
|
||||
json.put("type", type);
|
||||
json.put("description", description);
|
||||
json.put("ID", ID);
|
||||
json.put("announcements", collectionToJson(announcements));
|
||||
json.put("assignments", collectionToJson(assignments));
|
||||
json.put("events", collectionToJson(events));
|
||||
json.put("gradebook", collectionToJson(gradebook));
|
||||
json.put("resources", collectionToJson(resources));
|
||||
return json;
|
||||
}
|
||||
|
||||
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) {
|
||||
|
||||
title = title.replaceAll("(.*?) (S[0-9]{2}|W[0-9/]{5})", "$1");
|
||||
|
||||
@@ -192,11 +231,71 @@ public class Modules implements Iterable<Modules.Module>, Serializable {
|
||||
this.type = type;
|
||||
this.description = description;
|
||||
this.ID = ID;
|
||||
this.moduleType = moduleType;
|
||||
}
|
||||
|
||||
public void setLecturers(LinkedHashSet<Lecturer> lecturers) {
|
||||
this.lecturer = new ArrayList<>(lecturers);
|
||||
private Module(@NotNull JSONObject json) throws JSONException {
|
||||
HashSet<String> lv = new HashSet<>();
|
||||
for (String number: UtilsJson.jsonArrayToIterableString(json.getJSONArray("lvNumber"))) {
|
||||
lv.add(number);
|
||||
}
|
||||
LinkedHashSet<Lecturer> lecturer = new LinkedHashSet<>();
|
||||
for (JSONObject l: UtilsJson.jsonArrayToIterableObject(json.getJSONArray("lecturer"))) {
|
||||
lecturer.add(new Lecturer(l));
|
||||
}
|
||||
JSONObject obj = json.optJSONObject("semester");
|
||||
|
||||
this.semester = obj != null ? new Semester(obj) : null;
|
||||
this.lvNumber = lv;
|
||||
this.title = json.getString("title");
|
||||
this.lecturer = new ArrayList<>(lecturer);
|
||||
this.type = json.getString("type");
|
||||
this.description = json.getString("description");
|
||||
this.ID = json.getString("ID");
|
||||
|
||||
JSONArray arr = json.optJSONArray("announcements");
|
||||
if (obj != null) {
|
||||
ArrayList<Announcement> announce = new ArrayList<>();
|
||||
for (JSONObject l: UtilsJson.jsonArrayToIterableObject(arr)) {
|
||||
announce.add(new Announcement(l));
|
||||
}
|
||||
this.announcements = announce;
|
||||
}
|
||||
arr = json.optJSONArray("assignments");
|
||||
if (obj != null) {
|
||||
AssignmentList assign = new AssignmentList();
|
||||
for (JSONObject l: UtilsJson.jsonArrayToIterableObject(arr)) {
|
||||
assign.add(new Assignment(l));
|
||||
}
|
||||
this.assignments = assign;
|
||||
}
|
||||
|
||||
arr = json.optJSONArray("events");
|
||||
if (obj != null) {
|
||||
EventList events = new EventList();
|
||||
for (JSONObject l: UtilsJson.jsonArrayToIterableObject(arr)) {
|
||||
events.add(new Event(l));
|
||||
}
|
||||
this.events = events;
|
||||
}
|
||||
arr = json.optJSONArray("gradebook");
|
||||
if (obj != null) {
|
||||
ArrayList<Grade> grades = new ArrayList<>();
|
||||
for (JSONObject l: UtilsJson.jsonArrayToIterableObject(arr)) {
|
||||
grades.add(new Grade(l));
|
||||
}
|
||||
this.gradebook = grades;
|
||||
}
|
||||
arr = json.optJSONArray("resources");
|
||||
if (obj != null) {
|
||||
ArrayList<Resource> res = new ArrayList<>();
|
||||
for (JSONObject l: UtilsJson.jsonArrayToIterableObject(arr)) {
|
||||
if (l.getString("restype").equals("file"))
|
||||
res.add(new Resource.File(l));
|
||||
else
|
||||
res.add(new Resource.Folder(l));
|
||||
}
|
||||
this.resources = res;
|
||||
}
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@@ -214,19 +313,5 @@ public class Modules implements Iterable<Modules.Module>, Serializable {
|
||||
"\ntype: "+type+
|
||||
"\nID: "+ID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(semester, lvNumber, title, lecturer, type, description, ID, moduleType);
|
||||
}
|
||||
|
||||
public int getModuleType() {
|
||||
return moduleType;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public Module clone() {
|
||||
return new Module(semester, lvNumber, title, new LinkedHashSet<>(lecturer), type, description, ID, moduleType);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,17 +2,20 @@ package de.sebse.fuplanner.services.kvv.types;
|
||||
|
||||
import com.google.android.gms.common.internal.Objects;
|
||||
|
||||
import java.io.Serializable;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import androidx.annotation.LayoutRes;
|
||||
import androidx.annotation.NonNull;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.tools.UtilsJson;
|
||||
import de.sebse.fuplanner.tools.ui.treeview.LayoutItemType;
|
||||
import de.sebse.fuplanner.tools.ui.treeview.TreeNode;
|
||||
|
||||
|
||||
public abstract class Resource implements Serializable {
|
||||
public abstract class Resource implements UtilsJson.JsonConvertible {
|
||||
|
||||
final String author;
|
||||
final long modifiedDate;
|
||||
@@ -62,75 +65,17 @@ public abstract class Resource implements Serializable {
|
||||
return Objects.hashCode(getAuthor(), getContainer(), getModifiedDate(), getTitle(), getUrl());
|
||||
}
|
||||
|
||||
public static class Document extends Resource implements LayoutItemType {
|
||||
|
||||
private final ArrayList<DownloadFile> urls;
|
||||
private final String body;
|
||||
|
||||
public Document(String author, String title, long modifiedDate, String url, boolean visible, String container, String body) {
|
||||
super(author, title, modifiedDate, url, visible, container);
|
||||
this.body = body;
|
||||
this.urls = new ArrayList<>();
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Resource{" +
|
||||
"author='" + author + '\'' +
|
||||
", modifiedDate=" + modifiedDate +
|
||||
", title='" + title + '\'' +
|
||||
", url='" + url + '\'' +
|
||||
", body='" + body + '\'' +
|
||||
", urls='" + urls + '\'' +
|
||||
'}';
|
||||
}
|
||||
|
||||
public String getBody() {
|
||||
return body;
|
||||
}
|
||||
|
||||
public void addUrl(String url, String name){
|
||||
urls.add(new DownloadFile(url, name));
|
||||
}
|
||||
|
||||
public DownloadFile getUrl(int id){
|
||||
return urls.get(id);
|
||||
}
|
||||
|
||||
public int size(){
|
||||
return urls.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public TreeNode getTreeNode() {
|
||||
return new TreeNode<>(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @LayoutRes int getLayoutId() {
|
||||
return R.layout.list_announcement_items;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(super.hashCode(), urls, body, this.getClass().getSimpleName());
|
||||
}
|
||||
|
||||
public class DownloadFile implements Serializable {
|
||||
public final String url;
|
||||
public final String name;
|
||||
|
||||
public DownloadFile(String url, String name) {
|
||||
this.url = url;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(url, name);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public JSONObject toJSONObject() throws JSONException {
|
||||
JSONObject json = new JSONObject();
|
||||
json.put("author", author);
|
||||
json.put("modifiedDate", modifiedDate);
|
||||
json.put("title", title);
|
||||
json.put("url", url);
|
||||
json.put("visible", visible);
|
||||
json.put("container", container);
|
||||
json.put("restype", "");
|
||||
return json;
|
||||
}
|
||||
|
||||
public static class File extends Resource implements LayoutItemType {
|
||||
@@ -164,8 +109,11 @@ public abstract class Resource implements Serializable {
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(super.hashCode(), this.type, this.getClass().getSimpleName());
|
||||
public JSONObject toJSONObject() throws JSONException {
|
||||
JSONObject json = super.toJSONObject();
|
||||
json.put("type", type);
|
||||
json.put("restype", "file");
|
||||
return json;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,8 +164,11 @@ public abstract class Resource implements Serializable {
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(super.hashCode(), children, this.getClass().getSimpleName());
|
||||
public JSONObject toJSONObject() throws JSONException {
|
||||
JSONObject json = super.toJSONObject();
|
||||
json.put("children", UtilsJson.collectionToJson(children));
|
||||
json.put("restype", "dir");
|
||||
return json;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
package de.sebse.fuplanner.services.kvv.types;
|
||||
|
||||
import java.io.Serializable;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import de.sebse.fuplanner.tools.Regex;
|
||||
import de.sebse.fuplanner.tools.UtilsJson;
|
||||
|
||||
public class Semester implements Serializable {
|
||||
public class Semester implements UtilsJson.JsonConvertible {
|
||||
public static final int SEM_WS = 1;
|
||||
public static final int SEM_SS = 2;
|
||||
private int type;
|
||||
@@ -18,25 +19,17 @@ public class Semester implements Serializable {
|
||||
}
|
||||
|
||||
public Semester(String semester_string) throws NoSuchFieldException {
|
||||
/*Semester sem = null;
|
||||
if (semester != null) {
|
||||
sem = new Semester(semester)
|
||||
semester = semester.replace("SS", "S");
|
||||
semester = semester.replaceAll("[0-9]{2}([0-9]{2})", "$1");
|
||||
}*/
|
||||
|
||||
|
||||
/*String s1type = Regex.regex("^(S|WS) ", a);
|
||||
int s1year = Integer.parseInt(Regex.regex("^(S|WS) ([0-9]{2})", a, 2));
|
||||
String s2type = Regex.regex("^(S|WS) ", b);
|
||||
int s2year = Integer.parseInt(Regex.regex("^(S|WS) ([0-9]{2})", b, 2));*/
|
||||
|
||||
String type = Regex.regex("^(SS|WS) ", semester_string);
|
||||
String year = Regex.regex("^(SS|WS) ([0-9]{2})", semester_string, 2);
|
||||
this.type = type.equals("SS") ? SEM_SS : SEM_WS;
|
||||
this.year = Integer.parseInt(year);
|
||||
}
|
||||
|
||||
public Semester(JSONObject json) throws JSONException {
|
||||
this.type = json.getInt("type");
|
||||
this.year = json.getInt("year");
|
||||
}
|
||||
|
||||
public int getType() {
|
||||
return type;
|
||||
}
|
||||
@@ -54,9 +47,11 @@ public class Semester implements Serializable {
|
||||
return false;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
return (type == SEM_SS ? "SS" : "WS") + year;
|
||||
public JSONObject toJSONObject() throws JSONException {
|
||||
JSONObject json = new JSONObject();
|
||||
json.put("type", type);
|
||||
json.put("year", year);
|
||||
return json;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package de.sebse.fuplanner.services.kvv.types;
|
||||
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import de.sebse.fuplanner.tools.SortedList;
|
||||
|
||||
|
||||
@@ -2,16 +2,15 @@ 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;
|
||||
@@ -49,14 +48,8 @@ public class Download {
|
||||
if (context == null)
|
||||
return;
|
||||
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
|
||||
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());
|
||||
}
|
||||
File f = new File(Environment.getExternalStoragePublicDirectory(
|
||||
Environment.DIRECTORY_DOWNLOADS)+"/"+folderName+"/"+file.getTitle());
|
||||
Resources resources = context.getResources();
|
||||
String message = "";
|
||||
if (file.getAuthor() != null && !file.getAuthor().isEmpty())
|
||||
@@ -111,22 +104,20 @@ public class Download {
|
||||
showDownloadError();
|
||||
return;
|
||||
}
|
||||
activity.getKVV(kvv -> {
|
||||
kvv.modules().resources().file(file.getTitle(), file.getUrl(), folderName, success -> {
|
||||
Context context = contextInterface.get();
|
||||
if (success.equals("") || context== null) {
|
||||
showDownloadError();
|
||||
} else {
|
||||
if (Regex.has("^http", success)){
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(success));
|
||||
context.startActivity(intent);
|
||||
}
|
||||
else {
|
||||
fileOpen(new File(success));
|
||||
}
|
||||
activity.getKVV().modules().resources().file(file.getTitle(), file.getUrl(), folderName, success -> {
|
||||
Context context = contextInterface.get();
|
||||
if (success.equals("") || context== null) {
|
||||
showDownloadError();
|
||||
} else {
|
||||
if (Regex.has("^http", success)){
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(success));
|
||||
context.startActivity(intent);
|
||||
}
|
||||
}, log::e, downloadNew);
|
||||
});
|
||||
else {
|
||||
fileOpen(new File(success));
|
||||
}
|
||||
}
|
||||
}, log::e, downloadNew);
|
||||
}
|
||||
|
||||
private void showDownloadError() {
|
||||
@@ -155,6 +146,11 @@ 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) {
|
||||
@@ -196,7 +192,11 @@ public class Download {
|
||||
Uri uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".my.provider", url);
|
||||
|
||||
Intent intent;
|
||||
intent = new Intent(Intent.ACTION_VIEW);
|
||||
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
|
||||
intent = new Intent(Intent.ACTION_VIEW);
|
||||
} else {
|
||||
intent = new Intent();
|
||||
}
|
||||
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.
|
||||
@@ -244,12 +244,7 @@ public class Download {
|
||||
intent.setDataAndType(uri, "*/*");
|
||||
}
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
try {
|
||||
context.startActivity(intent);
|
||||
} catch (ActivityNotFoundException e) {
|
||||
log.e("No matching activity found!");
|
||||
e.printStackTrace();
|
||||
}
|
||||
context.startActivity(intent);
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ 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;
|
||||
@@ -16,7 +15,6 @@ 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 {
|
||||
@@ -53,28 +51,21 @@ public class NewsManager {
|
||||
|
||||
for (int i = news.length() - 1; i >= 0; i--) {
|
||||
try {
|
||||
String title;
|
||||
if (news.getJSONObject(i).has("title_" + language)) {
|
||||
title = news.getJSONObject(i).getString("title_" + language);
|
||||
} else {
|
||||
String title = news.getJSONObject(i).optString("title_" + language, null);
|
||||
if (title == null)
|
||||
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 = News.CATEGORY_TRICKS;
|
||||
category = de.sebse.fuplanner.tools.types.News.CATEGORY_TRICKS;
|
||||
else
|
||||
category = News.CATEGORY_UPDATE;
|
||||
category = de.sebse.fuplanner.tools.types.News.CATEGORY_UPDATE;
|
||||
String dateString = news.getJSONObject(i).getString("date");
|
||||
long date = UtilsDate.stringToMillis(dateString, "dd.MM.yyyy");
|
||||
News event = new News(title, category, date, text);
|
||||
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);
|
||||
dates.add(event);
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
@@ -91,7 +82,7 @@ public class NewsManager {
|
||||
byte[] buffer = new byte[size];
|
||||
is.read(buffer);
|
||||
is.close();
|
||||
return new String(buffer, StandardCharsets.UTF_8);
|
||||
return new String(buffer, "UTF-8");
|
||||
} catch (IOException ex) {
|
||||
ex.printStackTrace();
|
||||
return null;
|
||||
|
||||
@@ -9,16 +9,16 @@ import android.app.Activity;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import de.sebse.fuplanner.services.kvv.Login;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
|
||||
public class CustomAccountManager {
|
||||
private final AccountManager mAccountManager;
|
||||
private final ActivityInterface mActivityInterface;
|
||||
private Logger log = new Logger(this);
|
||||
|
||||
public CustomAccountManager(AccountManager manager, ActivityInterface activityInterface) {
|
||||
mAccountManager = manager;
|
||||
@@ -34,7 +34,11 @@ public class CustomAccountManager {
|
||||
try {
|
||||
String token = mAccountManager.blockingGetAuthToken(account, authTokenType, true);
|
||||
mAccountManager.invalidateAuthToken(accountType, token);
|
||||
} catch (AuthenticatorException | OperationCanceledException | IOException e) {
|
||||
} catch (AuthenticatorException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} catch (OperationCanceledException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
@@ -49,7 +53,11 @@ public class CustomAccountManager {
|
||||
if (callback != null)
|
||||
callback.run(true);
|
||||
return;
|
||||
} catch (AuthenticatorException | OperationCanceledException | IOException e) {
|
||||
} catch (AuthenticatorException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} catch (OperationCanceledException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
if (callback != null)
|
||||
@@ -59,6 +67,7 @@ public class CustomAccountManager {
|
||||
|
||||
public void deleteAccount(String accountType) {
|
||||
Account[] accounts = mAccountManager.getAccountsByType(accountType);
|
||||
int[] count = {accounts.length};
|
||||
for (Account account: accounts) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
|
||||
mAccountManager.removeAccount(account, null, null, null);
|
||||
@@ -68,7 +77,7 @@ public class CustomAccountManager {
|
||||
}
|
||||
}
|
||||
|
||||
public void getTokenByType(String accountType, String authTokenType, @Nullable StringInterface callback, @Nullable ExceptionInterface errorCallback) {
|
||||
public void getTokenByType(String accountType, String authTokenType, @Nullable StringInterface callback) {
|
||||
Activity activity = mActivityInterface.get();
|
||||
AccountManagerCallback<Bundle> cb = (accountManagerFuture -> {
|
||||
try {
|
||||
@@ -76,11 +85,16 @@ public class CustomAccountManager {
|
||||
final String authtoken = bnd.getString(AccountManager.KEY_AUTHTOKEN);
|
||||
if (callback != null)
|
||||
callback.run(authtoken);
|
||||
} catch (AuthenticatorException | IOException | OperationCanceledException e) {
|
||||
return;
|
||||
} catch (AuthenticatorException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} catch (OperationCanceledException e) {
|
||||
e.printStackTrace();
|
||||
if (errorCallback != null)
|
||||
errorCallback.run(e);
|
||||
}
|
||||
if (callback != null)
|
||||
callback.run(null);
|
||||
});
|
||||
if (activity != null) {
|
||||
mAccountManager.getAuthTokenByFeatures(accountType, authTokenType, null, mActivityInterface.get(), null, null, cb, null);
|
||||
@@ -94,7 +108,11 @@ public class CustomAccountManager {
|
||||
Account account = mAccountManager.getAccountsByType(accountType)[0];
|
||||
try {
|
||||
return mAccountManager.blockingGetAuthToken(account, authTokenType, true);
|
||||
} catch (AuthenticatorException | OperationCanceledException | IOException e) {
|
||||
} catch (AuthenticatorException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} catch (OperationCanceledException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
@@ -104,13 +122,6 @@ public class CustomAccountManager {
|
||||
return mAccountManager.getAccountsByType(accountType).length != 0;
|
||||
}
|
||||
|
||||
public Account getAccountByType(String accountType) {
|
||||
Account[] accountsByType = mAccountManager.getAccountsByType(accountType);
|
||||
if (accountsByType.length > 0)
|
||||
return accountsByType[0];
|
||||
return null;
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface ActivityInterface {
|
||||
@Nullable
|
||||
@@ -120,8 +131,4 @@ public class CustomAccountManager {
|
||||
public interface StringInterface {
|
||||
void run(@Nullable String string);
|
||||
}
|
||||
|
||||
public interface ExceptionInterface {
|
||||
void run(@NotNull Exception string);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
package de.sebse.fuplanner.tools;
|
||||
|
||||
import android.app.NotificationChannel;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Build;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import androidx.core.app.NotificationCompat;
|
||||
import androidx.core.app.NotificationManagerCompat;
|
||||
import de.sebse.fuplanner.MainActivity;
|
||||
import de.sebse.fuplanner.R;
|
||||
|
||||
public class CustomNotificationManager {
|
||||
private static final String CHANNEL_ID = "fuplanner-default";
|
||||
public static final String NOTIFICATION_INTENT = "notification-intent";
|
||||
public static final String NOTIFICATION_PAGE = "notification-page";
|
||||
public static final String NOTIFICATION_DATA = "notification-data";
|
||||
public static final String NOTIFICATION_TYPE_NAVIGATE = "navigate";
|
||||
|
||||
//public static ArrayList<Integer> passedNotifications = new ArrayList<>();
|
||||
|
||||
public static void sendNotification(Context context, String textTitle, String textContent, int page, String data) {
|
||||
Intent intent = new Intent(context, MainActivity.class);
|
||||
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
|
||||
intent.putExtra(NOTIFICATION_INTENT, NOTIFICATION_TYPE_NAVIGATE);
|
||||
intent.putExtra(NOTIFICATION_PAGE, page);
|
||||
intent.putExtra(NOTIFICATION_DATA, data);
|
||||
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
|
||||
|
||||
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(textTitle)
|
||||
.setContentText(textContent)
|
||||
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
||||
.setContentIntent(pendingIntent)
|
||||
.setAutoCancel(true);
|
||||
|
||||
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
|
||||
int notificationId = (int) (System.currentTimeMillis() % Integer.MAX_VALUE);
|
||||
notificationManager.notify(notificationId, mBuilder.build());
|
||||
}
|
||||
|
||||
public static void createNotificationChannel(@NotNull Context context) {
|
||||
// Create the NotificationChannel, but only on API 26+ because
|
||||
// the NotificationChannel class is new and not in the support library
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
CharSequence name = context.getString(R.string.channel_name);
|
||||
String description = context.getString(R.string.channel_description);
|
||||
int importance = NotificationManager.IMPORTANCE_DEFAULT;
|
||||
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
|
||||
channel.setDescription(description);
|
||||
// Register the channel with the system; you can't change the importance
|
||||
// or other notification behaviors after this
|
||||
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
|
||||
if (notificationManager != null) {
|
||||
notificationManager.createNotificationChannel(channel);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,8 @@ package de.sebse.fuplanner.tools;
|
||||
|
||||
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.news.NewsManager;
|
||||
|
||||
public interface MainActivityListener {
|
||||
@@ -15,7 +15,7 @@ public interface MainActivityListener {
|
||||
|
||||
void showToast(@StringRes int msgStringRes);
|
||||
|
||||
void getKVV(MainActivity.KVVCallback kvv);
|
||||
KVV getKVV();
|
||||
|
||||
CanteenBrowser getCanteenBrowser();
|
||||
|
||||
@@ -24,6 +24,4 @@ public interface MainActivityListener {
|
||||
void addRequestPermissionsResultListener(RequestPermissionsResultListener listener, String id);
|
||||
|
||||
void removeRequestPermissionsResultListener(String id);
|
||||
|
||||
void forceSync();
|
||||
}
|
||||
|
||||
@@ -5,13 +5,12 @@ import android.util.Pair;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import de.sebse.fuplanner.tools.network.NetworkCallback;
|
||||
import de.sebse.fuplanner.tools.network.NetworkError;
|
||||
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
|
||||
|
||||
public class NetworkCallbackCollector<T> extends HashSet<Pair<NetworkCallback<T>, NetworkErrorCallback>> {
|
||||
public void add(@Nullable NetworkCallback<T> success, @Nullable NetworkErrorCallback error) {
|
||||
public void add(NetworkCallback<T> success, NetworkErrorCallback error) {
|
||||
add(new Pair<>(success, error));
|
||||
}
|
||||
|
||||
@@ -19,8 +18,7 @@ public class NetworkCallbackCollector<T> extends HashSet<Pair<NetworkCallback<T>
|
||||
Iterator<Pair<NetworkCallback<T>, NetworkErrorCallback>> i;
|
||||
for (i = this.iterator(); i.hasNext();) {
|
||||
Pair<NetworkCallback<T>, NetworkErrorCallback> pair = i.next();
|
||||
if (pair.second != null)
|
||||
pair.second.onError(error);
|
||||
pair.second.onError(error);
|
||||
i.remove();
|
||||
}
|
||||
}
|
||||
@@ -29,8 +27,7 @@ public class NetworkCallbackCollector<T> extends HashSet<Pair<NetworkCallback<T>
|
||||
Iterator<Pair<NetworkCallback<T>, NetworkErrorCallback>> i;
|
||||
for (i = this.iterator(); i.hasNext();) {
|
||||
Pair<NetworkCallback<T>, NetworkErrorCallback> pair = i.next();
|
||||
if (pair.first != null)
|
||||
pair.first.onResponse(success);
|
||||
pair.first.onResponse(success);
|
||||
i.remove();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,9 +9,6 @@ public class NewAsyncQueue {
|
||||
private final LinkedList<AsyncQueueCallback> mQueue = new LinkedList<>();
|
||||
private boolean mIsRunning = false;
|
||||
|
||||
public NewAsyncQueue() {
|
||||
}
|
||||
|
||||
public void add(AsyncQueueCallback callback) {
|
||||
if (isRunning())
|
||||
getQueue().addLast(callback);
|
||||
|
||||
@@ -1,76 +1,23 @@
|
||||
package de.sebse.fuplanner.tools;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
|
||||
import androidx.annotation.ArrayRes;
|
||||
import androidx.annotation.StringRes;
|
||||
import androidx.preference.PreferenceManager;
|
||||
|
||||
public class Preferences {
|
||||
public static String getStringArray(Context context, @ArrayRes int key) {
|
||||
public static String getString(Context context, @ArrayRes int key) {
|
||||
String[] strings = context.getResources().getStringArray(key);
|
||||
return PreferenceManager.getDefaultSharedPreferences(context).getString(strings[0], strings[1]);
|
||||
}
|
||||
|
||||
|
||||
public static String getString(Context context, @StringRes int key) {
|
||||
String string = context.getResources().getString(key);
|
||||
return PreferenceManager.getDefaultSharedPreferences(context).getString(string, null);
|
||||
}
|
||||
public static void setString(Context context, @StringRes int key, String value) {
|
||||
String string = context.getResources().getString(key);
|
||||
PreferenceManager.getDefaultSharedPreferences(context).edit().putString(string, value).apply();
|
||||
}
|
||||
|
||||
public static long getLong(Context context, @StringRes int key) {
|
||||
String string = context.getResources().getString(key);
|
||||
return PreferenceManager.getDefaultSharedPreferences(context).getLong(string, 0);
|
||||
}
|
||||
|
||||
public static void setLong(Context context, @StringRes int key, long value) {
|
||||
String string = context.getResources().getString(key);
|
||||
PreferenceManager.getDefaultSharedPreferences(context).edit().putLong(string, value).apply();
|
||||
}
|
||||
|
||||
public static boolean getBoolean(Context context, @StringRes int key) {
|
||||
String string = context.getResources().getString(key);
|
||||
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(string, false);
|
||||
}
|
||||
public static void setBoolean(Context context, @StringRes int key, boolean value) {
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,15 +30,6 @@ public class Regex {
|
||||
return matcher.group(group);
|
||||
}
|
||||
|
||||
public static Matcher match(@Language("Regexp") String regex, String match) throws NoSuchFieldException {
|
||||
Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
|
||||
Matcher matcher = pattern.matcher(match);
|
||||
if (!matcher.find()) {
|
||||
throw new NoSuchFieldException(String.format("Pattern: %s - String: %s", regex, match));
|
||||
}
|
||||
return matcher;
|
||||
}
|
||||
|
||||
public static Iterable<MatchResult> allMatches(@Language("Regexp") String regex, final CharSequence input) {
|
||||
final Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
|
||||
return () -> new Iterator<MatchResult>() {
|
||||
|
||||
@@ -3,12 +3,11 @@ package de.sebse.fuplanner.tools;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
|
||||
public abstract class SortedList<T, I, F> implements Iterable<T>, Serializable {
|
||||
public abstract class SortedList<T, I, F> implements Iterable<T> {
|
||||
|
||||
private final ArrayList<T> internalList = new ArrayList<>();
|
||||
|
||||
|
||||
@@ -49,7 +49,11 @@ public class UtilsDate {
|
||||
skeleton = skeleton.replaceAll("h", "H");
|
||||
if (context != null && !DateFormat.is24HourFormat(context))
|
||||
skeleton = skeleton.replaceAll("H", "h");
|
||||
dateFormat = new SimpleDateFormat(getDateFormat(locale, skeleton));
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
|
||||
dateFormat = new SimpleDateFormat(getDateFormat(locale, skeleton));
|
||||
} else {
|
||||
dateFormat = new SimpleDateFormat(skeleton, locale);
|
||||
}
|
||||
|
||||
return dateFormat.format(new Date(modified));
|
||||
}
|
||||
|
||||
109
app/src/main/java/de/sebse/fuplanner/tools/UtilsJson.java
Normal file
109
app/src/main/java/de/sebse/fuplanner/tools/UtilsJson.java
Normal file
@@ -0,0 +1,109 @@
|
||||
package de.sebse.fuplanner.tools;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
public class UtilsJson {
|
||||
public static JSONArray collectionToJson(@Nullable HashSet<String> coll) {
|
||||
if (coll == null)
|
||||
return null;
|
||||
JSONArray arr = new JSONArray();
|
||||
for (String e: coll) {
|
||||
arr.put(e);
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
public static <E extends JsonConvertible> JSONArray collectionToJson(@Nullable Collection<E> coll) throws JSONException {
|
||||
if (coll == null)
|
||||
return null;
|
||||
JSONArray arr = new JSONArray();
|
||||
for (E e: coll) {
|
||||
arr.put(e.toJSONObject());
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
public static JSONArray collectionToJson(@Nullable ArrayList<String> coll) throws JSONException {
|
||||
if (coll == null)
|
||||
return null;
|
||||
JSONArray arr = new JSONArray();
|
||||
for (String e: coll) {
|
||||
arr.put(e);
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
public static <A extends JsonConvertible> JSONArray collectionToJson(@Nullable SortedList<A, ?, ?> coll) throws JSONException {
|
||||
if (coll == null)
|
||||
return null;
|
||||
JSONArray arr = new JSONArray();
|
||||
for (A e: coll) {
|
||||
arr.put(e.toJSONObject());
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
public static <T> Iterator<T> jsonArrayToIterator(JSONArray array, GetInterface<T> func) {
|
||||
return new Iterator<T>() {
|
||||
int size = array == null ? 0 : array.length();
|
||||
int pos = 0;
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return pos < size;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T next() {
|
||||
try {
|
||||
return func.get(array, pos++);
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface GetInterface<T> {
|
||||
T get(JSONArray array, int index) throws JSONException;
|
||||
}
|
||||
|
||||
public static JsonIterable<JSONObject> jsonArrayToIterableObject(JSONArray array) {
|
||||
return new JsonIterable<>(array, JSONArray::getJSONObject);
|
||||
}
|
||||
|
||||
public static JsonIterable<String> jsonArrayToIterableString(JSONArray array) {
|
||||
return new JsonIterable<>(array, JSONArray::getString);
|
||||
}
|
||||
|
||||
public static class JsonIterable<T> implements Iterable<T> {
|
||||
private JSONArray array;
|
||||
private GetInterface<T> getInterface;
|
||||
|
||||
JsonIterable(JSONArray array, GetInterface<T> getInterface) {
|
||||
this.array = array;
|
||||
this.getInterface = getInterface;
|
||||
}
|
||||
@NonNull
|
||||
@Override
|
||||
public Iterator<T> iterator() {
|
||||
return UtilsJson.jsonArrayToIterator(array, getInterface);
|
||||
}
|
||||
}
|
||||
|
||||
public interface JsonConvertible {
|
||||
JSONObject toJSONObject() throws JSONException;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,219 +0,0 @@
|
||||
package de.sebse.fuplanner.tools.network;
|
||||
|
||||
import android.app.Service;
|
||||
import android.content.Intent;
|
||||
import android.os.Binder;
|
||||
import android.os.IBinder;
|
||||
|
||||
import com.android.volley.AuthFailureError;
|
||||
import com.android.volley.NetworkResponse;
|
||||
import com.android.volley.Request;
|
||||
import com.android.volley.RequestQueue;
|
||||
import com.android.volley.Response;
|
||||
import com.android.volley.TimeoutError;
|
||||
import com.android.volley.VolleyError;
|
||||
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 androidx.annotation.Nullable;
|
||||
import de.sebse.fuplanner.tools.EventListener;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
|
||||
/**
|
||||
* Created by sebastian on 24.10.17.
|
||||
*/
|
||||
|
||||
public class HTTPNetwork extends Service {
|
||||
private RequestQueue requestQueue;
|
||||
protected final Logger log = new Logger(this);
|
||||
private final EventListener<VolleyError> errorResponseListener = new EventListener<>();
|
||||
private final EventListener<Result> successResponseListener = new EventListener<>();
|
||||
// Binder given to clients
|
||||
private final IBinder mBinder = new LocalBinder();
|
||||
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
requestQueue = Volley.newRequestQueue(getApplicationContext(), new BetterHurlStack(false));
|
||||
}
|
||||
|
||||
public void addErrorListener(String id, EventListener.EventFunction<VolleyError> listener) {
|
||||
errorResponseListener.add(id, listener);
|
||||
}
|
||||
|
||||
public void removeErrorListener(String id) {
|
||||
errorResponseListener.remove(id);
|
||||
}
|
||||
|
||||
public void addSuccessListener(String id, EventListener.EventFunction<Result> listener) {
|
||||
successResponseListener.add(id, listener);
|
||||
}
|
||||
|
||||
public void removeSuccessListener(String id) {
|
||||
successResponseListener.remove(id);
|
||||
}
|
||||
|
||||
protected void head(String url, @Nullable final HashMap<String, String> cookies, Response.Listener<Result> response, Response.ErrorListener error) {
|
||||
get(url, cookies, response, error, true);
|
||||
}
|
||||
|
||||
protected void get(String url, @Nullable final HashMap<String, String> cookies, Response.Listener<Result> response, Response.ErrorListener error) {
|
||||
get(url, cookies, response, error, false);
|
||||
}
|
||||
|
||||
private void get(String url, @Nullable final HashMap<String, String> cookies, Response.Listener<Result> response, Response.ErrorListener error, boolean noBody) {
|
||||
int requestMethod = noBody ? Request.Method.HEAD : Request.Method.GET;
|
||||
HttpRequest request = new HttpRequest(requestMethod, url, response, error) {
|
||||
@Override
|
||||
public void deliverError(VolleyError error) {
|
||||
if (error == null) {
|
||||
deliver(new VolleyError(new NetworkResponse(500, null, true, 0, null)));
|
||||
} else if (error.networkResponse == null) {
|
||||
int statusCode;
|
||||
if (error instanceof TimeoutError)
|
||||
statusCode = 408;
|
||||
else
|
||||
statusCode = 500;
|
||||
deliver(new VolleyError(new NetworkResponse(statusCode, null, true, error.getNetworkTimeMs(), null)));
|
||||
} else {
|
||||
final int status = error.networkResponse.statusCode;
|
||||
if (status == 302) {
|
||||
deliverResponse(new Result(null, error.networkResponse.headers));
|
||||
} else {
|
||||
deliver(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void deliverResponse(Result response) {
|
||||
successResponseListener.emit(response);
|
||||
super.deliverResponse(response);
|
||||
}
|
||||
|
||||
private void deliver(VolleyError error) {
|
||||
errorResponseListener.emit(error);
|
||||
super.deliverError(error);
|
||||
}
|
||||
|
||||
public Map<String, String> getHeaders() throws AuthFailureError {
|
||||
Map<String, String> params = super.getHeaders();
|
||||
if (cookies != null) {
|
||||
if (params==null)
|
||||
params = new HashMap<>();
|
||||
else
|
||||
params = new HashMap<>(params);
|
||||
StringBuilder newStr = new StringBuilder();
|
||||
for (String key : cookies.keySet())
|
||||
newStr.append(key).append("=").append(cookies.get(key)).append(";");
|
||||
newStr = new StringBuilder(newStr.substring(0, newStr.length() - 1));
|
||||
params.put("Cookie", newStr.toString());
|
||||
}
|
||||
|
||||
return params;
|
||||
}
|
||||
};
|
||||
requestQueue.add(request);
|
||||
}
|
||||
|
||||
protected void post(String url, @Nullable final HashMap<String, String> cookies, @Nullable final HashMap<String, String> body, Response.Listener<Result> response, Response.ErrorListener error) {
|
||||
HttpRequest request = new HttpRequest(Request.Method.POST, url, response, error) {
|
||||
@Override
|
||||
public String getBodyContentType() {
|
||||
return "application/x-www-form-urlencoded";
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] getBody() {
|
||||
if (body==null) {
|
||||
return null;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for(HashMap.Entry<String, String> e: body.entrySet()){
|
||||
if(sb.length() > 0){
|
||||
sb.append('&');
|
||||
}
|
||||
try {
|
||||
sb.append(URLEncoder.encode(e.getKey(), "UTF-8")).append('=').append(URLEncoder.encode(e.getValue(), "UTF-8"));
|
||||
} catch (UnsupportedEncodingException ignored) {
|
||||
}
|
||||
}
|
||||
String requestBody = sb.toString();
|
||||
return requestBody.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deliverError(VolleyError error) {
|
||||
if (error == null) {
|
||||
deliver(new VolleyError(new NetworkResponse(500, null, true, 0, null)));
|
||||
} else if (error.networkResponse == null) {
|
||||
int statusCode;
|
||||
if (error instanceof TimeoutError)
|
||||
statusCode = 408;
|
||||
else
|
||||
statusCode = 500;
|
||||
deliver(new VolleyError(new NetworkResponse(statusCode, null, true, error.getNetworkTimeMs(), null)));
|
||||
} else {
|
||||
final int status = error.networkResponse.statusCode;
|
||||
if (status == 302) {
|
||||
deliverResponse(new Result(null, error.networkResponse.headers));
|
||||
} else {
|
||||
deliver(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void deliver(VolleyError error) {
|
||||
errorResponseListener.emit(error);
|
||||
super.deliverError(error);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void deliverResponse(Result response) {
|
||||
successResponseListener.emit(response);
|
||||
super.deliverResponse(response);
|
||||
}
|
||||
|
||||
public Map<String, String> getHeaders() throws AuthFailureError {
|
||||
Map<String, String> params = super.getHeaders();
|
||||
if (cookies != null) {
|
||||
if (params==null)
|
||||
params = new HashMap<>();
|
||||
else
|
||||
params = new HashMap<>(params);
|
||||
StringBuilder newStr = new StringBuilder();
|
||||
for (String key : cookies.keySet())
|
||||
newStr.append(key).append("=").append(cookies.get(key)).append(";");
|
||||
newStr = new StringBuilder(newStr.substring(0, newStr.length() - 1));
|
||||
params.put("Cookie", newStr.toString());
|
||||
}
|
||||
|
||||
return params;
|
||||
}
|
||||
};
|
||||
requestQueue.add(request);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return mBinder;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Class used for the client Binder. Because we know this service always
|
||||
* runs in the same process as its clients, we don't need to deal with IPC.
|
||||
*/
|
||||
public class LocalBinder extends Binder {
|
||||
public HTTPNetwork getService() {
|
||||
// Return this instance of LocalService so clients can call public methods
|
||||
return HTTPNetwork.this;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,23 @@
|
||||
package de.sebse.fuplanner.tools.network;
|
||||
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.ServiceConnection;
|
||||
import android.os.CountDownTimer;
|
||||
import android.os.IBinder;
|
||||
|
||||
import com.android.volley.AuthFailureError;
|
||||
import com.android.volley.NetworkResponse;
|
||||
import com.android.volley.Request;
|
||||
import com.android.volley.RequestQueue;
|
||||
import com.android.volley.Response;
|
||||
import com.android.volley.TimeoutError;
|
||||
import com.android.volley.VolleyError;
|
||||
import com.android.volley.toolbox.Volley;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.HashMap;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.Map;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import de.sebse.fuplanner.tools.EventListener;
|
||||
import de.sebse.fuplanner.tools.NewAsyncQueue;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
|
||||
/**
|
||||
@@ -24,172 +25,167 @@ import de.sebse.fuplanner.tools.logging.Logger;
|
||||
*/
|
||||
|
||||
public class HTTPService {
|
||||
private final RequestQueue requestQueue;
|
||||
private final Context mContext;
|
||||
private NewAsyncQueue mQueue = new NewAsyncQueue();
|
||||
protected final Logger log = new Logger(this);
|
||||
|
||||
private int mRequestCount = 0;
|
||||
private final HashMap<String, EventListener.EventFunction<VolleyError>> errorListeners = new HashMap<>();
|
||||
private final HashMap<String, EventListener.EventFunction<Result>> successListeners = new HashMap<>();
|
||||
private CountDownTimer mDisconnectTimer = null;
|
||||
private HTTPNetwork mService;
|
||||
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
|
||||
HTTPNetwork.LocalBinder binder = (HTTPNetwork.LocalBinder) service;
|
||||
mService = binder.getService();
|
||||
mBound = true;
|
||||
for (String listenerKey: errorListeners.keySet()) {
|
||||
mService.addErrorListener(listenerKey, errorListeners.get(listenerKey));
|
||||
}
|
||||
for (String listenerKey: successListeners.keySet()) {
|
||||
mService.addSuccessListener(listenerKey, successListeners.get(listenerKey));
|
||||
}
|
||||
if (mWaitForBound) {
|
||||
mWaitForBound = false;
|
||||
mQueue.next();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onServiceDisconnected(ComponentName arg0) {
|
||||
mBound = false;
|
||||
mService = null;
|
||||
}
|
||||
};
|
||||
private final EventListener<VolleyError> errorResponseListener = new EventListener<>();
|
||||
private final EventListener<Result> successResponseListener = new EventListener<>();
|
||||
|
||||
public HTTPService(Context context) {
|
||||
this.mContext = context;
|
||||
requestQueue = Volley.newRequestQueue(context, new BetterHurlStack(false));
|
||||
}
|
||||
|
||||
public void addErrorListener(String id, EventListener.EventFunction<VolleyError> listener) {
|
||||
errorListeners.put(id, listener);
|
||||
connect();
|
||||
mQueue.add(() -> {
|
||||
mService.addErrorListener(id, listener);
|
||||
mQueue.next();
|
||||
disconnect();
|
||||
});
|
||||
errorResponseListener.add(id, listener);
|
||||
}
|
||||
|
||||
public void removeErrorListener(String id) {
|
||||
errorListeners.remove(id);
|
||||
connect();
|
||||
mQueue.add(() -> {
|
||||
mService.removeErrorListener(id);
|
||||
mQueue.next();
|
||||
disconnect();
|
||||
});
|
||||
errorResponseListener.remove(id);
|
||||
}
|
||||
|
||||
public void addSuccessListener(String id, EventListener.EventFunction<Result> listener) {
|
||||
successListeners.put(id, listener);
|
||||
connect();
|
||||
mQueue.add(() -> {
|
||||
mService.addSuccessListener(id, listener);
|
||||
mQueue.next();
|
||||
disconnect();
|
||||
});
|
||||
successResponseListener.add(id, listener);
|
||||
}
|
||||
|
||||
public void removeSuccessListener(String id) {
|
||||
successListeners.remove(id);
|
||||
connect();
|
||||
mQueue.add(() -> {
|
||||
mService.removeSuccessListener(id);
|
||||
mQueue.next();
|
||||
disconnect();
|
||||
});
|
||||
}
|
||||
|
||||
protected void head(String url, @Nullable final HashMap<String, String> cookies, Response.Listener<Result> response, Response.ErrorListener error) {
|
||||
connect();
|
||||
mQueue.add(() -> {
|
||||
mService.head(url, cookies, response1 -> {
|
||||
response.onResponse(response1);
|
||||
disconnect();
|
||||
}, error1 -> {
|
||||
error.onErrorResponse(error1);
|
||||
disconnect();
|
||||
});
|
||||
mQueue.next();
|
||||
});
|
||||
successResponseListener.remove(id);
|
||||
}
|
||||
|
||||
protected void get(String url, @Nullable final HashMap<String, String> cookies, Response.Listener<Result> response, Response.ErrorListener error) {
|
||||
connect();
|
||||
mQueue.add(() -> {
|
||||
mService.get(url, cookies, response1 -> {
|
||||
response.onResponse(response1);
|
||||
disconnect();
|
||||
}, error1 -> {
|
||||
error.onErrorResponse(error1);
|
||||
disconnect();
|
||||
});
|
||||
mQueue.next();
|
||||
});
|
||||
HttpRequest request = new HttpRequest(Request.Method.GET, url, response, error) {
|
||||
@Override
|
||||
public void deliverError(VolleyError error) {
|
||||
if (error == null) {
|
||||
deliver(new VolleyError(new NetworkResponse(500, null, true, 0, null)));
|
||||
} else if (error.networkResponse == null) {
|
||||
int statusCode;
|
||||
if (error instanceof TimeoutError)
|
||||
statusCode = 408;
|
||||
else
|
||||
statusCode = 500;
|
||||
deliver(new VolleyError(new NetworkResponse(statusCode, null, true, error.getNetworkTimeMs(), null)));
|
||||
} else {
|
||||
final int status = error.networkResponse.statusCode;
|
||||
if (status == 302) {
|
||||
deliverResponse(new Result(null, error.networkResponse.headers));
|
||||
} else {
|
||||
deliver(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void deliverResponse(Result response) {
|
||||
successResponseListener.emit(response);
|
||||
super.deliverResponse(response);
|
||||
}
|
||||
|
||||
private void deliver(VolleyError error) {
|
||||
errorResponseListener.emit(error);
|
||||
super.deliverError(error);
|
||||
}
|
||||
|
||||
public Map<String, String> getHeaders() throws AuthFailureError {
|
||||
Map<String, String> params = super.getHeaders();
|
||||
if (cookies != null) {
|
||||
if (params==null)
|
||||
params = new HashMap<>();
|
||||
else
|
||||
params = new HashMap<>(params);
|
||||
StringBuilder newStr = new StringBuilder();
|
||||
for (String key : cookies.keySet())
|
||||
newStr.append(key).append("=").append(cookies.get(key)).append(";");
|
||||
newStr = new StringBuilder(newStr.substring(0, newStr.length() - 1));
|
||||
params.put("Cookie", newStr.toString());
|
||||
}
|
||||
|
||||
return params;
|
||||
}
|
||||
};
|
||||
requestQueue.add(request);
|
||||
}
|
||||
|
||||
protected void post(String url, @Nullable final HashMap<String, String> cookies, @Nullable final HashMap<String, String> body, Response.Listener<Result> response, Response.ErrorListener error) {
|
||||
connect();
|
||||
mQueue.add(() -> {
|
||||
mService.post(url, cookies, body, response1 -> {
|
||||
response.onResponse(response1);
|
||||
disconnect();
|
||||
}, error1 -> {
|
||||
error.onErrorResponse(error1);
|
||||
disconnect();
|
||||
});
|
||||
mQueue.next();
|
||||
});
|
||||
}
|
||||
|
||||
private void connect() {
|
||||
if (!mBound) {
|
||||
Intent intent = new Intent(getContext(), HTTPNetwork.class);
|
||||
getContext().bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
|
||||
if (!mWaitForBound) mQueue.add(() -> {});
|
||||
mWaitForBound = true;
|
||||
}
|
||||
if (mDisconnectTimer != null) {
|
||||
mDisconnectTimer.cancel();
|
||||
mDisconnectTimer = null;
|
||||
}
|
||||
mRequestCount++;
|
||||
}
|
||||
|
||||
private void disconnect() {
|
||||
mRequestCount--;
|
||||
if (mDisconnectTimer == null) {
|
||||
if (mBound && mRequestCount == 0) {
|
||||
mBound = false;
|
||||
mService = null;
|
||||
getContext().unbindService(mConnection);
|
||||
HttpRequest request = new HttpRequest(Request.Method.POST, url, response, error) {
|
||||
@Override
|
||||
public String getBodyContentType() {
|
||||
return "application/x-www-form-urlencoded";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] getBody() {
|
||||
if (body==null) {
|
||||
return null;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for(HashMap.Entry<String, String> e: body.entrySet()){
|
||||
if(sb.length() > 0){
|
||||
sb.append('&');
|
||||
}
|
||||
try {
|
||||
sb.append(URLEncoder.encode(e.getKey(), "UTF-8")).append('=').append(URLEncoder.encode(e.getValue(), "UTF-8"));
|
||||
} catch (UnsupportedEncodingException ignored) {
|
||||
}
|
||||
}
|
||||
String requestBody = sb.toString();
|
||||
try {
|
||||
return requestBody.getBytes("utf-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
protected String getCookie(String cookies, String name) throws NoSuchFieldException {
|
||||
Pattern pattern = Pattern.compile(name+"=([^;]+);");
|
||||
Matcher matcher = pattern.matcher(cookies);
|
||||
if (!matcher.find()) {
|
||||
log.e("GETcookie failed", name);
|
||||
log.e("GETcookie failed", cookies);
|
||||
throw new NoSuchFieldException();
|
||||
}
|
||||
return matcher.group(1);
|
||||
}
|
||||
@Override
|
||||
public void deliverError(VolleyError error) {
|
||||
if (error == null) {
|
||||
deliver(new VolleyError(new NetworkResponse(500, null, true, 0, null)));
|
||||
} else if (error.networkResponse == null) {
|
||||
int statusCode;
|
||||
if (error instanceof TimeoutError)
|
||||
statusCode = 408;
|
||||
else
|
||||
statusCode = 500;
|
||||
deliver(new VolleyError(new NetworkResponse(statusCode, null, true, error.getNetworkTimeMs(), null)));
|
||||
} else {
|
||||
final int status = error.networkResponse.statusCode;
|
||||
if (status == 302) {
|
||||
deliverResponse(new Result(null, error.networkResponse.headers));
|
||||
} else {
|
||||
deliver(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected HashMap<String, String> getCookie(String cookies, String[] names) throws NoSuchFieldException {
|
||||
HashMap<String, String> result = new HashMap<>();
|
||||
for (String name: names) {
|
||||
result.put(name,this.getCookie(cookies, name));
|
||||
}
|
||||
return result;
|
||||
private void deliver(VolleyError error) {
|
||||
errorResponseListener.emit(error);
|
||||
super.deliverError(error);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void deliverResponse(Result response) {
|
||||
successResponseListener.emit(response);
|
||||
super.deliverResponse(response);
|
||||
}
|
||||
|
||||
public Map<String, String> getHeaders() throws AuthFailureError {
|
||||
Map<String, String> params = super.getHeaders();
|
||||
if (cookies != null) {
|
||||
if (params==null)
|
||||
params = new HashMap<>();
|
||||
else
|
||||
params = new HashMap<>(params);
|
||||
StringBuilder newStr = new StringBuilder();
|
||||
for (String key : cookies.keySet())
|
||||
newStr.append(key).append("=").append(cookies.get(key)).append(";");
|
||||
newStr = new StringBuilder(newStr.substring(0, newStr.length() - 1));
|
||||
params.put("Cookie", newStr.toString());
|
||||
}
|
||||
|
||||
return params;
|
||||
}
|
||||
};
|
||||
requestQueue.add(request);
|
||||
}
|
||||
|
||||
protected Context getContext() {
|
||||
|
||||
@@ -31,6 +31,6 @@ public class NetworkError {
|
||||
|
||||
@NonNull
|
||||
public String toString() {
|
||||
return getCode() + " - " + getHttpStatus() + " - " + getMessage();
|
||||
return String.valueOf(getCode()) + " - " + getHttpStatus() + " - " + getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
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;
|
||||
@@ -34,7 +32,6 @@ public class News {
|
||||
return text;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
return "News{" +
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
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]);
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,6 @@ import android.view.animation.Animation;
|
||||
import android.view.animation.RotateAnimation;
|
||||
import android.view.animation.Transformation;
|
||||
import android.widget.ImageButton;
|
||||
import android.widget.RelativeLayout;
|
||||
|
||||
import androidx.annotation.LayoutRes;
|
||||
import androidx.annotation.Nullable;
|
||||
@@ -50,7 +49,7 @@ public class ExpandableCardView extends CardView {
|
||||
private View outerView;
|
||||
private ImageButton imageButton;
|
||||
|
||||
private static final int DEFAULT_ANIM_DURATION = 300;
|
||||
private static final int DEFAULT_ANIM_DURATION = 350;
|
||||
private long animDuration = DEFAULT_ANIM_DURATION;
|
||||
|
||||
private final static int COLLAPSING = 0;
|
||||
@@ -64,15 +63,13 @@ public class ExpandableCardView extends CardView {
|
||||
private int collapsedHeight = 0;
|
||||
private int expandedHeight = 0;
|
||||
|
||||
LayoutParams layoutParamsPreset = new LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
|
||||
|
||||
private OnExpandedListener listener;
|
||||
private final Logger log = new Logger(this);
|
||||
|
||||
private final OnClickListener defaultClickListener = v -> {
|
||||
if(isExpanded()) collapse();
|
||||
else expand();
|
||||
};
|
||||
private final Logger log = new Logger(this);
|
||||
|
||||
public ExpandableCardView(Context context) {
|
||||
super(context);
|
||||
@@ -103,9 +100,11 @@ public class ExpandableCardView extends CardView {
|
||||
(int) UtilsUi.convertDpToPixels(getContext(), 10),
|
||||
(int) UtilsUi.convertDpToPixels(getContext(), 10)
|
||||
);
|
||||
TypedValue outValue = new TypedValue();
|
||||
context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
|
||||
imageButton.setBackgroundResource(outValue.resourceId);
|
||||
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);
|
||||
}
|
||||
isExpanded = startExpanded;
|
||||
}
|
||||
|
||||
@@ -135,10 +134,6 @@ public class ExpandableCardView extends CardView {
|
||||
|
||||
@Override
|
||||
protected void onLayout(boolean changed, int l, int t, int r, int b) {
|
||||
if (outerView == null || innerView == null) {
|
||||
log.w("This should not happen (onLayout)! Inner views are null!", innerView, outerView);
|
||||
return;
|
||||
}
|
||||
removeAllViews();
|
||||
int x = getPaddingLeft();
|
||||
int y = getPaddingTop();
|
||||
@@ -158,12 +153,7 @@ public class ExpandableCardView extends CardView {
|
||||
@Override
|
||||
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
|
||||
if (MeasureSpec.getSize(widthMeasureSpec) == 0 && MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.UNSPECIFIED || MeasureSpec.getSize(heightMeasureSpec) == 0 && MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.UNSPECIFIED) {
|
||||
log.w("This should not happen (onMeasure)! Invalid dimension size");
|
||||
setMeasuredDimension(reconcileSize(10, widthMeasureSpec), reconcileSize(10, heightMeasureSpec));
|
||||
return;
|
||||
}
|
||||
if (outerView == null || innerView == null) {
|
||||
log.w("This should not happen (onMeasure)! Inner views are null!", innerView, outerView);
|
||||
log.w("This should not happen! Invalid dimension size");
|
||||
setMeasuredDimension(reconcileSize(10, widthMeasureSpec), reconcileSize(10, heightMeasureSpec));
|
||||
return;
|
||||
}
|
||||
@@ -177,14 +167,12 @@ public class ExpandableCardView extends CardView {
|
||||
|
||||
widthMeasure = atMostExactlySpec(Math.max(0, MeasureSpec.getSize(widthMeasureSpec)-imageButton.getMeasuredWidth()), widthMeasureSpec);
|
||||
heightMeasure = atMostSpec(MeasureSpec.getSize(heightMeasureSpec), heightMeasureSpec);
|
||||
outerView.setLayoutParams(layoutParamsPreset);
|
||||
outerView.measure(widthMeasure, heightMeasure);
|
||||
desiredWidth = imageButton.getMeasuredWidth() + outerView.getMeasuredWidth();
|
||||
desiredHeight = Math.max(imageButton.getMeasuredHeight(), outerView.getMeasuredHeight());
|
||||
|
||||
widthMeasure = atMostSpec(MeasureSpec.getSize(widthMeasureSpec), widthMeasureSpec);
|
||||
heightMeasure = atMostSpec(Math.max(0, MeasureSpec.getSize(heightMeasureSpec)-desiredHeight), heightMeasureSpec);
|
||||
innerView.setLayoutParams(layoutParamsPreset);
|
||||
innerView.measure(widthMeasure, heightMeasure);
|
||||
desiredWidth = Math.max(desiredWidth, innerView.getMeasuredWidth());
|
||||
desiredHeight += innerView.getMeasuredHeight();
|
||||
@@ -260,29 +248,8 @@ public class ExpandableCardView extends CardView {
|
||||
new RotateAnimation(180,0,Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
|
||||
0.5f);
|
||||
|
||||
arrowAnimation.setAnimationListener(new Animation.AnimationListener() {
|
||||
@Override
|
||||
public void onAnimationStart(Animation animation) {
|
||||
imageButton.setRotationX(0);
|
||||
imageButton.setRotationY(0);
|
||||
}
|
||||
arrowAnimation.setFillAfter(true);
|
||||
|
||||
@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);
|
||||
@@ -399,3 +366,4 @@ public class ExpandableCardView extends CardView {
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user