Compare commits
186 Commits
newkvv
...
kvv_rename
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2585fbc01b | ||
|
|
e7e8da5db3 | ||
|
|
44ca33ae0f | ||
|
|
a8817babf8 | ||
|
|
7a39a0b854 | ||
|
|
c87241da65 | ||
|
|
6a837d8719 | ||
|
|
8655dc9927 | ||
|
|
e31d6cd042 | ||
|
|
8f2052180d | ||
|
|
e366e55143 | ||
|
|
34db5bf901 | ||
|
|
ab77ad4974 | ||
|
|
d098093c8a | ||
|
|
b4e11e3d10 | ||
|
|
6048714563 | ||
|
|
30f1cc9a67 | ||
|
|
489212c26a | ||
|
|
28e99f1fa5 | ||
|
|
9062035956 | ||
|
|
9769365e19 | ||
|
|
2441286165 | ||
|
|
14d5ca6759 | ||
|
|
c7fe1dc3f7 | ||
|
|
72216ea7d6 | ||
|
|
24dcb0e9e0 | ||
|
|
e8c3ca0b0e | ||
|
|
261878b6e3 | ||
|
|
041c46284b | ||
|
|
0776447d3b | ||
|
|
a6b5469058 | ||
|
|
b8be51d6fb | ||
|
|
019bdf80ce | ||
|
|
1041144b4f | ||
|
|
5f28f64efc | ||
|
|
8690aa4a5c | ||
|
|
9e3fa30366 | ||
|
|
e54a2c8957 | ||
|
|
8cdb52417b | ||
|
|
40e4612f27 | ||
|
|
7b85147d74 | ||
|
|
94ea032389 | ||
|
|
94e05ef8ba | ||
|
|
2ec6a3c08d | ||
|
|
123da07d35 | ||
|
|
31850e100d | ||
|
|
c589889db4 | ||
|
|
8f026f95d8 | ||
|
|
c6d9a288a6 | ||
|
|
74e5b16af6 | ||
|
|
8d0f3a83cf | ||
|
|
1414ad8a0e | ||
|
|
1d08534f4e | ||
|
|
e305605583 | ||
|
|
1e6ef4d6fc | ||
|
|
de9f6a5540 | ||
|
|
25004f8784 | ||
|
|
d78948d349 | ||
|
|
1bbb09499d | ||
|
|
c086a6c6b2 | ||
|
|
c9daa8b01b | ||
|
|
91eb7acd72 | ||
|
|
631bd0dd51 | ||
|
|
c5fc592169 | ||
|
|
d67542d93a | ||
|
|
42f460a2e1 | ||
|
|
bde4b0cbd0 | ||
|
|
2801261400 | ||
|
|
46429d3afe | ||
|
|
d5d867f4b5 | ||
|
|
f0d090fb8d | ||
|
|
a8997a2e99 | ||
|
|
7ae8a13c9f | ||
|
|
a94ce6c755 | ||
|
|
5bf6573baa | ||
|
|
0f6a11cf5f | ||
|
|
79f76ccefa | ||
|
|
593fb78ef2 | ||
|
|
a6b34f7814 | ||
|
|
3380e79232 | ||
|
|
d108d430df | ||
|
|
c7dd46a1a2 | ||
|
|
d5d4b680e8 | ||
|
|
331c3059bb | ||
|
|
011e31ac78 | ||
|
|
7f6e794fc8 | ||
|
|
35bb4e1629 | ||
|
|
48b034b63f | ||
|
|
ce322bd3ca | ||
|
|
c544adbd4b | ||
|
|
9fe2cf32fd | ||
|
|
10dc391606 | ||
|
|
fac7cb238b | ||
|
|
d60ea357d8 | ||
|
|
7c36db2bee | ||
|
|
c85e510722 | ||
|
|
740cc192dd | ||
|
|
64624ca784 | ||
|
|
a25b387756 | ||
|
|
7651eb47e2 | ||
|
|
86d8078aca | ||
|
|
068344ff5c | ||
|
|
c15fc1339f | ||
|
|
72234d2439 | ||
|
|
79305fb5bb | ||
|
|
e9ef587821 | ||
|
|
801b90e489 | ||
|
|
0610140cf6 | ||
|
|
afcd6afd00 | ||
|
|
3224946f43 | ||
|
|
7fe38cd60f | ||
|
|
31cea12d16 | ||
|
|
b8fe45e75e | ||
|
|
729d3165f7 | ||
|
|
6f1705ccf4 | ||
|
|
6a56573c6b | ||
|
|
322cf6f8a5 | ||
|
|
6d30050eae | ||
|
|
45a5513b54 | ||
|
|
e98e9f5e2f | ||
|
|
7d803777f8 | ||
|
|
7cc0709133 | ||
|
|
21d247052d | ||
|
|
57853eccf1 | ||
|
|
ceccd77f18 | ||
|
|
ae53e94108 | ||
|
|
786c001bbd | ||
|
|
1ed6522ac4 | ||
|
|
f646dd485d | ||
|
|
73f9485394 | ||
|
|
22f7cf3e96 | ||
|
|
4db38ba4fb | ||
|
|
6306cc9c77 | ||
|
|
d4275aad90 | ||
|
|
f9fb7e8351 | ||
|
|
8160ef12b1 | ||
|
|
4d22613672 | ||
|
|
fd18e4b61a | ||
|
|
889007ab42 | ||
|
|
cde5fc3582 | ||
|
|
c549bb39a4 | ||
|
|
1e0b2a8952 | ||
|
|
c807dda73c | ||
|
|
54196f3794 | ||
|
|
797e848900 | ||
|
|
2dbfd0141a | ||
|
|
9b39563474 | ||
|
|
8791d65d96 | ||
|
|
6bd99c59a8 | ||
|
|
6b117997c3 | ||
|
|
4c012ed2ba | ||
|
|
5209491287 | ||
|
|
4812336cc7 | ||
|
|
4fe6dee4c8 | ||
|
|
2aad0f19a3 | ||
|
|
a79f59c66c | ||
|
|
2d160d3b38 | ||
|
|
6acea97458 | ||
|
|
c6f032f92e | ||
|
|
544162bb47 | ||
|
|
d5e08ac3c3 | ||
|
|
671c9bd86a | ||
|
|
35141bc1ec | ||
|
|
d62256f1db | ||
|
|
0adeca7367 | ||
|
|
0b32f8e9f8 | ||
|
|
4d9b2200d3 | ||
|
|
50d07193a0 | ||
|
|
8e3360549f | ||
|
|
7679135af1 | ||
|
|
6523d82d6b | ||
|
|
7a7e56bdf5 | ||
|
|
14b38f22a3 | ||
|
|
1d90b3e9da | ||
|
|
b6deff7b99 | ||
|
|
dd7e9a910c | ||
|
|
3aa07e0a6d | ||
|
|
9a1892db0a | ||
|
|
5ba6c899be | ||
|
|
547a62d07b | ||
|
|
d9e2911554 | ||
|
|
2e96d205d6 | ||
|
|
17c093c040 | ||
|
|
a1ce5c644a | ||
|
|
2d1d8e1e8b | ||
|
|
959733a3c9 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -7,3 +7,4 @@
|
||||
/build
|
||||
/captures
|
||||
.externalNativeBuild
|
||||
app/release/*
|
||||
|
||||
@@ -7,8 +7,8 @@ android {
|
||||
applicationId "de.sebse.fuplanner"
|
||||
minSdkVersion 15
|
||||
targetSdkVersion 28
|
||||
versionCode 10
|
||||
versionName "1.2.2"
|
||||
versionCode 39
|
||||
versionName "1.5.16_2"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
buildTypes {
|
||||
@@ -27,28 +27,15 @@ android {
|
||||
|
||||
|
||||
dependencies {
|
||||
implementation fileTree(include: ['*.jar'], dir: 'libs')
|
||||
implementation 'androidx.recyclerview:recyclerview:1.0.0'
|
||||
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 'androidx.constraintlayout:constraintlayout:2.0.0-alpha2'
|
||||
implementation 'androidx.constraintlayout:constraintlayout:2.0.0-alpha3'
|
||||
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.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')
|
||||
implementation 'com.google.android.material:material:1.0.0'
|
||||
implementation 'com.google.android.gms:play-services-base:16.1.0'
|
||||
implementation 'com.ms-square:expandableTextView:0.1.4'
|
||||
implementation 'org.jetbrains:annotations-java5:15.0'
|
||||
//implementation 'com.github.quivr:android-week-view:2.0.2' //com.github.alamkanak:android-week-view:1.2.6
|
||||
}
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -2,28 +2,46 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="de.sebse.fuplanner">
|
||||
|
||||
<uses-permission
|
||||
android:name="android.permission.AUTHENTICATE_ACCOUNTS"
|
||||
android:maxSdkVersion="22" />
|
||||
<uses-permission
|
||||
android:name="android.permission.GET_ACCOUNTS"
|
||||
android:maxSdkVersion="22" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
|
||||
<uses-permission
|
||||
android:name="android.permission.MANAGE_ACCOUNTS"
|
||||
android:maxSdkVersion="22" />
|
||||
<uses-permission
|
||||
android:name="android.permission.USE_CREDENTIALS"
|
||||
android:maxSdkVersion="22" />
|
||||
<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.WRITE_SYNC_SETTINGS" />
|
||||
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
|
||||
|
||||
<application
|
||||
android:allowBackup="true"
|
||||
android:fullBackupContent="@xml/backup_descriptor"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/FUTheme"
|
||||
android:fullBackupContent="@xml/backup_descriptor">
|
||||
android:theme="@style/FUTheme">
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:label="@string/app_name">
|
||||
android:label="@string/app_name"
|
||||
android:clearTaskOnLaunch="true"
|
||||
android:launchMode="singleTop">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.my.provider"
|
||||
@@ -31,8 +49,53 @@
|
||||
android:grantUriPermissions="true">
|
||||
<meta-data
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/provider_paths"/>
|
||||
android:resource="@xml/provider_paths" />
|
||||
</provider>
|
||||
<provider
|
||||
android:authorities="de.sebse.fuplanner.contentprovider.kvv.modules"
|
||||
android:name="de.sebse.fuplanner.services.kvv.sync.KVVContentProvider"
|
||||
android:exported="false"
|
||||
android:syncable="true">
|
||||
|
||||
</provider>
|
||||
|
||||
<activity
|
||||
android:name=".services.fulogin.FUAuthenticatorActivity"
|
||||
android:label="@string/title_activity_fuauthenticator" />
|
||||
<service android:name=".services.fulogin.FUAuthenticatorService">
|
||||
<intent-filter>
|
||||
<action android:name="android.accounts.AccountAuthenticator" />
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.accounts.AccountAuthenticator"
|
||||
android:resource="@xml/authenticator" />
|
||||
</service>
|
||||
<service
|
||||
android:name=".services.kvv.sync.KVVSyncService"
|
||||
android:label="@string/kvv_sync"
|
||||
android:exported="false">
|
||||
<intent-filter>
|
||||
<action android:name="android.content.SyncAdapter" />
|
||||
</intent-filter>
|
||||
<meta-data
|
||||
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>
|
||||
|
||||
</manifest>
|
||||
@@ -1,7 +1,15 @@
|
||||
package de.sebse.fuplanner;
|
||||
|
||||
import android.accounts.Account;
|
||||
import android.accounts.AccountManager;
|
||||
import android.content.ComponentName;
|
||||
import android.content.ContentResolver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.ServiceConnection;
|
||||
import android.os.Bundle;
|
||||
import android.os.IBinder;
|
||||
import android.text.TextUtils;
|
||||
import android.view.Menu;
|
||||
import android.view.MenuItem;
|
||||
import android.view.View;
|
||||
@@ -11,11 +19,17 @@ import android.widget.Toast;
|
||||
import com.android.volley.NetworkResponse;
|
||||
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.arch.core.util.Function;
|
||||
import androidx.appcompat.app.ActionBarDrawerToggle;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
import androidx.appcompat.widget.Toolbar;
|
||||
@@ -25,67 +39,120 @@ import androidx.fragment.app.Fragment;
|
||||
import androidx.fragment.app.FragmentManager;
|
||||
import androidx.fragment.app.FragmentTransaction;
|
||||
import de.sebse.fuplanner.fragments.CanteensFragment;
|
||||
import de.sebse.fuplanner.fragments.LoginFragment;
|
||||
import de.sebse.fuplanner.fragments.ModulesFragment;
|
||||
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.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.GoogleAuth.Credentials;
|
||||
import de.sebse.fuplanner.services.GoogleAuth.GoogleAuth;
|
||||
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.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.Modules;
|
||||
import de.sebse.fuplanner.services.news.NewsManager;
|
||||
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;
|
||||
import de.sebse.fuplanner.tools.Regex;
|
||||
import de.sebse.fuplanner.tools.RequestPermissionsResultListener;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
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;
|
||||
|
||||
public class MainActivity extends AppCompatActivity
|
||||
implements MainActivityListener, KVVListener,
|
||||
implements MainActivityListener, KVVListener, CanteenListener,
|
||||
NavigationView.OnNavigationItemSelectedListener,
|
||||
ModulesFragment.OnModulesFragmentInteractionListener,
|
||||
CanteensFragment.OnCanteensFragmentInteractionListener {
|
||||
|
||||
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_LOGIN = 3;
|
||||
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;
|
||||
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_PREFERENCES = 7;
|
||||
public 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 GoogleAuth mGoogleAuth;
|
||||
private KVV mKVV;
|
||||
private NewsManager mNewsManager;
|
||||
private CanteenBrowser mCanteenBrowser;
|
||||
private final Logger log = new Logger(this);
|
||||
private NavigationView mNavigationView;
|
||||
|
||||
private int fragmentPage = FRAGMENT_NONE;
|
||||
private String fragmentData = "";
|
||||
private CanteenBrowser mCanteenBrowser;
|
||||
private HashMap<String, RequestPermissionsResultListener> permissionListeners = new HashMap<>();
|
||||
private boolean mOfflineBanner;
|
||||
private NewAsyncQueue mQueue = new NewAsyncQueue();
|
||||
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 = "";
|
||||
private final HashMap<String, RequestPermissionsResultListener> permissionListeners = new HashMap<>();
|
||||
private final NewAsyncQueue mQueue = new NewAsyncQueue();
|
||||
private long mDoubleBackToExitPressedOnce = 0;
|
||||
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 = "";
|
||||
if (savedInstanceState != null) {
|
||||
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) {
|
||||
desiredPage = savedInstanceState.getInt(ARG_FRAGMENT_PAGE, desiredPage);
|
||||
desiredData = savedInstanceState.getString(ARG_FRAGMENT_STATUS, desiredData);
|
||||
}
|
||||
@@ -94,38 +161,165 @@ 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();
|
||||
}
|
||||
|
||||
mNavigationView = findViewById(R.id.nav_view);
|
||||
mNavigationView.setNavigationItemSelectedListener(this);
|
||||
mFragmentManager = getSupportFragmentManager();
|
||||
|
||||
if (!getKVV().account().restoreOnlineLogin()) {
|
||||
desiredPage = FRAGMENT_LOGIN;
|
||||
//if (mAccountManager.getAccountsByType(AccountGeneral.ACCOUNT_TYPE).length == 0) {
|
||||
if (!mAccountManager.hasAccounts(AccountGeneral.ACCOUNT_TYPE)) {
|
||||
desiredPage = getDefaultFragmentAfterLogout();
|
||||
desiredData = "";
|
||||
}
|
||||
mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD, null, null);
|
||||
updateNavigation();
|
||||
changeFragment(desiredPage, desiredData);
|
||||
} else {
|
||||
updateNavigation();
|
||||
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());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (!mAlreadyCreated) {
|
||||
Intent serviceIntent = new Intent(this, KVV.class);
|
||||
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
|
||||
}
|
||||
mAlreadyCreated = true;
|
||||
|
||||
if (!Preferences.getBoolean(this, R.string.pref_set_auto_sync_on_startup)) {
|
||||
registerSync(true);
|
||||
Preferences.setBoolean(this, R.string.pref_set_auto_sync_on_startup, true);
|
||||
} else {
|
||||
registerSync(false);
|
||||
}
|
||||
CustomNotificationManager.createNotificationChannel(this);
|
||||
/*getKVV(kvv -> {
|
||||
kvv.modules().list().recv(list -> {
|
||||
Modules.Module module = list.getByIndex(0);
|
||||
CustomNotificationManager.sendNotification(this, "Test", module.title, FRAGMENT_MODULES_DETAILS, module.getID()+"."+ ModulePart.getPageByPart(ModulePart.EVENT));
|
||||
}, log::e);
|
||||
});*/
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStart() {
|
||||
super.onStart();
|
||||
if (!mAlreadyCreated) {
|
||||
Intent serviceIntent = new Intent(this, KVV.class);
|
||||
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
|
||||
}
|
||||
mAlreadyCreated = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStop() {
|
||||
super.onStop();
|
||||
if (mKVV != null)
|
||||
mKVV.removeListener("mainactivity");
|
||||
if (mBound)
|
||||
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());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
if (isPaused) {
|
||||
getKVV(kvv -> {
|
||||
kvv.account().restoreOnlineLogin(restoreResult -> {
|
||||
updateNavigation();
|
||||
if (restoreResult == Login.RESTORE_STATUS_SUCCESS && !isLoggedInBeforePause) {
|
||||
changeFragment(getDefaultFragmentAfterLogin());
|
||||
registerSync(true);
|
||||
} else if (restoreResult == Login.RESTORE_STATUS_INVALID_PASSWORD && isLoggedInBeforePause) {
|
||||
kvv.account().logout(false);
|
||||
changeFragment(getDefaultFragmentAfterLogout());
|
||||
}
|
||||
});
|
||||
kvv.modules().list().reloadIfOutdated();
|
||||
});
|
||||
}
|
||||
isPaused = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBackPressed() {
|
||||
if (mDoubleBackToExitPressedOnce + DOUBLE_CLICK_TO_EXIT_MILLIS > System.currentTimeMillis()) {
|
||||
super.onBackPressed();
|
||||
return;
|
||||
}
|
||||
|
||||
DrawerLayout drawer = findViewById(R.id.drawer_layout);
|
||||
if (drawer.isDrawerOpen(GravityCompat.START)) {
|
||||
if (drawer.isDrawerOpen(GravityCompat.START) && !isDrawerFixed) {
|
||||
drawer.closeDrawer(GravityCompat.START);
|
||||
} else {
|
||||
super.onBackPressed();
|
||||
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 (kvv.account().isLoggedIn() && mFragmentPage != getDefaultFragmentAfterLogin()) {
|
||||
changeFragment(getDefaultFragmentAfterLogin());
|
||||
} else {
|
||||
mDoubleBackToExitPressedOnce = System.currentTimeMillis();
|
||||
showToast(R.string.back_to_exit);
|
||||
//getTokenForAccountCreateIfNeeded(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCreateOptionsMenu(Menu menu) {
|
||||
// Inflate the menu; this adds items to the action bar if it is present.
|
||||
if (fragmentPage == FRAGMENT_SCHEDULE) {
|
||||
if (mFragmentPage == FRAGMENT_SCHEDULE) {
|
||||
getMenuInflater().inflate(R.menu.options_schedule, menu);
|
||||
return true;
|
||||
}
|
||||
@@ -171,6 +365,9 @@ public class MainActivity extends AppCompatActivity
|
||||
case R.id.nav_canteens:
|
||||
changeFragment(FRAGMENT_CANTEENS);
|
||||
break;
|
||||
case R.id.nav_news:
|
||||
changeFragment(FRAGMENT_NEWS);
|
||||
break;
|
||||
case R.id.nav_settings:
|
||||
changeFragment(FRAGMENT_PREFERENCES);
|
||||
break;
|
||||
@@ -182,18 +379,17 @@ public class MainActivity extends AppCompatActivity
|
||||
startActivity(sendIntent);
|
||||
break;
|
||||
case R.id.nav_logout:
|
||||
getKVV().account().logout(true);
|
||||
getKVV().modules().list().delete();
|
||||
this.getGoogleAuth().getLoginState(credentials -> {
|
||||
if (credentials != null) {
|
||||
this.getGoogleAuth().deleteLoginState(credentials.getUsername(), credentials.getPassword());
|
||||
}
|
||||
getKVV(kvv -> {
|
||||
kvv.account().logout(true);
|
||||
kvv.modules().list().delete();
|
||||
});
|
||||
break;
|
||||
|
||||
}
|
||||
if (!isDrawerFixed) {
|
||||
DrawerLayout drawer = findViewById(R.id.drawer_layout);
|
||||
drawer.closeDrawer(GravityCompat.START);
|
||||
}
|
||||
|
||||
int size = mNavigationView.getMenu().size();
|
||||
for (int k = 0; k < size; k++) {
|
||||
@@ -204,21 +400,17 @@ public class MainActivity extends AppCompatActivity
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onActivityResult(int requestCode, int resultCode, Intent data) {
|
||||
super.onActivityResult(requestCode, resultCode, data);
|
||||
this.getGoogleAuth().onActivityResult(requestCode, resultCode, data);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onSaveInstanceState(Bundle savedInstanceState) {
|
||||
if (fragmentPage != FRAGMENT_STARTUP && fragmentPage != FRAGMENT_NONE && fragmentPage != FRAGMENT_LOGIN) {
|
||||
Fragment fragment = mFragmentManager.findFragmentByTag(String.valueOf(fragmentPage));
|
||||
savedInstanceState.putInt(ARG_FRAGMENT_PAGE, fragmentPage);
|
||||
if (mFragmentPage != FRAGMENT_STARTUP && mFragmentPage != FRAGMENT_NONE) {
|
||||
Fragment fragment = mFragmentManager.findFragmentByTag(String.valueOf(mFragmentPage));
|
||||
savedInstanceState.putInt(ARG_FRAGMENT_PAGE, mFragmentPage);
|
||||
if (fragment instanceof ModDetailFragment) {
|
||||
savedInstanceState.putString(ARG_FRAGMENT_STATUS, ((ModDetailFragment) fragment).getData());
|
||||
} else if (fragment instanceof DaySwitcherFragment) {
|
||||
savedInstanceState.putString(ARG_FRAGMENT_STATUS, ((DaySwitcherFragment) fragment).getData());
|
||||
} else {
|
||||
savedInstanceState.putString(ARG_FRAGMENT_STATUS, fragmentData);
|
||||
savedInstanceState.putString(ARG_FRAGMENT_STATUS, mFragmentData);
|
||||
}
|
||||
}
|
||||
super.onSaveInstanceState(savedInstanceState);
|
||||
@@ -235,26 +427,19 @@ public class MainActivity extends AppCompatActivity
|
||||
/* --------------------------------------------*/
|
||||
/* --------------------------------------------*/
|
||||
|
||||
public GoogleAuth getGoogleAuth() {
|
||||
if (this.mGoogleAuth == null) {
|
||||
this.mGoogleAuth = new GoogleAuth(this);
|
||||
public NewsManager getNewsManager() {
|
||||
if (this.mNewsManager == null) {
|
||||
this.mNewsManager = new NewsManager(this);
|
||||
}
|
||||
return this.mGoogleAuth;
|
||||
return this.mNewsManager;
|
||||
}
|
||||
|
||||
/*@Deprecated
|
||||
public de.sebse.fuplanner.services.KVV.KVV getKVV() {
|
||||
public void getKVV(KVVCallback callback) {
|
||||
if (this.mKVV == null) {
|
||||
this.mKVV = new de.sebse.fuplanner.services.KVV.KVV(this);
|
||||
mCallbacks.add(callback);
|
||||
} else {
|
||||
callback.get(this.mKVV);
|
||||
}
|
||||
return this.mKVV;
|
||||
}*/
|
||||
|
||||
public KVV getKVV() {
|
||||
if (this.mKVV == null) {
|
||||
this.mKVV = new KVV(this, this);
|
||||
}
|
||||
return this.mKVV;
|
||||
}
|
||||
|
||||
public CanteenBrowser getCanteenBrowser() {
|
||||
@@ -268,15 +453,18 @@ public class MainActivity extends AppCompatActivity
|
||||
return FRAGMENT_MODULES;
|
||||
}
|
||||
|
||||
private void toLogoutState() {
|
||||
setOfflineBanner(false);
|
||||
setRefreshFailedBanner(false);
|
||||
updateNavigation();
|
||||
changeFragment(FRAGMENT_LOGIN);
|
||||
private int getDefaultFragmentAfterLogout() {
|
||||
return FRAGMENT_CANTEENS;
|
||||
}
|
||||
|
||||
private void toLoginState(String fullName, String email, int newFragment, boolean onlineMode) {
|
||||
setOfflineBanner(!onlineMode);
|
||||
private void toLogoutState() {
|
||||
setRefreshFailedBanner(false);
|
||||
updateNavigation();
|
||||
changeFragment(getDefaultFragmentAfterLogout());
|
||||
//mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD, null, null);
|
||||
}
|
||||
|
||||
private void toLoginState(String fullName, String email, int newFragment) {
|
||||
updateNavigation();
|
||||
|
||||
View header = mNavigationView.getHeaderView(0);
|
||||
@@ -286,6 +474,19 @@ public class MainActivity extends AppCompatActivity
|
||||
changeFragment(newFragment);
|
||||
}
|
||||
|
||||
private void registerSync(boolean onLogin) {
|
||||
Account accountByType = mAccountManager.getAccountByType(AccountGeneral.ACCOUNT_TYPE);
|
||||
if (accountByType != null) {
|
||||
if (onLogin)
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
private void changeFragment(int newFragment) {
|
||||
changeFragment(newFragment, "");
|
||||
}
|
||||
@@ -307,18 +508,20 @@ 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(Integer.parseInt(newData));
|
||||
fragment = DaySwitcherFragment.newInstance(newData);
|
||||
break;
|
||||
case FRAGMENT_CANTEENS:
|
||||
fragment = CanteensFragment.newInstance();
|
||||
break;
|
||||
case FRAGMENT_NEWS:
|
||||
Preferences.setLong(this, R.string.pref_last_visited_news, System.currentTimeMillis());
|
||||
updateNavigation();
|
||||
fragment = NewsFragment.newInstance();
|
||||
break;
|
||||
case FRAGMENT_PREFERENCES:
|
||||
fragment = PrefsFragment.newInstance();
|
||||
break;
|
||||
@@ -337,69 +540,83 @@ public class MainActivity extends AppCompatActivity
|
||||
findViewById(R.id.app_bar_include).setVisibility(View.VISIBLE);
|
||||
}
|
||||
|
||||
this.fragmentPage = newFragment;
|
||||
this.fragmentData = newData;
|
||||
this.mFragmentPage = newFragment;
|
||||
this.mFragmentData = newData;
|
||||
|
||||
invalidateOptionsMenu();
|
||||
}
|
||||
|
||||
private void setOfflineBanner(boolean visible) {
|
||||
View offline_header = findViewById(R.id.offline_msg);
|
||||
offline_header.setVisibility(visible ? View.VISIBLE : View.GONE);
|
||||
mOfflineBanner = visible;
|
||||
}
|
||||
|
||||
private void setRefreshFailedBanner(boolean refreshFailed) {
|
||||
View viewNoConnection = findViewById(R.id.no_connection_msg);
|
||||
if (!mOfflineBanner && refreshFailed)
|
||||
if (refreshFailed)
|
||||
viewNoConnection.setVisibility(View.VISIBLE);
|
||||
else
|
||||
viewNoConnection.setVisibility(View.GONE);
|
||||
}
|
||||
|
||||
private void setNavigationSelection() {
|
||||
MenuItem item;
|
||||
switch (fragmentPage) {
|
||||
MenuItem item = null;
|
||||
int dotPos = mFragmentData.indexOf(".");
|
||||
String moduleId = mFragmentData;
|
||||
if (dotPos != -1)
|
||||
moduleId = moduleId.substring(0, dotPos);
|
||||
switch (mFragmentPage) {
|
||||
case FRAGMENT_MODULES_DETAILS:
|
||||
getKVV().modules().list().find(fragmentData, success -> {
|
||||
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++) {
|
||||
mNavigationView.getMenu().getItem(k).setChecked(mNavigationView.getMenu().getItem(k).getTitle().equals(title));
|
||||
MenuItem menuItem = mNavigationView.getMenu().getItem(k);
|
||||
if (menuItem.getTitle().equals(title)) {
|
||||
menuItem.setChecked(true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}, log::e);
|
||||
break;
|
||||
});
|
||||
return;
|
||||
case FRAGMENT_MODULES:
|
||||
item = mNavigationView.getMenu().findItem(R.id.nav_modules);
|
||||
if (item != null)
|
||||
item.setChecked(true);
|
||||
break;
|
||||
case FRAGMENT_SCHEDULE:
|
||||
item = mNavigationView.getMenu().findItem(R.id.nav_schedule);
|
||||
if (item != null)
|
||||
item.setChecked(true);
|
||||
break;
|
||||
case FRAGMENT_CANTEENS_DETAILS:
|
||||
getCanteenBrowser().getCanteens(success -> {
|
||||
int size = mNavigationView.getMenu().size();
|
||||
Canteen canteen = success.getCanteen(Integer.parseInt(fragmentData));
|
||||
try {
|
||||
Canteen canteen = success.getCanteen(Integer.parseInt(mFragmentData));
|
||||
//noinspection ConstantConditions
|
||||
String title = canteen == null ? null : canteen.getName();
|
||||
for (int k = 0; k < size; k++) {
|
||||
mNavigationView.getMenu().getItem(k).setChecked(mNavigationView.getMenu().getItem(k).getTitle().equals(title));
|
||||
MenuItem menuItem = mNavigationView.getMenu().getItem(k);
|
||||
if (menuItem.getTitle().equals(title)) {
|
||||
menuItem.setChecked(true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}, log::e);
|
||||
break;
|
||||
return;
|
||||
case FRAGMENT_CANTEENS:
|
||||
mNavigationView.getMenu().findItem(R.id.nav_canteens).setChecked(true);
|
||||
item = mNavigationView.getMenu().findItem(R.id.nav_canteens);
|
||||
break;
|
||||
case FRAGMENT_NEWS:
|
||||
item = mNavigationView.getMenu().findItem(R.id.nav_news);
|
||||
break;
|
||||
case FRAGMENT_PREFERENCES:
|
||||
mNavigationView.getMenu().findItem(R.id.nav_settings).setChecked(true);
|
||||
item = mNavigationView.getMenu().findItem(R.id.nav_settings);
|
||||
break;
|
||||
default: // FRAGMENT_STARTUP / FRAGMENT_LOGIN
|
||||
break;
|
||||
}
|
||||
if (item != null)
|
||||
item.setChecked(true);
|
||||
}
|
||||
|
||||
private void setNavigationHeader(boolean isLoggedIn) {
|
||||
@@ -414,18 +631,19 @@ public class MainActivity extends AppCompatActivity
|
||||
if (!viewBtn.hasOnClickListeners())
|
||||
viewBtn.setOnClickListener(v -> {
|
||||
DrawerLayout drawer = findViewById(R.id.drawer_layout);
|
||||
if (drawer.isDrawerOpen(GravityCompat.START)) {
|
||||
if (drawer.isDrawerOpen(GravityCompat.START) && !isDrawerFixed) {
|
||||
drawer.closeDrawer(GravityCompat.START);
|
||||
}
|
||||
changeFragment(FRAGMENT_LOGIN);
|
||||
mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD, null, null);
|
||||
});
|
||||
}
|
||||
|
||||
private void afterAnyMenuInflate(boolean isLoggedIn, Runnable done) {
|
||||
int MAX_COUNT = isLoggedIn ? 2 : 1;
|
||||
int MAX_COUNT = isLoggedIn ? 3 : 2;
|
||||
final int[] count = {0};
|
||||
if (isLoggedIn) {
|
||||
getKVV().modules().list().recv(success -> {
|
||||
getKVV(kvv -> {
|
||||
kvv.modules().list().recv(success -> {
|
||||
int i = 0;
|
||||
for (Iterator<Modules.Module> it = success.latestSemesterIterator(); it.hasNext(); ) {
|
||||
Modules.Module module = it.next();
|
||||
@@ -437,9 +655,10 @@ public class MainActivity extends AppCompatActivity
|
||||
i++;
|
||||
}
|
||||
if (++count[0] == MAX_COUNT) done.run();
|
||||
}, msg -> {
|
||||
}, error -> {
|
||||
if (++count[0] == MAX_COUNT) done.run();
|
||||
log.e(msg);
|
||||
log.e(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
getCanteenBrowser().getCanteens(success -> {
|
||||
@@ -453,15 +672,35 @@ public class MainActivity extends AppCompatActivity
|
||||
i++;
|
||||
}
|
||||
if (++count[0] == MAX_COUNT) done.run();
|
||||
}, msg -> {
|
||||
}, error -> {
|
||||
if (++count[0] == MAX_COUNT) done.run();
|
||||
log.e(msg);
|
||||
log.e(error);
|
||||
});
|
||||
getNewsManager().recv(success -> {
|
||||
long lastVisited = Preferences.getLong(this, R.string.pref_last_visited_news);
|
||||
int i = 0;
|
||||
for (News news: success) {
|
||||
if (news.getDate() > lastVisited) i++;
|
||||
}
|
||||
if (i > 0) {
|
||||
MenuItem menuItem = mNavigationView.getMenu().findItem(R.id.nav_news);
|
||||
menuItem.setIcon(R.drawable.ic_sms_failed);
|
||||
View view = View.inflate(this, R.layout.action_icon_number, null);
|
||||
TextView v = view.findViewById(R.id.number);
|
||||
v.setText(String.format(Locale.getDefault(), "%d", i));
|
||||
menuItem.setActionView(view);
|
||||
}
|
||||
if (++count[0] == MAX_COUNT) done.run();
|
||||
}, error -> {
|
||||
if (++count[0] == MAX_COUNT) done.run();
|
||||
log.e(error);
|
||||
});
|
||||
}
|
||||
|
||||
private void updateNavigation() {
|
||||
mQueue.add(() -> {
|
||||
boolean isLoggedIn = getKVV().account().isLoggedIn();
|
||||
getKVV(kvv -> {
|
||||
boolean isLoggedIn = kvv.account().isLoggedIn();
|
||||
setNavigationHeader(isLoggedIn);
|
||||
mNavigationView.getMenu().clear();
|
||||
if (isLoggedIn)
|
||||
@@ -473,6 +712,7 @@ public class MainActivity extends AppCompatActivity
|
||||
mQueue.next();
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -483,14 +723,24 @@ public class MainActivity extends AppCompatActivity
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void onModulesFragmentInteraction(final String itemID) {
|
||||
changeFragment(FRAGMENT_MODULES_DETAILS, itemID);
|
||||
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));
|
||||
setNavigationSelection();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -504,7 +754,7 @@ public class MainActivity extends AppCompatActivity
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onRefreshCompleted(boolean isFailed) {
|
||||
public void onCanteenRefreshCompleted(boolean isFailed) {
|
||||
setRefreshFailedBanner(isFailed);
|
||||
}
|
||||
|
||||
@@ -537,20 +787,23 @@ public class MainActivity extends AppCompatActivity
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void getCredentials(NetworkCallback<Credentials> callback, NetworkErrorCallback error) {
|
||||
getGoogleAuth().getLoginState(credentials -> {
|
||||
if (credentials == null || credentials.getUsername() == null || credentials.getPassword() == null) {
|
||||
error.onError(new NetworkError(200100, 403, "No Google Login available!"));
|
||||
} else {
|
||||
callback.onResponse(credentials);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLogin(LoginToken token, boolean enteringOnlineMode) {
|
||||
toLoginState(token.getFullName(), token.getEmail(), getDefaultFragmentAfterLogin(), enteringOnlineMode);
|
||||
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());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -567,4 +820,20 @@ public class MainActivity extends AppCompatActivity
|
||||
public void onKVVNetworkResponse(NetworkResponse error) {
|
||||
setRefreshFailedBanner(error != null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CustomAccountManager getAccountManager() {
|
||||
return mAccountManager;
|
||||
}
|
||||
|
||||
public interface KVVCallback {
|
||||
void get(KVV kvv);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onModuleListPartiallyUpdated(Modules modules) {
|
||||
if (mMolduleListUpdateFunction != null) {
|
||||
mMolduleListUpdateFunction.apply(modules);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,12 +8,12 @@ import androidx.annotation.NonNull;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
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.services.canteen.types.Canteen;
|
||||
import de.sebse.fuplanner.services.canteen.types.Canteens;
|
||||
import de.sebse.fuplanner.tools.ui.ItemViewHolder;
|
||||
|
||||
/**
|
||||
* {@link RecyclerView.Adapter} that can display a {@link Modules.Module} and makes a call to the
|
||||
* {@link RecyclerView.Adapter} that can display a {@link Canteen} and makes a call to the
|
||||
* specified {@link OnCanteensFragmentInteractionListener}.
|
||||
*/
|
||||
class CanteensAdapter extends RecyclerView.Adapter<ItemViewHolder> {
|
||||
|
||||
@@ -13,7 +13,7 @@ import androidx.recyclerview.widget.RecyclerView;
|
||||
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
|
||||
import de.sebse.fuplanner.MainActivity;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.services.Canteen.CanteenBrowser;
|
||||
import de.sebse.fuplanner.services.canteen.CanteenBrowser;
|
||||
import de.sebse.fuplanner.tools.MainActivityListener;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
|
||||
@@ -48,7 +48,7 @@ public class CanteensFragment extends Fragment {
|
||||
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
|
||||
Bundle savedInstanceState) {
|
||||
|
||||
View view = inflater.inflate(R.layout.fragment_modules_list, container, false);
|
||||
View view = inflater.inflate(R.layout.fragment_recycler_view, container, false);
|
||||
// Set the adapter
|
||||
Context context = view.getContext();
|
||||
RecyclerView recyclerView = view.findViewById(R.id.list);
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
package de.sebse.fuplanner.fragments;
|
||||
|
||||
import android.app.ProgressDialog;
|
||||
import android.content.Context;
|
||||
import android.os.Bundle;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.Button;
|
||||
import android.widget.EditText;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.fragment.app.Fragment;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.tools.MainActivityListener;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
|
||||
/**
|
||||
* A simple {@link Fragment} subclass.
|
||||
* Use the {@link LoginFragment#newInstance} factory method to
|
||||
* create an instance of this fragment.
|
||||
*/
|
||||
public class LoginFragment extends Fragment {
|
||||
private final Logger log = new Logger(this);
|
||||
@Nullable private MainActivityListener mActivityListener;
|
||||
|
||||
public LoginFragment() {
|
||||
// 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 LoginFragment.
|
||||
*/
|
||||
public static LoginFragment newInstance() {
|
||||
LoginFragment fragment = new LoginFragment();
|
||||
Bundle args = new Bundle();
|
||||
fragment.setArguments(args);
|
||||
return fragment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
|
||||
Bundle savedInstanceState) {
|
||||
// Inflate the layout for this fragment
|
||||
View v = inflater.inflate(R.layout.fragment_login, container, false);
|
||||
if (mActivityListener != null && mActivityListener.getKVV().account().isOfflineStoredAvailable()) {
|
||||
Button offline_btn = v.findViewById(R.id.btn_offline);
|
||||
offline_btn.setVisibility(View.VISIBLE);
|
||||
offline_btn.setText(v.getResources().getString(R.string.enter_offline_mode, mActivityListener.getKVV().modules().list().getUsername()));
|
||||
offline_btn.setOnClickListener(v1 -> mActivityListener.getKVV().account().doOfflineLogin());
|
||||
}
|
||||
|
||||
View btn_login = v.findViewById(R.id.btn_login);
|
||||
btn_login.setOnClickListener(view -> {
|
||||
final ProgressDialog progressDialog = new ProgressDialog(LoginFragment.this.getContext(),
|
||||
R.style.FUTheme_Dialog);
|
||||
progressDialog.setIndeterminate(true);
|
||||
progressDialog.setMessage("Authenticating...");
|
||||
progressDialog.show();
|
||||
|
||||
EditText input_usr = ((View) view.getParent()).findViewById(R.id.input_username);
|
||||
EditText input_pwd = ((View) view.getParent()).findViewById(R.id.input_password);
|
||||
|
||||
String username = input_usr.getText().toString();
|
||||
String password = input_pwd.getText().toString();
|
||||
|
||||
mActivityListener.getKVV().account().doOnlineLogin(username, password, success -> {
|
||||
progressDialog.dismiss();
|
||||
mActivityListener.getGoogleAuth().setLoginState(username, password);
|
||||
input_usr.setError(null);
|
||||
input_pwd.setError(null);
|
||||
}, error -> {
|
||||
progressDialog.dismiss();
|
||||
// Invalid password
|
||||
if (mActivityListener != null) {
|
||||
if (error.getCode() == 100131) {
|
||||
mActivityListener.showToast(R.string.invalid_credentials);
|
||||
input_usr.setError(input_usr.getResources().getString(R.string.invalid_credentials));
|
||||
input_pwd.setError(input_pwd.getResources().getString(R.string.invalid_credentials));
|
||||
} else {
|
||||
mActivityListener.showToast(v.getResources().getString(R.string.error_occurred_code, error.getCode()));
|
||||
}
|
||||
}
|
||||
log.e("Error on KVV login!", error);
|
||||
});
|
||||
});
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void onAttach(Context context) {
|
||||
super.onAttach(context);
|
||||
if (context instanceof MainActivityListener) {
|
||||
mActivityListener = (MainActivityListener) context;
|
||||
mActivityListener.onTitleTextChange(R.string.log_in);
|
||||
} else
|
||||
throw new RuntimeException(context.toString() + " must implement MainActivityListener");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDetach() {
|
||||
super.onDetach();
|
||||
mActivityListener = null;
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,9 @@ import androidx.annotation.NonNull;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.fragments.ModulesFragment.OnModulesFragmentInteractionListener;
|
||||
import de.sebse.fuplanner.services.KVV.types.Lecturer;
|
||||
import de.sebse.fuplanner.services.KVV.types.Modules;
|
||||
import de.sebse.fuplanner.services.KVV.types.Semester;
|
||||
import de.sebse.fuplanner.services.kvv.types.Lecturer;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
import de.sebse.fuplanner.services.kvv.types.Semester;
|
||||
import de.sebse.fuplanner.tools.ui.CustomViewHolder;
|
||||
import de.sebse.fuplanner.tools.ui.ItemViewHolder;
|
||||
import de.sebse.fuplanner.tools.ui.StringViewHolder;
|
||||
@@ -40,12 +40,10 @@ class ModulesAdapter extends RecyclerView.Adapter<CustomViewHolder> {
|
||||
public void setModules(Modules modules) {
|
||||
mValues = modules;
|
||||
mPositionalData.clear();
|
||||
Semester lastSemester = null;
|
||||
Semester lastSemester = new Semester(Semester.SEM_WS, 0);
|
||||
for (Modules.Module module : mValues) {
|
||||
Semester semester = module.semester;
|
||||
if (semester == null)
|
||||
continue;
|
||||
if (!semester.equals(lastSemester)) {
|
||||
if (semester != null && !semester.equals(lastSemester) || semester == null && lastSemester != null) {
|
||||
mPositionalData.add(new Pair<>(TYPE_HEADER, semester));
|
||||
lastSemester = semester;
|
||||
}
|
||||
@@ -80,7 +78,9 @@ class ModulesAdapter extends RecyclerView.Adapter<CustomViewHolder> {
|
||||
StringViewHolder sHolder = (StringViewHolder) holder;
|
||||
String localizedSemester;
|
||||
Semester semester = (Semester) pair.second;
|
||||
if (semester.getType() == Semester.SEM_WS)
|
||||
if (semester == null)
|
||||
localizedSemester = holder.mView.getResources().getString(R.string.others);
|
||||
else 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());
|
||||
|
||||
@@ -8,11 +8,13 @@ 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;
|
||||
|
||||
@@ -47,7 +49,7 @@ public class ModulesFragment extends Fragment {
|
||||
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
|
||||
Bundle savedInstanceState) {
|
||||
|
||||
View view = inflater.inflate(R.layout.fragment_modules_list, container, false);
|
||||
View view = inflater.inflate(R.layout.fragment_recycler_view, container, false);
|
||||
// Set the adapter
|
||||
Context context = view.getContext();
|
||||
RecyclerView recyclerView = view.findViewById(R.id.list);
|
||||
@@ -66,15 +68,15 @@ public class ModulesFragment extends Fragment {
|
||||
|
||||
private void refresh(boolean forceRefresh) {
|
||||
if (mMainActivityListener != null) {
|
||||
mMainActivityListener.getKVV().modules().list().recv(success -> {
|
||||
mMainActivityListener.getKVV(kvv -> {
|
||||
kvv.modules().list().recv(success -> {
|
||||
adapter.setModules(success);
|
||||
//if (mMainActivityListener != null)
|
||||
// mMainActivityListener.refreshNavigation();
|
||||
swipeLayout.setRefreshing(false);
|
||||
}, error -> {
|
||||
log.e(error.toString());
|
||||
swipeLayout.setRefreshing(false);
|
||||
}, forceRefresh);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,6 +86,10 @@ public class ModulesFragment extends Fragment {
|
||||
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");
|
||||
@@ -105,5 +111,6 @@ public class ModulesFragment extends Fragment {
|
||||
|
||||
public interface OnModulesFragmentInteractionListener {
|
||||
void onModulesFragmentInteraction(String id);
|
||||
void onModulesFragmentListUpdate(Function<Modules, Void> update);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package de.sebse.fuplanner.fragments;
|
||||
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.fragments.ModulesFragment.OnModulesFragmentInteractionListener;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
import de.sebse.fuplanner.tools.UtilsDate;
|
||||
import de.sebse.fuplanner.tools.types.News;
|
||||
import de.sebse.fuplanner.tools.types.NewsList;
|
||||
import de.sebse.fuplanner.tools.ui.NewsViewHolder;
|
||||
|
||||
/**
|
||||
* {@link RecyclerView.Adapter} that can display a {@link Modules.Module} and makes a call to the
|
||||
* specified {@link OnModulesFragmentInteractionListener}.
|
||||
*/
|
||||
class NewsAdapter extends RecyclerView.Adapter<NewsViewHolder> {
|
||||
|
||||
|
||||
private NewsList mValues;
|
||||
|
||||
NewsAdapter() {
|
||||
mValues = null;
|
||||
}
|
||||
|
||||
public void setNews(NewsList news) {
|
||||
mValues = news;
|
||||
this.notifyDataSetChanged();
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public NewsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
|
||||
View view = LayoutInflater.from(parent.getContext())
|
||||
.inflate(R.layout.list_news_item, parent, false);
|
||||
return new NewsViewHolder(view);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolder(@NonNull NewsViewHolder holder, int position) {
|
||||
News news = mValues.getPast(position);
|
||||
holder.mHeader.setText(news.getTitle());
|
||||
switch (news.getCategory()) {
|
||||
case News.CATEGORY_UPDATE:
|
||||
holder.mSubLeft.setText(R.string.update_news);
|
||||
case News.CATEGORY_TRICKS:
|
||||
holder.mSubLeft.setText(R.string.tricks);
|
||||
}
|
||||
holder.mSubRight.setText(UtilsDate.getModifiedDate(news.getDate()));
|
||||
holder.mText.setText(news.getText());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemCount() {
|
||||
return mValues != null ? mValues.sizePast() : 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package de.sebse.fuplanner.fragments;
|
||||
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Bundle;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.fragment.app.Fragment;
|
||||
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
|
||||
import androidx.recyclerview.widget.LinearLayoutManager;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.tools.MainActivityListener;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
import de.sebse.fuplanner.tools.types.NewsList;
|
||||
|
||||
/**
|
||||
* A simple {@link Fragment} subclass.
|
||||
* Use the {@link NewsFragment#newInstance} factory method to
|
||||
* create an instance of this fragment.
|
||||
*/
|
||||
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() {
|
||||
// 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 NewsFragment.
|
||||
*/
|
||||
// TODO: Rename and change types and number of parameters
|
||||
public static NewsFragment newInstance() {
|
||||
NewsFragment fragment = new NewsFragment();
|
||||
Bundle args = new Bundle();
|
||||
fragment.setArguments(args);
|
||||
return fragment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAttach(Context context) {
|
||||
super.onAttach(context);
|
||||
if (context instanceof MainActivityListener) {
|
||||
mListener = (MainActivityListener) context;
|
||||
mListener.onTitleTextChange(R.string.news);
|
||||
}
|
||||
else
|
||||
throw new RuntimeException(context.toString() + " must implement MainActivityListener");
|
||||
refresh(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDetach() {
|
||||
super.onDetach();
|
||||
mListener = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
|
||||
Bundle savedInstanceState) {
|
||||
View view = inflater.inflate(R.layout.fragment_recycler_norefresh, container, false);
|
||||
// Set the adapter
|
||||
Context context = view.getContext();
|
||||
RecyclerView recyclerView = view.findViewById(R.id.list);
|
||||
recyclerView.setLayoutManager(new LinearLayoutManager(context));
|
||||
mAdapter = new NewsAdapter();
|
||||
recyclerView.setAdapter(mAdapter);
|
||||
refresh(false);
|
||||
|
||||
return view;
|
||||
}
|
||||
|
||||
private void refresh(boolean forceRefresh) {
|
||||
if (mListener == null)
|
||||
return;
|
||||
mListener.getNewsManager().recv(success -> {
|
||||
if (mAdapter != null)
|
||||
mAdapter.setNews(success);
|
||||
}, log::e, forceRefresh);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,18 +1,22 @@
|
||||
package de.sebse.fuplanner.fragments;
|
||||
|
||||
import android.accounts.Account;
|
||||
import android.content.ContentResolver;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.Bundle;
|
||||
|
||||
import androidx.preference.ListPreference;
|
||||
import androidx.preference.Preference;
|
||||
import androidx.preference.PreferenceFragmentCompat;
|
||||
|
||||
import de.sebse.fuplanner.MainActivity;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
import de.sebse.fuplanner.services.fulogin.AccountGeneral;
|
||||
import de.sebse.fuplanner.services.kvv.sync.KVVContentProvider;
|
||||
import de.sebse.fuplanner.tools.CustomAccountManager;
|
||||
import de.sebse.fuplanner.tools.Preferences;
|
||||
|
||||
public class PrefsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener {
|
||||
|
||||
private Logger log = new Logger(this);
|
||||
|
||||
public static PrefsFragment newInstance() {
|
||||
PrefsFragment fragment = new PrefsFragment();
|
||||
Bundle args = new Bundle();
|
||||
@@ -46,5 +50,20 @@ public class PrefsFragment extends PreferenceFragmentCompat implements SharedPre
|
||||
Preference preference = getPreferenceScreen().findPreference(s);
|
||||
if (preference instanceof ListPreference)
|
||||
preference.setSummary(((ListPreference) preference).getEntry());
|
||||
|
||||
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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,10 +16,11 @@ import java.util.List;
|
||||
import androidx.annotation.NonNull;
|
||||
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.tools.UtilsDate;
|
||||
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.logging.Logger;
|
||||
import de.sebse.fuplanner.tools.ui.weekview.MonthLoader;
|
||||
import de.sebse.fuplanner.tools.ui.weekview.WeekView;
|
||||
@@ -34,7 +35,11 @@ import de.sebse.fuplanner.tools.ui.weekview.WeekViewEvent;
|
||||
* create an instance of this fragment.
|
||||
*
|
||||
*/
|
||||
public class ScheduleFragment extends Fragment implements MonthLoader.MonthChangeListener, WeekView.ScrollListener, WeekView.DoubleTapListener, WeekView.EventClickListener {
|
||||
public class ScheduleFragment extends Fragment implements
|
||||
MonthLoader.MonthChangeListener,
|
||||
WeekView.ScrollListener,
|
||||
WeekView.DoubleTapLeftRightListener,
|
||||
WeekView.EventClickListener {
|
||||
private MainActivityListener mListener;
|
||||
private WeekView mWeekView;
|
||||
private final Logger log = new Logger(this);
|
||||
@@ -59,11 +64,14 @@ public class ScheduleFragment extends Fragment implements MonthLoader.MonthChang
|
||||
|
||||
public void invalidate(boolean forceRefresh) {
|
||||
if (mListener == null) return;
|
||||
mListener.getKVV().modules().list().recv(modules -> {
|
||||
mListener.getKVV(kvv -> {
|
||||
kvv.modules().list().recv(modules -> {
|
||||
mModules = modules;
|
||||
final int[] i = {0};
|
||||
for (Modules.Module module: mModules) {
|
||||
mListener.getKVV().modules().events().recv(module, success1 -> {
|
||||
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) {
|
||||
@@ -74,6 +82,7 @@ public class ScheduleFragment extends Fragment implements MonthLoader.MonthChang
|
||||
}, log::e, forceRefresh);
|
||||
}
|
||||
}, log::e, forceRefresh);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -83,7 +92,7 @@ public class ScheduleFragment extends Fragment implements MonthLoader.MonthChang
|
||||
mWeekView = v.findViewById(R.id.weekView);
|
||||
mWeekView.setMonthChangeListener(this);
|
||||
mWeekView.setScrollListener(this);
|
||||
mWeekView.setDoubleTapListener(this);
|
||||
mWeekView.setDoubleTapLeftRightListener(this);
|
||||
mWeekView.setOnEventClickListener(this);
|
||||
invalidate(false);
|
||||
return v;
|
||||
@@ -115,7 +124,11 @@ public class ScheduleFragment extends Fragment implements MonthLoader.MonthChang
|
||||
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()) {
|
||||
@@ -150,26 +163,21 @@ public class ScheduleFragment extends Fragment implements MonthLoader.MonthChang
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDoubleTapListener(Calendar time) {
|
||||
public void onDoubleTapLeftRightListener(boolean isRight) {
|
||||
Calendar firstVisibleDay = mWeekView.getFirstVisibleDay();
|
||||
Calendar c = Calendar.getInstance();
|
||||
c.set(firstVisibleDay.get(Calendar.YEAR), firstVisibleDay.get(Calendar.MONTH), firstVisibleDay.get(Calendar.DAY_OF_MONTH), 0,0 );
|
||||
// Limit when to go a week backwards and when to the next week
|
||||
c.add(Calendar.DATE, 2);
|
||||
|
||||
// skip to next week
|
||||
if (c.getTimeInMillis() > time.getTimeInMillis()){
|
||||
firstVisibleDay.add(Calendar.DATE, -1);
|
||||
while (firstVisibleDay.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
|
||||
firstVisibleDay.add(Calendar.DATE, -1);
|
||||
}
|
||||
}
|
||||
else{
|
||||
if (isRight){
|
||||
firstVisibleDay.add(Calendar.DATE, 1);
|
||||
while (firstVisibleDay.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
|
||||
firstVisibleDay.add(Calendar.DATE, 1);
|
||||
}
|
||||
}
|
||||
else {
|
||||
firstVisibleDay.add(Calendar.DATE, -1);
|
||||
while (firstVisibleDay.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
|
||||
firstVisibleDay.add(Calendar.DATE, -1);
|
||||
}
|
||||
}
|
||||
mWeekView.goToDate(firstVisibleDay);
|
||||
onFirstVisibleDayChanged(firstVisibleDay, mWeekView.getLastVisibleDay());
|
||||
}
|
||||
@@ -181,7 +189,8 @@ public class ScheduleFragment extends Fragment implements MonthLoader.MonthChang
|
||||
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());
|
||||
|
||||
if (mListener == null) return;
|
||||
mListener.getKVV().modules().list().find(moduleId, module -> {
|
||||
mListener.getKVV(kvv -> {
|
||||
kvv.modules().list().find(moduleId, module -> {
|
||||
String moduleName = module.title;
|
||||
alertDialogBuilder
|
||||
.setTitle(event.getName())
|
||||
@@ -196,5 +205,6 @@ public class ScheduleFragment extends Fragment implements MonthLoader.MonthChang
|
||||
AlertDialog alertDialog = alertDialogBuilder.create();
|
||||
alertDialog.show();
|
||||
}, log::e);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import androidx.fragment.app.Fragment;
|
||||
import androidx.fragment.app.FragmentManager;
|
||||
import androidx.fragment.app.FragmentStatePagerAdapter;
|
||||
|
||||
import de.sebse.fuplanner.services.Canteen.types.Canteen;
|
||||
import de.sebse.fuplanner.services.canteen.types.Canteen;
|
||||
import de.sebse.fuplanner.tools.UtilsDate;
|
||||
|
||||
class DaySwitcherAdapter extends FragmentStatePagerAdapter {
|
||||
|
||||
@@ -11,8 +11,8 @@ import androidx.fragment.app.Fragment;
|
||||
import androidx.viewpager.widget.ViewPager;
|
||||
import de.sebse.fuplanner.MainActivity;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.services.Canteen.CanteenBrowser;
|
||||
import de.sebse.fuplanner.services.Canteen.types.Canteen;
|
||||
import de.sebse.fuplanner.services.canteen.CanteenBrowser;
|
||||
import de.sebse.fuplanner.services.canteen.types.Canteen;
|
||||
import de.sebse.fuplanner.tools.MainActivityListener;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
import de.sebse.fuplanner.tools.network.NetworkCallback;
|
||||
@@ -31,10 +31,12 @@ public class DaySwitcherFragment extends Fragment implements DaySwitcherListener
|
||||
|
||||
// Parameters
|
||||
private int mCanteenId;
|
||||
private String mPageRestoreRequest = null;
|
||||
|
||||
private MainActivityListener mListener;
|
||||
private final Logger log = new Logger(this);
|
||||
private DaySwitcherAdapter adapterViewPager;
|
||||
private ViewPager mViewPager;
|
||||
|
||||
public DaySwitcherFragment() {
|
||||
// Required empty public constructor
|
||||
@@ -47,10 +49,14 @@ public class DaySwitcherFragment extends Fragment implements DaySwitcherListener
|
||||
* @param canteenId Canteen id in canteens list.
|
||||
* @return A new instance of fragment DaySwitcherFragment.
|
||||
*/
|
||||
public static Fragment newInstance(int canteenId) {
|
||||
public static Fragment newInstance(String canteenId) {
|
||||
DaySwitcherFragment fragment = new DaySwitcherFragment();
|
||||
Bundle args = new Bundle();
|
||||
args.putInt(ARG_POSITION, canteenId);
|
||||
if (!canteenId.contains("."))
|
||||
args.putString(ARG_POSITION, canteenId+".0");
|
||||
else
|
||||
args.putString(ARG_POSITION, canteenId);
|
||||
|
||||
fragment.setArguments(args);
|
||||
return fragment;
|
||||
}
|
||||
@@ -59,7 +65,15 @@ public class DaySwitcherFragment extends Fragment implements DaySwitcherListener
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
if (getArguments() != null) {
|
||||
mCanteenId = getArguments().getInt(ARG_POSITION);
|
||||
String canteenId = getArguments().getString(ARG_POSITION);
|
||||
if (!canteenId.contains(".")) {
|
||||
mCanteenId = Integer.parseInt(canteenId);
|
||||
mPageRestoreRequest = null;
|
||||
} else {
|
||||
String[] split = canteenId.split("\\.", 2);
|
||||
mCanteenId = Integer.parseInt(split[0]);
|
||||
mPageRestoreRequest = split[1];
|
||||
}
|
||||
}
|
||||
if (mListener != null) {
|
||||
mListener.onTitleTextChange(R.string.canteens);
|
||||
@@ -77,10 +91,10 @@ public class DaySwitcherFragment extends Fragment implements DaySwitcherListener
|
||||
// Inflate the layout for this fragment
|
||||
View v = inflater.inflate(R.layout.fragment_mod_detail, container, false);
|
||||
|
||||
ViewPager mViewPager = v.findViewById(R.id.vpPager);
|
||||
mViewPager = v.findViewById(R.id.vpPager);
|
||||
adapterViewPager = new DaySwitcherAdapter(getChildFragmentManager());
|
||||
mViewPager.setAdapter(adapterViewPager);
|
||||
|
||||
applyPageRequest();
|
||||
refresh();
|
||||
|
||||
return v;
|
||||
@@ -114,8 +128,10 @@ public class DaySwitcherFragment extends Fragment implements DaySwitcherListener
|
||||
Canteen canteen = canteens.getCanteen(mCanteenId);
|
||||
canteen.cleanUpDays();
|
||||
adapterViewPager.setModule(canteen);
|
||||
applyPageRequest();
|
||||
browser.getCanteen(canteen, success -> {
|
||||
adapterViewPager.setModule();
|
||||
applyPageRequest();
|
||||
if (callback != null)
|
||||
callback.onResponse(success);
|
||||
}, error -> {
|
||||
@@ -136,4 +152,20 @@ public class DaySwitcherFragment extends Fragment implements DaySwitcherListener
|
||||
refresh(true, callback, errorCallback);
|
||||
}
|
||||
|
||||
public void gotoFragmentPart(int part) {
|
||||
mViewPager.setCurrentItem(part, true);
|
||||
}
|
||||
|
||||
public String getData() {
|
||||
return mCanteenId+"."+mViewPager.getCurrentItem();
|
||||
}
|
||||
|
||||
private void applyPageRequest() {
|
||||
if (mPageRestoreRequest != null) {
|
||||
int request = Integer.parseInt(mPageRestoreRequest);
|
||||
mViewPager.setCurrentItem(request);
|
||||
if (request == mViewPager.getCurrentItem())
|
||||
mPageRestoreRequest = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package de.sebse.fuplanner.fragments.canteen;
|
||||
|
||||
import de.sebse.fuplanner.services.Canteen.types.Canteen;
|
||||
import de.sebse.fuplanner.services.canteen.types.Canteen;
|
||||
import de.sebse.fuplanner.tools.network.NetworkCallback;
|
||||
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
|
||||
|
||||
|
||||
@@ -13,19 +13,19 @@ import androidx.annotation.NonNull;
|
||||
import androidx.annotation.StringRes;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.services.Canteen.types.Day;
|
||||
import de.sebse.fuplanner.services.Canteen.types.Meal;
|
||||
import de.sebse.fuplanner.services.canteen.types.Day;
|
||||
import de.sebse.fuplanner.services.canteen.types.Meal;
|
||||
import de.sebse.fuplanner.tools.Preferences;
|
||||
import de.sebse.fuplanner.tools.ui.MealViewHolder;
|
||||
import de.sebse.fuplanner.tools.ui.StringViewHolder;
|
||||
|
||||
class MealAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
|
||||
private String[] CATEGORY_KEYS = new String[]{"Essen", "Aktionen", "Beilagen", "Desserts", "Salate", "Suppen", "Vorspeisen"};
|
||||
private final String[] CATEGORY_KEYS = new String[]{"Essen", "Aktionen", "Beilagen", "Desserts", "Salate", "Suppen", "Vorspeisen"};
|
||||
@StringRes
|
||||
private int[] CATEGORY_VALS = new int[]{R.string.meals, R.string.special_meals, R.string.side_dishes, R.string.desserts, R.string.salads, R.string.soups, R.string.starters};
|
||||
private final int[] CATEGORY_VALS = new int[]{R.string.meals, R.string.special_meals, R.string.side_dishes, R.string.desserts, R.string.salads, R.string.soups, R.string.starters};
|
||||
@StringRes
|
||||
private int CATEGORY_OTHER = R.string.others;
|
||||
private ArrayList<Object> matches = new ArrayList<>();
|
||||
private final int CATEGORY_OTHER = R.string.others;
|
||||
private final ArrayList<Object> matches = new ArrayList<>();
|
||||
|
||||
private Day mDay = null;
|
||||
private final Context mContext;
|
||||
@@ -56,7 +56,7 @@ class MealAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
|
||||
Meal meal = getMeal(position);
|
||||
viewHolder.mTitle.setText(meal.getName());
|
||||
String value;
|
||||
switch (Preferences.getString(mContext, R.array.pref_price_group)) {
|
||||
switch (Preferences.getStringArray(mContext, R.array.pref_price_group)) {
|
||||
case "student":
|
||||
if (meal.getPriceStdnt() < 0)
|
||||
value = mContext.getResources().getString(R.string.no_price_available);
|
||||
|
||||
@@ -13,9 +13,9 @@ import androidx.recyclerview.widget.RecyclerView;
|
||||
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
|
||||
import de.sebse.fuplanner.MainActivity;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.services.Canteen.CanteenBrowser;
|
||||
import de.sebse.fuplanner.services.Canteen.types.Canteen;
|
||||
import de.sebse.fuplanner.services.Canteen.types.Day;
|
||||
import de.sebse.fuplanner.services.canteen.CanteenBrowser;
|
||||
import de.sebse.fuplanner.services.canteen.types.Canteen;
|
||||
import de.sebse.fuplanner.services.canteen.types.Day;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
|
||||
/**
|
||||
|
||||
@@ -16,20 +16,18 @@ import androidx.annotation.Nullable;
|
||||
import androidx.core.content.ContextCompat;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.services.KVV.ui.Download;
|
||||
import de.sebse.fuplanner.services.KVV.types.Announcement;
|
||||
import de.sebse.fuplanner.services.KVV.types.Modules;
|
||||
import de.sebse.fuplanner.services.kvv.ui.Download;
|
||||
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 Download.OnDownloadRequestInterface requestInterface;
|
||||
@NonNull private final Download.OnDownloadRequestInterface requestInterface;
|
||||
|
||||
ModDetailAnnounceAdapter(@NonNull Download.OnDownloadRequestInterface requestInterface) {
|
||||
this.requestInterface = requestInterface;
|
||||
@@ -40,7 +38,7 @@ class ModDetailAnnounceAdapter extends RecyclerView.Adapter<CustomViewHolder> {
|
||||
this.setModule();
|
||||
}
|
||||
|
||||
public void setModule() {
|
||||
private void setModule() {
|
||||
this.notifyDataSetChanged();
|
||||
}
|
||||
|
||||
|
||||
@@ -14,8 +14,8 @@ import androidx.recyclerview.widget.RecyclerView;
|
||||
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
|
||||
import de.sebse.fuplanner.MainActivity;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.services.KVV.ui.Download;
|
||||
import de.sebse.fuplanner.services.KVV.types.Modules;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
import de.sebse.fuplanner.services.kvv.ui.Download;
|
||||
import de.sebse.fuplanner.tools.MainActivityListener;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
|
||||
@@ -82,26 +82,31 @@ public class ModDetailAnnounceFragment extends Fragment implements Download.OnDo
|
||||
}
|
||||
|
||||
private void refresh(boolean forceRefresh) {
|
||||
if (mListener == null)
|
||||
return;
|
||||
mListener.getKVV().modules().announcements().recv(mItemPos, success -> {
|
||||
adapter.setModule(success);
|
||||
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);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void request(String title, String url) {
|
||||
if (mListener == null)
|
||||
return;
|
||||
mListener.getKVV().modules().list().find(mItemPos, (Modules.Module module) -> {
|
||||
mListener.getKVV(kvv -> {
|
||||
kvv.modules().list().find(mItemPos, (Modules.Module module) -> {
|
||||
String folderName = "FU-"+module.title.replaceAll("[:*<>|/\"\\\\]", "-");
|
||||
folderName += "/Assignment";
|
||||
folderName += "/Announcement";
|
||||
getDownload().openDownloadDialog(title, url, folderName);
|
||||
}, log::e);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -123,7 +128,7 @@ public class ModDetailAnnounceFragment extends Fragment implements Download.OnDo
|
||||
}
|
||||
}
|
||||
|
||||
Download getDownload() {
|
||||
private Download getDownload() {
|
||||
if (download == null)
|
||||
download = new Download(this::getContext, () -> (MainActivity) getActivity());
|
||||
return download;
|
||||
|
||||
@@ -16,20 +16,18 @@ import androidx.annotation.Nullable;
|
||||
import androidx.core.content.ContextCompat;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.services.KVV.ui.Download;
|
||||
import de.sebse.fuplanner.services.KVV.types.Assignment;
|
||||
import de.sebse.fuplanner.services.KVV.types.Modules;
|
||||
import de.sebse.fuplanner.services.kvv.ui.Download;
|
||||
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 Download.OnDownloadRequestInterface requestInterface;
|
||||
@NonNull private final Download.OnDownloadRequestInterface requestInterface;
|
||||
|
||||
ModDetailAssignmentAdapter(@NonNull Download.OnDownloadRequestInterface requestInterface) {
|
||||
this.requestInterface = requestInterface;
|
||||
@@ -40,7 +38,7 @@ class ModDetailAssignmentAdapter extends RecyclerView.Adapter<CustomViewHolder>
|
||||
this.setModule();
|
||||
}
|
||||
|
||||
public void setModule() {
|
||||
private void setModule() {
|
||||
this.notifyDataSetChanged();
|
||||
}
|
||||
|
||||
|
||||
@@ -14,8 +14,8 @@ import androidx.recyclerview.widget.RecyclerView;
|
||||
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
|
||||
import de.sebse.fuplanner.MainActivity;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.services.KVV.ui.Download;
|
||||
import de.sebse.fuplanner.services.KVV.types.Modules;
|
||||
import de.sebse.fuplanner.services.kvv.ui.Download;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
import de.sebse.fuplanner.tools.MainActivityListener;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
|
||||
@@ -82,27 +82,31 @@ public class ModDetailAssignmentFragment extends Fragment implements Download.On
|
||||
}
|
||||
|
||||
private void refresh(boolean forceRefresh) {
|
||||
if (mListener == null)
|
||||
return;
|
||||
mListener.getKVV().modules().assignments().recv(mItemPos, success -> {
|
||||
adapter.setModule(success);
|
||||
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);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void request(String title, String url) {
|
||||
log.d(title, url, mListener);
|
||||
if (mListener == null)
|
||||
return;
|
||||
mListener.getKVV().modules().list().find(mItemPos, (Modules.Module module) -> {
|
||||
mListener.getKVV(kvv -> {
|
||||
kvv.modules().list().find(mItemPos, (Modules.Module module) -> {
|
||||
String folderName = "FU-"+module.title.replaceAll("[:*<>|/\"\\\\]", "-");
|
||||
folderName += "/Assignment";
|
||||
folderName += "/Announcement";
|
||||
getDownload().openDownloadDialog(title, url, folderName);
|
||||
}, log::e);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -124,7 +128,7 @@ public class ModDetailAssignmentFragment extends Fragment implements Download.On
|
||||
}
|
||||
}
|
||||
|
||||
Download getDownload() {
|
||||
private Download getDownload() {
|
||||
if (download == null)
|
||||
download = new Download(this::getContext, () -> (MainActivity) getActivity());
|
||||
return download;
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
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;
|
||||
import android.view.ViewGroup;
|
||||
@@ -12,14 +16,14 @@ import java.util.Map;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.services.KVV.types.Event;
|
||||
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.Triplet;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
import de.sebse.fuplanner.services.kvv.types.Event;
|
||||
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.ui.CustomViewHolder;
|
||||
import de.sebse.fuplanner.tools.ui.ListViewHolder;
|
||||
import de.sebse.fuplanner.tools.ui.ItemViewHolder;
|
||||
import de.sebse.fuplanner.tools.ui.StringViewHolder;
|
||||
|
||||
class ModDetailEventAdapter extends RecyclerView.Adapter<CustomViewHolder> {
|
||||
private static final String VALUE_LECTURE = "Class section - Lecture";
|
||||
@@ -33,11 +37,10 @@ class ModDetailEventAdapter extends RecyclerView.Adapter<CustomViewHolder> {
|
||||
private static final int TYPE_NONE = 0;
|
||||
private static final int TYPE_GROUPED = 1;
|
||||
private static final int TYPE_UNGROUPED = 2;
|
||||
private static final int TYPE_HEADER = 3;
|
||||
|
||||
private Modules.Module mValue;
|
||||
private final ArrayList<Triplet<Integer, String, Object>> mPositionalData;
|
||||
|
||||
private final Logger log = new Logger(this);
|
||||
private final ArrayList<Pair<Integer, Object>> mPositionalData;
|
||||
|
||||
ModDetailEventAdapter() {
|
||||
mValue = null;
|
||||
@@ -50,7 +53,7 @@ class ModDetailEventAdapter extends RecyclerView.Adapter<CustomViewHolder> {
|
||||
this.setModule();
|
||||
}
|
||||
|
||||
public void setModule() {
|
||||
private void setModule() {
|
||||
LinkedHashMap<String, GroupedEvents> listsGrouped = new LinkedHashMap<>();
|
||||
LinkedHashMap<String, EventList> listsUngrouped = new LinkedHashMap<>();
|
||||
for (String value : VALUES_GROUPED) listsGrouped.put(value, new GroupedEvents());
|
||||
@@ -75,15 +78,37 @@ class ModDetailEventAdapter extends RecyclerView.Adapter<CustomViewHolder> {
|
||||
|
||||
mPositionalData.clear();
|
||||
for (Map.Entry<String, GroupedEvents> value: listsGrouped.entrySet()) {
|
||||
if (value.getValue().getGroups().size() > 0)
|
||||
mPositionalData.add(new Triplet<>(TYPE_GROUPED, value.getKey(), value.getValue()));
|
||||
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) {
|
||||
showAsGrouped = false;
|
||||
}
|
||||
if (showAsGrouped) {
|
||||
mPositionalData.add(new Pair<>(TYPE_GROUPED, group));
|
||||
} else {
|
||||
ungroupedGroups.add(group);
|
||||
}
|
||||
}
|
||||
for (GroupedEvents.Group ungroupedGroup : ungroupedGroups) {
|
||||
for (Event event: ungroupedGroup) {
|
||||
mPositionalData.add(new Pair<>(TYPE_UNGROUPED, event));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Map.Entry<String, EventList> value: listsUngrouped.entrySet()) {
|
||||
if (value.getValue().size() > 0)
|
||||
mPositionalData.add(new Triplet<>(TYPE_UNGROUPED, value.getKey(), value.getValue()));
|
||||
if (value.getValue().size() > 0) {
|
||||
mPositionalData.add(new Pair<>(TYPE_HEADER, value.getKey()));
|
||||
for (Event event : value.getValue()) {
|
||||
mPositionalData.add(new Pair<>(TYPE_UNGROUPED, event));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (mPositionalData.size() == 0)
|
||||
mPositionalData.add(new Triplet<>(TYPE_NONE, null, null));
|
||||
mPositionalData.add(new Pair<>(TYPE_NONE, null));
|
||||
this.notifyDataSetChanged();
|
||||
}
|
||||
|
||||
@@ -92,66 +117,132 @@ class ModDetailEventAdapter extends RecyclerView.Adapter<CustomViewHolder> {
|
||||
public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
|
||||
View view;
|
||||
switch (viewType) {
|
||||
case TYPE_NONE:
|
||||
case TYPE_GROUPED:
|
||||
case TYPE_UNGROUPED:
|
||||
view = LayoutInflater.from(parent.getContext())
|
||||
.inflate(R.layout.list_all_items, parent, false);
|
||||
return new ItemViewHolder(view);
|
||||
case TYPE_HEADER:
|
||||
view = LayoutInflater.from(parent.getContext())
|
||||
.inflate(R.layout.list_all_caption, parent, false);
|
||||
return new StringViewHolder(view);
|
||||
default:
|
||||
view = LayoutInflater.from(parent.getContext())
|
||||
.inflate(R.layout.list_all_no_items, parent, false);
|
||||
return new CustomViewHolder(view);
|
||||
default:
|
||||
view = LayoutInflater.from(parent.getContext())
|
||||
.inflate(R.layout.list_all_cardview_list, parent, false);
|
||||
return new ListViewHolder(view);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemViewType(int position) {
|
||||
// Note that unlike in ListView adapters, types don't have to be contiguous
|
||||
if (position < mPositionalData.size())
|
||||
return mPositionalData.get(position).first;
|
||||
else return -1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolder(@NonNull final CustomViewHolder holder, int position) {
|
||||
if (mValue == null || position > mPositionalData.size())
|
||||
return;
|
||||
Triplet<Integer, String, Object> data = mPositionalData.get(position);
|
||||
if (data.first != TYPE_NONE) {
|
||||
ListViewHolder h;
|
||||
ModDetailEventAdapterInner adapter;
|
||||
h = (ListViewHolder) holder;
|
||||
Resources resources = h.mView.getResources();
|
||||
adapter = new ModDetailEventAdapterInner();
|
||||
String title;
|
||||
switch (data.second) {
|
||||
case VALUE_LECTURE:
|
||||
title = resources.getString(R.string.lecture);
|
||||
break;
|
||||
case VALUE_TUTORIAL:
|
||||
title = resources.getString(R.string.tutorial);
|
||||
break;
|
||||
case VALUE_EXAM:
|
||||
title = resources.getString(R.string.exam);
|
||||
break;
|
||||
case VALUE_DEADLINE:
|
||||
title = resources.getString(R.string.deadline);
|
||||
break;
|
||||
case VALUE_OTHER:
|
||||
title = resources.getString(R.string.others);
|
||||
break;
|
||||
default:
|
||||
title = data.second;
|
||||
}
|
||||
h.mString.setText(title);
|
||||
Pair<Integer, Object> data = mPositionalData.get(position);
|
||||
Resources resources = holder.mView.getResources();
|
||||
Context context = holder.mView.getContext();
|
||||
switch (data.first) {
|
||||
case TYPE_GROUPED:
|
||||
adapter.setData((GroupedEvents) data.third, h.mView.getContext());
|
||||
break;
|
||||
case TYPE_UNGROUPED:
|
||||
adapter.setData((EventList) data.third, h.mView.getContext());
|
||||
break;
|
||||
case TYPE_HEADER:
|
||||
StringViewHolder s = (StringViewHolder) holder;
|
||||
String title = "";
|
||||
if (VALUE_LECTURE.equals(data.second)) {
|
||||
title = resources.getString(R.string.lecture);
|
||||
|
||||
} else if (VALUE_TUTORIAL.equals(data.second)) {
|
||||
title = resources.getString(R.string.tutorial);
|
||||
|
||||
} else if (VALUE_EXAM.equals(data.second)) {
|
||||
title = resources.getString(R.string.exam);
|
||||
|
||||
} else if (VALUE_DEADLINE.equals(data.second)) {
|
||||
title = resources.getString(R.string.deadline);
|
||||
|
||||
} else if (VALUE_OTHER.equals(data.second)) {
|
||||
title = resources.getString(R.string.others);
|
||||
}
|
||||
h.mList.setAdapter(adapter);
|
||||
s.mString.setText(title);
|
||||
return;
|
||||
case TYPE_GROUPED:
|
||||
ItemViewHolder ig = (ItemViewHolder) holder;
|
||||
GroupedEvents.Group group = ((GroupedEvents.Group) data.second);
|
||||
long firstDateTime = group.getFirstDate()+group.getStartTime();
|
||||
long lastDateTime = group.getLastDate()+group.getStartTime()+group.getDuration();
|
||||
String start, end, weekday, startTime, endTime;
|
||||
StringBuilder excepts = null;
|
||||
start = UtilsDate.getModifiedDate(firstDateTime);
|
||||
end = UtilsDate.getModifiedDate(lastDateTime);
|
||||
weekday = UtilsDate.getModifiedDate(context, firstDateTime, "E");
|
||||
startTime = UtilsDate.getModifiedTime(context, firstDateTime);
|
||||
endTime = UtilsDate.getModifiedTime(context, lastDateTime+1);
|
||||
for (long skippedDate : group.getSkippedDates()) {
|
||||
if (excepts == null) {
|
||||
excepts = new StringBuilder(UtilsDate.getModifiedDate(skippedDate));
|
||||
} else {
|
||||
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.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;
|
||||
Event event = (Event) data.second;
|
||||
String date;
|
||||
if (UtilsDate.dateEquals(event.getStartDate(), System.currentTimeMillis()))
|
||||
start = UtilsDate.getModifiedTime(context, event.getStartDate());
|
||||
else
|
||||
start = UtilsDate.getModifiedDateTime(context, event.getStartDate());
|
||||
if (UtilsDate.dateEquals(event.getStartDate(), event.getEndDate()))
|
||||
end = UtilsDate.getModifiedTime(context, event.getEndDate()+1);
|
||||
else
|
||||
end = UtilsDate.getModifiedDateTime(context, event.getEndDate()+1);
|
||||
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();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
package de.sebse.fuplanner.fragments.moddetails;
|
||||
|
||||
import android.content.Context;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.services.KVV.types.Event;
|
||||
import de.sebse.fuplanner.services.KVV.types.EventList;
|
||||
import de.sebse.fuplanner.services.KVV.types.GroupedEvents;
|
||||
import de.sebse.fuplanner.tools.UtilsDate;
|
||||
import de.sebse.fuplanner.tools.ui.ItemViewHolder;
|
||||
|
||||
class ModDetailEventAdapterInner extends RecyclerView.Adapter<ItemViewHolder> {
|
||||
private final ArrayList<Entry> mPositionalData;
|
||||
|
||||
ModDetailEventAdapterInner() {
|
||||
mPositionalData = new ArrayList<>();
|
||||
}
|
||||
|
||||
public void setData(GroupedEvents events, final Context context) {
|
||||
mPositionalData.clear();
|
||||
for (GroupedEvents.Group group : events.getGroups()) {
|
||||
long firstDateTime = group.getFirstDate()+group.getStartTime();
|
||||
long lastDateTime = group.getLastDate()+group.getStartTime()+group.getDuration();
|
||||
String start, end, weekday, startTime, endTime;
|
||||
StringBuilder excepts = null;
|
||||
start = UtilsDate.getModifiedDate(firstDateTime);
|
||||
end = UtilsDate.getModifiedDate(lastDateTime);
|
||||
weekday = UtilsDate.getModifiedDate(context, firstDateTime, "E");
|
||||
startTime = UtilsDate.getModifiedTime(context, firstDateTime);
|
||||
endTime = UtilsDate.getModifiedTime(context, lastDateTime);
|
||||
for (long skippedDate : group.getSkippedDates()) {
|
||||
if (excepts == null) {
|
||||
excepts = new StringBuilder(UtilsDate.getModifiedDate(skippedDate));
|
||||
} else {
|
||||
excepts.append(", ").append(UtilsDate.getModifiedDate(skippedDate));
|
||||
}
|
||||
}
|
||||
mPositionalData.add(new Entry(
|
||||
context.getString(R.string.event_scale, weekday, startTime, endTime),
|
||||
context.getString(R.string.date_scale, start, end),
|
||||
excepts != null ? context.getString(R.string.except_list, excepts.toString()) : ""));
|
||||
}
|
||||
this.notifyDataSetChanged();
|
||||
}
|
||||
|
||||
public void setData(EventList events, final Context context) {
|
||||
mPositionalData.clear();
|
||||
for (Event event : events) {
|
||||
String date;
|
||||
String start, end;
|
||||
if (UtilsDate.dateEquals(event.getStartDate(), System.currentTimeMillis()))
|
||||
start = UtilsDate.getModifiedTime(context, event.getStartDate());
|
||||
else
|
||||
start = UtilsDate.getModifiedDateTime(context, event.getStartDate());
|
||||
if (UtilsDate.dateEquals(event.getStartDate(), event.getEndDate()))
|
||||
end = UtilsDate.getModifiedTime(context, event.getEndDate());
|
||||
else
|
||||
end = UtilsDate.getModifiedDateTime(context, event.getEndDate());
|
||||
date = context.getString(R.string.date_scale, start, end);
|
||||
mPositionalData.add(new Entry(event.getTitle(), date, ""));
|
||||
}
|
||||
this.notifyDataSetChanged();
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
|
||||
View view;
|
||||
view = LayoutInflater.from(parent.getContext())
|
||||
.inflate(R.layout.list_all_items, parent, false);
|
||||
return new ItemViewHolder(view);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolder(@NonNull final ItemViewHolder holder, int position) {
|
||||
holder.mTitle.setText(mPositionalData.get(position).title);
|
||||
holder.mSubLeft.setText(mPositionalData.get(position).subtitleLeft);
|
||||
holder.mSubRight.setText(mPositionalData.get(position).subtitleRight);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemCount() {
|
||||
return mPositionalData.size();
|
||||
}
|
||||
|
||||
private class Entry {
|
||||
private String title;
|
||||
private String subtitleLeft;
|
||||
private String subtitleRight;
|
||||
|
||||
private Entry(String title, String subtitleLeft, String subtitleRight) {
|
||||
this.title = title;
|
||||
this.subtitleLeft = subtitleLeft;
|
||||
this.subtitleRight = subtitleRight;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -81,15 +81,18 @@ public class ModDetailEventFragment extends Fragment {
|
||||
}
|
||||
|
||||
private void refresh(boolean forceRefresh) {
|
||||
if (mListener == null)
|
||||
return;
|
||||
mListener.getKVV().modules().events().recv(mItemPos, success -> {
|
||||
adapter.setModule(success);
|
||||
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);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -10,7 +10,7 @@ import androidx.annotation.NonNull;
|
||||
import androidx.fragment.app.Fragment;
|
||||
import androidx.viewpager.widget.ViewPager;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.services.KVV.types.Modules;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
import de.sebse.fuplanner.tools.MainActivityListener;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
|
||||
@@ -48,7 +48,7 @@ public class ModDetailFragment extends Fragment implements ModDetailListener {
|
||||
ModDetailFragment fragment = new ModDetailFragment();
|
||||
Bundle args = new Bundle();
|
||||
if (!itemPosition.contains("."))
|
||||
args.putString(ARG_POSITION, itemPosition+"."+0);
|
||||
args.putString(ARG_POSITION, itemPosition+".0");
|
||||
else
|
||||
args.putString(ARG_POSITION, itemPosition);
|
||||
|
||||
@@ -72,11 +72,13 @@ public class ModDetailFragment extends Fragment implements ModDetailListener {
|
||||
}
|
||||
if (mListener != null) {
|
||||
mListener.onTitleTextChange(R.string.courses);
|
||||
mListener.getKVV().modules().list().recv(success -> {
|
||||
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);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,8 +12,8 @@ import java.util.ArrayList;
|
||||
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.Modules;
|
||||
import de.sebse.fuplanner.services.kvv.types.Grade;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
import de.sebse.fuplanner.tools.ui.StringViewHolder;
|
||||
|
||||
class ModDetailGradebookAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
|
||||
@@ -36,20 +36,16 @@ class ModDetailGradebookAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
|
||||
this.setModule();
|
||||
}
|
||||
|
||||
public void setModule() {
|
||||
private void setModule() {
|
||||
mPositionalData.clear();
|
||||
mPositionalData.add(new Pair<>(TYPE_TOTAL, SECTION_GRADE));
|
||||
addPositionalListData(getGradesCount(), SECTION_GRADE);
|
||||
for (int i = 0; i < getGradesCount(); i++) {
|
||||
mPositionalData.add(new Pair<>(TYPE_GRADE, SECTION_GRADE +1024*i));
|
||||
}
|
||||
|
||||
this.notifyDataSetChanged();
|
||||
}
|
||||
|
||||
private void addPositionalListData(int count, int category) {
|
||||
for (int i = 0; i < count; i++) {
|
||||
mPositionalData.add(new Pair<>(TYPE_GRADE, category+1024*i));
|
||||
}
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
|
||||
@@ -131,6 +127,7 @@ class ModDetailGradebookAdapter extends RecyclerView.Adapter<RecyclerView.ViewHo
|
||||
mGradeMax = view.findViewById(R.id.grade_max);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
return super.toString() + " '" + mTitle.getText() + " '" + mGrade.getText() + " '" + mGradeMax.getText() + "'";
|
||||
|
||||
@@ -81,15 +81,18 @@ public class ModDetailGradebookFragment extends Fragment {
|
||||
}
|
||||
|
||||
private void refresh(boolean forceRefresh) {
|
||||
if (mListener == null)
|
||||
return;
|
||||
mListener.getKVV().modules().gradebook().recv(mItemPos, success -> {
|
||||
adapter.setModule(success);
|
||||
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);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -2,6 +2,7 @@ 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;
|
||||
@@ -15,16 +16,16 @@ import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.services.KVV.types.Announcement;
|
||||
import de.sebse.fuplanner.services.KVV.types.Assignment;
|
||||
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.services.kvv.types.Announcement;
|
||||
import de.sebse.fuplanner.services.kvv.types.Assignment;
|
||||
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;
|
||||
import de.sebse.fuplanner.tools.ui.ShortcutViewHolder;
|
||||
import de.sebse.fuplanner.tools.ui.StringViewHolder;
|
||||
|
||||
class ModDetailOverviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
|
||||
@@ -35,12 +36,13 @@ class ModDetailOverviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
|
||||
private static final int TYPE_ITEM = 2;
|
||||
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;
|
||||
@@ -53,10 +55,13 @@ class ModDetailOverviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
|
||||
this.setModule();
|
||||
}
|
||||
|
||||
public void setModule() {
|
||||
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_SHORTCUTS, null));
|
||||
mPositionalData.add(new Pair<>(TYPE_HEADER, ModulePart.LECTURERS));
|
||||
for (int i = 0; i < mValue.lecturer.size(); i++) {
|
||||
mPositionalData.add(new Pair<>(TYPE_MAIL, ModulePart.LECTURERS+1024*i));
|
||||
@@ -76,6 +81,9 @@ 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
|
||||
@@ -99,10 +107,18 @@ 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);
|
||||
return new MailViewHolder(view);
|
||||
case TYPE_SHORTCUTS:
|
||||
view = LayoutInflater.from(parent.getContext())
|
||||
.inflate(R.layout.list_moddetails_shortcuts, parent, false);
|
||||
return new ShortcutViewHolder(view);
|
||||
default:
|
||||
//noinspection ConstantConditions
|
||||
return null;
|
||||
@@ -186,9 +202,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());
|
||||
end = UtilsDate.getModifiedTime(i.mView.getContext(), event.getEndDate()+1);
|
||||
else
|
||||
end = UtilsDate.getModifiedDateTime(i.mView.getContext(), event.getEndDate());
|
||||
end = UtilsDate.getModifiedDateTime(i.mView.getContext(), event.getEndDate()+1);
|
||||
i.mSubRight.setText(i.mView.getResources().getString(R.string.date_scale,
|
||||
start, end
|
||||
));
|
||||
@@ -214,11 +230,22 @@ class ModDetailOverviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
|
||||
emailIntent.setData(Uri.parse("mailto:"+lecturer.getMail()));
|
||||
emailIntent.putExtra(Intent.EXTRA_SUBJECT, mValue.title);
|
||||
emailIntent.putExtra(Intent.EXTRA_TEXT, defaultText);
|
||||
m.mView.getContext().startActivity(Intent.createChooser(emailIntent, mValue.title));
|
||||
m.mView.getContext().startActivity(emailIntent);
|
||||
});
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case TYPE_SHORTCUTS:
|
||||
ShortcutViewHolder s = (ShortcutViewHolder) holder;
|
||||
s.mLeft.setOnClickListener(view -> {
|
||||
if (mListener != null) mListener.gotoFragmentPart(ModulePart.RESOURCES, -1);
|
||||
});
|
||||
s.mRight.setOnClickListener(view -> {
|
||||
if (mListener != null) mListener.gotoFragmentPart(ModulePart.GRADEBOOK, -1);
|
||||
});
|
||||
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,7 +86,8 @@ public class ModDetailOverviewFragment extends Fragment {
|
||||
|
||||
private void refresh(boolean forceRefresh) {
|
||||
if (mListener != null) {
|
||||
mListener.getKVV().modules().details().recv(mItemPos, pair -> {
|
||||
mListener.getKVV(kvv -> {
|
||||
kvv.modules().details().recv(mItemPos, pair -> {
|
||||
adapter.setModule(pair.first);
|
||||
if (pair.second)
|
||||
swipeLayout.setRefreshing(false);
|
||||
@@ -94,6 +95,7 @@ public class ModDetailOverviewFragment extends Fragment {
|
||||
swipeLayout.setRefreshing(false);
|
||||
log.e(error);
|
||||
}, forceRefresh);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,8 +3,8 @@ package de.sebse.fuplanner.fragments.moddetails;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import de.sebse.fuplanner.services.KVV.types.Modules;
|
||||
import de.sebse.fuplanner.services.KVV.types.Resource;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
import de.sebse.fuplanner.services.kvv.types.Resource;
|
||||
import de.sebse.fuplanner.tools.ui.treeview.TreeNode;
|
||||
import de.sebse.fuplanner.tools.ui.treeview.TreeViewAdapter;
|
||||
import de.sebse.fuplanner.tools.ui.treeview.TreeViewBinder;
|
||||
@@ -21,7 +21,7 @@ class ModDetailResourceAdapter extends TreeViewAdapter {
|
||||
this.setModule();
|
||||
}
|
||||
|
||||
public void setModule() {
|
||||
private void setModule() {
|
||||
if (mValue == null || mValue.resources == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -18,12 +18,13 @@ import androidx.recyclerview.widget.RecyclerView;
|
||||
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
|
||||
import de.sebse.fuplanner.MainActivity;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.services.KVV.ui.Download;
|
||||
import de.sebse.fuplanner.services.KVV.types.Modules;
|
||||
import de.sebse.fuplanner.services.KVV.types.Resource;
|
||||
import de.sebse.fuplanner.services.kvv.ui.Download;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
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;
|
||||
@@ -33,7 +34,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 {
|
||||
public class ModDetailResourceFragment extends Fragment implements Download.OnDownloadRequestInterface {
|
||||
private static final String ARG_POSITION = "itemPosition";
|
||||
|
||||
private String mItemPos;
|
||||
@@ -81,7 +82,7 @@ public class ModDetailResourceFragment extends Fragment {
|
||||
RecyclerView recyclerView = view.findViewById(R.id.list);
|
||||
recyclerView.setLayoutManager(new LinearLayoutManager(context));
|
||||
|
||||
adapter = new ModDetailResourceAdapter(Arrays.asList(new FileNodeBinder(), new DirectoryNodeBinder()));
|
||||
adapter = new ModDetailResourceAdapter(Arrays.asList(new FileNodeBinder(), new DirectoryNodeBinder(), new DocumentNodeBinder(this)));
|
||||
adapter.setOnTreeNodeListener(new TreeViewAdapter.OnTreeNodeListener() {
|
||||
@Override
|
||||
public boolean onClick(TreeNode node, RecyclerView.ViewHolder holder) {
|
||||
@@ -89,11 +90,13 @@ public class ModDetailResourceFragment extends Fragment {
|
||||
// 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().modules().resources().recv(mItemPos, (Modules.Module module) -> {
|
||||
ModDetailResourceFragment.this.mListener.getKVV(kvv -> {
|
||||
kvv.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;
|
||||
}
|
||||
@@ -118,6 +121,19 @@ public class ModDetailResourceFragment extends Fragment {
|
||||
return view;
|
||||
}
|
||||
|
||||
@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(Context context) {
|
||||
super.onAttach(context);
|
||||
@@ -138,18 +154,21 @@ public class ModDetailResourceFragment extends Fragment {
|
||||
}
|
||||
|
||||
private void refresh(boolean forceRefresh) {
|
||||
if (mListener == null)
|
||||
return;
|
||||
mListener.getKVV().modules().assignments().recv(mItemPos, success -> {
|
||||
adapter.setModule(success);
|
||||
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);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Download getDownload() {
|
||||
private Download getDownload() {
|
||||
if (download == null)
|
||||
download = new Download(this::getContext, () -> (MainActivity) getActivity());
|
||||
return download;
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
package de.sebse.fuplanner.fragments.moddetails;
|
||||
|
||||
class ModulePart {
|
||||
public class ModulePart {
|
||||
static final int DESCRIPTION = 0;
|
||||
static final int OVERVIEW = 1;
|
||||
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;
|
||||
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 LECTURERS = 7;
|
||||
private static final int[] pages = new int[]{OVERVIEW, ANNOUNCEMENT, ASSIGNMENT, GRADEBOOK, RESOURCES, EVENT};
|
||||
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
package de.sebse.fuplanner.services.GoogleAuth;
|
||||
|
||||
/**
|
||||
* Created by sebastian on 07.11.17.
|
||||
*/
|
||||
|
||||
public interface ConnectedListener {
|
||||
void connected();
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package de.sebse.fuplanner.services.GoogleAuth;
|
||||
|
||||
/**
|
||||
* Created by Sebastian on 06.11.2017.
|
||||
*/
|
||||
|
||||
public class Credentials {
|
||||
private final String username;
|
||||
private final String password;
|
||||
|
||||
public Credentials(String username, String password) {
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package de.sebse.fuplanner.services.GoogleAuth;
|
||||
|
||||
/**
|
||||
* Created by Sebastian on 06.11.2017.
|
||||
*/
|
||||
|
||||
public interface CredentialsListener {
|
||||
void onCredentials(Credentials credentials);
|
||||
}
|
||||
@@ -1,224 +0,0 @@
|
||||
package de.sebse.fuplanner.services.GoogleAuth;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.content.IntentSender;
|
||||
import android.util.Log;
|
||||
import android.widget.Toast;
|
||||
|
||||
import com.google.android.gms.auth.api.credentials.Credential;
|
||||
import com.google.android.gms.auth.api.credentials.CredentialRequest;
|
||||
import com.google.android.gms.auth.api.credentials.CredentialsClient;
|
||||
import com.google.android.gms.auth.api.credentials.CredentialsOptions;
|
||||
import com.google.android.gms.common.ConnectionResult;
|
||||
import com.google.android.gms.common.GoogleApiAvailability;
|
||||
import com.google.android.gms.common.api.ApiException;
|
||||
import com.google.android.gms.common.api.CommonStatusCodes;
|
||||
import com.google.android.gms.common.api.ResolvableApiException;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.fragment.app.FragmentActivity;
|
||||
|
||||
import static android.app.Activity.RESULT_OK;
|
||||
|
||||
/**
|
||||
* Created by Sebastian on 06.11.2017.
|
||||
*/
|
||||
|
||||
public class GoogleAuth {
|
||||
// https://developers.google.com/identity/smartlock-passwords/android/retrieve-credentials
|
||||
|
||||
private static final String TAG = "GoogleAuth";
|
||||
private final FragmentActivity activity;
|
||||
private static final String FU_PLANNER_PROVIDER = "FUPlanner";
|
||||
private CredentialsClient mCredentialsClient;
|
||||
private boolean mIsResolving;
|
||||
@Nullable
|
||||
private CredentialsListener mCredentialsListener;
|
||||
private boolean isConnected = false;
|
||||
|
||||
public GoogleAuth(FragmentActivity activity) {
|
||||
this.activity = activity;
|
||||
}
|
||||
|
||||
private void connect() {
|
||||
if (this.isUnavailable()) {
|
||||
Log.d(TAG, "STATUS: Google auth not available!");
|
||||
return;
|
||||
}
|
||||
this.mCredentialsClient = getClient();
|
||||
this.isConnected = true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public void getLoginState(final CredentialsListener credentialsListener) {
|
||||
if (this.isUnavailable()) {
|
||||
Log.d(TAG, "STATUS: Google auth not available!");
|
||||
credentialsListener.onCredentials(null);
|
||||
return;
|
||||
}
|
||||
if (!this.isConnected)
|
||||
connect();
|
||||
CredentialRequest request = new CredentialRequest.Builder()
|
||||
.setPasswordLoginSupported(true)
|
||||
.setAccountTypes(FU_PLANNER_PROVIDER)
|
||||
.build();
|
||||
|
||||
|
||||
mCredentialsClient.request(request).addOnCompleteListener(task -> {
|
||||
if (task.isSuccessful()) {
|
||||
// Successfully read the credential without any user interaction, this
|
||||
// means there was only a single credential and the user has auto
|
||||
// sign-in enabled.
|
||||
Credential credential = task.getResult().getCredential();
|
||||
credentialsListener.onCredentials(new Credentials(credential.getId(), credential.getPassword()));
|
||||
return;
|
||||
}
|
||||
|
||||
Exception e = task.getException();
|
||||
if (e instanceof ResolvableApiException) {
|
||||
// This is most likely the case where the user has multiple saved
|
||||
// credentials and needs to pick one. This requires showing UI to
|
||||
// resolve the read request.
|
||||
GoogleAuth.this.mCredentialsListener = credentialsListener;
|
||||
ResolvableApiException rae = (ResolvableApiException) e;
|
||||
resolveResult(rae, RequestCode.RC_READ);
|
||||
return;
|
||||
}
|
||||
|
||||
if (e instanceof ApiException) {
|
||||
ApiException ae = (ApiException) e;
|
||||
if (ae.getStatusCode() == CommonStatusCodes.SIGN_IN_REQUIRED) {
|
||||
// This means only a hint is available, but we are handling that
|
||||
// elsewhere so no need to act here.
|
||||
} else {
|
||||
credentialsListener.onCredentials(null);
|
||||
Log.w(TAG, "Unexpected status code: " + ae.getStatusCode());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void setLoginState(String username, String password) {
|
||||
if (this.isUnavailable()) {
|
||||
Log.d(TAG, "STATUS: Google auth not available!");
|
||||
Toast.makeText(activity, "Google auth not available!", Toast.LENGTH_SHORT).show();
|
||||
return;
|
||||
}
|
||||
if (!this.isConnected)
|
||||
connect();
|
||||
Credential credential = new Credential.Builder(username)
|
||||
.setPassword(password)
|
||||
.build();
|
||||
mCredentialsClient.save(credential).addOnCompleteListener(task -> {
|
||||
if (task.isSuccessful()) {
|
||||
showToast("Credential saved.");
|
||||
return;
|
||||
}
|
||||
|
||||
Exception e = task.getException();
|
||||
if (e instanceof ResolvableApiException) {
|
||||
// The first time a credential is saved, the user is shown UI
|
||||
// to confirm the action. This requires resolution.
|
||||
ResolvableApiException rae = (ResolvableApiException) e;
|
||||
resolveResult(rae, RequestCode.RC_SAVE);
|
||||
} else {
|
||||
// Save failure cannot be resolved.
|
||||
Log.w(TAG, "Save failed.", e);
|
||||
showToast("Credential Save Failed");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void deleteLoginState(String username, String password) {
|
||||
if (this.isUnavailable()) {
|
||||
Log.d(TAG, "STATUS: Google auth not available!");
|
||||
return;
|
||||
}
|
||||
if (!this.isConnected)
|
||||
connect();
|
||||
Credential credential = new Credential.Builder(username)
|
||||
.setPassword(password)
|
||||
.build();
|
||||
mCredentialsClient.delete(credential).addOnCompleteListener(task -> {
|
||||
if (task.isSuccessful()) {
|
||||
// Credential was deleted successfully
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
private boolean isUnavailable() {
|
||||
return GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this.activity) != ConnectionResult.SUCCESS;
|
||||
}
|
||||
|
||||
private CredentialsClient getClient() {
|
||||
CredentialsOptions options = new CredentialsOptions.Builder()
|
||||
.forceEnableSaveDialog()
|
||||
.build();
|
||||
return com.google.android.gms.auth.api.credentials.Credentials.getClient(this.activity, options);
|
||||
}
|
||||
|
||||
public void onActivityResult(int requestCode, int resultCode, Intent data) {
|
||||
Log.d(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);
|
||||
|
||||
switch (requestCode) {
|
||||
case RequestCode.RC_HINT:
|
||||
// Drop into handling for RC_READ
|
||||
case RequestCode.RC_READ:
|
||||
if (resultCode == RESULT_OK) {
|
||||
boolean isHint = (requestCode == RequestCode.RC_HINT);
|
||||
Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
|
||||
if (mCredentialsListener != null)
|
||||
this.mCredentialsListener.onCredentials(new Credentials(credential.getId(), credential.getPassword()));
|
||||
else
|
||||
Log.d(TAG, "No Credentials Listener");
|
||||
} else {
|
||||
if (mCredentialsListener != null)
|
||||
this.mCredentialsListener.onCredentials(null);
|
||||
else
|
||||
Log.d(TAG, "No Credentials Listener");
|
||||
Log.e(TAG, "Credential Read: NOT OK");
|
||||
showToast("Credential Read Failed");
|
||||
}
|
||||
|
||||
mIsResolving = false;
|
||||
break;
|
||||
case RequestCode.RC_SAVE:
|
||||
if (resultCode == RESULT_OK) {
|
||||
Log.d(TAG, "Credential Save: OK");
|
||||
showToast("Credential Save Success");
|
||||
} else {
|
||||
Log.e(TAG, "Credential Save: NOT OK");
|
||||
showToast("Credential Save Failed");
|
||||
}
|
||||
|
||||
mIsResolving = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void resolveResult(ResolvableApiException rae, int requestCode) {
|
||||
// We don't want to fire multiple resolutions at once since that can result
|
||||
// in stacked dialogs after rotation or another similar event.
|
||||
if (mIsResolving) {
|
||||
Log.w(TAG, "resolveResult: already resolving.");
|
||||
return;
|
||||
}
|
||||
|
||||
Log.d(TAG, "Resolving: " + rae);
|
||||
try {
|
||||
rae.startResolutionForResult(this.activity, requestCode);
|
||||
mIsResolving = true;
|
||||
} catch (IntentSender.SendIntentException e) {
|
||||
Log.e(TAG, "STATUS: Failed to send resolution.", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Display a short Toast message **/
|
||||
private void showToast(String msg) {
|
||||
Toast.makeText(this.activity, msg, Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package de.sebse.fuplanner.services.GoogleAuth;
|
||||
|
||||
/**
|
||||
* Created by sebastian on 07.11.17.
|
||||
*/
|
||||
|
||||
class RequestCode {
|
||||
public static final int RC_SAVE = 1;
|
||||
public static final int RC_HINT = 2;
|
||||
public static final int RC_READ = 3;
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package de.sebse.fuplanner.services.KVV;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
public class KVV {
|
||||
private final HashMap<String, Object> addons = new HashMap<>();
|
||||
private final KVVListener mListener;
|
||||
private final Context mContext;
|
||||
|
||||
public KVV(KVVListener listener, Context context) {
|
||||
this.mListener = listener;
|
||||
this.mContext = context;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Login account() {
|
||||
return (Login) addAndGet("account", () -> new Login(mListener, mContext));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Modules modules() {
|
||||
return (Modules) addAndGet("module", () -> new Modules(account(), mListener, mContext));
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@NotNull
|
||||
private Object addAndGet(@NotNull String addon, @NotNull ModuleCreatorInterface creatorInterface) {
|
||||
Object o = addons.get(addon);
|
||||
if (o == null) {
|
||||
o = creatorInterface.create();
|
||||
addons.put(addon, o);
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
private interface ModuleCreatorInterface {
|
||||
@NotNull Object create();
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package de.sebse.fuplanner.services.KVV;
|
||||
|
||||
import com.android.volley.NetworkResponse;
|
||||
|
||||
import de.sebse.fuplanner.services.GoogleAuth.Credentials;
|
||||
import de.sebse.fuplanner.services.KVV.types.LoginToken;
|
||||
import de.sebse.fuplanner.tools.network.NetworkCallback;
|
||||
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
|
||||
|
||||
public interface KVVListener {
|
||||
void getCredentials(NetworkCallback<Credentials> callback, NetworkErrorCallback error);
|
||||
|
||||
void onLogin(LoginToken token, boolean enteringOnlineMode);
|
||||
|
||||
void onLogout();
|
||||
|
||||
void onModuleListChange();
|
||||
|
||||
void onKVVNetworkResponse(NetworkResponse error);
|
||||
}
|
||||
@@ -1,444 +0,0 @@
|
||||
package de.sebse.fuplanner.services.KVV;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
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 {
|
||||
private KVVListener mListener;
|
||||
@Nullable private LoginToken mToken;
|
||||
private boolean mLoginPending = false;
|
||||
private boolean mOnlineMode = false;
|
||||
|
||||
Login(KVVListener listener, Context context) {
|
||||
super(context);
|
||||
this.mListener = listener;
|
||||
}
|
||||
|
||||
public void doOnlineLogin(@NotNull String username, @NotNull String password, NetworkCallback<LoginToken> callback, NetworkErrorCallback errorCallback) {
|
||||
if (mLoginPending) {
|
||||
errorCallback.onError(new NetworkError(100160, -1, "Login already pending!"));
|
||||
}
|
||||
mLoginPending = true;
|
||||
doLogin(username, password, token -> {
|
||||
testLoginToken(token, token2 -> {
|
||||
setToken(token2, true);
|
||||
mLoginPending = false;
|
||||
callback.onResponse(token2);
|
||||
}, error -> {
|
||||
mLoginPending = false;
|
||||
errorCallback.onError(error);
|
||||
});
|
||||
}, error -> {
|
||||
mLoginPending = false;
|
||||
errorCallback.onError(error);
|
||||
});
|
||||
}
|
||||
|
||||
public boolean restoreOnlineLogin() {
|
||||
return restoreLogin(true);
|
||||
}
|
||||
|
||||
public boolean doOfflineLogin() {
|
||||
return restoreLogin(false);
|
||||
}
|
||||
|
||||
private boolean restoreLogin(boolean enteringOnlineMode) {
|
||||
if (mLoginPending || mToken != null)
|
||||
return false;
|
||||
mLoginPending = true;
|
||||
boolean result = false;
|
||||
try {
|
||||
result = setToken(LoginToken.load(getContext()), enteringOnlineMode);
|
||||
} catch (FileNotFoundException ignored) {
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} catch (ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
mLoginPending = false;
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean isOfflineStoredAvailable() {
|
||||
try {
|
||||
LoginToken load = LoginToken.load(getContext());
|
||||
return load != null;
|
||||
} catch (FileNotFoundException ignored) {
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} catch (ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean logout(boolean delete) {
|
||||
if (mLoginPending)
|
||||
return false;
|
||||
if (mToken == null)
|
||||
return true;
|
||||
if (delete)
|
||||
mToken.delete(getContext());
|
||||
mToken = null;
|
||||
return handleCallbacks();
|
||||
}
|
||||
|
||||
public boolean isLoginPending() {
|
||||
return mLoginPending;
|
||||
}
|
||||
|
||||
public boolean isLoggedIn() {
|
||||
return mToken != null;
|
||||
}
|
||||
|
||||
public boolean isInOfflineMode() {
|
||||
return isLoggedIn() && !mOnlineMode;
|
||||
}
|
||||
|
||||
public boolean isInOnlineMode() {
|
||||
return isLoggedIn() && mOnlineMode;
|
||||
}
|
||||
|
||||
void testLoginToken(@NotNull NetworkCallback<LoginToken> callback, @NotNull NetworkErrorCallback errorCallback) {
|
||||
if (mToken == null) {
|
||||
errorCallback.onError(new NetworkError(100173, -1, "Not logged in!"));
|
||||
return;
|
||||
}
|
||||
testLoginToken(mToken, callback, errorCallback);
|
||||
}
|
||||
|
||||
private 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!")));
|
||||
}
|
||||
|
||||
@Nullable public LoginToken getLoginToken() {
|
||||
return mToken;
|
||||
}
|
||||
|
||||
void refreshLogin(NetworkCallback<LoginToken> success, NetworkErrorCallback error) {
|
||||
mListener.getCredentials(credentials -> {
|
||||
doOnlineLogin(credentials.getUsername(), credentials.getPassword(), success, error);
|
||||
}, e -> {
|
||||
logout(false);
|
||||
error.onError(e);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
private boolean handleCallbacks() {
|
||||
if (mToken != null) {
|
||||
mListener.onLogin(mToken, mOnlineMode);
|
||||
return true;
|
||||
} else {
|
||||
mListener.onLogout();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean setToken(@Nullable LoginToken token, boolean enteringOnlineMode) {
|
||||
if (token == null)
|
||||
return false;
|
||||
boolean isOnlyRefresh = mToken != null;
|
||||
mToken = token;
|
||||
if (enteringOnlineMode) {
|
||||
try {
|
||||
mToken.save(getContext());
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
mOnlineMode = enteringOnlineMode;
|
||||
return isOnlyRefresh || handleCallbacks();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
private 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,91 +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.util.ArrayList;
|
||||
|
||||
import de.sebse.fuplanner.services.KVV.types.Announcement;
|
||||
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 ModulesAnnouncements extends PartModules<ArrayList<Announcement>> {
|
||||
|
||||
ModulesAnnouncements(Login login, ModulesList list, Context context) {
|
||||
super(login, list, context);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ArrayList<Announcement> getPart(Modules.Module module) {
|
||||
return module.announcements;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean setPart(Modules.Module module, ArrayList<Announcement> part) {
|
||||
boolean changed = module.announcements == null || module.announcements.hashCode() != part.hashCode();
|
||||
module.announcements = part;
|
||||
return changed;
|
||||
}
|
||||
|
||||
@Override
|
||||
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("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!"));
|
||||
return;
|
||||
}
|
||||
ArrayList<Announcement> announcements = new ArrayList<>();
|
||||
JSONArray sites;
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
sites = json.getJSONArray("announcement_collection");
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
errorCallback.onError(new NetworkError(101202, 403, "Cannot parse announcements!"));
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < sites.length(); i++) {
|
||||
try {
|
||||
JSONObject site = sites.getJSONObject(i);
|
||||
String id = site.getString("announcementId");
|
||||
String title = site.getString("title");
|
||||
String text = site.getString("body");
|
||||
text = String.valueOf(fromHtml(text));
|
||||
String createdBy = site.getString("createdByDisplayName");
|
||||
long createdOn = site.getLong("createdOn");
|
||||
|
||||
// Extract attachment links
|
||||
JSONArray attachments = site.getJSONArray("attachments");
|
||||
ArrayList<String> urls = new ArrayList<>();
|
||||
for (int j = 0; j < attachments.length(); j++) {
|
||||
urls.add(attachments.getJSONObject(j).optString("url", null));
|
||||
}
|
||||
|
||||
announcements.add(new Announcement(id, title, text, createdBy, createdOn, urls));
|
||||
} catch (JSONException e) {
|
||||
log.e(new NetworkError(101205, 403, "Cannot parse announcements!"));
|
||||
log.e("ID:", i, "JSON:", sites);
|
||||
e.printStackTrace();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 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!")));
|
||||
}
|
||||
}
|
||||
@@ -1,83 +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 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.tools.network.NetworkCallback;
|
||||
import de.sebse.fuplanner.tools.network.NetworkError;
|
||||
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
|
||||
|
||||
public class ModulesEvents extends PartModules<EventList> {
|
||||
|
||||
ModulesEvents(Login login, ModulesList list, Context context) {
|
||||
super(login, list, context);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected EventList getPart(Modules.Module module) {
|
||||
return module.events;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean setPart(Modules.Module module, EventList part) {
|
||||
boolean changed = module.events == null || module.events.hashCode() != part.hashCode();
|
||||
module.events = part;
|
||||
return changed;
|
||||
}
|
||||
|
||||
@Override
|
||||
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("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!"));
|
||||
return;
|
||||
}
|
||||
EventList events = new EventList();
|
||||
JSONArray sites;
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
sites = json.getJSONArray("calendar_collection");
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
errorCallback.onError(new NetworkError(101402, 403, "Cannot parse events!"));
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < sites.length(); i++) {
|
||||
try {
|
||||
JSONObject site = sites.getJSONObject(i);
|
||||
String id = site.getString("eventId");
|
||||
String type = site.getString("type");
|
||||
String title = site.getString("title");
|
||||
String siteId = site.getString("siteId");
|
||||
long duration = site.getLong("duration");
|
||||
long firstTime = site.getJSONObject("firstTime").getLong("time");
|
||||
String location = site.getString("location");
|
||||
events.add(new Event(id, type, title, duration, firstTime, siteId, location));
|
||||
} catch (JSONException e) {
|
||||
log.e(new NetworkError(101405, 403, "Cannot parse events!"));
|
||||
e.printStackTrace();
|
||||
log.e("ID:", i, "JSON:", sites);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 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!")));
|
||||
}
|
||||
}
|
||||
@@ -1,76 +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.util.ArrayList;
|
||||
|
||||
import de.sebse.fuplanner.services.KVV.types.Grade;
|
||||
import de.sebse.fuplanner.services.KVV.types.Modules;
|
||||
import de.sebse.fuplanner.tools.network.NetworkCallback;
|
||||
import de.sebse.fuplanner.tools.network.NetworkError;
|
||||
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
|
||||
|
||||
public class ModulesGradebook extends PartModules<ArrayList<Grade>> {
|
||||
|
||||
ModulesGradebook(Login login, ModulesList list, Context context) {
|
||||
super(login, list, context);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ArrayList<Grade> getPart(Modules.Module module) {
|
||||
return module.gradebook;
|
||||
}
|
||||
|
||||
@Override
|
||||
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 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("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;
|
||||
}
|
||||
ArrayList<Grade> gradebook = new ArrayList<>();
|
||||
JSONArray sites;
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
sites = json.getJSONArray("assignments");
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
errorCallback.onError(new NetworkError(101502, 403, "Cannot parse gradebook!"));
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < sites.length(); i++) {
|
||||
try {
|
||||
JSONObject site = sites.getJSONObject(i);
|
||||
double grade = site.optDouble("grade", 0);
|
||||
String itemName = site.optString("itemName", null);
|
||||
double maxPoints = site.optDouble("points", -1);
|
||||
|
||||
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);
|
||||
e.printStackTrace();
|
||||
return;
|
||||
}
|
||||
}
|
||||
callback.onResponse(gradebook);
|
||||
}, error -> errorCallback.onError(new NetworkError(101503, error.networkResponse.statusCode, "Cannot get gradebook!")));
|
||||
}
|
||||
}
|
||||
@@ -1,201 +0,0 @@
|
||||
package de.sebse.fuplanner.services.KVV;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.regex.MatchResult;
|
||||
|
||||
import de.sebse.fuplanner.services.KVV.types.Lecturer;
|
||||
import de.sebse.fuplanner.services.KVV.types.Modules;
|
||||
import de.sebse.fuplanner.services.KVV.types.Semester;
|
||||
import de.sebse.fuplanner.tools.NewAsyncQueue;
|
||||
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;
|
||||
|
||||
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 NewAsyncQueue mQueue = new NewAsyncQueue();
|
||||
|
||||
ModulesList(Login login, KVVListener listener, Context context) {
|
||||
super(context);
|
||||
this.mLogin = login;
|
||||
this.mListener = listener;
|
||||
restore();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getUsername() {
|
||||
if (mModules != null) {
|
||||
return mModules.getUsername();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
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.getLoginToken() != null && !mLogin.getLoginToken().isSameUser(mModules.getUsername()))
|
||||
delete();
|
||||
if (retries < 0) {
|
||||
errorCallback.onError(new NetworkError(101107, -1, "Too many retries!"));
|
||||
return;
|
||||
}
|
||||
if (this.mModules != null) {
|
||||
Modules.Module module = this.mModules.get(moduleID);
|
||||
if (module != null) {
|
||||
moduleNetworkCallback.onResponse(module);
|
||||
return;
|
||||
}
|
||||
}
|
||||
recv(success -> find(moduleID, moduleNetworkCallback, errorCallback, retries - 1), errorCallback, true, RETRY_COUNT);
|
||||
}
|
||||
|
||||
void store() {
|
||||
if (this.mModules != null) {
|
||||
try {
|
||||
this.mModules.save(getContext());
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void restore() {
|
||||
try {
|
||||
this.mModules = Modules.load(getContext());
|
||||
} catch (FileNotFoundException ignored) {
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} catch (ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public void delete() {
|
||||
if (this.mModules != null) {
|
||||
this.mModules.delete(getContext());
|
||||
this.mModules = null;
|
||||
}
|
||||
}
|
||||
|
||||
public void recv(final NetworkCallback<Modules> callback, final NetworkErrorCallback errorCallback) {
|
||||
recv(callback, errorCallback, false);
|
||||
}
|
||||
|
||||
public void recv(final NetworkCallback<Modules> callback, final NetworkErrorCallback errorCallback, boolean forceRefresh) {
|
||||
recv(callback, errorCallback, forceRefresh, RETRY_COUNT);
|
||||
}
|
||||
|
||||
private void recv(final NetworkCallback<Modules> callback, final NetworkErrorCallback errorCallback, boolean forceRefresh, final int retries) {
|
||||
if (mModules != null && mLogin.getLoginToken() != null && !mLogin.getLoginToken().isSameUser(mModules.getUsername()))
|
||||
delete();
|
||||
mQueue.add(() -> {
|
||||
if (this.mModules != null && !forceRefresh) {
|
||||
callback.onResponse(this.mModules);
|
||||
mQueue.next();
|
||||
return;
|
||||
}
|
||||
this.upgrade(success -> {
|
||||
if (this.mModules == null)
|
||||
this.mModules = success;
|
||||
else
|
||||
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);
|
||||
mQueue.next();
|
||||
}, error1 -> {
|
||||
errorCallback.onError(error1);
|
||||
mQueue.next();
|
||||
});
|
||||
return;
|
||||
}
|
||||
errorCallback.onError(error);
|
||||
mQueue.next();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private void upgrade(final NetworkCallback<Modules> callback, final NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
|
||||
errorCallback.onError(new NetworkError(101105, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
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(101101, 403, "No module list retrieved!"));
|
||||
return;
|
||||
}
|
||||
Modules modules = new Modules(mLogin.getLoginToken().getUsername());
|
||||
JSONArray sites;
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
sites = json.getJSONArray("site_collection");
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
errorCallback.onError(new NetworkError(101102, 403, "Cannot parse module list!"));
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < sites.length(); i++) {
|
||||
try {
|
||||
JSONObject site = sites.getJSONObject(i);
|
||||
String semester_string = site.getJSONObject("props").optString("term_eid", null);
|
||||
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());
|
||||
}
|
||||
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(new NetworkError(101103, 403, "Cannot parse module list!"));
|
||||
log.e("ID:", i, "JSON:", sites);
|
||||
e.printStackTrace();
|
||||
} catch (NoSuchFieldException e) {
|
||||
log.e(new NetworkError(101106, 403, "Cannot parse module list!"));
|
||||
log.e("ID:", i, "JSON:", sites);
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
// 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,220 +0,0 @@
|
||||
package de.sebse.fuplanner.services.KVV;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Environment;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.util.ArrayList;
|
||||
|
||||
import de.sebse.fuplanner.services.KVV.types.Modules;
|
||||
import de.sebse.fuplanner.services.KVV.types.Resource;
|
||||
import de.sebse.fuplanner.tools.Regex;
|
||||
import de.sebse.fuplanner.tools.network.NetworkCallback;
|
||||
import de.sebse.fuplanner.tools.network.NetworkError;
|
||||
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
|
||||
|
||||
public class ModulesResources extends PartModules<ArrayList<Resource>> {
|
||||
|
||||
ModulesResources(Login login, ModulesList list, Context context) {
|
||||
super(login, list, context);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ArrayList<Resource> getPart(Modules.Module module) {
|
||||
return module.resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean setPart(Modules.Module module, ArrayList<Resource> part) {
|
||||
boolean changed = module.resources == null || module.resources.hashCode() != part.hashCode();
|
||||
module.resources = part;
|
||||
return changed;
|
||||
}
|
||||
|
||||
@Override
|
||||
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("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!"));
|
||||
return;
|
||||
}
|
||||
ArrayList<Resource> resources = new ArrayList<>();
|
||||
JSONArray sites;
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
sites = json.getJSONArray("content_collection");
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
errorCallback.onError(new NetworkError(101602, 403, "Cannot parse resources!"));
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < sites.length(); i++) {
|
||||
try {
|
||||
JSONObject site = sites.getJSONObject(i);
|
||||
String author = site.getString("author");
|
||||
String title = site.getString("title");
|
||||
long modifiedDate = site.getLong("modifiedDate");
|
||||
String url = site.getString("url");
|
||||
boolean visible = site.getBoolean("visible");
|
||||
String type = site.getString("type");
|
||||
String container = site.getString("container");
|
||||
if (type.equals("collection")){
|
||||
resources.add(new Resource.Folder(author, title, modifiedDate, url, visible, container));
|
||||
}
|
||||
else {
|
||||
resources.add(new Resource.File(author, title, modifiedDate, url, visible, container, type));
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
log.e(new NetworkError(101605, 403, "Cannot parse resources!"));
|
||||
e.printStackTrace();
|
||||
log.e("ID:", i, "JSON:", sites);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
ArrayList<Resource> root = new ArrayList<>();
|
||||
// Generate folder structure
|
||||
for (Resource res: resources) {
|
||||
if (!res.getContainer().equals("/content/group/")) {
|
||||
if (res.getContainer().equals("/content/group/"+ID+"/")){
|
||||
// if file in root folder
|
||||
root.add(res);
|
||||
} else {
|
||||
// in sub folder
|
||||
for (Resource res2: resources) {
|
||||
if (res2.getUrl().endsWith(res.getContainer()) && res2 instanceof Resource.Folder) {
|
||||
// Append File/Folder to list
|
||||
((Resource.Folder) res2).add(res);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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!")));
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public void file(final String filename, final String url, final String modulename, final NetworkCallback<String> callback, final NetworkErrorCallback errorCallback, boolean forceRefresh) {
|
||||
file(filename, url, modulename, callback, errorCallback, forceRefresh, RETRY_COUNT);
|
||||
}
|
||||
|
||||
public void file(final String filename, final String url, final String modulename, final NetworkCallback<String> callback, final NetworkErrorCallback errorCallback, boolean forceRefresh, int retries) {
|
||||
if (isExternalStorageReadable()){
|
||||
File f = new File(Environment.getExternalStoragePublicDirectory(
|
||||
Environment.DIRECTORY_DOWNLOADS)+"/"+modulename+"/"+filename);
|
||||
// check if file already downloaded -> do not download again
|
||||
if (f.exists() && !forceRefresh) {
|
||||
callback.onResponse(f.getPath());
|
||||
return;
|
||||
}
|
||||
}
|
||||
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);
|
||||
return;
|
||||
}
|
||||
errorCallback.onError(error);
|
||||
});
|
||||
}
|
||||
|
||||
private void fileUpgrade(String filename, String url, String modulename, final NetworkCallback<String> callback, final NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
|
||||
errorCallback.onError(new NetworkError(101604, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
get(url, mLogin.getLoginToken().getCookies(), response -> {
|
||||
if (Regex.has("\\.[Uu][Rr][Ll]$", url)){
|
||||
// Return redirected URL
|
||||
String path = response.getHeaders().get("Location");
|
||||
if (path == null){
|
||||
path = "";
|
||||
}
|
||||
callback.onResponse(path);
|
||||
} else if (response.getBytes() == null) {
|
||||
errorCallback.onError(new NetworkError(101705, 403, "Cannot get file!"));
|
||||
} else if (isExternalStorageWritable()) {
|
||||
String path = saveFileInDownloads(filename, response.getBytes(), modulename);
|
||||
callback.onResponse(path);
|
||||
} else {
|
||||
errorCallback.onError(new NetworkError(101704, 403, "External storage not writable!"));
|
||||
}
|
||||
}, error -> errorCallback.onError(new NetworkError(101702, error.networkResponse.statusCode, "Cannot get file!")));
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/* Checks if external storage is available for read and write */
|
||||
private boolean isExternalStorageWritable() {
|
||||
String state = Environment.getExternalStorageState();
|
||||
if (Environment.MEDIA_MOUNTED.equals(state)) {
|
||||
return true;
|
||||
}
|
||||
log.w("File system: Writing not possible!");
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Checks if external storage is available to at least read */
|
||||
private boolean isExternalStorageReadable() {
|
||||
String state = Environment.getExternalStorageState();
|
||||
if (Environment.MEDIA_MOUNTED.equals(state) ||
|
||||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
|
||||
return true;
|
||||
}
|
||||
log.w("File system: Reading not possible!");
|
||||
return false;
|
||||
}
|
||||
private String saveFileInDownloads(String filename, byte[] data, String moduleName) {
|
||||
// Saves file in folder: DOWNLOADS/moduleName
|
||||
File folder = new File(Environment.getExternalStoragePublicDirectory(
|
||||
Environment.DIRECTORY_DOWNLOADS), moduleName);
|
||||
if (!folder.mkdir()) {
|
||||
log.w( "Directory not created");
|
||||
}
|
||||
String path = "";
|
||||
try {
|
||||
// TODO check if enough storage space is available
|
||||
FileOutputStream out = new FileOutputStream(folder.getPath()+"/"+filename);
|
||||
out.write(data);
|
||||
out.close();
|
||||
path = folder.getPath()+"/"+filename;
|
||||
} catch (Exception e) {
|
||||
log.w("File not saved!");
|
||||
e.printStackTrace();
|
||||
}
|
||||
return path;
|
||||
}
|
||||
}
|
||||
@@ -1,117 +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 androidx.annotation.Nullable;
|
||||
|
||||
/**
|
||||
* Created by sebastian on 29.10.17.
|
||||
*/
|
||||
|
||||
public class LoginToken implements Serializable {
|
||||
private static final String FILE_NAME = "LoginTokenSaving";
|
||||
|
||||
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 LoginToken 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 LoginToken))
|
||||
return null;
|
||||
LoginToken loginToken = (LoginToken) readObject;
|
||||
is.close();
|
||||
fis.close();
|
||||
return loginToken;
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
public void delete(Context context) {
|
||||
context.deleteFile(FILE_NAME);
|
||||
}
|
||||
|
||||
public void setAdditionals(String fullName, String email) {
|
||||
this.fullName = fullName;
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
private String getShibsessionKey() {
|
||||
return shibsessionKey;
|
||||
}
|
||||
|
||||
private String getShibsessionName() {
|
||||
return shibsessionName;
|
||||
}
|
||||
|
||||
private String getJSESSIONID() {
|
||||
return JSESSIONID;
|
||||
}
|
||||
|
||||
public String getFullName() {
|
||||
return fullName;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public boolean isSameUser(String username) {
|
||||
return this.getUsername().equals(username);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
HashMap<String, String> cookies = this.getCookies();
|
||||
for (String header: cookies.keySet()) {
|
||||
result.append(header).append("=").append(cookies.get(header)).append(";");
|
||||
}
|
||||
return result.substring(0, result.length()-1);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package de.sebse.fuplanner.services.Canteen;
|
||||
package de.sebse.fuplanner.services.canteen;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Build;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
@@ -8,12 +9,11 @@ import org.json.JSONObject;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import de.sebse.fuplanner.MainActivity;
|
||||
import de.sebse.fuplanner.services.Canteen.types.Canteen;
|
||||
import de.sebse.fuplanner.services.Canteen.types.Canteens;
|
||||
import de.sebse.fuplanner.services.Canteen.types.Day;
|
||||
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.MainActivityListener;
|
||||
import de.sebse.fuplanner.tools.network.HTTPService;
|
||||
import de.sebse.fuplanner.tools.network.NetworkCallback;
|
||||
import de.sebse.fuplanner.tools.network.NetworkError;
|
||||
@@ -23,15 +23,15 @@ public class CanteenBrowser extends HTTPService {
|
||||
private Canteens canteens;
|
||||
private final AsyncQueue queue = new AsyncQueue();
|
||||
private final Context context;
|
||||
private MainActivityListener mListener;
|
||||
private CanteenListener mListener;
|
||||
|
||||
public CanteenBrowser(Context context) {
|
||||
super(context);
|
||||
this.context = context;
|
||||
if (context instanceof MainActivityListener)
|
||||
mListener = (MainActivity) context;
|
||||
if (context instanceof CanteenListener)
|
||||
mListener = (CanteenListener) context;
|
||||
else
|
||||
throw new RuntimeException(context.toString() + " must implement MainActivityListener");
|
||||
throw new RuntimeException(context.toString() + " must implement CanteenListener");
|
||||
try {
|
||||
this.canteens = Canteens.load(context);
|
||||
} catch (IOException e) {
|
||||
@@ -65,6 +65,11 @@ public class CanteenBrowser extends HTTPService {
|
||||
}
|
||||
|
||||
private void upgradeCanteens(final NetworkCallback<Canteens> callback, final NetworkErrorCallback errorCallback) {
|
||||
// TSL 1.2 not supported (https://github.com/google/volley/issues/77)
|
||||
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
|
||||
callback.onResponse(new Canteens());
|
||||
return;
|
||||
}
|
||||
get("https://openmensa.org/api/v2/canteens?near[lat]=52.449743&near[lng]=13.282245&near[dist]=7", null, response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
@@ -126,6 +131,11 @@ public class CanteenBrowser extends HTTPService {
|
||||
}
|
||||
|
||||
private void upgradeCanteen(Canteen canteen, final NetworkCallback<Canteen> callback, final NetworkErrorCallback errorCallback) {
|
||||
// TSL 1.2 not supported (https://github.com/google/volley/issues/77)
|
||||
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
|
||||
callback.onResponse(canteen);
|
||||
return;
|
||||
}
|
||||
get(String.format("https://openmensa.org/api/v2/canteens/%s/days", canteen.getId()), null, response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
@@ -173,6 +183,11 @@ public class CanteenBrowser extends HTTPService {
|
||||
}
|
||||
|
||||
private void upgradeDay(Day day, final NetworkCallback<Day> callback, final NetworkErrorCallback errorCallback) {
|
||||
// TSL 1.2 not supported (https://github.com/google/volley/issues/77)
|
||||
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
|
||||
callback.onResponse(day);
|
||||
return;
|
||||
}
|
||||
get(String.format("https://openmensa.org/api/v2/canteens/%s/days/%s/meals/", day.getCanteenId(), Canteen.calendarToKey(day.getCalendar())), null, response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
@@ -206,7 +221,6 @@ public class CanteenBrowser extends HTTPService {
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
log.d(body);
|
||||
errorCallback.onError(new NetworkError(201302, 403, "Cannot parse meal list!"));
|
||||
return;
|
||||
}
|
||||
@@ -225,14 +239,14 @@ public class CanteenBrowser extends HTTPService {
|
||||
private<T> NetworkCallback<T> saveOnCallback(NetworkCallback<T> callback, boolean forceRefresh){
|
||||
return (success -> {
|
||||
if (forceRefresh)
|
||||
mListener.onRefreshCompleted(false);
|
||||
mListener.onCanteenRefreshCompleted(false);
|
||||
callback.onResponse(success);
|
||||
});
|
||||
}
|
||||
|
||||
private NetworkErrorCallback errorOnCallback(NetworkErrorCallback errorCallback){
|
||||
return (error -> {
|
||||
mListener.onRefreshCompleted(true);
|
||||
mListener.onCanteenRefreshCompleted(true);
|
||||
errorCallback.onError(error);
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.sebse.fuplanner.services.Canteen.types;
|
||||
package de.sebse.fuplanner.services.canteen.types;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
@@ -121,6 +121,7 @@ public class Canteen implements Serializable, Iterable<Day> {
|
||||
return lng;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
return id+": "+name+"\n"+list.toString()+"\n";
|
||||
@@ -0,0 +1,5 @@
|
||||
package de.sebse.fuplanner.services.canteen.types;
|
||||
|
||||
public interface CanteenListener {
|
||||
void onCanteenRefreshCompleted(boolean b);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.sebse.fuplanner.services.Canteen.types;
|
||||
package de.sebse.fuplanner.services.canteen.types;
|
||||
|
||||
import android.content.Context;
|
||||
import androidx.annotation.NonNull;
|
||||
@@ -94,6 +94,7 @@ public class Canteens implements Serializable, Iterable<Canteen> {
|
||||
context.deleteFile(FILE_NAME);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.list.toString();
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.sebse.fuplanner.services.Canteen.types;
|
||||
package de.sebse.fuplanner.services.canteen.types;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
@@ -58,6 +58,7 @@ public class Day implements Serializable, Iterable<Meal> {
|
||||
return canteenId;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
return Canteen.calendarToKey(getCalendar())+"\n"+this.list+"\n";
|
||||
@@ -1,10 +1,12 @@
|
||||
package de.sebse.fuplanner.services.Canteen.types;
|
||||
package de.sebse.fuplanner.services.canteen.types;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
public class Meal implements Serializable {
|
||||
private static final int LIGHT_NONE = 0;
|
||||
private static final int LIGHT_GREEN = 1;
|
||||
@@ -112,6 +114,7 @@ public class Meal implements Serializable {
|
||||
return certificates;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
return name + " (" + category + ")";
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.sebse.fuplanner.services.Canteen.types;
|
||||
package de.sebse.fuplanner.services.canteen.types;
|
||||
|
||||
import de.sebse.fuplanner.tools.SortedList;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.sebse.fuplanner.services.Canteen.types;
|
||||
package de.sebse.fuplanner.services.canteen.types;
|
||||
|
||||
import java.util.Calendar;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.sebse.fuplanner.services.Canteen.types;
|
||||
package de.sebse.fuplanner.services.canteen.types;
|
||||
|
||||
import de.sebse.fuplanner.tools.SortedList;
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package de.sebse.fuplanner.services.fulogin;
|
||||
|
||||
public class AccountGeneral {
|
||||
public static final String ACCOUNT_TYPE = "de.sebse.fuplanner.fuauth";
|
||||
public static final String AUTHTOKEN_TYPE_KVV = "KVV";
|
||||
public static final String AUTHTOKEN_TYPE_BLACKBOARD = "Blackboard";
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package de.sebse.fuplanner.services.fulogin;
|
||||
|
||||
import android.accounts.AbstractAccountAuthenticator;
|
||||
import android.accounts.Account;
|
||||
import android.accounts.AccountAuthenticatorResponse;
|
||||
import android.accounts.AccountManager;
|
||||
import android.accounts.NetworkErrorException;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.text.TextUtils;
|
||||
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
public class FUAuthenticator extends AbstractAccountAuthenticator {
|
||||
|
||||
private final Context mContext;
|
||||
|
||||
public FUAuthenticator(Context context) {
|
||||
super(context);
|
||||
this.mContext = context;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Bundle editProperties(AccountAuthenticatorResponse accountAuthenticatorResponse, String s) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@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);
|
||||
intent.putExtra(FUAuthenticatorActivity.ARG_IS_ADDING_NEW_ACCOUNT, true);
|
||||
intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
|
||||
final Bundle bundle = new Bundle();
|
||||
bundle.putParcelable(AccountManager.KEY_INTENT, intent);
|
||||
return bundle;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Bundle confirmCredentials(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, Bundle bundle) throws NetworkErrorException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException {
|
||||
|
||||
// Extract the username and password from the Account Manager, and ask
|
||||
// the server for an appropriate AuthToken.
|
||||
final AccountManager am = AccountManager.get(mContext);
|
||||
|
||||
String authToken = am.peekAuthToken(account, authTokenType);
|
||||
|
||||
// Lets give another try to authenticate the user
|
||||
if (TextUtils.isEmpty(authToken)) {
|
||||
final String password = am.getPassword(account);
|
||||
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 e) {
|
||||
e.printStackTrace();
|
||||
} catch (ExecutionException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we get an authToken - we return it
|
||||
if (!TextUtils.isEmpty(authToken)) {
|
||||
final Bundle result = new Bundle();
|
||||
result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
|
||||
result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
|
||||
result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
|
||||
return result;
|
||||
}
|
||||
|
||||
// If we get here, then we couldn't access the user's password - so we
|
||||
// need to re-prompt them for their credentials. We do that by creating
|
||||
// an intent to display our AuthenticatorActivity.
|
||||
final Intent intent = new Intent(mContext, FUAuthenticatorActivity.class);
|
||||
intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
|
||||
intent.putExtra(FUAuthenticatorActivity.ARG_ACCOUNT_TYPE, account.type);
|
||||
intent.putExtra(FUAuthenticatorActivity.ARG_AUTH_TYPE, authTokenType);
|
||||
final Bundle bundle = new Bundle();
|
||||
bundle.putParcelable(AccountManager.KEY_INTENT, intent);
|
||||
return bundle;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthTokenLabel(String s) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Bundle updateCredentials(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, String s, Bundle bundle) throws NetworkErrorException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Bundle hasFeatures(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, String[] strings) throws NetworkErrorException {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package de.sebse.fuplanner.services.fulogin;
|
||||
|
||||
import android.accounts.Account;
|
||||
import android.accounts.AccountAuthenticatorActivity;
|
||||
import android.accounts.AccountManager;
|
||||
import android.animation.Animator;
|
||||
import android.animation.AnimatorListenerAdapter;
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
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 de.sebse.fuplanner.R;
|
||||
|
||||
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 {
|
||||
/**
|
||||
* 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 View mProgressView;
|
||||
private View mLoginFormView;
|
||||
|
||||
|
||||
|
||||
public static final String ARG_ACCOUNT_TYPE = "ARG_ACCOUNT_TYPE";
|
||||
public static final String ARG_AUTH_TYPE = "ARG_AUTH_TYPE";
|
||||
public static final String ARG_IS_ADDING_NEW_ACCOUNT = "ARG_IS_ADDING_NEW_ACCOUNT";
|
||||
private String mAccountType;
|
||||
private String mAuthTokenType;
|
||||
private boolean mIsAddingNewAccount;
|
||||
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
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);
|
||||
|
||||
mPasswordView = findViewById(R.id.input_password);
|
||||
mPasswordView.setOnEditorActionListener((textView, id, keyEvent) -> {
|
||||
if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
|
||||
attemptLogin();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
Button mEmailSignInButton = findViewById(R.id.btn_login);
|
||||
mEmailSignInButton.setOnClickListener(view -> attemptLogin());
|
||||
|
||||
mLoginFormView = findViewById(R.id.login_form);
|
||||
mProgressView = findViewById(R.id.login_progress);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Attempts to sign in or register the account specified by the login form.
|
||||
* If there are form errors (invalid email, missing fields, etc.), the
|
||||
* errors are presented and no actual login attempt is made.
|
||||
*/
|
||||
private void attemptLogin() {
|
||||
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
|
||||
if (inputManager != null && getCurrentFocus() != null)
|
||||
inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
|
||||
if (mAuthTask != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Reset errors.
|
||||
mEmailView.setError(null);
|
||||
mPasswordView.setError(null);
|
||||
|
||||
// Store values at the time of the login attempt.
|
||||
String email = mEmailView.getText().toString();
|
||||
String password = mPasswordView.getText().toString();
|
||||
|
||||
boolean cancel = false;
|
||||
View focusView = null;
|
||||
|
||||
// Check for a valid password, if the user entered one.
|
||||
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
|
||||
mPasswordView.setError(getString(R.string.error_invalid_password));
|
||||
focusView = mPasswordView;
|
||||
cancel = true;
|
||||
}
|
||||
|
||||
// Check for a valid email address.
|
||||
if (TextUtils.isEmpty(email)) {
|
||||
mEmailView.setError(getString(R.string.error_field_required));
|
||||
focusView = mEmailView;
|
||||
cancel = true;
|
||||
}
|
||||
|
||||
if (cancel) {
|
||||
// There was an error; don't attempt login and focus the first
|
||||
// form field with an error.
|
||||
focusView.requestFocus();
|
||||
} else {
|
||||
// Show a progress spinner, and kick off a background task to
|
||||
// perform the user login attempt.
|
||||
showProgress(true);
|
||||
mAuthTask = new UserLoginTask(email, password, mAuthTokenType, this);
|
||||
mAuthTask.execute((Void) null);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isPasswordValid(String password) {
|
||||
//TODO: Replace this with your own logic
|
||||
return password.length() > 4;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the progress UI and hides the login form.
|
||||
*/
|
||||
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
|
||||
void showProgress(final boolean show) {
|
||||
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
|
||||
// for very easy animations. If available, use these APIs to fade-in
|
||||
// the progress spinner.
|
||||
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
|
||||
|
||||
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
|
||||
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
|
||||
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
|
||||
@Override
|
||||
public void onAnimationEnd(Animator animation) {
|
||||
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
|
||||
}
|
||||
});
|
||||
|
||||
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
|
||||
mProgressView.animate().setDuration(shortAnimTime).alpha(
|
||||
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
|
||||
@Override
|
||||
public void onAnimationEnd(Animator animation) {
|
||||
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
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 (getIntent().getBooleanExtra(ARG_IS_ADDING_NEW_ACCOUNT, false)) {
|
||||
String authtoken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN);
|
||||
String authtokenType = mAuthTokenType;
|
||||
|
||||
// Creating the account on the device and setting the auth token we got
|
||||
// (Not setting the auth token will cause another call to the server to authenticate the user)
|
||||
mAccountManager.addAccountExplicitly(account, accountPassword, null);
|
||||
mAccountManager.setAuthToken(account, authtokenType, authtoken);
|
||||
} else {
|
||||
mAccountManager.setPassword(account, accountPassword);
|
||||
}
|
||||
|
||||
setAccountAuthenticatorResult(intent.getExtras());
|
||||
setResult(RESULT_OK, intent);
|
||||
finish();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package de.sebse.fuplanner.services.fulogin;
|
||||
|
||||
import android.app.Service;
|
||||
import android.content.Intent;
|
||||
import android.os.IBinder;
|
||||
|
||||
public class FUAuthenticatorService extends Service {
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
FUAuthenticator authenticator = new FUAuthenticator(this);
|
||||
return authenticator.getIBinder();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package de.sebse.fuplanner.services.fulogin;
|
||||
|
||||
import android.accounts.AccountManager;
|
||||
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;
|
||||
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
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.tools.logging.Logger;
|
||||
import de.sebse.fuplanner.tools.network.NetworkError;
|
||||
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
|
||||
|
||||
|
||||
/**
|
||||
* Represents an asynchronous login/registration task used to authenticate
|
||||
* the user.
|
||||
*/
|
||||
public class UserLoginTask extends AsyncTask<Void, Void, String> {
|
||||
|
||||
/**
|
||||
* A dummy authentication store containing known user names and passwords.
|
||||
* TODO: remove after connecting to a real authentication system.
|
||||
*/
|
||||
/*private static final String[] DUMMY_CREDENTIALS = new String[]{
|
||||
"foo@example.com:hello", "bar@example.com:world"
|
||||
};*/
|
||||
static final String PARAM_USER_PASS = "PARAM_USER_PASS";
|
||||
|
||||
private final String mUsername;
|
||||
private final String mPassword;
|
||||
private final KVVLogin mKVVLogin;
|
||||
private final BBLogin mBBLogin;
|
||||
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;
|
||||
mPassword = password;
|
||||
mTokenType = tokenType;
|
||||
FULogin mFULogin = new FULogin(context);
|
||||
mKVVLogin = new KVVLogin(context, mFULogin);
|
||||
mBBLogin = new BBLogin(context, mFULogin);
|
||||
if (context instanceof FUAuthenticatorActivity)
|
||||
mActivity = (FUAuthenticatorActivity) context;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String doInBackground(Void... params) {
|
||||
// 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: "+String.valueOf(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;
|
||||
}
|
||||
try {
|
||||
latch.await();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return login.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPostExecute(final String success) {
|
||||
if (mActivity == null || mActivity.isFinishing())
|
||||
return;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mActivity.isDestroyed())
|
||||
return;
|
||||
mActivity.mAuthTask = null;
|
||||
mActivity.showProgress(false);
|
||||
|
||||
if (success != null && !success.startsWith("Error: ")) {
|
||||
final Intent res = new Intent();
|
||||
res.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
|
||||
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"))) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCancelled() {
|
||||
if (mActivity == null || mActivity.isFinishing())
|
||||
return;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mActivity.isDestroyed())
|
||||
return;
|
||||
mActivity.mAuthTask = null;
|
||||
mActivity.showProgress(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package de.sebse.fuplanner.services.kvv;
|
||||
|
||||
public class Constants {
|
||||
public static final String KVV_SERVER_URL = "https://mycampus.imp.fu-berlin.de/";
|
||||
}
|
||||
120
app/src/main/java/de/sebse/fuplanner/services/kvv/KVV.java
Normal file
120
app/src/main/java/de/sebse/fuplanner/services/kvv/KVV.java
Normal file
@@ -0,0 +1,120 @@
|
||||
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 org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import de.sebse.fuplanner.services.kvv.types.LoginTokenBB;
|
||||
import de.sebse.fuplanner.services.kvv.types.LoginTokenKVV;
|
||||
import de.sebse.fuplanner.tools.CustomAccountManager;
|
||||
|
||||
public class KVV extends Service {
|
||||
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;
|
||||
|
||||
@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(LoginTokenKVV 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();
|
||||
|
||||
@NotNull
|
||||
public Login account() {
|
||||
return (Login) addAndGet("account", () -> new Login(mListener, getApplicationContext()));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Modules modules() {
|
||||
return (Modules) addAndGet("module", () -> new Modules(account(), mListener, getApplicationContext()));
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@NotNull
|
||||
private Object addAndGet(@NotNull String addon, @NotNull ModuleCreatorInterface creatorInterface) {
|
||||
Object o = addons.get(addon);
|
||||
if (o == null) {
|
||||
o = creatorInterface.create();
|
||||
addons.put(addon, o);
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
private interface ModuleCreatorInterface {
|
||||
@NotNull Object create();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package de.sebse.fuplanner.services.kvv;
|
||||
|
||||
import com.android.volley.NetworkResponse;
|
||||
|
||||
import de.sebse.fuplanner.services.kvv.types.LoginTokenBB;
|
||||
import de.sebse.fuplanner.services.kvv.types.LoginTokenKVV;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
import de.sebse.fuplanner.tools.CustomAccountManager;
|
||||
|
||||
public interface KVVListener {
|
||||
default void onLogin(LoginTokenKVV tokenKVV, LoginTokenBB tokenBB, boolean isOnlyRefresh) {}
|
||||
|
||||
default void onLogout() {}
|
||||
|
||||
default void onModuleListChange() {}
|
||||
|
||||
default void onModuleListPartiallyUpdated(Modules modules) {}
|
||||
|
||||
default void onKVVNetworkResponse(NetworkResponse error) {}
|
||||
|
||||
CustomAccountManager getAccountManager();
|
||||
}
|
||||
192
app/src/main/java/de/sebse/fuplanner/services/kvv/Login.java
Normal file
192
app/src/main/java/de/sebse/fuplanner/services/kvv/Login.java
Normal file
@@ -0,0 +1,192 @@
|
||||
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.fulogin.AccountGeneral;
|
||||
import de.sebse.fuplanner.services.kvv.sync.BBLogin;
|
||||
import de.sebse.fuplanner.services.kvv.sync.FULogin;
|
||||
import de.sebse.fuplanner.services.kvv.sync.KVVLogin;
|
||||
import de.sebse.fuplanner.services.kvv.types.LoginTokenBB;
|
||||
import de.sebse.fuplanner.services.kvv.types.LoginTokenKVV;
|
||||
import de.sebse.fuplanner.tools.CustomAccountManager;
|
||||
import de.sebse.fuplanner.tools.NetworkCallbackCollector;
|
||||
import de.sebse.fuplanner.tools.Preferences;
|
||||
import de.sebse.fuplanner.tools.network.HTTPService;
|
||||
import de.sebse.fuplanner.tools.network.NetworkCallback;
|
||||
import de.sebse.fuplanner.tools.network.NetworkError;
|
||||
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
|
||||
|
||||
public class Login extends HTTPService {
|
||||
public 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;
|
||||
|
||||
private final KVVListener mListener;
|
||||
@Nullable private LoginTokenKVV mTokenKVV;
|
||||
@Nullable private LoginTokenBB mTokenBB;
|
||||
private boolean mLoginPending = false;
|
||||
private final NetworkCallbackCollector<Pair<LoginTokenKVV, LoginTokenBB>> mRefreshCallbacks = new NetworkCallbackCollector<>();
|
||||
private final NetworkCallbackCollector<Integer> mRestoreCallbacks = new NetworkCallbackCollector<>();
|
||||
|
||||
Login(KVVListener listener, Context context) {
|
||||
super(context);
|
||||
this.mListener = listener;
|
||||
}
|
||||
|
||||
public void restoreOnlineLogin(IntegerInterface callback) {
|
||||
mRestoreCallbacks.add(new Pair<>(callback::run, null));
|
||||
if (mLoginPending) {
|
||||
return;
|
||||
}
|
||||
mLoginPending = true;
|
||||
LoginTokenKVV.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 -> {
|
||||
mLoginPending = false;
|
||||
mRestoreCallbacks.responseResponse(RESTORE_STATUS_ERROR);
|
||||
});
|
||||
}
|
||||
|
||||
public void isOfflineStoredAvailable(BooleanInterface callback) {
|
||||
LoginTokenKVV.load(mListener.getAccountManager(), tokenKVV -> {
|
||||
LoginTokenBB.load(mListener.getAccountManager(), tokenBB -> {
|
||||
callback.run(tokenKVV != null && tokenBB != null);
|
||||
}, e -> callback.run(false));
|
||||
}, e -> callback.run(false));
|
||||
}
|
||||
|
||||
public boolean logout(boolean delete) {
|
||||
if (mLoginPending)
|
||||
return false;
|
||||
if (mTokenKVV == null || mTokenBB == 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);
|
||||
}
|
||||
|
||||
public boolean isLoginPending() {
|
||||
return mLoginPending;
|
||||
}
|
||||
|
||||
public boolean isLoggedIn() {
|
||||
return mTokenKVV != null && mTokenBB != null;
|
||||
}
|
||||
|
||||
public boolean isInOnlineMode() {
|
||||
return isLoggedIn();
|
||||
}
|
||||
|
||||
void testLoginToken(@NotNull NetworkCallback<Pair<LoginTokenKVV, LoginTokenBB>> callback, @NotNull NetworkErrorCallback errorCallback) {
|
||||
if (mTokenKVV == 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);
|
||||
}
|
||||
|
||||
private void testLoginToken(@NotNull LoginTokenKVV tokenKVV, @NotNull LoginTokenBB tokenBB, @NotNull NetworkCallback<Pair<LoginTokenKVV, LoginTokenBB>> callback, @NotNull NetworkErrorCallback errorCallback) {
|
||||
FULogin mFULogin = new FULogin(getContext());
|
||||
new KVVLogin(getContext(), mFULogin).testLoginToken(tokenKVV, tokenKVV1 -> {
|
||||
new BBLogin(getContext(), mFULogin).testLoginToken(tokenBB, tokenBB1 -> {
|
||||
callback.onResponse(new Pair<>(tokenKVV1, tokenBB1));
|
||||
}, errorCallback);
|
||||
}, errorCallback);
|
||||
}
|
||||
|
||||
@Nullable public LoginTokenKVV getLoginTokenKVV() {
|
||||
return mTokenKVV;
|
||||
}
|
||||
|
||||
@Nullable public LoginTokenBB getLoginTokenBB() {
|
||||
return mTokenBB;
|
||||
}
|
||||
|
||||
void refreshLogin(NetworkCallback<Pair<LoginTokenKVV, LoginTokenBB>> success, NetworkErrorCallback error, int flags) {
|
||||
boolean isFirst = mRefreshCallbacks.isEmpty();
|
||||
mRefreshCallbacks.add(success, error);
|
||||
if (!isFirst)
|
||||
return;
|
||||
refreshLoginRunner(success, error, flags);
|
||||
}
|
||||
|
||||
private void refreshLoginRunner(NetworkCallback<Pair<LoginTokenKVV, LoginTokenBB>> success, NetworkErrorCallback error, int flags) {
|
||||
CustomAccountManager manager = mListener.getAccountManager();
|
||||
if ((flags & LOGOUT_KVV) == LOGOUT_KVV) {
|
||||
manager.doInvalidateToken(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV, ignored -> {
|
||||
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)
|
||||
testLoginToken(mRefreshCallbacks::responseResponse, mRefreshCallbacks::responseError);
|
||||
else if (restoreResult == RESTORE_STATUS_INVALID_PASSWORD) {
|
||||
logout(true);
|
||||
mRefreshCallbacks.responseError(new NetworkError(100180, 403, "Re-login failed (password)!"));
|
||||
} else {
|
||||
mRefreshCallbacks.responseError(new NetworkError(100181, 403, "Re-login failed (error)!"));
|
||||
}
|
||||
});
|
||||
} else {
|
||||
throw new IllegalArgumentException("Invalid flag in refreshLoginRunner: "+flags);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
private boolean handleCallbacks(boolean isOnlyRefresh) {
|
||||
if (mTokenKVV != null || mTokenBB != null) {
|
||||
mListener.onLogin(mTokenKVV, mTokenBB, isOnlyRefresh);
|
||||
return true;
|
||||
} else {
|
||||
mListener.onLogout();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean setToken(@Nullable LoginTokenKVV tokenKVV, @Nullable LoginTokenBB tokenBB) {
|
||||
if (tokenKVV == null || tokenBB == null)
|
||||
return false;
|
||||
boolean isOnlyRefresh = mTokenKVV != null;
|
||||
mTokenKVV = tokenKVV;
|
||||
mTokenBB = tokenBB;
|
||||
return isOnlyRefresh || handleCallbacks(isOnlyRefresh);
|
||||
}
|
||||
|
||||
public interface BooleanInterface {
|
||||
void run(boolean bool);
|
||||
}
|
||||
|
||||
public interface IntegerInterface {
|
||||
void run(int integer);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
package de.sebse.fuplanner.services.KVV;
|
||||
package de.sebse.fuplanner.services.kvv;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import com.android.volley.NetworkResponse;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.HashMap;
|
||||
@@ -10,7 +12,7 @@ public class Modules {
|
||||
private final HashMap<String, Part> mAddons = new HashMap<>();
|
||||
private ModulesList mList = null;
|
||||
private final Login mLogin;
|
||||
private KVVListener mListener;
|
||||
private final KVVListener mListener;
|
||||
private final Context context;
|
||||
|
||||
Modules(Login login, KVVListener listener, Context context) {
|
||||
@@ -56,7 +58,13 @@ public class Modules {
|
||||
public ModulesList list() {
|
||||
if (mList == null) {
|
||||
mList = new ModulesList(mLogin, mListener, context);
|
||||
mList.addErrorListener("Modules", error -> mListener.onKVVNetworkResponse(error.networkResponse));
|
||||
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.addSuccessListener("Modules", success -> mListener.onKVVNetworkResponse(null));
|
||||
}
|
||||
return mList;
|
||||
@@ -68,7 +76,13 @@ public class Modules {
|
||||
Part o = mAddons.get(addon);
|
||||
if (o == null) {
|
||||
o = creatorInterface.create();
|
||||
o.addErrorListener("Modules", error -> mListener.onKVVNetworkResponse(error.networkResponse));
|
||||
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.addSuccessListener("Modules", success -> mListener.onKVVNetworkResponse(null));
|
||||
mAddons.put(addon, o);
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package de.sebse.fuplanner.services.kvv;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
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;
|
||||
|
||||
public class ModulesAnnouncements extends PartModules<ArrayList<Announcement>> {
|
||||
|
||||
ModulesAnnouncements(Login login, ModulesList list, Context context) {
|
||||
super(login, list, context);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ArrayList<Announcement> getPart(Modules.Module module) {
|
||||
return module.announcements;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean setPart(Modules.Module module, ArrayList<Announcement> part) {
|
||||
boolean changed = module.announcements == null || module.announcements.hashCode() != part.hashCode();
|
||||
module.announcements = part;
|
||||
return changed;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void upgradeKVV(final String ID, final NetworkCallback<ArrayList<Announcement>> callback, final NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenKVV() == null || !mLogin.getLoginTokenKVV().isAvailable()) {
|
||||
errorCallback.onError(new NetworkError(101204, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
super.get(String.format(Constants.KVV_SERVER_URL+"direct/announcement/site/%s.json?n=999999&d=999999999&_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(101201, 403, "No announcements retrieved!"));
|
||||
return;
|
||||
}
|
||||
ArrayList<Announcement> announcements = new ArrayList<>();
|
||||
JSONArray sites;
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
sites = json.getJSONArray("announcement_collection");
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
errorCallback.onError(new NetworkError(101202, 403, "Cannot parse announcements!"));
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < sites.length(); i++) {
|
||||
try {
|
||||
JSONObject site = sites.getJSONObject(i);
|
||||
String id = site.getString("announcementId");
|
||||
String title = site.getString("title");
|
||||
String text = site.getString("body");
|
||||
text = String.valueOf(fromHtml(text));
|
||||
String createdBy = site.getString("createdByDisplayName");
|
||||
long createdOn = site.getLong("createdOn");
|
||||
|
||||
// Extract attachment links
|
||||
JSONArray attachments = site.getJSONArray("attachments");
|
||||
ArrayList<String> urls = new ArrayList<>();
|
||||
for (int j = 0; j < attachments.length(); j++) {
|
||||
urls.add(attachments.getJSONObject(j).optString("url", null));
|
||||
}
|
||||
|
||||
announcements.add(new Announcement(id, title, text, createdBy, createdOn, urls));
|
||||
} catch (JSONException e) {
|
||||
log.e(new NetworkError(101205, 403, "Cannot parse announcements!"));
|
||||
log.e("ID:", i, "JSON:", sites);
|
||||
e.printStackTrace();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
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!"));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.sebse.fuplanner.services.KVV;
|
||||
package de.sebse.fuplanner.services.kvv;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
@@ -8,9 +8,9 @@ import org.json.JSONObject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import de.sebse.fuplanner.services.KVV.types.Assignment;
|
||||
import de.sebse.fuplanner.services.KVV.types.AssignmentList;
|
||||
import de.sebse.fuplanner.services.KVV.types.Modules;
|
||||
import de.sebse.fuplanner.services.kvv.types.Assignment;
|
||||
import de.sebse.fuplanner.services.kvv.types.AssignmentList;
|
||||
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;
|
||||
@@ -34,12 +34,12 @@ public class ModulesAssignments extends PartModules<AssignmentList> {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void upgrade(final String ID, final NetworkCallback<AssignmentList> callback, final NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginToken() == null) {
|
||||
protected void upgradeKVV(final String ID, final NetworkCallback<AssignmentList> callback, final NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenKVV() == null || !mLogin.getLoginTokenKVV().isAvailable()) {
|
||||
errorCallback.onError(new NetworkError(101304, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
get(String.format("https://kvv.imp.fu-berlin.de/direct/assignment/site/%s.json", ID), mLogin.getLoginToken().getCookies(), response -> {
|
||||
get(String.format(Constants.KVV_SERVER_URL+"direct/assignment/site/%s.json?_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(101301, 403, "No assignments retrieved!"));
|
||||
@@ -80,11 +80,12 @@ public class ModulesAssignments extends PartModules<AssignmentList> {
|
||||
}
|
||||
}
|
||||
|
||||
// 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,11 +1,11 @@
|
||||
package de.sebse.fuplanner.services.KVV;
|
||||
package de.sebse.fuplanner.services.kvv;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.Pair;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import de.sebse.fuplanner.services.KVV.types.Modules;
|
||||
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;
|
||||
@@ -0,0 +1,188 @@
|
||||
package de.sebse.fuplanner.services.kvv;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Build;
|
||||
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);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected EventList getPart(Modules.Module module) {
|
||||
return module.events;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean setPart(Modules.Module module, EventList part) {
|
||||
boolean changed = module.events == null || module.events.hashCode() != part.hashCode();
|
||||
module.events = part;
|
||||
return changed;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void upgradeKVV(final String ID, final NetworkCallback<EventList> callback, final NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenKVV() == null || !mLogin.getLoginTokenKVV().isAvailable()) {
|
||||
errorCallback.onError(new NetworkError(101404, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
get(String.format(Constants.KVV_SERVER_URL+"direct/calendar/site/%s.json?detailed=true&_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(101401, 403, "No events retrieved!"));
|
||||
return;
|
||||
}
|
||||
EventList events = new EventList();
|
||||
JSONArray sites;
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
sites = json.getJSONArray("calendar_collection");
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
errorCallback.onError(new NetworkError(101402, 403, "Cannot parse events!"));
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < sites.length(); i++) {
|
||||
try {
|
||||
JSONObject site = sites.getJSONObject(i);
|
||||
String id = site.getString("eventId");
|
||||
String type = site.getString("type");
|
||||
String title = site.getString("title");
|
||||
String siteId = site.getString("siteId");
|
||||
long duration = site.getLong("duration");
|
||||
long firstTime = site.getJSONObject("firstTime").getLong("time");
|
||||
String location = site.getString("location");
|
||||
events.add(new Event(id, type, title, duration, firstTime, siteId, location));
|
||||
} catch (JSONException e) {
|
||||
log.e(new NetworkError(101405, 403, "Cannot parse events!"));
|
||||
e.printStackTrace();
|
||||
log.e("ID:", i, "JSON:", sites);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
// TSL 1.2 not supported (https://github.com/google/volley/issues/77)
|
||||
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
|
||||
callback.onResponse(new EventList());
|
||||
return;
|
||||
}
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenBB() == null || !mLogin.getLoginTokenBB().isAvailable()) {
|
||||
errorCallback.onError(new NetworkError(101414, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
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)];
|
||||
//log.d("LAAAAAAST", vvNumber);
|
||||
//vvNumber = "462126";
|
||||
super.get(String.format("https://www.fu-berlin.de/vv/de/lv/%s", vvNumber), null, response1 -> {
|
||||
String body = response1.getParsed();
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package de.sebse.fuplanner.services.kvv;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
|
||||
import de.sebse.fuplanner.services.kvv.types.CacheBBEventNumber;
|
||||
import de.sebse.fuplanner.services.kvv.types.CacheLecturer;
|
||||
import de.sebse.fuplanner.services.kvv.types.Lecturer;
|
||||
import de.sebse.fuplanner.tools.Regex;
|
||||
import de.sebse.fuplanner.tools.network.HTTPService;
|
||||
import de.sebse.fuplanner.tools.network.NetworkCallback;
|
||||
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 e) {
|
||||
e.printStackTrace();
|
||||
} catch (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!")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package de.sebse.fuplanner.services.kvv;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
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.Modules;
|
||||
import de.sebse.fuplanner.tools.network.NetworkCallback;
|
||||
import de.sebse.fuplanner.tools.network.NetworkError;
|
||||
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
|
||||
|
||||
public class ModulesGradebook extends PartModules<ArrayList<Grade>> {
|
||||
|
||||
ModulesGradebook(Login login, ModulesList list, Context context) {
|
||||
super(login, list, context);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ArrayList<Grade> getPart(Modules.Module module) {
|
||||
return module.gradebook;
|
||||
}
|
||||
|
||||
@Override
|
||||
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<ArrayList<Grade>> callback, final NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenKVV() == null || !mLogin.getLoginTokenKVV().isAvailable()) {
|
||||
errorCallback.onError(new NetworkError(101504, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
super.get(String.format(Constants.KVV_SERVER_URL+"direct/gradebook/site/%s.json", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(101501, 403, "No gradebook retrieved!"));
|
||||
return;
|
||||
}
|
||||
ArrayList<Grade> gradebook = new ArrayList<>();
|
||||
JSONArray sites;
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
sites = json.getJSONArray("assignments");
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
errorCallback.onError(new NetworkError(101502, 403, "Cannot parse gradebook!"));
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < sites.length(); i++) {
|
||||
try {
|
||||
JSONObject site = sites.getJSONObject(i);
|
||||
double grade = site.optDouble("grade", 0);
|
||||
String itemName = site.optString("itemName", null);
|
||||
double maxPoints = site.optDouble("points", -1);
|
||||
|
||||
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);
|
||||
e.printStackTrace();
|
||||
return;
|
||||
}
|
||||
}
|
||||
callback.onResponse(gradebook);
|
||||
}, error -> {
|
||||
if (error.networkResponse.statusCode == 400)
|
||||
callback.onResponse(new ArrayList<>());
|
||||
else
|
||||
errorCallback.onError(new NetworkError(101503, error.networkResponse.statusCode, "Cannot get gradebook!"));
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void upgradeBB(String ID, NetworkCallback<ArrayList<Grade>> 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;
|
||||
}
|
||||
|
||||
ArrayList<Grade> result = new ArrayList<>();
|
||||
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.add(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 ArrayList<>());
|
||||
else
|
||||
errorCallback.onError(new NetworkError(101517, error.networkResponse.statusCode, "Cannot get gradebook entries!"));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,457 @@
|
||||
package de.sebse.fuplanner.services.kvv;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
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;
|
||||
import de.sebse.fuplanner.tools.NewAsyncQueue;
|
||||
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;
|
||||
|
||||
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);
|
||||
this.mLogin = login;
|
||||
this.mListener = listener;
|
||||
restore();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getUsername() {
|
||||
if (mModules != null) {
|
||||
return mModules.getUsername();
|
||||
}
|
||||
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())
|
||||
)
|
||||
delete();
|
||||
if (retries < 0) {
|
||||
log.t("Too many retires", retries);
|
||||
errorCallback.onError(new NetworkError(101107, -1, "Too many retries!"));
|
||||
return;
|
||||
}
|
||||
if (this.mModules != null) {
|
||||
Modules.Module module = this.mModules.get(moduleID);
|
||||
if (module != null) {
|
||||
moduleNetworkCallback.onResponse(module);
|
||||
return;
|
||||
}
|
||||
}
|
||||
recv(success -> find(moduleID, moduleNetworkCallback, errorCallback, retries - 1), errorCallback, true, RETRY_COUNT);
|
||||
}
|
||||
|
||||
void store() {
|
||||
if (this.mModules != null) {
|
||||
try {
|
||||
this.mModules.save(getContext());
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void restore() {
|
||||
try {
|
||||
this.mModules = Modules.load(getContext());
|
||||
} catch (FileNotFoundException ignored) {
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} catch (ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
if (this.mModules == null) {
|
||||
recv(success -> {}, log::e);
|
||||
}
|
||||
}
|
||||
|
||||
public void delete() {
|
||||
if (this.mModules != null) {
|
||||
this.mModules.delete(getContext());
|
||||
this.mModules = null;
|
||||
}
|
||||
}
|
||||
|
||||
public void recv(final NetworkCallback<Modules> callback, final NetworkErrorCallback errorCallback) {
|
||||
recv(callback, errorCallback, false);
|
||||
}
|
||||
|
||||
public void recv(final NetworkCallback<Modules> callback, final NetworkErrorCallback errorCallback, boolean forceRefresh) {
|
||||
recv(callback, errorCallback, forceRefresh, RETRY_COUNT);
|
||||
}
|
||||
|
||||
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())
|
||||
)
|
||||
delete();
|
||||
mQueue.add(() -> {
|
||||
if (mLogin.isLoginPending()) {
|
||||
mLogin.restoreOnlineLogin(resCode -> {
|
||||
mQueue.next();
|
||||
});
|
||||
} else {
|
||||
mQueue.next();
|
||||
}
|
||||
});
|
||||
mQueue.add(() -> {
|
||||
if (this.mModules != null && !forceRefresh) {
|
||||
callback.onResponse(this.mModules);
|
||||
mQueue.next();
|
||||
return;
|
||||
}
|
||||
Function<Integer, NetworkErrorCallback> errorFunc = ((Integer errorCode) -> (error -> {
|
||||
if (retries > 0 && (error.getHttpStatus() == 401 || error.getHttpStatus() == 403)) {
|
||||
mLogin.refreshLogin(success -> {
|
||||
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!"));
|
||||
return;
|
||||
}
|
||||
Modules modules = new Modules(mLogin.getLoginTokenKVV().getUsername());
|
||||
if (!mLogin.getLoginTokenKVV().isAvailable()) {
|
||||
callback.onResponse(modules);
|
||||
return;
|
||||
}
|
||||
get(Constants.KVV_SERVER_URL+"direct/membership.json?_validateSession=", mLogin.getLoginTokenKVV().getCookies(), response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(101111, 403, "No membership list retrieved!"));
|
||||
return;
|
||||
}
|
||||
JSONArray memberships;
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
memberships = json.getJSONArray("membership_collection");
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
errorCallback.onError(new NetworkError(101112, 403, "Cannot parse membership list!"));
|
||||
return;
|
||||
}
|
||||
final int[] latch = {memberships.length()};
|
||||
if (latch[0] == 0) {
|
||||
successCallback.onResponse(modules);
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < memberships.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);
|
||||
continue;
|
||||
}
|
||||
get(String.format(Constants.KVV_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!")));
|
||||
} catch (JSONException e) {
|
||||
log.e("ID:", i, "JSON:", memberships);
|
||||
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]);
|
||||
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 e) {
|
||||
e.printStackTrace();
|
||||
} catch (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 e) {
|
||||
e.printStackTrace();
|
||||
} catch (ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
if (mKVVCache == null)
|
||||
mKVVCache = new CacheKVVCourse();
|
||||
return mKVVCache;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
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 e) {
|
||||
e.printStackTrace();
|
||||
} catch (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!")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
package de.sebse.fuplanner.services.kvv;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Build;
|
||||
import android.os.Environment;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
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;
|
||||
import de.sebse.fuplanner.services.kvv.types.Resource;
|
||||
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 ModulesResources extends PartModules<ArrayList<Resource>> {
|
||||
|
||||
ModulesResources(Login login, ModulesList list, Context context) {
|
||||
super(login, list, context);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ArrayList<Resource> getPart(Modules.Module module) {
|
||||
return module.resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean setPart(Modules.Module module, ArrayList<Resource> part) {
|
||||
boolean changed = module.resources == null || module.resources.hashCode() != part.hashCode();
|
||||
module.resources = part;
|
||||
return changed;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void upgradeKVV(final String ID, final NetworkCallback<ArrayList<Resource>> callback, final NetworkErrorCallback errorCallback) {
|
||||
if (!mLogin.isInOnlineMode() || mLogin.getLoginTokenKVV() == null || !mLogin.getLoginTokenKVV().isAvailable()) {
|
||||
errorCallback.onError(new NetworkError(101604, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
get(String.format(Constants.KVV_SERVER_URL+"direct/content/site/%s.json?_validateSession=", ID), mLogin.getLoginTokenKVV().getCookies(), response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(101601, 403, "No resources retrieved!"));
|
||||
return;
|
||||
}
|
||||
ArrayList<Resource> resources = new ArrayList<>();
|
||||
JSONArray sites;
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
sites = json.getJSONArray("content_collection");
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
errorCallback.onError(new NetworkError(101602, 403, "Cannot parse resources!"));
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < sites.length(); i++) {
|
||||
try {
|
||||
JSONObject site = sites.getJSONObject(i);
|
||||
String author = site.getString("author");
|
||||
String title = site.getString("title");
|
||||
//long modifiedDate = site.getLong("modifiedDate");"20181018155405439"
|
||||
long modifiedDate = UtilsDate.stringToMillis(site.getString("modifiedDate"), "yyyyMMddHHmmssSSS");
|
||||
String url = site.getString("url");
|
||||
boolean visible = site.getBoolean("visible");
|
||||
String type = site.getString("type");
|
||||
String container = site.getString("container");
|
||||
if (type.equals("collection")){
|
||||
resources.add(new Resource.Folder(author, title, modifiedDate, url, visible, container));
|
||||
}
|
||||
else {
|
||||
resources.add(new Resource.File(author, title, modifiedDate, url, visible, container, type));
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
log.e(new NetworkError(101605, 403, "Cannot parse resources!"));
|
||||
e.printStackTrace();
|
||||
log.e("ID:", i, "JSON:", sites);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
ArrayList<Resource> root = new ArrayList<>();
|
||||
// Generate folder structure
|
||||
for (Resource res: resources) {
|
||||
if (!res.getContainer().equals("/content/group/")) {
|
||||
if (res.getContainer().equals("/content/group/"+ID+"/")){
|
||||
// if file in root folder
|
||||
root.add(res);
|
||||
} else {
|
||||
// in sub folder
|
||||
for (Resource res2: resources) {
|
||||
try {
|
||||
String utf8Name;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
|
||||
utf8Name = StandardCharsets.UTF_8.name();
|
||||
else utf8Name = "UTF-8";
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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<>());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public void file(final String filename, final String url, final String modulename, final NetworkCallback<String> callback, final NetworkErrorCallback errorCallback, boolean forceRefresh) {
|
||||
file(filename, url, modulename, callback, errorCallback, forceRefresh, RETRY_COUNT);
|
||||
}
|
||||
|
||||
private void file(final String filename, final String url, final String modulename, final NetworkCallback<String> callback, final NetworkErrorCallback errorCallback, boolean forceRefresh, int retries) {
|
||||
if (isExternalStorageReadable()){
|
||||
File f = new File(Environment.getExternalStoragePublicDirectory(
|
||||
Environment.DIRECTORY_DOWNLOADS)+"/"+modulename+"/"+filename);
|
||||
// check if file already downloaded -> do not download again
|
||||
if (f.exists() && !forceRefresh) {
|
||||
callback.onResponse(f.getPath());
|
||||
return;
|
||||
}
|
||||
}
|
||||
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);
|
||||
return;
|
||||
}
|
||||
errorCallback.onError(error);
|
||||
});
|
||||
}
|
||||
|
||||
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()) {
|
||||
errorCallback.onError(new NetworkError(101604, 500, "Currently running in offline mode!"));
|
||||
return;
|
||||
}
|
||||
get(url, mLogin.getLoginTokenKVV().getCookies(), response -> {
|
||||
if (Regex.has("\\.[Uu][Rr][Ll]$", url)){
|
||||
// Return redirected URL
|
||||
String path = response.getHeaders().get("Location");
|
||||
if (path == null){
|
||||
path = "";
|
||||
}
|
||||
callback.onResponse(path);
|
||||
} else if (response.getBytes() == null) {
|
||||
errorCallback.onError(new NetworkError(101705, 403, "Cannot get file!"));
|
||||
} else if (isExternalStorageWritable()) {
|
||||
String path = saveFileInDownloads(filename, response.getBytes(), modulename);
|
||||
callback.onResponse(path);
|
||||
} else {
|
||||
errorCallback.onError(new NetworkError(101704, 400, "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!")));
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/* Checks if external storage is available for read and write */
|
||||
private boolean isExternalStorageWritable() {
|
||||
String state = Environment.getExternalStorageState();
|
||||
if (Environment.MEDIA_MOUNTED.equals(state)) {
|
||||
return true;
|
||||
}
|
||||
log.w("File system: Writing not possible!");
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Checks if external storage is available to at least read */
|
||||
private boolean isExternalStorageReadable() {
|
||||
String state = Environment.getExternalStorageState();
|
||||
if (Environment.MEDIA_MOUNTED.equals(state) ||
|
||||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
|
||||
return true;
|
||||
}
|
||||
log.w("File system: Reading not possible!");
|
||||
return false;
|
||||
}
|
||||
private String saveFileInDownloads(String filename, byte[] data, String moduleName) {
|
||||
// Saves file in folder: DOWNLOADS/moduleName
|
||||
File folder = new File(Environment.getExternalStoragePublicDirectory(
|
||||
Environment.DIRECTORY_DOWNLOADS), moduleName);
|
||||
if (!folder.mkdirs()) {
|
||||
log.w( "Directory not created");
|
||||
}
|
||||
String path = "";
|
||||
try {
|
||||
// TODO check if enough storage space is available
|
||||
FileOutputStream out = new FileOutputStream(folder.getPath()+"/"+filename);
|
||||
out.write(data);
|
||||
out.close();
|
||||
path = folder.getPath()+"/"+filename;
|
||||
} catch (Exception e) {
|
||||
log.w("File not saved!");
|
||||
e.printStackTrace();
|
||||
}
|
||||
return path;
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,16 @@
|
||||
package de.sebse.fuplanner.services.KVV;
|
||||
package de.sebse.fuplanner.services.kvv;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import de.sebse.fuplanner.services.KVV.types.Modules;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
import de.sebse.fuplanner.tools.network.HTTPService;
|
||||
import de.sebse.fuplanner.tools.network.NetworkCallback;
|
||||
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
|
||||
|
||||
public abstract class Part<T> extends HTTPService {
|
||||
static final int RETRY_COUNT = 1;
|
||||
protected final Login mLogin;
|
||||
protected final ModulesList mList;
|
||||
final Login mLogin;
|
||||
final ModulesList mList;
|
||||
|
||||
Part(Login login, ModulesList list, Context context) {
|
||||
super(context);
|
||||
@@ -1,17 +1,17 @@
|
||||
package de.sebse.fuplanner.services.KVV;
|
||||
package de.sebse.fuplanner.services.kvv;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Build;
|
||||
import android.text.Html;
|
||||
import android.text.Spanned;
|
||||
|
||||
import de.sebse.fuplanner.services.KVV.types.Modules;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
import de.sebse.fuplanner.tools.NewAsyncQueue;
|
||||
import de.sebse.fuplanner.tools.network.NetworkCallback;
|
||||
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
|
||||
|
||||
abstract class PartModules<T> extends Part<Modules.Module> {
|
||||
private NewAsyncQueue mQueue = new NewAsyncQueue();
|
||||
private final NewAsyncQueue mQueue = new NewAsyncQueue();
|
||||
|
||||
PartModules(Login login, ModulesList list, Context context) {
|
||||
super(login, list, context);
|
||||
@@ -19,13 +19,22 @@ 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) {
|
||||
mQueue.add(() -> {
|
||||
if (mLogin.isLoginPending()) {
|
||||
mLogin.restoreOnlineLogin(resCode -> {
|
||||
mQueue.next();
|
||||
});
|
||||
} else {
|
||||
mQueue.next();
|
||||
}
|
||||
});
|
||||
mQueue.add(() -> {
|
||||
if (getPart(module) != null && !forceRefresh) {
|
||||
callback.onResponse(module);
|
||||
mQueue.next();
|
||||
return;
|
||||
}
|
||||
upgrade(module.getID(), success -> {
|
||||
upgrade(module.getModuleType(), module.getID(), success -> {
|
||||
if (setPart(module, success)) {
|
||||
this.mList.store();
|
||||
}
|
||||
@@ -39,7 +48,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);
|
||||
@@ -61,5 +70,18 @@ abstract class PartModules<T> extends Part<Modules.Module> {
|
||||
|
||||
protected abstract boolean setPart(Modules.Module module, T part);
|
||||
|
||||
protected abstract void upgrade(final String ID, final NetworkCallback<T> callback, final NetworkErrorCallback errorCallback);
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
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.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;
|
||||
|
||||
public class BBLogin extends HTTPService {
|
||||
private final FULogin mFULogin;
|
||||
private long lastHash;
|
||||
private long lastSync;
|
||||
private static final long MAX_CACHE_TIME = 1000 * 60; // 1 minute
|
||||
|
||||
public BBLogin(Context context, FULogin fuLogin) {
|
||||
super(context);
|
||||
this.mFULogin = fuLogin;
|
||||
}
|
||||
|
||||
public void testLoginToken(@NotNull LoginTokenBB token, @NotNull NetworkCallback<LoginTokenBB> callback, @NotNull NetworkErrorCallback errorCallback) {
|
||||
if (token.hashCode() == lastHash && lastSync + MAX_CACHE_TIME > System.currentTimeMillis() && token.getStudentId() != null) {
|
||||
callback.onResponse(token);
|
||||
return;
|
||||
}
|
||||
get(String.format("https://lms.fu-berlin.de/learn/api/public/v1/users/?userName=%s", token.getUsername()), token.getCookies(), response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(100272, 403, "Testing login failed!"));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
json = json.getJSONArray("results").getJSONObject(0);
|
||||
String id = json.getString("id");
|
||||
String studentId = json.getString("studentId");
|
||||
token.setAdditionals(id, studentId);
|
||||
lastSync = System.currentTimeMillis();
|
||||
lastHash = token.hashCode();
|
||||
callback.onResponse(token);
|
||||
} catch (JSONException e) {
|
||||
errorCallback.onError(new NetworkError(100271, 403, "Cannot parse profile!"));
|
||||
}
|
||||
}, error -> errorCallback.onError(new NetworkError(100270, error.networkResponse.statusCode, "Testing login failed!")));
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public void doLogin(String username, String password, NetworkCallback<LoginTokenBB> callback, NetworkErrorCallback error) {
|
||||
step1(success1 -> {
|
||||
String samlLocation = success1.get("Location");
|
||||
mFULogin.fulogin(samlLocation, username, password, samlResponse -> {
|
||||
step5(samlResponse, success5 -> {
|
||||
String shibsessionKey = success5.get("shibsessionKey");
|
||||
String shibsessionName = success5.get("shibsessionName");
|
||||
step6(shibsessionKey, shibsessionName, success6 -> {
|
||||
String s_session_id = success6.get("s_session_id");
|
||||
String session_id = success6.get("session_id");
|
||||
LoginTokenBB token = new LoginTokenBB(username, s_session_id, session_id);
|
||||
callback.onResponse(token);
|
||||
}, error);
|
||||
}, error);
|
||||
}, error);
|
||||
}, error);
|
||||
}
|
||||
|
||||
/*
|
||||
1= GET https://lms.fu-berlin.de/lms-apps/login/sso/index.php
|
||||
-> Location-Header: https://identity.fu-berlin.de/idp-fub/profile/SAML2/Redirect/SSO?SAMLResponse=[SAMLResponse]&RelayState=[RelayState]
|
||||
*/
|
||||
private void step1(final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
|
||||
get("https://lms.fu-berlin.de/lms-apps/login/sso/index.php", null, response -> {
|
||||
String location = response.getHeaders().get("Location");
|
||||
if (location==null) {
|
||||
errorCallback.onError(new NetworkError(100211, -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(100210, error.networkResponse.statusCode, "Error on getting SAML request!")));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*
|
||||
5= POST https://lms.fu-berlin.de/Shibboleth.sso/SAML2/POST
|
||||
+ Body: SAMLResponse=[SAML-RESPONSE]
|
||||
+ Header: Content-Type: application/x-www-form-urlencoded
|
||||
-> Set-Cookie: _shibsession_[SESS-NR]: [SESS-VALUE]
|
||||
*/
|
||||
private void step5(String SAMLResponse, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
|
||||
HashMap<String, String> body = new HashMap<>();
|
||||
body.put("SAMLResponse", SAMLResponse);
|
||||
post("https://lms.fu-berlin.de/Shibboleth.sso/SAML2/POST", null, body, response -> {
|
||||
String cookies = response.getHeaders().get("Set-Cookie");
|
||||
if (cookies ==null) {
|
||||
errorCallback.onError(new NetworkError(100251, -1, "Error on starting KVV session!"));
|
||||
return;
|
||||
}
|
||||
HashMap<String, String> object = new HashMap<>();
|
||||
|
||||
|
||||
Pattern pattern = Pattern.compile("(_shibsession_[0-9a-f]+)=([^;]+);");
|
||||
Matcher matcher = pattern.matcher(cookies);
|
||||
if (!matcher.find()) {
|
||||
errorCallback.onError(new NetworkError(100252, -1, "Error on starting KVV session!"));
|
||||
}
|
||||
object.put("shibsessionKey", matcher.group(1));
|
||||
object.put("shibsessionName", matcher.group(2));
|
||||
|
||||
callback.onResponse(object);
|
||||
}, error -> errorCallback.onError(new NetworkError(100250, error.networkResponse.statusCode, "Error on starting KVV session!")));
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
6= https://lms.fu-berlin.de/webapps/bb-auth-provider-shibboleth-bb_bb60/execute/shibbolethLogin?returnUrl=https://lms.fu-berlin.de/webapps/portal/execute/defaultTab&authProviderId=_3_1
|
||||
+ Cookie: _shibsession_[SESS-NR]: [SESS-VALUE]
|
||||
-> Set-Cookie: JSESSIONID: [JSESSION-KVV]
|
||||
*/
|
||||
private void step6(String shibsessionKey, String shibsessionName, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
|
||||
HashMap<String, String> cookies = new HashMap<>();
|
||||
cookies.put(shibsessionKey, shibsessionName);
|
||||
get("https://lms.fu-berlin.de/webapps/bb-auth-provider-shibboleth-bb_bb60/execute/shibbolethLogin?returnUrl=https://lms.fu-berlin.de/webapps/portal/execute/defaultTab&authProviderId=_3_1", cookies, response -> {
|
||||
String cookies1 = response.getHeaders().get("Set-Cookie");
|
||||
if (cookies1 ==null) {
|
||||
errorCallback.onError(new NetworkError(100261, -1, "Cannot finish login process!"));
|
||||
return;
|
||||
}
|
||||
HashMap<String, String> object;
|
||||
try {
|
||||
object = getCookie(cookies1, new String[]{"session_id", "s_session_id"});
|
||||
} catch (NoSuchFieldException e) {
|
||||
errorCallback.onError(new NetworkError(100262, -1, "Cannot finish login process!"));
|
||||
return;
|
||||
}
|
||||
callback.onResponse(object);
|
||||
}, error -> errorCallback.onError(new NetworkError(100260, error.networkResponse.statusCode, "Cannot finish login process!")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package de.sebse.fuplanner.services.kvv.sync;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
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 requestURI, String username, String password, final NetworkCallback<String> callback, final NetworkErrorCallback errorCallback) {
|
||||
String old_shib_idp_session = Preferences.getString(getContext(), R.string.pref_shib_idp_session);
|
||||
step2(requestURI, old_shib_idp_session, success2 -> {
|
||||
String samlResp = success2.get("SAMLResponse");
|
||||
if (samlResp != null) {
|
||||
callback.onResponse(samlResp);
|
||||
return;
|
||||
}
|
||||
String fuJSESSIONID = success2.get("JSESSIONID");
|
||||
step3(fuJSESSIONID, success3 -> {
|
||||
step4(username, password, fuJSESSIONID, success4 -> {
|
||||
String shib_idp_session = success4.get("shib_idp_session");
|
||||
Preferences.setString(getContext(), R.string.pref_shib_idp_session, shib_idp_session);
|
||||
String samlResponse = success4.get("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 step2(String url, @Nullable String shib_idp_session, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
|
||||
HashMap<String, String> cookiesReq = null;
|
||||
if (shib_idp_session != null) {
|
||||
cookiesReq = new HashMap<>();
|
||||
cookiesReq.put("shib_idp_session", shib_idp_session);
|
||||
}
|
||||
get(url, cookiesReq, response -> {
|
||||
String body = response.getParsed();
|
||||
if (body != null) {
|
||||
Pattern pattern = Pattern.compile("name=\"SAMLResponse\" value=\"([0-9a-zA-Z+]+=*)");
|
||||
Matcher matcher = pattern.matcher(body);
|
||||
if (!matcher.find()) {
|
||||
errorCallback.onError(new NetworkError(100344, -1, "Error on getting SAML response!"));
|
||||
return;
|
||||
}
|
||||
HashMap<String, String> object = new HashMap<>();
|
||||
object.put("SAMLResponse", matcher.group(1));
|
||||
callback.onResponse(object);
|
||||
return;
|
||||
}
|
||||
String cookies = response.getHeaders().get("Set-Cookie");
|
||||
if (cookies == null) {
|
||||
errorCallback.onError(new NetworkError(100321, -1, "Error on starting FU session!"));
|
||||
return;
|
||||
}
|
||||
HashMap<String, String> object;
|
||||
try {
|
||||
object = getCookie(cookies, new String[]{"JSESSIONID"});
|
||||
} catch (NoSuchFieldException e) {
|
||||
errorCallback.onError(new NetworkError(100322, -1, "Error on starting FU session!"));
|
||||
return;
|
||||
}
|
||||
callback.onResponse(object);
|
||||
}, error -> errorCallback.onError(new NetworkError(100320, error.networkResponse.statusCode, "Error on starting FU session!")));
|
||||
}
|
||||
|
||||
/*
|
||||
3= GET [Location-Header 2]
|
||||
+ Cookie: JSESSIONID=[JSESSION-FU]
|
||||
*/
|
||||
private void step3(String JSESSIONID_FU, final NetworkCallback<Boolean> callback, final NetworkErrorCallback errorCallback) {
|
||||
HashMap<String, String> cookies = new HashMap<>();
|
||||
cookies.put("JSESSIONID", JSESSIONID_FU);
|
||||
head("https://identity.fu-berlin.de/idp-fub/profile/SAML2/Redirect/SSO?execution=e1s1", cookies, response -> {
|
||||
callback.onResponse(true);
|
||||
}, error -> errorCallback.onError(new NetworkError(100330, error.networkResponse.statusCode, "Error starting login page!")));
|
||||
}
|
||||
|
||||
/*
|
||||
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 step4(String username, String password, String JSESSIONID_FU, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
|
||||
HashMap<String, String> cookies = new HashMap<>();
|
||||
cookies.put("JSESSIONID", JSESSIONID_FU);
|
||||
HashMap<String, String> body = new HashMap<>();
|
||||
body.put("j_username", username);
|
||||
body.put("j_password", password);
|
||||
body.put("_eventId_proceed", "");
|
||||
post("https://identity.fu-berlin.de/idp-fub/profile/SAML2/Redirect/SSO?execution=e1s1", cookies, body, response -> {
|
||||
String content = response.getParsed();
|
||||
if (content == null) {
|
||||
errorCallback.onError(new NetworkError(100343, -1, "Error on getting SAML response!"));
|
||||
return;
|
||||
}
|
||||
|
||||
String cookies1 = response.getHeaders().get("Set-Cookie");
|
||||
if (cookies1 ==null) {
|
||||
errorCallback.onError(new NetworkError(100341, -1, "Error on logging in to FU Identity Server!"));
|
||||
return;
|
||||
}
|
||||
HashMap<String, String> object;
|
||||
try {
|
||||
object = getCookie(cookies1, 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;
|
||||
}
|
||||
object.put("SAMLResponse", matcher.group(1));
|
||||
callback.onResponse(object);
|
||||
}, error -> errorCallback.onError(new NetworkError(100345, error.networkResponse.statusCode, "Error on logging in to FU Identity Server!")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package de.sebse.fuplanner.services.kvv.sync;
|
||||
|
||||
import android.content.ContentProvider;
|
||||
import android.content.ContentValues;
|
||||
import android.content.UriMatcher;
|
||||
import android.database.Cursor;
|
||||
import android.net.Uri;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
public class KVVContentProvider extends ContentProvider {
|
||||
|
||||
public 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;
|
||||
private static final UriMatcher uriMatcher = getUriMatcher();
|
||||
|
||||
private static UriMatcher getUriMatcher() {
|
||||
UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
|
||||
uriMatcher.addURI(PROVIDER_NAME, "modules", MODULE);
|
||||
uriMatcher.addURI(PROVIDER_NAME, "modules/#", MODULE_ID);
|
||||
return uriMatcher;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean onCreate() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public Cursor query(@NonNull Uri uri, @Nullable String[] strings, @Nullable String s, @Nullable String[] strings1, @Nullable String s1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public String getType(@NonNull Uri uri) {
|
||||
switch (uriMatcher.match(uri)) {
|
||||
case MODULE:
|
||||
return "vnd.android.cursor.dir/vnd.com."+PROVIDER_NAME;
|
||||
case MODULE_ID:
|
||||
return "vnd.android.cursor.item/vnd.com."+PROVIDER_NAME;
|
||||
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package de.sebse.fuplanner.services.kvv.sync;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import de.sebse.fuplanner.services.kvv.Constants;
|
||||
import de.sebse.fuplanner.services.kvv.types.LoginTokenKVV;
|
||||
import de.sebse.fuplanner.tools.network.HTTPService;
|
||||
import de.sebse.fuplanner.tools.network.NetworkCallback;
|
||||
import de.sebse.fuplanner.tools.network.NetworkError;
|
||||
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;
|
||||
|
||||
public class KVVLogin extends HTTPService {
|
||||
private final FULogin mFULogin;
|
||||
private long lastHash;
|
||||
private long lastSync;
|
||||
private static final long MAX_CACHE_TIME = 1000 * 60; // 1 minute
|
||||
|
||||
public static final String KVV_SERVER_URL = Constants.KVV_SERVER_URL;
|
||||
|
||||
public KVVLogin(Context context, FULogin fuLogin) {
|
||||
super(context);
|
||||
this.mFULogin = fuLogin;
|
||||
}
|
||||
|
||||
|
||||
public void testLoginToken(@NotNull LoginTokenKVV token, @NotNull NetworkCallback<LoginTokenKVV> callback, @NotNull NetworkErrorCallback errorCallback) {
|
||||
if (token.hashCode() == lastHash && lastSync + MAX_CACHE_TIME > System.currentTimeMillis() && token.getFullName() != null) {
|
||||
callback.onResponse(token);
|
||||
return;
|
||||
}
|
||||
get(String.format(KVV_SERVER_URL+"direct/profile/%s.json", token.getUsername()), token.getCookies(), response -> {
|
||||
String body = response.getParsed();
|
||||
if (body == null) {
|
||||
errorCallback.onError(new NetworkError(100172, 403, "Testing login failed!"));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
String displayName = json.getString("displayName");
|
||||
String email = json.getString("email");
|
||||
token.setAdditionals(displayName, email);
|
||||
lastSync = System.currentTimeMillis();
|
||||
lastHash = token.hashCode();
|
||||
callback.onResponse(token);
|
||||
} catch (JSONException e) {
|
||||
errorCallback.onError(new NetworkError(100171, 403, "Cannot parse profile!"));
|
||||
}
|
||||
}, error -> errorCallback.onError(new NetworkError(100170, error.networkResponse.statusCode, "Testing login failed!")));
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public void doLogin(String username, String password, NetworkCallback<LoginTokenKVV> callback, NetworkErrorCallback error) {
|
||||
step0(username, success -> {
|
||||
step1(success1 -> {
|
||||
String samlLocation = success1.get("Location");
|
||||
mFULogin.fulogin(samlLocation, username, password, samlResponse -> {
|
||||
step5(samlResponse, success5 -> {
|
||||
String shibsessionKey = success5.get("shibsessionKey");
|
||||
String shibsessionName = success5.get("shibsessionName");
|
||||
step6(shibsessionKey, shibsessionName, success6 -> {
|
||||
String kvvJSESSIONID = success6.get("JSESSIONID");
|
||||
LoginTokenKVV token = new LoginTokenKVV(username, kvvJSESSIONID);
|
||||
callback.onResponse(token);
|
||||
}, error);
|
||||
}, error);
|
||||
}, error);
|
||||
}, error);
|
||||
}, error);
|
||||
}
|
||||
|
||||
private void step0(String username, final NetworkCallback<Boolean> callback, final NetworkErrorCallback errorCallback) {
|
||||
get(String.format(KVV_SERVER_URL+"direct/profile/%s", username), null, result -> {
|
||||
callback.onResponse(true);
|
||||
}, error -> {
|
||||
if (error.networkResponse.statusCode == 500) {
|
||||
errorCallback.onError(new NetworkError(100101, error.networkResponse.statusCode, "KVV not available!"));
|
||||
} else {
|
||||
callback.onResponse(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/*
|
||||
1= GET https://kvv.imp.fu-berlin.de/Shibboleth.sso/Login?entityID=https://identity.fu-berlin.de/idp-fub
|
||||
-> Location-Header: https://identity.fu-berlin.de/idp-fub/profile/SAML2/Redirect/SSO?SAMLResponse=[SAMLResponse]&RelayState=[RelayState]
|
||||
*/
|
||||
private void step1(final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
|
||||
get(KVV_SERVER_URL+"Shibboleth.sso/Login?entityID=https://identity.fu-berlin.de/idp-fub", null, response -> {
|
||||
String location = response.getHeaders().get("Location");
|
||||
if (location==null) {
|
||||
errorCallback.onError(new NetworkError(100111, -1, "Error on getting SAML request!"));
|
||||
return;
|
||||
}
|
||||
HashMap<String, String> object = new HashMap<>();
|
||||
object.put("Location", location);
|
||||
callback.onResponse(object);
|
||||
}, error -> errorCallback.onError(new NetworkError(100110, error.networkResponse.statusCode, "Error on getting SAML request!")));
|
||||
}
|
||||
|
||||
/*
|
||||
5= POST https://kvv.imp.fu-berlin.de/Shibboleth.sso/SAML2/POST
|
||||
+ Body: SAMLResponse=[SAML-RESPONSE]
|
||||
+ Header: Content-Type: application/x-www-form-urlencoded
|
||||
-> Set-Cookie: _shibsession_[SESS-NR]: [SESS-VALUE]
|
||||
*/
|
||||
private void step5(String SAMLResponse, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
|
||||
HashMap<String, String> body = new HashMap<>();
|
||||
body.put("SAMLResponse", SAMLResponse);
|
||||
post(KVV_SERVER_URL+"Shibboleth.sso/SAML2/POST", null, body, response -> {
|
||||
String cookies = response.getHeaders().get("Set-Cookie");
|
||||
if (cookies ==null) {
|
||||
errorCallback.onError(new NetworkError(100151, -1, "Error on starting KVV session!"));
|
||||
return;
|
||||
}
|
||||
HashMap<String, String> object = new HashMap<>();
|
||||
|
||||
|
||||
Pattern pattern = Pattern.compile("(_shibsession_[0-9a-f]+)=([^;]+);");
|
||||
Matcher matcher = pattern.matcher(cookies);
|
||||
if (!matcher.find()) {
|
||||
errorCallback.onError(new NetworkError(100152, -1, "Error on starting KVV session!"));
|
||||
}
|
||||
object.put("shibsessionKey", matcher.group(1));
|
||||
object.put("shibsessionName", matcher.group(2));
|
||||
|
||||
callback.onResponse(object);
|
||||
}, error -> errorCallback.onError(new NetworkError(100150, error.networkResponse.statusCode, "Error on starting KVV session!")));
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
6= https://kvv.imp.fu-berlin.de/sakai-login-tool/container
|
||||
+ Cookie: _shibsession_[SESS-NR]: [SESS-VALUE]
|
||||
-> Set-Cookie: JSESSIONID: [JSESSION-KVV]
|
||||
*/
|
||||
private void step6(String shibsessionKey, String shibsessionName, final NetworkCallback<HashMap<String, String>> callback, final NetworkErrorCallback errorCallback) {
|
||||
HashMap<String, String> cookies = new HashMap<>();
|
||||
cookies.put(shibsessionKey, shibsessionName);
|
||||
get(KVV_SERVER_URL+"sakai-login-tool/container", cookies, response -> {
|
||||
String cookies1 = response.getHeaders().get("Set-Cookie");
|
||||
if (cookies1 ==null) {
|
||||
errorCallback.onError(new NetworkError(100161, -1, "Cannot finish login process!"));
|
||||
return;
|
||||
}
|
||||
HashMap<String, String> object;
|
||||
try {
|
||||
object = getCookie(cookies1, new String[]{"JSESSIONID"});
|
||||
} catch (NoSuchFieldException e) {
|
||||
errorCallback.onError(new NetworkError(100162, -1, "Cannot finish login process!"));
|
||||
return;
|
||||
}
|
||||
callback.onResponse(object);
|
||||
}, error -> errorCallback.onError(new NetworkError(100160, error.networkResponse.statusCode, "Cannot finish login process!")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package de.sebse.fuplanner.services.kvv.sync;
|
||||
|
||||
import android.accounts.Account;
|
||||
import android.accounts.AccountManager;
|
||||
import android.content.AbstractThreadedSyncAdapter;
|
||||
import android.content.ComponentName;
|
||||
import android.content.ContentProviderClient;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.ServiceConnection;
|
||||
import android.content.SyncResult;
|
||||
import android.os.Bundle;
|
||||
import android.os.IBinder;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
|
||||
import androidx.annotation.StringRes;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.fragments.moddetails.ModulePart;
|
||||
import de.sebse.fuplanner.services.kvv.KVV;
|
||||
import de.sebse.fuplanner.services.kvv.KVVListener;
|
||||
import de.sebse.fuplanner.services.kvv.types.Announcement;
|
||||
import de.sebse.fuplanner.services.kvv.types.Assignment;
|
||||
import de.sebse.fuplanner.services.kvv.types.AssignmentList;
|
||||
import de.sebse.fuplanner.services.kvv.types.EventList;
|
||||
import de.sebse.fuplanner.services.kvv.types.Grade;
|
||||
import de.sebse.fuplanner.services.kvv.types.Modules;
|
||||
import de.sebse.fuplanner.services.kvv.types.Resource;
|
||||
import de.sebse.fuplanner.tools.CustomAccountManager;
|
||||
import de.sebse.fuplanner.tools.CustomNotificationManager;
|
||||
import de.sebse.fuplanner.tools.NewAsyncQueue;
|
||||
import de.sebse.fuplanner.tools.UtilsDate;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
|
||||
import static de.sebse.fuplanner.MainActivity.FRAGMENT_MODULES_DETAILS;
|
||||
|
||||
public class KVVSyncAdapter extends AbstractThreadedSyncAdapter {
|
||||
private KVV mKVV;
|
||||
private Logger log = new Logger(this);
|
||||
private NewAsyncQueue mQueue = new NewAsyncQueue();
|
||||
|
||||
|
||||
private boolean mBound = false;
|
||||
private boolean mWaitForBound = false;
|
||||
private ServiceConnection mConnection = new ServiceConnection() {
|
||||
@Override
|
||||
public void onServiceConnected(ComponentName className, IBinder service) {
|
||||
// We've bound to LocalService, cast the IBinder and get LocalService instance
|
||||
KVV.LocalBinder binder = (KVV.LocalBinder) service;
|
||||
mKVV = binder.getService();
|
||||
mBound = true;
|
||||
if (mWaitForBound) {
|
||||
mWaitForBound = false;
|
||||
mQueue.next();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onServiceDisconnected(ComponentName arg0) {
|
||||
mBound = false;
|
||||
mKVV = null;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Set up the sync adapter
|
||||
*/
|
||||
KVVSyncAdapter(Context context, boolean autoInitialize) {
|
||||
super(context, autoInitialize);
|
||||
init(context);
|
||||
}
|
||||
/**
|
||||
* Set up the sync adapter. This form of the
|
||||
* constructor maintains compatibility with Android 3.0
|
||||
* and later platform versions
|
||||
*/
|
||||
public KVVSyncAdapter(
|
||||
Context context,
|
||||
boolean autoInitialize,
|
||||
boolean allowParallelSyncs) {
|
||||
super(context, autoInitialize, allowParallelSyncs);
|
||||
init(context);
|
||||
}
|
||||
|
||||
private void init(Context context) {
|
||||
// Bind to LocalService
|
||||
}
|
||||
|
||||
/*
|
||||
* Specify the code you want to run in the sync adapter. The entire
|
||||
* sync adapter runs in a background thread, so you don't have to set
|
||||
* up your own background processing.
|
||||
*/
|
||||
@Override
|
||||
public void onPerformSync(
|
||||
Account account,
|
||||
Bundle extras,
|
||||
String authority,
|
||||
ContentProviderClient provider,
|
||||
SyncResult syncResult) {
|
||||
if (!mBound) {
|
||||
Intent intent = new Intent(getContext(), KVV.class);
|
||||
mWaitForBound = true;
|
||||
mQueue.add(() -> {});
|
||||
}
|
||||
mQueue.add(() -> {
|
||||
mKVV.account().restoreOnlineLogin(bool -> {
|
||||
mQueue.next();
|
||||
});
|
||||
});
|
||||
mQueue.add(() -> {
|
||||
if (!mKVV.account().isLoggedIn()) {
|
||||
log.w("Not logged in!");
|
||||
return;
|
||||
}
|
||||
mKVV.modules().list().reloadIfOutdated();
|
||||
mKVV.modules().list().recv(success -> {
|
||||
final int[] latch = {0};
|
||||
Iterator<Modules.Module> iterator = success.latestSemesterIterator();
|
||||
while (iterator.hasNext()) {
|
||||
latch[0] += 1;
|
||||
iterator.next();
|
||||
}
|
||||
iterator = success.latestSemesterIterator();
|
||||
while (iterator.hasNext()) {
|
||||
Modules.Module module = iterator.next();
|
||||
final ArrayList<Announcement> announcements = module.announcements;
|
||||
final AssignmentList assignments = module.assignments;
|
||||
final EventList events = module.events;
|
||||
final ArrayList<Grade> gradebook = module.gradebook;
|
||||
final ArrayList<Resource> resources = module.resources;
|
||||
mKVV.modules().details().recv(module, success1 -> {
|
||||
if (success1.second) {
|
||||
sendNotifications(announcements, module.announcements, module.title, Announcement::getTitle, Announcement::getId,
|
||||
module.getID(), ModulePart.ANNOUNCEMENT,
|
||||
R.string.announcement_updated, R.string.announcement_added, R.string.announcement_removed);
|
||||
sendNotifications(assignments, module.assignments, module.title, Assignment::getTitle, Assignment::getId,
|
||||
module.getID(), ModulePart.ASSIGNMENT,
|
||||
R.string.assignment_updated, R.string.assignment_added, R.string.assignment_removed);
|
||||
sendNotifications(events, module.events, module.title, evt -> evt.getTitle()+" - "+UtilsDate.getModifiedDate(evt.getStartDate()), event -> String.valueOf(event.getStartDate())+event.getType()+event.getTitle(),
|
||||
module.getID(), ModulePart.EVENT,
|
||||
R.string.event_updated, R.string.event_added, R.string.event_removed);
|
||||
sendNotifications(gradebook, module.gradebook, module.title, Grade::getItemName, Grade::getItemName,
|
||||
module.getID(), ModulePart.GRADEBOOK,
|
||||
R.string.gradebook_updated, R.string.gradebook_added, R.string.gradebook_removed);
|
||||
sendNotifications(resources, module.resources, module.title, Resource::getTitle, Resource::getUrl,
|
||||
module.getID(), ModulePart.RESOURCES,
|
||||
R.string.resource_updated, R.string.resource_added, R.string.resource_removed);
|
||||
if (--latch[0] == 0) mQueue.next();
|
||||
}
|
||||
}, error -> {
|
||||
log.e(error);
|
||||
if (--latch[0] == 0) mQueue.next();
|
||||
}, true);
|
||||
}
|
||||
}, msg -> {
|
||||
log.e(msg);
|
||||
mQueue.next();
|
||||
}, true);
|
||||
});
|
||||
mQueue.add(() -> {
|
||||
mBound = false;
|
||||
mKVV = null;
|
||||
getContext().unbindService(mConnection);
|
||||
});
|
||||
}
|
||||
|
||||
private <T> void sendNotifications(Iterable<T> oldList, Iterable<T> newList, String title, StringInterface<T> titleInterface, StringInterface<T> idInterface, String moduleId, int modulePart, @StringRes int updateRes, @StringRes int addRes, @StringRes int removeRes) {
|
||||
if (oldList == null || newList == null) {
|
||||
return;
|
||||
}
|
||||
ArrayList<T> obsoletes = new ArrayList<>();
|
||||
for (T old: oldList) {
|
||||
obsoletes.add(old);
|
||||
}
|
||||
String targetData = moduleId+"."+ModulePart.getPageByPart(modulePart);
|
||||
for (T newEntry: newList) {
|
||||
boolean found = false;
|
||||
for (T oldEntry: oldList) {
|
||||
if (idInterface.get(newEntry).equals(idInterface.get(oldEntry))) {
|
||||
found = true;
|
||||
if (newEntry.hashCode() != oldEntry.hashCode()) {
|
||||
CustomNotificationManager.sendNotification(getContext(), getContext().getString(updateRes, title), titleInterface.get(newEntry), FRAGMENT_MODULES_DETAILS, targetData);
|
||||
}
|
||||
obsoletes.remove(oldEntry);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
CustomNotificationManager.sendNotification(getContext(), getContext().getString(addRes, title), titleInterface.get(newEntry), FRAGMENT_MODULES_DETAILS, targetData);
|
||||
}
|
||||
}
|
||||
for (T oldEntry: obsoletes) {
|
||||
CustomNotificationManager.sendNotification(getContext(), getContext().getString(removeRes, title), titleInterface.get(oldEntry), FRAGMENT_MODULES_DETAILS, targetData);
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
interface StringInterface<T> {
|
||||
String get(T element);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package de.sebse.fuplanner.services.kvv.sync;
|
||||
|
||||
import android.app.Service;
|
||||
import android.content.Intent;
|
||||
import android.os.IBinder;
|
||||
|
||||
public class KVVSyncService extends Service {
|
||||
|
||||
private static final Object sSyncAdapterLock = new Object();
|
||||
private static KVVSyncAdapter sSyncAdapter = null;
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
synchronized (sSyncAdapterLock) {
|
||||
if (sSyncAdapter == null)
|
||||
sSyncAdapter = new KVVSyncAdapter(getApplicationContext(), true);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return sSyncAdapter.getSyncAdapterBinder();
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
package de.sebse.fuplanner.services.KVV.types;
|
||||
package de.sebse.fuplanner.services.kvv.types;
|
||||
|
||||
import com.google.android.gms.common.internal.Objects;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
public class Announcement implements Serializable {
|
||||
private final String id;
|
||||
private final String title;
|
||||
@@ -14,7 +16,6 @@ public class Announcement implements Serializable {
|
||||
private final ArrayList<String> urls;
|
||||
|
||||
public Announcement(String id, String title, String body, String createdBy, long createdOn, ArrayList<String> urls) {
|
||||
|
||||
this.id = id;
|
||||
this.title = title;
|
||||
this.body = body;
|
||||
@@ -27,7 +28,7 @@ public class Announcement implements Serializable {
|
||||
return urls;
|
||||
}
|
||||
|
||||
private String getId() {
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@@ -47,6 +48,7 @@ public class Announcement implements Serializable {
|
||||
return createdOn;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ID: "+getId()+
|
||||
@@ -1,10 +1,12 @@
|
||||
package de.sebse.fuplanner.services.KVV.types;
|
||||
package de.sebse.fuplanner.services.kvv.types;
|
||||
|
||||
import com.google.android.gms.common.internal.Objects;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
public class Assignment implements Serializable {
|
||||
private final String id;
|
||||
private final String title;
|
||||
@@ -20,7 +22,7 @@ public class Assignment implements Serializable {
|
||||
this.instructions = instructions;
|
||||
}
|
||||
|
||||
private String getId() {
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@@ -44,6 +46,7 @@ public class Assignment implements Serializable {
|
||||
return instructions;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ID: "+getId()+
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.sebse.fuplanner.services.KVV.types;
|
||||
package de.sebse.fuplanner.services.kvv.types;
|
||||
|
||||
import de.sebse.fuplanner.tools.DateSortedList;
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
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;
|
||||
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 = context.openFileInput(FILE_NAME);
|
||||
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 lecturer) {
|
||||
mBBCourseList.put(courseID, lecturer);
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
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;
|
||||
import java.util.HashSet;
|
||||
|
||||
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 = context.openFileInput(FILE_NAME);
|
||||
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 lecturer) {
|
||||
mKVVCourseList.put(courseID, lecturer);
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
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.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 = context.openFileInput(FILE_NAME);
|
||||
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,4 +1,4 @@
|
||||
package de.sebse.fuplanner.services.KVV.types;
|
||||
package de.sebse.fuplanner.services.kvv.types;
|
||||
|
||||
import com.google.android.gms.common.internal.Objects;
|
||||
|
||||
@@ -7,6 +7,7 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import de.sebse.fuplanner.tools.ColorRGB;
|
||||
|
||||
public class Event implements Serializable {
|
||||
@@ -106,6 +107,7 @@ public class Event implements Serializable {
|
||||
}
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ID: "+getId()+
|
||||
@@ -116,6 +118,6 @@ public class Event implements Serializable {
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(getId(), getType(), getStartDate(), getEndDate(), getTitle(), getLocation());
|
||||
return Objects.hashCode(getType(), getStartDate(), getEndDate(), getTitle(), getLocation());
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.sebse.fuplanner.services.KVV.types;
|
||||
package de.sebse.fuplanner.services.kvv.types;
|
||||
|
||||
import de.sebse.fuplanner.tools.DateSortedList;
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package de.sebse.fuplanner.services.KVV.types;
|
||||
package de.sebse.fuplanner.services.kvv.types;
|
||||
|
||||
import com.google.android.gms.common.internal.Objects;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
public class Grade implements Serializable {
|
||||
private final String itemName;
|
||||
private final double grade;
|
||||
@@ -27,6 +29,7 @@ public class Grade implements Serializable {
|
||||
return itemName;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Name: "+getItemName()+
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.sebse.fuplanner.services.KVV.types;
|
||||
package de.sebse.fuplanner.services.kvv.types;
|
||||
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
@@ -6,39 +6,48 @@ 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;
|
||||
import de.sebse.fuplanner.tools.logging.Logger;
|
||||
|
||||
public class GroupedEvents {
|
||||
private ArrayList<Group> arrayList = new ArrayList<>();
|
||||
private Logger log = new Logger(this);
|
||||
public class GroupedEvents extends EventList {
|
||||
private final ArrayList<Group> arrayList = new ArrayList<>();
|
||||
private int skippedDayCount = 0;
|
||||
|
||||
public void add(Event event) {
|
||||
public boolean add(Event event) {
|
||||
boolean result = super.add(event);
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTimeInMillis(event.getStartDate());
|
||||
long dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
|
||||
for (Group group : arrayList) {
|
||||
if (group.add(event)) {
|
||||
return;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
arrayList.add(new Group(event));
|
||||
return result;
|
||||
}
|
||||
|
||||
public List<Group> getGroups() {
|
||||
return Collections.unmodifiableList(arrayList);
|
||||
}
|
||||
|
||||
public class Group {
|
||||
public int getSkippedDayCount() {
|
||||
return skippedDayCount;
|
||||
}
|
||||
|
||||
public class Group implements Iterable<Event> {
|
||||
private long firstDate;
|
||||
private long lastDate;
|
||||
private ArrayList<Long> skippedDates;
|
||||
private final ArrayList<Long> skippedDates;
|
||||
private final ArrayList<Event> allEvents = new ArrayList<>();
|
||||
|
||||
private int dayOfWeek;
|
||||
private long startTime;
|
||||
private long duration;
|
||||
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();
|
||||
@@ -46,6 +55,8 @@ public class GroupedEvents {
|
||||
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);
|
||||
@@ -54,6 +65,7 @@ public class GroupedEvents {
|
||||
calendar.set(Calendar.MILLISECOND, 0);
|
||||
firstDate = calendar.getTimeInMillis();
|
||||
lastDate = firstDate;
|
||||
allEvents.add(event);
|
||||
}
|
||||
|
||||
private boolean add(Event event) {
|
||||
@@ -62,7 +74,8 @@ public class GroupedEvents {
|
||||
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();
|
||||
if (this.dayOfWeek != dayOfWeek || this.startTime != startTime || this.duration != length)
|
||||
String location = event.getLocation();
|
||||
if (this.dayOfWeek != dayOfWeek || this.startTime != startTime || this.duration != length || !this.location.equals(location))
|
||||
return false;
|
||||
calendar.set(Calendar.HOUR_OF_DAY, 0);
|
||||
calendar.set(Calendar.MINUTE, 0);
|
||||
@@ -73,17 +86,21 @@ public class GroupedEvents {
|
||||
firstDate = addDays(firstDate, -7);
|
||||
while (firstDate > date) {
|
||||
skippedDates.add(firstDate);
|
||||
skippedDayCount += 1;
|
||||
firstDate = addDays(firstDate, -7);
|
||||
}
|
||||
} else if (date > lastDate) {
|
||||
lastDate = addDays(lastDate, 7);
|
||||
while (lastDate < date) {
|
||||
skippedDates.add(lastDate);
|
||||
skippedDayCount += 1;
|
||||
lastDate = addDays(lastDate, 7);
|
||||
}
|
||||
} else {
|
||||
skippedDates.remove(date);
|
||||
skippedDayCount -= 1;
|
||||
}
|
||||
allEvents.add(event);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -118,11 +135,29 @@ public class GroupedEvents {
|
||||
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,15 +1,24 @@
|
||||
package de.sebse.fuplanner.services.KVV.types;
|
||||
package de.sebse.fuplanner.services.kvv.types;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
public class Lecturer implements Serializable {
|
||||
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);
|
||||
@@ -46,6 +55,7 @@ public class Lecturer implements Serializable {
|
||||
return getFirstName().substring(0, 1) + ". " + getSurname();
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
return "First name: "+ getFirstName()+
|
||||
@@ -0,0 +1,156 @@
|
||||
package de.sebse.fuplanner.services.kvv.types;
|
||||
|
||||
import com.google.android.gms.common.internal.Objects;
|
||||
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import de.sebse.fuplanner.services.fulogin.AccountGeneral;
|
||||
import de.sebse.fuplanner.tools.CustomAccountManager;
|
||||
|
||||
/**
|
||||
* Created by sebastian on 29.10.17.
|
||||
*/
|
||||
|
||||
public class LoginTokenBB {
|
||||
private final String s_session_id;
|
||||
private final String session_id;
|
||||
private final String username;
|
||||
private boolean isAvailable = true;
|
||||
@Nullable private String id;
|
||||
@Nullable private String studentId;
|
||||
|
||||
public LoginTokenBB(String username, String s_session_id, String session_id) {
|
||||
this.username = username;
|
||||
this.s_session_id = s_session_id;
|
||||
this.session_id = session_id;
|
||||
}
|
||||
|
||||
public static void load(CustomAccountManager manager, LoginTokenInterface callback, CustomAccountManager.ExceptionInterface errorCallback) {
|
||||
if (!manager.hasAccounts(AccountGeneral.ACCOUNT_TYPE)) {
|
||||
callback.run(null);
|
||||
return;
|
||||
}
|
||||
manager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_BLACKBOARD, tokenString -> {
|
||||
if (tokenString == null) {
|
||||
callback.run(null);
|
||||
return;
|
||||
}
|
||||
callback.run(LoginTokenBB.fromJsonString(tokenString));
|
||||
}, errorCallback);
|
||||
}
|
||||
|
||||
public void delete(CustomAccountManager manager) {
|
||||
manager.deleteAccount(AccountGeneral.ACCOUNT_TYPE);
|
||||
}
|
||||
|
||||
public void setAdditionals(String id, String studentId) {
|
||||
this.id = id;
|
||||
this.studentId = studentId;
|
||||
this.isAvailable = true;
|
||||
}
|
||||
|
||||
public void setNotAvailable() {
|
||||
this.id = null;
|
||||
this.studentId = null;
|
||||
this.isAvailable = false;
|
||||
}
|
||||
|
||||
public boolean isAvailable() {
|
||||
return isAvailable;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
private String getSessionId() {
|
||||
return session_id;
|
||||
}
|
||||
|
||||
public String getSSessionId() {
|
||||
return s_session_id;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getStudentId() {
|
||||
return studentId;
|
||||
}
|
||||
|
||||
public HashMap<String, String> getCookies() {
|
||||
HashMap<String, String> cookies = new HashMap<>();
|
||||
cookies.put("session_id", getSessionId());
|
||||
cookies.put("s_session_id", getSSessionId());
|
||||
return cookies;
|
||||
}
|
||||
|
||||
public boolean isOtherUser(String username) {
|
||||
return !this.getUsername().equals(username);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
HashMap<String, String> cookies = this.getCookies();
|
||||
for (String header: cookies.keySet()) {
|
||||
result.append(header).append("=").append(cookies.get(header)).append(";");
|
||||
}
|
||||
return result.substring(0, result.length()-1);
|
||||
}
|
||||
|
||||
public String toJsonString() {
|
||||
JSONObject json = new JSONObject();
|
||||
try {
|
||||
json.put("s_session_id", s_session_id);
|
||||
json.put("session_id", session_id);
|
||||
json.put("username", username);
|
||||
json.put("id", id);
|
||||
json.put("studentId", studentId);
|
||||
json.put("isAvailable", isAvailable);
|
||||
} catch (JSONException e) {
|
||||
return null;
|
||||
}
|
||||
return json.toString();
|
||||
}
|
||||
|
||||
private static LoginTokenBB fromJsonString(String tokenString) {
|
||||
try {
|
||||
JSONObject json = new JSONObject(tokenString);
|
||||
LoginTokenBB token = new LoginTokenBB(
|
||||
json.getString("username"),
|
||||
json.getString("s_session_id"),
|
||||
json.getString("session_id"));
|
||||
if (!json.isNull("id"))
|
||||
token.setAdditionals(
|
||||
json.getString("id"),
|
||||
json.getString("studentId")
|
||||
);
|
||||
if (!json.optBoolean("isAvailable", true)) {
|
||||
token.setNotAvailable();
|
||||
}
|
||||
return token;
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(s_session_id, session_id, username, id, studentId);
|
||||
}
|
||||
|
||||
public interface LoginTokenInterface {
|
||||
void run(LoginTokenBB token);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package de.sebse.fuplanner.services.kvv.types;
|
||||
|
||||
import com.google.android.gms.common.internal.Objects;
|
||||
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import de.sebse.fuplanner.services.fulogin.AccountGeneral;
|
||||
import de.sebse.fuplanner.tools.CustomAccountManager;
|
||||
|
||||
/**
|
||||
* Created by sebastian on 29.10.17.
|
||||
*/
|
||||
|
||||
public class LoginTokenKVV {
|
||||
private final String username;
|
||||
private final String JSESSIONID;
|
||||
private boolean isAvailable = true;
|
||||
@Nullable private String fullName;
|
||||
@Nullable private String email;
|
||||
|
||||
public LoginTokenKVV(String username, String JSESSIONID) {
|
||||
this.username = username;
|
||||
this.JSESSIONID = JSESSIONID;
|
||||
}
|
||||
|
||||
public static void load(CustomAccountManager manager, LoginTokenInterface callback, CustomAccountManager.ExceptionInterface errorCallback) {
|
||||
if (!manager.hasAccounts(AccountGeneral.ACCOUNT_TYPE)) {
|
||||
callback.run(null);
|
||||
return;
|
||||
}
|
||||
manager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV, tokenString -> {
|
||||
if (tokenString == null) {
|
||||
callback.run(null);
|
||||
return;
|
||||
}
|
||||
callback.run(LoginTokenKVV.fromJsonString(tokenString));
|
||||
}, errorCallback);
|
||||
}
|
||||
|
||||
public void delete(CustomAccountManager manager) {
|
||||
manager.deleteAccount(AccountGeneral.ACCOUNT_TYPE);
|
||||
}
|
||||
|
||||
public void setAdditionals(String fullName, String email) {
|
||||
this.fullName = fullName;
|
||||
this.email = email;
|
||||
this.isAvailable = true;
|
||||
}
|
||||
|
||||
public void setNotAvailable() {
|
||||
this.fullName = null;
|
||||
this.email = null;
|
||||
this.isAvailable = false;
|
||||
}
|
||||
|
||||
public boolean isAvailable() {
|
||||
return isAvailable;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
private String getJSESSIONID() {
|
||||
return JSESSIONID;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getFullName() {
|
||||
return fullName;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public HashMap<String, String> getCookies() {
|
||||
HashMap<String, String> cookies = new HashMap<>();
|
||||
cookies.put("JSESSIONID", getJSESSIONID());
|
||||
cookies.put("pasystem_timezone_ok", "true");
|
||||
return cookies;
|
||||
}
|
||||
|
||||
public boolean isOtherUser(String username) {
|
||||
return !this.getUsername().equals(username);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
HashMap<String, String> cookies = this.getCookies();
|
||||
for (String header: cookies.keySet()) {
|
||||
result.append(header).append("=").append(cookies.get(header)).append(";");
|
||||
}
|
||||
return result.substring(0, result.length()-1);
|
||||
}
|
||||
|
||||
public String toJsonString() {
|
||||
JSONObject json = new JSONObject();
|
||||
try {
|
||||
json.put("username", username);
|
||||
json.put("JSESSIONID", JSESSIONID);
|
||||
json.put("fullName", fullName);
|
||||
json.put("email", email);
|
||||
json.put("isAvailable", isAvailable);
|
||||
} catch (JSONException e) {
|
||||
return null;
|
||||
}
|
||||
return json.toString();
|
||||
}
|
||||
|
||||
private static LoginTokenKVV fromJsonString(String tokenString) {
|
||||
try {
|
||||
JSONObject json = new JSONObject(tokenString);
|
||||
LoginTokenKVV token = new LoginTokenKVV(
|
||||
json.getString("username"),
|
||||
json.getString("JSESSIONID"));
|
||||
if (!json.isNull("fullName"))
|
||||
token.setAdditionals(
|
||||
json.getString("fullName"),
|
||||
json.getString("email")
|
||||
);
|
||||
if (!json.optBoolean("isAvailable", true)) {
|
||||
token.setNotAvailable();
|
||||
}
|
||||
return token;
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(username, JSESSIONID, fullName, email);
|
||||
}
|
||||
|
||||
public interface LoginTokenInterface {
|
||||
void run(LoginTokenKVV token);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
package de.sebse.fuplanner.services.KVV.types;
|
||||
package de.sebse.fuplanner.services.kvv.types;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import com.google.android.gms.common.internal.Objects;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
@@ -23,19 +25,28 @@ import androidx.annotation.Nullable;
|
||||
*/
|
||||
|
||||
public class Modules implements Iterable<Modules.Module>, Serializable {
|
||||
public static final int TYPE_KVV = 1;
|
||||
public static final int TYPE_BB = 2;
|
||||
|
||||
private SortedListModule list;
|
||||
private final String mUsername;
|
||||
//private transient Logger log = new Logger(this);
|
||||
private transient long mLastTimestamp = 0;
|
||||
private static final String FILE_NAME = "ModuleListSaving";
|
||||
private static final String FILE_NAME_TIMESTAMP = "ModuleListSavingTimestamp";
|
||||
|
||||
public Modules(String username) {
|
||||
this.mUsername = username;
|
||||
this.list = new SortedListModule();
|
||||
}
|
||||
|
||||
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);
|
||||
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);
|
||||
this.list.add(m);
|
||||
return m;
|
||||
}
|
||||
|
||||
public void addModule(Module module) {
|
||||
this.list.add(module);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@@ -54,6 +65,10 @@ 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();
|
||||
}
|
||||
@@ -75,15 +90,38 @@ public class Modules implements Iterable<Modules.Module>, Serializable {
|
||||
Modules modules = (Modules) readObject;
|
||||
is.close();
|
||||
fis.close();
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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 delete(Context context) {
|
||||
@@ -94,30 +132,49 @@ public class Modules implements Iterable<Modules.Module>, Serializable {
|
||||
return mUsername;
|
||||
}
|
||||
|
||||
public void updateList(Modules modules) {
|
||||
public boolean updateList(Modules modules) {
|
||||
SortedListModule old = this.list;
|
||||
this.list = modules.list;
|
||||
boolean isChanged = false;
|
||||
for (Module oldModule : old) {
|
||||
Module newModule = this.list.getById(oldModule.getID());
|
||||
if (newModule != null) {
|
||||
if (!isChanged && !hashEquals(oldModule, newModule))
|
||||
isChanged = true;
|
||||
newModule.announcements = oldModule.announcements;
|
||||
newModule.assignments = oldModule.assignments;
|
||||
newModule.events = oldModule.events;
|
||||
newModule.gradebook = oldModule.gradebook;
|
||||
newModule.resources = oldModule.resources;
|
||||
} else {
|
||||
isChanged = true;
|
||||
}
|
||||
}
|
||||
if (this.list.size() != old.size())
|
||||
isChanged = true;
|
||||
return isChanged;
|
||||
}
|
||||
|
||||
private boolean hashEquals(Module o1, Module o2) {
|
||||
if (o1 == null && o2 == null)
|
||||
return true;
|
||||
else if (o1 == null || o2 == null)
|
||||
return false;
|
||||
else
|
||||
return o1.hashCode() == o2.hashCode();
|
||||
}
|
||||
|
||||
public class Module implements Serializable {
|
||||
|
||||
@Nullable public final Semester semester;
|
||||
@NotNull final HashSet<String> lvNumber;
|
||||
@NotNull public final HashSet<String> lvNumber;
|
||||
@NotNull public final String title;
|
||||
@NotNull
|
||||
public final ArrayList<Lecturer> lecturer;
|
||||
public ArrayList<Lecturer> lecturer;
|
||||
@Nullable public final String type;
|
||||
@Nullable public final String description;
|
||||
@NotNull private final String ID;
|
||||
@NotNull private final int moduleType;
|
||||
@Nullable public ArrayList<Announcement> announcements;
|
||||
@Nullable public AssignmentList assignments;
|
||||
@Nullable public EventList events;
|
||||
@@ -138,7 +195,7 @@ public class Modules implements Iterable<Modules.Module>, Serializable {
|
||||
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) {
|
||||
private Module(@Nullable Semester semester, @NotNull HashSet<String> lvNumber, @NotNull String title, @NotNull LinkedHashSet<Lecturer> lecturer, @Nullable String type, @Nullable String description, @NotNull String ID, @NotNull int moduleType) {
|
||||
|
||||
title = title.replaceAll("(.*?) (S[0-9]{2}|W[0-9/]{5})", "$1");
|
||||
|
||||
@@ -149,6 +206,11 @@ 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);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@@ -166,5 +228,18 @@ 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;
|
||||
}
|
||||
|
||||
public Module clone() {
|
||||
return new Module(semester, lvNumber, title, new LinkedHashSet<>(lecturer), type, description, ID, moduleType);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package de.sebse.fuplanner.services.KVV.types;
|
||||
package de.sebse.fuplanner.services.kvv.types;
|
||||
|
||||
import com.google.android.gms.common.internal.Objects;
|
||||
|
||||
@@ -6,6 +6,7 @@ import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
|
||||
import androidx.annotation.LayoutRes;
|
||||
import androidx.annotation.NonNull;
|
||||
import de.sebse.fuplanner.R;
|
||||
import de.sebse.fuplanner.tools.ui.treeview.LayoutItemType;
|
||||
import de.sebse.fuplanner.tools.ui.treeview.TreeNode;
|
||||
@@ -61,6 +62,77 @@ 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class File extends Resource implements LayoutItemType {
|
||||
private final String type;
|
||||
|
||||
@@ -69,6 +141,7 @@ public abstract class Resource implements Serializable {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Resource{" +
|
||||
@@ -89,6 +162,11 @@ public abstract class Resource implements Serializable {
|
||||
public @LayoutRes int getLayoutId() {
|
||||
return R.layout.item_file;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(super.hashCode(), this.type, this.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
|
||||
public static class Folder extends Resource implements LayoutItemType {
|
||||
@@ -111,6 +189,7 @@ public abstract class Resource implements Serializable {
|
||||
return children.size();
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Resource{" +
|
||||
@@ -135,6 +214,11 @@ public abstract class Resource implements Serializable {
|
||||
public @LayoutRes int getLayoutId() {
|
||||
return R.layout.item_dir;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(super.hashCode(), children, this.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user